diff options
author | Shauren <shauren.trinity@gmail.com> | 2020-01-02 14:19:35 +0100 |
---|---|---|
committer | Shauren <shauren.trinity@gmail.com> | 2022-10-04 00:19:38 +0200 |
commit | 9b924522d0549dd67b10e2cbdfc20297dd21e182 (patch) | |
tree | f0fcdf96902b7c497c1bc65db83621a8dfadf43a /src | |
parent | a131542855d23022714a97640be1c8d68a741c31 (diff) |
Core/Instances: Delete InstanceSaveMgr and replace most of its uses with new InstanceLockMgr
Diffstat (limited to 'src')
33 files changed, 269 insertions, 1929 deletions
diff --git a/src/server/game/DataStores/DB2Structure.h b/src/server/game/DataStores/DB2Structure.h index e200bbba3d8..4e674c03483 100644 --- a/src/server/game/DataStores/DB2Structure.h +++ b/src/server/game/DataStores/DB2Structure.h @@ -2587,6 +2587,7 @@ struct MapDifficultyEntry bool HasResetSchedule() const { return ResetInterval != MAP_DIFFICULTY_RESET_ANYTIME; } bool IsUsingEncounterLocks() const { return (Flags & MAP_DIFFICULTY_FLAG_LOCK_TO_ENCOUNTER) != 0; } + bool IsRestoringDungeonState() const { return (Flags & MAP_DIFFICULTY_FLAG_RESTORE_DUNGEON_STATE) != 0; } bool IsExtendable() const { return (Flags & MAP_DIFFICULTY_FLAG_CANNOT_EXTEND) == 0; } uint32 GetRaidDuration() const diff --git a/src/server/game/DataStores/DBCEnums.h b/src/server/game/DataStores/DBCEnums.h index 64161bb3334..964ced725a8 100644 --- a/src/server/game/DataStores/DBCEnums.h +++ b/src/server/game/DataStores/DBCEnums.h @@ -1020,8 +1020,9 @@ enum MapFlags enum MapDifficultyFlags : uint8 { - MAP_DIFFICULTY_FLAG_LOCK_TO_ENCOUNTER = 0x02, // Lock to single encounters - MAP_DIFFICULTY_FLAG_CANNOT_EXTEND = 0x10 + MAP_DIFFICULTY_FLAG_LOCK_TO_ENCOUNTER = 0x02, // Lock to single encounters + MAP_DIFFICULTY_FLAG_RESTORE_DUNGEON_STATE = 0x08, // Mythic dungeons with this flag zone into leaders instance instead of always using a fresh one (Return to Karazhan, Operation: Mechagon) + MAP_DIFFICULTY_FLAG_CANNOT_EXTEND = 0x10 }; enum MapDifficultyResetInterval : uint8 diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index a586f723edb..69972a4643e 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -23,7 +23,7 @@ #include "GameTime.h" #include "Group.h" #include "GroupMgr.h" -#include "InstanceSaveMgr.h" +#include "InstanceLockMgr.h" #include "LFGGroupData.h" #include "LFGPlayerData.h" #include "LFGQueue.h" @@ -841,17 +841,15 @@ void LFGMgr::GetCompatibleDungeons(LfgDungeonSet* dungeons, GuidSet const& playe LFGDungeonData const* dungeon = GetLFGDungeon(dungeonId); ASSERT(dungeon); ASSERT(player); - if (InstancePlayerBind* playerBind = player->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty))) + MapDb2Entries entries{ dungeon->map, Difficulty(dungeon->difficulty) }; + if (InstanceLock* playerBind = sInstanceLockMgr.FindActiveInstanceLock(guid, entries)) { - if (InstanceSave* playerSave = playerBind->save) - { - uint32 dungeonInstanceId = playerSave->GetInstanceId(); - auto itLockedDungeon = lockedDungeons.find(dungeonId); - if (itLockedDungeon == lockedDungeons.end() || itLockedDungeon->second == dungeonInstanceId) - eraseDungeon = false; - - lockedDungeons[dungeonId] = dungeonInstanceId; - } + uint32 dungeonInstanceId = playerBind->GetInstanceId(); + auto itLockedDungeon = lockedDungeons.find(dungeonId); + if (itLockedDungeon == lockedDungeons.end() || itLockedDungeon->second == dungeonInstanceId) + eraseDungeon = false; + + lockedDungeons[dungeonId] = dungeonInstanceId; } } @@ -1733,7 +1731,7 @@ LfgLockMap LFGMgr::GetLockedDungeons(ObjectGuid guid) return LFG_LOCKSTATUS_NOT_IN_SEASON; if (DisableMgr::IsDisabledFor(DISABLE_TYPE_LFG_MAP, dungeon->map, player)) return LFG_LOCKSTATUS_RAID_LOCKED; - if (dungeon->difficulty > DIFFICULTY_NORMAL && player->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty))) + if (dungeon->difficulty > DIFFICULTY_NORMAL && sInstanceLockMgr.FindActiveInstanceLock(guid, { dungeon->map, Difficulty(dungeon->difficulty) })) return LFG_LOCKSTATUS_RAID_LOCKED; if (Optional<ContentTuningLevels> levels = sDB2Manager.GetContentTuningData(dungeon->contentTuningId, player->m_playerData->CtrOptions->ContentTuningConditionMask)) { diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 6018cdeee61..61efb379d2a 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -68,7 +68,6 @@ #include "GuildMgr.h" #include "InstanceLockMgr.h" #include "InstancePackets.h" -#include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "ItemPackets.h" #include "KillRewarder.h" @@ -393,11 +392,6 @@ void Player::CleanupsBeforeDelete(bool finalCleanup) DuelComplete(DUEL_INTERRUPTED); Unit::CleanupsBeforeDelete(finalCleanup); - - // clean up player-instance binds, may unload some instance saves - for (auto difficultyItr = m_boundInstances.begin(); difficultyItr != m_boundInstances.end(); ++difficultyItr) - for (auto itr = difficultyItr->second.begin(); itr != difficultyItr->second.end(); ++itr) - itr->second.save->RemovePlayer(this); } bool Player::Create(ObjectGuid::LowType guidlow, WorldPackets::Character::CharacterCreateInfo const* createInfo) @@ -17235,7 +17229,6 @@ bool Player::LoadFromDB(ObjectGuid guid, CharacterDatabaseQueryHolder const& hol SetUpdateFieldValue(m_values.ModifyValue(&Player::m_activePlayerData).ModifyValue(&UF::ActivePlayerData::TodayHonorableKills), fields.totalKills); SetUpdateFieldValue(m_values.ModifyValue(&Player::m_activePlayerData).ModifyValue(&UF::ActivePlayerData::YesterdayHonorableKills), fields.yesterdayKills); - _LoadBoundInstances(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES)); _LoadInstanceTimeRestrictions(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES)); _LoadBGData(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_BG_DATA)); @@ -17419,12 +17412,6 @@ bool Player::LoadFromDB(ObjectGuid guid, CharacterDatabaseQueryHolder const& hol GetName().c_str(), GetGUID().ToString().c_str(), mapId); RelocateToHomebind(); } - - // fix crash (because of if (Map* map = _FindMap(instanceId)) in MapInstanced::CreateInstance) - if (instanceId) - if (InstanceSave* save = GetInstanceSave(mapId)) - if (save->GetInstanceId() != instanceId) - instanceId = 0; } // NOW player must have valid map @@ -17466,7 +17453,7 @@ bool Player::LoadFromDB(ObjectGuid guid, CharacterDatabaseQueryHolder const& hol areaTrigger = sObjectMgr->GetGoBackTrigger(mapId); check = true; } - else if (instanceId && !sInstanceSaveMgr->GetInstanceSave(instanceId)) // ... and instance is reseted then look for entrance. + else if (instanceId && !sInstanceLockMgr.FindActiveInstanceLock(guid, { mapId, map->GetDifficultyID() })) // ... and instance is reseted then look for entrance. { areaTrigger = sObjectMgr->GetMapEntranceTrigger(mapId); check = true; @@ -18971,235 +18958,6 @@ void Player::_LoadGroup(PreparedQueryResult result) RemovePlayerFlag(PLAYER_FLAGS_GROUP_LEADER); } -void Player::_LoadBoundInstances(PreparedQueryResult result) -{ - m_boundInstances.clear(); - - Group* group = GetGroup(); - - // 0 1 2 3 4 5 6 - // SELECT id, permanent, map, difficulty, extendState, resettime, entranceId FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = ? - if (result) - { - do - { - Field* fields = result->Fetch(); - - bool perm = fields[1].GetBool(); - uint32 mapId = fields[2].GetUInt16(); - uint32 instanceId = fields[0].GetUInt32(); - uint8 difficulty = fields[3].GetUInt8(); - BindExtensionState extendState = BindExtensionState(fields[4].GetUInt8()); - - time_t resetTime = fields[5].GetInt64(); - // the resettime for normal instances is only saved when the InstanceSave is unloaded - // so the value read from the DB may be wrong here but only if the InstanceSave is loaded - // and in that case it is not used - - uint32 entranceId = fields[6].GetUInt32(); - - bool deleteInstance = false; - - MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); - std::string mapname = mapEntry ? mapEntry->MapName[sWorld->GetDefaultDbcLocale()] : "Unknown"; - - if (!mapEntry || !mapEntry->IsDungeon()) - { - TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: Player '%s' (%s) has bind to not existed or not dungeon map %d (%s)", - GetName().c_str(), GetGUID().ToString().c_str(), mapId, mapname.c_str()); - deleteInstance = true; - } - else if (!sDifficultyStore.HasRecord(difficulty)) - { - TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '%s' (%s) has bind to not existed difficulty %d instance for map %u (%s)", - GetName().c_str(), GetGUID().ToString().c_str(), difficulty, mapId, mapname.c_str()); - deleteInstance = true; - } - else - { - MapDifficultyEntry const* mapDiff = sDB2Manager.GetMapDifficultyData(mapId, Difficulty(difficulty)); - if (!mapDiff) - { - TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '%s' (%s) has bind to not existed difficulty %d instance for map %u (%s)", - GetName().c_str(), GetGUID().ToString().c_str(), difficulty, mapId, mapname.c_str()); - deleteInstance = true; - } - else if (!perm && group) - { - TC_LOG_ERROR("entities.player", "Player::_LoadBoundInstances: player '%s' (%s) is in group %s but has a non-permanent character bind to map %d (%s), %d, %d", - GetName().c_str(), GetGUID().ToString().c_str(), group->GetGUID().ToString().c_str(), mapId, mapname.c_str(), instanceId, difficulty); - deleteInstance = true; - } - } - - if (deleteInstance) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); - - stmt->setUInt64(0, GetGUID().GetCounter()); - stmt->setUInt32(1, instanceId); - - CharacterDatabase.Execute(stmt); - - continue; - } - - // since non permanent binds are always solo bind, they can always be reset - if (InstanceSave* save = sInstanceSaveMgr->AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, entranceId, !perm, true)) - BindToInstance(save, perm, extendState, true); - } - while (result->NextRow()); - } -} - -InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty, bool withExpired) -{ - // some instances only have one difficulty - MapDifficultyEntry const* mapDiff = sDB2Manager.GetDownscaledMapDifficultyData(mapid, difficulty); - if (!mapDiff) - return nullptr; - - auto difficultyItr = m_boundInstances.find(difficulty); - if (difficultyItr == m_boundInstances.end()) - return nullptr; - - auto itr = difficultyItr->second.find(mapid); - if (itr != difficultyItr->second.end()) - if (itr->second.extendState || withExpired) - return &itr->second; - return nullptr; -} - -InstancePlayerBind const* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty) const -{ - // some instances only have one difficulty - MapDifficultyEntry const* mapDiff = sDB2Manager.GetDownscaledMapDifficultyData(mapid, difficulty); - if (!mapDiff) - return nullptr; - - auto difficultyItr = m_boundInstances.find(difficulty); - if (difficultyItr == m_boundInstances.end()) - return nullptr; - - auto itr = difficultyItr->second.find(mapid); - if (itr != difficultyItr->second.end()) - return &itr->second; - - return nullptr; -} - -InstanceSave* Player::GetInstanceSave(uint32 mapid) -{ - MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); - InstancePlayerBind* pBind = GetBoundInstance(mapid, GetDifficultyID(mapEntry)); - InstanceSave* pSave = pBind ? pBind->save : nullptr; - if (!pBind || !pBind->perm) - if (Group* group = GetGroup()) - if (InstanceGroupBind* groupBind = group->GetBoundInstance(GetDifficultyID(mapEntry), mapid)) - pSave = groupBind->save; - - return pSave; -} - -void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload) -{ - auto difficultyItr = m_boundInstances.find(difficulty); - if (difficultyItr != m_boundInstances.end()) - { - auto itr = difficultyItr->second.find(mapid); - if (itr != difficultyItr->second.end()) - UnbindInstance(itr, difficultyItr, unload); - } -} - -void Player::UnbindInstance(BoundInstancesMap::mapped_type::iterator& itr, BoundInstancesMap::iterator& difficultyItr, bool unload) -{ - if (itr != difficultyItr->second.end()) - { - if (!unload) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); - - stmt->setUInt64(0, GetGUID().GetCounter()); - stmt->setUInt32(1, itr->second.save->GetInstanceId()); - - CharacterDatabase.Execute(stmt); - } - - if (itr->second.perm) - GetSession()->SendCalendarRaidLockoutRemoved(itr->second.save); - - itr->second.save->RemovePlayer(this); // save can become invalid - difficultyItr->second.erase(itr++); - } -} - -InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, BindExtensionState extendState, bool load) -{ - if (save) - { - InstancePlayerBind& bind = m_boundInstances[save->GetDifficultyID()][save->GetMapId()]; - if (extendState == EXTEND_STATE_KEEP) // special flag, keep the player's current extend state when updating for new boss down - { - if (save == bind.save) - extendState = bind.extendState; - else - extendState = EXTEND_STATE_NORMAL; - } - if (!load) - { - if (bind.save) - { - // update the save when the group kills a boss - if (permanent != bind.perm || save != bind.save || extendState != bind.extendState) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE); - - stmt->setUInt32(0, save->GetInstanceId()); - stmt->setBool(1, permanent); - stmt->setUInt8(2, extendState); - stmt->setUInt64(3, GetGUID().GetCounter()); - stmt->setUInt32(4, bind.save->GetInstanceId()); - - CharacterDatabase.Execute(stmt); - } - } - else - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE); - - stmt->setUInt64(0, GetGUID().GetCounter()); - stmt->setUInt32(1, save->GetInstanceId()); - stmt->setBool(2, permanent); - stmt->setUInt8(3, extendState); - - CharacterDatabase.Execute(stmt); - } - } - - if (bind.save != save) - { - if (bind.save) - bind.save->RemovePlayer(this); - save->AddPlayer(this); - } - - if (permanent) - save->SetCanReset(false); - - bind.save = save; - bind.perm = permanent; - bind.extendState = extendState; - if (!load) - TC_LOG_DEBUG("maps", "Player::BindToInstance: Player '%s' (%s) is now bound to map (ID: %d, Instance: %d, Difficulty: %d)", - GetName().c_str(), GetGUID().ToString().c_str(), save->GetMapId(), save->GetInstanceId(), static_cast<uint32>(save->GetDifficultyID())); - sScriptMgr->OnPlayerBindToInstance(this, save->GetDifficultyID(), save->GetMapId(), permanent, uint8(extendState)); - return &bind; - } - - return nullptr; -} - void Player::ConfirmPendingBind() { InstanceMap* map = GetMap()->ToInstanceMap(); @@ -19233,7 +18991,7 @@ void Player::SendRaidInfo() lockInfos.InstanceID = instanceLock->GetInstanceId(); lockInfos.MapID = instanceLock->GetMapId(); lockInfos.DifficultyID = instanceLock->GetDifficultyId(); - lockInfos.TimeRemaining = int32(std::chrono::duration_cast<Seconds>(instanceLock->GetEffectiveExpiryTime() - now).count()); + lockInfos.TimeRemaining = int32(std::max(std::chrono::duration_cast<Seconds>(instanceLock->GetEffectiveExpiryTime() - now).count(), SI64LIT(0))); lockInfos.CompletedMask = instanceLock->GetData()->CompletedEncountersMask; lockInfos.Locked = !instanceLock->IsExpired(); @@ -20831,63 +20589,8 @@ void Player::SendResetFailedNotify(uint32 /*mapid*/) const } /// Reset all solo instances and optionally send a message on success for each -void Player::ResetInstances(uint8 method, bool isRaid, bool isLegacy) +void Player::ResetInstances(InstanceResetMethod /*method*/, bool /*isRaid*/, bool /*isLegacy*/) { - // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN - - // we assume that when the difficulty changes, all instances that can be reset will be - Difficulty diff = GetDungeonDifficultyID(); - if (isRaid) - { - if (!isLegacy) - diff = GetRaidDifficultyID(); - else - diff = GetLegacyRaidDifficultyID(); - } - - auto difficultyItr = m_boundInstances.find(diff); - if (difficultyItr == m_boundInstances.end()) - return; - - for (auto itr = difficultyItr->second.begin(); itr != difficultyItr->second.end();) - { - InstanceSave* p = itr->second.save; - MapEntry const* entry = sMapStore.LookupEntry(itr->first); - if (!entry || entry->IsRaid() != isRaid || !p->CanReset()) - { - ++itr; - continue; - } - - if (method == INSTANCE_RESET_ALL) - { - // the "reset all instances" method can only reset normal maps - if (entry->IsRaid() || diff == DIFFICULTY_HEROIC) - { - ++itr; - continue; - } - } - - // if the map is loaded, reset it - Map* map = sMapMgr->FindMap(p->GetMapId(), p->GetInstanceId()); - if (map && map->IsDungeon()) - if (!map->ToInstanceMap()->Reset(method)) - { - ++itr; - continue; - } - - // since this is a solo instance there should not be any players inside - if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY) - SendResetInstanceSuccess(p->GetMapId()); - - p->DeleteFromDB(); - difficultyItr->second.erase(itr++); - - // the following should remove the instance save from the manager and delete it as well - p->RemovePlayer(this); - } } void Player::SendResetInstanceSuccess(uint32 MapId) const @@ -23818,33 +23521,6 @@ void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 SendDirectMessage(transferAborted.Write()); } -void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const -{ - // type of warning, based on the time remaining until reset - uint32 type; - if (welcome) - type = RAID_INSTANCE_WELCOME; - else if (time > 21600) - type = RAID_INSTANCE_WELCOME; - else if (time > 3600) - type = RAID_INSTANCE_WARNING_HOURS; - else if (time > 300) - type = RAID_INSTANCE_WARNING_MIN; - else - type = RAID_INSTANCE_WARNING_MIN_SOON; - - WorldPackets::Instance::RaidInstanceMessage raidInstanceMessage; - raidInstanceMessage.Type = type; - raidInstanceMessage.MapID = mapid; - raidInstanceMessage.DifficultyID = difficulty; - if (InstancePlayerBind const* bind = GetBoundInstance(mapid, difficulty)) - raidInstanceMessage.Locked = bind->perm; - else - raidInstanceMessage.Locked = false; - raidInstanceMessage.Extended = false; - SendDirectMessage(raidInstanceMessage.Write()); -} - void Player::ApplyEquipCooldown(Item* pItem) { if (pItem->GetTemplate()->HasFlag(ITEM_FLAG_NO_EQUIP_COOLDOWN)) diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 6837371869d..64f12463459 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -794,8 +794,6 @@ enum ArenaTeamInfoType ARENA_TEAM_END = 7 }; -class InstanceSave; - enum TeleportToOptions { TELE_TO_GM_MODE = 0x01, @@ -834,7 +832,6 @@ enum PlayerLoginQueryIndex PLAYER_LOGIN_QUERY_LOAD_FROM, PLAYER_LOGIN_QUERY_LOAD_CUSTOMIZATIONS, PLAYER_LOGIN_QUERY_LOAD_GROUP, - PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES, PLAYER_LOGIN_QUERY_LOAD_AURAS, PLAYER_LOGIN_QUERY_LOAD_AURA_EFFECTS, PLAYER_LOGIN_QUERY_LOAD_AURA_STORED_LOCATIONS, @@ -912,29 +909,6 @@ enum PlayerDelayedOperations // Maximum money amount : 2^31 - 1 TC_GAME_API extern uint64 const MAX_MONEY_AMOUNT; -enum BindExtensionState -{ - EXTEND_STATE_EXPIRED = 0, - EXTEND_STATE_NORMAL = 1, - EXTEND_STATE_EXTENDED = 2, - EXTEND_STATE_KEEP = 255 // special state: keep current save type -}; -struct InstancePlayerBind -{ - InstanceSave* save; - /* permanent PlayerInstanceBinds are created in Raid/Heroic instances for players - that aren't already permanently bound when they are inside when a boss is killed - or when they enter an instance that the group leader is permanently bound to. */ - bool perm; - /* extend state listing: - EXPIRED - doesn't affect anything unless manually re-extended by player - NORMAL - standard state - EXTENDED - won't be promoted to EXPIRED at next reset period, will instead be promoted to NORMAL */ - BindExtensionState extendState; - - InstancePlayerBind() : save(nullptr), perm(false), extendState(EXTEND_STATE_NORMAL) { } -}; - enum CharDeleteMethod { CHAR_DELETE_REMOVE = 0, // Completely remove from the database @@ -1160,7 +1134,6 @@ class TC_GAME_API Player : public Unit, public GridObject<Player> void SendInitialPacketsAfterAddToMap(); void SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const; void SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg = 0, int32 mapDifficultyXConditionID = 0) const; - void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const; bool CanInteractWithQuestGiver(Object* questGiver) const; Creature* GetNPCIfCanInteractWith(ObjectGuid const& guid, NPCFlags npcFlags, NPCFlags2 npcFlags2) const; @@ -2112,7 +2085,7 @@ class TC_GAME_API Player : public Unit, public GridObject<Player> void SendDungeonDifficulty(int32 forcedDifficulty = -1) const; void SendRaidDifficulty(bool legacy, int32 forcedDifficulty = -1) const; - void ResetInstances(uint8 method, bool isRaid, bool isLegacy); + void ResetInstances(InstanceResetMethod method, bool isRaid, bool isLegacy); void SendResetInstanceSuccess(uint32 MapId) const; void SendResetInstanceFailed(ResetFailedReason reason, uint32 mapID) const; void SendResetFailedNotify(uint32 mapid) const; @@ -2532,8 +2505,6 @@ class TC_GAME_API Player : public Unit, public GridObject<Player> /*** INSTANCE SYSTEM ***/ /*********************************************************/ - typedef std::unordered_map<Difficulty, std::unordered_map<uint32 /*mapId*/, InstancePlayerBind>> BoundInstancesMap; - void UpdateHomebindTime(uint32 time); uint32 m_HomebindTimer; @@ -2550,15 +2521,7 @@ class TC_GAME_API Player : public Unit, public GridObject<Player> m_recentInstances[mapId] = instanceId; } - BoundInstancesMap m_boundInstances; std::unordered_map<uint32 /*mapId*/, uint32 /*instanceId*/> m_recentInstances; - InstancePlayerBind* GetBoundInstance(uint32 mapid, Difficulty difficulty, bool withExpired = false); - InstancePlayerBind const* GetBoundInstance(uint32 mapid, Difficulty difficulty) const; - BoundInstancesMap::iterator GetBoundInstances(Difficulty difficulty) { return m_boundInstances.find(difficulty); } - InstanceSave* GetInstanceSave(uint32 mapid); - void UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload = false); - void UnbindInstance(BoundInstancesMap::mapped_type::iterator& itr, BoundInstancesMap::iterator& difficultyItr, bool unload = false); - InstancePlayerBind* BindToInstance(InstanceSave* save, bool permanent, BindExtensionState extendState = EXTEND_STATE_NORMAL, bool load = false); void ConfirmPendingBind(); void SetPendingBind(uint32 instanceId, uint32 bindTimer); bool HasPendingBind() const { return _pendingBindId > 0; } @@ -2889,7 +2852,6 @@ class TC_GAME_API Player : public Unit, public GridObject<Player> void _LoadActions(PreparedQueryResult result); void _LoadAuras(PreparedQueryResult auraResult, PreparedQueryResult effectResult, uint32 timediff); void _LoadGlyphAuras(); - void _LoadBoundInstances(PreparedQueryResult result); void _LoadInventory(PreparedQueryResult result, PreparedQueryResult artifactsResult, PreparedQueryResult azeriteResult, PreparedQueryResult azeriteItemMilestonePowersResult, PreparedQueryResult azeriteItemUnlockedEssencesResult, PreparedQueryResult azeriteEmpoweredItemResult, uint32 timeDiff); diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index ff04ffcde5a..6dda8e06e02 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -42,7 +42,6 @@ #include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" -#include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "Item.h" #include "Log.h" diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index f8929654908..c799212b059 100644 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -24,7 +24,6 @@ #include "Formulas.h" #include "GameObject.h" #include "GroupMgr.h" -#include "InstanceSaveMgr.h" #include "Item.h" #include "LFGMgr.h" #include "Log.h" @@ -67,11 +66,6 @@ Group::~Group() TC_LOG_ERROR("misc", "Group::~Group: battleground group is not linked to the correct battleground."); } - // this may unload some instance saves - for (auto difficultyItr = m_boundInstances.begin(); difficultyItr != m_boundInstances.end(); ++difficultyItr) - for (auto itr2 = difficultyItr->second.begin(); itr2 != difficultyItr->second.end(); ++itr2) - itr2->second.save->RemoveGroup(this); - // Sub group counters clean up delete[] m_subGroupsCounts; } @@ -694,28 +688,6 @@ void Group::ChangeLeader(ObjectGuid newLeaderGuid, int8 partyIndex) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - // Remove the groups permanent instance bindings - for (auto difficultyItr = m_boundInstances.begin(); difficultyItr != m_boundInstances.end(); ++difficultyItr) - { - for (auto itr = difficultyItr->second.begin(); itr != difficultyItr->second.end();) - { - // Do not unbind saves of instances that already had map created (a newLeader entered) - // forcing a new instance with another leader requires group disbanding (confirmed on retail) - if (itr->second.perm && !sMapMgr->FindMap(itr->first, itr->second.save->GetInstanceId())) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_PERM_BINDING); - stmt->setUInt32(0, m_dbStoreId); - stmt->setUInt32(1, itr->second.save->GetInstanceId()); - trans->Append(stmt); - - itr->second.save->RemoveGroup(this); - difficultyItr->second.erase(itr++); - } - else - ++itr; - } - } - // Update the group leader CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_LEADER); @@ -1387,174 +1359,8 @@ Difficulty Group::GetDifficultyID(MapEntry const* mapEntry) const return m_raidDifficulty; } -void Group::ResetInstances(uint8 method, bool isRaid, bool isLegacy, Player* SendMsgTo) -{ - if (isBGGroup() || isBFGroup()) - return; - - // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_DISBAND - - // we assume that when the difficulty changes, all instances that can be reset will be - Difficulty diff = GetDungeonDifficultyID(); - if (isRaid) - { - if (!isLegacy) - diff = GetRaidDifficultyID(); - else - diff = GetLegacyRaidDifficultyID(); - } - - auto difficultyItr = m_boundInstances.find(diff); - if (difficultyItr == m_boundInstances.end()) - return; - - for (auto itr = difficultyItr->second.begin(); itr != difficultyItr->second.end();) - { - InstanceSave* instanceSave = itr->second.save; - MapEntry const* entry = sMapStore.LookupEntry(itr->first); - if (!entry || entry->IsRaid() != isRaid || (!instanceSave->CanReset() && method != INSTANCE_RESET_GROUP_DISBAND)) - { - ++itr; - continue; - } - - if (method == INSTANCE_RESET_ALL) - { - // the "reset all instances" method can only reset normal maps - if (entry->IsRaid() || diff == DIFFICULTY_HEROIC) - { - ++itr; - continue; - } - } - - bool isEmpty = true; - // if the map is loaded, reset it - Map* map = sMapMgr->FindMap(instanceSave->GetMapId(), instanceSave->GetInstanceId()); - if (map && map->IsDungeon() && !(method == INSTANCE_RESET_GROUP_DISBAND && !instanceSave->CanReset())) - { - if (instanceSave->CanReset()) - isEmpty = ((InstanceMap*)map)->Reset(method); - else - isEmpty = !map->HavePlayers(); - } - - if (SendMsgTo) - { - if (!isEmpty) - SendMsgTo->SendResetInstanceFailed(INSTANCE_RESET_FAILED, instanceSave->GetMapId()); - else if (sWorld->getBoolConfig(CONFIG_INSTANCES_RESET_ANNOUNCE)) - { - if (Group* group = SendMsgTo->GetGroup()) - { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) - if (Player* player = groupRef->GetSource()) - player->SendResetInstanceSuccess(instanceSave->GetMapId()); - } - - else - SendMsgTo->SendResetInstanceSuccess(instanceSave->GetMapId()); - } - else - SendMsgTo->SendResetInstanceSuccess(instanceSave->GetMapId()); - } - - if (isEmpty || method == INSTANCE_RESET_GROUP_DISBAND || method == INSTANCE_RESET_CHANGE_DIFFICULTY) - { - // do not reset the instance, just unbind if others are permanently bound to it - if (isEmpty && instanceSave->CanReset()) - { - if (map && map->IsDungeon() && SendMsgTo) - { - AreaTriggerStruct const* instanceEntrance = sObjectMgr->GetGoBackTrigger(map->GetId()); - - if (!instanceEntrance) - TC_LOG_DEBUG("root", "Instance entrance not found for maps %u", map->GetId()); - else - { - WorldSafeLocsEntry const* graveyardLocation = sObjectMgr->GetClosestGraveyard( - WorldLocation(instanceEntrance->target_mapId, instanceEntrance->target_X, instanceEntrance->target_Y, instanceEntrance->target_Z), - SendMsgTo->GetTeam(), nullptr); - uint32 const zoneId = sTerrainMgr.GetZoneId(PhasingHandler::GetEmptyPhaseShift(), graveyardLocation->Loc.GetMapId(), - graveyardLocation->Loc.GetPositionX(), graveyardLocation->Loc.GetPositionY(), graveyardLocation->Loc.GetPositionZ()); - - for (MemberSlot const& member : GetMemberSlots()) - { - if (!ObjectAccessor::FindConnectedPlayer(member.guid)) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION_BY_MAPID); - - stmt->setFloat(0, graveyardLocation->Loc.GetPositionX()); - stmt->setFloat(1, graveyardLocation->Loc.GetPositionY()); - stmt->setFloat(2, graveyardLocation->Loc.GetPositionZ()); - stmt->setFloat(3, instanceEntrance->target_Orientation); - stmt->setUInt32(4, graveyardLocation->Loc.GetMapId()); - stmt->setUInt32(5, zoneId); - stmt->setUInt64(6, member.guid.GetCounter()); - stmt->setUInt32(7, map->GetId()); - - CharacterDatabase.Execute(stmt); - } - } - } - } - - instanceSave->DeleteFromDB(); - } - else - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_BY_INSTANCE); - - stmt->setUInt32(0, instanceSave->GetInstanceId()); - - CharacterDatabase.Execute(stmt); - } - - itr = difficultyItr->second.erase(itr); - // this unloads the instance save unless online players are bound to it - // (eg. permanent binds or GM solo binds) - instanceSave->RemoveGroup(this); - } - else - ++itr; - } -} - -InstanceGroupBind* Group::GetBoundInstance(Player* player) -{ - uint32 mapid = player->GetMapId(); - MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); - return GetBoundInstance(mapEntry); -} - -InstanceGroupBind* Group::GetBoundInstance(Map* aMap) -{ - return GetBoundInstance(aMap->GetEntry()); -} - -InstanceGroupBind* Group::GetBoundInstance(MapEntry const* mapEntry) +void Group::ResetInstances(InstanceResetMethod /*method*/, bool /*isRaid*/, bool /*isLegacy*/, Player* /*SendMsgTo*/) { - if (!mapEntry || !mapEntry->IsDungeon()) - return nullptr; - - Difficulty difficulty = GetDifficultyID(mapEntry); - return GetBoundInstance(difficulty, mapEntry->ID); -} - -InstanceGroupBind* Group::GetBoundInstance(Difficulty difficulty, uint32 mapId) -{ - // some instances only have one difficulty - sDB2Manager.GetDownscaledMapDifficultyData(mapId, difficulty); - - auto difficultyItr = m_boundInstances.find(difficulty); - if (difficultyItr == m_boundInstances.end()) - return nullptr; - - auto itr = difficultyItr->second.find(mapId); - if (itr != difficultyItr->second.end()) - return &itr->second; - else - return nullptr; } void Group::LinkOwnedInstance(GroupInstanceReference* ref) @@ -1562,30 +1368,6 @@ void Group::LinkOwnedInstance(GroupInstanceReference* ref) m_ownedInstancesMgr.insertLast(ref); } -void Group::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload) -{ - auto difficultyItr = m_boundInstances.find(Difficulty(difficulty)); - if (difficultyItr == m_boundInstances.end()) - return; - - auto itr = difficultyItr->second.find(mapid); - if (itr != difficultyItr->second.end()) - { - if (!unload) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_BY_GUID); - - stmt->setUInt32(0, m_dbStoreId); - stmt->setUInt32(1, itr->second.save->GetInstanceId()); - - CharacterDatabase.Execute(stmt); - } - - itr->second.save->RemoveGroup(this); // save can become invalid - difficultyItr->second.erase(itr); - } -} - void Group::_homebindIfInstance(Player* player) { if (player && !player->IsGameMaster() && sMapStore.LookupEntry(player->GetMapId())->IsDungeon()) @@ -1983,16 +1765,6 @@ void Group::DelinkMember(ObjectGuid guid) } } -Group::BoundInstancesMap::iterator Group::GetBoundInstances(Difficulty difficulty) -{ - return m_boundInstances.find(difficulty); -} - -Group::BoundInstancesMap::iterator Group::GetBoundInstanceEnd() -{ - return m_boundInstances.end(); -} - void Group::_initRaidSubGroupsCounter() { // Sub group counters initialization diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index 7860a81fd5c..58b27fb459b 100644 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -31,7 +31,6 @@ class Battlefield; class Battleground; class Creature; -class InstanceSave; class Map; class Player; class Unit; @@ -155,15 +154,6 @@ enum GroupUpdatePetFlags GROUP_UPDATE_FLAG_PET_CUR_HP | GROUP_UPDATE_FLAG_PET_MAX_HP | GROUP_UPDATE_FLAG_PET_AURAS // all pet flags }; -struct InstanceGroupBind -{ - InstanceSave* save; - bool perm; - /* permanent InstanceGroupBinds exist if the leader has a permanent - PlayerInstanceBind for the same instance. */ - InstanceGroupBind() : save(nullptr), perm(false) { } -}; - struct RaidMarker { WorldLocation Location; @@ -195,7 +185,6 @@ class TC_GAME_API Group typedef std::list<MemberSlot> MemberSlotList; typedef MemberSlotList::const_iterator member_citerator; - typedef std::unordered_map<Difficulty, std::unordered_map<uint32 /*mapId*/, InstanceGroupBind>> BoundInstancesMap; protected: typedef MemberSlotList::iterator member_witerator; typedef std::set<Player*> InvitesList; @@ -315,7 +304,7 @@ class TC_GAME_API Group Difficulty GetDungeonDifficultyID() const { return m_dungeonDifficulty; } Difficulty GetRaidDifficultyID() const { return m_raidDifficulty; } Difficulty GetLegacyRaidDifficultyID() const { return m_legacyRaidDifficulty; } - void ResetInstances(uint8 method, bool isRaid, bool isLegacy, Player* SendMsgTo); + void ResetInstances(InstanceResetMethod method, bool isRaid, bool isLegacy, Player* SendMsgTo); // -no description- //void SendInit(WorldSession* session); @@ -345,8 +334,6 @@ class TC_GAME_API Group void LinkMember(GroupReference* pRef); void DelinkMember(ObjectGuid guid); - uint32 GetInstanceId(MapEntry const* mapEntry) const { return 0; } - InstanceGroupBind* BindToInstance(InstanceSave* save, bool permanent, bool load = false); ObjectGuid GetRecentInstanceOwner(uint32 mapId) const { auto itr = m_recentInstances.find(mapId); @@ -366,14 +353,6 @@ class TC_GAME_API Group void LinkOwnedInstance(GroupInstanceReference* ref); - void UnbindInstance(uint32 mapid, uint8 difficulty, bool unload = false); - InstanceGroupBind* GetBoundInstance(Player* player); - InstanceGroupBind* GetBoundInstance(Map* aMap); - InstanceGroupBind* GetBoundInstance(MapEntry const* mapEntry); - InstanceGroupBind* GetBoundInstance(Difficulty difficulty, uint32 mapId); - BoundInstancesMap::iterator GetBoundInstances(Difficulty difficulty); - BoundInstancesMap::iterator GetBoundInstanceEnd(); - void StartLeaderOfflineTimer(); void StopLeaderOfflineTimer(); void SelectNewPartyOrRaidLeader(); @@ -410,7 +389,6 @@ class TC_GAME_API Group ItemQualities m_lootThreshold; ObjectGuid m_looterGuid; ObjectGuid m_masterLooterGuid; - BoundInstancesMap m_boundInstances; std::unordered_map<uint32 /*mapId*/, std::pair<ObjectGuid /*instanceOwner*/, uint32 /*instanceId*/>> m_recentInstances; GroupInstanceRefManager m_ownedInstancesMgr; uint8* m_subGroupsCounts; diff --git a/src/server/game/Groups/GroupMgr.cpp b/src/server/game/Groups/GroupMgr.cpp index c8ed49365ad..69fbe8e4d21 100644 --- a/src/server/game/Groups/GroupMgr.cpp +++ b/src/server/game/Groups/GroupMgr.cpp @@ -18,9 +18,7 @@ #include "GroupMgr.h" #include "Common.h" #include "DatabaseEnv.h" -#include "DB2Stores.h" #include "Group.h" -#include "InstanceSaveMgr.h" #include "Log.h" #include "World.h" @@ -205,49 +203,4 @@ void GroupMgr::LoadGroups() TC_LOG_INFO("server.loading", ">> Loaded %u group members in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } - - TC_LOG_INFO("server.loading", "Loading Group instance saves..."); - { - uint32 oldMSTime = getMSTime(); - - // 0 1 2 3 4 5 6 - QueryResult result = CharacterDatabase.Query("SELECT gi.guid, i.map, gi.instance, gi.permanent, i.difficulty, i.resettime, i.entranceId, " - // 7 - "(SELECT COUNT(1) FROM character_instance ci LEFT JOIN `groups` g ON ci.guid = g.leaderGuid WHERE ci.instance = gi.instance AND ci.permanent = 1 LIMIT 1) " - "FROM group_instance gi LEFT JOIN instance i ON gi.instance = i.id ORDER BY guid"); - - if (!result) - { - TC_LOG_INFO("server.loading", ">> Loaded 0 group-instance saves. DB table `group_instance` is empty!"); - return; - } - - uint32 count = 0; - do - { - Field* fields = result->Fetch(); - Group* group = GetGroupByDbStoreId(fields[0].GetUInt32()); - // group will never be NULL (we have run consistency sql's before loading) - ASSERT(group); - - MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt16()); - if (!mapEntry || !mapEntry->IsDungeon()) - { - TC_LOG_ERROR("sql.sql", "Incorrect entry in group_instance table : no dungeon map %d", fields[1].GetUInt16()); - continue; - } - - uint32 diff = fields[4].GetUInt8(); - DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(diff); - if (!difficultyEntry || difficultyEntry->InstanceType != mapEntry->InstanceType) - continue; - - InstanceSave* save = sInstanceSaveMgr->AddInstanceSave(mapEntry->ID, fields[2].GetUInt32(), Difficulty(diff), fields[5].GetInt64(), fields[6].GetUInt32(), fields[7].GetUInt64() == 0, true); - group->BindToInstance(save, fields[3].GetBool(), true); - ++count; - } - while (result->NextRow()); - - TC_LOG_INFO("server.loading", ">> Loaded %u group-instance saves in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); - } } diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index f7ec9de1d99..f4831d15b29 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -22,7 +22,7 @@ SMSG_CALENDAR_EVENT_INVITE_NOTES [ ObjectGuid(InviteGuid), bool(ClearPend ?CMSG_CALENDAR_EVENT_INVITE_NOTES [ ObjectGuid(Guid), uint64(EventID), uint64(InviteID), uint64(ModeratorID), std::string(Notes) ] SMSG_CALENDAR_EVENT_INVITE_NOTES_ALERT [ uint64(EventID), std::string(Notes) ] SMSG_CALENDAR_EVENT_INVITE_STATUS_ALERT [ uint64(EventID), uint32(Date), uint32(Flags), uint8(Status) ] -SMSG_CALENDAR_RAID_LOCKOUT_UPDATED SendCalendarRaidLockoutUpdated(InstanceSave const* save) +SMSG_CALENDAR_RAID_LOCKOUT_UPDATED SendCalendarRaidLockoutUpdated(InstanceLock const* save) @todo @@ -44,7 +44,6 @@ Copied events should probably have a new owner #include "Guild.h" #include "GuildMgr.h" #include "InstanceLockMgr.h" -#include "InstanceSaveMgr.h" #include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" @@ -98,7 +97,7 @@ void WorldSession::HandleCalendarGetCalendar(WorldPackets::Calendar::CalendarGet lockoutInfo.MapID = lock->GetMapId(); lockoutInfo.DifficultyID = lock->GetDifficultyId(); - lockoutInfo.ExpireTime = int32(std::chrono::duration_cast<Seconds>(lock->GetEffectiveExpiryTime() - GameTime::GetSystemTime()).count()); + lockoutInfo.ExpireTime = int32(std::max(std::chrono::duration_cast<Seconds>(lock->GetEffectiveExpiryTime() - GameTime::GetSystemTime()).count(), SI64LIT(0))); lockoutInfo.InstanceID = lock->GetInstanceId(); packet.RaidLockouts.push_back(lockoutInfo); @@ -550,20 +549,23 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPackets::Calendar::SetSaved { TC_LOG_DEBUG("network", "CMSG_SET_SAVED_INSTANCE_EXTEND - MapId: %u, Difficulty: %u, ToggleExtend: %s", setSavedInstanceExtend.MapID, setSavedInstanceExtend.DifficultyID, setSavedInstanceExtend.Extend ? "On" : "Off"); - if (Player* player = GetPlayer()) - { - InstancePlayerBind* instanceBind = player->GetBoundInstance(setSavedInstanceExtend.MapID, Difficulty(setSavedInstanceExtend.DifficultyID), setSavedInstanceExtend.Extend); // include expired instances if we are toggling extend on - if (!instanceBind || !instanceBind->save || !instanceBind->perm) - return; + // cannot modify locks currently in use + if (_player->GetMapId() == uint32(setSavedInstanceExtend.MapID)) + return; - BindExtensionState newState; - if (!setSavedInstanceExtend.Extend || instanceBind->extendState == EXTEND_STATE_EXPIRED) - newState = EXTEND_STATE_NORMAL; - else - newState = EXTEND_STATE_EXTENDED; + std::pair<InstanceResetTimePoint, InstanceResetTimePoint> expiryTimes = sInstanceLockMgr.UpdateInstanceLockExtensionForPlayer(_player->GetGUID(), + { uint32(setSavedInstanceExtend.MapID), Difficulty(setSavedInstanceExtend.DifficultyID) }, setSavedInstanceExtend.Extend); - player->BindToInstance(instanceBind->save, true, newState, false); - } + if (expiryTimes.first == InstanceResetTimePoint::min()) + return; + + WorldPackets::Calendar::CalendarRaidLockoutUpdated calendarRaidLockoutUpdated; + calendarRaidLockoutUpdated.ServerTime = GameTime::GetGameTime(); + calendarRaidLockoutUpdated.MapID = setSavedInstanceExtend.MapID; + calendarRaidLockoutUpdated.DifficultyID = setSavedInstanceExtend.DifficultyID; + calendarRaidLockoutUpdated.OldTimeRemaining = std::max(std::chrono::duration_cast<Seconds>(expiryTimes.first - GameTime::GetSystemTime()).count(), SI64LIT(0)); + calendarRaidLockoutUpdated.NewTimeRemaining = std::max(std::chrono::duration_cast<Seconds>(expiryTimes.second - GameTime::GetSystemTime()).count(), SI64LIT(0)); + SendPacket(calendarRaidLockoutUpdated.Write()); } // ----------------------------------- SEND ------------------------------------ @@ -575,39 +577,10 @@ void WorldSession::SendCalendarRaidLockoutAdded(InstanceLock const* lock) calendarRaidLockoutAdded.ServerTime = uint32(GameTime::GetGameTime()); calendarRaidLockoutAdded.MapID = int32(lock->GetMapId()); calendarRaidLockoutAdded.DifficultyID = lock->GetDifficultyId(); - calendarRaidLockoutAdded.TimeRemaining = int32(std::chrono::duration_cast<Seconds>(lock->GetExpiryTime() - GameTime::GetSystemTime()).count()); + calendarRaidLockoutAdded.TimeRemaining = int32(std::chrono::duration_cast<Seconds>(lock->GetEffectiveExpiryTime() - GameTime::GetSystemTime()).count()); SendPacket(calendarRaidLockoutAdded.Write()); } -void WorldSession::SendCalendarRaidLockoutUpdated(InstanceSave const* save) -{ - if (!save) - return; - - ObjectGuid guid = _player->GetGUID(); - TC_LOG_DEBUG("network", "SMSG_CALENDAR_RAID_LOCKOUT_UPDATED [%s] Map: %u, Difficulty %u", - guid.ToString().c_str(), save->GetMapId(), static_cast<uint32>(save->GetDifficultyID())); - - time_t currTime = GameTime::GetGameTime(); - - WorldPackets::Calendar::CalendarRaidLockoutUpdated packet; - packet.DifficultyID = save->GetDifficultyID(); - packet.MapID = save->GetMapId(); - packet.NewTimeRemaining = 0; // FIXME - packet.OldTimeRemaining = save->GetResetTime() - currTime; - - SendPacket(packet.Write()); -} - -void WorldSession::SendCalendarRaidLockoutRemoved(InstanceSave const* save) -{ - WorldPackets::Calendar::CalendarRaidLockoutRemoved calendarRaidLockoutRemoved; - calendarRaidLockoutRemoved.InstanceID = save->GetInstanceId(); - calendarRaidLockoutRemoved.MapID = int32(save->GetMapId()); - calendarRaidLockoutRemoved.DifficultyID = save->GetDifficultyID(); - SendPacket(calendarRaidLockoutRemoved.Write()); -} - void WorldSession::SendCalendarRaidLockoutRemoved(InstanceLock const* lock) { WorldPackets::Calendar::CalendarRaidLockoutRemoved calendarRaidLockoutRemoved; diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index b1810319895..993d47cabc9 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -96,10 +96,6 @@ bool LoginQueryHolder::Initialize() stmt->setUInt64(0, lowGuid); res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GROUP, stmt); - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INSTANCE); - stmt->setUInt64(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES, stmt); - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AURAS); stmt->setUInt64(0, lowGuid); res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_AURAS, stmt); diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index fa65c980f93..1bcf20acb93 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -35,8 +35,8 @@ #include "Group.h" #include "Guild.h" #include "GuildMgr.h" +#include "InstanceLockMgr.h" #include "InstancePackets.h" -#include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "Language.h" #include "Log.h" @@ -644,18 +644,25 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPackets::AreaTrigger::AreaTrigge if (!teleported) { WorldSafeLocsEntry const* entranceLocation = nullptr; - InstanceSave* instanceSave = player->GetInstanceSave(at->target_mapId); - if (instanceSave) + MapEntry const* mapEntry = sMapStore.AssertEntry(at->target_mapId); + if (mapEntry->Instanceable()) { // Check if we can contact the instancescript of the instance for an updated entrance location - if (Map* map = sMapMgr->FindMap(at->target_mapId, player->GetInstanceSave(at->target_mapId)->GetInstanceId())) - if (InstanceMap* instanceMap = map->ToInstanceMap()) - if (InstanceScript* instanceScript = instanceMap->GetInstanceScript()) - entranceLocation = sObjectMgr->GetWorldSafeLoc(instanceScript->GetEntranceLocation()); + if (uint32 targetInstanceId = sMapMgr->FindInstanceIdForPlayer(at->target_mapId, _player)) + if (Map* map = sMapMgr->FindMap(at->target_mapId, targetInstanceId)) + if (InstanceMap* instanceMap = map->ToInstanceMap()) + if (InstanceScript* instanceScript = instanceMap->GetInstanceScript()) + entranceLocation = sObjectMgr->GetWorldSafeLoc(instanceScript->GetEntranceLocation()); // Finally check with the instancesave for an entrance location if we did not get a valid one from the instancescript if (!entranceLocation) - entranceLocation = sObjectMgr->GetWorldSafeLoc(instanceSave->GetEntranceLocation()); + { + Group* group = player->GetGroup(); + Difficulty difficulty = group ? group->GetDifficultyID(mapEntry) : player->GetDifficultyID(mapEntry); + ObjectGuid instanceOwnerGuid = group ? group->GetRecentInstanceOwner(at->target_mapId) : player->GetGUID(); + if (InstanceLock const* instanceLock = sInstanceLockMgr.FindActiveInstanceLock(instanceOwnerGuid, { mapEntry, sDB2Manager.GetDownscaledMapDifficultyData(at->target_mapId, difficulty) })) + entranceLocation = sObjectMgr->GetWorldSafeLoc(instanceLock->GetData()->EntranceWorldSafeLocId); + } } if (entranceLocation) diff --git a/src/server/game/Handlers/MovementHandler.cpp b/src/server/game/Handlers/MovementHandler.cpp index 0c027ea5f33..b28f83e03dc 100644 --- a/src/server/game/Handlers/MovementHandler.cpp +++ b/src/server/game/Handlers/MovementHandler.cpp @@ -22,8 +22,8 @@ #include "FlightPathMovementGenerator.h" #include "GameTime.h" #include "Garrison.h" +#include "InstanceLockMgr.h" #include "InstancePackets.h" -#include "InstanceSaveMgr.h" #include "Log.h" #include "Map.h" #include "MapManager.h" @@ -193,17 +193,24 @@ void WorldSession::HandleMoveWorldportAck() if (mEntry->IsDungeon()) { // check if this instance has a reset time and send it to player if so - Difficulty diff = newMap->GetDifficultyID(); - if (MapDifficultyEntry const* mapDiff = sDB2Manager.GetMapDifficultyData(mEntry->ID, diff)) + MapDb2Entries entries{ mEntry->ID, newMap->GetDifficultyID() }; + if (entries.MapDifficulty->HasResetSchedule()) { - if (mapDiff->GetRaidDuration()) + WorldPackets::Instance::RaidInstanceMessage raidInstanceMessage; + raidInstanceMessage.Type = RAID_INSTANCE_WELCOME; + raidInstanceMessage.MapID = mEntry->ID; + raidInstanceMessage.DifficultyID = newMap->GetDifficultyID(); + if (InstanceLock const* playerLock = sInstanceLockMgr.FindActiveInstanceLock(GetPlayer()->GetGUID(), entries)) { - if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(mEntry->ID, diff)) - { - uint32 timeleft = uint32(timeReset - GameTime::GetGameTime()); - player->SendInstanceResetWarning(mEntry->ID, diff, timeleft, true); - } + raidInstanceMessage.Locked = !playerLock->IsExpired(); + raidInstanceMessage.Extended = playerLock->IsExtended(); + } + else + { + raidInstanceMessage.Locked = false; + raidInstanceMessage.Extended = false; } + SendPacket(raidInstanceMessage.Write()); } // check if instance is valid diff --git a/src/server/game/Instances/InstanceLockMgr.cpp b/src/server/game/Instances/InstanceLockMgr.cpp index 007d994133a..94cfd09706c 100644 --- a/src/server/game/Instances/InstanceLockMgr.cpp +++ b/src/server/game/Instances/InstanceLockMgr.cpp @@ -414,10 +414,12 @@ void InstanceLockMgr::OnSharedInstanceLockDataDelete(uint32 instanceId) TC_LOG_DEBUG("instance.locks", "Deleting instance %u as it is no longer referenced by any player", instanceId); } -void InstanceLockMgr::UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, MapDb2Entries const& entries, bool extended) +std::pair<InstanceResetTimePoint, InstanceResetTimePoint> InstanceLockMgr::UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, + MapDb2Entries const& entries, bool extended) { if (InstanceLock* instanceLock = FindActiveInstanceLock(playerGuid, entries, true, false)) { + InstanceResetTimePoint oldExpiryTime = instanceLock->GetEffectiveExpiryTime(); instanceLock->SetExtended(extended); CharacterDatabase.PExecute("UPDATE character_instance_lock SET extended = %d WHERE guid = " UI64FMTD " AND mapId = %u AND lockId = %d", extended ? 1 : 0, @@ -429,7 +431,11 @@ void InstanceLockMgr::UpdateInstanceLockExtensionForPlayer(ObjectGuid const& pla entries.Map->ID, entries.Map->MapName[sWorld->GetDefaultDbcLocale()], uint32(entries.MapDifficulty->DifficultyID), sDifficultyStore.AssertEntry(entries.MapDifficulty->DifficultyID)->Name[sWorld->GetDefaultDbcLocale()], playerGuid.ToString().c_str(), extended ? "now" : "no longer"); + + return { oldExpiryTime, instanceLock->GetEffectiveExpiryTime() }; } + + return { InstanceResetTimePoint::min(), InstanceResetTimePoint::min() }; } #include "Config.h" diff --git a/src/server/game/Instances/InstanceLockMgr.h b/src/server/game/Instances/InstanceLockMgr.h index faf0bd584f6..45394451878 100644 --- a/src/server/game/Instances/InstanceLockMgr.h +++ b/src/server/game/Instances/InstanceLockMgr.h @@ -38,6 +38,7 @@ * `difficulty` tinyint(3) unsigned, * `data` text, ALWAYS FILLED (also might not match instance data for instanceId based locks) * `completedEncountersMask` int(10) unsigned, ALWAYS FILLED (also might not match instance data for instanceId based locks) + * `entranceWorldSafeLocId` int(10) unsigned, ALWAYS FILLED (also might not match instance data for instanceId based locks) * `expiryTime` bigint(20) unsigned, * `extended` tinyint(1) unsigned, * PRIMARY KEY (`guid`,`mapId`,`lockId`), @@ -46,6 +47,7 @@ * `instanceId` int(10) unsigned NOT NULL, * `data` text, FILLED ONLY FOR ID BASED LOCKS * `completedEncountersMask` int(10) unsigned, FILLED ONLY FOR ID BASED LOCKS + * `entranceWorldSafeLocId` int(10) unsigned, FILLED ONLY FOR ID BASED LOCKS * PRIMARY KEY (`instanceId`) */ @@ -73,6 +75,7 @@ struct InstanceLockData std::string Data; uint32 CompletedEncountersMask = 0; + uint32 EntranceWorldSafeLocId = 0; }; class TC_GAME_API InstanceLock @@ -185,6 +188,7 @@ struct InstanceLockUpdateEvent DungeonEncounterEntry const* CompletedEncounter; }; +// TOTALLY NOT THREADSAFE YET class TC_GAME_API InstanceLockMgr { public: @@ -252,8 +256,9 @@ public: @param playerGuid Guid of player whose lock is extended @param entries Map.db2 + MapDifficulty.db2 data for instance @param extended New instance lock extension state + @return pair<OldExpirationTime, NewExpirationTime> */ - void UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, MapDb2Entries const& entries, bool extended); + std::pair<InstanceResetTimePoint, InstanceResetTimePoint> UpdateInstanceLockExtensionForPlayer(ObjectGuid const& playerGuid, MapDb2Entries const& entries, bool extended); static InstanceLockMgr& Instance(); diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp deleted file mode 100644 index b566b4f0cf6..00000000000 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ /dev/null @@ -1,736 +0,0 @@ -/* - * This file is part of the TrinityCore 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 General Public License as published by the - * Free Software Foundation; either version 2 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 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 "InstanceSaveMgr.h" -#include "Common.h" -#include "Config.h" -#include "DatabaseEnv.h" -#include "DB2Stores.h" -#include "GameTime.h" -#include "GridNotifiers.h" -#include "GridStates.h" -#include "Group.h" -#include "InstanceScenario.h" -#include "InstanceScript.h" -#include "Log.h" -#include "Map.h" -#include "MapManager.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "Timer.h" -#include "World.h" - -uint16 InstanceSaveManager::ResetTimeDelay[] = {3600, 900, 300, 60}; - -InstanceSaveManager::~InstanceSaveManager() -{ -} - -InstanceSaveManager* InstanceSaveManager::instance() -{ - static InstanceSaveManager instance; - return &instance; -} - -void InstanceSaveManager::Unload() -{ - lock_instLists = true; - for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr) - { - InstanceSave* save = itr->second; - - for (InstanceSave::PlayerListType::iterator itr2 = save->m_playerList.begin(), next = itr2; itr2 != save->m_playerList.end(); itr2 = next) - { - ++next; - (*itr2)->UnbindInstance(save->GetMapId(), save->GetDifficultyID(), true); - } - - for (InstanceSave::GroupListType::iterator itr2 = save->m_groupList.begin(), next = itr2; itr2 != save->m_groupList.end(); itr2 = next) - { - ++next; - (*itr2)->UnbindInstance(save->GetMapId(), save->GetDifficultyID(), true); - } - - delete save; - } -} - -/* -- adding instance into manager -- called from InstanceMap::Add, _LoadBoundInstances, LoadGroups -*/ -InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, time_t resetTime, uint32 entranceId, bool canReset, bool load) -{ - if (InstanceSave* old_save = GetInstanceSave(instanceId)) - return old_save; - - MapEntry const* entry = sMapStore.LookupEntry(mapId); - if (!entry) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: wrong mapid = %d, instanceid = %d!", mapId, instanceId); - return nullptr; - } - - if (instanceId == 0) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, wrong instanceid = %d!", mapId, instanceId); - return nullptr; - } - - DifficultyEntry const* difficultyEntry = sDifficultyStore.LookupEntry(difficulty); - if (!difficultyEntry || difficultyEntry->InstanceType != entry->InstanceType) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d, wrong dificalty %u!", mapId, instanceId, static_cast<uint32>(difficulty)); - return nullptr; - } - - if (entranceId && !sObjectMgr->GetWorldSafeLoc(entranceId)) - { - TC_LOG_WARN("misc", "InstanceSaveManager::AddInstanceSave: invalid entranceId = %d defined for instance save with mapid = %d, instanceid = %d!", entranceId, mapId, instanceId); - entranceId = 0; - } - - if (!resetTime) - { - // initialize reset time - // for normal instances if no creatures are killed the instance will reset in two hours - if (entry->IsRaid() || difficulty > DIFFICULTY_NORMAL) - resetTime = GetResetTimeFor(mapId, difficulty); - else - { - resetTime = GameTime::GetGameTime() + 2 * HOUR; - // normally this will be removed soon after in InstanceMap::Add, prevent error - ScheduleReset(true, resetTime, InstResetEvent(0, mapId, difficulty, instanceId)); - } - } - - TC_LOG_DEBUG("maps", "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d", mapId, instanceId); - - InstanceSave* save = new InstanceSave(mapId, instanceId, difficulty, entranceId, resetTime, canReset); - if (!load) - save->SaveToDB(); - - m_instanceSaveById[instanceId] = save; - return save; -} - -InstanceSave* InstanceSaveManager::GetInstanceSave(uint32 InstanceId) -{ - InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId); - return itr != m_instanceSaveById.end() ? itr->second : nullptr; -} - -void InstanceSaveManager::DeleteInstanceFromDB(uint32 instanceid) -{ - CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INSTANCE_BY_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_BY_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_SCENARIO_INSTANCE_CRITERIA_FOR_INSTANCE); - stmt->setUInt32(0, instanceid); - trans->Append(stmt); - - CharacterDatabase.CommitTransaction(trans); - // Respawn times should be deleted only when the map gets unloaded -} - -void InstanceSaveManager::RemoveInstanceSave(uint32 InstanceId) -{ - InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId); - if (itr != m_instanceSaveById.end()) - { - // save the resettime for normal instances only when they get unloaded - if (time_t resettime = itr->second->GetResetTimeForDB()) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_RESETTIME); - - stmt->setInt64(0, resettime); - stmt->setUInt32(1, InstanceId); - - CharacterDatabase.Execute(stmt); - } - - itr->second->SetToDelete(true); - m_instanceSaveById.erase(itr); - } -} - -void InstanceSaveManager::UnloadInstanceSave(uint32 InstanceId) -{ - if (InstanceSave* save = GetInstanceSave(InstanceId)) - save->UnloadIfEmpty(); -} - -InstanceSave::InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, uint32 entranceId, time_t resetTime, bool canReset) -: m_resetTime(resetTime), m_instanceid(InstanceId), m_mapid(MapId), - m_difficulty(difficulty), m_entranceId(entranceId), m_canReset(canReset), m_toDelete(false) { } - -InstanceSave::~InstanceSave() -{ - // the players and groups must be unbound before deleting the save - ASSERT(m_playerList.empty() && m_groupList.empty()); -} - -/* - Called from AddInstanceSave -*/ -void InstanceSave::SaveToDB() -{ - // save instance data too - std::string data; - uint32 completedEncounters = 0; - - Map* map = sMapMgr->FindMap(GetMapId(), m_instanceid); - if (map) - { - ASSERT(map->IsDungeon()); - if (InstanceScript* instanceScript = ((InstanceMap*)map)->GetInstanceScript()) - { - data = instanceScript->GetSaveData(); - completedEncounters = instanceScript->GetCompletedEncounterMask(); - m_entranceId = instanceScript->GetEntranceLocation(); - } - - if (InstanceScenario* scenario = map->ToInstanceMap()->GetInstanceScenario()) - scenario->SaveToDB(); - } - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_INSTANCE_SAVE); - stmt->setUInt32(0, m_instanceid); - stmt->setUInt16(1, GetMapId()); - stmt->setUInt64(2, uint64(GetResetTimeForDB())); - stmt->setUInt8(3, uint8(GetDifficultyID())); - stmt->setUInt32(4, completedEncounters); - stmt->setString(5, data); - stmt->setUInt32(6, m_entranceId); - CharacterDatabase.Execute(stmt); -} - -time_t InstanceSave::GetResetTimeForDB() -{ - // only save the reset time for normal instances - MapEntry const* entry = sMapStore.LookupEntry(GetMapId()); - if (!entry || entry->IsRaid() || GetDifficultyID() == DIFFICULTY_HEROIC) - return 0; - else - return GetResetTime(); -} - -MapEntry const* InstanceSave::GetMapEntry() -{ - return sMapStore.LookupEntry(m_mapid); -} - -void InstanceSave::DeleteFromDB() -{ - InstanceSaveManager::DeleteInstanceFromDB(GetInstanceId()); -} - -/* true if the instance save is still valid */ -bool InstanceSave::UnloadIfEmpty() -{ - if (m_playerList.empty() && m_groupList.empty()) - { - // don't remove the save if there are still players inside the map - if (Map* map = sMapMgr->FindMap(GetMapId(), GetInstanceId())) - if (map->HavePlayers()) - return true; - - if (!sInstanceSaveMgr->lock_instLists) - sInstanceSaveMgr->RemoveInstanceSave(GetInstanceId()); - - return false; - } - else - return true; -} - -void InstanceSaveManager::LoadInstances() -{ - uint32 oldMSTime = getMSTime(); - - // Delete expired instances (Instance related spawns are removed in the following cleanup queries) - CharacterDatabase.DirectExecute("DELETE i FROM instance i LEFT JOIN instance_reset ir ON mapid = map AND i.difficulty = ir.difficulty " - "WHERE (i.resettime > 0 AND i.resettime < UNIX_TIMESTAMP()) OR (ir.resettime IS NOT NULL AND ir.resettime < UNIX_TIMESTAMP())"); - - // Delete invalid character_instance and group_instance references - CharacterDatabase.DirectExecute("DELETE ci.* FROM character_instance AS ci LEFT JOIN characters AS c ON ci.guid = c.guid WHERE c.guid IS NULL"); - CharacterDatabase.DirectExecute("DELETE gi.* FROM group_instance AS gi LEFT JOIN `groups` AS g ON gi.guid = g.guid WHERE g.guid IS NULL"); - - // Delete invalid instance references - CharacterDatabase.DirectExecute("DELETE i.* FROM instance AS i LEFT JOIN character_instance AS ci ON i.id = ci.instance LEFT JOIN group_instance AS gi ON i.id = gi.instance WHERE ci.guid IS NULL AND gi.guid IS NULL"); - - // Delete invalid references to instance - CharacterDatabase.DirectExecute("DELETE FROM respawn WHERE instanceId > 0 AND instanceId NOT IN (SELECT id FROM instance)"); - CharacterDatabase.DirectExecute("DELETE tmp.* FROM character_instance AS tmp LEFT JOIN instance ON tmp.instance = instance.id WHERE tmp.instance > 0 AND instance.id IS NULL"); - CharacterDatabase.DirectExecute("DELETE tmp.* FROM group_instance AS tmp LEFT JOIN instance ON tmp.instance = instance.id WHERE tmp.instance > 0 AND instance.id IS NULL"); - - // Clean invalid references to instance - CharacterDatabase.DirectExecute("UPDATE corpse SET instanceId = 0 WHERE instanceId > 0 AND instanceId NOT IN (SELECT id FROM instance)"); - CharacterDatabase.DirectExecute("UPDATE characters AS tmp LEFT JOIN instance ON tmp.instance_id = instance.id SET tmp.instance_id = 0 WHERE tmp.instance_id > 0 AND instance.id IS NULL"); - - // Initialize instance id storage (Needs to be done after the trash has been clean out) - sMapMgr->InitInstanceIds(); - - // Load reset times and clean expired instances - sInstanceSaveMgr->LoadResetTimes(); - - TC_LOG_INFO("server.loading", ">> Loaded instances in %u ms", GetMSTimeDiffToNow(oldMSTime)); - -} - -void InstanceSaveManager::LoadResetTimes() -{ - time_t now = GameTime::GetGameTime(); - time_t today = (now / DAY) * DAY; - - // NOTE: Use DirectPExecute for tables that will be queried later - - // get the current reset times for normal instances (these may need to be updated) - // these are only kept in memory for InstanceSaves that are loaded later - // resettime = 0 in the DB for raid/heroic instances so those are skipped - typedef std::pair<uint32 /*PAIR32(map, difficulty)*/, time_t> ResetTimeMapDiffType; - typedef std::map<uint32, ResetTimeMapDiffType> InstResetTimeMapDiffType; - InstResetTimeMapDiffType instResetTime; - - // index instance ids by map/difficulty pairs for fast reset warning send - typedef std::multimap<uint32 /*PAIR32(map, difficulty)*/, uint32 /*instanceid*/ > ResetTimeMapDiffInstances; - typedef std::pair<ResetTimeMapDiffInstances::const_iterator, ResetTimeMapDiffInstances::const_iterator> ResetTimeMapDiffInstancesBounds; - ResetTimeMapDiffInstances mapDiffResetInstances; - - if (QueryResult result = CharacterDatabase.Query("SELECT id, map, difficulty, resettime FROM instance ORDER BY id ASC")) - { - do - { - Field* fields = result->Fetch(); - - uint32 instanceId = fields[0].GetUInt32(); - - // Mark instance id as being used - sMapMgr->RegisterInstanceId(instanceId); - - if (time_t resettime = time_t(fields[3].GetUInt64())) - { - uint32 mapid = fields[1].GetUInt16(); - uint32 difficulty = fields[2].GetUInt8(); - - instResetTime[instanceId] = ResetTimeMapDiffType(MAKE_PAIR32(mapid, difficulty), resettime); - mapDiffResetInstances.insert(ResetTimeMapDiffInstances::value_type(MAKE_PAIR32(mapid, difficulty), instanceId)); - } - } - while (result->NextRow()); - - // schedule the reset times - for (InstResetTimeMapDiffType::iterator itr = instResetTime.begin(); itr != instResetTime.end(); ++itr) - if (itr->second.second > now) - ScheduleReset(true, itr->second.second, InstResetEvent(0, PAIR32_LOPART(itr->second.first), Difficulty(PAIR32_HIPART(itr->second.first)), itr->first)); - } - - // load the global respawn times for raid/heroic instances - uint32 resetHour = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR); - if (QueryResult result = CharacterDatabase.Query("SELECT mapid, difficulty, resettime FROM instance_reset")) - { - do - { - Field* fields = result->Fetch(); - uint32 mapid = fields[0].GetUInt16(); - Difficulty difficulty = Difficulty(fields[1].GetUInt8()); - uint64 oldresettime = fields[2].GetUInt64(); - - MapDifficultyEntry const* mapDiff = sDB2Manager.GetMapDifficultyData(mapid, difficulty); - if (!mapDiff) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::LoadResetTimes: invalid mapid(%u)/difficulty(%u) pair in instance_reset!", mapid, static_cast<uint32>(difficulty)); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GLOBAL_INSTANCE_RESETTIME); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - CharacterDatabase.DirectExecute(stmt); - continue; - } - - // update the reset time if the hour in the configs changes - uint64 newresettime = GetLocalHourTimestamp(oldresettime, resetHour, false); - if (oldresettime != newresettime) - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); - stmt->setUInt64(0, uint64(newresettime)); - stmt->setUInt16(1, uint16(mapid)); - stmt->setUInt8(2, uint8(difficulty)); - CharacterDatabase.DirectExecute(stmt); - } - - InitializeResetTimeFor(mapid, difficulty, newresettime); - } while (result->NextRow()); - } - - // calculate new global reset times for expired instances and those that have never been reset yet - // add the global reset times to the priority queue - for (auto& mapDifficultyPair : sDB2Manager.GetMapDifficulties()) - { - uint32 mapid = mapDifficultyPair.first; - - for (auto& difficultyPair : mapDifficultyPair.second) - { - Difficulty difficulty = Difficulty(difficultyPair.first); - MapDifficultyEntry const* mapDiff = difficultyPair.second; - if (!mapDiff->GetRaidDuration()) - continue; - - // the reset_delay must be at least one day - uint32 period = uint32(((mapDiff->GetRaidDuration() * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); - if (period < DAY) - period = DAY; - - time_t t = GetResetTimeFor(mapid, difficulty); - if (!t) - { - // initialize the reset time - t = GetLocalHourTimestamp(today + period, resetHour); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GLOBAL_INSTANCE_RESETTIME); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - stmt->setInt64(2, t); - CharacterDatabase.DirectExecute(stmt); - } - - if (t < now) - { - // assume that expired instances have already been cleaned - // calculate the next reset time - time_t day = (t / DAY) * DAY; - t = GetLocalHourTimestamp(day + ((today - day) / period + 1) * period, resetHour); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); - stmt->setInt64(0, t); - stmt->setUInt16(1, uint16(mapid)); - stmt->setUInt8(2, uint8(difficulty)); - CharacterDatabase.DirectExecute(stmt); - } - - InitializeResetTimeFor(mapid, difficulty, t); - - // schedule the global reset/warning - uint8 type; - for (type = 1; type < 4; ++type) - if (t - ResetTimeDelay[type - 1] > now) - break; - - ScheduleReset(true, t - ResetTimeDelay[type - 1], InstResetEvent(type, mapid, difficulty, 0)); - - ResetTimeMapDiffInstancesBounds range = mapDiffResetInstances.equal_range(MAKE_PAIR32(mapid, difficulty)); - for (; range.first != range.second; ++range.first) - ScheduleReset(true, t - ResetTimeDelay[type - 1], InstResetEvent(type, mapid, difficulty, range.first->second)); - } - } -} - -time_t InstanceSaveManager::GetSubsequentResetTime(uint32 mapid, Difficulty difficulty, time_t resetTime) const -{ - MapDifficultyEntry const* mapDiff = sDB2Manager.GetMapDifficultyData(mapid, difficulty); - if (!mapDiff || !mapDiff->GetRaidDuration()) - { - TC_LOG_ERROR("misc", "InstanceSaveManager::GetSubsequentResetTime: not valid difficulty or no reset delay for map %u", mapid); - return 0; - } - - time_t resetHour = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR); - time_t period = uint32(((mapDiff->GetRaidDuration() * sWorld->getRate(RATE_INSTANCE_RESET_TIME)) / DAY) * DAY); - if (period < DAY) - period = DAY; - - return GetLocalHourTimestamp(((resetTime + MINUTE) / DAY * DAY) + period, resetHour); -} - -void InstanceSaveManager::SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) -{ - ResetTimeByMapDifficultyMap::iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR64(mapid, d)); - ASSERT(itr != m_resetTimeByMapDifficulty.end()); - itr->second = t; -} - -void InstanceSaveManager::ScheduleReset(bool add, time_t time, InstResetEvent event) -{ - if (!add) - { - // find the event in the queue and remove it - ResetTimeQueue::iterator itr; - std::pair<ResetTimeQueue::iterator, ResetTimeQueue::iterator> range; - range = m_resetTimeQueue.equal_range(time); - for (itr = range.first; itr != range.second; ++itr) - { - if (itr->second == event) - { - m_resetTimeQueue.erase(itr); - return; - } - } - - // in case the reset time changed (should happen very rarely), we search the whole queue - if (itr == range.second) - { - for (itr = m_resetTimeQueue.begin(); itr != m_resetTimeQueue.end(); ++itr) - { - if (itr->second == event) - { - m_resetTimeQueue.erase(itr); - return; - } - } - - if (itr == m_resetTimeQueue.end()) - TC_LOG_ERROR("misc", "InstanceSaveManager::ScheduleReset: cannot cancel the reset, the event(%d, %d, %d) was not found!", event.type, event.mapid, event.instanceId); - } - } - else - m_resetTimeQueue.insert(std::pair<time_t, InstResetEvent>(time, event)); -} - -void InstanceSaveManager::ForceGlobalReset(uint32 mapId, Difficulty difficulty) -{ - if (!sDB2Manager.GetDownscaledMapDifficultyData(mapId, difficulty)) - return; - // remove currently scheduled reset times - ScheduleReset(false, 0, InstResetEvent(1, mapId, difficulty, 0)); - ScheduleReset(false, 0, InstResetEvent(4, mapId, difficulty, 0)); - // force global reset on the instance - _ResetOrWarnAll(mapId, difficulty, false, GameTime::GetGameTime()); -} - -void InstanceSaveManager::Update() -{ - time_t now = GameTime::GetGameTime(); - time_t t; - - while (!m_resetTimeQueue.empty()) - { - t = m_resetTimeQueue.begin()->first; - if (t >= now) - break; - - InstResetEvent &event = m_resetTimeQueue.begin()->second; - if (event.type == 0) - { - // for individual normal instances, max creature respawn + X hours - _ResetInstance(event.mapid, event.instanceId); - m_resetTimeQueue.erase(m_resetTimeQueue.begin()); - } - else - { - // global reset/warning for a certain map - time_t resetTime = GetResetTimeFor(event.mapid, event.difficulty); - _ResetOrWarnAll(event.mapid, event.difficulty, event.type != 4, resetTime); - if (event.type != 4) - { - // schedule the next warning/reset - ++event.type; - ScheduleReset(true, resetTime - ResetTimeDelay[event.type-1], event); - } - m_resetTimeQueue.erase(m_resetTimeQueue.begin()); - } - } -} - -void InstanceSaveManager::_ResetSave(InstanceSaveHashMap::iterator &itr) -{ - // unbind all players bound to the instance - // do not allow UnbindInstance to automatically unload the InstanceSaves - lock_instLists = true; - - bool shouldDelete = true; - InstanceSave::PlayerListType &pList = itr->second->m_playerList; - std::vector<Player*> temp; // list of expired binds that should be unbound - for (Player* player : pList) - { - if (InstancePlayerBind* bind = player->GetBoundInstance(itr->second->GetMapId(), itr->second->GetDifficultyID())) - { - ASSERT(bind->save == itr->second); - if (bind->perm && bind->extendState) // permanent and not already expired - { - // actual promotion in DB already happened in caller - bind->extendState = bind->extendState == EXTEND_STATE_EXTENDED ? EXTEND_STATE_NORMAL : EXTEND_STATE_EXPIRED; - shouldDelete = false; - continue; - } - } - temp.push_back(player); - } - for (Player* player : temp) - { - player->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficultyID(), true); - } - - InstanceSave::GroupListType &gList = itr->second->m_groupList; - while (!gList.empty()) - { - Group* group = *(gList.begin()); - group->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficultyID(), true); - } - - if (shouldDelete) - { - delete itr->second; - itr = m_instanceSaveById.erase(itr); - } - else - ++itr; - - lock_instLists = false; -} - -void InstanceSaveManager::_ResetInstance(uint32 mapid, uint32 instanceId) -{ - TC_LOG_DEBUG("maps", "InstanceSaveMgr::_ResetInstance %u, %u", mapid, instanceId); - MapEntry const* map = sMapStore.LookupEntry(mapid); - if (!map->IsDungeon()) - return; - - InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(instanceId); - if (itr != m_instanceSaveById.end()) - _ResetSave(itr); - - DeleteInstanceFromDB(instanceId); // even if save not loaded - - Map* iMap = sMapMgr->FindMap(mapid, instanceId); - if (iMap) - { - ((InstanceMap*)iMap)->Reset(INSTANCE_RESET_RESPAWN_DELAY); - iMap->DeleteRespawnTimes(); - iMap->DeleteCorpseData(); - } - else - Map::DeleteRespawnTimesInDB(mapid, instanceId); - - // Free up the instance id and allow it to be reused - sMapMgr->FreeInstanceId(instanceId); -} - -void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime) -{ - // global reset for all instances of the given map - MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); - if (!mapEntry->Instanceable()) - return; - TC_LOG_DEBUG("misc", "InstanceSaveManager::ResetOrWarnAll: Processing map %s (%u) on difficulty %u (warn? %u)", mapEntry->MapName[sWorld->GetDefaultDbcLocale()], mapid, static_cast<uint32>(difficulty), warn); - - time_t now = GameTime::GetGameTime(); - - if (!warn) - { - // calculate the next reset time - time_t next_reset = GetSubsequentResetTime(mapid, difficulty, resetTime); - if (!next_reset) - return; - - // delete/promote instance binds from the DB, even if not loaded - CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_CHAR_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EXPIRE_CHAR_INSTANCE_BY_MAP_DIFF); - stmt->setUInt16(0, uint16(mapid)); - stmt->setUInt8(1, uint8(difficulty)); - trans->Append(stmt); - - CharacterDatabase.CommitTransaction(trans); - - // promote loaded binds to instances of the given map - for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end();) - { - if (itr->second->GetMapId() == mapid && itr->second->GetDifficultyID() == difficulty) - _ResetSave(itr); - else - ++itr; - } - - SetResetTimeFor(mapid, difficulty, next_reset); - ScheduleReset(true, time_t(next_reset-3600), InstResetEvent(1, mapid, difficulty, 0)); - - // Update it in the DB - stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); - - stmt->setUInt64(0, uint64(next_reset)); - stmt->setUInt16(1, uint16(mapid)); - stmt->setUInt8(2, uint8(difficulty)); - - CharacterDatabase.Execute(stmt); - } - - // note: this isn't fast but it's meant to be executed very rarely - if (mapEntry->IsDungeon()) - { - sMapMgr->DoForAllMapsWithMapId(mapid, [=](Map* map) - { - if (warn) - { - uint32 timeLeft; - if (now >= resetTime) - timeLeft = 0; - else - timeLeft = uint32(resetTime - now); - - ((InstanceMap*)map)->SendResetWarnings(timeLeft); - } - else - ((InstanceMap*)map)->Reset(INSTANCE_RESET_GLOBAL); - }); - } - - /// @todo delete creature/gameobject respawn times even if the maps are not loaded -} - -uint32 InstanceSaveManager::GetNumBoundPlayersTotal() const -{ - uint32 ret = 0; - for (InstanceSaveHashMap::const_iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr) - ret += itr->second->GetPlayerCount(); - - return ret; -} - -uint32 InstanceSaveManager::GetNumBoundGroupsTotal() const -{ - uint32 ret = 0; - for (InstanceSaveHashMap::const_iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr) - ret += itr->second->GetGroupCount(); - - return ret; -} diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h deleted file mode 100644 index 6b5ac5c562f..00000000000 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ /dev/null @@ -1,245 +0,0 @@ -/* - * This file is part of the TrinityCore 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 General Public License as published by the - * Free Software Foundation; either version 2 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 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 _INSTANCESAVEMGR_H -#define _INSTANCESAVEMGR_H - -#include <list> -#include <map> -#include <mutex> -#include <unordered_map> - -#include "Define.h" -#include "DBCEnums.h" -#include "ObjectDefines.h" - -struct InstanceTemplate; -struct MapEntry; -class Player; -class Group; - -/* - Holds the information necessary for creating a new map for an existing instance - Is referenced in three cases: - - player-instance binds for solo players (not in group) - - player-instance binds for permanent heroic/raid saves - - group-instance binds (both solo and permanent) cache the player binds for the group leader -*/ -class TC_GAME_API InstanceSave -{ - friend class InstanceSaveManager; - public: - /* Created either when: - - any new instance is being generated - - the first time a player bound to InstanceId logs in - - when a group bound to the instance is loaded */ - InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, uint32 entranceId, time_t resetTime, bool canReset); - - /* Unloaded when m_playerList and m_groupList become empty - or when the instance is reset */ - ~InstanceSave(); - - InstanceSave(InstanceSave const& right) = delete; - InstanceSave(InstanceSave&& right) = delete; - InstanceSave& operator=(InstanceSave const& right) = delete; - InstanceSave& operator=(InstanceSave&& right) = delete; - - uint32 GetPlayerCount() const { return uint32(m_playerList.size()); } - uint32 GetGroupCount() const { return uint32(m_groupList.size()); } - - /* A map corresponding to the InstanceId/MapId does not always exist. - InstanceSave objects may be created on player logon but the maps are - created and loaded only when a player actually enters the instance. */ - uint32 GetInstanceId() const { return m_instanceid; } - uint32 GetMapId() const { return m_mapid; } - - /* Saved when the instance is generated for the first time */ - void SaveToDB(); - /* When the instance is being reset (permanently deleted) */ - void DeleteFromDB(); - - /* for normal instances this corresponds to max(creature respawn time) + X hours - for raid/heroic instances this caches the global respawn time for the map */ - time_t GetResetTime() const { return m_resetTime; } - void SetResetTime(time_t resetTime) { m_resetTime = resetTime; } - time_t GetResetTimeForDB(); - - uint32 GetEntranceLocation() const { return m_entranceId; } - void SetEntranceLocation(uint32 entranceId) { m_entranceId = entranceId; } - - MapEntry const* GetMapEntry(); - - /* online players bound to the instance (perm/solo) - does not include the members of the group unless they have permanent saves */ - void AddPlayer(Player* player) - { - std::lock_guard<std::mutex> lock(_playerListLock); - m_playerList.push_back(player); - } - - bool RemovePlayer(Player* player) - { - _playerListLock.lock(); - m_playerList.remove(player); - bool isStillValid = UnloadIfEmpty(); - _playerListLock.unlock(); - - //delete here if needed, after releasing the lock - if (m_toDelete) - delete this; - - return isStillValid; - } - /* all groups bound to the instance */ - void AddGroup(Group* group) { m_groupList.push_back(group); } - bool RemoveGroup(Group* group) - { - m_groupList.remove(group); - bool isStillValid = UnloadIfEmpty(); - if (m_toDelete) - delete this; - return isStillValid; - } - - /* instances cannot be reset (except at the global reset time) - if there are players permanently bound to it - this is cached for the case when those players are offline */ - bool CanReset() const { return m_canReset; } - void SetCanReset(bool canReset) { m_canReset = canReset; } - - /* currently it is possible to omit this information from this structure - but that would depend on a lot of things that can easily change in future */ - Difficulty GetDifficultyID() const { return m_difficulty; } - - /* used to flag the InstanceSave as to be deleted, so the caller can delete it */ - void SetToDelete(bool toDelete) - { - m_toDelete = toDelete; - } - - typedef std::list<Player*> PlayerListType; - typedef std::list<Group*> GroupListType; - private: - bool UnloadIfEmpty(); - /* the only reason the instSave-object links are kept is because - the object-instSave links need to be broken at reset time */ - /// @todo: Check if maybe it's enough to just store the number of players/groups - PlayerListType m_playerList; - GroupListType m_groupList; - time_t m_resetTime; - uint32 m_instanceid; - uint32 m_mapid; - Difficulty m_difficulty; - uint32 m_entranceId; - bool m_canReset; - bool m_toDelete; - - std::mutex _playerListLock; -}; - -typedef std::unordered_map<uint64 /*PAIR64(map, difficulty)*/, time_t /*resetTime*/> ResetTimeByMapDifficultyMap; - -class TC_GAME_API InstanceSaveManager -{ - friend class InstanceSave; - - private: - InstanceSaveManager() : lock_instLists(false) { }; - ~InstanceSaveManager(); - - public: - typedef std::unordered_map<uint32 /*InstanceId*/, InstanceSave*> InstanceSaveHashMap; - - static InstanceSaveManager* instance(); - - void Unload(); - - /* resetTime is a global propery of each (raid/heroic) map - all instances of that map reset at the same time */ - struct InstResetEvent - { - uint8 type; - Difficulty difficulty:8; - uint32 mapid; - uint32 instanceId; - - InstResetEvent() : type(0), difficulty(DIFFICULTY_NORMAL), mapid(0), instanceId(0) { } - InstResetEvent(uint8 t, uint32 _mapid, Difficulty d, uint32 _instanceid) - : type(t), difficulty(d), mapid(_mapid), instanceId(_instanceid) { } - bool operator==(InstResetEvent const& e) const { return e.instanceId == instanceId; } - }; - typedef std::multimap<time_t /*resetTime*/, InstResetEvent> ResetTimeQueue; - - void LoadInstances(); - - void LoadResetTimes(); - time_t GetResetTimeFor(uint32 mapid, Difficulty d) const - { - ResetTimeByMapDifficultyMap::const_iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR64(mapid, d)); - return itr != m_resetTimeByMapDifficulty.end() ? itr->second : 0; - } - time_t GetSubsequentResetTime(uint32 mapid, Difficulty difficulty, time_t resetTime) const; - - // Use this on startup when initializing reset times - void InitializeResetTimeFor(uint32 mapid, Difficulty d, time_t t) - { - m_resetTimeByMapDifficulty[MAKE_PAIR64(mapid, d)] = t; - } - - // Use this only when updating existing reset times - void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t); - - ResetTimeByMapDifficultyMap const& GetResetTimeMap() const - { - return m_resetTimeByMapDifficulty; - } - void ScheduleReset(bool add, time_t time, InstResetEvent event); - void ForceGlobalReset(uint32 mapId, Difficulty difficulty); - - void Update(); - - InstanceSave* AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, time_t resetTime, uint32 entranceId, - bool canReset, bool load = false); - void RemoveInstanceSave(uint32 InstanceId); - void UnloadInstanceSave(uint32 InstanceId); - static void DeleteInstanceFromDB(uint32 instanceid); - - InstanceSave* GetInstanceSave(uint32 InstanceId); - - /* statistics */ - uint32 GetNumInstanceSaves() const { return uint32(m_instanceSaveById.size()); } - uint32 GetNumBoundPlayersTotal() const; - uint32 GetNumBoundGroupsTotal() const; - - protected: - static uint16 ResetTimeDelay[]; - - private: - void _ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime); - void _ResetInstance(uint32 mapid, uint32 instanceId); - void _ResetSave(InstanceSaveHashMap::iterator &itr); - // used during global instance resets - bool lock_instLists; - // fast lookup by instance id - InstanceSaveHashMap m_instanceSaveById; - // fast lookup for reset times (always use existed functions for access/set) - ResetTimeByMapDifficultyMap m_resetTimeByMapDifficulty; - ResetTimeQueue m_resetTimeQueue; -}; - -#define sInstanceSaveMgr InstanceSaveManager::instance() -#endif diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index 358ce8d60c0..159eb82b89e 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -451,7 +451,7 @@ bool InstanceScript::SetBossState(uint32 id, EncounterState state) bossInfo->state = state; SaveToDB(); - if (state == DONE) + if (state == DONE && dungeonEncounter) instance->UpdateInstanceLock(dungeonEncounter, { id, state }); } @@ -779,11 +779,20 @@ bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player con return false; } +bool InstanceScript::IsEncounterCompleted(uint32 dungeonEncounterId) const +{ + for (std::size_t i = 0; i < bosses.size(); ++i) + for (std::size_t j = 0; j < bosses[i].DungeonEncounters.size(); ++j) + if (bosses[i].DungeonEncounters[j] && bosses[i].DungeonEncounters[j]->ID == dungeonEncounterId) + return bosses[i].state == DONE; + + return false; +} + void InstanceScript::SetEntranceLocation(uint32 worldSafeLocationId) { _entranceId = worldSafeLocationId; - if (_temporaryEntranceId) - _temporaryEntranceId = 0; + _temporaryEntranceId = 0; } void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= nullptr*/, uint8 priority) diff --git a/src/server/game/Instances/InstanceScript.h b/src/server/game/Instances/InstanceScript.h index 8e34702361b..77c8886628d 100644 --- a/src/server/game/Instances/InstanceScript.h +++ b/src/server/game/Instances/InstanceScript.h @@ -273,6 +273,8 @@ class TC_GAME_API InstanceScript : public ZoneScript // Returns completed encounters mask for packets uint32 GetCompletedEncounterMask() const { return completedEncounters; } + bool IsEncounterCompleted(uint32 dungeonEncounterId) const; + uint32 GetEncounterCount() const { return uint32(bosses.size()); } // Sets the entrance location (WorldSafeLoc) id diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index 4c838cd7d09..5d2a530b9d7 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -33,7 +33,6 @@ #include "Group.h" #include "InstanceLockMgr.h" #include "InstancePackets.h" -#include "InstanceSaveMgr.h" #include "InstanceScenario.h" #include "InstanceScript.h" #include "Log.h" @@ -1813,16 +1812,14 @@ Map::EnterState Map::PlayerCannotEnter(uint32 mapid, Player* player, bool /*logi if (entry->Instanceable()) { //Get instance where player's group is bound & its map - if (uint32 instanceIdToCheck = sMapMgr->FindInstanceIdForPlayer(mapid, player)) - { - if (Map* boundMap = sMapMgr->FindMap(mapid, instanceIdToCheck)) - if (EnterState denyReason = boundMap->CannotEnter(player)) - return denyReason; + uint32 instanceIdToCheck = sMapMgr->FindInstanceIdForPlayer(mapid, player); + if (Map* boundMap = sMapMgr->FindMap(mapid, instanceIdToCheck)) + if (EnterState denyReason = boundMap->CannotEnter(player)) + return denyReason; - // players are only allowed to enter 10 instances per hour - if (entry->IsDungeon() && !player->CheckInstanceCount(instanceIdToCheck) && !player->isDead()) - return Map::CANNOT_ENTER_TOO_MANY_INSTANCES; - } + // players are only allowed to enter 10 instances per hour + if (entry->IsDungeon() && !player->CheckInstanceCount(instanceIdToCheck) && !player->isDead()) + return CANNOT_ENTER_TOO_MANY_INSTANCES; } return CAN_ENTER; @@ -2161,6 +2158,9 @@ void Map::DeleteRespawnInfo(RespawnInfo* info, CharacterDatabaseTransaction dbTr void Map::DeleteRespawnInfoFromDB(SpawnObjectType type, ObjectGuid::LowType spawnId, CharacterDatabaseTransaction dbTrans) { + if (Instanceable()) + return; + CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_RESPAWN); stmt->setUInt16(0, type); stmt->setUInt64(1, spawnId); @@ -2921,7 +2921,6 @@ void InstanceMap::RemovePlayerFromMap(Player* player, bool remove) // for normal instances schedule the reset after all players have left SetResetSchedule(true); - sInstanceSaveMgr->UnloadInstanceSave(GetInstanceId()); } void InstanceMap::CreateInstanceData() @@ -2967,13 +2966,14 @@ void InstanceMap::TrySetOwningGroup(Group* group) /* Returns true if there are no players in the instance */ -bool InstanceMap::Reset(uint8 method) +bool InstanceMap::Reset(InstanceResetMethod method) { // note: since the map may not be loaded when the instance needs to be reset - // the instance must be deleted from the DB by InstanceSaveManager + // the instance must be deleted from the DB if (HavePlayers()) { + // on manual reset, fail if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY) { // notify the players to leave the instance so it can be reset @@ -2982,24 +2982,15 @@ bool InstanceMap::Reset(uint8 method) } else { - bool doUnload = true; + // on lock expiration boot players (do we also care about extension state?) if (method == INSTANCE_RESET_GLOBAL) { // set the homebind timer for players inside (1 minute) for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) - { - InstancePlayerBind* bind = itr->GetSource()->GetBoundInstance(GetId(), GetDifficultyID()); - if (bind && bind->extendState && bind->save->GetInstanceId() == GetInstanceId()) - doUnload = false; - else - itr->GetSource()->m_InstanceValid = false; - } - - if (doUnload && HasPermBoundPlayers()) // check if any unloaded players have a nonexpired save to this - doUnload = false; + itr->GetSource()->m_InstanceValid = false; } - if (doUnload) + if (!HasPermBoundPlayers()) { // the unload timer is not started // instead the map will unload immediately after the players have left @@ -3107,25 +3098,8 @@ void InstanceMap::UnloadAll() Map::UnloadAll(); } -void InstanceMap::SendResetWarnings(uint32 timeLeft) const +void InstanceMap::SetResetSchedule(bool /*on*/) { - for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) - itr->GetSource()->SendInstanceResetWarning(GetId(), itr->GetSource()->GetDifficultyID(GetEntry()), timeLeft, true); -} - -void InstanceMap::SetResetSchedule(bool on) -{ - // only for normal instances - // the reset time is only scheduled when there are no payers inside - // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled - if (IsDungeon() && !HavePlayers() && !IsRaidOrHeroicDungeon()) - { - if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(GetInstanceId())) - sInstanceSaveMgr->ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), GetDifficultyID(), GetInstanceId())); - else - TC_LOG_ERROR("maps", "InstanceMap::SetResetSchedule: cannot turn schedule %s, there is no save information for instance (map [id: %u, name: %s], instance id: %u, difficulty: %u)", - on ? "on" : "off", GetId(), GetMapName(), GetInstanceId(), static_cast<uint32>(GetDifficultyID())); - } } MapDifficultyEntry const* Map::GetMapDifficulty() const @@ -3170,11 +3144,6 @@ bool Map::IsRaid() const return i_mapEntry && i_mapEntry->IsRaid(); } -bool Map::IsRaidOrHeroicDungeon() const -{ - return IsRaid() || IsHeroic(); -} - bool Map::IsHeroic() const { if (DifficultyEntry const* difficulty = sDifficultyStore.LookupEntry(i_spawnMode)) @@ -3235,12 +3204,6 @@ uint32 InstanceMap::GetMaxPlayers() const return GetEntry()->MaxPlayers; } -uint32 InstanceMap::GetMaxResetDelay() const -{ - MapDifficultyEntry const* mapDiff = GetMapDifficulty(); - return mapDiff ? mapDiff->GetRaidDuration() : 0; -} - TeamId InstanceMap::GetTeamIdInInstance() const { if (sWorldStateMgr->GetValue(WS_TEAM_IN_INSTANCE_ALLIANCE, this)) @@ -3451,6 +3414,9 @@ void Map::SaveRespawnTime(SpawnObjectType type, ObjectGuid::LowType spawnId, uin void Map::SaveRespawnInfoDB(RespawnInfo const& info, CharacterDatabaseTransaction dbTrans) { + if (Instanceable()) + return; + CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_RESPAWN); stmt->setUInt16(0, info.type); stmt->setUInt64(1, info.spawnId); @@ -3462,6 +3428,9 @@ void Map::SaveRespawnInfoDB(RespawnInfo const& info, CharacterDatabaseTransactio void Map::LoadRespawnTimes() { + if (Instanceable()) + return; + CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_RESPAWNS); stmt->setUInt16(0, GetId()); stmt->setUInt32(1, GetInstanceId()); @@ -3490,11 +3459,14 @@ void Map::LoadRespawnTimes() } } -/*static*/ void Map::DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId) +void Map::DeleteRespawnTimesInDB() { + if (Instanceable()) + return; + CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_RESPAWNS); - stmt->setUInt16(0, mapId); - stmt->setUInt32(1, instanceId); + stmt->setUInt16(0, GetId()); + stmt->setUInt32(1, GetInstanceId()); CharacterDatabase.Execute(stmt); } diff --git a/src/server/game/Maps/Map.h b/src/server/game/Maps/Map.h index e1e70b4ab6f..68a81710c64 100644 --- a/src/server/game/Maps/Map.h +++ b/src/server/game/Maps/Map.h @@ -52,7 +52,6 @@ class GameObjectModel; class Group; class InstanceLock; class InstanceMap; -class InstanceSave; class InstanceScript; class InstanceScenario; class Object; @@ -292,7 +291,6 @@ class TC_GAME_API Map : public GridRefManager<NGridType> bool IsDungeon() const; bool IsNonRaidDungeon() const; bool IsRaid() const; - bool IsRaidOrHeroicDungeon() const; bool IsHeroic() const; bool Is25ManRaid() const; bool IsBattleground() const; @@ -446,8 +444,8 @@ class TC_GAME_API Map : public GridRefManager<NGridType> void SaveRespawnTime(SpawnObjectType type, ObjectGuid::LowType spawnId, uint32 entry, time_t respawnTime, uint32 gridId, CharacterDatabaseTransaction dbTrans = nullptr, bool startup = false); void SaveRespawnInfoDB(RespawnInfo const& info, CharacterDatabaseTransaction dbTrans = nullptr); void LoadRespawnTimes(); - void DeleteRespawnTimes() { UnloadAllRespawnInfos(); DeleteRespawnTimesInDB(GetId(), GetInstanceId()); } - static void DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId); + void DeleteRespawnTimes() { UnloadAllRespawnInfos(); DeleteRespawnTimesInDB(); } + void DeleteRespawnTimesInDB(); void LoadCorpseData(); void DeleteCorpseData(); @@ -807,7 +805,7 @@ class TC_GAME_API InstanceMap : public Map void RemovePlayerFromMap(Player*, bool) override; void Update(uint32) override; void CreateInstanceData(); - bool Reset(uint8 method); + bool Reset(InstanceResetMethod method); uint32 GetScriptId() const { return i_script_id; } std::string const& GetScriptName() const; InstanceScript* GetInstanceScript() { return i_data; } @@ -820,18 +818,17 @@ class TC_GAME_API InstanceMap : public Map void CreateInstanceLockForPlayer(Player* player); void UnloadAll() override; EnterState CannotEnter(Player* player) override; - void SendResetWarnings(uint32 timeLeft) const; void SetResetSchedule(bool on); /* this checks if any players have a permanent bind (included reactivatable expired binds) to the instance ID it needs a DB query, so use sparingly */ bool HasPermBoundPlayers() const; uint32 GetMaxPlayers() const; - uint32 GetMaxResetDelay() const; TeamId GetTeamIdInInstance() const; Team GetTeamInInstance() const { return GetTeamIdInInstance() == TEAM_ALLIANCE ? ALLIANCE : HORDE; } virtual void InitVisibilityDistance() override; + Group* GetOwningGroup() const { return i_owningGroupRef.getTarget(); } void TrySetOwningGroup(Group* group); diff --git a/src/server/game/Maps/MapManager.cpp b/src/server/game/Maps/MapManager.cpp index 8a525d2b64e..788d27301a4 100644 --- a/src/server/game/Maps/MapManager.cpp +++ b/src/server/game/Maps/MapManager.cpp @@ -23,7 +23,6 @@ #include "GarrisonMap.h" #include "Group.h" #include "InstanceLockMgr.h" -#include "InstanceSaveMgr.h" #include "Log.h" #include "Map.h" #include "Player.h" @@ -250,6 +249,49 @@ Map* MapManager::FindMap(uint32 mapId, uint32 instanceId) const return FindMap_i(mapId, instanceId); } +uint32 MapManager::FindInstanceIdForPlayer(uint32 mapId, Player const* player) const +{ + MapEntry const* entry = sMapStore.LookupEntry(mapId); + if (!entry) + return 0; + + if (entry->IsBattlegroundOrArena()) + return player->GetBattlegroundId(); + else if (entry->IsDungeon()) + { + Group const* group = player->GetGroup(); + Difficulty difficulty = group ? group->GetDifficultyID(entry) : player->GetDifficultyID(entry); + MapDb2Entries entries{ entry, sDB2Manager.GetDownscaledMapDifficultyData(mapId, difficulty) }; + ObjectGuid instanceOwnerGuid = group ? group->GetRecentInstanceOwner(mapId) : player->GetGUID(); + InstanceLock* instanceLock = sInstanceLockMgr.FindActiveInstanceLock(instanceOwnerGuid, entries); + uint32 newInstanceId = 0; + if (instanceLock) + newInstanceId = instanceLock->GetInstanceId(); + else if (!entries.MapDifficulty->HasResetSchedule()) // Try finding instance id for normal dungeon + newInstanceId = group ? group->GetRecentInstanceId(mapId) : player->GetRecentInstanceId(mapId); + + if (!newInstanceId) + return 0; + + Map* map = FindMap(mapId, newInstanceId); + + // is is possible that instance id is already in use by another group for boss-based locks + if (!entries.IsInstanceIdBound() && instanceLock && map && map->ToInstanceMap()->GetInstanceLock() != instanceLock) + return 0; + + return newInstanceId; + } + else if (entry->IsGarrison()) + return uint32(player->GetGUID().GetCounter()); + else + { + if (entry->IsSplitByFaction()) + return player->GetTeamId(); + + return 0; + } +} + void MapManager::Update(uint32 diff) { i_timer.Update(diff); diff --git a/src/server/game/Maps/MapManager.h b/src/server/game/Maps/MapManager.h index 474972707a8..5121fd5aeac 100644 --- a/src/server/game/Maps/MapManager.h +++ b/src/server/game/Maps/MapManager.h @@ -52,6 +52,7 @@ class TC_GAME_API MapManager Map* CreateMap(uint32 mapId, Player* player); Map* FindMap(uint32 mapId, uint32 instanceId) const; + uint32 FindInstanceIdForPlayer(uint32 mapId, Player const* player) const; void Initialize(); void Update(uint32 diff); diff --git a/src/server/game/Scenarios/InstanceScenario.cpp b/src/server/game/Scenarios/InstanceScenario.cpp index 1dbb6c08359..30336a6b8f9 100644 --- a/src/server/game/Scenarios/InstanceScenario.cpp +++ b/src/server/game/Scenarios/InstanceScenario.cpp @@ -19,11 +19,13 @@ #include "DatabaseEnv.h" #include "DB2Stores.h" #include "GameTime.h" -#include "InstanceSaveMgr.h" #include "Log.h" #include "Map.h" #include "Player.h" +// TODO +// Do not save to db except for scenario type 3 (SCENARIO_TYPE_USE_DUNGEON_DISPLAY) + InstanceScenario::InstanceScenario(Map const* map, ScenarioData const* scenarioData) : Scenario(scenarioData), _map(map) { ASSERT(_map); @@ -60,8 +62,9 @@ void InstanceScenario::SaveToDB() Criteria const* criteria = sCriteriaMgr->GetCriteria(iter->first); switch (CriteriaType(criteria->Entry->Type)) { - // Blizzard only appears to store creature kills + // Blizzard only appears to store creature kills and dungeon encounters case CriteriaType::KillCreature: + case CriteriaType::DefeatDungeonEncounter: break; default: continue; @@ -127,6 +130,7 @@ void InstanceScenario::LoadInstanceData(uint32 instanceId) { // Blizzard appears to only stores creatures killed progress for unknown reasons. Either technical shortcoming or intentional case CriteriaType::KillCreature: + case CriteriaType::DefeatDungeonEncounter: break; default: continue; diff --git a/src/server/game/Scenarios/Scenario.cpp b/src/server/game/Scenarios/Scenario.cpp index 868ce78ed4b..33bf970a09a 100644 --- a/src/server/game/Scenarios/Scenario.cpp +++ b/src/server/game/Scenarios/Scenario.cpp @@ -16,7 +16,6 @@ */ #include "Scenario.h" -#include "InstanceSaveMgr.h" #include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" diff --git a/src/server/game/Server/Packets/CalendarPackets.h b/src/server/game/Server/Packets/CalendarPackets.h index 4ee6ddbfc3a..4b45b13952c 100644 --- a/src/server/game/Server/Packets/CalendarPackets.h +++ b/src/server/game/Server/Packets/CalendarPackets.h @@ -508,11 +508,11 @@ namespace WorldPackets WorldPacket const* Write() override; - int32 MapID = 0; - int32 OldTimeRemaining = 0; time_t ServerTime = 0; + int32 MapID = 0; uint32 DifficultyID = 0; int32 NewTimeRemaining = 0; + int32 OldTimeRemaining = 0; }; struct CalendarEventInitialInviteInfo diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index 4433c91fa31..741767098a8 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -44,7 +44,6 @@ class BlackMarketEntry; class CollectionMgr; class Creature; class InstanceLock; -class InstanceSave; class Item; class LoginQueryHolder; class Player; @@ -1684,8 +1683,6 @@ class TC_GAME_API WorldSession void HandleCalendarEventSignup(WorldPackets::Calendar::CalendarEventSignUp& calendarEventSignUp); void SendCalendarRaidLockoutAdded(InstanceLock const* lock); - void SendCalendarRaidLockoutUpdated(InstanceSave const* save); - void SendCalendarRaidLockoutRemoved(InstanceSave const* save); void SendCalendarRaidLockoutRemoved(InstanceLock const* lock); void HandleSetSavedInstanceExtend(WorldPackets::Calendar::SetSavedInstanceExtend& setSavedInstanceExtend); diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 8e29980fe83..4b2a8cb63a4 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -34,6 +34,7 @@ #include "GameObjectAI.h" #include "GridNotifiersImpl.h" #include "Guild.h" +#include "InstanceLockMgr.h" #include "InstanceScript.h" #include "Item.h" #include "Log.h" @@ -6219,16 +6220,13 @@ SpellCastResult Spell::CheckCast(bool strict, int32* param1 /*= nullptr*/, int32 return SPELL_FAILED_SUMMON_PENDING; // check if our map is dungeon - MapEntry const* map = sMapStore.LookupEntry(m_caster->GetMapId()); - if (map->IsDungeon()) + if (InstanceMap const* map = m_caster->GetMap()->ToInstanceMap()) { - uint32 mapId = m_caster->GetMap()->GetId(); - Difficulty difficulty = m_caster->GetMap()->GetDifficultyID(); - if (map->IsRaid()) - if (InstancePlayerBind* targetBind = target->GetBoundInstance(mapId, difficulty)) - if (InstancePlayerBind* casterBind = m_caster->ToPlayer()->GetBoundInstance(mapId, difficulty)) - if (targetBind->perm && targetBind->save != casterBind->save) - return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE; + uint32 mapId = map->GetId(); + Difficulty difficulty = map->GetDifficultyID(); + if (InstanceLock const* mapLock = map->GetInstanceLock()) + if (sInstanceLockMgr.CanJoinInstanceLock(target->GetGUID(), { mapId, difficulty }, mapLock) != TRANSFER_ABORT_NONE) + return SPELL_FAILED_TARGET_LOCKED_TO_RAID_INSTANCE; if (!target->Satisfy(sObjectMgr->GetAccessRequirement(mapId, difficulty), mapId)) return SPELL_FAILED_BAD_TARGETS; diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index cda9e94cf83..21960dc7b0a 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -59,7 +59,6 @@ #include "GroupMgr.h" #include "GuildMgr.h" #include "InstanceLockMgr.h" -#include "InstanceSaveMgr.h" #include "IPLocation.h" #include "Language.h" #include "LanguageMgr.h" @@ -1878,8 +1877,7 @@ void World::SetInitialWorldSettings() // Must be called before `respawn` data TC_LOG_INFO("server.loading", "Loading instances..."); - sInstanceSaveMgr->LoadInstances(); - + sMapMgr->InitInstanceIds(); sInstanceLockMgr.Load(); TC_LOG_INFO("server.loading", "Loading Localization strings..."); @@ -2826,12 +2824,6 @@ void World::Update(uint32 diff) sGuildMgr->SaveGuilds(); } - { - TC_METRIC_TIMER("world_update_time", TC_METRIC_TAG("type", "Update instance reset times")); - // update the instance reset times - sInstanceSaveMgr->Update(); - } - // Check for shutdown warning if (_guidWarn && !_guidAlert) { diff --git a/src/server/scripts/Commands/cs_debug.cpp b/src/server/scripts/Commands/cs_debug.cpp index 72e3ffc6838..c242f96ae94 100644 --- a/src/server/scripts/Commands/cs_debug.cpp +++ b/src/server/scripts/Commands/cs_debug.cpp @@ -37,7 +37,6 @@ EndScriptData */ #include "DB2Stores.h" #include "GameTime.h" #include "GridNotifiersImpl.h" -#include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "Language.h" #include "Log.h" @@ -1347,27 +1346,6 @@ public: return true; } - if (!difficulty) - { - handler->PSendSysMessage("Resetting all difficulties for '%s'.", mEntry->MapName[handler->GetSessionDbcLocale()]); - for (DifficultyEntry const* diff : sDifficultyStore) - { - if (sDB2Manager.GetMapDifficultyData(mapId, Difficulty(diff->ID))) - { - handler->PSendSysMessage("Resetting difficulty %d for '%s'.", diff->ID, mEntry->MapName[handler->GetSessionDbcLocale()]); - sInstanceSaveMgr->ForceGlobalReset(mapId, Difficulty(diff->ID)); - } - } - } - else if (mEntry->IsNonRaidDungeon() && *difficulty == DIFFICULTY_NORMAL) - { - handler->PSendSysMessage("'%s' does not have any permanent saves for difficulty %d.", mEntry->MapName[handler->GetSessionDbcLocale()], *difficulty); - } - else - { - handler->PSendSysMessage("Resetting difficulty %d for '%s'.", *difficulty, mEntry->MapName[handler->GetSessionDbcLocale()]); - sInstanceSaveMgr->ForceGlobalReset(mapId, Difficulty(*difficulty)); - } return true; } diff --git a/src/server/scripts/Commands/cs_instance.cpp b/src/server/scripts/Commands/cs_instance.cpp index a00853298c0..63d43b525bf 100644 --- a/src/server/scripts/Commands/cs_instance.cpp +++ b/src/server/scripts/Commands/cs_instance.cpp @@ -28,7 +28,6 @@ EndScriptData */ #include "DB2Stores.h" #include "GameTime.h" #include "Group.h" -#include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "Language.h" #include "Map.h" @@ -65,89 +64,89 @@ public: return commandTable; } - static bool HandleInstanceListBindsCommand(ChatHandler* handler) + static bool HandleInstanceListBindsCommand(ChatHandler* /*handler*/) { - Player* player = handler->getSelectedPlayer(); - if (!player) - player = handler->GetSession()->GetPlayer(); - - uint32 counter = 0; - for (DifficultyEntry const* difficulty : sDifficultyStore) - { - auto binds = player->GetBoundInstances(Difficulty(difficulty->ID)); - if (binds != player->m_boundInstances.end()) - { - for (auto const& [mapId, bind] : binds->second) - { - InstanceSave* save = bind.save; - std::string timeleft = secsToTimeString(save->GetResetTime() - GameTime::GetGameTime(), TimeFormat::ShortText); - handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, mapId, save->GetInstanceId(), bind.perm ? "yes" : "no", bind.extendState == EXTEND_STATE_EXPIRED ? "expired" : bind.extendState == EXTEND_STATE_EXTENDED ? "yes" : "no", save->GetDifficultyID(), save->CanReset() ? "yes" : "no", timeleft.c_str()); - counter++; - } - } - } - handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_PLAYER_BINDS, counter); - - counter = 0; - if (Group* group = player->GetGroup()) - { - for (DifficultyEntry const* difficulty : sDifficultyStore) - { - auto binds = group->GetBoundInstances(Difficulty(difficulty->ID)); - if (binds != group->GetBoundInstanceEnd()) - { - for (auto const& [mapId, bind] : binds->second) - { - InstanceSave* save = bind.save; - std::string timeleft = secsToTimeString(save->GetResetTime() - GameTime::GetGameTime(), TimeFormat::ShortText); - handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, mapId, save->GetInstanceId(), bind.perm ? "yes" : "no", "-", save->GetDifficultyID(), save->CanReset() ? "yes" : "no", timeleft.c_str()); - counter++; - } - } - } - } - handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_GROUP_BINDS, counter); + //Player* player = handler->getSelectedPlayer(); + //if (!player) + // player = handler->GetSession()->GetPlayer(); + + //uint32 counter = 0; + //for (DifficultyEntry const* difficulty : sDifficultyStore) + //{ + // auto binds = player->GetBoundInstances(Difficulty(difficulty->ID)); + // if (binds != player->m_boundInstances.end()) + // { + // for (auto const& [mapId, bind] : binds->second) + // { + // InstanceSave* save = bind.save; + // std::string timeleft = secsToTimeString(save->GetResetTime() - GameTime::GetGameTime(), TimeFormat::ShortText); + // handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, mapId, save->GetInstanceId(), bind.perm ? "yes" : "no", bind.extendState == EXTEND_STATE_EXPIRED ? "expired" : bind.extendState == EXTEND_STATE_EXTENDED ? "yes" : "no", save->GetDifficultyID(), save->CanReset() ? "yes" : "no", timeleft.c_str()); + // counter++; + // } + // } + //} + //handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_PLAYER_BINDS, counter); + + //counter = 0; + //if (Group* group = player->GetGroup()) + //{ + // for (DifficultyEntry const* difficulty : sDifficultyStore) + // { + // auto binds = group->GetBoundInstances(Difficulty(difficulty->ID)); + // if (binds != group->GetBoundInstanceEnd()) + // { + // for (auto const& [mapId, bind] : binds->second) + // { + // InstanceSave* save = bind.save; + // std::string timeleft = secsToTimeString(save->GetResetTime() - GameTime::GetGameTime(), TimeFormat::ShortText); + // handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, mapId, save->GetInstanceId(), bind.perm ? "yes" : "no", "-", save->GetDifficultyID(), save->CanReset() ? "yes" : "no", timeleft.c_str()); + // counter++; + // } + // } + // } + //} + //handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_GROUP_BINDS, counter); return true; } - static bool HandleInstanceUnbindCommand(ChatHandler* handler, Variant<uint32, EXACT_SEQUENCE("all")> mapArg, Optional<uint8> difficultyArg) + static bool HandleInstanceUnbindCommand(ChatHandler* /*handler*/, Variant<uint32, EXACT_SEQUENCE("all")> /*mapArg*/, Optional<uint8> /*difficultyArg*/) { - Player* player = handler->getSelectedPlayer(); - if (!player) - player = handler->GetSession()->GetPlayer(); - - uint16 counter = 0; - uint32 mapId = 0; - - if (mapArg.holds_alternative<uint32>()) - { - mapId = mapArg.get<uint32>(); - if (!mapId) - return false; - } - - for (DifficultyEntry const* difficulty : sDifficultyStore) - { - auto binds = player->GetBoundInstances(Difficulty(difficulty->ID)); - if (binds != player->m_boundInstances.end()) - { - for (auto itr = binds->second.begin(); itr != binds->second.end();) - { - InstanceSave const* save = itr->second.save; - if (itr->first != player->GetMapId() && (!mapId || mapId == itr->first) && (!difficultyArg || difficultyArg == save->GetDifficultyID())) - { - std::string timeleft = secsToTimeString(save->GetResetTime() - GameTime::GetGameTime(), TimeFormat::ShortText); - handler->PSendSysMessage(LANG_COMMAND_INST_UNBIND_UNBINDING, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficultyID(), save->CanReset() ? "yes" : "no", timeleft.c_str()); - player->UnbindInstance(itr, binds); - counter++; - } - else - ++itr; - } - } - } - handler->PSendSysMessage(LANG_COMMAND_INST_UNBIND_UNBOUND, counter); + //Player* player = handler->getSelectedPlayer(); + //if (!player) + // player = handler->GetSession()->GetPlayer(); + + //uint16 counter = 0; + //uint32 mapId = 0; + + //if (mapArg.holds_alternative<uint32>()) + //{ + // mapId = mapArg.get<uint32>(); + // if (!mapId) + // return false; + //} + + //for (DifficultyEntry const* difficulty : sDifficultyStore) + //{ + // auto binds = player->GetBoundInstances(Difficulty(difficulty->ID)); + // if (binds != player->m_boundInstances.end()) + // { + // for (auto itr = binds->second.begin(); itr != binds->second.end();) + // { + // InstanceSave const* save = itr->second.save; + // if (itr->first != player->GetMapId() && (!mapId || mapId == itr->first) && (!difficultyArg || difficultyArg == save->GetDifficultyID())) + // { + // std::string timeleft = secsToTimeString(save->GetResetTime() - GameTime::GetGameTime(), TimeFormat::ShortText); + // handler->PSendSysMessage(LANG_COMMAND_INST_UNBIND_UNBINDING, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficultyID(), save->CanReset() ? "yes" : "no", timeleft.c_str()); + // player->UnbindInstance(itr, binds); + // counter++; + // } + // else + // ++itr; + // } + // } + //} + //handler->PSendSysMessage(LANG_COMMAND_INST_UNBIND_UNBOUND, counter); return true; } @@ -156,9 +155,9 @@ public: { handler->PSendSysMessage(LANG_COMMAND_INST_STAT_LOADED_INST, sMapMgr->GetNumInstances()); handler->PSendSysMessage(LANG_COMMAND_INST_STAT_PLAYERS_IN, sMapMgr->GetNumPlayersInInstances()); - handler->PSendSysMessage(LANG_COMMAND_INST_STAT_SAVES, sInstanceSaveMgr->GetNumInstanceSaves()); - handler->PSendSysMessage(LANG_COMMAND_INST_STAT_PLAYERSBOUND, sInstanceSaveMgr->GetNumBoundPlayersTotal()); - handler->PSendSysMessage(LANG_COMMAND_INST_STAT_GROUPSBOUND, sInstanceSaveMgr->GetNumBoundGroupsTotal()); + //handler->PSendSysMessage(LANG_COMMAND_INST_STAT_SAVES, sInstanceSaveMgr->GetNumInstanceSaves()); + //handler->PSendSysMessage(LANG_COMMAND_INST_STAT_PLAYERSBOUND, sInstanceSaveMgr->GetNumBoundPlayersTotal()); + //handler->PSendSysMessage(LANG_COMMAND_INST_STAT_GROUPSBOUND, sInstanceSaveMgr->GetNumBoundGroupsTotal()); return true; } diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index 68b6d1b4d3e..32724dd6824 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -27,7 +27,6 @@ #include "DisableMgr.h" #include "GridNotifiers.h" #include "Group.h" -#include "InstanceSaveMgr.h" #include "IpAddress.h" #include "IPLocation.h" #include "Item.h" diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index efc3f3cb298..69b9b00d978 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -33,7 +33,6 @@ #include "DeadlineTimer.h" #include "GitRevision.h" #include "InstanceLockMgr.h" -#include "InstanceSaveMgr.h" #include "IoContext.h" #include "MapManager.h" #include "Metric.h" @@ -317,7 +316,6 @@ extern int main(int argc, char** argv) // unload battleground templates before different singletons destroyed sBattlegroundMgr->DeleteAllBattlegrounds(); - sInstanceSaveMgr->Unload(); sOutdoorPvPMgr->Die(); // unload it before MapManager sMapMgr->UnloadAll(); // unload all grids (including locked in memory) sTerrainMgr.UnloadAll(); |