format codebase

This commit is contained in:
aronwk-aaron
2022-07-28 08:39:57 -05:00
parent 4f7aa11067
commit 19e77a38d8
881 changed files with 34700 additions and 38689 deletions

View File

@@ -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<uint32_t, uint64_t> 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<uint32_t, uint64_t> 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<double> 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<double> 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<MissionComponent>();
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<uint64_t>(m_PermissionMap) & static_cast<uint64_t>(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);
}

View File

@@ -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<int>& 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<LOT>& 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<LOT> 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<int> 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<uint32_t, uint64_t> m_PlayerFlags;
/**
* The gameplay flags this character has (not just true values)
*/
std::unordered_map<uint32_t, uint64_t> 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<LWOMAPID, NiPoint3> 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

File diff suppressed because it is too large Load Diff

View File

@@ -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<std::string>& GetGroups() { return m_Groups; };
Spawner* GetSpawner() const { return m_Spawner; }
LWOOBJID GetSpawnerID() const { return m_SpawnerID; }
const std::vector<LDFBaseData*>& 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<typename T>
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<int32_t, Component*>& 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<void(Entity* user)>& callback) const;
void AddRebuildCompleteCallback(const std::function<void(Entity* user)>& callback) const;
void AddCollisionPhantomCallback(const std::function<void(Entity* target)>& callback);
void AddDieCallback(const std::function<void()>& 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<typename T>
void SetNetworkVar(const std::u16string& name, T value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS);
template<typename T>
void SetNetworkVar(const std::u16string& name, std::vector<T> value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS);
template<typename T>
void SetNetworkVar(const std::u16string& name, std::vector<T> value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS);
template<typename T>
T GetNetworkVar(const std::u16string& name);
template<typename T>
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<LDFBaseData*> m_Settings;
std::vector<LDFBaseData*> m_NetworkSettings;
LWOOBJID m_ObjectID;
NiPoint3 m_DefaultPosition;
NiQuaternion m_DefaultRotation;
LOT m_TemplateID;
std::vector<LDFBaseData*> m_Settings;
std::vector<LDFBaseData*> 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<Entity*> m_ChildEntities;
uint8_t m_GMLevel;
uint16_t m_CollectibleID;
uint8_t m_GMLevel;
uint16_t m_CollectibleID;
std::vector<std::string> m_Groups;
uint16_t m_NetworkID;
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::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::vector<EntityTimer*> m_Timers;
std::vector<EntityTimer*> m_PendingTimers;
std::vector<EntityCallbackTimer*> m_CallbackTimers;
@@ -338,12 +338,10 @@ protected:
*/
template<typename T>
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 <typename T>
T* Entity::GetComponent() const
{
T* Entity::GetComponent() const {
return dynamic_cast<T*>(GetComponent(T::ComponentType));
}
template<typename T>
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<T>::Default;
}
auto* typed = dynamic_cast<LDFData<T>*>(data);
if (typed == nullptr)
{
if (typed == nullptr) {
return LDFData<T>::Default;
}
@@ -382,14 +376,12 @@ const T& Entity::GetVar(const std::u16string& name) const
}
template<typename T>
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<T>::Default;
}
@@ -397,12 +389,10 @@ T Entity::GetVarAs(const std::u16string& name) const
}
template<typename T>
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<T>(name, value);
m_Settings.push_back(data);
@@ -412,8 +402,7 @@ void Entity::SetVar(const std::u16string& name, T value)
auto* typed = dynamic_cast<LDFData<T>*>(data);
if (typed == nullptr)
{
if (typed == nullptr) {
return;
}
@@ -422,81 +411,81 @@ void Entity::SetVar(const std::u16string& name, T value)
template<typename T>
void Entity::SetNetworkVar(const std::u16string& name, T value, const SystemAddress& sysAddr) {
LDFData<T>* newData = nullptr;
LDFData<T>* 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<LDFData<T>*>(data);
if (newData != nullptr) {
newData->SetValue(value);
} else { // If we're changing types
m_NetworkSettings.erase(
newData = dynamic_cast<LDFData<T>*>(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<T>(name, value);
}
if (newData == nullptr) {
newData = new LDFData<T>(name, value);
}
m_NetworkSettings.push_back(newData);
SendNetworkVar(newData->GetString(true), sysAddr);
m_NetworkSettings.push_back(newData);
SendNetworkVar(newData->GetString(true), sysAddr);
}
template<typename T>
void Entity::SetNetworkVar(const std::u16string& name, std::vector<T> values, const SystemAddress& sysAddr) {
std::stringstream updates;
auto index = 1;
std::stringstream updates;
auto index = 1;
for (const auto& value : values) {
LDFData<T>* newData = nullptr;
const auto& indexedName = name + u"." + GeneralUtils::to_u16string(index);
for (const auto& value : values) {
LDFData<T>* 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<LDFData<T>*>(data);
newData->SetValue(value);
break;
}
newData = dynamic_cast<LDFData<T>*>(data);
newData->SetValue(value);
break;
}
if (newData == nullptr) {
newData = new LDFData<T>(indexedName, value);
}
if (newData == nullptr) {
newData = new LDFData<T>(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<typename T>
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<LDFData<T>*>(data);
if (typed == nullptr)
continue;
auto* typed = dynamic_cast<LDFData<T>*>(data);
if (typed == nullptr)
continue;
return typed->GetValue();
}
return typed->GetValue();
}
return LDFData<T>::Default;
return LDFData<T>::Default;
}

View File

@@ -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<Entity*> EntityManager::GetEntitiesByComponent(const int componentTy
return withComp;
}
std::vector<Entity *> EntityManager::GetEntitiesByLOT(const LOT &lot) const {
std::vector<Entity*> entities;
std::vector<Entity*> EntityManager::GetEntitiesByLOT(const LOT& lot) const {
std::vector<Entity*> 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<std::string, LWOOBJID>& EntityManager::GetSpawnPointEntities() const
{
const std::unordered_map<std::string, LWOOBJID>& 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<MissionComponent>();
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<uint32_t>(collectionId) + static_cast<uint32_t>(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();
}

View File

@@ -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<Entity*> GetEntitiesInGroup(const std::string& group);
std::vector<Entity*> GetEntitiesByComponent(int componentType) const;
std::vector<Entity*> GetEntitiesByLOT(const LOT& lot) const;
@@ -48,12 +48,12 @@ public:
const std::unordered_map<LWOOBJID, Entity*> 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<LWOMAPID> m_GhostingExcludedZones;
static std::vector<LOT> m_GhostingExcludedLOTs;
std::unordered_map<LWOOBJID, Entity*> m_Entities;
std::unordered_map<LWOOBJID, Entity*> m_Entities;
std::vector<LWOOBJID> m_EntitiesToKill;
std::vector<LWOOBJID> m_EntitiesToDelete;
std::vector<LWOOBJID> m_EntitiesToSerialize;
@@ -95,7 +95,7 @@ private:
float m_GhostDistanceMinSqaured = 100 * 100;
float m_GhostDistanceMaxSquared = 150 * 150;
bool m_GhostingEnabled = true;
std::stack<uint16_t> m_LostNetworkIds;
// Map of spawnname to entity object ID

View File

@@ -9,244 +9,243 @@
#include "dConfig.h"
Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector<LeaderboardEntry> 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<LeaderboardEntry> 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<LeaderboardEntry> entries {};
std::vector<LeaderboardEntry> 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<CDActivitiesTable>("Activities");
std::vector<CDActivities> activities = activitiesTable->Query([=](const CDActivities& entry) {
return (entry.ActivityID == gameID);
});
auto* activitiesTable = CDClientManager::Instance()->GetTable<CDActivitiesTable>("Activities");
std::vector<CDActivities> activities = activitiesTable->Query([=](const CDActivities& entry) {
return (entry.ActivityID == gameID);
});
for (const auto& activity : activities) {
return static_cast<LeaderboardType>(activity.leaderboardType);
}
for (const auto& activity : activities) {
return static_cast<LeaderboardType>(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 ( "

View File

@@ -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<LeaderboardEntry> entries,
LWOOBJID relatedPlayer = LWOOBJID_EMPTY, LeaderboardType = None);
std::vector<LeaderboardEntry> 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<LeaderboardEntry> entries,
LWOOBJID relatedPlayer = LWOOBJID_EMPTY, LeaderboardType = None);
std::vector<LeaderboardEntry> GetEntries();
[[nodiscard]] std::u16string ToString() const;
[[nodiscard]] uint32_t GetGameID() const;
[[nodiscard]] uint32_t GetInfoType() const;
void Send(LWOOBJID targetID) const;
private:
std::vector<LeaderboardEntry> entries {};
LWOOBJID relatedPlayer;
uint32_t gameID;
uint32_t infoType;
LeaderboardType leaderboardType;
bool weekly;
std::vector<LeaderboardEntry> 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;
};

View File

@@ -17,8 +17,7 @@
std::vector<Player*> 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<LWOOBJID, Loot::Info>& Player::GetDroppedLoot()
{
std::map<LWOOBJID, Loot::Info>& 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<Player*>(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<Player*>(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*>& Player::GetAllPlayers()
{
const std::vector<Player*>& 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<Entity*> 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<Entity*> 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);

View File

@@ -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<Player*>& 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<int32_t> m_ObservedEntities;
int32_t m_ObservedEntitiesLength;
int32_t m_ObservedEntitiesUsed;

View File

@@ -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<LWOOBJID>& members)
{
const auto& pair = m_Teams.find(teamId);
void TeamManager::UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector<LWOOBJID>& 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() {
}

View File

@@ -6,18 +6,18 @@ struct Team
{
LWOOBJID teamID = LWOOBJID_EMPTY;
char lootOption = 0;
std::vector<LWOOBJID> members {};
std::vector<LWOOBJID> 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<LWOOBJID>& members);
void DeleteTeam(LWOOBJID teamId);
explicit TeamManager();
~TeamManager();
explicit TeamManager();
~TeamManager();
private:
static TeamManager* m_Address; //For singleton method
std::unordered_map<LWOOBJID, Team*> m_Teams {};
static TeamManager* m_Address; //For singleton method
std::unordered_map<LWOOBJID, Team*> m_Teams{};
};

View File

@@ -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<TradeItem> items)
{
if (participant == m_ParticipantA)
{
m_ItemsA = items;
}
else if (participant == m_ParticipantB)
{
m_ItemsB = items;
}
void Trade::SetItems(LWOOBJID participant, std::vector<TradeItem> 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<InventoryComponent>();
auto* inventoryB = entityB->GetComponent<InventoryComponent>();
auto* missionsA = entityA->GetComponent<MissionComponent>();
auto* missionsB = entityB->GetComponent<MissionComponent>();
auto* characterA = entityA->GetCharacter();
auto* characterB = entityB->GetCharacter();
auto* inventoryA = entityA->GetComponent<InventoryComponent>();
auto* inventoryB = entityB->GetComponent<InventoryComponent>();
auto* missionsA = entityA->GetComponent<MissionComponent>();
auto* missionsB = entityB->GetComponent<MissionComponent>();
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<TradeItem> itemIds;
void Trade::SendUpdateToOther(LWOOBJID participant) {
Entity* other = nullptr;
Entity* self = nullptr;
uint64_t coins;
std::vector<TradeItem> 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<TradeItem> items {};
std::vector<TradeItem> items{};
auto* inventoryComponent = self->GetComponent<InventoryComponent>();
auto* inventoryComponent = self->GetComponent<InventoryComponent>();
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;
}

View File

@@ -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<TradeItem> items);
void SetAccepted(LWOOBJID participant, bool value);
void SetCoins(LWOOBJID participant, uint64_t coins);
void SetItems(LWOOBJID participant, std::vector<TradeItem> 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<TradeItem> m_ItemsA {};
std::vector<TradeItem> m_ItemsB {};
std::vector<TradeItem> m_ItemsA{};
std::vector<TradeItem> 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<LWOOBJID, Trade*> trades;
std::unordered_map<LWOOBJID, Trade*> trades;
};

View File

@@ -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<std::string, bool>();
@@ -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;
}

View File

@@ -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<Character*>& 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<uint32_t, BehaviorParams> 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<Character*> m_Characters;
LWOOBJID m_LoggedInCharID;
LWOOBJID m_LoggedInCharID;
std::unordered_map<std::string, bool> m_IsBestFriendMap;

View File

@@ -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<Character*>& 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<SkillComponent>();
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 << "<obj v=\"1\"><mf hc=\"" << hairColor << "\" hs=\"" << hairStyle << "\" hd=\"0\" t=\"" << shirtColor << "\" l=\"" << pantsColor;
xml << "\" hdc=\"0\" cd=\"" << shirtStyle << "\" lh=\"" << lh << "\" rh=\"" << rh << "\" es=\"" << eyebrows << "\" ";
xml << "ess=\"" << eyes << "\" ms=\"" << mouth << "\"/>";
std::stringstream xml;
xml << "<obj v=\"1\"><mf hc=\"" << hairColor << "\" hs=\"" << hairStyle << "\" hd=\"0\" t=\"" << shirtColor << "\" l=\"" << pantsColor;
xml << "\" hdc=\"0\" cd=\"" << shirtStyle << "\" lh=\"" << lh << "\" rh=\"" << rh << "\" es=\"" << eyebrows << "\" ";
xml << "ess=\"" << eyes << "\" ms=\"" << mouth << "\"/>";
xml << "<char acct=\"" << u->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;\"></char>";
xml << "<dest hm=\"4\" hc=\"4\" im=\"0\" ic=\"0\" am=\"0\" ac=\"0\" d=\"0\"/>";
xml << "<inv><bag><b t=\"0\" m=\"20\"/><b t=\"1\" m=\"40\"/><b t=\"2\" m=\"240\"/><b t=\"3\" m=\"240\"/><b t=\"14\" m=\"40\"/></bag><items><in t=\"0\">";
std::string xmlSave1 = xml.str();
xml << "<char acct=\"" << u->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;\"></char>";
xml << "<dest hm=\"4\" hc=\"4\" im=\"0\" ic=\"0\" am=\"0\" ac=\"0\" d=\"0\"/>";
xml << "<inv><bag><b t=\"0\" m=\"20\"/><b t=\"1\" m=\"40\"/><b t=\"2\" m=\"240\"/><b t=\"3\" m=\"240\"/><b t=\"14\" m=\"40\"/></bag><items><in t=\"0\">";
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 << "<i l=\"" << shirtLOT << "\" id=\"" << lwoidforshirt << "\" s=\"0\" c=\"1\" eq=\"1\" b=\"1\"/>";
LWOOBJID lwoidforshirt = idforshirt;
lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER);
lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT);
xml2 << xmlSave1 << "<i l=\"" << shirtLOT << "\" id=\"" << lwoidforshirt << "\" s=\"0\" c=\"1\" eq=\"1\" b=\"1\"/>";
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 << "<i l=\"" << pantsLOT << "\" id=\"" << lwoidforpants << "\" s=\"1\" c=\"1\" eq=\"1\" b=\"1\"/>";
std::stringstream xml3;
xml3 << xmlSave2 << "<i l=\"" << pantsLOT << "\" id=\"" << lwoidforpants << "\" s=\"1\" c=\"1\" eq=\"1\" b=\"1\"/>";
xml3 << "</in></items></inv><lvl l=\"1\" cv=\"1\" sb=\"500\"/><flag></flag></obj>";
xml3 << "</in></items></inv><lvl l=\"1\" cv=\"1\" sb=\"500\"/><flag></flag></obj>";
//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<uint32_t>(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<Character*>& 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<Character*>& 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<uint32_t>(objectID);
Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID);
uint32_t charID = static_cast<uint32_t>(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<Character*>& 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<Character*>& 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<Character*>& characters = u->GetCharacters();
Character* character = nullptr;
bool hasCharacter = false;
std::vector<Character*>& 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;

View File

@@ -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<SystemAddress, User*> m_Users;
std::vector<User*> m_UsersToDelete;
std::vector<std::string> m_FirstNames;
std::vector<std::string> m_MiddleNames;
std::vector<std::string> m_LastNames;

View File

@@ -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() {
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -8,18 +8,17 @@ class AndBehavior final : public Behavior
{
public:
std::vector<Behavior*> 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;

View File

@@ -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<BuffComponent>();
auto* buffComponent = entity->GetComponent<BuffComponent>();
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<BuffComponent>();
auto* buffComponent = entity->GetComponent<BuffComponent>();
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");
}

View File

@@ -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;
};

View File

@@ -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<DestroyableComponent>();
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");

View File

@@ -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;

View File

@@ -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<float>(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;
}
}

View File

@@ -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;
};

View File

@@ -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<DestroyableComponent>();
auto* destroyableComponent = entity->GetComponent<DestroyableComponent>();
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<DestroyableComponent>();
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);
}
}

View File

@@ -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;
};

View File

@@ -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<uint32_t, Behavior*> 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<CDBehaviorParameterTable>("BehaviorParameter");
}
const auto pair = Cache.find(behaviorId);
if (pair == Cache.end())
{
if (pair == Cache.end()) {
return nullptr;
}
return static_cast<Behavior*>(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<std::string, std::string>();
}
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<CDBehaviorTemplateTable>("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<CDBehaviorParameterTable>("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<int32_t>(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<int32_t>(value));
}
std::map<std::string, float> Behavior::GetParameterNames() 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");
@@ -493,40 +465,31 @@ std::map<std::string, float> 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;

View File

@@ -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<std::string, std::string>* 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<std::string, float> 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();
};

View File

@@ -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;

View File

@@ -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));
};

View File

@@ -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<SkillComponent>();
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<BehaviorTimerEntry> 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<BehaviorEndEntry> 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<BehaviorSyncEntry> 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<BehaviorSyncEntry> keptSync {};
void BehaviorContext::Interrupt() {
std::vector<BehaviorSyncEntry> 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<LWOOBJID> BehaviorContext::GetValidTargets(int32_t ignoreFaction, int32_t includeFaction, bool targetSelf, bool targetEnemy, bool targetFriend) const
{
std::vector<LWOOBJID> BehaviorContext::GetValidTargets(int32_t ignoreFaction, int32_t includeFaction, bool targetSelf, bool targetEnemy, bool targetFriend) const {
auto* entity = EntityManager::Instance()->GetEntity(this->caster);
std::vector<LWOOBJID> 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<LWOOBJID> 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<LWOOBJID> 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();
}

View File

@@ -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<BehaviorSyncEntry> syncEntries;
std::vector<BehaviorTimerEntry> timerEntries;
std::vector<BehaviorEndEntry> endEntries;
std::vector<LWOOBJID> 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<LWOOBJID> 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();

View File

@@ -67,4 +67,4 @@ enum class BehaviorTemplates : unsigned int {
BEHAVIOR_TAKE_PICTURE,
BEHAVIOR_MOUNT,
BEHAVIOR_SKILL_SET
};
};

View File

@@ -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<DestroyableComponent>();
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");
}

View File

@@ -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;
};

View File

@@ -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<DestroyableComponent>();
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<DestroyableComponent>();
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");

View File

@@ -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;
};

View File

@@ -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<PossessableComponent>();
if (possessableComponent != nullptr) {
auto* possessableComponent = entity->GetComponent<PossessableComponent>();
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<CharacterComponent>();
if (characterComponent != nullptr) {
Game::logger->Log("Car boost", "Tracking car boost!");
characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated);
}
}
}
auto* characterComponent = possessor->GetComponent<CharacterComponent>();
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");
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -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;

View File

@@ -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<BaseCombatAIComponent>();
if (m_OrientCaster) {
auto* baseCombatAIComponent = self->GetComponent<BaseCombatAIComponent>();
/*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");
}

View File

@@ -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;

View File

@@ -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");
}

View File

@@ -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;
};

View File

@@ -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");
}

View File

@@ -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;

View File

@@ -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<DestroyableComponent>();
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<DestroyableComponent>();
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");
}

View File

@@ -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;

View File

@@ -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<DestroyableComponent>();
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<DestroyableComponent>();
if (destroyable == nullptr)
{
if (destroyable == nullptr) {
return;
}
destroyable->SetDamageReduction(0);
}
void DamageReductionBehavior::Load()
{
void DamageReductionBehavior::Load() {
this->m_ReductionAmount = GetInt("reduction_amount");
}

View File

@@ -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;

View File

@@ -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");

View File

@@ -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;

View File

@@ -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) {
}
};

View File

@@ -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");
}

View File

@@ -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;

View File

@@ -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<ControllablePhysicsComponent>();
if (controllablePhysicsComponent != nullptr) {
auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster);
if (casterEntity != nullptr) {
auto* controllablePhysicsComponent = casterEntity->GetComponent<ControllablePhysicsComponent>();
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<ControllablePhysicsComponent>();
if (controllablePhysicsComponent != nullptr) {
auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster);
if (casterEntity != nullptr) {
auto* controllablePhysicsComponent = casterEntity->GetComponent<ControllablePhysicsComponent>();
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);
}

View File

@@ -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;
};

View File

@@ -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<DestroyableComponent*>(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");
}

View File

@@ -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;

View File

@@ -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<DestroyableComponent>();
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");
}

View File

@@ -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;

View File

@@ -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<DestroyableComponent*>(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<DestroyableComponent*>(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");
}

View File

@@ -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;

View File

@@ -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<SkillComponent>();
if (skillComponent == nullptr) return;
skillComponent->Interrupt();
}
void InterruptBehavior::Load()
{
void InterruptBehavior::Load() {
this->m_target = GetBoolean("target");
this->m_interruptBlock = GetBoolean("interrupt_block");
}

View File

@@ -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;
};

View File

@@ -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);
}

View File

@@ -1,7 +1,7 @@
#pragma once
#include "Behavior.h"
class JetPackBehavior final : public Behavior
class JetPackBehavior final : public Behavior
{
public:
int32_t m_WarningEffectID;

View File

@@ -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<DestroyableComponent>();
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");

View File

@@ -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;

View File

@@ -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<ControllablePhysicsComponent>();
if (!controllablePhysicsComponent) return;
auto controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
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<ControllablePhysicsComponent>();
if (!controllablePhysicsComponent) return;
auto controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
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");
}
this->m_Scale = GetFloat("scale");
}

View File

@@ -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;

View File

@@ -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");

View File

@@ -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;

View File

@@ -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);

View File

@@ -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;

View File

@@ -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<SkillComponent>();
auto* skillComponent = entity->GetComponent<SkillComponent>();
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<CDSkillBehaviorTable>("SkillBehavior");
m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID;
CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("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");
}

View File

@@ -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;

View File

@@ -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() {
}

View File

@@ -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;
};

View File

@@ -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<SkillComponent>();
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<SkillComponent>();
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<LWOOBJID>(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;
}

View File

@@ -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;

View File

@@ -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<MovementAIComponent>();
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() {
}

View File

@@ -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;

View File

@@ -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<DestroyableComponent*>(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");
}

View File

@@ -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;

View File

@@ -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() {
}

View File

@@ -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;

View File

@@ -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);
}
}
}

View File

@@ -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;
};

View File

@@ -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<RebuildComponent>();
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<DestroyableComponent*>(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");
}

View File

@@ -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;
};
};

View File

@@ -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() {
}

View File

@@ -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;

View File

@@ -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<ControllablePhysicsComponent>();
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
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<ControllablePhysicsComponent>();
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
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<ControllablePhysicsComponent>();
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
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");
}

View File

@@ -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;
};

Some files were not shown because too many files have changed in this diff Show More