feat(Core): Add clustering support (#16832)

Co-authored-by: 3kynox <thierry.prost@gmail.com>
Co-authored-by: nox <nox@noxen.net>
Co-authored-by: Ludwig <sudlud@users.noreply.github.com>
This commit is contained in:
Anton Popovichenko
2026-07-27 18:51:04 +02:00
committed by GitHub
parent f23ac046ab
commit 6f0ba8e896
80 changed files with 3675 additions and 297 deletions
+2 -1
View File
@@ -139,7 +139,8 @@ foreach(APPLICATION_NAME ${APPLICATIONS_BUILD_LIST})
game
gsoap
readline
gperftools)
gperftools
libsidecar)
if (UNIX AND NOT NOJEM)
set(${APP_PROJECT_NAME}_LINK_FLAGS "-pthread -lncurses ${${APP_PROJECT_NAME}_LINK_FLAGS}")
+13 -3
View File
@@ -49,10 +49,12 @@
#include "SharedDefines.h"
#include "SteadyTimer.h"
#include "Systemd.h"
#include "TC9Sidecar.h"
#include "World.h"
#include "WorldSessionMgr.h"
#include "WorldSocket.h"
#include "WorldSocketMgr.h"
#include "libsidecar.h"
#include <boost/asio/signal_set.hpp>
#include <boost/program_options.hpp>
#include <csignal>
@@ -365,7 +367,8 @@ int main(int argc, char** argv)
sWorldSocketMgr.StopNetwork();
///- Clean database before leaving
ClearOnlineAccounts();
if (!sToCloud9Sidecar->ClusterModeEnabled())
ClearOnlineAccounts();
});
// Set server online (allow connecting now)
@@ -397,11 +400,15 @@ int main(int argc, char** argv)
cliThread.reset(new std::thread(CliThread), &ShutdownCLIThread);
}
sToCloud9Sidecar->Init(worldPort, realm.Id.Realm);
WorldUpdateLoop();
// Shutdown starts here
threadPool.reset();
sToCloud9Sidecar->Deinit();
sLog->SetSynchronous();
sScriptMgr->OnShutdown();
@@ -455,8 +462,11 @@ bool StartDB()
LOG_INFO("server.loading", "Loading World Information...");
LOG_INFO("server.loading", "> RealmID: {}", realm.Id.Realm);
///- Clean the database before starting
ClearOnlineAccounts();
///- Clean the database before starting.
/// Cluster.Enabled is read from config here because sToCloud9Sidecar->Init()
/// has not run yet; ClusterModeEnabled() would still be the default false.
if (!sConfigMgr->GetOption<bool>("Cluster.Enabled", false))
ClearOnlineAccounts();
///- Insert version info into DB
WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_VERSION);
@@ -72,6 +72,8 @@
# DEBUG
# DYNAMIC RESPAWN SETTINGS
#
# CLUSTER SETTINGS
#
###################################################################################################
###################################################################################################
@@ -4893,3 +4895,56 @@ Respawn.ForceCompatibilityMode = 0
# GAME SETTINGS END #
# #
###################################################################################################
###################################################################################################
# #
# CLUSTER SETTINGS BEGIN #
# #
###################################################################################################
###################################################################################################
# CLUSTER SETTINGS
#
# This feature is experimental and still under development. It enables cluster mode, allowing multiple
# worldservers to run for a single realm, distributing the load between them. Alongside worldservers,
# additional services are required for proper functionality. If you encounter any issues, please report
# them to the ToCloud9 project: https://github.com/walkline/ToCloud9.
#
# Cluster.Enabled
# Description: Enables/disables cluster mode.
# SECURITY: in cluster mode the ToCloud9 gateway is the trusted
# authentication boundary. This worldserver then skips session-key
# digest verification, packet encryption, warden, IP/country locks,
# ban and minimum-security-level enforcement, and the
# character-ownership check on login. The worldserver port must
# only be reachable by the gateway, never directly by players.
# Default: 0 - (Disabled)
# 1 - (Enabled)
Cluster.Enabled=0
#
# Cluster.AvailableMaps
# Description: List of available maps id on this server.
# Examples: "" - (Can handle any map)
# "0,1,573"
Cluster.AvailableMaps=""
#
# Cluster.IsCrossrealm
# Description: Enables cross-realm functionality for a cross-realm setup.
# When enabled, a connection to a MySQL cross-realm reverse proxy is required.
# Default: 0 - (Disabled)
# 1 - (Enabled)
Cluster.IsCrossrealm=0
#
###################################################################################################
###################################################################################################
# #
# CLUSTER SETTINGS END #
# #
###################################################################################################
@@ -634,6 +634,13 @@ void CharacterDatabaseConnection::DoPrepareStatements()
// world_state
PrepareStatement(CHAR_SEL_WORLD_STATE, "SELECT Id, Data FROM world_state", CONNECTION_SYNCH);
PrepareStatement(CHAR_REP_WORLD_STATE, "REPLACE INTO world_state (Id, Data) VALUES(?, ?)", CONNECTION_ASYNC);
// CHAR_NO_OP_PROVIDE_REALM_CONTEXT is a no-op query that accepts a single parameter: the realm ID.
// This query is used specifically in cross-realm scenarios when the database transaction
// lacks sufficient context to determine which realm's database the query should target.
// By providing the realm ID explicitly, this ensures that mysql reverse proxy will use
// correct realm database for the transaction.
PrepareStatement(CHAR_NO_OP_PROVIDE_REALM_CONTEXT, "SELECT ? AS no_op", CONNECTION_ASYNC);
}
CharacterDatabaseConnection::CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo)
@@ -543,6 +543,8 @@ enum CharacterDatabaseStatements : uint32
CHAR_SEL_WORLD_STATE,
CHAR_REP_WORLD_STATE,
CHAR_NO_OP_PROVIDE_REALM_CONTEXT,
MAX_CHARACTERDATABASE_STATEMENTS
};
@@ -35,10 +35,12 @@
#include "ObjectMgr.h"
#include "Pet.h"
#include "Player.h"
#include "Realm.h"
#include "RBAC.h"
#include "ReputationMgr.h"
#include "ScriptMgr.h"
#include "SpellAuras.h"
#include "TC9Sidecar.h"
#include "Transport.h"
#include "Util.h"
#include "World.h"
@@ -277,6 +279,12 @@ void Battleground::Update(uint32 diff)
if (!GetInvitedCount(TEAM_HORDE) && !GetInvitedCount(TEAM_ALLIANCE))
{
m_SetDeleteThis = true;
// Only needed for the sidecar notify inside SetStatus; queue and
// spectator code read the status within this manager pass, so do
// not change it on non-cluster servers.
if (sToCloud9Sidecar->ClusterModeEnabled())
SetStatus(STATUS_WAIT_LEAVE);
}
return;
@@ -1071,6 +1079,11 @@ void Battleground::RemovePlayerAtLeave(Player* player)
// if the player was a match participant
if (participant)
{
if (sToCloud9Sidecar->ClusterModeEnabled())
sToCloud9Sidecar->OnPlayerLeftBattleground(player->GetGUID().GetCounter(),
player->GetGUID().GetRealmID(),
GetInstanceID());
player->ClearAfkReports();
WorldPacket data;
@@ -1889,3 +1902,11 @@ uint8 Battleground::GetUniqueBracketId() const
{
return GetMaxLevel() / 10;
}
void Battleground::SetStatus(BattlegroundStatus Status)
{
m_Status = Status;
if (sToCloud9Sidecar->ClusterModeEnabled() && GetInstanceID() != 0)
sToCloud9Sidecar->OnBattlegroundStatusChanged(GetInstanceID(), Status);
}
+1 -1
View File
@@ -366,7 +366,7 @@ public:
void SetRandomTypeID(BattlegroundTypeId TypeID) { m_RandomTypeID = TypeID; }
void SetBracket(PvPDifficultyEntry const* bracketEntry);
void SetInstanceID(uint32 InstanceID) { m_InstanceID = InstanceID; }
void SetStatus(BattlegroundStatus Status) { m_Status = Status; }
void SetStatus(BattlegroundStatus Status);
void SetClientInstanceID(uint32 InstanceID) { m_ClientInstanceID = InstanceID; }
void SetStartTime(uint32 Time) { m_StartTime = Time; }
void SetEndTime(uint32 Time) { m_EndTime = Time; }
+2 -1
View File
@@ -54,7 +54,8 @@ target_link_libraries(game
PRIVATE
acore-core-interface
PUBLIC
game-interface)
game-interface
libsidecar)
set_target_properties(game
PROPERTIES
+28 -24
View File
@@ -26,6 +26,7 @@
#include "SpellInfo.h"
#include "SpellMgr.h"
#include "StringConvert.h"
#include "TC9Sidecar.h"
#include "Tokenize.h"
#include "WorldPacket.h"
@@ -348,7 +349,7 @@ void Item::SaveToDB(CharacterDatabaseTransaction trans)
uint8 index = 0;
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_REP_ITEM_INSTANCE : CHAR_UPD_ITEM_INSTANCE);
stmt->SetData( index, GetEntry());
stmt->SetData(++index, GetOwnerGUID().GetCounter());
stmt->SetData(++index, GetOwnerGUID().GetRawValue());
stmt->SetData(++index, GetGuidValue(ITEM_FIELD_CREATOR).GetCounter());
stmt->SetData(++index, GetGuidValue(ITEM_FIELD_GIFTCREATOR).GetCounter());
stmt->SetData(++index, GetCount());
@@ -381,7 +382,7 @@ void Item::SaveToDB(CharacterDatabaseTransaction trans)
if ((uState == ITEM_CHANGED) && IsWrapped())
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GIFT_OWNER);
stmt->SetData(0, GetOwnerGUID().GetCounter());
stmt->SetData(0, GetOwnerGUID().GetRawValue());
stmt->SetData(1, guid);
trans->Append(stmt);
}
@@ -1096,29 +1097,32 @@ Item* Item::CreateItem(uint32 item, uint32 count, Player const* player, bool clo
return nullptr; //don't create item at zero count
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
if (pProto)
{
if (count > pProto->GetMaxStackSize())
count = pProto->GetMaxStackSize();
ASSERT_NODEBUGINFO(count != 0 && "pProto->Stackable == 0 but checked at loading already");
Item* pItem = NewItemOrBag(pProto);
if (pItem->Create(sObjectMgr->GetGenerator<HighGuid::Item>().Generate(), item, player))
{
pItem->SetCount(count);
if (!clone)
pItem->SetItemRandomProperties(randomPropertyId ? randomPropertyId : Item::GenerateItemRandomPropertyId(item));
else if (randomPropertyId)
pItem->SetItemRandomProperties(randomPropertyId);
return pItem;
}
else
delete pItem;
}
else
if (!pProto)
ABORT();
return nullptr;
if (count > pProto->GetMaxStackSize())
count = pProto->GetMaxStackSize();
ASSERT_NODEBUGINFO(count != 0 && "pProto->Stackable == 0 but checked at loading already");
uint16 realmId = DEFAULT_NON_CROSSREALM_REALM_ID;
if (sToCloud9Sidecar->IsCrossrealm() && player)
realmId = player->GetGUID().GetRealmID();
Item* pItem = NewItemOrBag(pProto);
if (!pItem->Create(sObjectMgr->GetGenerator<HighGuid::Item>().Generate(realmId), item, player))
{
delete pItem;
return nullptr;
}
pItem->SetCount(count);
if (!clone)
pItem->SetItemRandomProperties(randomPropertyId ? randomPropertyId : Item::GenerateItemRandomPropertyId(item));
else if (randomPropertyId)
pItem->SetItemRandomProperties(randomPropertyId);
return pItem;
}
Item* Item::CloneItem(uint32 count, Player const* player) const
+5 -1
View File
@@ -121,10 +121,14 @@ void Object::_InitValues()
}
void Object::_Create(ObjectGuid::LowType guidlow, uint32 entry, HighGuid guidhigh)
{
_Create(ObjectGuid(guidhigh, entry, guidlow));
}
void Object::_Create(ObjectGuid guid)
{
if (!m_uint32Values) _InitValues();
ObjectGuid guid(guidhigh, entry, guidlow);
SetGuidValue(OBJECT_FIELD_GUID, guid);
SetUInt32Value(OBJECT_FIELD_TYPE, m_objectType);
m_PackGUID.Set(guid);
+1
View File
@@ -241,6 +241,7 @@ protected:
void _InitValues();
void _Create(ObjectGuid::LowType guidlow, uint32 entry, HighGuid guidhigh);
void _Create(ObjectGuid guid);
[[nodiscard]] std::string _ConcatFields(uint16 startIndex, uint16 size) const;
bool _LoadIntoDataField(std::string const& data, uint32 startOffset, uint32 count);
@@ -17,6 +17,7 @@
#include "ObjectGuid.h"
#include "Log.h"
#include "TC9Sidecar.h"
#include "World.h"
#include <iomanip>
#include <sstream>
@@ -96,6 +97,21 @@ void ObjectGuidGeneratorBase::HandleCounterOverflow(HighGuid high)
World::StopNow(ERROR_EXIT_CODE);
}
bool ObjectGuidGeneratorBase::GetClusterGuid(HighGuid high, uint16 realmId, ObjectGuid::LowType& clusterGuid)
{
if (!sToCloud9Sidecar->ClusterModeEnabled())
return false;
if (high == HighGuid::Player)
clusterGuid = ObjectGuid::LowType(sToCloud9Sidecar->GenerateCharacterGuid(realmId));
else if (high == HighGuid::Item)
clusterGuid = ObjectGuid::LowType(sToCloud9Sidecar->GenerateItemGuid(realmId));
else
return false;
return true;
}
#define GUID_TRAIT_INSTANTIATE_GUID( HIGH_GUID ) \
template class ObjectGuidGenerator< HIGH_GUID >;
+11 -2
View File
@@ -27,6 +27,9 @@
#include <unordered_set>
#include <vector>
// Realm id packed into bits 32-47 of a player ObjectGuid; 0 means local / non-crossrealm.
constexpr uint16 DEFAULT_NON_CROSSREALM_REALM_ID = 0;
enum TypeID
{
TYPEID_OBJECT = 0,
@@ -142,6 +145,7 @@ class ObjectGuid
[[nodiscard]] uint64 GetRawValue() const { return _guid; }
[[nodiscard]] HighGuid GetHigh() const { return HighGuid((_guid >> 48) & 0x0000FFFF); }
[[nodiscard]] uint32 GetEntry() const { return HasEntry() ? uint32((_guid >> 24) & UI64LIT(0x0000000000FFFFFF)) : 0; }
[[nodiscard]] uint16 GetRealmID() const { return IsPlayer() ? uint16((_guid >> 32) & UI64LIT(0xFFFF)) : 0; }
[[nodiscard]] LowType GetCounter() const
{
return HasEntry()
@@ -283,12 +287,13 @@ public:
ObjectGuidGeneratorBase(ObjectGuid::LowType start = 1) : _nextGuid(start) { }
virtual void Set(ObjectGuid::LowType val) { _nextGuid = val; }
virtual ObjectGuid::LowType Generate() = 0;
virtual ObjectGuid::LowType Generate(uint16 realmId = DEFAULT_NON_CROSSREALM_REALM_ID) = 0;
[[nodiscard]] ObjectGuid::LowType GetNextAfterMaxUsed() const { return _nextGuid; }
virtual ~ObjectGuidGeneratorBase() = default;
protected:
static void HandleCounterOverflow(HighGuid high);
static bool GetClusterGuid(HighGuid high, uint16 realmId, ObjectGuid::LowType& clusterGuid);
ObjectGuid::LowType _nextGuid;
};
@@ -298,8 +303,12 @@ class ObjectGuidGenerator : public ObjectGuidGeneratorBase
public:
explicit ObjectGuidGenerator(ObjectGuid::LowType start = 1) : ObjectGuidGeneratorBase(start) { }
ObjectGuid::LowType Generate() override
ObjectGuid::LowType Generate(uint16 realmId = DEFAULT_NON_CROSSREALM_REALM_ID) override
{
ObjectGuid::LowType clusterGuid = 0;
if (GetClusterGuid(high, realmId, clusterGuid))
return clusterGuid;
if (_nextGuid >= ObjectGuid::GetMaxCounter(high) - 1)
HandleCounterOverflow(high);
+21 -21
View File
@@ -3783,7 +3783,7 @@ void Player::_LoadSpellCooldowns(PreparedQueryResult result)
void Player::_SaveSpellCooldowns(CharacterDatabaseTransaction trans, bool logout)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
time_t curTime = GameTime::GetGameTime().count();
@@ -4770,7 +4770,7 @@ void Player::SpawnCorpseBones(bool triggerSave /*= true*/)
// pussywizard: update only ghost flag instead of whole character table entry! data integrity is crucial
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_REMOVE_GHOST);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
_SaveAuras(trans, false);
@@ -6455,7 +6455,7 @@ void Player::ModifyHonorPoints(int32 value, CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_HONOR_POINTS);
stmt->SetData(0, newValue);
stmt->SetData(1, GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetRawValue());
trans->Append(stmt);
}
}
@@ -6471,7 +6471,7 @@ void Player::ModifyArenaPoints(int32 value, CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_ARENA_POINTS);
stmt->SetData(0, newValue);
stmt->SetData(1, GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetRawValue());
trans->Append(stmt);
}
}
@@ -9324,7 +9324,7 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
// Handle removing pet while it is in "temporarily unsummoned" state, for example on mount
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID);
stmt->SetData(0, PET_SAVE_NOT_IN_SLOT);
stmt->SetData(1, GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetRawValue());
stmt->SetData(2, m_petStable->CurrentPet->PetNumber);
CharacterDatabase.Execute(stmt);
@@ -11502,7 +11502,7 @@ void Player::LeaveBattleground(Battleground* bg)
if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS))
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, BG_DESERTION_TYPE_LEAVE_BG);
CharacterDatabase.Execute(stmt);
}
@@ -14026,7 +14026,7 @@ void Player::_LoadSkills(PreparedQueryResult result)
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, skill);
CharacterDatabase.Execute(stmt);
@@ -14971,7 +14971,7 @@ void Player::_SaveEquipmentSets(CharacterDatabaseTransaction trans)
stmt->SetData(j++, eqset.IgnoreMask);
for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt->SetData(j++, eqset.Items[i].GetCounter());
stmt->SetData(j++, GetGUID().GetCounter());
stmt->SetData(j++, GetGUID().GetRawValue());
stmt->SetData(j++, eqset.Guid);
stmt->SetData(j, index);
trans->Append(stmt);
@@ -14980,7 +14980,7 @@ void Player::_SaveEquipmentSets(CharacterDatabaseTransaction trans)
break;
case EQUIPMENT_SET_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET);
stmt->SetData(j++, GetGUID().GetCounter());
stmt->SetData(j++, GetGUID().GetRawValue());
stmt->SetData(j++, eqset.Guid);
stmt->SetData(j++, index);
stmt->SetData(j++, eqset.Name.c_str());
@@ -15010,11 +15010,11 @@ void Player::_SaveEntryPoint(CharacterDatabaseTransaction trans)
return;
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ENTRY_POINT);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_ENTRY_POINT);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData (1, m_entryPointData.joinPos.GetPositionX());
stmt->SetData (2, m_entryPointData.joinPos.GetPositionY());
stmt->SetData (3, m_entryPointData.joinPos.GetPositionZ());
@@ -15050,7 +15050,7 @@ void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/)
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG);
stmt->SetData(0, uint16(flags));
stmt->SetData(1, GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetRawValue());
CharacterDatabase.Execute(stmt);
}
@@ -15097,7 +15097,7 @@ void Player::_SaveCharacter(bool create, CharacterDatabaseTransaction trans)
//! Insert query
//! TO DO: Filter out more redundant fields that can take their default value at player create
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER);
stmt->SetData(index++, GetGUID().GetCounter());
stmt->SetData(index++, GetGUID().GetRawValue());
stmt->SetData(index++, GetSession()->GetAccountId());
stmt->SetData(index++, GetName());
stmt->SetData(index++, getRace(true));
@@ -15355,7 +15355,7 @@ void Player::_SaveCharacter(bool create, CharacterDatabaseTransaction trans)
stmt->SetData(index++, IsInWorld() && !GetSession()->PlayerLogout() ? 1 : 0);
// Index
stmt->SetData(index++, GetGUID().GetCounter());
stmt->SetData(index++, GetGUID().GetRawValue());
}
trans->Append(stmt);
@@ -15390,7 +15390,7 @@ void Player::_SaveGlyphs(CharacterDatabaseTransaction trans)
return;
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
for (uint8 spec = 0; spec < m_specsCount; ++spec)
@@ -15398,7 +15398,7 @@ void Player::_SaveGlyphs(CharacterDatabaseTransaction trans)
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GLYPHS);
stmt->SetData(index++, GetGUID().GetCounter());
stmt->SetData(index++, GetGUID().GetRawValue());
stmt->SetData(index++, spec);
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
@@ -15445,7 +15445,7 @@ void Player::_SaveTalents(CharacterDatabaseTransaction trans)
if (itr->second->State == PLAYERSPELL_REMOVED || itr->second->State == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, itr->first);
trans->Append(stmt);
}
@@ -15454,7 +15454,7 @@ void Player::_SaveTalents(CharacterDatabaseTransaction trans)
if (itr->second->State == PLAYERSPELL_NEW || itr->second->State == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_TALENT);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, itr->first);
stmt->SetData(2, itr->second->specMask);
trans->Append(stmt);
@@ -15627,7 +15627,7 @@ void Player::ActivateSpec(uint8 spec)
// load them asynchronously
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, m_activeSpec);
WorldSession* mySess = GetSession();
@@ -16142,7 +16142,7 @@ void Player::SetRandomWinner(bool isWinner)
if (m_IsBGRandomWinner)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
CharacterDatabase.Execute(stmt);
}
}
@@ -16259,7 +16259,7 @@ void Player::_LoadBrewOfTheMonth(PreparedQueryResult result)
// Update Event Id
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_BREW_OF_THE_MONTH);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, uint32(eventId));
trans->Append(stmt);
@@ -4978,7 +4978,7 @@ void Player::SetHomebind(WorldLocation const& loc, uint32 areaId)
stmt->SetData (2, m_homebindX);
stmt->SetData (3, m_homebindY);
stmt->SetData (4, m_homebindZ);
stmt->SetData(5, GetGUID().GetCounter());
stmt->SetData(5, GetGUID().GetRawValue());
CharacterDatabase.Execute(stmt);
}
@@ -5027,9 +5027,9 @@ bool Player::LoadFromDB(ObjectGuid playerGuid, CharacterDatabaseQueryHolder cons
return false;
}
ObjectGuid::LowType guid = playerGuid.GetCounter();
uint64 guid = playerGuid.GetRawValue();
Object::_Create(guid, 0, HighGuid::Player);
Object::_Create(playerGuid);
m_name = fields[2].Get<std::string>();
@@ -6101,7 +6101,7 @@ Item* Player::_LoadItem(CharacterDatabaseTransaction trans, uint32 zoneId, uint3
// xinef: sync query
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_REFUNDS);
stmt->SetData(0, item->GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetRawValue());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
item->SetRefundRecipient((*result)[0].Get<uint32>());
@@ -7152,7 +7152,7 @@ bool Player::_LoadHomeBind(PreparedQueryResult result)
else
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
CharacterDatabase.Execute(stmt);
}
}
@@ -7166,7 +7166,7 @@ bool Player::_LoadHomeBind(PreparedQueryResult result)
m_homebindZ = info->positionZ;
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, m_homebindMapId);
stmt->SetData(2, m_homebindAreaId);
stmt->SetData (3, m_homebindX);
@@ -7265,7 +7265,7 @@ void Player::SaveGoldToDB(CharacterDatabaseTransaction trans)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY);
stmt->SetData(0, GetMoney());
stmt->SetData(1, GetGUID().GetCounter());
stmt->SetData(1, GetGUID().GetRawValue());
trans->Append(stmt);
}
@@ -7279,7 +7279,7 @@ void Player::_SaveActions(CharacterDatabaseTransaction trans)
{
case ACTIONBUTTON_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, m_activeSpec);
stmt->SetData(2, itr->first);
stmt->SetData(3, itr->second.GetAction());
@@ -7293,7 +7293,7 @@ void Player::_SaveActions(CharacterDatabaseTransaction trans)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ACTION);
stmt->SetData(0, itr->second.GetAction());
stmt->SetData(1, uint8(itr->second.GetType()));
stmt->SetData(2, GetGUID().GetCounter());
stmt->SetData(2, GetGUID().GetRawValue());
stmt->SetData(3, itr->first);
stmt->SetData(4, m_activeSpec);
trans->Append(stmt);
@@ -7303,7 +7303,7 @@ void Player::_SaveActions(CharacterDatabaseTransaction trans)
break;
case ACTIONBUTTON_DELETED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, itr->first);
stmt->SetData(2, m_activeSpec);
trans->Append(stmt);
@@ -7320,7 +7320,7 @@ void Player::_SaveActions(CharacterDatabaseTransaction trans)
void Player::_SaveAuras(CharacterDatabaseTransaction trans, bool logout)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
for (AuraMap::const_iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end(); ++itr)
@@ -7355,7 +7355,7 @@ void Player::_SaveAuras(CharacterDatabaseTransaction trans, bool logout)
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA);
stmt->SetData(index++, GetGUID().GetCounter());
stmt->SetData(index++, GetGUID().GetRawValue());
stmt->SetData(index++, itr->second->GetCasterGUID().GetRawValue());
stmt->SetData(index++, itr->second->GetCastItemGUID().GetRawValue());
stmt->SetData(index++, itr->second->GetId());
@@ -7440,7 +7440,7 @@ void Player::_SaveInventory(CharacterDatabaseTransaction trans)
if (m_itemUpdateQueue.empty())
return;
ObjectGuid::LowType lowGuid = GetGUID().GetCounter();
uint64 guid = GetGUID().GetRawValue();
for (std::size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item* item = m_itemUpdateQueue[i];
@@ -7459,12 +7459,12 @@ void Player::_SaveInventory(CharacterDatabaseTransaction trans)
if (Item* test2 = GetItemByPos(INVENTORY_SLOT_BAG_0, item->GetBagSlot()))
bagTestGUID = test2->GetGUID().GetCounter();
LOG_ERROR("entities.player", "Player(GUID: {} Name: {})::_SaveInventory - the bag({}) and slot({}) values for the item {} (state {}) are incorrect, the player doesn't have an item at that position!",
lowGuid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString(), (int32)item->GetState());
guid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString(), (int32)item->GetState());
// according to the test that was just performed nothing should be in this slot, delete
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT);
stmt->SetData(0, bagTestGUID);
stmt->SetData(1, item->GetSlot());
stmt->SetData(2, lowGuid);
stmt->SetData(2, guid);
trans->Append(stmt);
RemoveTradeableItem(item); // pussywizard
@@ -7480,7 +7480,7 @@ void Player::_SaveInventory(CharacterDatabaseTransaction trans)
else if (test != item)
{
LOG_ERROR("entities.player", "Player(GUID: {} Name: {})::_SaveInventory - the bag({}) and slot({}) values for the item ({}) are incorrect, the item ({}) is there instead!",
lowGuid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString(), test->GetGUID().ToString());
guid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString(), test->GetGUID().ToString());
// save all changes to the item...
if (item->GetState() != ITEM_NEW) // only for existing items, no dupes
item->SaveToDB(trans);
@@ -7494,7 +7494,7 @@ void Player::_SaveInventory(CharacterDatabaseTransaction trans)
case ITEM_NEW:
case ITEM_CHANGED:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_INVENTORY_ITEM);
stmt->SetData(0, lowGuid);
stmt->SetData(0, guid);
stmt->SetData(1, bag_guid);
stmt->SetData (2, item->GetSlot());
stmt->SetData(3, item->GetGUID().GetCounter());
@@ -7610,7 +7610,7 @@ void Player::_SaveQuestStatus(CharacterDatabaseTransaction trans)
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS);
stmt->SetData(index++, GetGUID().GetCounter());
stmt->SetData(index++, GetGUID().GetRawValue());
stmt->SetData(index++, statusItr->first);
stmt->SetData(index++, uint8(statusItr->second.Status));
stmt->SetData(index++, statusItr->second.Explored);
@@ -7629,7 +7629,7 @@ void Player::_SaveQuestStatus(CharacterDatabaseTransaction trans)
else
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, saveItr->first);
trans->Append(stmt);
}
@@ -7644,7 +7644,7 @@ void Player::_SaveQuestStatus(CharacterDatabaseTransaction trans)
else // xinef: what the is this? quest can be removed by spelleffect if (!keepAbandoned)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, saveItr->first);
trans->Append(stmt);
}
@@ -7666,14 +7666,14 @@ void Player::_SaveDailyQuestStatus(CharacterDatabaseTransaction trans)
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx));
stmt->SetData(2, uint64(m_lastDailyQuestTime));
trans->Append(stmt);
@@ -7685,7 +7685,7 @@ void Player::_SaveDailyQuestStatus(CharacterDatabaseTransaction trans)
for (DFQuestsDoneList::iterator itr = m_DFQuests.begin(); itr != m_DFQuests.end(); ++itr)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, (*itr));
stmt->SetData(2, uint64(m_lastDailyQuestTime));
trans->Append(stmt);
@@ -7700,7 +7700,7 @@ void Player::_SaveWeeklyQuestStatus(CharacterDatabaseTransaction trans)
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
@@ -7708,7 +7708,7 @@ void Player::_SaveWeeklyQuestStatus(CharacterDatabaseTransaction trans)
uint32 quest_id = *iter;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, quest_id);
trans->Append(stmt);
}
@@ -7725,7 +7725,7 @@ void Player::_SaveSeasonalQuestStatus(CharacterDatabaseTransaction trans)
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
m_SeasonalQuestChanged = false;
@@ -7744,7 +7744,7 @@ void Player::_SaveSeasonalQuestStatus(CharacterDatabaseTransaction trans)
uint32 questId = *itr;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS);
stmt->SetArguments(GetGUID().GetCounter(), questId, eventId);
stmt->SetArguments(GetGUID().GetRawValue(), questId, eventId);
trans->Append(stmt);
}
}
@@ -7757,14 +7757,14 @@ void Player::_SaveMonthlyQuestStatus(CharacterDatabaseTransaction trans)
// we don't need transactions here.
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_MONTHLYQUESTSTATUS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, quest_id);
trans->Append(stmt);
}
@@ -7787,7 +7787,7 @@ void Player::_SaveSkills(CharacterDatabaseTransaction trans)
if (itr->second.uState == SKILL_DELETED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, itr->first);
trans->Append(stmt);
@@ -7803,7 +7803,7 @@ void Player::_SaveSkills(CharacterDatabaseTransaction trans)
{
case SKILL_NEW:
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILLS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, uint16(itr->first));
stmt->SetData(2, value);
stmt->SetData(3, max);
@@ -7814,7 +7814,7 @@ void Player::_SaveSkills(CharacterDatabaseTransaction trans)
stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_SKILLS);
stmt->SetData(0, value);
stmt->SetData(1, max);
stmt->SetData(2, GetGUID().GetCounter());
stmt->SetData(2, GetGUID().GetRawValue());
stmt->SetData(3, uint16(itr->first));
trans->Append(stmt);
@@ -7845,7 +7845,7 @@ void Player::_SaveSpells(CharacterDatabaseTransaction trans)
if (itr->second->State == PLAYERSPELL_REMOVED || itr->second->State == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, itr->first);
trans->Append(stmt);
}
@@ -7854,7 +7854,7 @@ void Player::_SaveSpells(CharacterDatabaseTransaction trans)
if (itr->second->State == PLAYERSPELL_NEW || itr->second->State == PLAYERSPELL_CHANGED)
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SPELL);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
stmt->SetData(1, itr->first);
stmt->SetData(2, itr->second->specMask);
trans->Append(stmt);
@@ -7884,13 +7884,13 @@ void Player::_SaveStats(CharacterDatabaseTransaction trans)
CharacterDatabasePreparedStatement* stmt = nullptr;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS);
stmt->SetData(0, GetGUID().GetCounter());
stmt->SetData(0, GetGUID().GetRawValue());
trans->Append(stmt);
uint8 index = 0;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_STATS);
stmt->SetData(index++, GetGUID().GetCounter());
stmt->SetData(index++, GetGUID().GetRawValue());
stmt->SetData(index++, GetMaxHealth());
for (uint8 i = 0; i < MAX_POWERS; ++i)
@@ -19,6 +19,7 @@
#include "Cell.h"
#include "CellImpl.h"
#include "Common.h"
#include "Config.h"
#include "DBCStores.h"
#include "GameObjectAI.h"
#include "GameTime.h"
@@ -30,8 +31,28 @@
#include "Spell.h"
#include "Vehicle.h"
#include "WorldModel.h"
#include <chrono>
MotionTransport::MotionTransport() : Transport(), _transportInfo(nullptr), _isMoving(true), _pendingStop(false), _triggeredArrivalEvent(false), _triggeredDepartureEvent(false), _passengersLoaded(false), _delayedTeleport(false)
namespace
{
// Any fixed reference epoch works; this one is 2023-07-12 05:20:00 UTC.
std::time_t const startTimestamp = 1689139200;
std::chrono::system_clock::time_point const transportStartDate = std::chrono::system_clock::from_time_t(startTimestamp);
// Calculates time of the next departure cycle.
std::chrono::system_clock::time_point calculateNextDepartureTime(int oneIterationInterval)
{
std::chrono::system_clock::time_point currentTime = std::chrono::system_clock::now();
std::chrono::milliseconds interval(oneIterationInterval);
std::chrono::milliseconds timeSinceStart = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - transportStartDate);
int64 intervalsPassed = timeSinceStart.count() / oneIterationInterval;
std::chrono::system_clock::time_point nextDeparture = transportStartDate + (interval * (intervalsPassed + 1));
return nextDeparture;
}
}
MotionTransport::MotionTransport() : Transport(), _transportInfo(nullptr), _isMoving(true), _pendingStop(false), _triggeredArrivalEvent(false), _triggeredDepartureEvent(false), _passengersLoaded(false), _delayedTeleport(false),
_requiresFirstDepartureSync(false), _firstDepartureTime(transportStartDate)
{
m_updateFlag = UPDATEFLAG_TRANSPORT | UPDATEFLAG_LOWGUID | UPDATEFLAG_STATIONARY_POSITION | UPDATEFLAG_ROTATION;
}
@@ -76,6 +97,13 @@ bool MotionTransport::CreateMoTrans(ObjectGuid::LowType guidlow, uint32 entry, u
_transportInfo = tInfo;
// Enable transport sync only in cluster mode and for transport with several maps.
if (sConfigMgr->GetOption<bool>("Cluster.Enabled", false) && tInfo->mapsUsed.size() > 1)
{
_requiresFirstDepartureSync = true;
this->SetPhaseMask(2, true);
}
// initialize waypoints
_nextFrame = tInfo->keyFrames.begin();
_currentFrame = _nextFrame++;
@@ -108,6 +136,56 @@ bool MotionTransport::CreateMoTrans(ObjectGuid::LowType guidlow, uint32 entry, u
return true;
}
// Delays first departure to make sure that transport follows strict schedule
// and with that makes transport synced between cluster nodes.
uint32 MotionTransport::HandleFirstDepartureSync(uint32 diff)
{
if (!_requiresFirstDepartureSync)
return diff;
if (_firstDepartureTime == transportStartDate)
{
_firstDepartureTime = calculateNextDepartureTime(_transportInfo->pathTime);
return diff;
}
// Making system call for current time to be more accurate.
// Shouldn't be an issue since it runs only before the very first departure.
int32 millLeftToDeparture = std::chrono::duration_cast<std::chrono::milliseconds>(_firstDepartureTime - std::chrono::system_clock::now()).count();
if (millLeftToDeparture > 0)
return diff;
// At this point we are ready for first departure.
_requiresFirstDepartureSync = false;
this->SetPhaseMask(1, true);
// Players don't know about transport because it was in a different phase.
// We need to notify players that object exists before departure.
Map::PlayerList const& players = this->GetMap()->GetPlayers();
if (!players.IsEmpty())
{
for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i)
{
if (Player* player = i->GetSource())
{
// Same phase filter as Map::SendInitTransports: players outside
// the transport's phase must not get a create-block for it.
if (!player->InSamePhase(this))
continue;
UpdateData transData;
this->BuildCreateUpdateBlockForPlayer(&transData, player);
WorldPacket packet;
transData.BuildPacket(packet);
player->SendDirectMessage(&packet);
}
}
}
return millLeftToDeparture * -1;
}
void MotionTransport::CleanupsBeforeDelete(bool finalCleanup /*= true*/)
{
UnloadStaticPassengers();
@@ -137,6 +215,13 @@ void MotionTransport::BuildUpdate(UpdateDataMapType& data_map)
void MotionTransport::Update(uint32 diff)
{
if (_requiresFirstDepartureSync)
{
diff = HandleFirstDepartureSync(diff);
if (_requiresFirstDepartureSync)
return;
}
uint32 const positionUpdateDelay = 1;
if (AI())
@@ -90,6 +90,8 @@ private:
void UpdatePassengerPositions(PassengerSet& passengers);
void DoEventIfAny(KeyFrame const& node, bool departure);
uint32 HandleFirstDepartureSync(uint32 diff);
//! Helpers to know if stop frame was reached
bool IsMoving() const { return _isMoving; }
void SetMoving(bool val) { _isMoving = val; }
@@ -109,6 +111,9 @@ private:
mutable std::mutex Lock;
bool _passengersLoaded;
bool _delayedTeleport;
bool _requiresFirstDepartureSync;
std::chrono::system_clock::time_point _firstDepartureTime;
};
class StaticTransport : public Transport
+89 -17
View File
@@ -34,6 +34,7 @@
#include "Player.h"
#include "ScriptMgr.h"
#include "SharedDefines.h"
#include "TC9Sidecar.h"
#include "UpdateFieldFlags.h"
#include "Util.h"
#include "World.h"
@@ -329,7 +330,7 @@ void Group::ConvertToRaid()
_initRaidSubGroupsCounter();
if (!isBGGroup() && !isBFGroup())
if (!sToCloud9Sidecar->ClusterModeEnabled() && !isBGGroup() && !isBFGroup())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_TYPE);
@@ -577,6 +578,52 @@ bool Group::AddMember(Player* player, uint8 roles /* = 0 */)
return true;
}
void Group::AddMemberWithGuid(ObjectGuid guid)
{
// Idempotent under sidecar event redelivery: never duplicate a MemberSlot.
if (IsMember(guid))
return;
if (Player* player = ObjectAccessor::FindPlayer(guid))
{
AddMember(player);
return;
}
// Get first not-full group
uint8 subGroup = 0;
if (m_subGroupsCounts)
{
bool groupFound = false;
for (; subGroup < MAX_RAID_SUBGROUPS; ++subGroup)
{
if (m_subGroupsCounts[subGroup] < MAXGROUPSIZE)
{
groupFound = true;
break;
}
}
// We are raid group and no one slot is free
if (!groupFound)
return;
}
MemberSlot member;
member.guid = guid;
sCharacterCache->GetCharacterNameByGuid(guid, member.name);
member.group = subGroup;
member.flags = 0;
member.roles = 0;
m_memberSlots.push_back(member);
if (!isBGGroup() && !isBFGroup())
{
sCharacterCache->UpdateCharacterGroup(guid, GetGUID());
}
SubGroupCounterIncrease(subGroup);
}
bool Group::RemoveMember(ObjectGuid guid, RemoveMethod const& method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= ObjectGuid::Empty*/, char const* reason /*= nullptr*/)
{
BroadcastGroupUpdate();
@@ -588,8 +635,14 @@ bool Group::RemoveMember(ObjectGuid guid, RemoveMethod const& method /*= GROUP_R
return m_memberSlots.size() > 0;
}
// remove member and change leader (if need) only if strong more 2 members _before_ member remove (BG/BF allow 1 member group)
if (GetMembersCount() > ((isBGGroup() || isLFGGroup() || isBFGroup()) ? 1u : 2u))
// remove member and change leader (if need) only if strong more 2 members _before_ member remove (BG/BF allow 1 member group),
// except in cluster mode, where this branch is taken for any size: the group
// service owns the group lifecycle and local Disband() is a no-op, so always
// unlink the removed member here; waiting for the disband event leaves the
// last two members with a dangling group pointer whenever that event is lost
// (group service restart).
if (GetMembersCount() > ((isBGGroup() || isLFGGroup() || isBFGroup()) ? 1u : 2u)
|| (sToCloud9Sidecar->ClusterModeEnabled() && !isBGGroup() && !isBFGroup()))
{
Player* player = ObjectAccessor::FindConnectedPlayer(guid);
if (player)
@@ -609,19 +662,24 @@ bool Group::RemoveMember(ObjectGuid guid, RemoveMethod const& method /*= GROUP_R
player->UpdateForQuestWorldObjects();
}
WorldPacket data;
if (method == GROUP_REMOVEMETHOD_KICK || method == GROUP_REMOVEMETHOD_KICK_LFG)
// BG/BF groups stay locally owned in cluster mode (see the gates above),
// so their removal packets must not be delegated to the group service.
if (!sToCloud9Sidecar->ClusterModeEnabled() || isBGGroup() || isBFGroup())
{
data.Initialize(SMSG_GROUP_UNINVITE, 0);
player->SendDirectMessage(&data);
}
WorldPacket data;
// Do we really need to send this opcode?
data.Initialize(SMSG_GROUP_LIST, 1 + 1 + 1 + 1 + 8 + 4 + 4 + 8);
data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0);
data << m_guid << uint32(m_counter) << uint32(0) << uint64(0);
player->SendDirectMessage(&data);
if (method == GROUP_REMOVEMETHOD_KICK || method == GROUP_REMOVEMETHOD_KICK_LFG)
{
data.Initialize(SMSG_GROUP_UNINVITE, 0);
player->GetSession()->SendPacket(&data);
}
// Do we really need to send this opcode?
data.Initialize(SMSG_GROUP_LIST, 1 + 1 + 1 + 1 + 8 + 4 + 4 + 8);
data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0);
data << m_guid << uint32(m_counter) << uint32(0) << uint64(0);
player->GetSession()->SendPacket(&data);
}
}
// Remove player from group in DB
@@ -756,7 +814,7 @@ void Group::ChangeLeader(ObjectGuid newLeaderGuid)
sScriptMgr->OnGroupChangeLeader(this, newLeaderGuid, m_leaderGuid); // This hook should be executed at the end - Not used anywhere in the original core
}
void Group::Disband(bool hideDestroy /* = false */)
void Group::ForcedDisband(bool hideDestroy /* = false */)
{
sScriptMgr->OnGroupDisband(this);
@@ -852,6 +910,14 @@ void Group::Disband(bool hideDestroy /* = false */)
delete this;
}
void Group::Disband(bool hideDestroy /* = false */)
{
if (sToCloud9Sidecar->ClusterModeEnabled() && !this->isBFGroup() && !this->isBGGroup())
return;
ForcedDisband(hideDestroy);
}
/*********************************************************/
/*** LOOT SYSTEM ***/
/*********************************************************/
@@ -1791,6 +1857,12 @@ void Group::SendTargetIconList(WorldSession* session)
void Group::SendUpdate()
{
if (sToCloud9Sidecar->ClusterModeEnabled() && !this->isBFGroup() && !this->isBGGroup())
{
// Group service responsible for sending these updates.
return;
}
for (member_witerator witr = m_memberSlots.begin(); witr != m_memberSlots.end(); ++witr)
SendUpdateToPlayer(witr->guid, &(*witr));
}
@@ -2207,7 +2279,7 @@ void Roll::targetObjectBuildLink()
void Group::SetDungeonDifficulty(Difficulty difficulty)
{
m_dungeonDifficulty = difficulty;
if (!isBGGroup() && !isBFGroup())
if (!sToCloud9Sidecar->ClusterModeEnabled() && !isBGGroup() && !isBFGroup())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_DIFFICULTY);
@@ -2228,7 +2300,7 @@ void Group::SetDungeonDifficulty(Difficulty difficulty)
void Group::SetRaidDifficulty(Difficulty difficulty)
{
m_raidDifficulty = difficulty;
if (!isBGGroup() && !isBFGroup())
if (!sToCloud9Sidecar->ClusterModeEnabled() && !isBGGroup() && !isBFGroup())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_RAID_DIFFICULTY);
+5
View File
@@ -37,6 +37,7 @@ class Unit;
class WorldObject;
class WorldPacket;
class WorldSession;
class ToCloud9GroupHooks;
struct MapEntry;
@@ -174,6 +175,7 @@ public:
/** todo: uninvite people that not accepted invite **/
class Group
{
friend class ToCloud9GroupHooks;
public:
struct MemberSlot
{
@@ -344,6 +346,9 @@ protected:
void SubGroupCounterDecrease(uint8 subgroup);
void ToggleGroupMemberFlag(member_witerator slot, uint8 flag, bool apply);
void AddMemberWithGuid(ObjectGuid guid);
void ForcedDisband(bool hideDestroy = false);
MemberSlotList m_memberSlots;
GroupRefMgr m_memberMgr;
InvitesList m_invitees;
+5 -1
View File
@@ -53,7 +53,11 @@ void GroupMgr::InitGroupIds()
void GroupMgr::RegisterGroupId(ObjectGuid::LowType groupId)
{
// Allocation was done in InitGroupIds()
// InitGroupIds() sizes the bitmap to the local MAX(guid) at startup. In cluster mode the
// group service assigns ids (auto-increment), which can exceed that bound, so grow on demand.
if (groupId >= _groupIds.size())
_groupIds.resize(groupId + 1);
_groupIds[groupId] = true;
// Groups are pulled in ascending order from db and _nextGroupId is initialized with 1,
@@ -18,6 +18,8 @@
#include "ChannelMgr.h"
#include "ObjectMgr.h" // for normalizePlayerName
#include "Player.h"
#include "Language.h"
#include "TC9Sidecar.h"
#include <cctype>
void WorldSession::HandleJoinChannel(WorldPacket& recvPacket)
@@ -38,6 +40,23 @@ void WorldSession::HandleJoinChannel(WorldPacket& recvPacket)
AreaTableEntry const* zone = sAreaTableStore.LookupEntry(GetPlayer()->GetZoneId());
if (!zone || !GetPlayer()->CanJoinConstantChannelInZone(channel, zone))
return;
// Cluster mode rebuilds the localized channel name so nodes agree on it;
// stock servers keep the client-supplied name.
if (sToCloud9Sidecar->ClusterModeEnabled())
{
auto const locale = GetSessionDbcLocale();
std::string const& zoneName = zone->area_name[locale];
std::string const cityName = sObjectMgr->GetAcoreStringForDBCLocale(LANG_CHANNEL_CITY);
char const* nameExt = (channel->flags & CHANNEL_DBC_FLAG_CITY_ONLY) ? cityName.c_str() : zoneName.c_str();
std::array<char, 128> buffer{};
if (char const* pattern = channel->pattern[locale])
{
std::snprintf(buffer.data(), buffer.size(), pattern, nameExt);
channelName = buffer.data();
}
}
}
if (channelName.empty())
+62 -47
View File
@@ -54,6 +54,7 @@
#include "SpellAuraEffects.h"
#include "SpellAuras.h"
#include "StringConvert.h"
#include "TC9Sidecar.h"
#include "Tokenize.h"
#include "Transport.h"
#include "Util.h"
@@ -81,125 +82,126 @@ bool LoginQueryHolder::Initialize()
SetSize(MAX_PLAYER_LOGIN_QUERY);
bool res = true;
ObjectGuid::LowType lowGuid = m_guid.GetCounter();
uint64 rawGUID = m_guid.GetRawValue();
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_FROM, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AURAS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_AURAS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELL);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELLS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DAILYQUESTSTATUS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_WEEKLYQUESTSTATUS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MONTHLYQUESTSTATUS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SEASONALQUESTSTATUS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_REPUTATION);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_REPUTATION, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INVENTORY);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INVENTORY, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACTIONS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAILS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_ITEMS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SOCIALLIST);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_HOMEBIND);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_HOME_BIND, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS, stmt);
if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
{
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES, stmt);
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_EQUIPMENTSETS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ENTRY_POINT);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ENTRY_POINT, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GLYPHS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GLYPHS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_TALENTS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_TALENTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SKILLS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SKILLS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_RANDOMBG);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_BANNED);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BANNED, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BREW_OF_THE_MONTH);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BREW_OF_THE_MONTH, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES);
@@ -207,19 +209,19 @@ bool LoginQueryHolder::Initialize()
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CORPSE_LOCATION);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CORPSE_LOCATION, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_SETTINGS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CHARACTER_SETTINGS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PETS);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_PET_SLOTS, stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_ACHIEVEMENT_OFFLINE_UPDATES);
stmt->SetData(0, lowGuid);
stmt->SetData(0, rawGUID);
res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_OFFLINE_ACHIEVEMENTS_UPDATES, stmt);
return res;
@@ -699,7 +701,9 @@ void WorldSession::HandlePlayerLoginOpcode(WorldPacket& recvData)
ObjectGuid playerGuid;
recvData >> playerGuid;
if (!IsLegitCharacterForAccount(playerGuid))
// The ownership check is delegated to the gateway in cluster mode, but a
// non-player GUID is invalid regardless of who authenticated the session.
if (!playerGuid.IsPlayer() || (!sToCloud9Sidecar->ClusterModeEnabled() && !IsLegitCharacterForAccount(playerGuid)))
{
LOG_ERROR("network", "Account ({}) can't login with that character ({}).", GetAccountId(), playerGuid.ToString());
KickPlayer("Account can't login with this character");
@@ -847,20 +851,28 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder const& holder)
chH.PSendSysMessage("{}", GitRevision::GetFullVersion());
}
if (uint32 guildId = sCharacterCache->GetCharacterGuildIdByGuid(pCurrChar->GetGUID()))
if (!sToCloud9Sidecar->ClusterModeEnabled())
{
Guild* guild = sGuildMgr->GetGuildById(guildId);
Guild::Member const* member = guild ? guild->GetMember(pCurrChar->GetGUID()) : nullptr;
if (member)
if (uint32 guildId = sCharacterCache->GetCharacterGuildIdByGuid(pCurrChar->GetGUID()))
{
pCurrChar->SetInGuild(guildId);
pCurrChar->SetRank(member->GetRankId());
guild->SendLoginInfo(this);
Guild* guild = sGuildMgr->GetGuildById(guildId);
Guild::Member const* member = guild ? guild->GetMember(pCurrChar->GetGUID()) : nullptr;
if (member)
{
pCurrChar->SetInGuild(guildId);
pCurrChar->SetRank(member->GetRankId());
guild->SendLoginInfo(this);
}
else
{
LOG_ERROR("network.opcode", "Player {} ({}) marked as member of not existing guild (id: {}), removing guild membership for player.",
pCurrChar->GetName(), pCurrChar->GetGUID().ToString(), guildId);
pCurrChar->SetInGuild(0);
pCurrChar->SetRank(0);
}
}
else
{
LOG_ERROR("network.opcode", "Player {} ({}) marked as member of not existing guild (id: {}), removing guild membership for player.",
pCurrChar->GetName(), pCurrChar->GetGUID().ToString(), guildId);
pCurrChar->SetInGuild(0);
pCurrChar->SetRank(0);
}
@@ -914,9 +926,12 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder const& holder)
pCurrChar->SendInitialPacketsAfterAddToMap();
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE);
stmt->SetData(0, pCurrChar->GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
if (!sToCloud9Sidecar->ClusterModeEnabled())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE);
stmt->SetData(0, pCurrChar->GetGUID().GetCounter());
CharacterDatabase.Execute(stmt);
}
LoginDatabasePreparedStatement* loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_ONLINE);
loginStmt->SetData(0, realm.Id.Realm);
+13 -2
View File
@@ -713,6 +713,18 @@ namespace Acore
void WorldSession::HandleTextEmoteOpcode(WorldPacket& recvData)
{
uint32 text_emote;
recvData >> text_emote;
constexpr uint32 readyEmote = 126;
// Handle confirmation redirect when the player types "/ready" after the new node becomes available for redirection.
if (text_emote == readyEmote && GetPlayer()->GetMap()->IsPlayerRedirectKickTimerActive())
{
HandleTC9PrepareForRedirect(recvData);
return;
}
if (!GetPlayer()->IsAlive())
return;
@@ -728,10 +740,9 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket& recvData)
if (GetPlayer()->IsSpectator())
return;
uint32 text_emote, emoteNum;
uint32 emoteNum;
ObjectGuid guid;
recvData >> text_emote;
recvData >> emoteNum;
recvData >> guid;
+93 -5
View File
@@ -27,6 +27,7 @@
#include "SocialMgr.h"
#include "Spell.h"
#include "SpellMgr.h"
#include "TC9Sidecar.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
@@ -505,6 +506,79 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/)
}
}
bool needsCrossrealmHandling = sToCloud9Sidecar->IsCrossrealm() && _player->GetGUID().GetRealmID() != trader->GetGUID().GetRealmID();
// Create new items for crossrealm usage.
if (needsCrossrealmHandling)
{
CharacterDatabasePreparedStatement* stmt = nullptr;
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
stmt = CharacterDatabase.GetPreparedStatement(CHAR_NO_OP_PROVIDE_REALM_CONTEXT);
stmt->SetData(0, _player->GetGUID().GetRealmID());
trans->Append(stmt);
for (uint8 i = 0; i < TRADE_SLOT_TRADED_COUNT; i++)
{
if (myItems[i])
{
Item* newItem = myItems[i]->CloneItem(myItems[i]->GetCount(), trader);
if (!newItem)
{
ItemPosCountVec playerDst;
if (_player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, myItems[i], false) == EQUIP_ERR_OK)
_player->MoveItemToInventory(playerDst, myItems[i], true, true);
// Should we handle else statement here?
continue;
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->SetData(0, myItems[i]->GetGUID().GetCounter());
trans->Append(stmt);
delete myItems[i];
myItems[i] = newItem;
}
}
CharacterDatabase.CommitTransaction(trans);
trans = CharacterDatabase.BeginTransaction();
stmt = CharacterDatabase.GetPreparedStatement(CHAR_NO_OP_PROVIDE_REALM_CONTEXT);
stmt->SetData(0, trader->GetGUID().GetRealmID());
trans->Append(stmt);
for (uint8 i = 0; i < TRADE_SLOT_TRADED_COUNT; i++)
{
if (hisItems[i])
{
Item* newItem = hisItems[i]->CloneItem(hisItems[i]->GetCount(), _player);
if (!newItem)
{
ItemPosCountVec playerDst;
if (trader->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false) == EQUIP_ERR_OK)
trader->MoveItemToInventory(playerDst, hisItems[i], true, true);
// Should we handle else statement here?
continue;
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
stmt->SetData(0, hisItems[i]->GetGUID().GetCounter());
trans->Append(stmt);
delete hisItems[i];
hisItems[i] = newItem;
}
}
CharacterDatabase.CommitTransaction(trans);
}
// execute trade: 2. store
moveItems(myItems, hisItems);
@@ -575,11 +649,25 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/)
delete trader->m_trade;
trader->m_trade = nullptr;
// desynchronized with the other saves here (SaveInventoryAndGoldToDB() not have own transaction guards)
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
_player->SaveInventoryAndGoldToDB(trans);
trader->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
// We can't use single transaction with different databases.
if (needsCrossrealmHandling)
{
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
_player->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
trans = CharacterDatabase.BeginTransaction();
trader->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
}
else
{
// desynchronized with the other saves here (SaveInventoryAndGoldToDB() not have own transaction guards)
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
_player->SaveInventoryAndGoldToDB(trans);
trader->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
}
info.Status = TRADE_STATUS_TRADE_COMPLETE;
trader->GetSession()->SendTradeStatus(info);
@@ -29,6 +29,7 @@
#include "ObjectMgr.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "TC9Sidecar.h"
#include "Timer.h"
#include "Transport.h"
#include "World.h"
@@ -164,6 +165,9 @@ InstanceSave::~InstanceSave()
void InstanceSave::InsertToDB()
{
if (sToCloud9Sidecar->ClusterModeEnabled() && !sToCloud9Sidecar->IsMapAssigned(GetMapId()))
return;
std::string data;
uint32 completedEncounters = 0;
@@ -454,6 +458,157 @@ void InstanceSaveMgr::LoadCharacterBinds()
lock_instLists = false;
}
// Runs on a std::async worker thread. Only the two synchronous CharacterDatabase
// reads happen here (safe: the synch connection pool is mutex-guarded per connection).
// All manager-state access is deferred to MergeWithNewInstanceSaves on the world thread.
InstanceMapLoadRows InstanceSaveMgr::LoadInstanceSavesAndBindsForMapIDs(std::vector<uint32> const& mapIDs)
{
InstanceMapLoadRows rows;
std::stringstream mapIDsStr;
for (size_t i = 0; i < mapIDs.size(); ++i)
{
mapIDsStr << mapIDs[i];
if (i < mapIDs.size() - 1)
mapIDsStr << ",";
}
QueryResult result = CharacterDatabase.Query("SELECT id, map, resettime, difficulty, completedEncounters, data FROM instance WHERE map IN ({}) ORDER BY id ASC", mapIDsStr.str());
if (result)
{
do
{
Field* fields = result->Fetch();
InstanceMapLoadRows::InstanceRow row;
row.instanceId = fields[0].Get<uint32>();
row.mapId = fields[1].Get<uint16>();
row.resetTime = time_t(fields[2].Get<uint32>());
row.difficulty = fields[3].Get<uint8>();
row.completedEncounters = fields[4].Get<uint32>();
row.data = fields[5].Get<std::string>();
rows.instances.push_back(std::move(row));
} while (result->NextRow());
}
result = CharacterDatabase.Query("SELECT guid, instance, permanent, extended FROM character_instance WHERE instance IN (SELECT id FROM instance WHERE map IN ({}))", mapIDsStr.str());
if (result)
{
do
{
Field* fields = result->Fetch();
InstanceMapLoadRows::BindRow row;
row.guidLow = fields[0].Get<uint32>();
row.instanceId = fields[1].Get<uint32>();
row.perm = fields[2].Get<bool>();
row.extended = fields[3].Get<bool>();
rows.binds.push_back(row);
} while (result->NextRow());
}
return rows;
}
// Runs on the world thread (TC9 async completion callback). Safe to touch
// m_instanceSaveById, playerBindStorage, m_resetExtendedTimeByMapDifficulty and MapMgr here.
void InstanceSaveMgr::MergeWithNewInstanceSaves(InstanceMapLoadRows const& loadResult)
{
// Same guard as LoadCharacterBinds: without it, an unbind cascading into
// DeleteInstanceSaveIfNeeded would delete the very DB rows being merged.
lock_instLists = true;
for (InstanceMapLoadRows::InstanceRow const& row : loadResult.instances)
{
MapEntry const* entry = sMapStore.LookupEntry(row.mapId);
if (!entry)
{
LOG_ERROR("instance.save", "InstanceSaveMgr::MergeWithNewInstanceSaves: wrong mapid = {}, instanceid = {}!", row.mapId, row.instanceId);
continue;
}
// Same row validation as AddInstanceSave for rows loaded on reassignment.
if (row.instanceId == 0)
{
LOG_ERROR("instance.save", "InstanceSaveMgr::MergeWithNewInstanceSaves: mapid = {}, wrong instanceid = {}!", row.mapId, row.instanceId);
continue;
}
if (row.difficulty >= (entry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
{
LOG_ERROR("instance.save", "InstanceSaveMgr::MergeWithNewInstanceSaves: mapid = {}, instanceid = {}, wrong difficulty {}!", row.mapId, row.instanceId, row.difficulty);
continue;
}
time_t extendedResetTime = 0;
if (entry->IsRaid() || row.difficulty > DUNGEON_DIFFICULTY_NORMAL)
extendedResetTime = GetExtendedResetTimeFor(row.mapId, Difficulty(row.difficulty));
InstanceSave* save = new InstanceSave(row.mapId, row.instanceId, Difficulty(row.difficulty), row.resetTime, extendedResetTime);
save->SetCompletedEncounterMask(row.completedEncounters);
save->SetInstanceData(row.data);
if (row.resetTime > 0)
save->SetResetTime(row.resetTime);
InstanceSaveHashMap::iterator currentSave = m_instanceSaveById.find(row.instanceId);
if (currentSave != m_instanceSaveById.end())
{
InstanceSave* oldSave = currentSave->second;
// Unbind every player still pointing at the stale save before it is
// freed, in-memory only: the DB rows were just refetched and are
// rebound below. Iterate a copy, PlayerUnbindInstance mutates the list.
GuidList players = oldSave->m_playerList;
for (ObjectGuid const& playerGuid : players)
PlayerUnbindInstance(playerGuid, oldSave->GetMapId(), oldSave->GetDifficulty(), false);
m_instanceSaveById.erase(currentSave);
delete oldSave;
}
m_instanceSaveById[row.instanceId] = save;
}
for (InstanceMapLoadRows::BindRow const& row : loadResult.binds)
{
InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(row.instanceId);
InstanceSave* save = itr != m_instanceSaveById.end() ? itr->second : nullptr;
if (!save)
continue;
ObjectGuid guid = ObjectGuid::Create<HighGuid::Player>(row.guidLow);
PlayerCreateBoundInstancesMaps(guid);
InstancePlayerBind& bind = playerBindStorage[guid]->m[save->GetDifficulty()][save->GetMapId()];
if (bind.save) // pussywizard: another bind for the same map and difficulty! may happen because of mysql thread races
{
if (bind.perm) // already loaded perm -> delete currently checked one from db
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
stmt->SetData(0, guid.GetCounter());
stmt->SetData(1, row.instanceId);
CharacterDatabase.Execute(stmt);
continue;
}
else // override temp bind by newest one
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);
stmt->SetData(0, guid.GetCounter());
stmt->SetData(1, bind.save->GetInstanceId());
CharacterDatabase.Execute(stmt);
bind.save->RemovePlayer(guid, this);
}
}
bind.save = save;
bind.perm = row.perm;
bind.extended = row.extended;
save->AddPlayer(guid);
if (row.perm)
save->SetCanReset(false);
}
lock_instLists = false;
}
void InstanceSaveMgr::ScheduleReset(time_t time, InstResetEvent event)
{
m_resetTimeQueue.insert(std::pair<time_t, InstResetEvent>(time, event));
@@ -27,6 +27,7 @@
#include <map>
#include <mutex>
#include <unordered_map>
#include <vector>
struct InstanceTemplate;
struct MapEntry;
@@ -103,6 +104,31 @@ private:
typedef std::unordered_map<uint32 /*PAIR32(map, difficulty)*/, time_t /*resetTime*/> ResetTimeByMapDifficultyMap;
// Raw rows fetched on a worker thread by LoadInstanceSavesAndBindsForMapIDs.
// Contains no manager-owned state, so it is safe to build off the world thread
// and consume later on the world thread in MergeWithNewInstanceSaves.
struct InstanceMapLoadRows
{
struct InstanceRow
{
uint32 instanceId;
uint16 mapId;
time_t resetTime;
uint8 difficulty;
uint32 completedEncounters;
std::string data;
};
struct BindRow
{
uint32 guidLow;
uint32 instanceId;
bool perm;
bool extended;
};
std::vector<InstanceRow> instances;
std::vector<BindRow> binds;
};
class InstanceSaveMgr
{
friend class InstanceSave;
@@ -133,6 +159,11 @@ public:
void LoadInstanceSaves();
void LoadCharacterBinds();
// Worker thread: performs only the (blocking) DB reads, touches no manager state.
[[nodiscard]] InstanceMapLoadRows LoadInstanceSavesAndBindsForMapIDs(std::vector<uint32> const& mapIDs);
// World thread: builds InstanceSaves and player binds from the fetched rows and merges them in.
void MergeWithNewInstanceSaves(InstanceMapLoadRows const& loadResult);
[[nodiscard]] time_t GetResetTimeFor(uint32 mapid, Difficulty d) const
{
ResetTimeByMapDifficultyMap::const_iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d));
@@ -31,6 +31,7 @@
#include "RBAC.h"
#include "ScriptMgr.h"
#include "Spell.h"
#include "TC9Sidecar.h"
#include "WorldSession.h"
BossBoundaryData::~BossBoundaryData()
@@ -41,6 +42,9 @@ BossBoundaryData::~BossBoundaryData()
void InstanceScript::SaveToDB()
{
if (sToCloud9Sidecar->ClusterModeEnabled() && !sToCloud9Sidecar->IsMapAssigned(instance->GetEntry()->MapID))
return;
std::string data = GetSaveData();
//if (data.empty()) // pussywizard: encounterMask can be updated and theres no reason to not save
// return;
+48 -1
View File
@@ -38,6 +38,7 @@
#include "Pet.h"
#include "PoolMgr.h"
#include "ScriptMgr.h"
#include "TC9Sidecar.h"
#include "Transport.h"
#include "VMapFactory.h"
#include "Vehicle.h"
@@ -518,6 +519,8 @@ void Map::Update(const uint32 t_diff, const uint32 s_diff, bool /*thread*/)
HandleDelayedVisibility();
UpdatePlayersRedirectKickEvent(t_diff);
UpdateWeather(t_diff);
UpdateExpiredCorpses(t_diff);
@@ -1670,7 +1673,7 @@ void Map::SendInitTransports(Player* player)
// Hack to send out transports
UpdateData transData;
for (TransportsContainer::const_iterator itr = _transports.begin(); itr != _transports.end(); ++itr)
if (*itr != player->GetTransport())
if (*itr != player->GetTransport() && (!sToCloud9Sidecar->ClusterModeEnabled() || player->InSamePhase(*itr)))
(*itr)->BuildCreateUpdateBlockForPlayer(&transData, player);
if (!transData.HasData())
@@ -1848,6 +1851,50 @@ uint32 Map::GetPlayersCountExceptGMs(bool aliveOnly /*= false*/) const
return count;
}
void Map::StartPlayersRedirectKickTimer()
{
for (MapRefMgr::iterator itr = m_mapRefMgr.begin(); itr != m_mapRefMgr.end(); ++itr)
itr->GetSource()->SendSystemMessage("Preparing to enter parallel dimension... One minute!\nAccelerate transfer: Teleport or type \"/ready\" in chat.");
_redirectKickTimer.Reset(60 * SECOND * IN_MILLISECONDS);
_lastAnnounceRedirectKickTimer.Reset(55 * SECOND * IN_MILLISECONDS);
_lastAnnounceRedirectKickTimer.Update(1);
}
void Map::StopPlayersRedirectKickTimer()
{
_redirectKickTimer.Reset(0);
_lastAnnounceRedirectKickTimer.Reset(0);
}
void Map::UpdatePlayersRedirectKickEvent(uint32 diff)
{
if (_redirectKickTimer.Passed())
return;
_redirectKickTimer.Update(diff);
if (_redirectKickTimer.Passed())
{
auto emptyPacket = WorldPacket();
for (MapRefMgr::iterator itr = m_mapRefMgr.begin(); itr != m_mapRefMgr.end(); ++itr)
itr->GetSource()->GetSession()->HandleTC9PrepareForRedirect(emptyPacket);
return;
}
if (_lastAnnounceRedirectKickTimer.Passed())
return;
_lastAnnounceRedirectKickTimer.Update(diff);
if (_lastAnnounceRedirectKickTimer.Passed())
for (MapRefMgr::iterator itr = m_mapRefMgr.begin(); itr != m_mapRefMgr.end(); ++itr)
itr->GetSource()->SendSystemMessage("Dimensional shift incoming! Prepare to transition in 5 seconds...");
}
void Map::SendToPlayers(WorldPacket const* data) const
{
for (MapRefMgr::const_iterator itr = m_mapRefMgr.begin(); itr != m_mapRefMgr.end(); ++itr)
+10
View File
@@ -27,6 +27,7 @@
#include "GameObjectModel.h"
#include "GridDefines.h"
#include "GridRefMgr.h"
#include "Timer.h"
#include "MapCollisionData.h"
#include "MapGridManager.h"
#include "MapRefMgr.h"
@@ -325,6 +326,10 @@ public:
void SendToPlayers(WorldPacket const* data) const;
void StartPlayersRedirectKickTimer();
void StopPlayersRedirectKickTimer();
bool IsPlayerRedirectKickTimerActive() { return !_redirectKickTimer.Passed(); }
typedef MapRefMgr PlayerList;
[[nodiscard]] PlayerList const& GetPlayers() const { return m_mapRefMgr; }
@@ -585,6 +590,8 @@ private:
void SendObjectUpdates();
void UpdatePlayersRedirectKickEvent(uint32 diff);
protected:
// Type specific code for add/remove to/from grid
template<class T>
@@ -693,6 +700,9 @@ private:
PendingAddUpdatableObjectList _pendingAddUpdatableObjectList;
IntervalTimer _updatableObjectListRecheckTimer;
ZoneWideVisibleWorldObjectsMap _zoneWideVisibleWorldObjectsMap;
TimeTrackerSmall _redirectKickTimer;
TimeTrackerSmall _lastAnnounceRedirectKickTimer;
};
enum InstanceResetMethod
+4
View File
@@ -31,6 +31,7 @@
#include "Opcodes.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "TC9Sidecar.h"
#include "Transport.h"
#include "World.h"
#include "WorldPacket.h"
@@ -405,6 +406,9 @@ void MapMgr::RegisterInstanceId(uint32 instanceId)
uint32 MapMgr::GenerateInstanceId()
{
if (sToCloud9Sidecar->ClusterModeEnabled())
return sToCloud9Sidecar->GenerateInstanceGuid();
uint32 newInstanceId = _nextInstanceId;
// find the lowest available id starting from the current _nextInstanceId
+3
View File
@@ -21,6 +21,9 @@
#include "MoveSpline.h"
#include "QueryResult.h"
#include "Transport.h"
#include "TaskScheduler.h"
#include "Config.h"
#include <chrono>
TransportTemplate::~TransportTemplate()
{
@@ -1439,6 +1439,8 @@ void OpcodeTable::Initialize()
/*0x51C*/ DEFINE_SERVER_OPCODE_HANDLER(SMSG_COMMENTATOR_SKIRMISH_QUEUE_RESULT1, STATUS_NEVER);
/*0x51D*/ DEFINE_SERVER_OPCODE_HANDLER(SMSG_COMMENTATOR_SKIRMISH_QUEUE_RESULT2, STATUS_NEVER);
/*0x51E*/ DEFINE_SERVER_OPCODE_HANDLER(SMSG_MULTIPLE_MOVES, STATUS_NEVER);
/*0x51F*/ DEFINE_HANDLER(TC9_CMSG_PREPARE_FOR_REDIRECT, STATUS_AUTHED, PROCESS_THREADUNSAFE, &WorldSession::HandleTC9PrepareForRedirect);
/*0x520*/ DEFINE_SERVER_OPCODE_HANDLER(TC9_SMSG_READY_FOR_REDIRECT, STATUS_NEVER);
#undef DEFINE_HANDLER
#undef DEFINE_SERVER_OPCODE_HANDLER
+3 -1
View File
@@ -1338,7 +1338,9 @@ enum Opcodes : uint16
SMSG_COMMENTATOR_SKIRMISH_QUEUE_RESULT1 = 0x51C,
SMSG_COMMENTATOR_SKIRMISH_QUEUE_RESULT2 = 0x51D,
SMSG_MULTIPLE_MOVES = 0x51E, // uncompressed version of SMSG_COMPRESSED_MOVES
NUM_MSG_TYPES = 0x51F
TC9_CMSG_PREPARE_FOR_REDIRECT = 0x51F,
TC9_SMSG_READY_FOR_REDIRECT = 0x520,
NUM_MSG_TYPES = 0x521
};
enum OpcodeMisc : uint16
+91 -33
View File
@@ -19,6 +19,7 @@
\ingroup u2w
*/
#include "TC9Sidecar.h"
#include "WorldSession.h"
#include "AccountMgr.h"
#include "BattlegroundMgr.h"
@@ -673,7 +674,7 @@ void WorldSession::SendPlayTimeWarning(PlayTimeFlag flag, int32 playTimeRemainin
}
/// %Log the player out
void WorldSession::LogoutPlayer(bool save)
void WorldSession::LogoutPlayer(bool save, bool redirecting)
{
// finish pending transfers before starting the logout
while (_player && _player->IsBeingTeleportedFar())
@@ -759,23 +760,26 @@ void WorldSession::LogoutPlayer(bool save)
// there are some positive auras from boss encounters that can be kept by logging out and logging in after boss is dead, and may be used on next bosses
_player->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
if (Group *group = _player->GetGroupInvite())
sWorld->getBoolConfig(CONFIG_LEAVE_GROUP_ON_LOGOUT)
? _player->UninviteFromGroup() // Can disband group.
: group->RemoveInvite(_player); // Just removes invite.
if (!redirecting)
{
if (Group *group = _player->GetGroupInvite())
sWorld->getBoolConfig(CONFIG_LEAVE_GROUP_ON_LOGOUT)
? _player->UninviteFromGroup() // Can disband group.
: group->RemoveInvite(_player); // Just removes invite.
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected) d) LeaveGroupOnLogout is enabled
if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && !_player->GetGroup()->isLFGGroup() && m_Socket && sWorld->getBoolConfig(CONFIG_LEAVE_GROUP_ON_LOGOUT))
_player->RemoveFromGroup();
// Remove player from active loot rolls in LFG groups (player stays in group but should not block rolls)
else if (Group* group = _player->GetGroup())
if (group->isLFGGroup())
group->RemovePlayerFromRolls(_player->GetGUID());
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected) d) LeaveGroupOnLogout is enabled
if (!sToCloud9Sidecar->ClusterModeEnabled() && _player->GetGroup() && !_player->GetGroup()->isRaidGroup() && !_player->GetGroup()->isLFGGroup() && m_Socket && sWorld->getBoolConfig(CONFIG_LEAVE_GROUP_ON_LOGOUT))
_player->RemoveFromGroup();
// Remove player from active loot rolls in LFG groups (player stays in group but should not block rolls)
else if (Group* group = _player->GetGroup())
if (group->isLFGGroup())
group->RemovePlayerFromRolls(_player->GetGUID());
// pussywizard: checked second time after being removed from a group
if (!_player->IsBeingTeleportedFar() && !_player->m_InstanceValid && !_player->IsGameMaster())
_player->RepopAtGraveyard();
// pussywizard: checked second time after being removed from a group
if (!_player->IsBeingTeleportedFar() && !_player->m_InstanceValid && !_player->IsGameMaster())
_player->RepopAtGraveyard();
}
// Repop at Graveyard or other player far teleport will prevent saving player because of not present map
// Teleport player immediately for correct player save
@@ -814,12 +818,15 @@ void WorldSession::LogoutPlayer(bool save)
}
}
//! Broadcast a logout message to the player's friends
sSocialMgr->SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUID(), true);
sSocialMgr->RemovePlayerSocial(_player->GetGUID());
if (!redirecting)
{
//! Broadcast a logout message to the player's friends
sSocialMgr->SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUID(), true);
sSocialMgr->RemovePlayerSocial(_player->GetGUID());
//! Call script hook before deletion
sScriptMgr->OnPlayerLogout(_player);
//! Call script hook before deletion
sScriptMgr->OnPlayerLogout(_player);
}
METRIC_EVENT("player_events", "Logout", _player->GetName());
@@ -845,9 +852,12 @@ void WorldSession::LogoutPlayer(bool save)
LOG_DEBUG("network", "SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
//! Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE);
stmt->SetData(0, GetAccountId());
CharacterDatabase.Execute(stmt);
if (!redirecting)
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE);
stmt->SetData(0, GetAccountId());
CharacterDatabase.Execute(stmt);
}
}
m_playerLogout = false;
@@ -1563,21 +1573,69 @@ void WorldSession::InitializeSessionCallback(CharacterDatabaseQueryHolder const&
LoadAccountData(realmHolder.GetPreparedResult(AccountInfoQueryHolderPerRealm::GLOBAL_ACCOUNT_DATA), GLOBAL_CACHE_MASK);
LoadTutorialsData(realmHolder.GetPreparedResult(AccountInfoQueryHolderPerRealm::TUTORIALS));
if (!m_inQueue)
if (!sToCloud9Sidecar->ClusterModeEnabled())
{
SendAuthResponse(AUTH_OK, true);
}
else
{
SendAuthWaitQueue(0);
if (!m_inQueue)
{
SendAuthResponse(AUTH_OK, true);
}
else
{
SendAuthWaitQueue(0);
}
}
SetInQueue(false);
ResetTimeOutTime(false);
SendAddonsInfo();
SendClientCacheVersion(clientCacheVersion);
SendTutorialsData();
if (!sToCloud9Sidecar->ClusterModeEnabled())
{
SendAddonsInfo();
SendClientCacheVersion(clientCacheVersion);
SendTutorialsData();
}
}
void WorldSession::HandleTC9PrepareForRedirect(WorldPacket& /*recvData*/)
{
if (!sToCloud9Sidecar->ClusterModeEnabled())
return;
Player* player = this->GetPlayer();
if (player == nullptr)
{
WorldPacket data(TC9_SMSG_READY_FOR_REDIRECT, 1);
data << uint8(1); // 1 - Failed.
SendPacket(&data);
return;
}
LOG_DEBUG("network", "Starting saving, AccountId = {}", GetAccountId());
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
player->SaveToDB(trans, false, true);
AddTransactionCallback(CharacterDatabase.AsyncCommitTransaction(trans)).AfterComplete([this](bool success)
{
WorldPacket data(TC9_SMSG_READY_FOR_REDIRECT, 1);
data << uint8(!success); // 0 - Success, 1 - Failed.
SendPacket(&data);
if (!success)
{
LOG_ERROR("network", "Failed to save player, AccountId = {}", GetAccountId());
return;
}
LOG_DEBUG("network", "Saved, AccountId = {}", GetAccountId());
Player* player = GetPlayer();
if (!player)
return;
player->m_Events.AddEventAtOffset([this](){
KickPlayer("HandlePrepareForRedirect client redirected");
}, 100ms);
});
}
void WorldSession::SetPacketLogging(bool state)
+3 -1
View File
@@ -524,7 +524,7 @@ public:
return (_logoutTime > 0 && currTime >= _logoutTime + 20);
}
void LogoutPlayer(bool save);
void LogoutPlayer(bool save, bool redirecting = false);
void KickPlayer(bool setKicked = true) { return this->KickPlayer("Unknown reason", setKicked); }
void KickPlayer(std::string const& reason, bool setKicked = true);
@@ -687,6 +687,8 @@ public: // opcodes handlers
void SendCharFactionChange(ResponseCodes result, CharacterFactionChangeInfo const* factionChangeInfo);
void SendSetPlayerDeclinedNamesResult(DeclinedNameResult result, ObjectGuid guid);
void HandleTC9PrepareForRedirect(WorldPacket& recvData);
// played time
void HandlePlayedTime(WorldPackets::Character::PlayedTimeClient& packet);
+87 -82
View File
@@ -15,6 +15,7 @@
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TC9Sidecar.h"
#include "WorldSocket.h"
#include "AccountMgr.h"
#include "Config.h"
@@ -579,8 +580,9 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<ClientAuthSession> a
LoginDatabase.Execute(stmt);
// This also allows to check for possible "hack" attempts on account
// even if auth credentials are bad, try using the session key we have - client cannot read auth response error without it
_authCrypt.Init(account.SessionKey);
if (!sToCloud9Sidecar->ClusterModeEnabled())
// even if auth credentials are bad, try using the session key we have - client cannot read auth response error without it
_authCrypt.Init(account.SessionKey);
// First reject the connection if packet contains invalid data or realm state doesn't allow logging in
if (sWorld->IsClosed())
@@ -591,7 +593,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<ClientAuthSession> a
return;
}
if (authSession->RealmID != realm.Id.Realm)
if (!sToCloud9Sidecar->ClusterModeEnabled() && authSession->RealmID != realm.Id.Realm)
{
SendAuthResponseError(REALM_LIST_REALM_NOT_FOUND);
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client {} requested connecting with realm id {} but this realm has id {} set in config.",
@@ -600,105 +602,107 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<ClientAuthSession> a
return;
}
// Must be done before WorldSession is created
bool wardenActive = sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED);
if (wardenActive && account.OS != "Win" && account.OS != "OSX")
if (!sToCloud9Sidecar->ClusterModeEnabled())
{
SendAuthResponseError(AUTH_REJECT);
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client {} attempted to log in using invalid client OS ({}).", address, account.OS);
DelayedCloseSocket();
return;
}
// Must be done before WorldSession is created
if (wardenActive && account.OS != "Win" && account.OS != "OSX")
{
SendAuthResponseError(AUTH_REJECT);
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client {} attempted to log in using invalid client OS ({}).", address, account.OS);
DelayedCloseSocket();
return;
}
// Check that Key and account name are the same on client and server
uint8 t[4] = { 0x00,0x00,0x00,0x00 };
// Check that Key and account name are the same on client and server
uint8 t[4] = { 0x00,0x00,0x00,0x00 };
Acore::Crypto::SHA1 sha;
sha.UpdateData(authSession->Account);
sha.UpdateData(t);
sha.UpdateData(authSession->LocalChallenge);
sha.UpdateData(_authSeed);
sha.UpdateData(account.SessionKey);
sha.Finalize();
Acore::Crypto::SHA1 sha;
sha.UpdateData(authSession->Account);
sha.UpdateData(t);
sha.UpdateData(authSession->LocalChallenge);
sha.UpdateData(_authSeed);
sha.UpdateData(account.SessionKey);
sha.Finalize();
if (sha.GetDigest() != authSession->Digest)
{
SendAuthResponseError(AUTH_FAILED);
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Authentication failed for account: {} ('{}') address: {}", account.Id, authSession->Account, address);
DelayedCloseSocket();
return;
}
if (IpLocationRecord const* location = sIPLocation->GetLocationRecord(address))
_ipCountry = location->CountryCode;
///- Re-check ip locking (same check as in auth).
if (account.IsLockedToIP)
{
if (account.LastIP != address)
if (sha.GetDigest() != authSession->Digest)
{
SendAuthResponseError(AUTH_FAILED);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs. Original IP: {}, new IP: {}).", account.LastIP, address);
// We could log on hook only instead of an additional db log, however action logger is config based. Better keep DB logging as well
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Authentication failed for account: {} ('{}') address: {}", account.Id, authSession->Account, address);
DelayedCloseSocket();
return;
}
if (IpLocationRecord const* location = sIPLocation->GetLocationRecord(address))
_ipCountry = location->CountryCode;
///- Re-check ip locking (same check as in auth).
if (account.IsLockedToIP)
{
if (account.LastIP != address)
{
SendAuthResponseError(AUTH_FAILED);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs. Original IP: {}, new IP: {}).", account.LastIP, address);
// We could log on hook only instead of an additional db log, however action logger is config based. Better keep DB logging as well
sScriptMgr->OnFailedAccountLogin(account.Id);
DelayedCloseSocket();
return;
}
}
else if (!account.LockCountry.empty() && account.LockCountry != "00" && !_ipCountry.empty())
{
if (account.LockCountry != _ipCountry)
{
SendAuthResponseError(AUTH_FAILED);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account country differs. Original country: {}, new country: {}).", account.LockCountry, _ipCountry);
// We could log on hook only instead of an additional db log, however action logger is config based. Better keep DB logging as well
sScriptMgr->OnFailedAccountLogin(account.Id);
DelayedCloseSocket();
return;
}
}
//! Negative mutetime indicates amount of minutes to be muted effective on next login - which is now.
if (account.MuteTime < 0)
{
account.MuteTime = GameTime::GetGameTime().count() + std::llabs(account.MuteTime);
auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN);
stmt->SetData(0, account.MuteTime);
stmt->SetData(1, account.Id);
LoginDatabase.Execute(stmt);
}
if (account.IsBanned)
{
SendAuthResponseError(AUTH_BANNED);
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account banned).");
sScriptMgr->OnFailedAccountLogin(account.Id);
DelayedCloseSocket();
return;
}
}
else if (!account.LockCountry.empty() && account.LockCountry != "00" && !_ipCountry.empty())
{
if (account.LockCountry != _ipCountry)
// Check locked state for server
AccountTypes allowedAccountType = sWorld->GetPlayerSecurityLimit();
LOG_DEBUG("network", "Allowed Level: {} Player Level {}", allowedAccountType, account.Security);
if (allowedAccountType > SEC_PLAYER && account.Security < allowedAccountType)
{
SendAuthResponseError(AUTH_FAILED);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account country differs. Original country: {}, new country: {}).", account.LockCountry, _ipCountry);
// We could log on hook only instead of an additional db log, however action logger is config based. Better keep DB logging as well
SendAuthResponseError(AUTH_UNAVAILABLE);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: User tries to login but his security level is not enough");
sScriptMgr->OnFailedAccountLogin(account.Id);
DelayedCloseSocket();
return;
}
}
//! Negative mutetime indicates amount of minutes to be muted effective on next login - which is now.
if (account.MuteTime < 0)
{
account.MuteTime = GameTime::GetGameTime().count() + std::llabs(account.MuteTime);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Client '{}' authenticated successfully from {}.", authSession->Account, address);
auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN);
stmt->SetData(0, account.MuteTime);
stmt->SetData(1, account.Id);
// Update the last_ip in the database as it was successful for login
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_IP);
stmt->SetData(0, address);
stmt->SetData(1, authSession->Account);
LoginDatabase.Execute(stmt);
}
if (account.IsBanned)
{
SendAuthResponseError(AUTH_BANNED);
LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account banned).");
sScriptMgr->OnFailedAccountLogin(account.Id);
DelayedCloseSocket();
return;
}
// Check locked state for server
AccountTypes allowedAccountType = sWorld->GetPlayerSecurityLimit();
LOG_DEBUG("network", "Allowed Level: {} Player Level {}", allowedAccountType, account.Security);
if (allowedAccountType > SEC_PLAYER && account.Security < allowedAccountType)
{
SendAuthResponseError(AUTH_UNAVAILABLE);
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: User tries to login but his security level is not enough");
sScriptMgr->OnFailedAccountLogin(account.Id);
DelayedCloseSocket();
return;
}
LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Client '{}' authenticated successfully from {}.", authSession->Account, address);
// Update the last_ip in the database as it was successful for login
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_IP);
stmt->SetData(0, address);
stmt->SetData(1, authSession->Account);
LoginDatabase.Execute(stmt);
// At this point, we can safely hook a successful login
sScriptMgr->OnAccountLogin(account.Id);
@@ -712,8 +716,9 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr<ClientAuthSession> a
_worldSession->ReadAddonsInfo(authSession->AddonInfo);
// Initialize Warden system only if it is enabled by config
if (wardenActive)
if (!sToCloud9Sidecar->ClusterModeEnabled() && wardenActive)
{
// TODO: move warden outside of a node?
_worldSession->InitWarden(account.SessionKey, account.OS);
}
+93
View File
@@ -0,0 +1,93 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _ASYNC_TASK_H
#define _ASYNC_TASK_H
#include "Errors.h"
#include "Log.h"
#include <chrono>
#include <functional>
#include <future>
template <typename T>
class AsyncTask
{
public:
using AsyncFunction = std::function<T()>;
using CallbackFunction = std::function<void(T)>;
AsyncTask(AsyncFunction asyncFunc, CallbackFunction callbackFunc)
: asyncFunc(std::move(asyncFunc)), callbackFunc(std::move(callbackFunc)), isReady(false)
{
}
~AsyncTask()
{
// Ensure that the asynchronous task has completed before destruction
if (asyncTask.valid() && asyncTask.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
{
asyncTask.wait(); // Wait for the task to complete
}
}
bool InvokeIfReady()
{
if (!isReady)
{
// Check if the asynchronous task is ready
if (asyncTask.valid() && asyncTask.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
// get() rethrows anything the async function threw. Swallowing it
// would wedge the cluster handoff (the completion callback signals
// map readiness to the registry), so fail fast with context and let
// the registry's crash recovery rebalance this node.
try
{
callbackFunc(asyncTask.get());
}
catch (std::exception const& e)
{
LOG_ERROR("server.tc9", "AsyncTask failed: {}", e.what());
ABORT("AsyncTask failed: {}", e.what());
}
isReady = true;
return true;
}
}
return false;
}
void ExecuteAsync()
{
// Capture the function by value so a moved AsyncTask does not leave
// the in-flight async holding a dangling this pointer.
AsyncFunction fn = asyncFunc;
asyncTask = std::async(std::launch::async, [fn = std::move(fn)]() mutable
{
return fn();
});
}
private:
AsyncFunction asyncFunc;
CallbackFunction callbackFunc;
std::shared_future<T> asyncTask;
bool isReady;
};
#endif // _ASYNC_TASK_H
@@ -0,0 +1,115 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TC9GroupHooks.h"
#include "CharacterCache.h"
#include "Group.h"
#include "GroupMgr.h"
#include "Log.h"
void ToCloud9GroupHooks::OnGroupCreated(EventObjectGroup *group)
{
LOG_INFO("server", "Group created. ID: {}; Leader: {}.", group->guid, group->leader);
// Idempotent under sidecar event redelivery: a replayed create must not leak a second Group.
if (sGroupMgr->GetGroupByGUID(group->guid))
return;
Group* g = new Group();
g->m_guid = ObjectGuid(HighGuid::Group, group->guid);
g->m_leaderGuid = ObjectGuid(group->leader);
sCharacterCache->GetCharacterNameByGuid(g->m_leaderGuid, g->m_leaderName);
g->m_dungeonDifficulty = Difficulty(group->difficulty);
g->m_raidDifficulty = Difficulty(group->raidDifficulty);
g->m_lootMethod = LootMethod(group->lootMethod);
g->m_lootThreshold = ItemQualities(group->lootThreshold);
g->m_looterGuid = ObjectGuid(group->looterGuid);
g->m_masterLooterGuid = ObjectGuid(group->masterLooterGuid);
g->m_groupType = GroupType(group->groupType);
// Must precede member insertion: it zeroes the subgroup counters that AddMemberWithGuid increments.
if (g->m_groupType & GROUPTYPE_RAID)
g->_initRaidSubGroupsCounter();
for (int i = 0; i < group->membersSize; i++)
g->AddMemberWithGuid(ObjectGuid(group->members[i]));
sGroupMgr->AddGroup(g);
// Mark the service-assigned id used so a locally generated group can't collide with it.
sGroupMgr->RegisterGroupId(g->GetGUID().GetCounter());
}
void ToCloud9GroupHooks::OnGroupDisbanded(uint32 group)
{
LOG_INFO("server", "Group disbanded. ID: {}.", group);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
g->ForcedDisband(true);
}
void ToCloud9GroupHooks::OnGroupMemberAdded(uint32 group, uint64 member)
{
LOG_INFO("server", "Group member added. ID: {}; Member: {}.", group, member);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
g->AddMemberWithGuid(ObjectGuid(member));
}
void ToCloud9GroupHooks::OnGroupMemberRemoved(uint32 group, uint64 member, uint64 newLeader)
{
LOG_INFO("server", "Group member removed. ID: {}; Member: {}; NewLeader: {}.", group, member, newLeader);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
g->RemoveMember(ObjectGuid(member));
}
void ToCloud9GroupHooks::OnGroupLootTypeChanged(uint32 group, uint8 lootType, uint64 looter, uint8 lootThreshold)
{
LOG_INFO("server", "Group loot type changed. ID: {}; LootType: {}; Looter: {}; LootThreshold: {}.",
group, lootType, looter, lootThreshold);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
{
g->SetLootMethod((LootMethod)lootType);
g->SetMasterLooterGuid(ObjectGuid(looter));
g->SetLootThreshold((ItemQualities)lootThreshold);
}
}
void ToCloud9GroupHooks::OnGroupConvertedToRaid(uint32 group)
{
LOG_INFO("server", "Group converted to raid. ID: {}.", group);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
g->ConvertToRaid();
}
void ToCloud9GroupHooks::OnGroupRaidDifficultyChanged(uint32 group, uint8 difficulty)
{
LOG_INFO("server", "Raid difficulty changed. ID: {}; Difficulty: {}.", group, difficulty);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
g->SetRaidDifficulty((Difficulty)difficulty);
}
void ToCloud9GroupHooks::OnGroupDungeonDifficultyChanged(uint32 group, uint8 difficulty)
{
LOG_INFO("server", "Dungeon difficulty changed. ID: {}; Difficulty: {}.", group, difficulty);
if (Group* g = sGroupMgr->GetGroupByGUID(group))
g->SetDungeonDifficulty((Difficulty)difficulty);
}
@@ -0,0 +1,40 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TC9_GROUP_HOOKS_H
#define _TC9_GROUP_HOOKS_H
#include "Common.h"
#include "libsidecar.h"
class ToCloud9GroupHooks
{
public:
ToCloud9GroupHooks() {};
~ToCloud9GroupHooks() {};
static void OnGroupCreated(EventObjectGroup *group);
static void OnGroupDisbanded(uint32 group);
static void OnGroupMemberAdded(uint32 group, uint64 member);
static void OnGroupMemberRemoved(uint32 group, uint64 member, uint64 newLeader);
static void OnGroupLootTypeChanged(uint32 group, uint8 lootType, uint64 looter, uint8 lootThreshold);
static void OnGroupConvertedToRaid(uint32 group);
static void OnGroupRaidDifficultyChanged(uint32 group, uint8 difficulty);
static void OnGroupDungeonDifficultyChanged(uint32 group, uint8 difficulty);
};
#endif /* TC9GroupHooks_h */
@@ -0,0 +1,374 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TC9GrpcHandler.h"
#include "Bag.h"
#include "BattlegroundMgr.h"
#include "Item.h"
#include "ObjectAccessor.h"
#include "Player.h"
GetPlayerItemsByGuidsResponse ToCloud9GrpcHandler::GetPlayerItemsByGuids(uint64 playerGuid, uint64* items, int itemsLen)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
{
GetPlayerItemsByGuidsResponse resp;
resp.errorCode = PlayerItemErrorCodePlayerNotFound;
return resp;
}
if (itemsLen <= 0)
{
GetPlayerItemsByGuidsResponse resp;
resp.errorCode = PlayerItemErrorCodeNoError;
resp.items = nullptr;
resp.itemsSize = 0;
return resp;
}
int itemsFound = 0;
std::unique_ptr<Item* []> foundItems(new Item * [itemsLen]);
for (int i = 0; i < itemsLen; i++)
{
foundItems[i] = player->GetItemByGuid(ObjectGuid(items[i]));
if (foundItems[i])
itemsFound++;
}
// Don't forget to delete on "that" side.
PlayerItem* itemsResult = static_cast<PlayerItem *>(malloc(sizeof(PlayerItem) * itemsFound));
int itemsResultsItr = 0;
for (int i = 0; i < itemsLen; i++)
{
if (!foundItems[i])
continue;
Item* pItem = foundItems[i];
PlayerItem item;
item.guid = pItem->GetGUID().GetRawValue();
item.entry = pItem->GetEntry();
item.owner = playerGuid;
item.bagSlot = pItem->GetBagSlot();
item.slot = pItem->GetSlot();
item.isTradable = pItem->CanBeTraded(true);
item.count = pItem->GetCount();
item.flags = pItem->GetUInt32Value(ITEM_FIELD_FLAGS);
item.durability = pItem->GetUInt32Value(ITEM_FIELD_DURABILITY);
item.randomPropertyID = pItem->GetItemRandomPropertyId();
// Don't forget to delete on "that" side.
char *text = (char*)malloc(sizeof(char) * (pItem->GetText().length() + 1));
strcpy(text, pItem->GetText().c_str());
item.text = text;
itemsResult[itemsResultsItr] = item;
itemsResultsItr++;
}
GetPlayerItemsByGuidsResponse resp;
resp.errorCode = PlayerItemErrorCodeNoError;
resp.items = itemsResult;
resp.itemsSize = itemsFound;
return resp;
}
RemoveItemsWithGuidsFromPlayerResponse ToCloud9GrpcHandler::RemoveItemsWithGuidsFromPlayer(uint64 playerGuid, uint64* items, int itemsLen, uint64 assignToPlayerGuid)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
{
RemoveItemsWithGuidsFromPlayerResponse resp;
resp.errorCode = PlayerItemErrorCodePlayerNotFound;
return resp;
}
if (itemsLen <= 0)
{
RemoveItemsWithGuidsFromPlayerResponse resp;
resp.errorCode = PlayerItemErrorCodeNoError;
resp.updatedItems = nullptr;
resp.updatedItemsSize = 0;
return resp;
}
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
int itemsFound = 0;
std::unique_ptr<uint64[]> deletedItems(new uint64 [itemsLen]);
for (int i = 0; i < itemsLen; i++)
{
Item *item = player->GetItemByGuid(ObjectGuid(items[i]));
if (!item)
{
deletedItems[i] = 0;
continue;
}
itemsFound++;
deletedItems[i] = item->GetGUID().GetRawValue();
item->SetNotRefundable(player);
player->MoveItemFromInventory(item->GetBagSlot(), item->GetSlot(), true);
item->DeleteFromInventoryDB(trans);
item->SetOwnerGUID(ObjectGuid(assignToPlayerGuid));
item->SetState(ITEM_CHANGED);
item->SaveToDB(trans);
delete item;
}
if (itemsFound > 0)
{
player->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
}
// Don't forget to delete on "that" side.
uint64_t* itemsResult = (uint64_t*)malloc(sizeof(uint64_t) * itemsFound);
int itemsResultsItr = 0;
for (int i = 0; i < itemsLen; i++)
{
if (deletedItems[i] == 0)
continue;
itemsResult[itemsResultsItr] = deletedItems[i];
itemsResultsItr++;
}
RemoveItemsWithGuidsFromPlayerResponse resp;
resp.errorCode = PlayerItemErrorCodeNoError;
resp.updatedItems = itemsResult;
resp.updatedItemsSize = itemsResultsItr;
return resp;
}
PlayerItemErrorCode ToCloud9GrpcHandler::AddExistingItemToPlayer(AddExistingItemToPlayerRequest* request)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(request->playerGuid));
if (!player)
return PlayerItemErrorCodePlayerNotFound;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(request->itemEntry);
if (!proto)
return PlayerItemErrorUnknownTemplate;
Item* item = NewItemOrBag(proto);
if (!item->Create(ObjectGuid(request->itemGuid).GetCounter(), request->itemEntry, player))
{
delete item;
return PlayerItemErrorFailedToCreateItem;
}
item->SetUInt32Value(ITEM_FIELD_FLAGS, request->itemFlags);
item->SetUInt32Value(ITEM_FIELD_DURABILITY, request->itemDurability);
item->SetItemRandomProperties(request->itemRandomPropertyID);
item->SetCount(request->itemCount);
// TODO: Add text.
ItemPosCountVec dest;
uint8 msg = player->CanStoreItem(NULL_BAG, NULL_SLOT, dest, item, false);
if (msg != EQUIP_ERR_OK)
{
delete item;
return PlayerItemErrorNoInventorySpace;
}
player->MoveItemToInventory(dest, item, true);
CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();
player->SaveInventoryAndGoldToDB(trans);
CharacterDatabase.CommitTransaction(trans);
return PlayerItemErrorCodeNoError;
}
GetMoneyForPlayerResponse ToCloud9GrpcHandler::GetMoneyForPlayer(uint64 playerGuid)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
{
GetMoneyForPlayerResponse resp;
resp.errorCode = PlayerMoneyErrorCodePlayerNotFound;
return resp;
}
GetMoneyForPlayerResponse resp;
resp.errorCode = PlayerMoneyErrorCodeNoError;
resp.money = player->GetMoney();
return resp;
}
ModifyMoneyForPlayerResponse ToCloud9GrpcHandler::ModifyMoneyForPlayer(uint64 playerGuid, int32 value)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
{
ModifyMoneyForPlayerResponse resp;
resp.errorCode = PlayerMoneyErrorCodePlayerNotFound;
return resp;
}
if (!player->ModifyMoney(value, true))
{
ModifyMoneyForPlayerResponse resp;
resp.errorCode = PlayerMoneyErrorCodeTooMuchMoney;
resp.newMoneyValue = player->GetMoney();
return resp;
}
ModifyMoneyForPlayerResponse resp;
resp.errorCode = PlayerMoneyErrorCodeNoError;
resp.newMoneyValue = player->GetMoney();
return resp;
}
CanPlayerInteractWithGOAndTypeResponse ToCloud9GrpcHandler::CanPlayerInteractWithGOAndType(uint64 playerGuid, uint64 go, uint8 goType)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
{
CanPlayerInteractWithGOAndTypeResponse resp;
resp.errorCode = PlayerInteractionErrorCodeCodePlayerNotFound;
return resp;
}
CanPlayerInteractWithGOAndTypeResponse resp;
resp.errorCode = PlayerInteractionErrorCodeNoError;
resp.canInteract = player->GetGameObjectIfCanInteractWith(ObjectGuid(go), (GameobjectTypes)goType) != nullptr;
return resp;
}
CanPlayerInteractWithNPCAndFlagsResponse ToCloud9GrpcHandler::CanPlayerInteractWithNPCAndFlags(uint64 playerGuid, uint64 npc, uint32 unitFlags)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
{
CanPlayerInteractWithNPCAndFlagsResponse resp;
resp.errorCode = PlayerInteractionErrorCodeCodePlayerNotFound;
return resp;
}
CanPlayerInteractWithNPCAndFlagsResponse resp;
resp.errorCode = PlayerInteractionErrorCodeNoError;
resp.canInteract = player->GetNPCIfCanInteractWith(ObjectGuid(npc), (NPCFlags)unitFlags) != nullptr;
return resp;
}
BattlegroundStartResponse ToCloud9GrpcHandler::StartBattleground(BattlegroundStartRequest* req)
{
PvPDifficultyEntry const* pvpEntry = GetBattlegroundBracketByLevel(req->mapID, req->bracketLvl);
if (!pvpEntry)
{
BattlegroundStartResponse resp;
resp.errorCode = BattlegroundErrorFailedToCreateBG;
return resp;
}
BattlegroundTypeId bgTypeId = BattlegroundTypeId(req->battlegroundTypeID);
Battleground* bg = sBattlegroundMgr->CreateNewBattleground(bgTypeId, pvpEntry, req->arenaType, req->isRated);
if (!bg)
{
BattlegroundStartResponse resp;
resp.errorCode = BattlegroundErrorFailedToCreateBG;
return resp;
}
bg->StartBattleground();
bg->IncreaseInvitedCount(TEAM_HORDE);
bg->IncreaseInvitedCount(TEAM_ALLIANCE);
BattlegroundStartResponse resp;
resp.errorCode = BattlegroundErrorCodeNoError;
resp.instanceID = bg->GetInstanceID();
resp.instanceClientID = bg->GetClientInstanceID();
return resp;
}
BattlegroundErrorCode ToCloud9GrpcHandler::AddPlayersToBattleground(BattlegroundAddPlayersRequest* request)
{
BattlegroundTypeId bgTypeId = BattlegroundTypeId(request->battlegroundTypeID);
Battleground* bg = sBattlegroundMgr->GetBattleground(request->instanceID, BATTLEGROUND_TYPE_NONE);
if (!bg)
return BattlegroundErrorBattlegroundNotFound;
for (int i = 0; i < request->alliancePlayersToAddSize; i++)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(request->alliancePlayersToAdd[i]));
if (player)
{
player->SetEntryPoint();
player->SetBattlegroundId(bg->GetInstanceID(), bg->GetBgTypeID(), 1, true, bgTypeId == BATTLEGROUND_RB, player->GetTeamId(true));
sBattlegroundMgr->SendToBattleground(player, bg->GetInstanceID(), bgTypeId);
}
}
for (int i = 0; i < request->hordePlayersToAddSize; i++)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(request->hordePlayersToAdd[i]));
if (player)
{
player->SetEntryPoint();
player->SetBattlegroundId(bg->GetInstanceID(), bg->GetBgTypeID(), 1, true, bgTypeId == BATTLEGROUND_RB, player->GetTeamId(true));
sBattlegroundMgr->SendToBattleground(player, bg->GetInstanceID(), bgTypeId);
}
}
return BattlegroundErrorCodeNoError;
}
BattlegroundJoinCheckErrorCode ToCloud9GrpcHandler::CanPlayerJoinBattlegroundQueue(uint64 playerGuid)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
return BattlegroundJoinCheckErrorCodePlayerNotFound;
// Lets ignore RBAC checks for now.
Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(BATTLEGROUND_RB);
if (!bg)
return BattlegroundJoinCheckErrorCodeResponseIsFalse;
// has deserter debuff
if (!player->CanJoinToBattleground(bg))
return BattlegroundJoinCheckErrorCodeResponseIsFalse;
// don't let Death Knights join BG queues when they are not allowed to be teleported yet
if (player->IsClass(CLASS_DEATH_KNIGHT, CLASS_CONTEXT_TELEPORT) && player->GetMapId() == 609 && !player->IsGameMaster() && !player->HasSpell(50977))
return BattlegroundJoinCheckErrorCodeResponseIsFalse;
return BattlegroundJoinCheckErrorCodeOK;
}
BattlegroundJoinCheckErrorCode ToCloud9GrpcHandler::CanPlayerTeleportToBattleground(uint64 playerGuid)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(playerGuid));
if (!player)
return BattlegroundJoinCheckErrorCodePlayerNotFound;
if (player->GetCharmGUID() || player->IsInCombat())
return BattlegroundJoinCheckErrorCodeResponseIsFalse;
return BattlegroundJoinCheckErrorCodeOK;
}
@@ -0,0 +1,50 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TC9_GRPC_HANDLER_H
#define _TC9_GRPC_HANDLER_H
#include "Common.h"
#include "libsidecar.h"
class ToCloud9GrpcHandler
{
public:
ToCloud9GrpcHandler() {};
~ToCloud9GrpcHandler() {};
// Items
static GetPlayerItemsByGuidsResponse GetPlayerItemsByGuids(uint64 player, uint64* items, int items_len);
static RemoveItemsWithGuidsFromPlayerResponse RemoveItemsWithGuidsFromPlayer(uint64 player, uint64* items, int itemsLen, uint64 assignToPlayer);
static PlayerItemErrorCode AddExistingItemToPlayer(AddExistingItemToPlayerRequest*);
// Money
static GetMoneyForPlayerResponse GetMoneyForPlayer(uint64 player);
static ModifyMoneyForPlayerResponse ModifyMoneyForPlayer(uint64 player, int32 value);
// Interactions
static CanPlayerInteractWithGOAndTypeResponse CanPlayerInteractWithGOAndType(uint64 player, uint64 go, uint8 goType);
static CanPlayerInteractWithNPCAndFlagsResponse CanPlayerInteractWithNPCAndFlags(uint64 player, uint64 npc, uint32 unitFlags);
// Battlegrounds
static BattlegroundStartResponse StartBattleground(BattlegroundStartRequest* request);
static BattlegroundErrorCode AddPlayersToBattleground(BattlegroundAddPlayersRequest* request);
static BattlegroundJoinCheckErrorCode CanPlayerJoinBattlegroundQueue(uint64 player);
static BattlegroundJoinCheckErrorCode CanPlayerTeleportToBattleground(uint64 player);
};
#endif // _TC9_GRPC_HANDLER_H
@@ -0,0 +1,47 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TC9GuildHooks.h"
#include "ObjectAccessor.h"
#include "Player.h"
void ToCloud9GuildHooks::OnGuildMemberAdded(uint64 guild, uint64 character)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(character));
if (!player)
return;
player->SetInGuild(guild);
}
void ToCloud9GuildHooks::OnGuildMemberRemoved(uint64 /*guild*/, uint64 character)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(character));
if (!player)
return;
player->SetInGuild(0);
}
void ToCloud9GuildHooks::OnGuildMemberLeft(uint64 /*guild*/, uint64 character)
{
Player *player = ObjectAccessor::FindPlayer(ObjectGuid(character));
if (!player)
return;
player->SetInGuild(0);
}
@@ -0,0 +1,34 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TC9_GUILD_HOOKS_H
#define _TC9_GUILD_HOOKS_H
#include "Common.h"
class ToCloud9GuildHooks
{
public:
ToCloud9GuildHooks() {};
~ToCloud9GuildHooks() {};
static void OnGuildMemberAdded(uint64 guild, uint64 character);
static void OnGuildMemberRemoved(uint64 guild, uint64 character);
static void OnGuildMemberLeft(uint64 guild, uint64 character);
};
#endif // _TC9_GUILD_HOOKS_H
+268
View File
@@ -0,0 +1,268 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TC9Sidecar.h"
#include "Config.h"
#include "InstanceSaveMgr.h"
#include "libsidecar.h"
#include "Log.h"
#include "MapMgr.h"
#include "Player.h"
#include "TC9GroupHooks.h"
#include "TC9GrpcHandler.h"
#include "TC9GuildHooks.h"
#include "UpdateTime.h"
#include "WorldSessionMgr.h"
#include <limits>
#define AVAILABLE_MAPS_ALL_MAPS ""
MonitoringDataCollectorResponse HandleMonitoringRequest();
ToCloud9Sidecar* ToCloud9Sidecar::instance()
{
static ToCloud9Sidecar instance;
return &instance;
}
ToCloud9Sidecar::ToCloud9Sidecar() : _clusterModeEnabled(false), _isCrossrealm(false)
{
}
void ToCloud9Sidecar::Init(uint16 port, int realmId)
{
_clusterModeEnabled = sConfigMgr->GetOption<bool>("Cluster.Enabled", false);
if (_clusterModeEnabled)
{
uint32 *assignedMaps;
int assignedMapsSize = 0;
_isCrossrealm = sConfigMgr->GetOption<bool>("Cluster.IsCrossrealm", false);
std::string availableMaps = sConfigMgr->GetOption<std::string>("Cluster.AvailableMaps", AVAILABLE_MAPS_ALL_MAPS);
TC9InitLib(port, realmId, _isCrossrealm, availableMaps.data(), &assignedMaps, &assignedMapsSize);
for (int i = 0; i < MAX_MAP_ID; i++)
_assignedMapsByID[i] = false;
for (int i = 0; i < assignedMapsSize; i++)
{
uint32 mapId = assignedMaps[i];
if (mapId >= MAX_MAP_ID)
{
LOG_ERROR("server", "ToCloud9Sidecar::Init: map id {} out of range [0, {}), ignored",
mapId, MAX_MAP_ID);
continue;
}
_assignedMapsByID[mapId] = true;
}
if (assignedMapsSize > 0)
free(assignedMaps);
SetupHooks();
SetupGrpcHandlers();
}
}
void ToCloud9Sidecar::Deinit()
{
if (_clusterModeEnabled)
TC9GracefulShutdown();
}
void ToCloud9Sidecar::SetupHooks()
{
TC9SetOnMapsReassignedHook(&ToCloud9Sidecar::OnMapsReassigned);
TC9SetOnGuildMemberLeftHook(&ToCloud9GuildHooks::OnGuildMemberLeft);
TC9SetOnGuildMemberAddedHook(&ToCloud9GuildHooks::OnGuildMemberAdded);
TC9SetOnGuildMemberRemovedHook(&ToCloud9GuildHooks::OnGuildMemberRemoved);
TC9SetOnGroupCreatedHook(&ToCloud9GroupHooks::OnGroupCreated);
TC9SetOnGroupDisbandedHook(&ToCloud9GroupHooks::OnGroupDisbanded);
TC9SetOnGroupMemberAddedHook(&ToCloud9GroupHooks::OnGroupMemberAdded);
TC9SetOnGroupMemberRemovedHook(&ToCloud9GroupHooks::OnGroupMemberRemoved);
TC9SetOnGroupLootTypeChangedHook(&ToCloud9GroupHooks::OnGroupLootTypeChanged);
TC9SetOnGroupConvertedToRaidHook(&ToCloud9GroupHooks::OnGroupConvertedToRaid);
TC9SetOnGroupRaidDifficultyChangedHook(&ToCloud9GroupHooks::OnGroupRaidDifficultyChanged);
TC9SetOnGroupDungeonDifficultyChangedHook(&ToCloud9GroupHooks::OnGroupDungeonDifficultyChanged);
}
void ToCloud9Sidecar::SetupGrpcHandlers()
{
TC9SetGetPlayerItemsByGuidsHandler(&ToCloud9GrpcHandler::GetPlayerItemsByGuids);
TC9SetRemoveItemsWithGuidsFromPlayerHandler(&ToCloud9GrpcHandler::RemoveItemsWithGuidsFromPlayer);
TC9SetAddExistingItemToPlayerHandler(&ToCloud9GrpcHandler::AddExistingItemToPlayer);
TC9SetGetMoneyForPlayerHandler(&ToCloud9GrpcHandler::GetMoneyForPlayer);
TC9SetModifyMoneyForPlayerHandler(&ToCloud9GrpcHandler::ModifyMoneyForPlayer);
TC9SetCanPlayerInteractWithGOAndTypeHandler(&ToCloud9GrpcHandler::CanPlayerInteractWithGOAndType);
TC9SetCanPlayerInteractWithNPCAndFlagsHandler(&ToCloud9GrpcHandler::CanPlayerInteractWithNPCAndFlags);
TC9SetBattlegroundStartHandler(&ToCloud9GrpcHandler::StartBattleground);
TC9SetBattlegroundAddPlayersHandler(&ToCloud9GrpcHandler::AddPlayersToBattleground);
TC9SetCanPlayerJoinBattlegroundQueueHandler(&ToCloud9GrpcHandler::CanPlayerJoinBattlegroundQueue);
TC9SetCanPlayerTeleportToBattlegroundHandler(&ToCloud9GrpcHandler::CanPlayerTeleportToBattleground);
TC9SetMonitoringDataCollectorHandler(&HandleMonitoringRequest);
}
void ToCloud9Sidecar::ProcessHooks()
{
TC9ProcessEventsHooks();
}
void ToCloud9Sidecar::ProcessGrpcOrHttpRequests()
{
TC9ProcessGRPCOrHTTPRequests();
}
void ToCloud9Sidecar::ProcessAsyncTasks()
{
_asyncTasksProcessor.ProcessReadyCallbacks();
}
bool ToCloud9Sidecar::IsMapAssigned(uint32 mapId)
{
if (mapId >= MAX_MAP_ID)
return false;
return _assignedMapsByID[mapId];
}
uint32 ToCloud9Sidecar::GenerateCharacterGuid(uint16 realmId)
{
return uint32(TC9GetNextAvailableCharacterGuid(realmId));
}
uint32 ToCloud9Sidecar::GenerateItemGuid(uint16 realmId)
{
return uint32(TC9GetNextAvailableItemGuid(realmId));
}
uint32 ToCloud9Sidecar::GenerateInstanceGuid(uint16 realmId)
{
return uint32(TC9GetNextAvailableInstanceGuid(realmId));
}
void ToCloud9Sidecar::OnPlayerLeftBattleground(uint64 playerGUID, uint32 realmID, uint32 instanceID)
{
TC9PlayerLeftBattleground(playerGUID, realmID, instanceID);
}
void ToCloud9Sidecar::OnBattlegroundStatusChanged(uint32 instanceID, uint8 status)
{
TC9BattlegroundStatusChanged(instanceID, status);
}
bool ToCloud9Sidecar::NatsPublish(std::string const& subject, std::string const& payload)
{
if (!_clusterModeEnabled)
return false;
if (payload.size() > size_t(std::numeric_limits<int>::max()))
return false;
return TC9NatsPublish(subject.c_str(), payload.c_str(), int(payload.size())) == 0;
}
bool ToCloud9Sidecar::NatsSubscribe(std::string const& subject, void (*handler)(char const*, char const*, int))
{
if (!_clusterModeEnabled || !handler)
return false;
return TC9NatsSubscribe(subject.c_str(), handler) == 0;
}
void ToCloud9Sidecar::OnMapsReassigned(uint32* addedMaps, int addedMapsSize, uint32* removedMaps, int removedMapsSize)
{
std::vector<uint32_t> newMapIDs;
newMapIDs.reserve(addedMapsSize > 0 ? addedMapsSize : 0);
for (int i = 0; i < addedMapsSize; i++)
{
uint32 mapId = addedMaps[i];
if (mapId >= MAX_MAP_ID)
{
LOG_ERROR("server", "ToCloud9Sidecar::OnMapsReassigned: added map id {} out of range [0, {}), ignored",
mapId, MAX_MAP_ID);
continue;
}
sToCloud9Sidecar->_assignedMapsByID[mapId] = true;
newMapIDs.push_back(mapId);
if (Map* map = sMapMgr->FindBaseNonInstanceMap(mapId))
map->StopPlayersRedirectKickTimer();
}
for (int i = 0; i < removedMapsSize; i++)
{
uint32 mapId = removedMaps[i];
if (mapId >= MAX_MAP_ID)
{
LOG_ERROR("server", "ToCloud9Sidecar::OnMapsReassigned: removed map id {} out of range [0, {}), ignored",
mapId, MAX_MAP_ID);
continue;
}
sToCloud9Sidecar->_assignedMapsByID[mapId] = false;
if (Map* map = sMapMgr->FindBaseNonInstanceMap(mapId))
map->StartPlayersRedirectKickTimer();
}
if (!newMapIDs.empty())
{
auto loadRowsPtr = std::make_shared<InstanceMapLoadRows>();
AsyncTask<bool> task(
[loadRowsPtr, newMapIDs]() -> bool {
LOG_INFO("server", "Starting to load data for newly assigned maps...");
*loadRowsPtr = sInstanceSaveMgr->LoadInstanceSavesAndBindsForMapIDs(newMapIDs);
return true;
},
[loadRowsPtr, newMapIDs](bool) {
sInstanceSaveMgr->MergeWithNewInstanceSaves(*loadRowsPtr);
TC9ReadyToAcceptPlayersFromMaps((uint32_t*)newMapIDs.data(), newMapIDs.size());
LOG_INFO("server", "Finished loading data for newly assigned maps.");
}
);
task.ExecuteAsync();
sToCloud9Sidecar->_asyncTasksProcessor.AddCallback(std::move(task));
}
}
MonitoringDataCollectorResponse HandleMonitoringRequest()
{
MonitoringDataCollectorResponse res;
res.errorCode = MonitoringErrorCodeNoError;
res.diffMean = sWorldUpdateTime.GetAverageUpdateTime();
res.diffMedian = sWorldUpdateTime.GetPercentile(50);
res.diff95Percentile = sWorldUpdateTime.GetPercentile(95);
res.diff99Percentile = sWorldUpdateTime.GetPercentile(99);
res.diffMaxPercentile = sWorldUpdateTime.GetPercentile(100);
res.connectedPlayers = sWorldSessionMgr->GetActiveSessionCount();
return res;
}
+78
View File
@@ -0,0 +1,78 @@
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TC9_SIDECAR_H
#define _TC9_SIDECAR_H
#include "AsyncCallbackProcessor.h"
#include "AsyncTask.h"
#include "Common.h"
#include "ObjectGuid.h"
#define MAX_MAP_ID 800 // Probably too much, but let's lean towards caution.
class ToCloud9Sidecar
{
private:
ToCloud9Sidecar();
~ToCloud9Sidecar() {};
public:
static ToCloud9Sidecar* instance();
void Init(uint16 port, int realmId);
void Deinit();
bool ClusterModeEnabled() { return _clusterModeEnabled; }
bool IsCrossrealm() { return _isCrossrealm; }
bool IsMapAssigned(uint32 mapId);
void SetupHooks();
void SetupGrpcHandlers();
void ProcessHooks();
void ProcessGrpcOrHttpRequests();
void ProcessAsyncTasks();
uint32 GenerateCharacterGuid(uint16 realmId = DEFAULT_NON_CROSSREALM_REALM_ID);
uint32 GenerateItemGuid(uint16 realmId = DEFAULT_NON_CROSSREALM_REALM_ID);
uint32 GenerateInstanceGuid(uint16 realmId = DEFAULT_NON_CROSSREALM_REALM_ID);
void OnPlayerLeftBattleground(uint64 playerGUID, uint32 realmID, uint32 instanceID);
void OnBattlegroundStatusChanged(uint32 instanceID, uint8 status);
// Generic NATS pub/sub (single choke point for in-process modules).
// No-ops outside cluster mode. Subscribe callbacks run on the world
// thread (ProcessHooks).
bool NatsPublish(std::string const& subject, std::string const& payload);
bool NatsSubscribe(std::string const& subject, void (*handler)(char const* subject, char const* payload, int payloadLen));
private:
static void OnMapsReassigned(uint32* addedMaps, int addedMapsSize, uint32* removedMaps, int removedMapsSize);
bool _clusterModeEnabled;
bool _isCrossrealm;
bool _assignedMapsByID[MAX_MAP_ID];
AsyncCallbackProcessor<AsyncTask<bool>> _asyncTasksProcessor;
};
#define sToCloud9Sidecar ToCloud9Sidecar::instance()
#endif // _TC9_SIDECAR_H
+21 -2
View File
@@ -23,8 +23,8 @@
#include "AccountMgr.h"
#include "AchievementMgr.h"
#include "AddonMgr.h"
#include "ArenaTeamMgr.h"
#include "ArenaSeasonMgr.h"
#include "ArenaTeamMgr.h"
#include "AuctionHouseMgr.h"
#include "AutobroadcastMgr.h"
#include "BattlefieldMgr.h"
@@ -53,8 +53,8 @@
#include "GridNotifiersImpl.h"
#include "GroupMgr.h"
#include "GuildMgr.h"
#include "IPLocation.h"
#include "InstanceSaveMgr.h"
#include "IPLocation.h"
#include "ItemEnchantmentMgr.h"
#include "LFGMgr.h"
#include "Language.h"
@@ -82,6 +82,7 @@
#include "SmartAI.h"
#include "SpellMgr.h"
#include "TaskScheduler.h"
#include "TC9Sidecar.h"
#include "TicketMgr.h"
#include "Transport.h"
#include "TransportMgr.h"
@@ -1341,6 +1342,24 @@ void World::Update(uint32 diff)
sScriptMgr->OnWorldUpdate(diff);
}
if (sToCloud9Sidecar->ClusterModeEnabled())
{
{
METRIC_TIMER("world_update_time", METRIC_TAG("type", "Process TC9 async tasks"));
sToCloud9Sidecar->ProcessAsyncTasks();
}
{
METRIC_TIMER("world_update_time", METRIC_TAG("type", "Process TC9 hooks"));
sToCloud9Sidecar->ProcessHooks();
}
{
METRIC_TIMER("world_update_time", METRIC_TAG("type", "Process TC9 gRPC and HTTP requests"));
sToCloud9Sidecar->ProcessGrpcOrHttpRequests();
}
}
{
METRIC_TIMER("world_update_time", METRIC_TAG("type", "Update metrics"));
// Stats logger update
+21 -13
View File
@@ -22,6 +22,7 @@
#include "MapMgr.h"
#include "Player.h"
#include "SharedDefines.h"
#include "TC9Sidecar.h"
#include "UnitAI.h"
#include "Weather.h"
#include "WorldState.h"
@@ -160,20 +161,27 @@ void WorldState::LoadWorldStates()
// Setting a worldstate will save it to DB
void WorldState::setWorldState(uint32 index, uint64 timeValue)
{
auto const& it = _worldstates.find(index);
if (it != _worldstates.end())
// Crossrealm nodes must not persist worldstates: their CharacterDatabase is
// the routing proxy and the write would land in an arbitrary realm DB. The
// in-memory value still has to be updated so read-modify-write users
// (e.g. the Wintergrasp clock) keep working.
if (!sToCloud9Sidecar->IsCrossrealm())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_WORLDSTATE);
stmt->SetData(0, uint32(timeValue));
stmt->SetData(1, index);
CharacterDatabase.Execute(stmt);
}
else
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_WORLDSTATE);
stmt->SetData(0, index);
stmt->SetData(1, uint32(timeValue));
CharacterDatabase.Execute(stmt);
auto const& it = _worldstates.find(index);
if (it != _worldstates.end())
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_WORLDSTATE);
stmt->SetData(0, uint32(timeValue));
stmt->SetData(1, index);
CharacterDatabase.Execute(stmt);
}
else
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_WORLDSTATE);
stmt->SetData(0, index);
stmt->SetData(1, uint32(timeValue));
CharacterDatabase.Execute(stmt);
}
}
_worldstates[index] = timeValue;
+2 -1
View File
@@ -232,7 +232,8 @@ target_link_libraries(scripts
PRIVATE
acore-core-interface
PUBLIC
game-interface)
game-interface
libsidecar)
target_include_directories(scripts
PUBLIC