diff --git a/conf/playerbots.conf.dist b/conf/playerbots.conf.dist index 81668a9559..22615b4071 100644 --- a/conf/playerbots.conf.dist +++ b/conf/playerbots.conf.dist @@ -544,8 +544,8 @@ AiPlayerbot.AutoGearQualityLimit = 3 # Max iLVL Phase 1(MC, Ony, ZG) = 78 | Phase 2(BWL) = 83 | Phase 2.5(AQ40) = 88 | Phase 3(Naxx40) = 92 # TBC # Max iLVL Tier 4 = 120 | Tier 5 = 133 | Tier 6 = 164 -# Max iLVL Phase 1(Kara, Gruul, Mag) = 125 | Phase 1.5(ZA) = 138 | Phase 2(SC, TK) = 141 | Phase 3(Hyjal, BT) = 156 | Phase 4(Sunwell) = 164 -# Wotlk +# Max iLVL Phase 1(Kara, Gruul, Mag) = 125 | Phase 2(SSC, TK, ZA) = 141 | Phase 3(Hyjal, BT) = 156 | Phase 4(Sunwell) = 164 +# WotLK # Max iLVL Tier 7(10/25) = 200/213 | Tier 8(10/25) = 225/232 | Tier 9(10/25) = 232/245 | Tier 10(10/25/HC) = 251/264/290 # Max iLVL Phase 1(Naxx) = 224 | Phase 2(Ulduar) = 245 | Phase 3(ToC) = 258 | Phase 4(ICC) = 290 # Default: 0 (no limit) @@ -736,7 +736,7 @@ AiPlayerbot.RandomGearQualityLimit = 3 # TBC # Max iLVL Tier 4 = 120 | Tier 5 = 133 | Tier 6 = 164 # Max iLVL Phase 1(Kara, Gruul, Mag) = 125 | Phase 2(SSC, TK, ZA) = 141 | Phase 3(Hyjal, BT) = 156 | Phase 4(Sunwell) = 164 -# Wotlk +# WotLK # Max iLVL Tier 7(10/25) = 200/213 | Tier 8(10/25) = 225/232 | Tier 9(10/25) = 232/245 | Tier 10(10/25/HC) = 251/264/290 # Max iLVL Phase 1(Naxx) = 224 | Phase 2(Ulduar) = 245 | Phase 3(ToC) = 258 | Phase 4(ICC) = 290 # Default: 0 (no limit) @@ -1624,7 +1624,7 @@ AiPlayerbot.PremadeSpecLink.9.1.60 = -003203301135112530135201051 AiPlayerbot.PremadeSpecLink.9.1.70 = -003203301135112530135201051-55 AiPlayerbot.PremadeSpecLink.9.1.80 = -003203301135112530135221351-55000005 AiPlayerbot.PremadeSpecName.9.2 = destro pve -AiPlayerbot.PremadeSpecGlyph.9.2 = 45785,43390,50077,43394,43393,42454 +AiPlayerbot.PremadeSpecGlyph.9.2 = 45785,43390,42454,43394,43393,45785 AiPlayerbot.PremadeSpecLink.9.2.60 = --05203215200231051305031151 AiPlayerbot.PremadeSpecLink.9.2.80 = 23-0302-05203215220331051335231351 AiPlayerbot.PremadeSpecName.9.3 = affli pvp diff --git a/src/Ai/Base/ActionContext.h b/src/Ai/Base/ActionContext.h index 93bba4afee..23931f62b6 100644 --- a/src/Ai/Base/ActionContext.h +++ b/src/Ai/Base/ActionContext.h @@ -43,6 +43,7 @@ #include "MoveToTravelTargetAction.h" #include "MovementActions.h" #include "NonCombatActions.h" +#include "DrinkAction.h" #include "OutfitAction.h" #include "PositionAction.h" #include "DropQuestAction.h" diff --git a/src/Ai/Base/Actions/AcceptBattlegroundInvitationAction.cpp b/src/Ai/Base/Actions/AcceptBattlegroundInvitationAction.cpp index 96d61d4ba3..e302927ac8 100644 --- a/src/Ai/Base/Actions/AcceptBattlegroundInvitationAction.cpp +++ b/src/Ai/Base/Actions/AcceptBattlegroundInvitationAction.cpp @@ -6,9 +6,9 @@ #include "AcceptBattlegroundInvitationAction.h" #include "Event.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" -bool AcceptBgInvitationAction::Execute(Event event) +bool AcceptBgInvitationAction::Execute(Event) { uint8 type = 0; // arenatype if arena uint8 unk2 = 0; // unk, can be 0x0 (may be if was invited?) and 0x1 @@ -18,9 +18,9 @@ bool AcceptBgInvitationAction::Execute(Event event) WorldPacket packet(CMSG_BATTLEFIELD_PORT, 20); packet << type << unk2 << (uint32)bgTypeId_ << unk << action; - // packet << bgTypeId_ << action; bot->GetSession()->HandleBattleFieldPortOpcode(packet); botAI->ResetStrategies(); + return true; } diff --git a/src/Ai/Base/Actions/AcceptInvitationAction.cpp b/src/Ai/Base/Actions/AcceptInvitationAction.cpp index 5e0bffc47f..1be3c0921a 100644 --- a/src/Ai/Base/Actions/AcceptInvitationAction.cpp +++ b/src/Ai/Base/Actions/AcceptInvitationAction.cpp @@ -46,10 +46,10 @@ bool AcceptInvitationAction::Execute(Event event) if (!bot->GetGroup() || !bot->GetGroup()->IsMember(inviter->GetGUID())) return false; - if (sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sRandomPlayerbotMgr.IsRandomBot(bot)) botAI->SetMaster(inviter); // else - // sPlayerbotRepository->Save(botAI); + // PlayerbotRepository::instance().Save(botAI); botAI->ResetStrategies(); botAI->ChangeStrategy("+follow,-lfg,-bg", BOT_STATE_NON_COMBAT); @@ -57,7 +57,7 @@ bool AcceptInvitationAction::Execute(Event event) botAI->TellMaster("Hello"); - if (sPlayerbotAIConfig->summonWhenGroup && bot->GetDistance(inviter) > sPlayerbotAIConfig->sightDistance) + if (sPlayerbotAIConfig.summonWhenGroup && bot->GetDistance(inviter) > sPlayerbotAIConfig.sightDistance) { Teleport(inviter, bot, true); } diff --git a/src/Ai/Base/Actions/AddLootAction.cpp b/src/Ai/Base/Actions/AddLootAction.cpp index 9e16ee2d3a..0b6a85d29a 100644 --- a/src/Ai/Base/Actions/AddLootAction.cpp +++ b/src/Ai/Base/Actions/AddLootAction.cpp @@ -22,7 +22,7 @@ bool AddLootAction::Execute(Event event) return AI_VALUE(LootObjectStack*, "available loot")->Add(guid); } -bool AddAllLootAction::Execute(Event event) +bool AddAllLootAction::Execute(Event) { bool added = false; diff --git a/src/Ai/Base/Actions/AreaTriggerAction.cpp b/src/Ai/Base/Actions/AreaTriggerAction.cpp index f480277825..77e992b5ca 100644 --- a/src/Ai/Base/Actions/AreaTriggerAction.cpp +++ b/src/Ai/Base/Actions/AreaTriggerAction.cpp @@ -50,7 +50,7 @@ bool ReachAreaTriggerAction::Execute(Event event) /*forceDestination*/ false); float distance = bot->GetDistance(at->x, at->y, at->z); - float delay = 1000.0f * distance / bot->GetSpeed(MOVE_RUN) + sPlayerbotAIConfig->reactDelay; + float delay = 1000.0f * distance / bot->GetSpeed(MOVE_RUN) + sPlayerbotAIConfig.reactDelay; botAI->TellError("Wait for me"); botAI->SetNextCheckDelay(delay); context->GetValue("last area trigger")->Get().lastAreaTrigger = triggerId; @@ -58,7 +58,7 @@ bool ReachAreaTriggerAction::Execute(Event event) return true; } -bool AreaTriggerAction::Execute(Event event) +bool AreaTriggerAction::Execute(Event) { LastMovement& movement = context->GetValue("last area trigger")->Get(); diff --git a/src/Ai/Base/Actions/AttackAction.cpp b/src/Ai/Base/Actions/AttackAction.cpp index 2b8c486f8b..87bbd31c6b 100644 --- a/src/Ai/Base/Actions/AttackAction.cpp +++ b/src/Ai/Base/Actions/AttackAction.cpp @@ -87,8 +87,8 @@ bool AttackAction::Attack(Unit* target, bool /*with_pet*/ /*true*/) // Check if bot OR target is in prohibited zone/area (skip for duels) if ((target->IsPlayer() || target->IsPet()) && (!bot->duel || bot->duel->Opponent != target) && - (sPlayerbotAIConfig->IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()) || - sPlayerbotAIConfig->IsPvpProhibited(target->GetZoneId(), target->GetAreaId()))) + (sPlayerbotAIConfig.IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()) || + sPlayerbotAIConfig.IsPvpProhibited(target->GetZoneId(), target->GetAreaId()))) { if (verbose) botAI->TellError("I cannot attack other players in PvP prohibited areas."); @@ -160,7 +160,7 @@ bool AttackAction::Attack(Unit* target, bool /*with_pet*/ /*true*/) } if (botAI->CanMove() && !bot->HasInArc(CAST_ANGLE_IN_FRONT, target)) - sServerFacade->SetFacingTo(bot, target); + ServerFacade::instance().SetFacingTo(bot, target); botAI->ChangeEngine(BOT_STATE_COMBAT); diff --git a/src/Ai/Base/Actions/AutoMaintenanceOnLevelupAction.cpp b/src/Ai/Base/Actions/AutoMaintenanceOnLevelupAction.cpp index 6939e5c925..2a92715afa 100644 --- a/src/Ai/Base/Actions/AutoMaintenanceOnLevelupAction.cpp +++ b/src/Ai/Base/Actions/AutoMaintenanceOnLevelupAction.cpp @@ -1,25 +1,26 @@ #include "AutoMaintenanceOnLevelupAction.h" -#include "GuildMgr.h" +#include "SpellMgr.h" + #include "PlayerbotAIConfig.h" #include "PlayerbotFactory.h" -#include "Playerbots.h" #include "RandomPlayerbotMgr.h" #include "SharedDefines.h" #include "BroadcastHelper.h" -bool AutoMaintenanceOnLevelupAction::Execute(Event event) +bool AutoMaintenanceOnLevelupAction::Execute(Event) { AutoPickTalents(); AutoLearnSpell(); AutoUpgradeEquip(); AutoTeleportForLevel(); + return true; } void AutoMaintenanceOnLevelupAction::AutoTeleportForLevel() { - if (!sPlayerbotAIConfig->autoTeleportForLevel || !sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sPlayerbotAIConfig.autoTeleportForLevel || !sRandomPlayerbotMgr.IsRandomBot(bot)) { return; } @@ -27,13 +28,13 @@ void AutoMaintenanceOnLevelupAction::AutoTeleportForLevel() { return; } - sRandomPlayerbotMgr->RandomTeleportForLevel(bot); + sRandomPlayerbotMgr.RandomTeleportForLevel(bot); return; } void AutoMaintenanceOnLevelupAction::AutoPickTalents() { - if (!sPlayerbotAIConfig->autoPickTalents || !sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sPlayerbotAIConfig.autoPickTalents || !sRandomPlayerbotMgr.IsRandomBot(bot)) return; if (bot->GetFreeTalentPoints() <= 0) @@ -65,14 +66,14 @@ void AutoMaintenanceOnLevelupAction::AutoLearnSpell() void AutoMaintenanceOnLevelupAction::LearnSpells(std::ostringstream* out) { BroadcastHelper::BroadcastLevelup(botAI, bot); - if (sPlayerbotAIConfig->autoLearnTrainerSpells && sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sPlayerbotAIConfig.autoLearnTrainerSpells && sRandomPlayerbotMgr.IsRandomBot(bot)) LearnTrainerSpells(out); - if (sPlayerbotAIConfig->autoLearnQuestSpells && sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sPlayerbotAIConfig.autoLearnQuestSpells && sRandomPlayerbotMgr.IsRandomBot(bot)) LearnQuestSpells(out); } -void AutoMaintenanceOnLevelupAction::LearnTrainerSpells(std::ostringstream* out) +void AutoMaintenanceOnLevelupAction::LearnTrainerSpells(std::ostringstream*) { PlayerbotFactory factory(bot, bot->GetLevel()); factory.InitSkills(); @@ -166,7 +167,7 @@ std::string const AutoMaintenanceOnLevelupAction::FormatSpell(SpellInfo const* s void AutoMaintenanceOnLevelupAction::AutoUpgradeEquip() { - if (!sPlayerbotAIConfig->autoUpgradeEquip || !sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sPlayerbotAIConfig.autoUpgradeEquip || !sRandomPlayerbotMgr.IsRandomBot(bot)) return; PlayerbotFactory factory(bot, bot->GetLevel()); @@ -180,9 +181,9 @@ void AutoMaintenanceOnLevelupAction::AutoUpgradeEquip() factory.InitConsumables(); factory.InitPotions(); - if (!sPlayerbotAIConfig->equipmentPersistence || bot->GetLevel() < sPlayerbotAIConfig->equipmentPersistenceLevel) + if (!sPlayerbotAIConfig.equipmentPersistence || bot->GetLevel() < sPlayerbotAIConfig.equipmentPersistenceLevel) { - if (sPlayerbotAIConfig->incrementalGearInit) + if (sPlayerbotAIConfig.incrementalGearInit) factory.InitEquipment(true); } } diff --git a/src/Ai/Base/Actions/BankAction.cpp b/src/Ai/Base/Actions/BankAction.cpp index 4d8d6c4d8c..1e6a0bc93f 100644 --- a/src/Ai/Base/Actions/BankAction.cpp +++ b/src/Ai/Base/Actions/BankAction.cpp @@ -27,7 +27,7 @@ bool BankAction::Execute(Event event) return false; } -bool BankAction::ExecuteBank(std::string const text, Unit* bank) +bool BankAction::ExecuteBank(std::string const text, Unit*) { if (text.empty() || text == "?") { diff --git a/src/Ai/Base/Actions/BattleGroundJoinAction.cpp b/src/Ai/Base/Actions/BattleGroundJoinAction.cpp index 542c7566ff..3107f39873 100644 --- a/src/Ai/Base/Actions/BattleGroundJoinAction.cpp +++ b/src/Ai/Base/Actions/BattleGroundJoinAction.cpp @@ -13,9 +13,8 @@ #include "PlayerbotAI.h" #include "Playerbots.h" #include "PositionValue.h" -#include "UpdateTime.h" -bool BGJoinAction::Execute(Event event) +bool BGJoinAction::Execute(Event) { uint32 queueType = AI_VALUE(uint32, "bg type"); if (!queueType) // force join to fill bg @@ -25,8 +24,6 @@ bool BGJoinAction::Execute(Event event) BattlegroundQueueTypeId queueTypeId = (BattlegroundQueueTypeId)bgList[urand(0, bgList.size() - 1)]; BattlegroundTypeId bgTypeId = BattlegroundMgr::BGTemplateId(queueTypeId); - BattlegroundBracketId bracketId; - bool isArena = false; bool isRated = false; Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(bgTypeId); @@ -38,12 +35,8 @@ bool BGJoinAction::Execute(Event event) if (!pvpDiff) return false; - bracketId = pvpDiff->GetBracketId(); - if (ArenaType type = ArenaType(BattlegroundMgr::BGArenaType(queueTypeId))) { - isArena = true; - std::vector::iterator i = find(ratedList.begin(), ratedList.end(), queueTypeId); if (i != ratedList.end()) isRated = true; @@ -89,7 +82,7 @@ bool BGJoinAction::gatherArenaTeam(ArenaType type) // continue; if (offline) - sRandomPlayerbotMgr->AddPlayerBot(itr->Guid, 0); + sRandomPlayerbotMgr.AddPlayerBot(itr->Guid, 0); if (member) { @@ -100,7 +93,7 @@ bool BGJoinAction::gatherArenaTeam(ArenaType type) if (member->GetGroup() && memberBotAI->HasRealPlayerMaster()) continue; - if (!sPlayerbotAIConfig->IsInRandomAccountList(member->GetSession()->GetAccountId())) + if (!sPlayerbotAIConfig.IsInRandomAccountList(member->GetSession()->GetAccountId())) continue; if (member->IsInCombat()) @@ -250,13 +243,13 @@ bool BGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battlegroun TeamSize = (uint32)type; // Check if bots should join Rated Arena (Only captains can queue) - uint32 ratedArenaBotCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount; + uint32 ratedArenaBotCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount; uint32 ratedArenaPlayerCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaPlayerCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaPlayerCount; uint32 ratedArenaInstanceCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaInstanceCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaInstanceCount; uint32 activeRatedArenaQueue = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].activeRatedArenaQueue; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].activeRatedArenaQueue; bool isRated = (ratedArenaBotCount + ratedArenaPlayerCount) < (BracketSize * (activeRatedArenaQueue + ratedArenaInstanceCount)); @@ -265,7 +258,7 @@ bool BGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battlegroun { if (sArenaTeamMgr->GetArenaTeamByCaptain(bot->GetGUID(), type)) { - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount += TeamSize; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount += TeamSize; ratedList.push_back(queueTypeId); return true; } @@ -274,13 +267,13 @@ bool BGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battlegroun // Check if bots should join Skirmish Arena // We have extra bots queue because same faction can vs each other but can't be in the same group. uint32 skirmishArenaBotCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaBotCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaBotCount; uint32 skirmishArenaPlayerCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaPlayerCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaPlayerCount; uint32 skirmishArenaInstanceCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaInstanceCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaInstanceCount; uint32 activeSkirmishArenaQueue = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].activeSkirmishArenaQueue; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].activeSkirmishArenaQueue; uint32 maxRequiredSkirmishBots = BracketSize * (activeSkirmishArenaQueue + skirmishArenaInstanceCount); if (maxRequiredSkirmishBots != 0) maxRequiredSkirmishBots = maxRequiredSkirmishBots + TeamSize; @@ -294,12 +287,12 @@ bool BGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battlegroun } // Check if bots should join Battleground - uint32 bgAllianceBotCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount; - uint32 bgAlliancePlayerCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgAlliancePlayerCount; - uint32 bgHordeBotCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgHordeBotCount; - uint32 bgHordePlayerCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgHordePlayerCount; - uint32 activeBgQueue = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].activeBgQueue; - uint32 bgInstanceCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgInstanceCount; + uint32 bgAllianceBotCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount; + uint32 bgAlliancePlayerCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgAlliancePlayerCount; + uint32 bgHordeBotCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgHordeBotCount; + uint32 bgHordePlayerCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgHordePlayerCount; + uint32 activeBgQueue = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].activeBgQueue; + uint32 bgInstanceCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgInstanceCount; if (teamId == TEAM_ALLIANCE) { @@ -318,7 +311,7 @@ bool BGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battlegroun bool BGJoinAction::isUseful() { // do not try if BG bots disabled - if (!sPlayerbotAIConfig->randomBotJoinBG) + if (!sPlayerbotAIConfig.randomBotJoinBG) return false; // can't queue while in BG/Arena @@ -409,8 +402,6 @@ bool BGJoinAction::JoinQueue(uint32 type) bracketId = pvpDiff->GetBracketId(); - uint32 BracketSize = bg->GetMaxPlayersPerTeam() * 2; - uint32 TeamSize = bg->GetMaxPlayersPerTeam(); TeamId teamId = bot->GetTeamId(); // check if already in queue @@ -440,7 +431,7 @@ bool BGJoinAction::JoinQueue(uint32 type) // get battlemaster // Unit* unit = botAI->GetUnit(AI_VALUE2(CreatureData const*, "bg master", bgTypeId)); - Unit* unit = botAI->GetUnit(sRandomPlayerbotMgr->GetBattleMasterGUID(bot, bgTypeId)); + Unit* unit = botAI->GetUnit(sRandomPlayerbotMgr.GetBattleMasterGUID(bot, bgTypeId)); if (!unit && isArena) { botAI->GetAiObjectContext()->GetValue("bg type")->Set(0); @@ -450,7 +441,7 @@ bool BGJoinAction::JoinQueue(uint32 type) // This breaks groups as refresh includes a remove from group function call. // refresh food/regs - // sRandomPlayerbotMgr->Refresh(bot); + // sRandomPlayerbotMgr.Refresh(bot); bool joinAsGroup = bot->GetGroup() && bot->GetGroup()->GetLeaderGUID() == bot->GetGUID(); @@ -487,8 +478,6 @@ bool BGJoinAction::JoinQueue(uint32 type) if (isArena) { isArena = true; - BracketSize = type * 2; - TeamSize = type; isRated = botAI->GetAiObjectContext()->GetValue("arena type")->Get(); if (joinAsGroup) @@ -523,23 +512,23 @@ bool BGJoinAction::JoinQueue(uint32 type) { if (!isRated) { - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaBotCount++; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaBotCount++; } } else if (!joinAsGroup) { if (teamId == TEAM_ALLIANCE) - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount++; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount++; else - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgHordeBotCount++; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgHordeBotCount++; } else { if (teamId == TEAM_ALLIANCE) - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount += + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount += bot->GetGroup()->GetMembersCount(); else - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgHordeBotCount += + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgHordeBotCount += bot->GetGroup()->GetMembersCount(); } @@ -588,13 +577,13 @@ bool FreeBGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battleg TeamSize = (uint32)type; // Check if bots should join Rated Arena (Only captains can queue) - uint32 ratedArenaBotCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount; + uint32 ratedArenaBotCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount; uint32 ratedArenaPlayerCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaPlayerCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaPlayerCount; uint32 ratedArenaInstanceCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaInstanceCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaInstanceCount; uint32 activeRatedArenaQueue = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].activeRatedArenaQueue; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].activeRatedArenaQueue; bool isRated = (ratedArenaBotCount + ratedArenaPlayerCount) < (BracketSize * (activeRatedArenaQueue + ratedArenaInstanceCount)); @@ -603,7 +592,7 @@ bool FreeBGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battleg { if (sArenaTeamMgr->GetArenaTeamByCaptain(bot->GetGUID(), type)) { - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount += TeamSize; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaBotCount += TeamSize; ratedList.push_back(queueTypeId); return true; } @@ -612,13 +601,13 @@ bool FreeBGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battleg // Check if bots should join Skirmish Arena // We have extra bots queue because same faction can vs each other but can't be in the same group. uint32 skirmishArenaBotCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaBotCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaBotCount; uint32 skirmishArenaPlayerCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaPlayerCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaPlayerCount; uint32 skirmishArenaInstanceCount = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaInstanceCount; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaInstanceCount; uint32 activeSkirmishArenaQueue = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].activeSkirmishArenaQueue; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].activeSkirmishArenaQueue; uint32 maxRequiredSkirmishBots = BracketSize * (activeSkirmishArenaQueue + skirmishArenaInstanceCount); if (maxRequiredSkirmishBots != 0) maxRequiredSkirmishBots = maxRequiredSkirmishBots + TeamSize; @@ -632,12 +621,12 @@ bool FreeBGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battleg } // Check if bots should join Battleground - uint32 bgAllianceBotCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount; - uint32 bgAlliancePlayerCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgAlliancePlayerCount; - uint32 bgHordeBotCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgHordeBotCount; - uint32 bgHordePlayerCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgHordePlayerCount; - uint32 activeBgQueue = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].activeBgQueue; - uint32 bgInstanceCount = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].bgInstanceCount; + uint32 bgAllianceBotCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgAllianceBotCount; + uint32 bgAlliancePlayerCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgAlliancePlayerCount; + uint32 bgHordeBotCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgHordeBotCount; + uint32 bgHordePlayerCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgHordePlayerCount; + uint32 activeBgQueue = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].activeBgQueue; + uint32 bgInstanceCount = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].bgInstanceCount; if (teamId == TEAM_ALLIANCE) { @@ -653,7 +642,7 @@ bool FreeBGJoinAction::shouldJoinBg(BattlegroundQueueTypeId queueTypeId, Battleg return false; } -bool BGLeaveAction::Execute(Event event) +bool BGLeaveAction::Execute(Event) { if (!(bot->InBattlegroundQueue() || bot->InBattleground())) return false; @@ -670,7 +659,7 @@ bool BGLeaveAction::Execute(Event event) uint16 unk = 0x1F90; uint8 unk2 = 0x0; bool isArena = false; - bool IsRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot); + bool IsRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot); ArenaType arenaType = ArenaType(BattlegroundMgr::BGArenaType(queueTypeId)); if (arenaType) @@ -709,7 +698,7 @@ bool BGStatusAction::LeaveBG(PlayerbotAI* botAI) if (!bg) return false; bool isArena = bg->isArena(); - bool isRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot); + bool isRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot); if (isRandomBot) botAI->SetMaster(nullptr); @@ -805,7 +794,7 @@ bool BGStatusAction::Execute(Event event) break; } - bool IsRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot); + bool IsRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot); BattlegroundQueueTypeId queueTypeId = bot->GetBattlegroundQueueTypeId(QueueSlot); BattlegroundTypeId _bgTypeId = BattlegroundMgr::BGTemplateId(queueTypeId); if (!queueTypeId) @@ -958,10 +947,10 @@ bool BGStatusAction::Execute(Event event) //TeamId teamId = bot->GetTeamId(); //not used, line marked for removal. bool realPlayers = false; if (isRated) - realPlayers = sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].ratedArenaPlayerCount > 0; + realPlayers = sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].ratedArenaPlayerCount > 0; else realPlayers = - sRandomPlayerbotMgr->BattlegroundData[queueTypeId][bracketId].skirmishArenaPlayerCount > 0; + sRandomPlayerbotMgr.BattlegroundData[queueTypeId][bracketId].skirmishArenaPlayerCount > 0; if (realPlayers) return false; @@ -1064,7 +1053,7 @@ bool BGStatusAction::Execute(Event event) return true; } -bool BGStatusCheckAction::Execute(Event event) +bool BGStatusCheckAction::Execute(Event) { if (bot->IsBeingTeleported()) return false; @@ -1080,7 +1069,7 @@ bool BGStatusCheckAction::Execute(Event event) bool BGStatusCheckAction::isUseful() { return bot->InBattlegroundQueue(); } -bool BGStrategyCheckAction::Execute(Event event) +bool BGStrategyCheckAction::Execute(Event) { bool inside_bg = bot->InBattleground() && bot->GetBattleground(); ; diff --git a/src/Ai/Base/Actions/BattleGroundTactics.cpp b/src/Ai/Base/Actions/BattleGroundTactics.cpp index 827ab01970..598e2cc939 100644 --- a/src/Ai/Base/Actions/BattleGroundTactics.cpp +++ b/src/Ai/Base/Actions/BattleGroundTactics.cpp @@ -1276,7 +1276,7 @@ static std::pair IC_AttackObjectives[] = { // useful commands for fixing BG bugs and checking waypoints/paths bool BGTactics::HandleConsoleCommand(ChatHandler* handler, char const* args) { - if (!sPlayerbotAIConfig->enabled) + if (!sPlayerbotAIConfig.enabled) { handler->PSendSysMessage("|cffff0000Playerbot system is currently disabled!"); return true; @@ -1364,8 +1364,8 @@ std::string const BGTactics::HandleConsoleCommandPrivate(WorldSession* session, } } } - uint32 min = 0u; - uint32 max = vPaths->size() - 1; + int64_t min = 0u; + int64_t max = vPaths->size() - 1; if (num >= 0) // num specified or found { if (num > max) @@ -1557,7 +1557,7 @@ bool BGTactics::eyJumpDown() // // actual bg tactics below // -bool BGTactics::Execute(Event event) +bool BGTactics::Execute(Event) { Battleground* bg = bot->GetBattleground(); if (!bg) @@ -2185,16 +2185,6 @@ bool BGTactics::selectObjective(bool reset) case 3: // Balanced defendersProhab = 3; break; - case 4: - case 5: - case 6: - case 7: // Heavy Offense - defendersProhab = 1; - break; - case 8: - case 9: // Heavy Defense - defendersProhab = 6; - break; } if (enemyStrategy == WS_STRATEGY_DEFENSIVE) @@ -2219,16 +2209,21 @@ bool BGTactics::selectObjective(bool reset) if (urand(0, 99) < 20 && teamFC) { target.Relocate(teamFC->GetPositionX(), teamFC->GetPositionY(), teamFC->GetPositionZ()); - if (sServerFacade->GetDistance2d(bot, teamFC) < 33.0f) + if (ServerFacade::instance().GetDistance2d(bot, teamFC) < 33.0f) Follow(teamFC); } else target.Relocate(enemyFC->GetPositionX(), enemyFC->GetPositionY(), enemyFC->GetPositionZ()); } // Graveyard Camping if in lead - else if (!hasFlag && role < 8 && - (team == TEAM_ALLIANCE && allianceScore == 2 && hordeScore == 0) || - (team == TEAM_HORDE && hordeScore == 2 && allianceScore == 0)) + else if ( + !hasFlag + && role < 8 + && ( + (team == TEAM_ALLIANCE && allianceScore == 2 && hordeScore == 0) + || (team == TEAM_HORDE && hordeScore == 2 && allianceScore == 0) + ) + ) { if (team == TEAM_ALLIANCE) SetSafePos(WS_GY_CAMPING_HORDE, 10.0f); @@ -2263,7 +2258,7 @@ bool BGTactics::selectObjective(bool reset) if (urand(0, 99) < 70) { target.Relocate(teamFC->GetPositionX(), teamFC->GetPositionY(), teamFC->GetPositionZ()); - if (sServerFacade->GetDistance2d(bot, teamFC) < 33.0f) + if (ServerFacade::instance().GetDistance2d(bot, teamFC) < 33.0f) Follow(teamFC); } } @@ -2284,7 +2279,7 @@ bool BGTactics::selectObjective(bool reset) { // Assist own FC if not pursuing enemy FC target.Relocate(teamFC->GetPositionX(), teamFC->GetPositionY(), teamFC->GetPositionZ()); - if (sServerFacade->GetDistance2d(bot, teamFC) < 33.0f) + if (ServerFacade::instance().GetDistance2d(bot, teamFC) < 33.0f) Follow(teamFC); } else if (urand(0, 99) < 5) @@ -2497,7 +2492,6 @@ bool BGTactics::selectObjective(bool reset) EYBotStrategy strategyHorde = static_cast(GetBotStrategyForTeam(bg, TEAM_HORDE)); EYBotStrategy strategyAlliance = static_cast(GetBotStrategyForTeam(bg, TEAM_ALLIANCE)); EYBotStrategy strategy = (team == TEAM_ALLIANCE) ? strategyAlliance : strategyHorde; - EYBotStrategy enemyStrategy = (team == TEAM_ALLIANCE) ? strategyHorde : strategyAlliance; auto IsOwned = [&](uint32 nodeId) -> bool { return eyeOfTheStormBG->GetCapturePointInfo(nodeId)._ownerTeamId == team; }; @@ -3197,11 +3191,11 @@ bool BGTactics::moveToObjective(bool ignoreDist) return true; } - if (!ignoreDist && sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(bot, pos.x, pos.y), 100.0f)) + if (!ignoreDist && ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(bot, pos.x, pos.y), 100.0f)) { // std::ostringstream out; // out << "It is too far away! " << pos.x << ", " << pos.y << ", Distance: " << - // sServerFacade->GetDistance2d(bot, pos.x, pos.y); bot->Say(out.str(), LANG_UNIVERSAL); + // ServerFacade::instance().GetDistance2d(bot, pos.x, pos.y); bot->Say(out.str(), LANG_UNIVERSAL); return false; } @@ -3213,7 +3207,7 @@ bool BGTactics::moveToObjective(bool ignoreDist) } // std::ostringstream out; out << "Moving to objective " << pos.x << ", " << pos.y << ", Distance: " << - // sServerFacade->GetDistance2d(bot, pos.x, pos.y); bot->Say(out.str(), LANG_UNIVERSAL); + // ServerFacade::instance().GetDistance2d(bot, pos.x, pos.y); bot->Say(out.str(), LANG_UNIVERSAL); // dont increase from 1.5 will cause bugs with horde capping AV towers return MoveNear(bot->GetMapId(), pos.x, pos.y, pos.z, 1.5f); @@ -3231,7 +3225,6 @@ bool BGTactics::selectObjectiveWp(std::vector const& vPaths) if (bgType == BATTLEGROUND_RB) bgType = bg->GetBgTypeID(true); - PositionMap& posMap = context->GetValue("position")->Get(); PositionInfo pos = context->GetValue("position")->Get()["bg objective"]; if (!pos.isSet()) return false; @@ -3326,7 +3319,9 @@ bool BGTactics::selectObjectiveWp(std::vector const& vPaths) // don't pick path where bot is already closest to the paths closest point to target (it means path cant lead it // anywhere) don't pick path where closest point is too far away - if (closestPointIndex == (reverse ? 0 : path->size() - 1) || closestPointDistToBot > botDistanceLimit) + const int64_t pathSize = path->size() - 1; + + if (closestPointIndex == (reverse ? 0 : pathSize) || closestPointDistToBot > botDistanceLimit) continue; // creates a score based on dist-to-bot and dist-to-destination, where lower is better, and dist-to-bot is more @@ -3433,7 +3428,7 @@ bool BGTactics::moveToObjectiveWp(BattleBotPath* const& currentPath, uint32 curr // out << "WP: "; // reverse ? out << currPoint << " <<< -> " << nPoint : out << currPoint << ">>> ->" << nPoint; // out << ", " << nextPoint.x << ", " << nextPoint.y << " Path Size: " << currentPath->size() << ", Dist: " << - // sServerFacade->GetDistance2d(bot, nextPoint.x, nextPoint.y); bot->Say(out.str(), LANG_UNIVERSAL); + // ServerFacade::instance().GetDistance2d(bot, nextPoint.x, nextPoint.y); bot->Say(out.str(), LANG_UNIVERSAL); return MoveTo(bot->GetMapId(), nextPoint.x + frand(-2, 2), nextPoint.y + frand(-2, 2), nextPoint.z); } @@ -4039,9 +4034,9 @@ bool BGTactics::useBuff() if (closeObjects.empty()) return false; - bool needRegen = bot->GetHealthPct() < sPlayerbotAIConfig->mediumHealth || + bool needRegen = bot->GetHealthPct() < sPlayerbotAIConfig.mediumHealth || (AI_VALUE2(bool, "has mana", "self target") && - AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig->mediumMana); + AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig.mediumMana); bool needSpeed = (bgType != BATTLEGROUND_WS || bot->HasAura(BG_WS_SPELL_WARSONG_FLAG) || bot->HasAura(BG_WS_SPELL_SILVERWING_FLAG) || bot->HasAura(BG_EY_NETHERSTORM_FLAG_SPELL)) || !(teamFlagTaken() || flagTaken()); @@ -4057,7 +4052,7 @@ bool BGTactics::useBuff() continue; // use speed buff only if close - if (sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(bot, go), + if (ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(bot, go), go->GetEntry() == Buff_Entries[0] ? 20.0f : 50.0f)) continue; @@ -4107,7 +4102,7 @@ uint32 BGTactics::getPlayersInArea(TeamId teamId, Position point, float range, b if (!combat && player->IsInCombat()) continue; - if (sServerFacade->GetDistance2d(player, point.GetPositionX(), point.GetPositionY()) < range) + if (ServerFacade::instance().GetDistance2d(player, point.GetPositionX(), point.GetPositionY()) < range) ++defCount; } } @@ -4191,9 +4186,9 @@ bool BGTactics::IsLockedInsideKeep() // get closest portal if (bot->GetTeamId() == TEAM_ALLIANCE && go->GetEntry() == GO_TELEPORTER_4) { - float tempDist = sServerFacade->GetDistance2d(bot, go->GetPositionX(), go->GetPositionY()); + float tempDist = ServerFacade::instance().GetDistance2d(bot, go->GetPositionX(), go->GetPositionY()); - if (sServerFacade->IsDistanceLessThan(tempDist, closestDistance)) + if (ServerFacade::instance().IsDistanceLessThan(tempDist, closestDistance)) { closestDistance = tempDist; closestPortal = go; @@ -4204,9 +4199,9 @@ bool BGTactics::IsLockedInsideKeep() // get closest portal if (bot->GetTeamId() == TEAM_HORDE && go->GetEntry() == GO_TELEPORTER_2) { - float tempDist = sServerFacade->GetDistance2d(bot, go->GetPositionX(), go->GetPositionY()); + float tempDist = ServerFacade::instance().GetDistance2d(bot, go->GetPositionX(), go->GetPositionY()); - if (sServerFacade->IsDistanceLessThan(tempDist, closestDistance)) + if (ServerFacade::instance().IsDistanceLessThan(tempDist, closestDistance)) { closestDistance = tempDist; closestPortal = go; @@ -4249,11 +4244,11 @@ bool BGTactics::IsLockedInsideKeep() return false; } -bool ArenaTactics::Execute(Event event) +bool ArenaTactics::Execute(Event) { if (!bot->InBattleground()) { - bool IsRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot->GetGUID().GetCounter()); + bool IsRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot->GetGUID().GetCounter()); botAI->ChangeStrategy("-arena", BOT_STATE_COMBAT); botAI->ChangeStrategy("-arena", BOT_STATE_NON_COMBAT); botAI->ResetStrategies(!IsRandomBot); diff --git a/src/Ai/Base/Actions/BossAuraActions.cpp b/src/Ai/Base/Actions/BossAuraActions.cpp index d711559ee5..1cd77d2035 100644 --- a/src/Ai/Base/Actions/BossAuraActions.cpp +++ b/src/Ai/Base/Actions/BossAuraActions.cpp @@ -18,7 +18,7 @@ bool BossFireResistanceAction::isUseful() return bossFireResistanceTrigger.IsActive(); } -bool BossFireResistanceAction::Execute(Event event) +bool BossFireResistanceAction::Execute(Event) { PaladinFireResistanceStrategy paladinFireResistanceStrategy(botAI); botAI->ChangeStrategy(ADD_STRATEGY_CHAR + paladinFireResistanceStrategy.getName(), BotState::BOT_STATE_COMBAT); @@ -32,7 +32,7 @@ bool BossFrostResistanceAction::isUseful() return bossFrostResistanceTrigger.IsActive(); } -bool BossFrostResistanceAction::Execute(Event event) +bool BossFrostResistanceAction::Execute(Event) { PaladinFrostResistanceStrategy paladinFrostResistanceStrategy(botAI); botAI->ChangeStrategy(ADD_STRATEGY_CHAR + paladinFrostResistanceStrategy.getName(), BotState::BOT_STATE_COMBAT); @@ -46,7 +46,7 @@ bool BossNatureResistanceAction::isUseful() return bossNatureResistanceTrigger.IsActive(); } -bool BossNatureResistanceAction::Execute(Event event) +bool BossNatureResistanceAction::Execute(Event) { HunterNatureResistanceStrategy hunterNatureResistanceStrategy(botAI); botAI->ChangeStrategy(ADD_STRATEGY_CHAR + hunterNatureResistanceStrategy.getName(), BotState::BOT_STATE_COMBAT); @@ -60,7 +60,7 @@ bool BossShadowResistanceAction::isUseful() return bossShadowResistanceTrigger.IsActive(); } -bool BossShadowResistanceAction::Execute(Event event) +bool BossShadowResistanceAction::Execute(Event) { PaladinShadowResistanceStrategy paladinShadowResistanceStrategy(botAI); botAI->ChangeStrategy(ADD_STRATEGY_CHAR + paladinShadowResistanceStrategy.getName(), BotState::BOT_STATE_COMBAT); diff --git a/src/Ai/Base/Actions/CancelChannelAction.cpp b/src/Ai/Base/Actions/CancelChannelAction.cpp index 9f359f392b..314430844f 100644 --- a/src/Ai/Base/Actions/CancelChannelAction.cpp +++ b/src/Ai/Base/Actions/CancelChannelAction.cpp @@ -7,12 +7,14 @@ #include "Player.h" #include "PlayerbotAI.h" -bool CancelChannelAction::Execute(Event event) +bool CancelChannelAction::Execute(Event) { if (bot->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) { bot->InterruptSpell(CURRENT_CHANNELED_SPELL); + return true; } + return false; } diff --git a/src/Ai/Base/Actions/CastCustomSpellAction.cpp b/src/Ai/Base/Actions/CastCustomSpellAction.cpp index 417ffb50d3..48c61f3902 100644 --- a/src/Ai/Base/Actions/CastCustomSpellAction.cpp +++ b/src/Ai/Base/Actions/CastCustomSpellAction.cpp @@ -130,10 +130,10 @@ bool CastCustomSpellAction::Execute(Event event) return false; } - if (target != bot && !bot->HasInArc(CAST_ANGLE_IN_FRONT, target, sPlayerbotAIConfig->sightDistance)) + if (target != bot && !bot->HasInArc(CAST_ANGLE_IN_FRONT, target, sPlayerbotAIConfig.sightDistance)) { - sServerFacade->SetFacingTo(bot, target); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + ServerFacade::instance().SetFacingTo(bot, target); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); msg << "cast " << text; botAI->HandleCommand(CHAT_MSG_WHISPER, msg.str(), master); @@ -286,7 +286,7 @@ bool CastRandomSpellAction::Execute(Event event) if (isCast) { - if (MultiCast && ((wo && bot->HasInArc(CAST_ANGLE_IN_FRONT, wo, sPlayerbotAIConfig->sightDistance)))) + if (MultiCast && ((wo && bot->HasInArc(CAST_ANGLE_IN_FRONT, wo, sPlayerbotAIConfig.sightDistance)))) { std::ostringstream cmd; cmd << "castnc " << chat->FormatWorldobject(wo) + " " << spellId << " " << 19; @@ -334,7 +334,7 @@ bool CastRandomSpellAction::castSpell(uint32 spellId, WorldObject* wo) return botAI->CastSpell(spellId, wo->GetPositionX(), wo->GetPositionY(), wo->GetPositionZ()); } -bool DisEnchantRandomItemAction::Execute(Event event) +bool DisEnchantRandomItemAction::Execute(Event) { std::vector items = AI_VALUE2(std::vector, "inventory items", "usage " + std::to_string(ITEM_USAGE_DISENCHANT)); diff --git a/src/Ai/Base/Actions/CastCustomSpellAction.h b/src/Ai/Base/Actions/CastCustomSpellAction.h index ed53b18a5a..67bbb6ccc5 100644 --- a/src/Ai/Base/Actions/CastCustomSpellAction.h +++ b/src/Ai/Base/Actions/CastCustomSpellAction.h @@ -21,7 +21,7 @@ class CastCustomSpellAction : public InventoryAction } bool Execute(Event event) override; - virtual std::string const castString(WorldObject* target) { return "cast"; } + virtual std::string const castString(WorldObject*) { return "cast"; } protected: bool ncCast = false; @@ -49,7 +49,7 @@ class CastRandomSpellAction : public ListSpellsAction bool isUseful() override { return false; } virtual bool AcceptSpell(SpellInfo const* spellInfo); - virtual uint32 GetSpellPriority(SpellInfo const* spellInfo) { return 1; } + virtual uint32 GetSpellPriority(SpellInfo const*) { return 1; } virtual bool castSpell(uint32 spellId, WorldObject* wo); bool Execute(Event event) override; diff --git a/src/Ai/Base/Actions/ChangeStrategyAction.cpp b/src/Ai/Base/Actions/ChangeStrategyAction.cpp index d17cd005d3..b4fe5faaf2 100644 --- a/src/Ai/Base/Actions/ChangeStrategyAction.cpp +++ b/src/Ai/Base/Actions/ChangeStrategyAction.cpp @@ -24,7 +24,7 @@ bool ChangeCombatStrategyAction::Execute(Event event) case '+': case '-': case '~': - sPlayerbotRepository->Save(botAI); + PlayerbotRepository::instance().Save(botAI); break; case '?': break; @@ -40,7 +40,7 @@ bool ChangeNonCombatStrategyAction::Execute(Event event) std::string const text = event.getParam(); uint32 account = bot->GetSession()->GetAccountId(); - if (sPlayerbotAIConfig->IsInRandomAccountList(account) && botAI->GetMaster() && + if (sPlayerbotAIConfig.IsInRandomAccountList(account) && botAI->GetMaster() && botAI->GetMaster()->GetSession()->GetSecurity() < SEC_GAMEMASTER) { if (text.find("loot") != std::string::npos || text.find("gather") != std::string::npos) @@ -62,7 +62,7 @@ bool ChangeNonCombatStrategyAction::Execute(Event event) case '+': case '-': case '~': - sPlayerbotRepository->Save(botAI); + PlayerbotRepository::instance().Save(botAI); break; case '?': break; diff --git a/src/Ai/Base/Actions/ChangeTalentsAction.cpp b/src/Ai/Base/Actions/ChangeTalentsAction.cpp index c50e4a9274..a2c6f1e34b 100644 --- a/src/Ai/Base/Actions/ChangeTalentsAction.cpp +++ b/src/Ai/Base/Actions/ChangeTalentsAction.cpp @@ -10,9 +10,9 @@ #include "Event.h" #include "PlayerbotAIConfig.h" #include "PlayerbotFactory.h" -#include "Playerbots.h" #include "AiObjectContext.h" #include "Log.h" +#include "RandomPlayerbotMgr.h" bool ChangeTalentsAction::Execute(Event event) { @@ -110,20 +110,20 @@ std::string ChangeTalentsAction::SpecList() std::ostringstream out; for (int specNo = 0; specNo < MAX_SPECNO; ++specNo) { - if (sPlayerbotAIConfig->premadeSpecName[cls][specNo].size() == 0) + if (sPlayerbotAIConfig.premadeSpecName[cls][specNo].size() == 0) { break; } specFound++; std::ostringstream out; - std::vector> parsed = sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specNo][80]; + std::vector> parsed = sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specNo][80]; std::unordered_map tabCount; tabCount[0] = tabCount[1] = tabCount[2] = 0; for (auto& item : parsed) { tabCount[item[0]] += item[3]; } - out << specFound << ". " << sPlayerbotAIConfig->premadeSpecName[cls][specNo] << " ("; + out << specFound << ". " << sPlayerbotAIConfig.premadeSpecName[cls][specNo] << " ("; out << tabCount[0] << "-" << tabCount[1] << "-" << tabCount[2] << ")"; botAI->TellMasterNoFacing(out.str()); } @@ -137,11 +137,11 @@ std::string ChangeTalentsAction::SpecPick(std::string param) // int specFound = 0; //not used, line marked for removal. for (int specNo = 0; specNo < MAX_SPECNO; ++specNo) { - if (sPlayerbotAIConfig->premadeSpecName[cls][specNo].size() == 0) + if (sPlayerbotAIConfig.premadeSpecName[cls][specNo].size() == 0) { break; } - if (sPlayerbotAIConfig->premadeSpecName[cls][specNo] == param) + if (sPlayerbotAIConfig.premadeSpecName[cls][specNo] == param) { PlayerbotFactory::InitTalentsBySpecNo(bot, specNo, true); @@ -149,7 +149,7 @@ std::string ChangeTalentsAction::SpecPick(std::string param) factory.InitGlyphs(false); std::ostringstream out; - out << "Picking " << sPlayerbotAIConfig->premadeSpecName[cls][specNo]; + out << "Picking " << sPlayerbotAIConfig.premadeSpecName[cls][specNo]; return out.str(); } } @@ -176,7 +176,7 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // std::vector ChangeTalentsAction::getPremadePaths(std::string const findName) // { // std::vector ret; -// // for (auto& path : sPlayerbotAIConfig->classSpecs[bot->getClass()].talentPath) +// // for (auto& path : sPlayerbotAIConfig.classSpecs[bot->getClass()].talentPath) // // { // // if (findName.empty() || path.name.find(findName) != std::string::npos) // // { @@ -191,7 +191,7 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // { // std::vector ret; -// // for (auto& path : sPlayerbotAIConfig->classSpecs[bot->getClass()].talentPath) +// // for (auto& path : sPlayerbotAIConfig.classSpecs[bot->getClass()].talentPath) // // { // // TalentSpec newSpec = *GetBestPremadeSpec(path.id); // // newSpec.CropTalents(bot->GetLevel()); @@ -206,7 +206,7 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // TalentPath* ChangeTalentsAction::getPremadePath(uint32 id) // { -// // for (auto& path : sPlayerbotAIConfig->classSpecs[bot->getClass()].talentPath) +// // for (auto& path : sPlayerbotAIConfig.classSpecs[bot->getClass()].talentPath) // // { // // if (id == path.id) // // { @@ -214,7 +214,7 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // // } // // } -// // return &sPlayerbotAIConfig->classSpecs[bot->getClass()].talentPath[0]; +// // return &sPlayerbotAIConfig.classSpecs[bot->getClass()].talentPath[0]; // return nullptr; // } @@ -270,9 +270,9 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // return false; // } -// uint32 specNo = sRandomPlayerbotMgr->GetValue(bot->GetGUID().GetCounter(), "specNo"); +// uint32 specNo = sRandomPlayerbotMgr.GetValue(bot->GetGUID().GetCounter(), "specNo"); // uint32 specId = specNo - 1; -// std::string specLink = sRandomPlayerbotMgr->GetData(bot->GetGUID().GetCounter(), "specLink"); +// std::string specLink = sRandomPlayerbotMgr.GetData(bot->GetGUID().GetCounter(), "specLink"); // //Continue the current spec // if (specNo > 0) @@ -319,15 +319,15 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // specId = -1; // // specLink = ""; // } -// else if (paths.size() > 1 && false/*!sPlayerbotAIConfig->autoPickTalents*/ && -// !sRandomPlayerbotMgr->IsRandomBot(bot)) +// else if (paths.size() > 1 && false/*!sPlayerbotAIConfig.autoPickTalents*/ && +// !sRandomPlayerbotMgr.IsRandomBot(bot)) // { // *out << "Found multiple specs: "; // listPremadePaths(paths, out); // } // else // { -// specId = PickPremadePath(paths, sRandomPlayerbotMgr->IsRandomBot(bot))->id; +// specId = PickPremadePath(paths, sRandomPlayerbotMgr.IsRandomBot(bot))->id; // TalentSpec newSpec = *GetBestPremadeSpec(specId); // specLink = newSpec.GetTalentLink(); // newSpec.CropTalents(bot->GetLevel()); @@ -341,12 +341,12 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // } // } -// sRandomPlayerbotMgr->SetValue(bot->GetGUID().GetCounter(), "specNo", specId + 1); +// sRandomPlayerbotMgr.SetValue(bot->GetGUID().GetCounter(), "specNo", specId + 1); // if (!specLink.empty() && specId == -1) -// sRandomPlayerbotMgr->SetValue(bot->GetGUID().GetCounter(), "specLink", 1, specLink); +// sRandomPlayerbotMgr.SetValue(bot->GetGUID().GetCounter(), "specLink", 1, specLink); // else -// sRandomPlayerbotMgr->SetValue(bot->GetGUID().GetCounter(), "specLink", 0); +// sRandomPlayerbotMgr.SetValue(bot->GetGUID().GetCounter(), "specLink", 0); // return (specNo == 0) ? false : true; // } @@ -364,15 +364,15 @@ std::string ChangeTalentsAction::SpecApply(std::string param) // if (path->talentSpec.size()) // return &path->talentSpec.back(); -// // return &sPlayerbotAIConfig->classSpecs[bot->getClassMask()].baseSpec; +// // return &sPlayerbotAIConfig.classSpecs[bot->getClassMask()].baseSpec; // return nullptr; // } -bool AutoSetTalentsAction::Execute(Event event) +bool AutoSetTalentsAction::Execute(Event) { std::ostringstream out; - if (!sPlayerbotAIConfig->autoPickTalents || !sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!PlayerbotAIConfig::instance().autoPickTalents || !RandomPlayerbotMgr::instance().IsRandomBot(bot)) return false; if (bot->GetFreeTalentPoints() <= 0) diff --git a/src/Ai/Base/Actions/ChatShortcutActions.cpp b/src/Ai/Base/Actions/ChatShortcutActions.cpp index 02c306b8f7..18a417c35e 100644 --- a/src/Ai/Base/Actions/ChatShortcutActions.cpp +++ b/src/Ai/Base/Actions/ChatShortcutActions.cpp @@ -42,7 +42,7 @@ void PositionsResetAction::SetStayPosition(float x, float y, float z) posMap["stay"] = pos; } -bool FollowChatShortcutAction::Execute(Event event) +bool FollowChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -74,7 +74,7 @@ bool FollowChatShortcutAction::Execute(Event event) else { WorldLocation loc = formation->GetLocation(); - if (Formation::IsNullLocation(loc) || loc.GetMapId() == -1) + if (Formation::IsNullLocation(loc)) return false; MovementPriority priority = botAI->GetState() == BOT_STATE_COMBAT ? MovementPriority::MOVEMENT_COMBAT : MovementPriority::MOVEMENT_NORMAL; @@ -82,7 +82,7 @@ bool FollowChatShortcutAction::Execute(Event event) true, priority); } - if (Pet* pet = bot->GetPet()) + if (bot->GetPet() != nullptr) { botAI->PetFollow(); } @@ -96,7 +96,7 @@ bool FollowChatShortcutAction::Execute(Event event) /* Default mechanics takes care of this now. if (bot->GetMapId() != master->GetMapId() || (master && bot->GetDistance(master) > - sPlayerbotAIConfig->sightDistance)) + sPlayerbotAIConfig.sightDistance)) { if (bot->isDead()) { @@ -116,7 +116,7 @@ bool FollowChatShortcutAction::Execute(Event event) return true; } -bool StayChatShortcutAction::Execute(Event event) +bool StayChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -133,7 +133,7 @@ bool StayChatShortcutAction::Execute(Event event) return true; } -bool MoveFromGroupChatShortcutAction::Execute(Event event) +bool MoveFromGroupChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -148,7 +148,7 @@ bool MoveFromGroupChatShortcutAction::Execute(Event event) return true; } -bool FleeChatShortcutAction::Execute(Event event) +bool FleeChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -161,7 +161,7 @@ bool FleeChatShortcutAction::Execute(Event event) ResetReturnPosition(); ResetStayPosition(); - if (bot->GetMapId() != master->GetMapId() || bot->GetDistance(master) > sPlayerbotAIConfig->sightDistance) + if (bot->GetMapId() != master->GetMapId() || bot->GetDistance(master) > sPlayerbotAIConfig.sightDistance) { botAI->TellError("I will not flee with you - too far away"); return true; @@ -171,7 +171,7 @@ bool FleeChatShortcutAction::Execute(Event event) return true; } -bool GoawayChatShortcutAction::Execute(Event event) +bool GoawayChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -188,7 +188,7 @@ bool GoawayChatShortcutAction::Execute(Event event) return true; } -bool GrindChatShortcutAction::Execute(Event event) +bool GrindChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -204,7 +204,7 @@ bool GrindChatShortcutAction::Execute(Event event) return true; } -bool TankAttackChatShortcutAction::Execute(Event event) +bool TankAttackChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -224,7 +224,7 @@ bool TankAttackChatShortcutAction::Execute(Event event) return true; } -bool MaxDpsChatShortcutAction::Execute(Event event) +bool MaxDpsChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) @@ -241,7 +241,7 @@ bool MaxDpsChatShortcutAction::Execute(Event event) return true; } -bool BwlChatShortcutAction::Execute(Event event) +bool BwlChatShortcutAction::Execute(Event) { Player* master = GetMaster(); if (!master) diff --git a/src/Ai/Base/Actions/CheatAction.cpp b/src/Ai/Base/Actions/CheatAction.cpp index b3f4ec5cf7..790134e953 100644 --- a/src/Ai/Base/Actions/CheatAction.cpp +++ b/src/Ai/Base/Actions/CheatAction.cpp @@ -86,7 +86,7 @@ void CheatAction::ListCheats() for (int i = 0; i < log2((uint32)BotCheatMask::maxMask); i++) { BotCheatMask cheatMask = BotCheatMask(1 << i); - if ((uint32)cheatMask & (uint32)sPlayerbotAIConfig->botCheatMask) + if ((uint32)cheatMask & (uint32)sPlayerbotAIConfig.botCheatMask) out << "[conf:" << GetCheatName(BotCheatMask(cheatMask)) << "]"; else if (botAI->HasCheat(cheatMask)) out << "[" << GetCheatName(BotCheatMask(cheatMask)) << "]"; diff --git a/src/Ai/Base/Actions/CheckMailAction.cpp b/src/Ai/Base/Actions/CheckMailAction.cpp index 85df168f58..25c82a0ade 100644 --- a/src/Ai/Base/Actions/CheckMailAction.cpp +++ b/src/Ai/Base/Actions/CheckMailAction.cpp @@ -7,9 +7,10 @@ #include "Event.h" #include "GuildTaskMgr.h" -#include "Playerbots.h" +#include "PlayerbotAIConfig.h" +#include "PlayerbotAI.h" -bool CheckMailAction::Execute(Event event) +bool CheckMailAction::Execute(Event) { WorldPacket p; bot->GetSession()->HandleQueryNextMailTime(p); @@ -28,7 +29,7 @@ bool CheckMailAction::Execute(Event event) continue; uint32 account = owner->GetSession()->GetAccountId(); - if (sPlayerbotAIConfig->IsInRandomAccountList(account)) + if (PlayerbotAIConfig::instance().IsInRandomAccountList(account)) continue; ProcessMail(mail, owner, trans); @@ -80,7 +81,7 @@ void CheckMailAction::ProcessMail(Mail* mail, Player* owner, CharacterDatabaseTr if (!item) continue; - if (!sGuildTaskMgr->CheckItemTask(i->item_template, item->GetCount(), owner, bot, true)) + if (!GuildTaskMgr::instance().CheckItemTask(i->item_template, item->GetCount(), owner, bot, true)) { std::ostringstream body; body << "Hello, " << owner->GetName() << ",\n"; diff --git a/src/Ai/Base/Actions/CheckMountStateAction.cpp b/src/Ai/Base/Actions/CheckMountStateAction.cpp index bf7a3a169a..5ab7cc0f92 100644 --- a/src/Ai/Base/Actions/CheckMountStateAction.cpp +++ b/src/Ai/Base/Actions/CheckMountStateAction.cpp @@ -89,7 +89,7 @@ bool CheckMountStateAction::isUseful() return false; // Not useful when level lower than minimum required - if (bot->GetLevel() < sPlayerbotAIConfig->useGroundMountAtMinLevel) + if (bot->GetLevel() < sPlayerbotAIConfig.useGroundMountAtMinLevel) return false; // Allow mounting while transformed only if the form allows it @@ -402,7 +402,7 @@ float CheckMountStateAction::CalculateDismountDistance() const // Warrior bots should dismount far enough to charge (because it's important for generating some initial rage), // a real player would be riding toward enemy mashing the charge key but the bots won't cast charge while mounted. bool isMelee = PlayerbotAI::IsMelee(bot); - float dismountDistance = isMelee ? sPlayerbotAIConfig->meleeDistance + 2.0f : sPlayerbotAIConfig->spellDistance + 2.0f; + float dismountDistance = isMelee ? sPlayerbotAIConfig.meleeDistance + 2.0f : sPlayerbotAIConfig.spellDistance + 2.0f; return bot->getClass() == CLASS_WARRIOR ? std::max(18.0f, dismountDistance) : dismountDistance; } @@ -413,7 +413,7 @@ float CheckMountStateAction::CalculateMountDistance() const // seconds: // 21 / 7 = 21 / 14 + 1.5 = 3 (7 = dismounted speed 14 = epic-mount speed 1.5 = mount-spell cast time) bool isMelee = PlayerbotAI::IsMelee(bot); - float baseDistance = isMelee ? sPlayerbotAIConfig->meleeDistance + 10.0f : sPlayerbotAIConfig->spellDistance + 10.0f; + float baseDistance = isMelee ? sPlayerbotAIConfig.meleeDistance + 10.0f : sPlayerbotAIConfig.spellDistance + 10.0f; return std::max(21.0f, baseDistance); } @@ -440,7 +440,7 @@ int32 CheckMountStateAction::CalculateMasterMountSpeed(Player* master, const Mou int32 ridingSkill = bot->GetPureSkillValue(SKILL_RIDING); int32 botLevel = bot->GetLevel(); - if (ridingSkill <= 75 && botLevel < static_cast(sPlayerbotAIConfig->useFastGroundMountAtMinLevel)) + if (ridingSkill <= 75 && botLevel < static_cast(sPlayerbotAIConfig.useFastGroundMountAtMinLevel)) return 59; // If there is a master and bot not in BG, use master's aura effects. diff --git a/src/Ai/Base/Actions/CheckValuesAction.cpp b/src/Ai/Base/Actions/CheckValuesAction.cpp index 1fc0d4c3a1..2b001d82f9 100644 --- a/src/Ai/Base/Actions/CheckValuesAction.cpp +++ b/src/Ai/Base/Actions/CheckValuesAction.cpp @@ -6,12 +6,15 @@ #include "CheckValuesAction.h" #include "Event.h" -#include "Playerbots.h" #include "ServerFacade.h" +#include "PlayerbotAI.h" +#include "TravelNode.h" +#include "AiObjectContext.h" + CheckValuesAction::CheckValuesAction(PlayerbotAI* botAI) : Action(botAI, "check values") {} -bool CheckValuesAction::Execute(Event event) +bool CheckValuesAction::Execute(Event) { if (botAI->HasStrategy("debug move", BOT_STATE_NON_COMBAT)) { @@ -20,7 +23,7 @@ bool CheckValuesAction::Execute(Event event) if (botAI->HasStrategy("map", BOT_STATE_NON_COMBAT) || botAI->HasStrategy("map full", BOT_STATE_NON_COMBAT)) { - sTravelNodeMap->manageNodes(bot, botAI->HasStrategy("map full", BOT_STATE_NON_COMBAT)); + TravelNodeMap::instance().manageNodes(bot, botAI->HasStrategy("map full", BOT_STATE_NON_COMBAT)); } GuidVector possible_targets = *context->GetValue("possible targets"); diff --git a/src/Ai/Base/Actions/ChooseRpgTargetAction.cpp b/src/Ai/Base/Actions/ChooseRpgTargetAction.cpp index a888aa14ee..8893b0f747 100644 --- a/src/Ai/Base/Actions/ChooseRpgTargetAction.cpp +++ b/src/Ai/Base/Actions/ChooseRpgTargetAction.cpp @@ -6,7 +6,6 @@ #include #include "ChooseRpgTargetAction.h" -#include "BattlegroundMgr.h" #include "BudgetValues.h" #include "ChatHelper.h" #include "Event.h" @@ -14,7 +13,6 @@ #include "GuildCreateActions.h" #include "Playerbots.h" #include "RpgSubActions.h" -#include "Util.h" #include "ServerFacade.h" #include "PossibleRpgTargetsValue.h" @@ -112,21 +110,17 @@ float ChooseRpgTargetAction::getMaxRelevance(GuidPosition guidP) return floor((maxRelevance - 1.0) * 1000.0f); } -bool ChooseRpgTargetAction::Execute(Event event) +bool ChooseRpgTargetAction::Execute(Event) { - //TravelTarget* travelTarget = AI_VALUE(TravelTarget*, "travel target"); //not used, line marked for removal. Player* master = botAI->GetMaster(); GuidPosition masterRpgTarget; - if (master && master != bot && GET_PLAYERBOT_AI(master) && master->GetMapId() == bot->GetMapId() && !master->IsBeingTeleported()) + + if (master == nullptr || master == bot || GET_PLAYERBOT_AI(master) == nullptr || master->GetMapId() != bot->GetMapId() || master->IsBeingTeleported()) { - Player* player = botAI->GetMaster(); - //GuidPosition masterRpgTarget = PAI_VALUE(GuidPosition, "rpg target"); //not used, line marked for removal. - } - else master = nullptr; + } std::unordered_map targets; - // uint32 num = 0; //not used, line marked for removal. GuidVector possibleTargets = AI_VALUE(GuidVector, "possible rpg targets"); GuidVector possibleObjects = AI_VALUE(GuidVector, "nearest game objects no los"); GuidVector possiblePlayers = AI_VALUE(GuidVector, "nearest friendly players"); @@ -248,7 +242,7 @@ bool ChooseRpgTargetAction::Execute(Event event) } std::mt19937 gen(time(0)); - sTravelMgr->weighted_shuffle(guidps.begin(), guidps.end(), relevances.begin(), relevances.end(), gen); + TravelMgr::instance().weighted_shuffle(guidps.begin(), guidps.end(), relevances.begin(), relevances.end(), gen); GuidPosition guidP(guidps.front()); if (!guidP) @@ -279,7 +273,7 @@ bool ChooseRpgTargetAction::isUseful() GuidPosition guidP = AI_VALUE(GuidPosition, "rpg target"); - if (guidP && guidP.distance(bot) < sPlayerbotAIConfig->reactDistance * 2) + if (guidP && guidP.distance(bot) < sPlayerbotAIConfig.reactDistance * 2) return false; // TravelTarget* travelTarget = AI_VALUE(TravelTarget*, "travel target"); //not used, line marked for removal. @@ -330,7 +324,7 @@ bool ChooseRpgTargetAction::isFollowValid(Player* bot, WorldPosition pos) if (!botAI->HasStrategy("follow", BOT_STATE_NON_COMBAT)) return true; - if (bot->GetDistance(groupLeader) > sPlayerbotAIConfig->rpgDistance * 2) + if (bot->GetDistance(groupLeader) > sPlayerbotAIConfig.rpgDistance * 2) return false; Formation* formation = AI_VALUE(Formation*, "formation"); @@ -339,8 +333,14 @@ bool ChooseRpgTargetAction::isFollowValid(Player* bot, WorldPosition pos) if (!botAI->HasActivePlayerMaster() && distance < 50.0f) { Player* player = groupLeader; - if (groupLeader && !groupLeader->isMoving() || - PAI_VALUE(WorldPosition, "last long move").distance(pos) < sPlayerbotAIConfig->reactDistance) + + if ( + ( + groupLeader != nullptr + && !groupLeader->isMoving() + ) + || PAI_VALUE(WorldPosition, "last long move").distance(pos) < sPlayerbotAIConfig.reactDistance + ) return true; } diff --git a/src/Ai/Base/Actions/ChooseTargetActions.cpp b/src/Ai/Base/Actions/ChooseTargetActions.cpp index ab533e7136..793f61000e 100644 --- a/src/Ai/Base/Actions/ChooseTargetActions.cpp +++ b/src/Ai/Base/Actions/ChooseTargetActions.cpp @@ -20,13 +20,13 @@ bool AttackEnemyPlayerAction::isUseful() if (PlayerHasFlag::IsCapturingFlag(bot)) return false; - return !sPlayerbotAIConfig->IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()); + return !sPlayerbotAIConfig.IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()); } bool AttackEnemyFlagCarrierAction::isUseful() { Unit* target = context->GetValue("enemy flag carrier")->Get(); - return target && sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, target), 100.0f) && + return target && ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, target), 100.0f) && PlayerHasFlag::IsCapturingFlag(bot); } @@ -61,7 +61,7 @@ bool AttackAnythingAction::isUseful() return true; } -bool DropTargetAction::Execute(Event event) +bool DropTargetAction::Execute(Event) { Unit* target = context->GetValue("current target")->Get(); if (target && target->isDead()) @@ -111,20 +111,30 @@ bool DropTargetAction::Execute(Event event) bool AttackAnythingAction::Execute(Event event) { bool result = AttackAction::Execute(event); - if (result) + + if (!result) { - if (Unit* grindTarget = GetTarget()) - { - if (char const* grindName = grindTarget->GetName().c_str()) - { - context->GetValue("pull target")->Set(grindTarget->GetGUID()); - bot->GetMotionMaster()->Clear(); - // bot->StopMoving(); - } - } + return false; + } + + const Unit* const grindTarget = this->GetTarget(); + + if (grindTarget == nullptr) + { + return true; + } + + const std::string& grindTargetName = grindTarget->GetName(); + + if (grindTargetName.empty()) + { + return true; } - return result; + this->context->GetValue("pull target")->Set(grindTarget->GetGUID()); + this->bot->GetMotionMaster()->Clear(); + + return true; } bool AttackAnythingAction::isPossible() { return AttackAction::isPossible() && GetTarget(); } @@ -137,7 +147,7 @@ bool DpsAssistAction::isUseful() return true; } -bool AttackRtiTargetAction::Execute(Event event) +bool AttackRtiTargetAction::Execute(Event) { Unit* rtiTarget = AI_VALUE(Unit*, "rti target"); diff --git a/src/Ai/Base/Actions/ChooseTravelTargetAction.cpp b/src/Ai/Base/Actions/ChooseTravelTargetAction.cpp index cf6dddd40c..761efc5b62 100644 --- a/src/Ai/Base/Actions/ChooseTravelTargetAction.cpp +++ b/src/Ai/Base/Actions/ChooseTravelTargetAction.cpp @@ -9,7 +9,7 @@ #include "LootObjectStack.h" #include "Playerbots.h" -bool ChooseTravelTargetAction::Execute(Event event) +bool ChooseTravelTargetAction::Execute(Event) { // Player* requester = event.getOwner() ? event.getOwner() : GetMaster(); //not used, line marked for removal. @@ -103,13 +103,13 @@ void ChooseTravelTargetAction::getNewTarget(TravelTarget* newTarget, TravelTarge if (urand(1, 100) > 50) { // Turn in quests for money. - foundTarget = SetQuestTarget(newTarget, true, false, true, true); + foundTarget = SetQuestTarget(newTarget, false, true, true); } if (!foundTarget) { // Find new (low) level quests - foundTarget = SetQuestTarget(newTarget, false, true, false, false); + foundTarget = SetQuestTarget(newTarget, true, false, false); } } else @@ -150,7 +150,7 @@ void ChooseTravelTargetAction::getNewTarget(TravelTarget* newTarget, TravelTarge if (!foundTarget && urand(1, 100) > 5) { // Do any nearby - foundTarget = SetQuestTarget(newTarget, false, true, true, true); + foundTarget = SetQuestTarget(newTarget, true, true, true); } //Explore a nearby unexplored area. @@ -232,15 +232,6 @@ void ChooseTravelTargetAction::ReportTravelTarget(TravelTarget* newTarget, Trave QuestTravelDestination* QuestDestination = (QuestTravelDestination*)destination; Quest const* quest = QuestDestination->GetQuestTemplate(); WorldPosition botLocation(bot); - - CreatureTemplate const* cInfo = nullptr; - GameObjectTemplate const* gInfo = nullptr; - - if (destination->getEntry() > 0) - cInfo = sObjectMgr->GetCreatureTemplate(destination->getEntry()); - else - gInfo = sObjectMgr->GetGameObjectTemplate(destination->getEntry() * -1); - std::string Sub; if (newTarget->isGroupCopy()) @@ -366,7 +357,7 @@ bool ChooseTravelTargetAction::getBestDestination(std::vector availablePoints = - sTravelMgr->getNextPoint(&botLocation, *activePoints); // Pick a good point. + TravelMgr::instance().getNextPoint(&botLocation, *activePoints); // Pick a good point. if (availablePoints.empty()) // No points available. return false; @@ -478,7 +469,7 @@ bool ChooseTravelTargetAction::SetCurrentTarget(TravelTarget* target, TravelTarg return target->isActive(); } -bool ChooseTravelTargetAction::SetQuestTarget(TravelTarget* target, bool onlyCompleted, bool newQuests, bool activeQuests, bool completedQuests) +bool ChooseTravelTargetAction::SetQuestTarget(TravelTarget* target, bool newQuests, bool activeQuests, bool completedQuests) { std::vector activeDestinations; std::vector activePoints; @@ -488,7 +479,7 @@ bool ChooseTravelTargetAction::SetQuestTarget(TravelTarget* target, bool onlyCom if (newQuests) { // Prefer new quests near the player at lower levels. - activeDestinations = sTravelMgr->getQuestTravelDestinations(bot, -1, true, false, 400 + bot->GetLevel() * 10); + activeDestinations = TravelMgr::instance().getQuestTravelDestinations(bot, -1, true, false, 400 + bot->GetLevel() * 10); } if (activeQuests || completedQuests) { @@ -510,7 +501,7 @@ bool ChooseTravelTargetAction::SetQuestTarget(TravelTarget* target, bool onlyCom continue; //Find quest takers or objectives - std::vector questDestinations = sTravelMgr->getQuestTravelDestinations(bot, questId, true, false, 0); + std::vector questDestinations = TravelMgr::instance().getQuestTravelDestinations(bot, questId, true, false, 0); if (onlyClassQuest && activeDestinations.size() && questDestinations.size()) //Only do class quests if we have any. { @@ -525,7 +516,7 @@ bool ChooseTravelTargetAction::SetQuestTarget(TravelTarget* target, bool onlyCom } } if (newQuests && activeDestinations.empty()) - activeDestinations = sTravelMgr->getQuestTravelDestinations(bot, -1, true, false); //If we really don't find any new quests look futher away. + activeDestinations = TravelMgr::instance().getQuestTravelDestinations(bot, -1, true, false); //If we really don't find any new quests look futher away. if (botAI->HasStrategy("debug travel", BotState::BOT_STATE_NON_COMBAT)) botAI->TellMasterNoFacing(std::to_string(activeDestinations.size()) + " quest destinations found."); @@ -547,7 +538,7 @@ bool ChooseTravelTargetAction::SetNewQuestTarget(TravelTarget* target) // Find quest givers. std::vector TravelDestinations = - sTravelMgr->getQuestTravelDestinations(bot, -1, botAI->HasRealPlayerMaster()); + TravelMgr::instance().getQuestTravelDestinations(bot, -1, botAI->HasRealPlayerMaster()); activeDestinations.insert(activeDestinations.end(), TravelDestinations.begin(), TravelDestinations.end()); @@ -576,7 +567,7 @@ bool ChooseTravelTargetAction::SetRpgTarget(TravelTarget* target) // Find rpg npcs std::vector TravelDestinations = - sTravelMgr->getRpgTravelDestinations(bot, botAI->HasRealPlayerMaster()); + TravelMgr::instance().getRpgTravelDestinations(bot, botAI->HasRealPlayerMaster()); activeDestinations.insert(activeDestinations.end(), TravelDestinations.begin(), TravelDestinations.end()); @@ -605,7 +596,7 @@ bool ChooseTravelTargetAction::SetGrindTarget(TravelTarget* target) // Find grind mobs. std::vector TravelDestinations = - sTravelMgr->getGrindTravelDestinations(bot, botAI->HasRealPlayerMaster()); + TravelMgr::instance().getGrindTravelDestinations(bot, botAI->HasRealPlayerMaster()); activeDestinations.insert(activeDestinations.end(), TravelDestinations.begin(), TravelDestinations.end()); @@ -634,7 +625,7 @@ bool ChooseTravelTargetAction::SetBossTarget(TravelTarget* target) // Find boss mobs. std::vector TravelDestinations = - sTravelMgr->getBossTravelDestinations(bot, botAI->HasRealPlayerMaster()); + TravelMgr::instance().getBossTravelDestinations(bot, botAI->HasRealPlayerMaster()); activeDestinations.insert(activeDestinations.end(), TravelDestinations.begin(), TravelDestinations.end()); @@ -662,7 +653,7 @@ bool ChooseTravelTargetAction::SetExploreTarget(TravelTarget* target) WorldPosition botLocation(bot); // Find quest givers. - std::vector TravelDestinations = sTravelMgr->getExploreTravelDestinations(bot, true, true); + std::vector TravelDestinations = TravelMgr::instance().getExploreTravelDestinations(bot, true, true); activeDestinations.insert(activeDestinations.end(), TravelDestinations.begin(), TravelDestinations.end()); /* @@ -681,7 +672,7 @@ bool ChooseTravelTargetAction::SetExploreTarget(TravelTarget* target) if (activePoints.empty()) { - TravelDestinations = sTravelMgr->getExploreTravelDestinations(bot, botAI->HasRealPlayerMaster()); + TravelDestinations = TravelMgr::instance().getExploreTravelDestinations(bot, botAI->HasRealPlayerMaster()); for (auto& activeTarget : activeDestinations) { @@ -710,7 +701,7 @@ bool ChooseTravelTargetAction::SetNpcFlagTarget(TravelTarget* target, std::vecto std::vector dests; - for (auto& d : sTravelMgr->getRpgTravelDestinations(bot, true, true)) + for (auto& d : TravelMgr::instance().getRpgTravelDestinations(bot, true, true)) { if (!d->getEntry()) continue; @@ -813,7 +804,7 @@ std::vector TravelMgr::getBossTravelDestinations(Player* bot bool ChooseTravelTargetAction::SetNullTarget(TravelTarget* target) { - target->setTarget(sTravelMgr->nullTravelDestination, sTravelMgr->nullWorldPosition, true); + target->setTarget(TravelMgr::instance().nullTravelDestination, TravelMgr::instance().nullWorldPosition, true); return true; } @@ -823,16 +814,12 @@ char* strstri(char const* haystack, char const* needle); TravelDestination* ChooseTravelTargetAction::FindDestination(Player* bot, std::string const name, bool zones, bool npcs, bool quests, bool mobs, bool bosses) { - PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); - - // AiObjectContext* context = botAI->GetAiObjectContext(); //not used, line marked for removal. - std::vector dests; //Quests if (quests) { - for (auto& d : sTravelMgr->getQuestTravelDestinations(bot, 0, true, true)) + for (auto& d : TravelMgr::instance().getQuestTravelDestinations(bot, 0, true, true)) { if (strstri(d->getTitle().c_str(), name.c_str())) dests.push_back(d); @@ -842,7 +829,7 @@ TravelDestination* ChooseTravelTargetAction::FindDestination(Player* bot, std::s //Zones if (zones) { - for (auto& d : sTravelMgr->getExploreTravelDestinations(bot, true, true)) + for (auto& d : TravelMgr::instance().getExploreTravelDestinations(bot, true, true)) { if (strstri(d->getTitle().c_str(), name.c_str())) dests.push_back(d); @@ -852,7 +839,7 @@ TravelDestination* ChooseTravelTargetAction::FindDestination(Player* bot, std::s //Npcs if (npcs) { - for (auto& d : sTravelMgr->getRpgTravelDestinations(bot, true, true)) + for (auto& d : TravelMgr::instance().getRpgTravelDestinations(bot, true, true)) { if (strstri(d->getTitle().c_str(), name.c_str())) dests.push_back(d); @@ -862,7 +849,7 @@ TravelDestination* ChooseTravelTargetAction::FindDestination(Player* bot, std::s //Mobs if (mobs) { - for (auto& d : sTravelMgr->getGrindTravelDestinations(bot, true, true, 5000.0f)) + for (auto& d : TravelMgr::instance().getGrindTravelDestinations(bot, true, true, 5000.0f)) { if (strstri(d->getTitle().c_str(), name.c_str())) dests.push_back(d); @@ -872,7 +859,7 @@ TravelDestination* ChooseTravelTargetAction::FindDestination(Player* bot, std::s //Bosses if (bosses) { - for (auto& d : sTravelMgr->getBossTravelDestinations(bot, true, true)) + for (auto& d : TravelMgr::instance().getBossTravelDestinations(bot, true, true)) { if (strstri(d->getTitle().c_str(), name.c_str())) dests.push_back(d); @@ -934,14 +921,16 @@ bool ChooseTravelTargetAction::needForQuest(Unit* target) for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++) { - int32 entry = questTemplate->RequiredNpcOrGo[j]; + int32_t entry = questTemplate->RequiredNpcOrGo[j]; - if (entry && entry > 0) + if (entry > 0) { int required = questTemplate->RequiredNpcOrGoCount[j]; int available = questStatus.CreatureOrGOCount[j]; - if (required && available < required && (target->GetEntry() == entry || justCheck)) + const int64_t targetEntry = target->GetEntry(); + + if (required && available < required && (targetEntry == entry || justCheck)) return true; } diff --git a/src/Ai/Base/Actions/ChooseTravelTargetAction.h b/src/Ai/Base/Actions/ChooseTravelTargetAction.h index 2ec026dc20..7a259612ec 100644 --- a/src/Ai/Base/Actions/ChooseTravelTargetAction.h +++ b/src/Ai/Base/Actions/ChooseTravelTargetAction.h @@ -36,7 +36,7 @@ class ChooseTravelTargetAction : public MovementAction bool getBestDestination(std::vector* activeDestinations, std::vector* activePoints); bool SetGroupTarget(TravelTarget* target); bool SetCurrentTarget(TravelTarget* target, TravelTarget* oldTarget); - bool SetQuestTarget(TravelTarget* target, bool onlyCompleted = false, bool newQuests = true, bool activeQuests = true, bool completedQuests = true); + bool SetQuestTarget(TravelTarget* target, bool newQuests = true, bool activeQuests = true, bool completedQuests = true); bool SetNewQuestTarget(TravelTarget* target); bool SetRpgTarget(TravelTarget* target); bool SetGrindTarget(TravelTarget* target); diff --git a/src/Ai/Base/Actions/CombatActions.cpp b/src/Ai/Base/Actions/CombatActions.cpp index fe29a11b4f..2f687d5e03 100644 --- a/src/Ai/Base/Actions/CombatActions.cpp +++ b/src/Ai/Base/Actions/CombatActions.cpp @@ -25,7 +25,7 @@ bool SwitchToMeleeAction::isUseful() return botAI->HasStrategy("ranged", BOT_STATE_COMBAT) && ((bot->IsInCombat() && target && (target->GetVictim() == bot && (!bot->GetGroup() || lastFlee) && - sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "current target"), 8.0f))) || + ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "current target"), 8.0f))) || (!bot->IsInCombat())); } @@ -47,7 +47,7 @@ bool SwitchToRangedAction::isUseful() return botAI->HasStrategy("close", BOT_STATE_COMBAT) && hasAmmo && ((bot->IsInCombat() && target && ((target->GetVictim() != bot || target->GetTarget() != bot->GetGUID()) || - sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "current target"), 8.0f))) || + ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "current target"), 8.0f))) || (!bot->IsInCombat())); } diff --git a/src/Ai/Base/Actions/DebugAction.cpp b/src/Ai/Base/Actions/DebugAction.cpp index 11a0bf26a0..cff3c9c457 100644 --- a/src/Ai/Base/Actions/DebugAction.cpp +++ b/src/Ai/Base/Actions/DebugAction.cpp @@ -7,7 +7,11 @@ #include "ChooseTravelTargetAction.h" #include "MapMgr.h" -#include "Playerbots.h" +#include "TravelMgr.h" +#include "Player.h" +#include "PlayerbotAI.h" +#include "SpellMgr.h" +#include "Spell.h" bool DebugAction::Execute(Event event) { @@ -19,7 +23,7 @@ bool DebugAction::Execute(Event event) if (text == "scan") { - sPlayerbotAIConfig->openLog("scan.csv", "w"); + sPlayerbotAIConfig.openLog("scan.csv", "w"); uint32 i = 0; for (auto p : WorldPosition().getCreaturesNear()) @@ -36,15 +40,15 @@ bool DebugAction::Execute(Event event) pos.printWKT(out); - sPlayerbotAIConfig->log("scan.csv", out.str().c_str()); + sPlayerbotAIConfig.log("scan.csv", out.str().c_str()); if (zoneId == 0 && areaId == 0) { - sPlayerbotAIConfig->log("x", out.str().c_str()); + sPlayerbotAIConfig.log("x", out.str().c_str()); } else { - sPlayerbotAIConfig->log("y", out.str().c_str()); + sPlayerbotAIConfig.log("y", out.str().c_str()); } i = zoneId; @@ -53,8 +57,8 @@ bool DebugAction::Execute(Event event) } else if (text.find("printmap") != std::string::npos) { - sTravelNodeMap->printMap(); - sTravelNodeMap->printNodeStore(); + TravelNodeMap::instance().printMap(); + TravelNodeMap::instance().printNodeStore(); return true; } else if (text.find("travel ") != std::string::npos) @@ -72,7 +76,7 @@ bool DebugAction::Execute(Event event) return false; std::vector beginPath, endPath; - TravelNodeRoute route = sTravelNodeMap->getRoute(botPos, *points.front(), beginPath, bot); + TravelNodeRoute route = TravelNodeMap::instance().getRoute(botPos, *points.front(), beginPath, bot); std::ostringstream out; out << "Traveling to " << dest->getTitle() << ": "; @@ -108,7 +112,7 @@ bool DebugAction::Execute(Event event) out << quest->GetTitle() << ": "; - QuestContainer* cont = sTravelMgr->quests[questId]; + QuestContainer* cont = TravelMgr::instance().quests[questId]; for (auto g : cont->questGivers) { @@ -135,11 +139,11 @@ bool DebugAction::Execute(Event event) else if (text.find("quest") != std::string::npos) { std::ostringstream out; - out << sTravelMgr->quests.size() << " quests "; + out << TravelMgr::instance().quests.size() << " quests "; uint32 noT = 0, noG = 0, noO = 0; - for (auto q : sTravelMgr->quests) + for (auto q : TravelMgr::instance().quests) { if (q.second->questGivers.empty()) noG++; @@ -164,7 +168,7 @@ bool DebugAction::Execute(Event event) // uint32 noT = 0, noG = 0, noO = 0; //not used, line marked for removal. - for (auto q : sTravelMgr->quests) + for (auto q : TravelMgr::instance().quests) { Quest const* quest = sObjectMgr->GetQuestTemplate(q.first); @@ -194,16 +198,16 @@ bool DebugAction::Execute(Event event) std::string const name = "USER:" + text.substr(9); - /* TravelNode* startNode = */ sTravelNodeMap->addNode(pos, name, false, false); // startNode not used, but addNode as side effect, fragment marked for removal. + /* TravelNode* startNode = */ TravelNodeMap::instance().addNode(pos, name, false, false); // startNode not used, but addNode as side effect, fragment marked for removal. - for (auto& endNode : sTravelNodeMap->getNodes(pos, 2000)) + for (auto& endNode : TravelNodeMap::instance().getNodes(pos, 2000)) { endNode->setLinked(false); } botAI->TellMasterNoFacing("Node " + name + " created."); - sTravelNodeMap->setHasToGen(); + TravelNodeMap::instance().setHasToGen(); return true; } @@ -211,7 +215,7 @@ bool DebugAction::Execute(Event event) { WorldPosition pos(bot); - TravelNode* startNode = sTravelNodeMap->getNode(pos, nullptr, 50); + TravelNode* startNode = TravelNodeMap::instance().getNode(pos, nullptr, 50); if (!startNode) return false; @@ -221,24 +225,24 @@ bool DebugAction::Execute(Event event) botAI->TellMasterNoFacing("Node can not be removed."); } - sTravelNodeMap->m_nMapMtx.lock(); - sTravelNodeMap->removeNode(startNode); + TravelNodeMap::instance().m_nMapMtx.lock(); + TravelNodeMap::instance().removeNode(startNode); botAI->TellMasterNoFacing("Node removed."); - sTravelNodeMap->m_nMapMtx.unlock(); + TravelNodeMap::instance().m_nMapMtx.unlock(); - sTravelNodeMap->setHasToGen(); + TravelNodeMap::instance().setHasToGen(); return true; } else if (text.find("reset node") != std::string::npos) { - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) node->setLinked(false); return true; } else if (text.find("reset path") != std::string::npos) { - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) for (auto& path : *node->getLinks()) node->removeLinkTo(path.first, true); return true; @@ -246,23 +250,23 @@ bool DebugAction::Execute(Event event) else if (text.find("gen node") != std::string::npos) { // Pathfinder - sTravelNodeMap->generateNodes(); + TravelNodeMap::instance().generateNodes(); return true; } else if (text.find("gen path") != std::string::npos) { - sTravelNodeMap->generatePaths(); + TravelNodeMap::instance().generatePaths(); return true; } else if (text.find("crop path") != std::string::npos) { - sTravelNodeMap->removeUselessPaths(); + TravelNodeMap::instance().removeUselessPaths(); return true; } else if (text.find("save node") != std::string::npos) { - sTravelNodeMap->printNodeStore(); - sTravelNodeMap->saveNodeStore(); + TravelNodeMap::instance().printNodeStore(); + TravelNodeMap::instance().saveNodeStore(); return true; } else if (text.find("load node") != std::string::npos) @@ -270,8 +274,8 @@ bool DebugAction::Execute(Event event) std::thread t( [] { - sTravelNodeMap->removeNodes(); - sTravelNodeMap->loadNodeStore(); + TravelNodeMap::instance().removeNodes(); + TravelNodeMap::instance().loadNodeStore(); }); t.detach(); @@ -282,7 +286,7 @@ bool DebugAction::Execute(Event event) { WorldPosition pos(bot); - std::vector nodes = sTravelNodeMap->getNodes(pos, 500); + std::vector nodes = TravelNodeMap::instance().getNodes(pos, 500); for (auto& node : nodes) { @@ -516,7 +520,7 @@ bool DebugAction::Execute(Event event) botPos.setY(botPos.getY() + (dy - 5) * 5); botPos.setZ(botPos.getHeight()); - Creature* wpCreature = bot->SummonCreature(effect, botPos.getX(), botPos.getY(), botPos.getZ(), 0, + bot->SummonCreature(effect, botPos.getX(), botPos.getY(), botPos.getZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 10000.0f); } } diff --git a/src/Ai/Base/Actions/DelayAction.cpp b/src/Ai/Base/Actions/DelayAction.cpp index 8d47912fe4..9d9affa36b 100644 --- a/src/Ai/Base/Actions/DelayAction.cpp +++ b/src/Ai/Base/Actions/DelayAction.cpp @@ -6,15 +6,19 @@ #include "DelayAction.h" #include "Event.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" +#include "PlayerbotAIConfig.h" -bool DelayAction::Execute(Event event) +bool DelayAction::Execute(Event) { - uint32 delay = sPlayerbotAIConfig->passiveDelay + sPlayerbotAIConfig->globalCoolDown; + const uint32 delay = PlayerbotAIConfig::instance().passiveDelay + PlayerbotAIConfig::instance().globalCoolDown; botAI->SetNextCheckDelay(delay); return true; } -bool DelayAction::isUseful() { return !botAI->AllowActivity(ALL_ACTIVITY); } +bool DelayAction::isUseful() +{ + return !botAI->AllowActivity(ALL_ACTIVITY); +} diff --git a/src/Ai/Base/Actions/DestroyItemAction.cpp b/src/Ai/Base/Actions/DestroyItemAction.cpp index 0fce4ad701..cd5fbfebec 100644 --- a/src/Ai/Base/Actions/DestroyItemAction.cpp +++ b/src/Ai/Base/Actions/DestroyItemAction.cpp @@ -39,7 +39,7 @@ void DestroyItemAction::DestroyItem(FindItemVisitor* visitor) bool SmartDestroyItemAction::isUseful() { return !botAI->HasActivePlayerMaster(); } -bool SmartDestroyItemAction::Execute(Event event) +bool SmartDestroyItemAction::Execute(Event) { uint8 bagSpace = AI_VALUE(uint8, "bag space"); diff --git a/src/Ai/Base/Actions/DropQuestAction.cpp b/src/Ai/Base/Actions/DropQuestAction.cpp index 48e571eb3e..b3cba9c560 100644 --- a/src/Ai/Base/Actions/DropQuestAction.cpp +++ b/src/Ai/Base/Actions/DropQuestAction.cpp @@ -67,7 +67,7 @@ bool CleanQuestLogAction::Execute(Event event) return false; } - if (!sPlayerbotAIConfig->dropObsoleteQuests) + if (!sPlayerbotAIConfig.dropObsoleteQuests) { return false; } diff --git a/src/Ai/Base/Actions/EmoteAction.cpp b/src/Ai/Base/Actions/EmoteAction.cpp index 1770ca2b75..8e2c9f67b1 100644 --- a/src/Ai/Base/Actions/EmoteAction.cpp +++ b/src/Ai/Base/Actions/EmoteAction.cpp @@ -6,7 +6,6 @@ #include "EmoteAction.h" #include "Event.h" -#include "PlayerbotTextMgr.h" #include "Playerbots.h" #include "ServerFacade.h" @@ -88,7 +87,7 @@ void EmoteActionBase::InitEmotes() bool EmoteActionBase::Emote(Unit* target, uint32 type, bool textEmote) { - if (target && !bot->HasInArc(static_cast(M_PI), target, sPlayerbotAIConfig->sightDistance)) + if (target && !bot->HasInArc(static_cast(M_PI), target, sPlayerbotAIConfig.sightDistance)) bot->SetFacingToObject(target); ObjectGuid oldSelection = bot->GetTarget(); @@ -100,7 +99,7 @@ bool EmoteActionBase::Emote(Unit* target, uint32 type, bool textEmote) if (player) { PlayerbotAI* playerBotAI = GET_PLAYERBOT_AI(player); - if (playerBotAI && !player->HasInArc(static_cast(M_PI), bot, sPlayerbotAIConfig->sightDistance)) + if (playerBotAI && !player->HasInArc(static_cast(M_PI), bot, sPlayerbotAIConfig.sightDistance)) { player->SetFacingToObject(bot); } @@ -133,7 +132,7 @@ Unit* EmoteActionBase::GetTarget() for (GuidVector::iterator i = nfp.begin(); i != nfp.end(); ++i) { Unit* unit = botAI->GetUnit(*i); - if (unit && sServerFacade->GetDistance2d(bot, unit) < sPlayerbotAIConfig->tooCloseDistance) + if (unit && ServerFacade::instance().GetDistance2d(bot, unit) < sPlayerbotAIConfig.tooCloseDistance) targets.push_back(unit); } @@ -618,8 +617,8 @@ bool EmoteActionBase::ReceiveEmote(Player* source, uint32 emote, bool verbal) break; } - if (source && !bot->isMoving() && !bot->HasInArc(static_cast(M_PI), source, sPlayerbotAIConfig->farDistance)) - sServerFacade->SetFacingTo(bot, source); + if (source && !bot->isMoving() && !bot->HasInArc(static_cast(M_PI), source, sPlayerbotAIConfig.farDistance)) + ServerFacade::instance().SetFacingTo(bot, source); if (verbal) { @@ -689,7 +688,7 @@ bool EmoteAction::Execute(Event event) p >> emoteId >> source; pSource = ObjectAccessor::FindPlayer(source); - if (pSource && pSource != bot && sServerFacade->GetDistance2d(bot, pSource) < sPlayerbotAIConfig->farDistance && + if (pSource && pSource != bot && ServerFacade::instance().GetDistance2d(bot, pSource) < sPlayerbotAIConfig.farDistance && emoteId != EMOTE_ONESHOT_NONE) { if ((pSource->GetGUID() != bot->GetGUID()) && @@ -737,7 +736,7 @@ bool EmoteAction::Execute(Event event) // time_t lastEmote = AI_VALUE2(time_t, "last emote", qualifier); //not used, line marked for removal. botAI->GetAiObjectContext() ->GetValue("last emote", qualifier) - ->Set(time(nullptr) + urand(1000, sPlayerbotAIConfig->repeatDelay) / 1000); + ->Set(time(nullptr) + urand(1000, sPlayerbotAIConfig.repeatDelay) / 1000); param = qualifier; } @@ -787,7 +786,7 @@ bool EmoteAction::isUseful() return time(nullptr) >= lastEmote; } -bool TalkAction::Execute(Event event) +bool TalkAction::Execute(Event) { Unit* target = botAI->GetUnit(AI_VALUE(ObjectGuid, "talk target")); if (!target) diff --git a/src/Ai/Base/Actions/EquipAction.cpp b/src/Ai/Base/Actions/EquipAction.cpp index 9f4a67ca90..e0770abe19 100644 --- a/src/Ai/Base/Actions/EquipAction.cpp +++ b/src/Ai/Base/Actions/EquipAction.cpp @@ -85,8 +85,8 @@ void EquipAction::EquipItem(Item* item) if (itemProto->Class == ITEM_CLASS_CONTAINER) { // Attempt to equip as a bag - Bag* pBag = reinterpret_cast(item); uint8 newBagSlot = GetSmallestBagSlot(); + if (newBagSlot > 0) { uint16 src = ((bagIndex << 8) | slot); @@ -330,7 +330,7 @@ void EquipAction::EquipItem(Item* item) bool EquipUpgradesAction::Execute(Event event) { - if (!sPlayerbotAIConfig->autoEquipUpgradeLoot && !sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sPlayerbotAIConfig.autoEquipUpgradeLoot && !sRandomPlayerbotMgr.IsRandomBot(bot)) return false; if (event.GetSource() == "trade status") @@ -397,7 +397,7 @@ bool EquipUpgradesAction::Execute(Event event) return true; } -bool EquipUpgradeAction::Execute(Event event) +bool EquipUpgradeAction::Execute(Event) { CollectItemsVisitor visitor; IterateItems(&visitor, ITERATE_ITEMS_IN_BAGS); diff --git a/src/Ai/Base/Actions/FishingAction.cpp b/src/Ai/Base/Actions/FishingAction.cpp index dc431d3425..c38cbe576a 100644 --- a/src/Ai/Base/Actions/FishingAction.cpp +++ b/src/Ai/Base/Actions/FishingAction.cpp @@ -8,6 +8,7 @@ #include "Event.h" #include "GridNotifiers.h" +// Required due to poor AC implementation #include "GridNotifiersImpl.h" #include "ItemPackets.h" #include "LastMovementValue.h" @@ -246,7 +247,7 @@ WorldPosition FindFishingHole(PlayerbotAI* botAI) return WorldPosition(); } -bool MoveNearWaterAction::Execute(Event event) +bool MoveNearWaterAction::Execute(Event) { WorldPosition landSpot = AI_VALUE(WorldPosition, "fishing spot"); if (landSpot.IsValid()) @@ -272,9 +273,9 @@ bool MoveNearWaterAction::isPossible() float fishingSearchWindow; if (master) - fishingSearchWindow = sPlayerbotAIConfig->fishingDistanceFromMaster; + fishingSearchWindow = sPlayerbotAIConfig.fishingDistanceFromMaster; else - fishingSearchWindow = sPlayerbotAIConfig->fishingDistance; + fishingSearchWindow = sPlayerbotAIConfig.fishingDistance; WorldPosition fishingHole = FindFishingHole(botAI); @@ -292,7 +293,6 @@ bool MoveNearWaterAction::isPossible() // Water spot is out of range, lets look for a spot to move to for the fishing hole. if (distance > MAX_DISTANCE_TO_WATER || distance < MIN_DISTANCE_TO_WATER) { - float angle = bot->GetAngle(fishingHole.GetPositionX(), fishingHole.GetPositionY()); WorldPosition landSpot = FindLandRadialFromPosition(botAI, fishingHole, MIN_DISTANCE_TO_WATER, MAX_DISTANCE_TO_WATER, SEARCH_INCREMENT, fishingSearchWindow, 32); if (landSpot.IsValid()) { @@ -323,7 +323,6 @@ bool MoveNearWaterAction::isPossible() if (!water.IsValid()) return false; - bool hasLOS = bot->IsWithinLOS(water.GetPositionX(), water.GetPositionY(), water.GetPositionZ()); float angle = bot->GetAngle(water.GetPositionX(), water.GetPositionY()); WorldPosition landSpot = FindLandFromPosition(botAI, 0.0f, MAX_DISTANCE_TO_WATER, 1.0f, angle, water, fishingSearchWindow, false); @@ -336,7 +335,7 @@ bool MoveNearWaterAction::isPossible() return false; } -bool EquipFishingPoleAction::Execute(Event event) +bool EquipFishingPoleAction::Execute(Event) { if (!_pole) return false; @@ -385,7 +384,7 @@ bool EquipFishingPoleAction::isUseful() } } - if (sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sRandomPlayerbotMgr.IsRandomBot(bot)) { bot->StoreNewItemInBestSlots(FISHING_POLE, 1); // Try to get a fishing pole return true; @@ -396,7 +395,7 @@ bool EquipFishingPoleAction::isUseful() return false; std::string masterName = master->GetName(); - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "no_fishing_pole_error", "I don't have a Fishing Pole",{}); botAI->Whisper(text, masterName); @@ -463,7 +462,7 @@ bool UseBobberAction::isUseful() return AI_VALUE(bool, "can use fishing bobber"); } -bool UseBobberAction::Execute(Event event) +bool UseBobberAction::Execute(Event) { GuidVector gos = AI_VALUE(GuidVector, "nearest game objects no los"); for (auto const& guid : gos) @@ -485,7 +484,7 @@ bool UseBobberAction::Execute(Event event) return false; } -bool EndMasterFishingAction::Execute(Event event) +bool EndMasterFishingAction::Execute(Event) { botAI->ChangeStrategy("-master fishing", BOT_STATE_NON_COMBAT); return true; @@ -499,11 +498,11 @@ bool EndMasterFishingAction::isUseful() return false; WorldPosition nearWater = FindWaterRadial(bot, bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), - bot->GetMap(), bot->GetPhaseMask(), MIN_DISTANCE_TO_WATER, sPlayerbotAIConfig->endFishingWithMaster, 10.0f); + bot->GetMap(), bot->GetPhaseMask(), MIN_DISTANCE_TO_WATER, sPlayerbotAIConfig.endFishingWithMaster, 10.0f); return !nearWater.IsValid(); } -bool RemoveBobberStrategyAction::Execute(Event event) +bool RemoveBobberStrategyAction::Execute(Event) { botAI->ChangeStrategy("-use bobber", BOT_STATE_NON_COMBAT); return true; diff --git a/src/Ai/Base/Actions/FollowActions.cpp b/src/Ai/Base/Actions/FollowActions.cpp index 2593ea28e5..cfed8ae620 100644 --- a/src/Ai/Base/Actions/FollowActions.cpp +++ b/src/Ai/Base/Actions/FollowActions.cpp @@ -5,17 +5,14 @@ #include "FollowActions.h" -#include - #include "Event.h" #include "Formations.h" #include "LastMovementValue.h" #include "PlayerbotAI.h" #include "Playerbots.h" #include "ServerFacade.h" -#include "SharedDefines.h" -bool FollowAction::Execute(Event event) +bool FollowAction::Execute(Event) { Formation* formation = AI_VALUE(Formation*, "formation"); std::string const target = formation->GetTargetName(); @@ -28,7 +25,7 @@ bool FollowAction::Execute(Event event) else { WorldLocation loc = formation->GetLocation(); - if (Formation::IsNullLocation(loc) || loc.GetMapId() == -1) + if (Formation::IsNullLocation(loc)) return false; MovementPriority priority = botAI->GetState() == BOT_STATE_COMBAT ? MovementPriority::MOVEMENT_COMBAT : MovementPriority::MOVEMENT_NORMAL; @@ -44,7 +41,7 @@ bool FollowAction::Execute(Event event) // botAI->PetFollow(); // } // if (moved) - // botAI->SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + // botAI->SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); return moved; } @@ -98,9 +95,9 @@ bool FollowAction::isUseful() distance = bot->GetDistance(loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ()); } if (botAI->HasStrategy("master fishing", BOT_STATE_NON_COMBAT)) - return sServerFacade->IsDistanceGreaterThan(distance, sPlayerbotAIConfig->fishingDistanceFromMaster); + return ServerFacade::instance().IsDistanceGreaterThan(distance, sPlayerbotAIConfig.fishingDistanceFromMaster); - return sServerFacade->IsDistanceGreaterThan(distance, formation->GetMaxDistance()); + return ServerFacade::instance().IsDistanceGreaterThan(distance, formation->GetMaxDistance()); } bool FollowAction::CanDeadFollow(Unit* target) @@ -116,7 +113,7 @@ bool FollowAction::CanDeadFollow(Unit* target) return true; } -bool FleeToGroupLeaderAction::Execute(Event event) +bool FleeToGroupLeaderAction::Execute(Event) { Unit* fTarget = AI_VALUE(Unit*, "group leader"); bool canFollow = Follow(fTarget); @@ -130,7 +127,7 @@ bool FleeToGroupLeaderAction::Execute(Event event) WorldPosition bosPos(bot); float distance = bosPos.fDist(targetPos); - if (distance < sPlayerbotAIConfig->reactDistance * 3) + if (distance < sPlayerbotAIConfig.reactDistance * 3) { if (!urand(0, 3)) botAI->TellMaster("I am close, wait for me!"); diff --git a/src/Ai/Base/Actions/GenericActions.cpp b/src/Ai/Base/Actions/GenericActions.cpp index 184b17715d..cb4f4fb9e6 100644 --- a/src/Ai/Base/Actions/GenericActions.cpp +++ b/src/Ai/Base/Actions/GenericActions.cpp @@ -11,8 +11,6 @@ #include "CreatureAI.h" #include "Playerbots.h" #include "CharmInfo.h" -#include "SharedDefines.h" -#include "ObjectGuid.h" #include "SpellMgr.h" #include "SpellInfo.h" #include @@ -54,7 +52,7 @@ bool MeleeAction::isUseful() return true; } -bool TogglePetSpellAutoCastAction::Execute(Event event) +bool TogglePetSpellAutoCastAction::Execute(Event) { Pet* pet = bot->GetPet(); if (!pet) @@ -113,13 +111,13 @@ bool TogglePetSpellAutoCastAction::Execute(Event event) } // Debug message if pet spells have been toggled and debug is enabled - if (toggled && sPlayerbotAIConfig->petChatCommandDebug == 1) + if (toggled && sPlayerbotAIConfig.petChatCommandDebug == 1) botAI->TellMaster("Pet autocast spells have been toggled."); return toggled; } -bool PetAttackAction::Execute(Event event) +bool PetAttackAction::Execute(Event) { Guardian* pet = bot->GetGuardianPet(); if (!pet) @@ -185,7 +183,7 @@ bool SetPetStanceAction::Execute(Event /*event*/) } // Get the default pet stance from the configuration - int32 stance = sPlayerbotAIConfig->defaultPetStance; + int32 stance = sPlayerbotAIConfig.defaultPetStance; ReactStates react = REACT_DEFENSIVE; std::string stanceText = "defensive (from config, fallback)"; @@ -221,7 +219,7 @@ bool SetPetStanceAction::Execute(Event /*event*/) } // If debug is enabled in config, inform the master of the new stance - if (sPlayerbotAIConfig->petChatCommandDebug == 1) + if (sPlayerbotAIConfig.petChatCommandDebug == 1) botAI->TellMaster("Pet stance set to " + stanceText + " (applied to all pets/guardians)."); return true; diff --git a/src/Ai/Base/Actions/GenericBuffUtils.cpp b/src/Ai/Base/Actions/GenericBuffUtils.cpp index 1ac71bad4e..e33c12f180 100644 --- a/src/Ai/Base/Actions/GenericBuffUtils.cpp +++ b/src/Ai/Base/Actions/GenericBuffUtils.cpp @@ -87,7 +87,7 @@ namespace ai::buff { std::string castName = baseName; Group* g = bot->GetGroup(); - if (!g || g->GetMembersCount() < static_cast(sPlayerbotAIConfig->minBotsForGreaterBuff)) + if (!g || g->GetMembersCount() < static_cast(sPlayerbotAIConfig.minBotsForGreaterBuff)) return castName; // Group too small: stay in solo mode if (std::string const groupName = GroupVariantFor(baseName); !groupName.empty()) @@ -114,7 +114,7 @@ namespace ai::buff time_t now = std::time(nullptr); uint32 botLow = static_cast(bot->GetGUID().GetCounter()); time_t& last = s_lastWarn[ std::make_pair(botLow, groupName) ]; - if (!last || now - last >= sPlayerbotAIConfig->rpWarningCooldown) // Configurable anti-spam + if (!last || now - last >= sPlayerbotAIConfig.rpWarningCooldown) // Configurable anti-spam { // DB Key choice in regard of the buff std::string key; @@ -132,7 +132,7 @@ namespace ai::buff placeholders["%group_spell"] = groupName; placeholders["%base_spell"] = baseName; - std::string announceText = sPlayerbotTextMgr->GetBotTextOrDefault(key, + std::string announceText = PlayerbotTextMgr::instance().GetBotTextOrDefault(key, "Out of components for %group_spell. Using %base_spell!", placeholders); announce(announceText); diff --git a/src/Ai/Base/Actions/GenericSpellActions.cpp b/src/Ai/Base/Actions/GenericSpellActions.cpp index af06a457f0..0762bbdaab 100644 --- a/src/Ai/Base/Actions/GenericSpellActions.cpp +++ b/src/Ai/Base/Actions/GenericSpellActions.cpp @@ -17,19 +17,17 @@ #include "WorldPacket.h" #include "Group.h" #include "Chat.h" -#include "Language.h" #include "GenericBuffUtils.h" #include "PlayerbotAI.h" using ai::buff::MakeAuraQualifierForBuff; -using ai::buff::UpgradeToGroupIfAppropriate; CastSpellAction::CastSpellAction(PlayerbotAI* botAI, std::string const spell) - : Action(botAI, spell), range(botAI->GetRange("spell")), spell(spell) + : Action(botAI, spell), spell(spell), range(botAI->GetRange("spell")) { } -bool CastSpellAction::Execute(Event event) +bool CastSpellAction::Execute(Event) { if (spell == "conjure food" || spell == "conjure water") { @@ -82,7 +80,7 @@ bool CastSpellAction::isPossible() { if (botAI->IsInVehicle() && !botAI->IsInVehicle(false, false, true)) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && botAI->HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && botAI->HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. Vehicle. - bot name: {}", bot->GetName()); } @@ -94,7 +92,7 @@ bool CastSpellAction::isPossible() if (spell == "mount" && bot->IsInCombat()) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && botAI->HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && botAI->HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. Mount. - bot name: {}", bot->GetName()); } @@ -133,7 +131,7 @@ bool CastSpellAction::isUseful() return spellTarget && AI_VALUE2(bool, "spell cast useful", - spell); // && sServerFacade->GetDistance2d(bot, spellTarget) <= (range + combatReach); + spell); // && ServerFacade::instance().GetDistance2d(bot, spellTarget) <= (range + combatReach); } CastMeleeSpellAction::CastMeleeSpellAction(PlayerbotAI* botAI, std::string const spell) : CastSpellAction(botAI, spell) @@ -172,13 +170,27 @@ bool CastMeleeDebuffSpellAction::isUseful() bool CastAuraSpellAction::isUseful() { - if (!GetTarget() || !CastSpellAction::isUseful()) + Unit* const target = this->GetTarget(); + + if (target == nullptr || !CastSpellAction::isUseful()) + { return false; - Aura* aura = botAI->GetAura(spell, GetTarget(), isOwner, checkDuration); - if (!aura) + } + + const Aura* const aura = botAI->GetAura(this->spell, target, this->isOwner, this->checkDuration); + + if (aura == nullptr) + { return true; - if (beforeDuration && aura->GetDuration() < beforeDuration) + } + + const int64_t& signedBeforeDuration = this->beforeDuration; + + if (signedBeforeDuration > 0 && aura->GetDuration() < signedBeforeDuration) + { return true; + } + return false; } @@ -207,7 +219,7 @@ bool CastEnchantItemAction::isPossible() CastHealingSpellAction::CastHealingSpellAction(PlayerbotAI* botAI, std::string const spell, uint8 estAmount, HealingManaEfficiency manaEfficiency, bool isOwner) - : CastAuraSpellAction(botAI, spell, isOwner), estAmount(estAmount), manaEfficiency(manaEfficiency) + : CastAuraSpellAction(botAI, spell, isOwner), manaEfficiency(manaEfficiency), estAmount(estAmount) { range = botAI->GetRange("heal"); } @@ -233,7 +245,7 @@ Value* BuffOnPartyAction::GetTargetValue() return context->GetValue("party member without aura", MakeAuraQualifierForBuff(spell)); } -bool BuffOnPartyAction::Execute(Event event) +bool BuffOnPartyAction::Execute(Event) { std::string castName = spell; // default = mono @@ -290,7 +302,7 @@ Value* CastSnareSpellAction::GetTargetValue() { return context->GetValue< Value* CastCrowdControlSpellAction::GetTargetValue() { return context->GetValue("cc target", getName()); } -bool CastCrowdControlSpellAction::Execute(Event event) { return botAI->CastSpell(getName(), GetTarget()); } +bool CastCrowdControlSpellAction::Execute(Event) { return botAI->CastSpell(getName(), GetTarget()); } bool CastCrowdControlSpellAction::isPossible() { return botAI->CanCastSpell(getName(), GetTarget()); } @@ -308,13 +320,13 @@ bool CastVehicleSpellAction::isPossible() bool CastVehicleSpellAction::isUseful() { return botAI->IsInVehicle(false, true); } -bool CastVehicleSpellAction::Execute(Event event) +bool CastVehicleSpellAction::Execute(Event) { uint32 spellId = AI_VALUE2(uint32, "vehicle spell id", spell); return botAI->CastVehicleSpell(spellId, GetTarget()); } -bool UseTrinketAction::Execute(Event event) +bool UseTrinketAction::Execute(Event) { Item* trinket1 = bot->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_TRINKET1); diff --git a/src/Ai/Base/Actions/GiveItemAction.cpp b/src/Ai/Base/Actions/GiveItemAction.cpp index 6e2d6744ec..029d16f513 100644 --- a/src/Ai/Base/Actions/GiveItemAction.cpp +++ b/src/Ai/Base/Actions/GiveItemAction.cpp @@ -11,7 +11,7 @@ std::vector split(std::string const s, char delim); -bool GiveItemAction::Execute(Event event) +bool GiveItemAction::Execute(Event) { Unit* target = GetTarget(); if (!target) @@ -28,7 +28,6 @@ bool GiveItemAction::Execute(Event event) if (receiverAi->GetAiObjectContext()->GetValue("item count", item)->Get()) return true; - bool moved = false; std::vector items = InventoryAction::parseItems(item, ITERATE_ITEMS_IN_BAGS); for (Item* item : items) { @@ -42,7 +41,6 @@ bool GiveItemAction::Execute(Event event) bot->MoveItemFromInventory(item->GetBagSlot(), item->GetSlot(), true); item->SetOwnerGUID(target->GetGUID()); receiver->MoveItemToInventory(dest, item, true); - moved = true; std::ostringstream out; out << "Got " << chat->FormatItem(item->GetTemplate(), item->GetCount()) << " from " << bot->GetName(); @@ -64,7 +62,7 @@ Unit* GiveItemAction::GetTarget() { return AI_VALUE2(Unit*, "party member withou bool GiveItemAction::isUseful() { - return GetTarget() && AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig->lowMana; + return GetTarget() && AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig.lowMana; } Unit* GiveFoodAction::GetTarget() { return AI_VALUE(Unit*, "party member without food"); } @@ -74,7 +72,7 @@ bool GiveFoodAction::isUseful() if (!GetTarget()) return false; - bool isRandomBot = GetTarget()->IsPlayer() && sRandomPlayerbotMgr->IsRandomBot((Player*)GetTarget()); + bool isRandomBot = GetTarget()->IsPlayer() && sRandomPlayerbotMgr.IsRandomBot((Player*)GetTarget()); return !isRandomBot || (isRandomBot && !botAI->HasCheat(BotCheatMask::food)); } @@ -86,7 +84,7 @@ bool GiveWaterAction::isUseful() if (!GetTarget()) return false; - bool isRandomBot = GetTarget()->IsPlayer() && sRandomPlayerbotMgr->IsRandomBot((Player*)GetTarget()); + bool isRandomBot = GetTarget()->IsPlayer() && sRandomPlayerbotMgr.IsRandomBot((Player*)GetTarget()); return !isRandomBot || (isRandomBot && !botAI->HasCheat(BotCheatMask::food)); } diff --git a/src/Ai/Base/Actions/GoAction.cpp b/src/Ai/Base/Actions/GoAction.cpp index 1b8cd62a2a..61a7550c2b 100644 --- a/src/Ai/Base/Actions/GoAction.cpp +++ b/src/Ai/Base/Actions/GoAction.cpp @@ -61,7 +61,7 @@ bool GoAction::Execute(Event event) else { botAI->TellMasterNoFacing("Clearing travel target"); - target->setTarget(sTravelMgr->nullTravelDestination, sTravelMgr->nullWorldPosition); + target->setTarget(TravelMgr::instance().nullTravelDestination, TravelMgr::instance().nullWorldPosition); target->setForced(false); return true; } @@ -75,8 +75,8 @@ bool GoAction::Execute(Event event) if (GameObject* go = botAI->GetGameObject(guid)) if (go->isSpawned()) { - if (sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(bot, go), - sPlayerbotAIConfig->reactDistance)) + if (ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(bot, go), + sPlayerbotAIConfig.reactDistance)) { botAI->TellError("It is too far away"); return false; @@ -86,7 +86,7 @@ bool GoAction::Execute(Event event) out << "Moving to " << ChatHelper::FormatGameobject(go); botAI->TellMasterNoFacing(out.str()); return MoveNear(bot->GetMapId(), go->GetPositionX(), go->GetPositionY(), go->GetPositionZ() + 0.5f, - sPlayerbotAIConfig->followDistance); + sPlayerbotAIConfig.followDistance); } } return false; @@ -106,7 +106,7 @@ bool GoAction::Execute(Event event) out << "Moving to " << unit->GetName(); botAI->TellMasterNoFacing(out.str()); return MoveNear(bot->GetMapId(), unit->GetPositionX(), unit->GetPositionY(), - unit->GetPositionZ() + 0.5f, sPlayerbotAIConfig->followDistance); + unit->GetPositionZ() + 0.5f, sPlayerbotAIConfig.followDistance); } } @@ -176,8 +176,8 @@ bool GoAction::Execute(Event event) float z = bot->GetPositionZ(); bot->UpdateAllowedPositionZ(x, y, z); - if (sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(bot, x, y), - sPlayerbotAIConfig->reactDistance)) + if (ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(bot, x, y), + sPlayerbotAIConfig.reactDistance)) { botAI->TellMaster("It is too far away"); return false; @@ -203,14 +203,14 @@ bool GoAction::Execute(Event event) out << "Moving to " << x1 << "," << y1; botAI->TellMasterNoFacing(out.str()); - return MoveNear(bot->GetMapId(), x, y, z + 0.5f, sPlayerbotAIConfig->followDistance); + return MoveNear(bot->GetMapId(), x, y, z + 0.5f, sPlayerbotAIConfig.followDistance); } PositionInfo pos = context->GetValue("position")->Get()[param]; if (pos.isSet()) { - if (sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(bot, pos.x, pos.y), - sPlayerbotAIConfig->reactDistance)) + if (ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(bot, pos.x, pos.y), + sPlayerbotAIConfig.reactDistance)) { botAI->TellError("It is too far away"); return false; @@ -219,7 +219,7 @@ bool GoAction::Execute(Event event) std::ostringstream out; out << "Moving to position " << param; botAI->TellMasterNoFacing(out.str()); - return MoveNear(bot->GetMapId(), pos.x, pos.y, pos.z + 0.5f, sPlayerbotAIConfig->followDistance); + return MoveNear(bot->GetMapId(), pos.x, pos.y, pos.z + 0.5f, sPlayerbotAIConfig.followDistance); } botAI->TellMaster("Whisper 'go x,y', 'go [game object]', 'go unit' or 'go position' and I will go there"); diff --git a/src/Ai/Base/Actions/GreetAction.cpp b/src/Ai/Base/Actions/GreetAction.cpp index 87bf2c5ffb..630f969398 100644 --- a/src/Ai/Base/Actions/GreetAction.cpp +++ b/src/Ai/Base/Actions/GreetAction.cpp @@ -10,7 +10,7 @@ GreetAction::GreetAction(PlayerbotAI* botAI) : Action(botAI, "greet") {} -bool GreetAction::Execute(Event event) +bool GreetAction::Execute(Event) { ObjectGuid guid = AI_VALUE(ObjectGuid, "new player nearby"); if (!guid || !guid.IsPlayer()) @@ -20,7 +20,7 @@ bool GreetAction::Execute(Event event) if (!player) return false; - if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, player, sPlayerbotAIConfig->sightDistance)) + if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, player, sPlayerbotAIConfig.sightDistance)) bot->SetFacingToObject(player); ObjectGuid oldSel = bot->GetTarget(); diff --git a/src/Ai/Base/Actions/GuildBankAction.cpp b/src/Ai/Base/Actions/GuildBankAction.cpp index 2d9c74ff69..2de53864d3 100644 --- a/src/Ai/Base/Actions/GuildBankAction.cpp +++ b/src/Ai/Base/Actions/GuildBankAction.cpp @@ -6,7 +6,8 @@ #include "GuildBankAction.h" #include "GuildMgr.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" +#include "AiObjectContext.h" bool GuildBankAction::Execute(Event event) { @@ -52,7 +53,7 @@ bool GuildBankAction::Execute(std::string const text, GameObject* bank) return result; } -bool GuildBankAction::MoveFromCharToBank(Item* item, GameObject* bank) +bool GuildBankAction::MoveFromCharToBank(Item* item, GameObject*) { uint32 playerSlot = item->GetSlot(); uint32 playerBag = item->GetBagSlot(); diff --git a/src/Ai/Base/Actions/GuildCreateActions.cpp b/src/Ai/Base/Actions/GuildCreateActions.cpp index 075b28cac3..2e36ac15b3 100644 --- a/src/Ai/Base/Actions/GuildCreateActions.cpp +++ b/src/Ai/Base/Actions/GuildCreateActions.cpp @@ -12,12 +12,11 @@ #include "Playerbots.h" #include "RandomPlayerbotFactory.h" #include "ServerFacade.h" -#include "SharedDefines.h" // GOLD +#include "SharedDefines.h" -bool BuyPetitionAction::Execute(Event event) +bool BuyPetitionAction::Execute(Event) { GuidVector vendors = botAI->GetAiObjectContext()->GetValue("nearest npcs")->Get(); - bool vendored = false, result = false; for (GuidVector::iterator i = vendors.begin(); i != vendors.end(); ++i) { ObjectGuid vendorguid = *i; @@ -97,7 +96,6 @@ bool BuyPetitionAction::canBuyPetition(Player* bot) bool PetitionOfferAction::Execute(Event event) { - uint32 petitionEntry = 5863; // GUILD_CHARTER std::vector petitions = AI_VALUE2(std::vector, "inventory items", chat->FormatQItem(5863)); if (petitions.empty()) @@ -152,7 +150,7 @@ bool PetitionOfferAction::Execute(Event event) bool PetitionOfferAction::isUseful() { return !bot->GetGuildId(); } -bool PetitionOfferNearbyAction::Execute(Event event) +bool PetitionOfferNearbyAction::Execute(Event) { uint32 found = 0; @@ -184,11 +182,11 @@ bool PetitionOfferNearbyAction::Execute(Event event) } else { - if (!sPlayerbotAIConfig->randomBotGroupNearby) + if (!sPlayerbotAIConfig.randomBotGroupNearby) return false; } - if (sServerFacade->GetDistance2d(bot, player) > sPlayerbotAIConfig->sightDistance) + if (ServerFacade::instance().GetDistance2d(bot, player) > sPlayerbotAIConfig.sightDistance) continue; // Parse rpg target to quest action. @@ -209,10 +207,9 @@ bool PetitionOfferNearbyAction::isUseful() AI_VALUE(uint8, "petition signs") < sWorld->getIntConfig(CONFIG_MIN_PETITION_SIGNS); } -bool PetitionTurnInAction::Execute(Event event) +bool PetitionTurnInAction::Execute(Event) { GuidVector vendors = botAI->GetAiObjectContext()->GetValue("nearest npcs")->Get(); - bool vendored = false, result = false; std::vector petitions = AI_VALUE2(std::vector, "inventory items", chat->FormatQItem(5863)); if (petitions.empty()) @@ -297,7 +294,7 @@ bool PetitionTurnInAction::isUseful() !context->GetValue("travel target")->Get()->isTraveling(); } -bool BuyTabardAction::Execute(Event event) +bool BuyTabardAction::Execute(Event) { bool canBuy = botAI->DoSpecificAction("buy", Event("buy tabard", "Hitem:5976:")); if (canBuy && AI_VALUE2(uint32, "item count", chat->FormatQItem(5976))) diff --git a/src/Ai/Base/Actions/GuildManagementActions.cpp b/src/Ai/Base/Actions/GuildManagementActions.cpp index f00a955e7c..27f96120a3 100644 --- a/src/Ai/Base/Actions/GuildManagementActions.cpp +++ b/src/Ai/Base/Actions/GuildManagementActions.cpp @@ -128,7 +128,7 @@ bool GuildRemoveAction::PlayerIsValid(Player* member) return member->GetGuildId() == bot->GetGuildId() && GetRankId(bot) < GetRankId(member); }; -bool GuildManageNearbyAction::Execute(Event event) +bool GuildManageNearbyAction::Execute(Event) { uint32 found = 0; @@ -149,7 +149,6 @@ bool GuildManageNearbyAction::Execute(Event event) // Promote or demote nearby members based on chance. if (player->GetGuildId() && player->GetGuildId() == bot->GetGuildId()) { - Guild::Member* member = guild->GetMember(player->GetGUID()); uint32 dCount = AI_VALUE(uint32, "death count"); if (!urand(0, 30) && dCount < 2 && guild->GetRankRights(botMember->GetRankId()) & GR_RIGHT_PROMOTE) @@ -171,7 +170,7 @@ bool GuildManageNearbyAction::Execute(Event event) continue; } - if (!sPlayerbotAIConfig->randomBotGuildNearby) + if (!sPlayerbotAIConfig.randomBotGuildNearby) return false; if (guild->GetMemberSize() > 1000) @@ -185,7 +184,7 @@ bool GuildManageNearbyAction::Execute(Event event) PlayerbotAI* botAi = GET_PLAYERBOT_AI(player); - if (!sPlayerbotAIConfig->randomBotInvitePlayer && botAi && botAi->IsRealPlayer()) + if (!sPlayerbotAIConfig.randomBotInvitePlayer && botAi && botAi->IsRealPlayer()) continue; if (botAi) @@ -193,16 +192,16 @@ bool GuildManageNearbyAction::Execute(Event event) if (botAi->GetGuilderType() == GuilderType::SOLO && !botAi->HasRealPlayerMaster()) //Do not invite solo players. continue; - if (botAi->HasActivePlayerMaster() && !sRandomPlayerbotMgr->IsRandomBot(player)) //Do not invite alts of active players. + if (botAi->HasActivePlayerMaster() && !sRandomPlayerbotMgr.IsRandomBot(player)) //Do not invite alts of active players. continue; } bool sameGroup = bot->GetGroup() && bot->GetGroup()->IsMember(player->GetGUID()); - if (!sameGroup && sServerFacade->GetDistance2d(bot, player) > sPlayerbotAIConfig->spellDistance) + if (!sameGroup && ServerFacade::instance().GetDistance2d(bot, player) > sPlayerbotAIConfig.spellDistance) continue; - if (sPlayerbotAIConfig->inviteChat && (sRandomPlayerbotMgr->IsRandomBot(bot) || !botAI->HasActivePlayerMaster())) + if (sPlayerbotAIConfig.inviteChat && (sRandomPlayerbotMgr.IsRandomBot(bot) || !botAI->HasActivePlayerMaster())) { /* std::map placeholders; placeholders["%name"] = player->GetName(); @@ -210,8 +209,8 @@ bool GuildManageNearbyAction::Execute(Event event) placeholders["%guildname"] = guild->GetName(); AreaTableEntry const* current_area = botAI->GetCurrentArea(); AreaTableEntry const* current_zone = botAI->GetCurrentZone(); - placeholders["%area_name"] = current_area ? current_area->area_name[BroadcastHelper::GetLocale()] : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? current_zone->area_name[BroadcastHelper::GetLocale()] : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? current_area->area_name[BroadcastHelper::GetLocale()] : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? current_zone->area_name[BroadcastHelper::GetLocale()] : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); std::vector lines; @@ -219,45 +218,45 @@ bool GuildManageNearbyAction::Execute(Event event) switch ((urand(0, 10) * urand(0, 10)) / 10) { case 0: - lines.push_back(BOT_TEXT2("Hey %name do you want to join my guild?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("Hey %name do you want to join my guild?", placeholders)); break; case 1: - lines.push_back(BOT_TEXT2("Hey man you wanna join my guild %name?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("Hey man you wanna join my guild %name?", placeholders)); break; case 2: - lines.push_back(BOT_TEXT2("I think you would be a good contribution to %guildname. Would you like to join %name?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("I think you would be a good contribution to %guildname. Would you like to join %name?", placeholders)); break; case 3: - lines.push_back(BOT_TEXT2("My guild %guildname has %members quality members. Would you like to make it 1 more %name?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("My guild %guildname has %members quality members. Would you like to make it 1 more %name?", placeholders)); break; case 4: - lines.push_back(BOT_TEXT2("Hey %name do you want to join %guildname? We have %members members and looking to become number 1 of the server.", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("Hey %name do you want to join %guildname? We have %members members and looking to become number 1 of the server.", placeholders)); break; case 5: - lines.push_back(BOT_TEXT2("I'm not really good at smalltalk. Do you wanna join my guild %name/r?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("I'm not really good at smalltalk. Do you wanna join my guild %name/r?", placeholders)); break; case 6: - lines.push_back(BOT_TEXT2("Welcome to %zone_name.... do you want to join my guild %name?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("Welcome to %zone_name.... do you want to join my guild %name?", placeholders)); break; case 7: - lines.push_back(BOT_TEXT2("%name, you should join my guild!", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("%name, you should join my guild!", placeholders)); break; case 8: - lines.push_back(BOT_TEXT2("%name, I got this guild....", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("%name, I got this guild....", placeholders)); break; case 9: - lines.push_back(BOT_TEXT2("You are actually going to join my guild %name?", placeholders)); - lines.push_back(BOT_TEXT2("Haha.. you are the man! We are going to raid Molten...", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("You are actually going to join my guild %name?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("Haha.. you are the man! We are going to raid Molten...", placeholders)); break; case 10: - lines.push_back(BOT_TEXT2("Hey Hey! do you guys wanna join my gild????", placeholders)); - lines.push_back(BOT_TEXT2("We've got a bunch of high levels and we are really super friendly..", placeholders)); - lines.push_back(BOT_TEXT2("..and watch your dog and do your homework...", placeholders)); - lines.push_back(BOT_TEXT2("..and we raid once a week and are working on MC raids...", placeholders)); - lines.push_back(BOT_TEXT2("..and we have more members than just me...", placeholders)); - lines.push_back(BOT_TEXT2("..and please stop I'm lonenly and we can get a ride the whole time...", placeholders)); - lines.push_back(BOT_TEXT2("..and it's really beautifull and I feel like crying...", placeholders)); - lines.push_back(BOT_TEXT2("So what do you guys say are you going to join are you going to join?", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("Hey Hey! do you guys wanna join my gild????", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("We've got a bunch of high levels and we are really super friendly..", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("..and watch your dog and do your homework...", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("..and we raid once a week and are working on MC raids...", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("..and we have more members than just me...", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("..and please stop I'm lonenly and we can get a ride the whole time...", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("..and it's really beautifull and I feel like crying...", placeholders)); + lines.push_back(PlayerbotTextMgr::instance().GetBotText("So what do you guys say are you going to join are you going to join?", placeholders)); break; } @@ -274,7 +273,7 @@ bool GuildManageNearbyAction::Execute(Event event) if (botAI->DoSpecificAction("guild invite", Event("guild management", guid), true)) { - if (sPlayerbotAIConfig->inviteChat) + if (sPlayerbotAIConfig.inviteChat) return true; found++; } diff --git a/src/Ai/Base/Actions/HelpAction.cpp b/src/Ai/Base/Actions/HelpAction.cpp index 3dbe1d6e4b..afa56fc022 100644 --- a/src/Ai/Base/Actions/HelpAction.cpp +++ b/src/Ai/Base/Actions/HelpAction.cpp @@ -7,13 +7,13 @@ #include "ChatActionContext.h" #include "Event.h" -#include "Playerbots.h" +#include "AiObjectContext.h" HelpAction::HelpAction(PlayerbotAI* botAI) : Action(botAI, "help") { chatContext = new ChatActionContext(); } HelpAction::~HelpAction() { delete chatContext; } -bool HelpAction::Execute(Event event) +bool HelpAction::Execute(Event) { TellChatCommands(); TellStrategies(); diff --git a/src/Ai/Base/Actions/HireAction.cpp b/src/Ai/Base/Actions/HireAction.cpp index f8b3653964..53e399caab 100644 --- a/src/Ai/Base/Actions/HireAction.cpp +++ b/src/Ai/Base/Actions/HireAction.cpp @@ -6,15 +6,16 @@ #include "HireAction.h" #include "Event.h" -#include "Playerbots.h" +#include "RandomPlayerbotMgr.h" +#include "PlayerbotAI.h" -bool HireAction::Execute(Event event) +bool HireAction::Execute(Event) { Player* master = GetMaster(); if (!master) return false; - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!RandomPlayerbotMgr::instance().IsRandomBot(bot)) return false; uint32 account = master->GetSession()->GetAccountId(); @@ -39,7 +40,7 @@ bool HireAction::Execute(Event event) return false; } - uint32 discount = sRandomPlayerbotMgr->GetTradeDiscount(bot, master); + uint32 discount = RandomPlayerbotMgr::instance().GetTradeDiscount(bot, master); uint32 m = 1 + (bot->GetLevel() / 10); uint32 moneyReq = m * 5000 * bot->GetLevel(); if (discount < moneyReq) @@ -54,7 +55,7 @@ bool HireAction::Execute(Event event) botAI->TellMaster("I will join you at your next relogin"); bot->SetMoney(moneyReq); - sRandomPlayerbotMgr->Remove(bot); + RandomPlayerbotMgr::instance().Remove(bot); CharacterDatabase.Execute("UPDATE characters SET account = {} WHERE guid = {}", account, bot->GetGUID().GetCounter()); diff --git a/src/Ai/Base/Actions/ImbueAction.cpp b/src/Ai/Base/Actions/ImbueAction.cpp index 8c151ef8a6..1f07d21e34 100644 --- a/src/Ai/Base/Actions/ImbueAction.cpp +++ b/src/Ai/Base/Actions/ImbueAction.cpp @@ -10,7 +10,7 @@ ImbueWithPoisonAction::ImbueWithPoisonAction(PlayerbotAI* botAI) : Action(botAI, "apply poison") {} -bool ImbueWithPoisonAction::Execute(Event event) +bool ImbueWithPoisonAction::Execute(Event) { if (bot->IsInCombat()) return false; @@ -103,7 +103,7 @@ bool ImbueWithPoisonAction::Execute(Event event) // Search and apply stone to weapons ImbueWithStoneAction::ImbueWithStoneAction(PlayerbotAI* botAI) : Action(botAI, "apply stone") {} -bool ImbueWithStoneAction::Execute(Event event) +bool ImbueWithStoneAction::Execute(Event) { if (bot->IsInCombat()) return false; @@ -148,7 +148,7 @@ bool ImbueWithStoneAction::Execute(Event event) // Search and apply oil to weapons ImbueWithOilAction::ImbueWithOilAction(PlayerbotAI* botAI) : Action(botAI, "apply oil") {} -bool ImbueWithOilAction::Execute(Event event) +bool ImbueWithOilAction::Execute(Event) { if (bot->IsInCombat()) return false; @@ -201,7 +201,7 @@ static const uint32 uPrioritizedHealingItemIds[19] = { TryEmergencyAction::TryEmergencyAction(PlayerbotAI* botAI) : Action(botAI, "try emergency") {} -bool TryEmergencyAction::Execute(Event event) +bool TryEmergencyAction::Execute(Event) { // Do not use consumable if bot can heal self if ((botAI->IsHeal(bot)) && (bot->GetPowerPct(POWER_MANA) > 20)) diff --git a/src/Ai/Base/Actions/InventoryAction.cpp b/src/Ai/Base/Actions/InventoryAction.cpp index f7b606a91a..c929e1787e 100644 --- a/src/Ai/Base/Actions/InventoryAction.cpp +++ b/src/Ai/Base/Actions/InventoryAction.cpp @@ -373,9 +373,12 @@ ItemIds InventoryAction::FindOutfitItems(std::string const name) std::string const InventoryAction::parseOutfitName(std::string const outfit) { - uint32 pos = outfit.find("="); - if (pos == -1) - return ""; + const uint64_t pos = outfit.find("="); + + if (pos == std::string::npos) + { + return outfit; + } return outfit.substr(0, pos); } @@ -387,9 +390,7 @@ ItemIds InventoryAction::parseOutfitItems(std::string const text) uint8 pos = text.find("=") + 1; while (pos < text.size()) { - uint32 endPos = text.find(',', pos); - if (endPos == -1) - endPos = text.size(); + uint64_t endPos = text.find(',', pos); std::string const idC = text.substr(pos, endPos - pos); uint32 id = atol(idC.c_str()); diff --git a/src/Ai/Base/Actions/InviteToGroupAction.cpp b/src/Ai/Base/Actions/InviteToGroupAction.cpp index bec515fefb..1f99ade256 100644 --- a/src/Ai/Base/Actions/InviteToGroupAction.cpp +++ b/src/Ai/Base/Actions/InviteToGroupAction.cpp @@ -8,7 +8,6 @@ #include "BroadcastHelper.h" #include "Event.h" #include "GuildMgr.h" -#include "Log.h" #include "PlayerbotOperations.h" #include "Playerbots.h" #include "PlayerbotWorldThreadProcessor.h" @@ -31,7 +30,7 @@ bool InviteToGroupAction::Invite(Player* inviter, Player* player) if (!group->isRaidGroup() && group->GetMembersCount() > 4) { auto convertOp = std::make_unique(inviter->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(convertOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(convertOp)); } } @@ -44,7 +43,7 @@ bool InviteToGroupAction::Invite(Player* inviter, Player* player) return true; } -bool InviteNearbyToGroupAction::Execute(Event event) +bool InviteNearbyToGroupAction::Execute(Event) { GuidVector nearGuids = botAI->GetAiObjectContext()->GetValue("nearest friendly players")->Get(); for (auto& i : nearGuids) @@ -62,7 +61,7 @@ bool InviteNearbyToGroupAction::Execute(Event event) if (player->GetGroup()) continue; - if (!sPlayerbotAIConfig->randomBotInvitePlayer && GET_PLAYERBOT_AI(player)->IsRealPlayer()) + if (!PlayerbotAIConfig::instance().randomBotInvitePlayer && GET_PLAYERBOT_AI(player)->IsRealPlayer()) continue; Group* group = bot->GetGroup(); @@ -88,7 +87,7 @@ bool InviteNearbyToGroupAction::Execute(Event event) if (abs(int32(player->GetLevel() - bot->GetLevel())) > 2) continue; - if (sServerFacade->GetDistance2d(bot, player) > sPlayerbotAIConfig->sightDistance) + if (ServerFacade::instance().GetDistance2d(bot, player) > PlayerbotAIConfig::instance().sightDistance) continue; // When inviting the 5th member of the group convert to raid for future invites. @@ -96,19 +95,19 @@ bool InviteNearbyToGroupAction::Execute(Event event) bot->GetGroup()->GetMembersCount() > 3) { auto convertOp = std::make_unique(bot->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(convertOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(convertOp)); } - if (sPlayerbotAIConfig->inviteChat && sRandomPlayerbotMgr->IsRandomBot(bot)) + if (PlayerbotAIConfig::instance().inviteChat && RandomPlayerbotMgr::instance().IsRandomBot(bot)) { std::map placeholders; placeholders["%player"] = player->GetName(); if (group && group->isRaidGroup()) - bot->Say(BOT_TEXT2("join_raid", placeholders), + bot->Say(PlayerbotTextMgr::instance().GetBotText("join_raid", placeholders), (bot->GetTeamId() == TEAM_ALLIANCE ? LANG_COMMON : LANG_ORCISH)); else - bot->Say(BOT_TEXT2("join_group", placeholders), + bot->Say(PlayerbotTextMgr::instance().GetBotText("join_group", placeholders), (bot->GetTeamId() == TEAM_ALLIANCE ? LANG_COMMON : LANG_ORCISH)); } @@ -120,7 +119,7 @@ bool InviteNearbyToGroupAction::Execute(Event event) bool InviteNearbyToGroupAction::isUseful() { - if (!sPlayerbotAIConfig->randomBotGroupNearby) + if (!PlayerbotAIConfig::instance().randomBotGroupNearby) return false; if (bot->InBattleground()) @@ -166,11 +165,9 @@ std::vector InviteGuildToGroupAction::getGuildMembers() return worker.GetResult(); } -bool InviteGuildToGroupAction::Execute(Event event) +bool InviteGuildToGroupAction::Execute(Event) { - Guild* guild = sGuildMgr->GetGuildById(bot->GetGuildId()); - - for (auto& member : getGuildMembers()) + for (auto& member : this->getGuildMembers()) { Player* player = member; @@ -186,7 +183,7 @@ bool InviteGuildToGroupAction::Execute(Event event) if (player->isDND()) continue; - if (!sPlayerbotAIConfig->randomBotInvitePlayer && GET_PLAYERBOT_AI(player)->IsRealPlayer()) + if (!PlayerbotAIConfig::instance().randomBotInvitePlayer && GET_PLAYERBOT_AI(player)->IsRealPlayer()) continue; if (player->IsBeingTeleported()) @@ -221,7 +218,7 @@ bool InviteGuildToGroupAction::Execute(Event event) player->GetLevel() + 5) // Do not invite members that too low level or risk dragging them to deadly places. continue; - if (!playerAi && sServerFacade->GetDistance2d(bot, player) > sPlayerbotAIConfig->sightDistance) + if (!playerAi && ServerFacade::instance().GetDistance2d(bot, player) > PlayerbotAIConfig::instance().sightDistance) continue; Group* group = bot->GetGroup(); @@ -230,16 +227,16 @@ bool InviteGuildToGroupAction::Execute(Event event) bot->GetGroup()->GetMembersCount() > 3) { auto convertOp = std::make_unique(bot->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(convertOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(convertOp)); } - if (sPlayerbotAIConfig->inviteChat && - (sRandomPlayerbotMgr->IsRandomBot(bot) || !botAI->HasActivePlayerMaster())) + if (PlayerbotAIConfig::instance().inviteChat && + (RandomPlayerbotMgr::instance().IsRandomBot(bot) || !botAI->HasActivePlayerMaster())) { BroadcastHelper::BroadcastGuildGroupOrRaidInvite(botAI, bot, player, group); } - return Invite(bot, player); + return this->Invite(bot, player); } return false; @@ -373,7 +370,7 @@ bool LfgAction::Execute(Event event) else { auto convertOp = std::make_unique(requester->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(convertOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(convertOp)); } } diff --git a/src/Ai/Base/Actions/LeaveGroupAction.cpp b/src/Ai/Base/Actions/LeaveGroupAction.cpp index a279c9426c..47b7724827 100644 --- a/src/Ai/Base/Actions/LeaveGroupAction.cpp +++ b/src/Ai/Base/Actions/LeaveGroupAction.cpp @@ -33,7 +33,7 @@ bool PartyCommandAction::Execute(Event event) Player* master = GetMaster(); if (master && member == master->GetName()) { - if (sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sRandomPlayerbotMgr.IsRandomBot(bot)) { Player* newMaster = botAI->FindNewMaster(); if (newMaster || bot->InBattleground()) @@ -92,7 +92,7 @@ bool LeaveGroupAction::Leave() return true; } -bool LeaveFarAwayAction::Execute(Event event) +bool LeaveFarAwayAction::Execute(Event) { // allow bot to leave party when they want return Leave(); @@ -150,7 +150,7 @@ bool LeaveFarAwayAction::isUseful() if (abs(int32(groupLeader->GetLevel() - bot->GetLevel())) > 4) return true; - if (bot->GetMapId() != groupLeader->GetMapId() || bot->GetDistance2d(groupLeader) >= 2 * sPlayerbotAIConfig->rpgDistance) + if (bot->GetMapId() != groupLeader->GetMapId() || bot->GetDistance2d(groupLeader) >= 2 * sPlayerbotAIConfig.rpgDistance) { return true; } diff --git a/src/Ai/Base/Actions/LfgActions.cpp b/src/Ai/Base/Actions/LfgActions.cpp index 15f8b92f25..1a3a332715 100644 --- a/src/Ai/Base/Actions/LfgActions.cpp +++ b/src/Ai/Base/Actions/LfgActions.cpp @@ -8,19 +8,22 @@ #include "AiFactory.h" #include "ItemVisitors.h" #include "LFGMgr.h" -#include "LFGPackets.h" #include "Opcodes.h" #include "Playerbots.h" #include "World.h" #include "WorldPacket.h" +#include "RandomPlayerbotMgr.h" using namespace lfg; -bool LfgJoinAction::Execute(Event event) { return JoinLFG(); } +bool LfgJoinAction::Execute(Event) +{ + return JoinLFG(); +} -uint32 LfgJoinAction::GetRoles() +uint8_t LfgJoinAction::GetRoles() const { - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!RandomPlayerbotMgr::instance().IsRandomBot(bot)) { if (botAI->IsTank(bot)) return PLAYER_ROLE_TANK; @@ -30,7 +33,7 @@ uint32 LfgJoinAction::GetRoles() return PLAYER_ROLE_DAMAGE; } - uint8 spec = AiFactory::GetPlayerSpecTab(bot); + const uint8_t spec = AiFactory::GetPlayerSpecTab(bot); switch (bot->getClass()) { case CLASS_DRUID: @@ -101,7 +104,7 @@ bool LfgJoinAction::JoinLFG() LfgDungeonSet list; std::vector selected; - std::vector dungeons = sRandomPlayerbotMgr->LfgDungeons[bot->GetTeamId()]; + std::vector dungeons = RandomPlayerbotMgr::instance().LfgDungeons[bot->GetTeamId()]; if (!dungeons.size()) return false; @@ -115,9 +118,16 @@ bool LfgJoinAction::JoinLFG() auto const& botLevel = bot->GetLevel(); /*LFG_TYPE_RANDOM on classic is 15-58 so bot over level 25 will never queue*/ - if (dungeon->MinLevel && (botLevel < dungeon->MinLevel || botLevel > dungeon->MaxLevel) || - (botLevel > dungeon->MinLevel + 10 && dungeon->TypeID == LFG_TYPE_DUNGEON)) + if ( + ( + dungeon->MinLevel != 0 + && (botLevel < dungeon->MinLevel || botLevel > dungeon->MaxLevel) + ) + || (botLevel > dungeon->MinLevel + 10 && dungeon->TypeID == LFG_TYPE_DUNGEON) + ) + { continue; + } selected.push_back(dungeon->ID); list.insert(dungeon->ID); @@ -170,28 +180,31 @@ bool LfgJoinAction::JoinLFG() return true; } -bool LfgRoleCheckAction::Execute(Event event) +bool LfgRoleCheckAction::Execute(Event) { - if (Group* group = bot->GetGroup()) + const Group* const group = bot->GetGroup(); + + if (group == nullptr) { - uint32 currentRoles = sLFGMgr->GetRoles(bot->GetGUID()); - uint32 newRoles = GetRoles(); - // if (currentRoles == newRoles) - // return false; + return false; + } - WorldPacket* packet = new WorldPacket(CMSG_LFG_SET_ROLES); - *packet << (uint8)newRoles; - bot->GetSession()->QueuePacket(packet); - // sLFGMgr->SetRoles(bot->GetGUID(), newRoles); - // sLFGMgr->UpdateRoleCheck(group->GetGUID(), bot->GetGUID(), newRoles); + const uint8_t newRoles = this->GetRoles(); - LOG_INFO("playerbots", "Bot {} {}:{} <{}>: LFG roles checked", bot->GetGUID().ToString().c_str(), - bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->GetLevel(), bot->GetName().c_str()); + WorldPacket* const packet = new WorldPacket(CMSG_LFG_SET_ROLES); + *packet << newRoles; + bot->GetSession()->QueuePacket(packet); - return true; - } + LOG_INFO( + "playerbots", + "Bot {} {}:{} <{}>: LFG roles checked", + bot->GetGUID().ToString().c_str(), + bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", + bot->GetLevel(), + bot->GetName().c_str() + ); - return false; + return true; } bool LfgAcceptAction::Execute(Event event) @@ -216,9 +229,9 @@ bool LfgAcceptAction::Execute(Event event) *packet << id << true; bot->GetSession()->QueuePacket(packet); - if (sRandomPlayerbotMgr->IsRandomBot(bot) && !bot->GetGroup()) + if (RandomPlayerbotMgr::instance().IsRandomBot(bot) && !bot->GetGroup()) { - sRandomPlayerbotMgr->Refresh(bot); + RandomPlayerbotMgr::instance().Refresh(bot); botAI->ResetStrategies(); } @@ -251,9 +264,9 @@ bool LfgAcceptAction::Execute(Event event) *packet << id << true; bot->GetSession()->QueuePacket(packet); - if (sRandomPlayerbotMgr->IsRandomBot(bot) && !bot->GetGroup()) + if (RandomPlayerbotMgr::instance().IsRandomBot(bot) && !bot->GetGroup()) { - sRandomPlayerbotMgr->Refresh(bot); + RandomPlayerbotMgr::instance().Refresh(bot); botAI->ResetStrategies(); } @@ -265,7 +278,7 @@ bool LfgAcceptAction::Execute(Event event) return false; } -bool LfgLeaveAction::Execute(Event event) +bool LfgLeaveAction::Execute(Event) { // Don't leave if lfg strategy enabled // if (botAI->HasStrategy("lfg", BOT_STATE_NON_COMBAT)) @@ -306,7 +319,7 @@ bool LfgTeleportAction::Execute(Event event) bool LfgJoinAction::isUseful() { - if (!sPlayerbotAIConfig->randomBotJoinLfg) + if (!sPlayerbotAIConfig.randomBotJoinLfg) { // botAI->ChangeStrategy("-lfg", BOT_STATE_NON_COMBAT); return false; @@ -337,7 +350,7 @@ bool LfgJoinAction::isUseful() if (bot->isDead()) return false; - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!RandomPlayerbotMgr::instance().IsRandomBot(bot)) return false; Map* map = bot->GetMap(); diff --git a/src/Ai/Base/Actions/LfgActions.h b/src/Ai/Base/Actions/LfgActions.h index 8622a42d76..a45ac2c8a9 100644 --- a/src/Ai/Base/Actions/LfgActions.h +++ b/src/Ai/Base/Actions/LfgActions.h @@ -20,7 +20,7 @@ class LfgJoinAction : public InventoryAction protected: bool JoinLFG(); - uint32 GetRoles(); + uint8_t GetRoles() const; }; class LfgAcceptAction : public LfgJoinAction diff --git a/src/Ai/Base/Actions/ListQuestsActions.cpp b/src/Ai/Base/Actions/ListQuestsActions.cpp index 7968417059..0071b113fe 100644 --- a/src/Ai/Base/Actions/ListQuestsActions.cpp +++ b/src/Ai/Base/Actions/ListQuestsActions.cpp @@ -107,14 +107,14 @@ uint32 ListQuestsAction::ListQuests(bool completed, bool silent, QuestTravelDeta if (travelDetail == QUEST_TRAVEL_DETAIL_SUMMARY) { std::vector allDestinations = - sTravelMgr->getQuestTravelDestinations(bot, questId, true, true, -1); + TravelMgr::instance().getQuestTravelDestinations(bot, questId, true, true, -1); std::vector availDestinations = - sTravelMgr->getQuestTravelDestinations(bot, questId, botAI->GetMaster(), false, -1); + TravelMgr::instance().getQuestTravelDestinations(bot, questId, botAI->GetMaster(), false, -1); uint32 desTot = allDestinations.size(); uint32 desAvail = availDestinations.size(); - uint32 desFull = desAvail - sTravelMgr->getQuestTravelDestinations(bot, questId, false, false, -1).size(); - uint32 desRange = desAvail - sTravelMgr->getQuestTravelDestinations(bot, questId, false, false).size(); + uint32 desFull = desAvail - TravelMgr::instance().getQuestTravelDestinations(bot, questId, false, false, -1).size(); + uint32 desRange = desAvail - TravelMgr::instance().getQuestTravelDestinations(bot, questId, false, false).size(); uint32 tpoints = 0; uint32 apoints = 0; @@ -140,7 +140,7 @@ uint32 ListQuestsAction::ListQuests(bool completed, bool silent, QuestTravelDeta { uint32 limit = 0; std::vector allDestinations = - sTravelMgr->getQuestTravelDestinations(bot, questId, true, true, -1); + TravelMgr::instance().getQuestTravelDestinations(bot, questId, true, true, -1); std::sort(allDestinations.begin(), allDestinations.end(), [botPos](TravelDestination* i, TravelDestination* j) { diff --git a/src/Ai/Base/Actions/ListSpellsAction.cpp b/src/Ai/Base/Actions/ListSpellsAction.cpp index 6f67aef1aa..aed7adc6e7 100644 --- a/src/Ai/Base/Actions/ListSpellsAction.cpp +++ b/src/Ai/Base/Actions/ListSpellsAction.cpp @@ -136,7 +136,7 @@ std::vector> ListSpellsAction::GetSpellList(std:: if (spellInfo->IsPassive()) continue; - SkillLineAbilityEntry const* skillLine = sPlayerbotSpellRepository->GetSkillLine(itr->first); + SkillLineAbilityEntry const* skillLine = PlayerbotSpellRepository::Instance().GetSkillLine(itr->first); if (skill != SKILL_NONE && (!skillLine || skillLine->SkillLine != skill)) continue; @@ -175,7 +175,7 @@ std::vector> ListSpellsAction::GetSpellList(std:: FindItemByIdVisitor visitor(itemid); uint32 reagentsInInventory = InventoryAction::GetItemCount(&visitor); - bool buyable = sPlayerbotSpellRepository->IsItemBuyable(itemid); + bool buyable = PlayerbotSpellRepository::Instance().IsItemBuyable(itemid); if (!buyable) { uint32 craftable = reagentsInInventory / reagentsRequired; diff --git a/src/Ai/Base/Actions/LootAction.cpp b/src/Ai/Base/Actions/LootAction.cpp index 2e0656e711..93368f5244 100644 --- a/src/Ai/Base/Actions/LootAction.cpp +++ b/src/Ai/Base/Actions/LootAction.cpp @@ -25,7 +25,7 @@ bool LootAction::Execute(Event /*event*/) LootObject prevLoot = AI_VALUE(LootObject, "loot target"); LootObject const& lootObject = - AI_VALUE(LootObjectStack*, "available loot")->GetLoot(sPlayerbotAIConfig->lootDistance); + AI_VALUE(LootObjectStack*, "available loot")->GetLoot(sPlayerbotAIConfig.lootDistance); if (!prevLoot.IsEmpty() && prevLoot.guid != lootObject.guid) { @@ -37,7 +37,7 @@ bool LootAction::Execute(Event /*event*/) // Provide a system to check if the game object id is disallowed in the user configurable list or not. // Check if the game object id is disallowed in the user configurable list or not. - if (sPlayerbotAIConfig->disallowedGameObjects.find(lootObject.guid.GetEntry()) != sPlayerbotAIConfig->disallowedGameObjects.end()) + if (sPlayerbotAIConfig.disallowedGameObjects.find(lootObject.guid.GetEntry()) != sPlayerbotAIConfig.disallowedGameObjects.end()) { return false; // Game object ID is disallowed, so do not proceed } @@ -50,7 +50,7 @@ bool LootAction::Execute(Event /*event*/) bool LootAction::isUseful() { - return sPlayerbotAIConfig->freeMethodLoot || !bot->GetGroup() || bot->GetGroup()->GetLootMethod() != FREE_FOR_ALL; + return sPlayerbotAIConfig.freeMethodLoot || !bot->GetGroup() || bot->GetGroup()->GetLootMethod() != FREE_FOR_ALL; } enum ProfessionSpells @@ -95,7 +95,7 @@ bool OpenLootAction::DoLoot(LootObject& lootObject) if (bot->IsMounted()) { bot->Dismount(); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->lootDelay); // Small delay to avoid animation issues + botAI->SetNextCheckDelay(sPlayerbotAIConfig.lootDelay); // Small delay to avoid animation issues } if (creature && creature->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE)) @@ -104,7 +104,7 @@ bool OpenLootAction::DoLoot(LootObject& lootObject) *packet << lootObject.guid; bot->GetSession()->QueuePacket(packet); // bot->GetSession()->HandleLootOpcode(packet); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->lootDelay); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.lootDelay); return true; } @@ -202,7 +202,7 @@ uint32 OpenLootAction::GetOpeningSpell(LootObject& lootObject, GameObject* go) return spellId; } - return sPlayerbotAIConfig->openGoSpell; + return sPlayerbotAIConfig.openGoSpell; } bool OpenLootAction::CanOpenLock(LootObject& /*lootObject*/, SpellInfo const* spellInfo, GameObject* go) @@ -294,7 +294,7 @@ bool StoreLootAction::AuctionItem(uint32 itemId) AuctionHouseObject* auctionHouse = sAuctionMgr->GetAuctionsMap(ahEntry); - uint32 price = oldItem->GetCount() * proto->BuyPrice * sRandomPlayerbotMgr->GetBuyMultiplier(bot); + uint32 price = oldItem->GetCount() * proto->BuyPrice * sRandomPlayerbotMgr.GetBuyMultiplier(bot); uint32 stackCount = urand(1, proto->GetMaxStackSize()); if (!price || !stackCount) @@ -426,28 +426,28 @@ bool StoreLootAction::Execute(Event event) } Player* master = botAI->GetMaster(); - if (sRandomPlayerbotMgr->IsRandomBot(bot) && master) + if (sRandomPlayerbotMgr.IsRandomBot(bot) && master) { - uint32 price = itemcount * proto->BuyPrice * sRandomPlayerbotMgr->GetBuyMultiplier(bot) + gold; + uint32 price = itemcount * proto->BuyPrice * sRandomPlayerbotMgr.GetBuyMultiplier(bot) + gold; if (price) - sRandomPlayerbotMgr->AddTradeDiscount(bot, master, price); + sRandomPlayerbotMgr.AddTradeDiscount(bot, master, price); if (Group* group = bot->GetGroup()) for (GroupReference* ref = group->GetFirstMember(); ref; ref = ref->next()) if (ref->GetSource() != bot) - sGuildTaskMgr->CheckItemTask(itemid, itemcount, ref->GetSource(), bot); + GuildTaskMgr::instance().CheckItemTask(itemid, itemcount, ref->GetSource(), bot); } WorldPacket* packet = new WorldPacket(CMSG_AUTOSTORE_LOOT_ITEM, 1); *packet << itemindex; bot->GetSession()->QueuePacket(packet); // bot->GetSession()->HandleAutostoreLootItemOpcode(packet); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->lootDelay); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.lootDelay); - if (proto->Quality > ITEM_QUALITY_NORMAL && !urand(0, 50) && botAI->HasStrategy("emote", BOT_STATE_NON_COMBAT) && sPlayerbotAIConfig->randomBotEmote) + if (proto->Quality > ITEM_QUALITY_NORMAL && !urand(0, 50) && botAI->HasStrategy("emote", BOT_STATE_NON_COMBAT) && sPlayerbotAIConfig.randomBotEmote) botAI->PlayEmote(TEXT_EMOTE_CHEER); - if (proto->Quality >= ITEM_QUALITY_RARE && !urand(0, 1) && botAI->HasStrategy("emote", BOT_STATE_NON_COMBAT) && sPlayerbotAIConfig->randomBotEmote) + if (proto->Quality >= ITEM_QUALITY_RARE && !urand(0, 1) && botAI->HasStrategy("emote", BOT_STATE_NON_COMBAT) && sPlayerbotAIConfig.randomBotEmote) botAI->PlayEmote(TEXT_EMOTE_CHEER); BroadcastHelper::BroadcastLootingItem(botAI, bot, proto); @@ -498,7 +498,7 @@ bool StoreLootAction::IsLootAllowed(uint32 itemid, PlayerbotAI* botAI) { // if (AI_VALUE2(uint32, "item count", proto->Name1) < quest->RequiredItemCount[i]) // { - // if (botAI->GetMaster() && sPlayerbotAIConfig->syncQuestWithPlayer) + // if (botAI->GetMaster() && sPlayerbotAIConfig.syncQuestWithPlayer) // return false; //Quest is autocomplete for the bot so no item needed. // } @@ -514,7 +514,7 @@ bool StoreLootAction::IsLootAllowed(uint32 itemid, PlayerbotAI* botAI) bool canLoot = lootStrategy->CanLoot(proto, context); // if (canLoot && proto->Bonding == BIND_WHEN_PICKED_UP && botAI->HasActivePlayerMaster()) - // canLoot = sPlayerbotAIConfig->IsInRandomAccountList(botAI->GetBot()->GetSession()->GetAccountId()); + // canLoot = sPlayerbotAIConfig.IsInRandomAccountList(botAI->GetBot()->GetSession()->GetAccountId()); return canLoot; } diff --git a/src/Ai/Base/Actions/LootRollAction.cpp b/src/Ai/Base/Actions/LootRollAction.cpp index 912f75fddf..0047522730 100644 --- a/src/Ai/Base/Actions/LootRollAction.cpp +++ b/src/Ai/Base/Actions/LootRollAction.cpp @@ -13,7 +13,7 @@ #include "PlayerbotAIConfig.h" #include "Playerbots.h" -bool LootRollAction::Execute(Event event) +bool LootRollAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -27,7 +27,6 @@ bool LootRollAction::Execute(Event event) continue; } ObjectGuid guid = roll->itemGUID; - uint32 slot = roll->itemSlot; uint32 itemId = roll->itemid; int32 randomProperty = 0; if (roll->itemRandomPropId) @@ -84,11 +83,11 @@ bool LootRollAction::Execute(Event event) break; } } - if (sPlayerbotAIConfig->lootRollLevel == 0) + if (sPlayerbotAIConfig.lootRollLevel == 0) { vote = PASS; } - else if (sPlayerbotAIConfig->lootRollLevel == 1) + else if (sPlayerbotAIConfig.lootRollLevel == 1) { if (vote == NEED) { @@ -186,7 +185,6 @@ bool MasterLootRollAction::Execute(Event event) if (!group) return false; - RollVote vote = CalculateRollVote(proto); group->CountRollVote(bot->GetGUID(), creatureGuid, CalculateRollVote(proto)); return true; diff --git a/src/Ai/Base/Actions/LootStrategyAction.cpp b/src/Ai/Base/Actions/LootStrategyAction.cpp index 68f8089c2e..b5f328b041 100644 --- a/src/Ai/Base/Actions/LootStrategyAction.cpp +++ b/src/Ai/Base/Actions/LootStrategyAction.cpp @@ -16,7 +16,6 @@ bool LootStrategyAction::Execute(Event event) { std::string const strategy = event.getParam(); - LootObjectStack* lootItems = AI_VALUE(LootObjectStack*, "available loot"); std::set& alwaysLootItems = AI_VALUE(std::set&, "always loot list"); Value* lootStrategy = context->GetValue("loot strategy"); diff --git a/src/Ai/Base/Actions/MailAction.cpp b/src/Ai/Base/Actions/MailAction.cpp index 4ee2fee6d7..cbbc6eb6c5 100644 --- a/src/Ai/Base/Actions/MailAction.cpp +++ b/src/Ai/Base/Actions/MailAction.cpp @@ -78,7 +78,7 @@ class TellMailProcessor : public MailProcessor class TakeMailProcessor : public MailProcessor { public: - bool Process(uint32 index, Mail* mail, PlayerbotAI* botAI) override + bool Process(uint32_t, Mail* mail, PlayerbotAI* botAI) override { Player* bot = botAI->GetBot(); if (!CheckBagSpace(bot)) @@ -104,8 +104,14 @@ class TakeMailProcessor : public MailProcessor { std::vector guids; for (MailItemInfoVec::iterator i = mail->items.begin(); i != mail->items.end(); ++i) - if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(i->item_template)) + { + const ItemTemplate* const itemTemplate = ObjectMgr::instance()->GetItemTemplate(i->item_template); + + if (itemTemplate != nullptr) + { guids.push_back(i->item_guid); + } + } for (std::vector::iterator i = guids.begin(); i != guids.end(); ++i) { @@ -134,7 +140,7 @@ class TakeMailProcessor : public MailProcessor private: bool CheckBagSpace(Player* bot) { - uint32 totalused = 0, total = 16; + uint32 totalused = 0; for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < INVENTORY_SLOT_ITEM_END; slot++) if (bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) ++totalused; @@ -157,7 +163,7 @@ class TakeMailProcessor : public MailProcessor class DeleteMailProcessor : public MailProcessor { public: - bool Process(uint32 index, Mail* mail, PlayerbotAI* botAI) override + bool Process(uint32_t, Mail* mail, PlayerbotAI* botAI) override { std::ostringstream out; out << "|cffffffff" << mail->subject << "|cffff0000 deleted"; @@ -172,7 +178,7 @@ class DeleteMailProcessor : public MailProcessor class ReadMailProcessor : public MailProcessor { public: - bool Process(uint32 index, Mail* mail, PlayerbotAI* botAI) override + bool Process(uint32_t, Mail* mail, PlayerbotAI* botAI) override { std::ostringstream out, body; out << "|cffffffff" << mail->subject; diff --git a/src/Ai/Base/Actions/MoveToRpgTargetAction.cpp b/src/Ai/Base/Actions/MoveToRpgTargetAction.cpp index 618af10af1..0fbbf6b7e9 100644 --- a/src/Ai/Base/Actions/MoveToRpgTargetAction.cpp +++ b/src/Ai/Base/Actions/MoveToRpgTargetAction.cpp @@ -11,7 +11,7 @@ #include "LastMovementValue.h" #include "Playerbots.h" -bool MoveToRpgTargetAction::Execute(Event event) +bool MoveToRpgTargetAction::Execute(Event) { GuidPosition guidP = AI_VALUE(GuidPosition, "rpg target"); Unit* unit = botAI->GetUnit(guidP); @@ -24,7 +24,6 @@ bool MoveToRpgTargetAction::Execute(Event event) { return false; } - Player* player = guidP.GetPlayer(); WorldObject* wo = nullptr; if (unit) @@ -61,7 +60,7 @@ bool MoveToRpgTargetAction::Execute(Event event) } if ((unit && unit->isMoving() && !urand(0, 20)) || !ChooseRpgTargetAction::isFollowValid(bot, wo) || - guidP.distance(bot) > sPlayerbotAIConfig->reactDistance * 2 || !urand(0, 50)) + guidP.distance(bot) > sPlayerbotAIConfig.reactDistance * 2 || !urand(0, 50)) { AI_VALUE(GuidSet&, "ignore rpg target").insert(AI_VALUE(GuidPosition, "rpg target")); RESET_AI_VALUE(GuidPosition, "rpg target"); @@ -73,7 +72,7 @@ bool MoveToRpgTargetAction::Execute(Event event) float z = wo->GetPositionZ(); float mapId = wo->GetMapId(); - if (sPlayerbotAIConfig->randombotsWalkingRPG) + if (sPlayerbotAIConfig.randombotsWalkingRPG) if (!bot->IsOutdoors()) bot->m_movementInfo.AddMovementFlag(MOVEMENTFLAG_WALKING); diff --git a/src/Ai/Base/Actions/MoveToTravelTargetAction.cpp b/src/Ai/Base/Actions/MoveToTravelTargetAction.cpp index ed60339b82..1679a824e1 100644 --- a/src/Ai/Base/Actions/MoveToTravelTargetAction.cpp +++ b/src/Ai/Base/Actions/MoveToTravelTargetAction.cpp @@ -7,10 +7,9 @@ #include "ChooseRpgTargetAction.h" #include "LootObjectStack.h" -#include "PathGenerator.h" #include "Playerbots.h" -bool MoveToTravelTargetAction::Execute(Event event) +bool MoveToTravelTargetAction::Execute(Event) { TravelTarget* target = AI_VALUE(TravelTarget*, "travel target"); @@ -43,7 +42,7 @@ bool MoveToTravelTargetAction::Execute(Event event) if (memberDistance < 50.0f) continue; - if (memberDistance > sPlayerbotAIConfig->reactDistance * 20) + if (memberDistance > sPlayerbotAIConfig.reactDistance * 20) continue; // float memberAngle = botLocation.getAngleBetween(targetPos, memberPos); @@ -65,9 +64,9 @@ bool MoveToTravelTargetAction::Execute(Event event) botAI->TellMasterNoFacing(out); } - target->setExpireIn(target->getTimeLeft() + sPlayerbotAIConfig->maxWaitForMove); + target->setExpireIn(target->getTimeLeft() + sPlayerbotAIConfig.maxWaitForMove); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->maxWaitForMove); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.maxWaitForMove); return true; } @@ -80,7 +79,7 @@ bool MoveToTravelTargetAction::Execute(Event event) if (target->getMaxTravelTime() > target->getTimeLeft()) // The bot is late. Speed it up. { - // distance = sPlayerbotAIConfig->fleeDistance; + // distance = sPlayerbotAIConfig.fleeDistance; // angle = bot->GetAngle(location.GetPositionX(), location.GetPositionY()); // location = botLocation.getLocation(); } diff --git a/src/Ai/Base/Actions/MovementActions.cpp b/src/Ai/Base/Actions/MovementActions.cpp index 69e5c278ba..a052fe2e3f 100644 --- a/src/Ai/Base/Actions/MovementActions.cpp +++ b/src/Ai/Base/Actions/MovementActions.cpp @@ -15,7 +15,6 @@ #include "FleeManager.h" #include "G3D/Vector3.h" #include "GameObject.h" -#include "Geometry.h" #include "LastMovementValue.h" #include "LootObjectStack.h" #include "Map.h" @@ -36,9 +35,7 @@ #include "SpellAuraEffects.h" #include "SpellInfo.h" #include "Stances.h" -#include "TargetedMovementGenerator.h" #include "Timer.h" -#include "Transport.h" #include "Unit.h" #include "Vehicle.h" #include "WaypointMovementGenerator.h" @@ -51,7 +48,7 @@ MovementAction::MovementAction(PlayerbotAI* botAI, std::string const name) : Act void MovementAction::CreateWp(Player* wpOwner, float x, float y, float z, float o, uint32 entry, bool important) { float dist = wpOwner->GetDistance(x, y, z); - float delay = 1000.0f * dist / wpOwner->GetSpeed(MOVE_RUN) + sPlayerbotAIConfig->reactDelay; + float delay = 1000.0f * dist / wpOwner->GetSpeed(MOVE_RUN) + sPlayerbotAIConfig.reactDelay; // if (!important) // delay *= 0.25; @@ -78,7 +75,6 @@ bool MovementAction::JumpTo(uint32 mapId, float x, float y, float z, MovementPri { return false; } - float botZ = bot->GetPositionZ(); float speed = bot->GetSpeed(MOVE_RUN); MotionMaster& mm = *bot->GetMotionMaster(); mm.Clear(); @@ -100,9 +96,6 @@ bool MovementAction::MoveNear(WorldObject* target, float distance, MovementPrior distance += target->GetCombatReach(); - float x = target->GetPositionX(); - float y = target->GetPositionY(); - float z = target->GetPositionZ(); float followAngle = GetFollowAngle(); for (float angle = followAngle; angle <= followAngle + static_cast(2 * M_PI); @@ -120,7 +113,6 @@ bool MovementAction::MoveNear(WorldObject* target, float distance, MovementPrior return true; } - // botAI->TellError("All paths not in LOS"); return false; } @@ -129,9 +121,6 @@ bool MovementAction::MoveToLOS(WorldObject* target, bool ranged) if (!target) return false; - // std::ostringstream out; out << "Moving to LOS!"; - // bot->Say(out.str(), LANG_UNIVERSAL); - float x = target->GetPositionX(); float y = target->GetPositionY(); float z = target->GetPositionZ(); @@ -176,7 +165,7 @@ bool MovementAction::MoveToLOS(WorldObject* target, bool ranged) return false; } -bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, bool react, bool normal_only, +bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool, bool, bool normal_only, bool exact_waypoint, MovementPriority priority, bool lessDelay, bool backwards) { UpdateMovementState(); @@ -195,8 +184,8 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, bool generatePath = !bot->IsFlying() && !bot->isSwimming(); bool disableMoveSplinePath = - sPlayerbotAIConfig->disableMoveSplinePath >= 2 || - (sPlayerbotAIConfig->disableMoveSplinePath == 1 && bot->InBattleground()); + sPlayerbotAIConfig.disableMoveSplinePath >= 2 || + (sPlayerbotAIConfig.disableMoveSplinePath == 1 && bot->InBattleground()); if (Vehicle* vehicle = bot->GetVehicle()) { VehicleSeatEntry const* seat = vehicle->GetSeatForPassenger(bot); @@ -216,7 +205,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, delay -= botAI->GetReactDelay(); } delay = std::max(.0f, delay); - delay = std::min((float)sPlayerbotAIConfig->maxWaitForMove, delay); + delay = std::min((float)sPlayerbotAIConfig.maxWaitForMove, delay); AI_VALUE(LastMovement&, "last movement").Set(mapId, x, y, z, bot->GetOrientation(), delay, priority); return true; } @@ -241,7 +230,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, delay -= botAI->GetReactDelay(); } delay = std::max(.0f, delay); - delay = std::min((float)sPlayerbotAIConfig->maxWaitForMove, delay); + delay = std::min((float)sPlayerbotAIConfig.maxWaitForMove, delay); AI_VALUE(LastMovement&, "last movement").Set(mapId, x, y, z, bot->GetOrientation(), delay, priority); return true; } @@ -250,7 +239,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, { float modifiedZ; Movement::PointsArray path = - SearchForBestPath(x, y, z, modifiedZ, sPlayerbotAIConfig->maxMovementSearchTime, normal_only); + SearchForBestPath(x, y, z, modifiedZ, sPlayerbotAIConfig.maxMovementSearchTime, normal_only); if (modifiedZ == INVALID_HEIGHT) return false; float distance = bot->GetExactDist(x, y, modifiedZ); @@ -264,7 +253,6 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // bot->CastStop(); // botAI->InterruptSpell(); // } - G3D::Vector3 endP = path.back(); DoMovePoint(bot, x, y, z, generatePath, backwards); float delay = 1000.0f * MoveDelay(distance, backwards); if (lessDelay) @@ -272,7 +260,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, delay -= botAI->GetReactDelay(); } delay = std::max(.0f, delay); - delay = std::min((float)sPlayerbotAIConfig->maxWaitForMove, delay); + delay = std::min((float)sPlayerbotAIConfig.maxWaitForMove, delay); AI_VALUE(LastMovement&, "last movement").Set(mapId, x, y, z, bot->GetOrientation(), delay, priority); return true; } @@ -308,8 +296,8 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // } // } - // float minDist = sPlayerbotAIConfig->targetPosRecalcDistance; //Minium distance a bot should move. - // float maxDist = sPlayerbotAIConfig->reactDistance; //Maxium distance a bot can move in one single + // float minDist = sPlayerbotAIConfig.targetPosRecalcDistance; //Minium distance a bot should move. + // float maxDist = sPlayerbotAIConfig.reactDistance; //Maxium distance a bot can move in one single // action. float originalZ = z; // save original destination height to check // if bot needs to fly up @@ -372,9 +360,9 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // if (startPosition.getMapId() != endPosition.getMapId() || totalDistance > maxDist) // { - // if (!sTravelNodeMap->getNodes().empty() && !bot->InBattleground()) + // if (!TravelNodeMap::instance().getNodes().empty() && !bot->InBattleground()) // { - // if (sPlayerbotAIConfig->tweakValue) + // if (sPlayerbotAIConfig.tweakValue) // { // if (lastMove.future.valid()) // { @@ -388,12 +376,12 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // } // } // else - // movePath = sTravelNodeMap->getFullPath(startPosition, endPosition, bot); + // movePath = TravelNodeMap::instance().getFullPath(startPosition, endPosition, bot); // if (movePath.empty()) // { // //We have no path. Beyond 450yd the standard PathGenerator will probably move the wrong way. - // if (sServerFacade->IsDistanceGreaterThan(totalDistance, maxDist * 3)) + // if (ServerFacade::instance().IsDistanceGreaterThan(totalDistance, maxDist * 3)) // { // movePath.clear(); // movePath.addPoint(endPosition); @@ -402,7 +390,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // bot->StopMoving(); // if (botAI->HasStrategy("debug move", BOT_STATE_NON_COMBAT)) // botAI->TellMasterNoFacing("I have no path"); - // LOG_DEBUG("playerbots", "sServerFacade->IsDistanceGreaterThan(totalDistance, maxDist * 3)"); + // LOG_DEBUG("playerbots", "ServerFacade::instance().IsDistanceGreaterThan(totalDistance, maxDist * 3)"); // return false; // } @@ -450,7 +438,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // if (pathType == TravelNodePathType::portal) // && !botAI->isRealPlayer()) // { // //Log bot movement - // if (sPlayerbotAIConfig->hasLog("bot_movement.csv")) + // if (sPlayerbotAIConfig.hasLog("bot_movement.csv")) // { // WorldPosition telePos; // if (entry) @@ -463,7 +451,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // telePos = movePosition; // std::ostringstream out; - // out << sPlayerbotAIConfig->GetTimestampStr() << "+00,"; + // out << sPlayerbotAIConfig.GetTimestampStr() << "+00,"; // out << bot->GetName() << ","; // if (telePos && telePos.GetExactDist(movePosition) > 0.001) // startPosition.printWKT({ startPosition, movePosition, telePos }, out, 1); @@ -475,7 +463,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // out << bot->GetLevel() << ","; // out << (entry ? -1 : entry); - // sPlayerbotAIConfig->log("bot_movement.csv", out.str().c_str()); + // sPlayerbotAIConfig.log("bot_movement.csv", out.str().c_str()); // } // if (entry) @@ -621,10 +609,10 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // } // //Log bot movement - // if (sPlayerbotAIConfig->hasLog("bot_movement.csv") && lastMove.lastMoveShort.GetExactDist(movePosition) > 0.001) + // if (sPlayerbotAIConfig.hasLog("bot_movement.csv") && lastMove.lastMoveShort.GetExactDist(movePosition) > 0.001) // { // std::ostringstream out; - // out << sPlayerbotAIConfig->GetTimestampStr() << "+00,"; + // out << sPlayerbotAIConfig.GetTimestampStr() << "+00,"; // out << bot->GetName() << ","; // startPosition.printWKT({ startPosition, movePosition }, out, 1); // out << std::to_string(bot->getRace()) << ","; @@ -632,7 +620,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // out << bot->GetLevel(); // out << 0; - // sPlayerbotAIConfig->log("bot_movement.csv", out.str().c_str()); + // sPlayerbotAIConfig.log("bot_movement.csv", out.str().c_str()); // } // // LOG_DEBUG("playerbots", "({}, {}) -> ({}, {})", startPosition.getX(), startPosition.getY(), // movePosition.getX(), movePosition.getY()); if (!react) @@ -694,7 +682,7 @@ bool MovementAction::MoveTo(uint32 mapId, float x, float y, float z, bool idle, // if (botAI->GetMaster()) // { // if (botAI->GetMaster()->m_movementInfo.HasMovementFlag(MOVEMENTFLAG_WALKING) && - // sServerFacade->GetDistance2d(bot, botAI->GetMaster()) < 20.0f) + // ServerFacade::instance().GetDistance2d(bot, botAI->GetMaster()) < 20.0f) // masterWalking = true; // } @@ -779,15 +767,13 @@ bool MovementAction::MoveTo(WorldObject* target, float distance, MovementPriorit float by = bot->GetPositionY(); float bz = bot->GetPositionZ(); - float tx = target->GetPositionX(); - float ty = target->GetPositionY(); float tz = target->GetPositionZ(); float distanceToTarget = bot->GetDistance(target); float angle = bot->GetAngle(target); float needToGo = distanceToTarget - distance; - float maxDistance = sPlayerbotAIConfig->spellDistance; + float maxDistance = sPlayerbotAIConfig.spellDistance; if (needToGo > 0 && needToGo > maxDistance) needToGo = maxDistance; else if (needToGo < 0 && needToGo < -maxDistance) @@ -812,10 +798,6 @@ bool MovementAction::ReachCombatTo(Unit* target, float distance) if (!IsMovingAllowed(target)) return false; - float bx = bot->GetPositionX(); - float by = bot->GetPositionY(); - float bz = bot->GetPositionZ(); - float tx = target->GetPositionX(); float ty = target->GetPositionY(); float tz = target->GetPositionZ(); @@ -898,14 +880,14 @@ bool MovementAction::IsMovingAllowed(WorldObject* target) if (bot->GetMapId() != target->GetMapId()) return false; - // float distance = sServerFacade->GetDistance2d(bot, target); - // if (!bot->InBattleground() && distance > sPlayerbotAIConfig->reactDistance) + // float distance = ServerFacade::instance().GetDistance2d(bot, target); + // if (!bot->InBattleground() && distance > sPlayerbotAIConfig.reactDistance) // return false; return IsMovingAllowed(); } -bool MovementAction::IsMovingAllowed(uint32 mapId, float x, float y, float z) +bool MovementAction::IsMovingAllowed(uint32, float, float, float) { // removed sqrt as means distance limit was effectively 22500 (ReactDistance�) // leaving it commented incase we find ReactDistance limit causes problems @@ -918,12 +900,12 @@ bool MovementAction::IsMovingAllowed(uint32 mapId, float x, float y, float z) return IsMovingAllowed(); } -bool MovementAction::IsDuplicateMove(uint32 mapId, float x, float y, float z) +bool MovementAction::IsDuplicateMove(uint32, float x, float y, float z) { LastMovement& lastMove = *context->GetValue("last movement"); // heuristic 5s - if (lastMove.msTime + sPlayerbotAIConfig->maxWaitForMove < getMSTime() || + if (lastMove.msTime + sPlayerbotAIConfig.maxWaitForMove < getMSTime() || lastMove.lastMoveShort.GetExactDist(x, y, z) > 0.01f) return false; @@ -1046,7 +1028,7 @@ void MovementAction::UpdateMovementState() // if (bot->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE && bot->CanNotReachTarget() && // !bot->InBattleground()) // { - // if (Unit* pTarget = sServerFacade->GetChaseTarget(bot)) + // if (Unit* pTarget = ServerFacade::instance().GetChaseTarget(bot)) // { // if (!bot->IsWithinMeleeRange(pTarget) && pTarget->IsCreature()) // { @@ -1080,7 +1062,7 @@ void MovementAction::UpdateMovementState() // bot->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE) && bot->CanNotReachTarget() // && !bot->InBattleground()) // { - // if (Unit* pTarget = sServerFacade->GetChaseTarget(bot)) + // if (Unit* pTarget = ServerFacade::instance().GetChaseTarget(bot)) // { // if (pTarget != botAI->GetGroupLeader()) // return; @@ -1117,8 +1099,8 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) if (!target) return false; - if (!bot->InBattleground() && sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, target), - sPlayerbotAIConfig->followDistance)) + if (!bot->InBattleground() && ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, target), + sPlayerbotAIConfig.followDistance)) { // botAI->TellError("No need to follow"); return false; @@ -1126,9 +1108,9 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) /* if (!bot->InBattleground() - && sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, target->GetPositionX(), - target->GetPositionY()), sPlayerbotAIConfig->sightDistance) - && abs(bot->GetPositionZ() - target->GetPositionZ()) >= sPlayerbotAIConfig->spellDistance && + && ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, target->GetPositionX(), + target->GetPositionY()), sPlayerbotAIConfig.sightDistance) + && abs(bot->GetPositionZ() - target->GetPositionZ()) >= sPlayerbotAIConfig.spellDistance && botAI->HasRealPlayerMaster() && (target->GetMapId() && bot->GetMapId() != target->GetMapId())) { @@ -1189,13 +1171,13 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) WorldPosition botPos(bot); WorldPosition cPos(corpse); - if (botPos.fDist(cPos) > sPlayerbotAIConfig->spellDistance) + if (botPos.fDist(cPos) > sPlayerbotAIConfig.spellDistance) return MoveTo(cPos.getMapId(), cPos.getX(), cPos.getY(), cPos.getZ()); } } - if (sServerFacade->IsDistanceGreaterOrEqualThan(sServerFacade->GetDistance2d(bot, target), - sPlayerbotAIConfig->sightDistance)) + if (ServerFacade::instance().IsDistanceGreaterOrEqualThan(ServerFacade::instance().GetDistance2d(bot, target), + sPlayerbotAIConfig.sightDistance)) { if (target->GetGUID().IsPlayer()) { @@ -1238,11 +1220,11 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) } if (!target->HasUnitState(UNIT_STATE_IN_FLIGHT)) - return MoveTo(target, sPlayerbotAIConfig->followDistance); + return MoveTo(target, sPlayerbotAIConfig.followDistance); } - if (sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, target), - sPlayerbotAIConfig->followDistance)) + if (ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, target), + sPlayerbotAIConfig.followDistance)) { // botAI->TellError("No need to follow"); return false; @@ -1251,8 +1233,8 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) if (target->IsFriendlyTo(bot) && bot->IsMounted() && AI_VALUE(GuidVector, "all targets").empty()) distance += angle; - if (!bot->InBattleground() && sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, target), - sPlayerbotAIConfig->followDistance)) + if (!bot->InBattleground() && ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, target), + sPlayerbotAIConfig.followDistance)) { // botAI->TellError("No need to follow"); return false; @@ -1274,7 +1256,7 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) if (bot->GetMotionMaster()->GetCurrentMovementGeneratorType() == FOLLOW_MOTION_TYPE) { - Unit* currentTarget = sServerFacade->GetChaseTarget(bot); + Unit* currentTarget = ServerFacade::instance().GetChaseTarget(bot); if (currentTarget && currentTarget->GetGUID() == target->GetGUID()) return false; } @@ -1286,7 +1268,7 @@ bool MovementAction::Follow(Unit* target, float distance, float angle) return true; } -bool MovementAction::ChaseTo(WorldObject* obj, float distance, float angle) +bool MovementAction::ChaseTo(WorldObject* obj, float distance, float) { if (!IsMovingAllowed()) { @@ -1347,13 +1329,13 @@ void MovementAction::WaitForReach(float distance) { float delay = 1000.0f * MoveDelay(distance); - if (delay > sPlayerbotAIConfig->maxWaitForMove) - delay = sPlayerbotAIConfig->maxWaitForMove; + if (delay > sPlayerbotAIConfig.maxWaitForMove) + delay = sPlayerbotAIConfig.maxWaitForMove; Unit* target = *botAI->GetAiObjectContext()->GetValue("current target"); Unit* player = *botAI->GetAiObjectContext()->GetValue("enemy player target"); - if ((player || target) && delay > sPlayerbotAIConfig->globalCoolDown) - delay = sPlayerbotAIConfig->globalCoolDown; + if ((player || target) && delay > sPlayerbotAIConfig.globalCoolDown) + delay = sPlayerbotAIConfig.globalCoolDown; if (delay < 0) delay = 0; @@ -1378,7 +1360,7 @@ bool MovementAction::Flee(Unit* target) if (!target) return false; - if (!sPlayerbotAIConfig->fleeingEnabled) + if (!sPlayerbotAIConfig.fleeingEnabled) return false; if (!IsMovingAllowed()) @@ -1390,7 +1372,7 @@ bool MovementAction::Flee(Unit* target) bool foundFlee = false; time_t lastFlee = AI_VALUE(LastMovement&, "last movement").lastFlee; time_t now = time(0); - uint32 fleeDelay = urand(2, sPlayerbotAIConfig->returnDelay / 1000); + uint32 fleeDelay = urand(2, sPlayerbotAIConfig.returnDelay / 1000); if (lastFlee) { @@ -1406,7 +1388,7 @@ bool MovementAction::Flee(Unit* target) if (Group* group = bot->GetGroup()) { Unit* fleeTarget = nullptr; - float fleeDistance = sPlayerbotAIConfig->sightDistance; + float fleeDistance = sPlayerbotAIConfig.sightDistance; for (GroupReference* gref = group->GetFirstMember(); gref; gref = gref->next()) { @@ -1416,8 +1398,7 @@ bool MovementAction::Flee(Unit* target) if (botAI->IsTank(player)) { - float distanceToTank = sServerFacade->GetDistance2d(bot, player); - float distanceToTarget = sServerFacade->GetDistance2d(bot, target); + float distanceToTank = ServerFacade::instance().GetDistance2d(bot, player); if (distanceToTank < fleeDistance) { fleeTarget = player; @@ -1438,8 +1419,6 @@ bool MovementAction::Flee(Unit* target) else // bot is not targeted, try to flee dps/healers { bool isHealer = botAI->IsHeal(bot); - bool isDps = !isHealer && !botAI->IsTank(bot); - bool isTank = botAI->IsTank(bot); bool needHealer = !isHealer && AI_VALUE2(uint8, "health", "self target") < 50; bool isRanged = botAI->IsRanged(bot); @@ -1460,10 +1439,10 @@ bool MovementAction::Flee(Unit* target) if ((isHealer && botAI->IsHeal(player)) || needHealer) { - float distanceToHealer = sServerFacade->GetDistance2d(bot, player); - float distanceToTarget = sServerFacade->GetDistance2d(player, target); + float distanceToHealer = ServerFacade::instance().GetDistance2d(bot, player); + float distanceToTarget = ServerFacade::instance().GetDistance2d(player, target); if (distanceToHealer < fleeDistance && - distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig->followDistance) && + distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig.followDistance) && (needHealer || player->IsWithinLOSInMap(target))) { fleeTarget = player; @@ -1473,10 +1452,10 @@ bool MovementAction::Flee(Unit* target) } else if (isRanged && botAI->IsRanged(player)) { - float distanceToRanged = sServerFacade->GetDistance2d(bot, player); - float distanceToTarget = sServerFacade->GetDistance2d(player, target); + float distanceToRanged = ServerFacade::instance().GetDistance2d(bot, player); + float distanceToTarget = ServerFacade::instance().GetDistance2d(player, target); if (distanceToRanged < fleeDistance && - distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig->followDistance) && + distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig.followDistance) && player->IsWithinLOSInMap(target)) { fleeTarget = player; @@ -1485,10 +1464,10 @@ bool MovementAction::Flee(Unit* target) } } // remember any group member in case no one else found - float distanceToFlee = sServerFacade->GetDistance2d(bot, player); - float distanceToTarget = sServerFacade->GetDistance2d(player, target); + float distanceToFlee = ServerFacade::instance().GetDistance2d(bot, player); + float distanceToTarget = ServerFacade::instance().GetDistance2d(player, target); if (distanceToFlee < spareDistance && - distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig->followDistance) && + distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig.followDistance) && player->IsWithinLOSInMap(target)) { spareTarget = player; @@ -1508,8 +1487,8 @@ bool MovementAction::Flee(Unit* target) if ((!fleeTarget || !foundFlee) && master && master->IsAlive() && master->IsWithinLOSInMap(target)) { - float distanceToTarget = sServerFacade->GetDistance2d(master, target); - if (distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig->followDistance)) + float distanceToTarget = ServerFacade::instance().GetDistance2d(master, target); + if (distanceToTarget > (botAI->GetRange("shoot") / 2 + sPlayerbotAIConfig.followDistance)) foundFlee = MoveNear(master); } } @@ -1844,9 +1823,9 @@ void MovementAction::DoMovePoint(Unit* unit, float x, float y, float z, bool gen } } -bool FleeAction::Execute(Event event) +bool FleeAction::Execute(Event) { - return MoveAway(AI_VALUE(Unit*, "current target"), sPlayerbotAIConfig->fleeDistance, true); + return MoveAway(AI_VALUE(Unit*, "current target"), sPlayerbotAIConfig.fleeDistance, true); } bool FleeAction::isUseful() @@ -1862,9 +1841,9 @@ bool FleeAction::isUseful() return true; } -bool FleeWithPetAction::Execute(Event event) +bool FleeWithPetAction::Execute(Event) { - if (Pet* pet = bot->GetPet()) + if (bot->GetPet() != nullptr) { botAI->PetFollow(); } @@ -1874,7 +1853,9 @@ bool FleeWithPetAction::Execute(Event event) bool AvoidAoeAction::isUseful() { - if (getMSTime() - moveInterval < lastMoveTimer) + const int64_t currentMoveTimer = getMSTime() - this->lastMoveTimer; + + if (currentMoveTimer < this->lastMoveTimer) { return false; } @@ -1883,7 +1864,7 @@ bool AvoidAoeAction::isUseful() return AI_VALUE(Aura*, "area debuff") || !traps.empty() || !triggers.empty(); } -bool AvoidAoeAction::Execute(Event event) +bool AvoidAoeAction::Execute(Event) { // Case #1: Aura with dynamic object (e.g. rain of fire) if (AvoidAuraWithDynamicObj()) @@ -1924,8 +1905,8 @@ bool AvoidAoeAction::AvoidAuraWithDynamicObj() { return false; } - if (sPlayerbotAIConfig->aoeAvoidSpellWhitelist.find(spellInfo->Id) != - sPlayerbotAIConfig->aoeAvoidSpellWhitelist.end()) + if (sPlayerbotAIConfig.aoeAvoidSpellWhitelist.find(spellInfo->Id) != + sPlayerbotAIConfig.aoeAvoidSpellWhitelist.end()) return false; DynamicObject* dynOwner = aura->GetDynobjOwner(); @@ -1934,7 +1915,7 @@ bool AvoidAoeAction::AvoidAuraWithDynamicObj() return false; } float radius = dynOwner->GetRadius(); - if (!radius || radius > sPlayerbotAIConfig->maxAoeAvoidRadius) + if (!radius || radius > sPlayerbotAIConfig.maxAoeAvoidRadius) return false; if (bot->GetDistance(dynOwner) > radius) { @@ -1944,7 +1925,7 @@ bool AvoidAoeAction::AvoidAuraWithDynamicObj() name << spellInfo->SpellName[LOCALE_enUS]; // << "] (aura)"; if (FleePosition(dynOwner->GetPosition(), radius)) { - if (sPlayerbotAIConfig->tellWhenAvoidAoe && lastTellTimer < time(NULL) - 10) + if (sPlayerbotAIConfig.tellWhenAvoidAoe && lastTellTimer < time(NULL) - 10) { lastTellTimer = time(NULL); lastMoveTimer = getMSTime(); @@ -1990,8 +1971,8 @@ bool AvoidAoeAction::AvoidGameObjectWithDamage() continue; } - if (sPlayerbotAIConfig->aoeAvoidSpellWhitelist.find(spellId) != - sPlayerbotAIConfig->aoeAvoidSpellWhitelist.end()) + if (sPlayerbotAIConfig.aoeAvoidSpellWhitelist.find(spellId) != + sPlayerbotAIConfig.aoeAvoidSpellWhitelist.end()) continue; const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); @@ -2001,7 +1982,7 @@ bool AvoidAoeAction::AvoidGameObjectWithDamage() } float radius = (float)goInfo->trap.diameter / 2 + go->GetCombatReach(); - if (!radius || radius > sPlayerbotAIConfig->maxAoeAvoidRadius) + if (!radius || radius > sPlayerbotAIConfig.maxAoeAvoidRadius) continue; if (bot->GetDistance(go) > radius) @@ -2012,7 +1993,7 @@ bool AvoidAoeAction::AvoidGameObjectWithDamage() name << spellInfo->SpellName[LOCALE_enUS]; // << "] (object)"; if (FleePosition(go->GetPosition(), radius)) { - if (sPlayerbotAIConfig->tellWhenAvoidAoe && lastTellTimer < time(NULL) - 10) + if (sPlayerbotAIConfig.tellWhenAvoidAoe && lastTellTimer < time(NULL) - 10) { lastTellTimer = time(NULL); lastMoveTimer = getMSTime(); @@ -2061,8 +2042,8 @@ bool AvoidAoeAction::AvoidUnitWithDamageAura() sSpellMgr->GetSpellInfo(spellInfo->Effects[aurEff->GetEffIndex()].TriggerSpell); if (!triggerSpellInfo) continue; - if (sPlayerbotAIConfig->aoeAvoidSpellWhitelist.find(triggerSpellInfo->Id) != - sPlayerbotAIConfig->aoeAvoidSpellWhitelist.end()) + if (sPlayerbotAIConfig.aoeAvoidSpellWhitelist.find(triggerSpellInfo->Id) != + sPlayerbotAIConfig.aoeAvoidSpellWhitelist.end()) return false; for (int j = 0; j < MAX_SPELL_EFFECTS; j++) { @@ -2073,13 +2054,13 @@ bool AvoidAoeAction::AvoidUnitWithDamageAura() { break; } - if (!radius || radius > sPlayerbotAIConfig->maxAoeAvoidRadius) + if (!radius || radius > sPlayerbotAIConfig.maxAoeAvoidRadius) continue; std::ostringstream name; name << triggerSpellInfo->SpellName[LOCALE_enUS]; //<< "] (unit)"; if (FleePosition(unit->GetPosition(), radius)) { - if (sPlayerbotAIConfig->tellWhenAvoidAoe && lastTellTimer < time(NULL) - 10) + if (sPlayerbotAIConfig.tellWhenAvoidAoe && lastTellTimer < time(NULL) - 10) { lastTellTimer = time(NULL); lastMoveTimer = getMSTime(); @@ -2134,7 +2115,7 @@ Position MovementAction::BestPositionForMeleeToFlee(Position pos, float radius) continue; } bool strict = checkAngle.strict; - float fleeDis = std::min(radius + 1.0f, sPlayerbotAIConfig->fleeDistance); + float fleeDis = std::min(radius + 1.0f, sPlayerbotAIConfig.fleeDistance); float dx = bot->GetPositionX() + cos(angle) * fleeDis; float dy = bot->GetPositionY() + sin(angle) * fleeDis; float dz = bot->GetPositionZ(); @@ -2146,7 +2127,7 @@ Position MovementAction::BestPositionForMeleeToFlee(Position pos, float radius) Position fleePos{dx, dy, dz}; if (strict && currentTarget && fleePos.GetExactDist(currentTarget) - currentTarget->GetCombatReach() > - sPlayerbotAIConfig->tooCloseDistance && + sPlayerbotAIConfig.tooCloseDistance && bot->IsWithinMeleeRange(currentTarget)) { continue; @@ -2197,7 +2178,7 @@ Position MovementAction::BestPositionForRangedToFlee(Position pos, float radius) continue; } bool strict = checkAngle.strict; - float fleeDis = std::min(radius + 1.0f, sPlayerbotAIConfig->fleeDistance); + float fleeDis = std::min(radius + 1.0f, sPlayerbotAIConfig.fleeDistance); float dx = bot->GetPositionX() + cos(angle) * fleeDis; float dy = bot->GetPositionY() + sin(angle) * fleeDis; float dz = bot->GetPositionZ(); @@ -2208,13 +2189,13 @@ Position MovementAction::BestPositionForRangedToFlee(Position pos, float radius) } Position fleePos{dx, dy, dz}; if (strict && currentTarget && - fleePos.GetExactDist(currentTarget) - currentTarget->GetCombatReach() > sPlayerbotAIConfig->spellDistance) + fleePos.GetExactDist(currentTarget) - currentTarget->GetCombatReach() > sPlayerbotAIConfig.spellDistance) { continue; } if (strict && currentTarget && fleePos.GetExactDist(currentTarget) - currentTarget->GetCombatReach() < - (sPlayerbotAIConfig->tooCloseDistance)) + (sPlayerbotAIConfig.tooCloseDistance)) { continue; } @@ -2306,7 +2287,9 @@ bool MovementAction::CheckLastFlee(float curAngle, std::list& infoList bool CombatFormationMoveAction::isUseful() { - if (getMSTime() - moveInterval < lastMoveTimer) + const int64_t currentMoveTimer = getMSTime() - this->lastMoveTimer; + + if (currentMoveTimer < this->lastMoveTimer) { return false; } @@ -2317,7 +2300,7 @@ bool CombatFormationMoveAction::isUseful() return true; } -bool CombatFormationMoveAction::Execute(Event event) +bool CombatFormationMoveAction::Execute(Event) { float dis = AI_VALUE(float, "disperse distance"); if (dis <= 0.0f || (!bot->IsInCombat() && botAI->HasStrategy("stay", BotState::BOT_STATE_NON_COMBAT)) || @@ -2357,7 +2340,7 @@ Position CombatFormationMoveAction::AverageGroupPos(float dis, bool ranged, bool continue; if (!member->IsAlive() || member->GetMapId() != bot->GetMapId() || member->IsCharmed() || - sServerFacade->GetDistance2d(bot, member) > dis) + ServerFacade::instance().GetDistance2d(bot, member) > dis) continue; averageX += member->GetPositionX(); @@ -2395,7 +2378,7 @@ float CombatFormationMoveAction::AverageGroupAngle(Unit* from, bool ranged, bool continue; if (!member->IsAlive() || member->GetMapId() != bot->GetMapId() || member->IsCharmed() || - sServerFacade->GetDistance2d(bot, member) > sPlayerbotAIConfig->sightDistance) + ServerFacade::instance().GetDistance2d(bot, member) > sPlayerbotAIConfig.sightDistance) continue; cnt++; @@ -2437,7 +2420,7 @@ Player* CombatFormationMoveAction::NearestGroupMember(float dis) { Player* member = ObjectAccessor::FindPlayer(itr->guid); if (!member || !member->IsAlive() || member == bot || member->GetMapId() != bot->GetMapId() || - member->IsCharmed() || sServerFacade->GetDistance2d(bot, member) > dis) + member->IsCharmed() || ServerFacade::instance().GetDistance2d(bot, member) > dis) continue; if (nearestDis > bot->GetExactDist(member)) { @@ -2448,7 +2431,7 @@ Player* CombatFormationMoveAction::NearestGroupMember(float dis) return result; } -bool TankFaceAction::Execute(Event event) +bool TankFaceAction::Execute(Event) { Unit* target = AI_VALUE(Unit*, "current target"); if (!target) @@ -2532,7 +2515,7 @@ bool RearFlankAction::isUseful() return inFront || inRear; } -bool RearFlankAction::Execute(Event event) +bool RearFlankAction::Execute(Event) { Unit* target = AI_VALUE(Unit*, "current target"); if (!target) @@ -2643,29 +2626,29 @@ bool DisperseSetAction::Execute(Event event) return true; } -bool RunAwayAction::Execute(Event event) { return Flee(AI_VALUE(Unit*, "group leader")); } +bool RunAwayAction::Execute(Event) { return Flee(AI_VALUE(Unit*, "group leader")); } -bool MoveToLootAction::Execute(Event event) +bool MoveToLootAction::Execute(Event) { LootObject loot = AI_VALUE(LootObject, "loot target"); if (!loot.IsLootPossible(bot)) return false; - return MoveNear(loot.GetWorldObject(bot), sPlayerbotAIConfig->contactDistance); + return MoveNear(loot.GetWorldObject(bot), sPlayerbotAIConfig.contactDistance); } -bool MoveOutOfEnemyContactAction::Execute(Event event) +bool MoveOutOfEnemyContactAction::Execute(Event) { Unit* target = AI_VALUE(Unit*, "current target"); if (!target) return false; - return MoveTo(target, sPlayerbotAIConfig->contactDistance); + return MoveTo(target, sPlayerbotAIConfig.contactDistance); } bool MoveOutOfEnemyContactAction::isUseful() { return AI_VALUE2(bool, "inside target", "current target"); } -bool SetFacingTargetAction::Execute(Event event) +bool SetFacingTargetAction::Execute(Event) { Unit* target = AI_VALUE(Unit*, "current target"); if (!target) @@ -2674,8 +2657,8 @@ bool SetFacingTargetAction::Execute(Event event) if (bot->HasUnitState(UNIT_STATE_IN_FLIGHT)) return true; - sServerFacade->SetFacingTo(bot, target); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + ServerFacade::instance().SetFacingTo(bot, target); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); return true; } @@ -2691,7 +2674,7 @@ bool SetFacingTargetAction::isPossible() return true; } -bool SetBehindTargetAction::Execute(Event event) +bool SetBehindTargetAction::Execute(Event) { Unit* target = AI_VALUE(Unit*, "current target"); if (!target) @@ -2751,10 +2734,10 @@ bool SetBehindTargetAction::Execute(Event event) false, true, MovementPriority::MOVEMENT_COMBAT); } -bool MoveOutOfCollisionAction::Execute(Event event) +bool MoveOutOfCollisionAction::Execute(Event) { float angle = M_PI * 2000 / frand(1.f, 1000.f); - float distance = sPlayerbotAIConfig->followDistance; + float distance = sPlayerbotAIConfig.followDistance; return MoveTo(bot->GetMapId(), bot->GetPositionX() + cos(angle) * distance, bot->GetPositionY() + sin(angle) * distance, bot->GetPositionZ()); } @@ -2769,9 +2752,9 @@ bool MoveOutOfCollisionAction::isUseful() botAI->GetAiObjectContext()->GetValue("nearest friendly players")->Get().size() < 15; } -bool MoveRandomAction::Execute(Event event) +bool MoveRandomAction::Execute(Event) { - float distance = sPlayerbotAIConfig->tooCloseDistance + urand(10, 30); + float distance = sPlayerbotAIConfig.tooCloseDistance + urand(10, 30); Map* map = bot->GetMap(); for (int i = 0; i < 3; ++i) @@ -2782,9 +2765,7 @@ bool MoveRandomAction::Execute(Event event) float angle = (float)rand_norm() * static_cast(M_PI); x += urand(0, distance) * cos(angle); y += urand(0, distance) * sin(angle); - float ox = x; - float oy = y; - float oz = z; + if (!bot->GetMap()->CheckCollisionAndGetValidCoords(bot, bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ(), x, y, z)) continue; @@ -2801,9 +2782,9 @@ bool MoveRandomAction::Execute(Event event) bool MoveRandomAction::isUseful() { return !AI_VALUE(GuidPosition, "rpg target"); } -bool MoveInsideAction::Execute(Event event) { return MoveInside(bot->GetMapId(), x, y, bot->GetPositionZ(), distance); } +bool MoveInsideAction::Execute(Event) { return MoveInside(bot->GetMapId(), x, y, bot->GetPositionZ(), distance); } -bool RotateAroundTheCenterPointAction::Execute(Event event) +bool RotateAroundTheCenterPointAction::Execute(Event) { uint32 next_point = GetCurrWaypoint(); if (MoveTo(bot->GetMapId(), waypoints[next_point].first, waypoints[next_point].second, bot->GetPositionZ(), false, @@ -2823,10 +2804,9 @@ bool MoveFromGroupAction::Execute(Event event) return MoveFromGroup(distance); } -bool MoveAwayFromCreatureAction::Execute(Event event) +bool MoveAwayFromCreatureAction::Execute(Event) { GuidVector targets = AI_VALUE(GuidVector, "nearest npcs"); - Creature* nearestCreature = bot->FindNearestCreature(creatureId, range, alive); // Find all creatures with the specified Id std::vector creatures; @@ -2904,13 +2884,11 @@ bool MoveAwayFromCreatureAction::Execute(Event event) bool MoveAwayFromCreatureAction::isPossible() { return bot->CanFreeMove(); } -bool MoveAwayFromPlayerWithDebuffAction::Execute(Event event) +bool MoveAwayFromPlayerWithDebuffAction::Execute(Event) { - Player* closestPlayer = nullptr; - float minDistance = 0.0f; + Group* const group = bot->GetGroup(); - Group* group = bot->GetGroup(); - if (!group) + if (group == nullptr) { return false; } diff --git a/src/Ai/Base/Actions/MovementActions.h b/src/Ai/Base/Actions/MovementActions.h index d12bcd555c..046805ccf3 100644 --- a/src/Ai/Base/Actions/MovementActions.h +++ b/src/Ai/Base/Actions/MovementActions.h @@ -29,7 +29,7 @@ class MovementAction : public Action protected: bool JumpTo(uint32 mapId, float x, float y, float z, MovementPriority priority = MovementPriority::MOVEMENT_NORMAL); - bool MoveNear(uint32 mapId, float x, float y, float z, float distance = sPlayerbotAIConfig->contactDistance, + bool MoveNear(uint32 mapId, float x, float y, float z, float distance = sPlayerbotAIConfig.contactDistance, MovementPriority priority = MovementPriority::MOVEMENT_NORMAL); bool MoveToLOS(WorldObject* target, bool ranged = false); bool MoveTo(uint32 mapId, float x, float y, float z, bool idle = false, bool react = false, @@ -38,10 +38,10 @@ class MovementAction : public Action bool backwards = false); bool MoveTo(WorldObject* target, float distance = 0.0f, MovementPriority priority = MovementPriority::MOVEMENT_NORMAL); - bool MoveNear(WorldObject* target, float distance = sPlayerbotAIConfig->contactDistance, + bool MoveNear(WorldObject* target, float distance = sPlayerbotAIConfig.contactDistance, MovementPriority priority = MovementPriority::MOVEMENT_NORMAL); float GetFollowAngle(); - bool Follow(Unit* target, float distance = sPlayerbotAIConfig->followDistance); + bool Follow(Unit* target, float distance = sPlayerbotAIConfig.followDistance); bool Follow(Unit* target, float distance, float angle); bool ChaseTo(WorldObject* obj, float distance = 0.0f, float angle = 0.0f); bool ReachCombatTo(Unit* target, float distance = 0.0f); @@ -56,10 +56,10 @@ class MovementAction : public Action bool Flee(Unit* target); void ClearIdleState(); void UpdateMovementState(); - bool MoveAway(Unit* target, float distance = sPlayerbotAIConfig->fleeDistance, bool backwards = false); + bool MoveAway(Unit* target, float distance = sPlayerbotAIConfig.fleeDistance, bool backwards = false); bool MoveFromGroup(float distance); bool Move(float angle, float distance); - bool MoveInside(uint32 mapId, float x, float y, float z, float distance = sPlayerbotAIConfig->followDistance, + bool MoveInside(uint32 mapId, float x, float y, float z, float distance = sPlayerbotAIConfig.followDistance, MovementPriority priority = MovementPriority::MOVEMENT_NORMAL); void CreateWp(Player* wpOwner, float x, float y, float z, float o, uint32 entry, bool important = false); Position BestPositionForMeleeToFlee(Position pos, float radius); @@ -86,7 +86,7 @@ class MovementAction : public Action class FleeAction : public MovementAction { public: - FleeAction(PlayerbotAI* botAI, float distance = sPlayerbotAIConfig->spellDistance) + FleeAction(PlayerbotAI* botAI, float distance = sPlayerbotAIConfig.spellDistance) : MovementAction(botAI, "flee"), distance(distance) { } @@ -138,8 +138,8 @@ class CombatFormationMoveAction : public MovementAction bool Execute(Event event) override; protected: - Position AverageGroupPos(float dis = sPlayerbotAIConfig->sightDistance, bool ranged = false, bool self = false); - Player* NearestGroupMember(float dis = sPlayerbotAIConfig->sightDistance); + Position AverageGroupPos(float dis = sPlayerbotAIConfig.sightDistance, bool ranged = false, bool self = false); + Player* NearestGroupMember(float dis = sPlayerbotAIConfig.sightDistance); float AverageGroupAngle(Unit* from, bool ranged = false, bool self = false); Position GetNearestPosition(const std::vector& positions); int lastMoveTimer = 0; @@ -266,7 +266,7 @@ class RotateAroundTheCenterPointAction : public MovementAction { public: RotateAroundTheCenterPointAction(PlayerbotAI* ai, std::string name, float center_x, float center_y, - float radius = 40.0f, uint32 intervals = 16, bool clockwise = true, + float radius = 40.0f, uint32_t intervals = 16, bool clockwise = true, float start_angle = 0) : MovementAction(ai, name) { @@ -276,7 +276,8 @@ class RotateAroundTheCenterPointAction : public MovementAction this->intervals = intervals; this->clockwise = clockwise; this->call_counters = 0; - for (int i = 0; i < intervals; i++) + + for (uint32_t i = 0; i < intervals; ++i) { float angle = start_angle + 2 * M_PI * i / intervals; waypoints.push_back(std::make_pair(center_x + cos(angle) * radius, center_y + sin(angle) * radius)); diff --git a/src/Ai/Base/Actions/NonCombatActions.cpp b/src/Ai/Base/Actions/NonCombatActions.cpp index f87aa891dd..22e6cd802e 100644 --- a/src/Ai/Base/Actions/NonCombatActions.cpp +++ b/src/Ai/Base/Actions/NonCombatActions.cpp @@ -8,61 +8,6 @@ #include "Event.h" #include "Playerbots.h" -bool DrinkAction::Execute(Event event) -{ - if (botAI->HasCheat(BotCheatMask::food)) - { - // if (bot->IsNonMeleeSpellCast(true)) - // return false; - - bot->ClearUnitState(UNIT_STATE_CHASE); - bot->ClearUnitState(UNIT_STATE_FOLLOW); - - if (bot->isMoving()) - { - bot->StopMoving(); - // botAI->SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); - // return false; - } - bot->SetStandState(UNIT_STAND_STATE_SIT); - botAI->InterruptSpell(); - - // float hp = bot->GetHealthPercent(); - float mp = bot->GetPowerPct(POWER_MANA); - float p = mp; - float delay; - - if (!bot->InBattleground()) - delay = 18000.0f * (100 - p) / 100.0f; - else - delay = 12000.0f * (100 - p) / 100.0f; - - botAI->SetNextCheckDelay(delay); - - bot->AddAura(25990, bot); - return true; - // return botAI->CastSpell(24707, bot); - } - - return UseItemAction::Execute(event); -} - -bool DrinkAction::isUseful() -{ - return UseItemAction::isUseful() && - AI_VALUE2(bool, "has mana", "self target") && - AI_VALUE2(uint8, "mana", "self target") < 100; -} - -bool DrinkAction::isPossible() -{ - return !bot->IsInCombat() && - !bot->IsMounted() && - !botAI->HasAnyAuraOf(GetTarget(), "dire bear form", "bear form", "cat form", "travel form", - "aquatic form","flight form", "swift flight form", nullptr) && - (botAI->HasCheat(BotCheatMask::food) || UseItemAction::isPossible()); -} - bool EatAction::Execute(Event event) { if (botAI->HasCheat(BotCheatMask::food)) @@ -76,7 +21,7 @@ bool EatAction::Execute(Event event) if (bot->isMoving()) { bot->StopMoving(); - // botAI->SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + // botAI->SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); // return false; } diff --git a/src/Ai/Base/Actions/NonCombatActions.h b/src/Ai/Base/Actions/NonCombatActions.h index 3156d49921..86b353cf0a 100644 --- a/src/Ai/Base/Actions/NonCombatActions.h +++ b/src/Ai/Base/Actions/NonCombatActions.h @@ -10,16 +10,6 @@ class PlayerbotAI; -class DrinkAction : public UseItemAction -{ -public: - DrinkAction(PlayerbotAI* botAI) : UseItemAction(botAI, "drink") {} - - bool Execute(Event event) override; - bool isUseful() override; - bool isPossible() override; -}; - class EatAction : public UseItemAction { public: diff --git a/src/Ai/Base/Actions/OpenItemAction.cpp b/src/Ai/Base/Actions/OpenItemAction.cpp index d1ebcbaaaf..b298aef855 100644 --- a/src/Ai/Base/Actions/OpenItemAction.cpp +++ b/src/Ai/Base/Actions/OpenItemAction.cpp @@ -7,35 +7,35 @@ #include "LootObjectStack.h" #include "AiObjectContext.h" -bool OpenItemAction::Execute(Event event) +bool OpenItemAction::Execute(Event) { - bool foundOpenable = false; + Item* const item = botAI->FindOpenableItem(); - Item* item = botAI->FindOpenableItem(); - if (item) + if (item == nullptr) { - uint8 bag = item->GetBagSlot(); // Retrieves the bag slot (0 for main inventory) - uint8 slot = item->GetSlot(); // Retrieves the actual slot inside the bag - - OpenItem(item, bag, slot); - foundOpenable = true; + return false; } - return foundOpenable; + uint8_t bag = item->GetBagSlot(); // Retrieves the bag slot (255 for main inventory) + uint8_t slot = item->GetSlot(); // Retrieves the actual slot inside the bag + + this->OpenItem(item, bag, slot); + + return true; } -void OpenItemAction::OpenItem(Item* item, uint8 bag, uint8 slot) +void OpenItemAction::OpenItem(Item* item, uint8_t bag, uint8_t slot) { WorldPacket packet(CMSG_OPEN_ITEM); packet << bag << slot; - bot->GetSession()->HandleOpenItemOpcode(packet); + this->bot->GetSession()->HandleOpenItemOpcode(packet); // Store the item GUID as the loot target LootObject lootObject; lootObject.guid = item->GetGUID(); - botAI->GetAiObjectContext()->GetValue("loot target")->Set(lootObject); + this->botAI->GetAiObjectContext()->GetValue("loot target")->Set(lootObject); std::ostringstream out; out << "Opened item: " << item->GetTemplate()->Name1; - botAI->TellMaster(out.str()); + this->botAI->TellMaster(out.str()); } diff --git a/src/Ai/Base/Actions/PassLeadershipToMasterAction.cpp b/src/Ai/Base/Actions/PassLeadershipToMasterAction.cpp index 87890c1c57..9db5787230 100644 --- a/src/Ai/Base/Actions/PassLeadershipToMasterAction.cpp +++ b/src/Ai/Base/Actions/PassLeadershipToMasterAction.cpp @@ -7,38 +7,47 @@ #include "Event.h" #include "PlayerbotOperations.h" -#include "Playerbots.h" #include "PlayerbotWorldThreadProcessor.h" -bool PassLeadershipToMasterAction::Execute(Event event) +bool PassLeadershipToMasterAction::Execute(Event) { - if (Player* master = GetMaster()) - if (master && master != bot && bot->GetGroup() && bot->GetGroup()->IsMember(master->GetGUID())) - { - auto setLeaderOp = std::make_unique(bot->GetGUID(), master->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(setLeaderOp)); + const Player* const master = this->GetMaster(); - if (!message.empty()) - botAI->TellMasterNoFacing(message); + if (master == nullptr || master == this->bot) + { + return false; + } - if (sRandomPlayerbotMgr->IsRandomBot(bot)) - { - botAI->ResetStrategies(); - botAI->Reset(); - } + const Group* const group = this->bot->GetGroup(); - return true; - } + if (group == nullptr || !this->bot->GetGroup()->IsMember(master->GetGUID())) + { + return false; + } - return false; + std::unique_ptr setLeaderOp = std::make_unique(this->bot->GetGUID(), master->GetGUID()); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(setLeaderOp)); + + if (!message.empty()) + { + this->botAI->TellMasterNoFacing(message); + } + + if (RandomPlayerbotMgr::instance().IsRandomBot(this->bot)) + { + this->botAI->ResetStrategies(); + this->botAI->Reset(); + } + + return true; } bool PassLeadershipToMasterAction::isUseful() { - return botAI->IsAlt() && bot->GetGroup() && bot->GetGroup()->IsLeader(bot->GetGUID()); + return this->botAI->IsAlt() && this->bot->GetGroup() && this->bot->GetGroup()->IsLeader(this->bot->GetGUID()); } bool GiveLeaderAction::isUseful() { - return botAI->HasActivePlayerMaster() && bot->GetGroup() && bot->GetGroup()->IsLeader(bot->GetGUID()); + return this->botAI->HasActivePlayerMaster() && this->bot->GetGroup() && this->bot->GetGroup()->IsLeader(this->bot->GetGUID()); } diff --git a/src/Ai/Base/Actions/PetsAction.cpp b/src/Ai/Base/Actions/PetsAction.cpp index cb9dc93957..97d03514ea 100644 --- a/src/Ai/Base/Actions/PetsAction.cpp +++ b/src/Ai/Base/Actions/PetsAction.cpp @@ -23,7 +23,7 @@ bool PetsAction::Execute(Event event) if (param.empty()) { // If no parameter is provided, show usage instructions and return. - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_usage_error", "Usage: pet ", {}); botAI->TellError(text); return false; @@ -52,7 +52,7 @@ bool PetsAction::Execute(Event event) // If no pets or guardians are found, notify and return. if (targets.empty()) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_no_pet_error", "You have no pet or guardian pet.", {}); botAI->TellError(text); return false; @@ -65,19 +65,19 @@ bool PetsAction::Execute(Event event) if (param == "aggressive") { react = REACT_AGGRESSIVE; - stanceText = sPlayerbotTextMgr->GetBotTextOrDefault( + stanceText = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_aggressive", "aggressive", {}); } else if (param == "defensive") { react = REACT_DEFENSIVE; - stanceText = sPlayerbotTextMgr->GetBotTextOrDefault( + stanceText = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_defensive", "defensive", {}); } else if (param == "passive") { react = REACT_PASSIVE; - stanceText = sPlayerbotTextMgr->GetBotTextOrDefault( + stanceText = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_passive", "passive", {}); } // The "stance" command simply reports the current stance of each pet/guardian. @@ -86,30 +86,30 @@ bool PetsAction::Execute(Event event) for (Creature* target : targets) { std::string type = target->IsPet() ? - sPlayerbotTextMgr->GetBotTextOrDefault("pet_type_pet", "pet", {}) : - sPlayerbotTextMgr->GetBotTextOrDefault("pet_type_guardian", "guardian", {}); + PlayerbotTextMgr::instance().GetBotTextOrDefault("pet_type_pet", "pet", {}) : + PlayerbotTextMgr::instance().GetBotTextOrDefault("pet_type_guardian", "guardian", {}); std::string name = target->GetName(); std::string stance; switch (target->GetReactState()) { case REACT_AGGRESSIVE: - stance = sPlayerbotTextMgr->GetBotTextOrDefault( + stance = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_aggressive", "aggressive", {}); break; case REACT_DEFENSIVE: - stance = sPlayerbotTextMgr->GetBotTextOrDefault( + stance = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_defensive", "defensive", {}); break; case REACT_PASSIVE: - stance = sPlayerbotTextMgr->GetBotTextOrDefault( + stance = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_passive", "passive", {}); break; default: - stance = sPlayerbotTextMgr->GetBotTextOrDefault( + stance = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_unknown", "unknown", {}); break; } - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_report", "Current stance of %type \"%name\": %stance.", {{"type", type}, {"name", name}, {"stance", stance}}); botAI->TellMaster(text); @@ -133,30 +133,30 @@ bool PetsAction::Execute(Event event) // If no valid target is selected, show an error and return. if (!targetUnit) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_no_target_error", "No valid target selected by master.", {}); botAI->TellError(text); return false; } if (!targetUnit->IsAlive()) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_target_dead_error", "Target is not alive.", {}); botAI->TellError(text); return false; } if (!bot->IsValidAttackTarget(targetUnit)) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_invalid_target_error", "Target is not a valid attack target for the bot.", {}); botAI->TellError(text); return false; } - if (sPlayerbotAIConfig->IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()) && + if (sPlayerbotAIConfig.IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()) && (targetUnit->IsPlayer() || targetUnit->IsPet()) && (!bot->duel || bot->duel->Opponent != targetUnit)) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_pvp_prohibited_error", "I cannot command my pet to attack players in PvP prohibited areas.", {}); botAI->TellError(text); return false; @@ -208,15 +208,15 @@ bool PetsAction::Execute(Event event) } } // Inform the master if the command succeeded or failed. - if (didAttack && sPlayerbotAIConfig->petChatCommandDebug == 1) + if (didAttack && sPlayerbotAIConfig.petChatCommandDebug == 1) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_attack_success", "Pet commanded to attack your target.", {}); botAI->TellMaster(text); } else if (!didAttack) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_attack_failed", "Pet did not attack. (Already attacking or unable to attack target)", {}); botAI->TellError(text); } @@ -226,9 +226,9 @@ bool PetsAction::Execute(Event event) else if (param == "follow") { botAI->PetFollow(); - if (sPlayerbotAIConfig->petChatCommandDebug == 1) + if (sPlayerbotAIConfig.petChatCommandDebug == 1) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_follow_success", "Pet commanded to follow.", {}); botAI->TellMaster(text); } @@ -267,9 +267,9 @@ bool PetsAction::Execute(Event event) charmInfo->SetForcedTargetGUID(); } } - if (sPlayerbotAIConfig->petChatCommandDebug == 1) + if (sPlayerbotAIConfig.petChatCommandDebug == 1) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stay_success", "Pet commanded to stay.", {}); botAI->TellMaster(text); } @@ -278,7 +278,7 @@ bool PetsAction::Execute(Event event) // Unknown command: show usage instructions and return. else { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_unknown_command_error", "Unknown pet command: %param. Use: pet ", {{"param", param}}); botAI->TellError(text); @@ -295,9 +295,9 @@ bool PetsAction::Execute(Event event) } // Inform the master of the new stance if debug is enabled. - if (sPlayerbotAIConfig->petChatCommandDebug == 1) + if (sPlayerbotAIConfig.petChatCommandDebug == 1) { - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "pet_stance_set_success", "Pet stance set to %stance.", {{"stance", stanceText}}); botAI->TellMaster(text); diff --git a/src/Ai/Base/Actions/PetsAction.h b/src/Ai/Base/Actions/PetsAction.h index f9334e3194..eaccdcb1a8 100644 --- a/src/Ai/Base/Actions/PetsAction.h +++ b/src/Ai/Base/Actions/PetsAction.h @@ -9,8 +9,6 @@ #include #include "Action.h" -#include "PlayerbotFactory.h" -#include "Unit.h" class PlayerbotAI; @@ -22,7 +20,6 @@ class PetsAction : public Action bool Execute(Event event) override; private: - bool warningEnabled = true; std::string defaultCmd; }; diff --git a/src/Ai/Base/Actions/PositionAction.cpp b/src/Ai/Base/Actions/PositionAction.cpp index 2de27f0414..e7e7f3b5f7 100644 --- a/src/Ai/Base/Actions/PositionAction.cpp +++ b/src/Ai/Base/Actions/PositionAction.cpp @@ -102,7 +102,7 @@ bool PositionAction::Execute(Event event) return false; } -bool MoveToPositionAction::Execute(Event event) +bool MoveToPositionAction::Execute(Event) { PositionInfo pos = context->GetValue("position")->Get()[qualifier]; if (!pos.isSet()) @@ -120,10 +120,10 @@ bool MoveToPositionAction::isUseful() { PositionInfo pos = context->GetValue("position")->Get()[qualifier]; float distance = AI_VALUE2(float, "distance", std::string("position_") + qualifier); - return pos.isSet() && distance > sPlayerbotAIConfig->followDistance && distance < sPlayerbotAIConfig->reactDistance; + return pos.isSet() && distance > sPlayerbotAIConfig.followDistance && distance < sPlayerbotAIConfig.reactDistance; } -bool SetReturnPositionAction::Execute(Event event) +bool SetReturnPositionAction::Execute(Event) { PositionMap& posMap = context->GetValue("position")->Get(); PositionInfo returnPos = posMap["return"]; @@ -131,7 +131,7 @@ bool SetReturnPositionAction::Execute(Event event) if (returnPos.isSet() && !randomPos.isSet()) { float angle = 2 * M_PI * urand(0, 1000) / 100.0f; - float dist = sPlayerbotAIConfig->followDistance * urand(0, 1000) / 1000.0f; + float dist = sPlayerbotAIConfig.followDistance * urand(0, 1000) / 1000.0f; float x = returnPos.x + cos(angle) * dist; float y = returnPos.y + sin(angle) * dist; float z = bot->GetPositionZ(); @@ -157,7 +157,7 @@ bool SetReturnPositionAction::isUseful() bool ReturnAction::isUseful() { PositionInfo pos = context->GetValue("position")->Get()[qualifier]; - return pos.isSet() && AI_VALUE2(float, "distance", "position_random") > sPlayerbotAIConfig->followDistance; + return pos.isSet() && AI_VALUE2(float, "distance", "position_random") > sPlayerbotAIConfig.followDistance; } bool ReturnToStayPositionAction::isPossible() @@ -167,7 +167,7 @@ bool ReturnToStayPositionAction::isPossible() if (stayPosition.isSet()) { const float distance = bot->GetDistance(stayPosition.x, stayPosition.y, stayPosition.z); - if (distance > sPlayerbotAIConfig->reactDistance) + if (distance > sPlayerbotAIConfig.reactDistance) { botAI->TellMaster("The stay position is too far to return. I am going to stay where I am now"); diff --git a/src/Ai/Base/Actions/QueryItemUsageAction.cpp b/src/Ai/Base/Actions/QueryItemUsageAction.cpp index 2fbc75af8f..34e2cc831b 100644 --- a/src/Ai/Base/Actions/QueryItemUsageAction.cpp +++ b/src/Ai/Base/Actions/QueryItemUsageAction.cpp @@ -118,7 +118,7 @@ std::string const QueryItemUsageAction::QueryItemUsage(ItemTemplate const* item) std::string const QueryItemUsageAction::QueryItemPrice(ItemTemplate const* item) { - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sRandomPlayerbotMgr.IsRandomBot(bot)) return ""; if (item->Bonding == BIND_WHEN_PICKED_UP) @@ -133,7 +133,7 @@ std::string const QueryItemUsageAction::QueryItemPrice(ItemTemplate const* item) { Item* sell = *i; int32 price = - sell->GetCount() * sell->GetTemplate()->SellPrice * sRandomPlayerbotMgr->GetSellMultiplier(bot); + sell->GetCount() * sell->GetTemplate()->SellPrice * sRandomPlayerbotMgr.GetSellMultiplier(bot); if (!sellPrice || sellPrice > price) sellPrice = price; } @@ -147,7 +147,7 @@ std::string const QueryItemUsageAction::QueryItemPrice(ItemTemplate const* item) if (usage == ITEM_USAGE_NONE) return msg.str(); - int32 buyPrice = item->BuyPrice * sRandomPlayerbotMgr->GetBuyMultiplier(bot); + int32 buyPrice = item->BuyPrice * sRandomPlayerbotMgr.GetBuyMultiplier(bot); if (buyPrice) { if (sellPrice) diff --git a/src/Ai/Base/Actions/QueryQuestAction.cpp b/src/Ai/Base/Actions/QueryQuestAction.cpp index 6ceccad975..337f83a213 100644 --- a/src/Ai/Base/Actions/QueryQuestAction.cpp +++ b/src/Ai/Base/Actions/QueryQuestAction.cpp @@ -7,7 +7,7 @@ #include "ChatHelper.h" #include "Event.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" void QueryQuestAction::TellObjective(std::string const name, uint32 available, uint32 required) { @@ -16,7 +16,6 @@ void QueryQuestAction::TellObjective(std::string const name, uint32 available, u bool QueryQuestAction::Execute(Event event) { - Player* requester = event.getOwner() ? event.getOwner() : GetMaster(); Player* bot = botAI->GetBot(); WorldPosition botPos(bot); WorldPosition* ptr_botpos = &botPos; @@ -73,7 +72,7 @@ bool QueryQuestAction::Execute(Event event) { uint32 limit = 0; std::vector allDestinations = - sTravelMgr->getQuestTravelDestinations(bot, questId, true, true, -1); + TravelMgr::instance().getQuestTravelDestinations(bot, questId, true, true, -1); std::sort(allDestinations.begin(), allDestinations.end(), [ptr_botpos](TravelDestination* i, TravelDestination* j) {return i->distanceTo(ptr_botpos) < j->distanceTo(ptr_botpos); }); for (auto dest : allDestinations) diff --git a/src/Ai/Base/Actions/QuestAction.cpp b/src/Ai/Base/Actions/QuestAction.cpp index b96c539475..e30ff38481 100644 --- a/src/Ai/Base/Actions/QuestAction.cpp +++ b/src/Ai/Base/Actions/QuestAction.cpp @@ -5,6 +5,7 @@ #include "QuestAction.h" #include +#include #include "Chat.h" #include "ChatHelper.h" @@ -116,7 +117,8 @@ bool QuestAction::CompleteQuest(Player* player, uint32 entry) player->CastedCreatureOrGO(creature, ObjectGuid(), spell_id); } }*/ - /*else*/ if (creature > 0) + /*else*/ + if (creature > 0) { if (CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(creature)) for (uint16 z = 0; z < creaturecount; ++z) @@ -182,7 +184,7 @@ bool QuestAction::ProcessQuests(WorldObject* questGiver) { ObjectGuid guid = questGiver->GetGUID(); - if (bot->GetDistance(questGiver) > INTERACTION_DISTANCE && !sPlayerbotAIConfig->syncQuestWithPlayer) + if (bot->GetDistance(questGiver) > INTERACTION_DISTANCE && !sPlayerbotAIConfig.syncQuestWithPlayer) { //if (botAI->HasStrategy("debug", BotState::BOT_STATE_COMBAT) || botAI->HasStrategy("debug", BotState::BOT_STATE_NON_COMBAT)) @@ -190,7 +192,7 @@ bool QuestAction::ProcessQuests(WorldObject* questGiver) return false; } - if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, questGiver, sPlayerbotAIConfig->sightDistance)) + if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, questGiver, sPlayerbotAIConfig.sightDistance)) bot->SetFacingToObject(questGiver); bot->SetTarget(guid); @@ -238,7 +240,7 @@ bool QuestAction::AcceptQuest(Quest const* quest, ObjectGuid questGiver) p.rpos(0); bot->GetSession()->HandleQuestgiverAcceptQuestOpcode(p); - if (bot->GetQuestStatus(questId) == QUEST_STATUS_NONE && sPlayerbotAIConfig->syncQuestWithPlayer) + if (bot->GetQuestStatus(questId) == QUEST_STATUS_NONE && sPlayerbotAIConfig.syncQuestWithPlayer) { Object* pObject = ObjectAccessor::GetObjectByTypeMask(*bot, questGiver, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM); @@ -350,7 +352,6 @@ bool QuestUpdateAddItemAction::Execute(Event event) uint32 itemId, count; p >> itemId >> count; - Player* requester = event.getOwner() ? event.getOwner() : GetMaster(); auto const* itemPrototype = sObjectMgr->GetItemTemplate(itemId); if (itemPrototype) { @@ -366,7 +367,7 @@ bool QuestUpdateAddItemAction::Execute(Event event) placeholders["%quest_obj_required"] = std::to_string(requiredItemsCount); if (botAI->HasStrategy("debug quest", BotState::BOT_STATE_COMBAT) || botAI->HasStrategy("debug quest", BotState::BOT_STATE_NON_COMBAT)) { - const auto text = BOT_TEXT2("%quest_link - %item_link %quest_obj_available/%quest_obj_required", placeholders); + const auto text = PlayerbotTextMgr::instance().GetBotText("%quest_link - %item_link %quest_obj_available/%quest_obj_required", placeholders); botAI->Say(text); LOG_INFO("playerbots", "{} => {}", bot->GetName(), text); } @@ -405,15 +406,14 @@ bool QuestItemPushResultAction::Execute(Event event) if (!quest) return false; - const QuestStatusData& q_status = bot->getQuestStatusMap().at(questId); - for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; i++) { uint32 itemId = quest->RequiredItemId[i]; if (!itemId) continue; - int32 previousCount = itemCount - count; + uint32_t previousCount = std::max(itemCount - count, 0); + if (itemId == itemEntry && previousCount < quest->RequiredItemCount[i]) { if (botAI->GetMaster()) @@ -432,7 +432,7 @@ bool QuestItemPushResultAction::Execute(Event event) return false; } -bool QuestUpdateFailedAction::Execute(Event event) +bool QuestUpdateFailedAction::Execute(Event) { //opcode SMSG_QUESTUPDATE_FAILED is never sent...(yet?) return false; @@ -446,15 +446,13 @@ bool QuestUpdateFailedTimerAction::Execute(Event event) uint32 questId; p >> questId; - Player* requester = event.getOwner() ? event.getOwner() : GetMaster(); - Quest const* qInfo = sObjectMgr->GetQuestTemplate(questId); if (qInfo) { std::map placeholders; placeholders["%quest_link"] = botAI->GetChatHelper()->FormatQuest(qInfo); - botAI->TellMaster(BOT_TEXT2("Failed timer for %quest_link, abandoning", placeholders)); + botAI->TellMaster(PlayerbotTextMgr::instance().GetBotText("Failed timer for %quest_link, abandoning", placeholders)); BroadcastHelper::BroadcastQuestUpdateFailedTimer(botAI, bot, qInfo); } else diff --git a/src/Ai/Base/Actions/RandomBotUpdateAction.cpp b/src/Ai/Base/Actions/RandomBotUpdateAction.cpp index 61a8360e59..fdf853bee0 100644 --- a/src/Ai/Base/Actions/RandomBotUpdateAction.cpp +++ b/src/Ai/Base/Actions/RandomBotUpdateAction.cpp @@ -8,9 +8,9 @@ #include "Event.h" #include "Playerbots.h" -bool RandomBotUpdateAction::Execute(Event event) +bool RandomBotUpdateAction::Execute(Event) { - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sRandomPlayerbotMgr.IsRandomBot(bot)) return false; if (bot->GetGroup() && botAI->GetGroupLeader()) @@ -20,10 +20,10 @@ bool RandomBotUpdateAction::Execute(Event event) return true; } - if (botAI->HasPlayerNearby(sPlayerbotAIConfig->grindDistance)) + if (botAI->HasPlayerNearby(sPlayerbotAIConfig.grindDistance)) return true; - return sRandomPlayerbotMgr->ProcessBot(bot); + return sRandomPlayerbotMgr.ProcessBot(bot); } bool RandomBotUpdateAction::isUseful() { return AI_VALUE(bool, "random bot update"); } diff --git a/src/Ai/Base/Actions/ReachTargetActions.cpp b/src/Ai/Base/Actions/ReachTargetActions.cpp index 2be0da6beb..e0528555f0 100644 --- a/src/Ai/Base/Actions/ReachTargetActions.cpp +++ b/src/Ai/Base/Actions/ReachTargetActions.cpp @@ -10,7 +10,7 @@ #include "Playerbots.h" #include "ServerFacade.h" -bool ReachTargetAction::Execute(Event event) { return ReachCombatTo(AI_VALUE(Unit*, GetTargetName()), distance); } +bool ReachTargetAction::Execute(Event) { return ReachCombatTo(AI_VALUE(Unit*, GetTargetName()), distance); } bool ReachTargetAction::isUseful() { @@ -28,7 +28,7 @@ bool ReachTargetAction::isUseful() Unit* target = GetTarget(); // float dis = distance + CONTACT_DISTANCE; return target && - !bot->IsWithinCombatRange(target, distance); // sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, + !bot->IsWithinCombatRange(target, distance); // ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, // "distance", GetTargetName()), distance); } @@ -42,8 +42,8 @@ bool CastReachTargetSpellAction::isUseful() return false; } - return sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "current target"), - (distance + sPlayerbotAIConfig->contactDistance)); + return ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "current target"), + (distance + sPlayerbotAIConfig.contactDistance)); } ReachSpellAction::ReachSpellAction(PlayerbotAI* botAI) diff --git a/src/Ai/Base/Actions/ReachTargetActions.h b/src/Ai/Base/Actions/ReachTargetActions.h index 40559753f9..1a8ce0c9cc 100644 --- a/src/Ai/Base/Actions/ReachTargetActions.h +++ b/src/Ai/Base/Actions/ReachTargetActions.h @@ -44,7 +44,7 @@ class CastReachTargetSpellAction : public CastSpellAction class ReachMeleeAction : public ReachTargetAction { public: - ReachMeleeAction(PlayerbotAI* botAI) : ReachTargetAction(botAI, "reach melee", sPlayerbotAIConfig->meleeDistance) {} + ReachMeleeAction(PlayerbotAI* botAI) : ReachTargetAction(botAI, "reach melee", sPlayerbotAIConfig.meleeDistance) {} }; class ReachSpellAction : public ReachTargetAction diff --git a/src/Ai/Base/Actions/ReadyCheckAction.cpp b/src/Ai/Base/Actions/ReadyCheckAction.cpp index 2fc25e6dcc..671fef37dd 100644 --- a/src/Ai/Base/Actions/ReadyCheckAction.cpp +++ b/src/Ai/Base/Actions/ReadyCheckAction.cpp @@ -11,19 +11,32 @@ #include "Event.h" #include "Playerbots.h" -std::string const formatPercent(std::string const name, uint8 value, float percent) +std::string_view getColorForThreshold(const float threshold) +{ + if (threshold > 75.0f) + { + return "|cff00ff00"; + } + + if (threshold > 50.0f) + { + return "|cffffff00"; + } + + return "|cffff0000"; +} + +std::string formatPercent(const std::string& name, const uint32_t value, const float threshold) { std::ostringstream out; - std::string color; - if (percent > 75) - color = "|cff00ff00"; - else if (percent > 50) - color = "|cffffff00"; - else - color = "|cffff0000"; + out << "|cffffffff[" + << name + << "]" + << getColorForThreshold(threshold) + << "x" + << value; - out << "|cffffffff[" << name << "]" << color << "x" << (int)value; return out.str(); } @@ -45,9 +58,9 @@ std::once_flag ReadyChecker::initFlag; class HealthChecker : public ReadyChecker { public: - bool Check(PlayerbotAI* botAI, AiObjectContext* context) override + bool Check(PlayerbotAI*, AiObjectContext* context) override { - return AI_VALUE2(uint8, "health", "self target") > sPlayerbotAIConfig->almostFullHealth; + return AI_VALUE2(uint8, "health", "self target") > sPlayerbotAIConfig.almostFullHealth; } std::string const getName() override { return "HP"; } @@ -56,10 +69,10 @@ class HealthChecker : public ReadyChecker class ManaChecker : public ReadyChecker { public: - bool Check(PlayerbotAI* botAI, AiObjectContext* context) override + bool Check(PlayerbotAI*, AiObjectContext* context) override { return !AI_VALUE2(bool, "has mana", "self target") || - AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig->mediumHealth; + AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig.mediumHealth; } std::string const getName() override { return "MP"; } @@ -68,12 +81,12 @@ class ManaChecker : public ReadyChecker class DistanceChecker : public ReadyChecker { public: - bool Check(PlayerbotAI* botAI, AiObjectContext* context) override + bool Check(PlayerbotAI* botAI, AiObjectContext*) override { Player* bot = botAI->GetBot(); if (Player* master = botAI->GetMaster()) { - bool distance = bot->GetDistance(master) <= sPlayerbotAIConfig->sightDistance; + bool distance = bot->GetDistance(master) <= sPlayerbotAIConfig.sightDistance; if (!distance) { return false; @@ -90,7 +103,7 @@ class DistanceChecker : public ReadyChecker class HunterChecker : public ReadyChecker { public: - bool Check(PlayerbotAI* botAI, AiObjectContext* context) override + bool Check(PlayerbotAI* botAI, AiObjectContext*) override { Player* bot = botAI->GetBot(); if (bot->getClass() == CLASS_HUNTER) @@ -126,7 +139,7 @@ class ItemCountChecker : public ReadyChecker public: ItemCountChecker(std::string const item, std::string const name) : item(item), name(name) {} - bool Check(PlayerbotAI* botAI, AiObjectContext* context) override + bool Check(PlayerbotAI*, AiObjectContext* context) override { return AI_VALUE2(uint32, "item count", item) > 0; } @@ -225,4 +238,4 @@ bool ReadyCheckAction::ReadyCheck() return true; } -bool FinishReadyCheckAction::Execute(Event event) { return ReadyCheck(); } +bool FinishReadyCheckAction::Execute(Event) { return ReadyCheck(); } diff --git a/src/Ai/Base/Actions/ReleaseSpiritAction.cpp b/src/Ai/Base/Actions/ReleaseSpiritAction.cpp index 17fcc42a0b..e62192b61a 100644 --- a/src/Ai/Base/Actions/ReleaseSpiritAction.cpp +++ b/src/Ai/Base/Actions/ReleaseSpiritAction.cpp @@ -65,7 +65,7 @@ void ReleaseSpiritAction::IncrementDeathCount() const } } -void ReleaseSpiritAction::LogRelease(const std::string& releaseMsg, bool isAutoRelease) const +void ReleaseSpiritAction::LogRelease(const std::string& releaseMsg, bool) const { const std::string teamPrefix = bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H"; @@ -78,7 +78,7 @@ void ReleaseSpiritAction::LogRelease(const std::string& releaseMsg, bool isAutoR } // AutoReleaseSpiritAction implementation -bool AutoReleaseSpiritAction::Execute(Event event) +bool AutoReleaseSpiritAction::Execute(Event) { IncrementDeathCount(); bot->DurabilityRepairAll(false, 1.0f, false); @@ -183,9 +183,9 @@ bool AutoReleaseSpiritAction::ShouldAutoRelease() const return false; } - return sServerFacade->IsDistanceGreaterThan( + return ServerFacade::instance().IsDistanceGreaterThan( AI_VALUE2(float, "distance", "group leader"), - sPlayerbotAIConfig->sightDistance); + sPlayerbotAIConfig.sightDistance); } bool AutoReleaseSpiritAction::ShouldDelayBattlegroundRelease() const @@ -214,7 +214,7 @@ bool AutoReleaseSpiritAction::ShouldDelayBattlegroundRelease() const return true; } -bool RepopAction::Execute(Event event) +bool RepopAction::Execute(Event) { const GraveyardStruct* graveyard = GetGrave( AI_VALUE(uint32, "death count") > 10 || @@ -250,7 +250,7 @@ void RepopAction::PerformGraveyardTeleport(const GraveyardStruct* graveyard) con } // SelfResurrectAction implementation for Warlock's Soulstone Resurrection/Shaman's Reincarnation -bool SelfResurrectAction::Execute(Event event) +bool SelfResurrectAction::Execute(Event) { if (!bot->IsAlive() && bot->GetUInt32Value(PLAYER_SELF_RES_SPELL)) { diff --git a/src/Ai/Base/Actions/RememberTaxiAction.cpp b/src/Ai/Base/Actions/RememberTaxiAction.cpp index af5a540370..b056f38402 100644 --- a/src/Ai/Base/Actions/RememberTaxiAction.cpp +++ b/src/Ai/Base/Actions/RememberTaxiAction.cpp @@ -7,7 +7,7 @@ #include "Event.h" #include "LastMovementValue.h" -#include "Playerbots.h" +#include "AiObjectContext.h" bool RememberTaxiAction::Execute(Event event) { @@ -28,7 +28,7 @@ bool RememberTaxiAction::Execute(Event event) case CMSG_ACTIVATETAXIEXPRESS: { ObjectGuid guid; - uint32 node_count, totalcost; + uint32 node_count; p >> guid >> node_count; LastMovement& movement = context->GetValue("last taxi")->Get(); diff --git a/src/Ai/Base/Actions/RepairAllAction.cpp b/src/Ai/Base/Actions/RepairAllAction.cpp index a66ba3a1bb..d62fb1ad12 100644 --- a/src/Ai/Base/Actions/RepairAllAction.cpp +++ b/src/Ai/Base/Actions/RepairAllAction.cpp @@ -9,7 +9,7 @@ #include "Event.h" #include "Playerbots.h" -bool RepairAllAction::Execute(Event event) +bool RepairAllAction::Execute(Event) { GuidVector npcs = AI_VALUE(GuidVector, "nearest npcs"); for (ObjectGuid const guid : npcs) diff --git a/src/Ai/Base/Actions/ResetAiAction.cpp b/src/Ai/Base/Actions/ResetAiAction.cpp index 3df6bbcd2a..19017c9161 100644 --- a/src/Ai/Base/Actions/ResetAiAction.cpp +++ b/src/Ai/Base/Actions/ResetAiAction.cpp @@ -44,7 +44,7 @@ bool ResetAiAction::Execute(Event event) } } } - sPlayerbotRepository->Reset(botAI); + PlayerbotRepository::instance().Reset(botAI); botAI->ResetStrategies(false); botAI->TellMaster("AI was reset to defaults"); return true; diff --git a/src/Ai/Base/Actions/ResetInstancesAction.cpp b/src/Ai/Base/Actions/ResetInstancesAction.cpp index cce5eef1e3..8bf9946d5d 100644 --- a/src/Ai/Base/Actions/ResetInstancesAction.cpp +++ b/src/Ai/Base/Actions/ResetInstancesAction.cpp @@ -5,15 +5,19 @@ #include "ResetInstancesAction.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" -bool ResetInstancesAction::Execute(Event event) +bool ResetInstancesAction::Execute(Event) { WorldPacket packet(CMSG_RESET_INSTANCES, 0); - bot->GetSession()->HandleResetInstancesOpcode(packet); - botAI->TellMaster("Resetting all instances"); + this->bot->GetSession()->HandleResetInstancesOpcode(packet); + this->botAI->TellMaster("Resetting all instances"); + return true; } -bool ResetInstancesAction::isUseful() { return botAI->GetGroupLeader() == bot; }; +bool ResetInstancesAction::isUseful() +{ + return this->botAI->GetGroupLeader() == this->bot; +}; diff --git a/src/Ai/Base/Actions/RevealGatheringItemAction.cpp b/src/Ai/Base/Actions/RevealGatheringItemAction.cpp index 9725dce5ce..7c2a3c85ee 100644 --- a/src/Ai/Base/Actions/RevealGatheringItemAction.cpp +++ b/src/Ai/Base/Actions/RevealGatheringItemAction.cpp @@ -5,31 +5,33 @@ #include "RevealGatheringItemAction.h" -#include "CellImpl.h" #include "ChatHelper.h" #include "Event.h" #include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Playerbots.h" #include "ServerFacade.h" #include "NearestGameObjects.h" +#include "PlayerbotAI.h" + +// Required due to a poor implementation by AC +#include "CellImpl.h" +#include "GridNotifiersImpl.h" -bool RevealGatheringItemAction::Execute(Event event) +bool RevealGatheringItemAction::Execute(Event) { if (!bot->GetGroup()) return false; std::list targets; - AnyGameObjectInObjectRangeCheck u_check(bot, sPlayerbotAIConfig->grindDistance); + AnyGameObjectInObjectRangeCheck u_check(bot, sPlayerbotAIConfig.grindDistance); Acore::GameObjectListSearcher searcher(bot, targets, u_check); - Cell::VisitObjects(bot, searcher, sPlayerbotAIConfig->reactDistance); + Cell::VisitObjects(bot, searcher, sPlayerbotAIConfig.reactDistance); std::vector result; for (GameObject* go : targets) { if (!go || !go->isSpawned() || - sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, go), - sPlayerbotAIConfig->lootDistance)) + ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, go), + sPlayerbotAIConfig.lootDistance)) continue; if (LockEntry const* lockInfo = sLockStore.LookupEntry(go->GetGOInfo()->GetLockId())) diff --git a/src/Ai/Base/Actions/ReviveFromCorpseAction.cpp b/src/Ai/Base/Actions/ReviveFromCorpseAction.cpp index ce0b1fa05d..7a60753f69 100644 --- a/src/Ai/Base/Actions/ReviveFromCorpseAction.cpp +++ b/src/Ai/Base/Actions/ReviveFromCorpseAction.cpp @@ -9,7 +9,6 @@ #include "FleeManager.h" #include "GameGraveyard.h" #include "MapMgr.h" -#include "PlayerbotFactory.h" #include "Playerbots.h" #include "RandomPlayerbotMgr.h" #include "ServerFacade.h" @@ -24,8 +23,8 @@ bool ReviveFromCorpseAction::Execute(Event event) WorldPacket& p = event.getPacket(); if (!p.empty() && p.GetOpcode() == CMSG_RECLAIM_CORPSE && groupLeader && !corpse && bot->IsAlive()) { - if (sServerFacade->IsDistanceLessThan(AI_VALUE2(float, "distance", "group leader"), - sPlayerbotAIConfig->farDistance)) + if (ServerFacade::instance().IsDistanceLessThan(AI_VALUE2(float, "distance", "group leader"), + sPlayerbotAIConfig.farDistance)) { if (!botAI->HasStrategy("follow", BOT_STATE_NON_COMBAT)) { @@ -46,8 +45,8 @@ bool ReviveFromCorpseAction::Execute(Event event) if (groupLeader) { if (!GET_PLAYERBOT_AI(groupLeader) && groupLeader->isDead() && groupLeader->GetCorpse() && - sServerFacade->IsDistanceLessThan(AI_VALUE2(float, "distance", "group leader"), - sPlayerbotAIConfig->farDistance)) + ServerFacade::instance().IsDistanceLessThan(AI_VALUE2(float, "distance", "group leader"), + sPlayerbotAIConfig.farDistance)) return false; } @@ -74,7 +73,7 @@ bool ReviveFromCorpseAction::Execute(Event event) return true; } -bool FindCorpseAction::Execute(Event event) +bool FindCorpseAction::Execute(Event) { if (bot->InBattleground()) return false; @@ -87,8 +86,8 @@ bool FindCorpseAction::Execute(Event event) // if (groupLeader) // { // if (!GET_PLAYERBOT_AI(groupLeader) && - // sServerFacade->IsDistanceLessThan(AI_VALUE2(float, "distance", "group leader"), - // sPlayerbotAIConfig->farDistance)) return false; + // ServerFacade::instance().IsDistanceLessThan(AI_VALUE2(float, "distance", "group leader"), + // sPlayerbotAIConfig.farDistance)) return false; // } uint32 dCount = AI_VALUE(uint32, "death count"); @@ -101,8 +100,8 @@ bool FindCorpseAction::Execute(Event event) // bot->GetGUID().ToString().c_str(), bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->GetLevel(), // bot->GetName().c_str()); context->GetValue("death count")->Set(0); - // sRandomPlayerbotMgr->RandomTeleportForLevel(bot); - sRandomPlayerbotMgr->Revive(bot); + // sRandomPlayerbotMgr.RandomTeleportForLevel(bot); + sRandomPlayerbotMgr.Revive(bot); return true; } } @@ -123,7 +122,7 @@ bool FindCorpseAction::Execute(Event event) { if (moveToLeader) // We are near group leader. { - if (botPos.fDist(leaderPos) < sPlayerbotAIConfig->spellDistance) + if (botPos.fDist(leaderPos) < sPlayerbotAIConfig.spellDistance) return false; } else if (deadTime > 8 * MINUTE) // We have walked too long already. @@ -138,7 +137,7 @@ bool FindCorpseAction::Execute(Event event) } // If we are getting close move to a save ressurrection spot instead of just the corpse. - if (corpseDist < sPlayerbotAIConfig->reactDistance) + if (corpseDist < sPlayerbotAIConfig.reactDistance) { if (moveToLeader) moveToPos = leaderPos; @@ -162,7 +161,7 @@ bool FindCorpseAction::Execute(Event event) if (!botAI->AllowActivity(ALL_ACTIVITY)) { - uint32 delay = sServerFacade->GetDistance2d(bot, corpse) / + uint32 delay = ServerFacade::instance().GetDistance2d(bot, corpse) / bot->GetSpeed(MOVE_RUN); // Time a bot would take to travel to it's corpse. delay = std::min(delay, uint32(10 * MINUTE)); // Cap time to get to corpse at 10 minutes. @@ -293,7 +292,7 @@ GraveyardStruct const* SpiritHealerAction::GetGrave(bool startZone) return ClosestGrave; } -bool SpiritHealerAction::Execute(Event event) +bool SpiritHealerAction::Execute(Event) { Corpse* corpse = bot->GetCorpse(); if (!corpse) @@ -308,7 +307,7 @@ bool SpiritHealerAction::Execute(Event event) GraveyardStruct const* ClosestGrave = GetGrave(dCount > 10 || deadTime > 15 * MINUTE || AI_VALUE(uint8, "durability") < 10); - if (bot->GetDistance2d(ClosestGrave->x, ClosestGrave->y) < sPlayerbotAIConfig->sightDistance) + if (bot->GetDistance2d(ClosestGrave->x, ClosestGrave->y) < sPlayerbotAIConfig.sightDistance) { GuidVector npcs = AI_VALUE(GuidVector, "nearest npcs"); for (GuidVector::iterator i = npcs.begin(); i != npcs.end(); i++) diff --git a/src/Ai/Base/Actions/RpgAction.cpp b/src/Ai/Base/Actions/RpgAction.cpp index 6002eaf63a..c1a484882d 100644 --- a/src/Ai/Base/Actions/RpgAction.cpp +++ b/src/Ai/Base/Actions/RpgAction.cpp @@ -7,7 +7,6 @@ #include -#include "BattlegroundMgr.h" #include "ChatHelper.h" #include "EmoteAction.h" #include "Event.h" @@ -16,7 +15,7 @@ #include "ServerFacade.h" #include "RpgSubActions.h" -bool RpgAction::Execute(Event event) +bool RpgAction::Execute(Event) { GuidPosition guidP = AI_VALUE(GuidPosition, "rpg target"); if (!guidP && botAI->GetMaster()) @@ -108,7 +107,7 @@ bool RpgAction::SetNextRpgAction() { std::vector> sortedActions; - for (int i = 0; i < actions.size(); i++) + for (uint64_t i = 0; i < actions.size(); i++) sortedActions.push_back(std::make_pair(actions[i], relevances[i])); std::sort(sortedActions.begin(), sortedActions.end(), [](std::pairi, std::pair j) {return i.second > j.second; }); @@ -130,7 +129,7 @@ bool RpgAction::SetNextRpgAction() std::mt19937 gen(time(0)); - sTravelMgr->weighted_shuffle(actions.begin(), actions.end(), relevances.begin(), relevances.end(), gen); + TravelMgr::instance().weighted_shuffle(actions.begin(), actions.end(), relevances.begin(), relevances.end(), gen); Action* action = actions.front(); diff --git a/src/Ai/Base/Actions/RpgSubActions.cpp b/src/Ai/Base/Actions/RpgSubActions.cpp index aa4269fa92..16a463ce5d 100644 --- a/src/Ai/Base/Actions/RpgSubActions.cpp +++ b/src/Ai/Base/Actions/RpgSubActions.cpp @@ -77,9 +77,9 @@ void RpgHelper::setFacing(GuidPosition guidPosition) void RpgHelper::setDelay(bool waitForGroup) { if (!botAI->HasRealPlayerMaster() || (waitForGroup && botAI->GetGroupLeader() == bot && bot->GetGroup())) - botAI->SetNextCheckDelay(sPlayerbotAIConfig->rpgDelay); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.rpgDelay); else - botAI->SetNextCheckDelay(sPlayerbotAIConfig->rpgDelay / 5); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.rpgDelay / 5); } bool RpgSubAction::isPossible() { return rpg->guidP() && rpg->guidP().GetWorldObject(); } @@ -99,7 +99,7 @@ Event RpgSubAction::ActionEvent(Event event) { return event; } bool RpgStayAction::isUseful() { return rpg->InRange() && !botAI->HasRealPlayerMaster(); } -bool RpgStayAction::Execute(Event event) +bool RpgStayAction::Execute(Event) { bot->PlayerTalkClass->SendCloseGossip(); @@ -109,7 +109,7 @@ bool RpgStayAction::Execute(Event event) bool RpgWorkAction::isUseful() { return rpg->InRange() && !botAI->HasRealPlayerMaster(); } -bool RpgWorkAction::Execute(Event event) +bool RpgWorkAction::Execute(Event) { bot->HandleEmoteCommand(EMOTE_STATE_USE_STANDING); rpg->AfterExecute(); @@ -118,7 +118,7 @@ bool RpgWorkAction::Execute(Event event) bool RpgEmoteAction::isUseful() { return rpg->InRange() && !botAI->HasRealPlayerMaster(); } -bool RpgEmoteAction::Execute(Event event) +bool RpgEmoteAction::Execute(Event) { uint32 type = TalkAction::GetRandomEmote(rpg->guidP().GetUnit()); @@ -133,7 +133,7 @@ bool RpgEmoteAction::Execute(Event event) return true; } -bool RpgCancelAction::Execute(Event event) +bool RpgCancelAction::Execute(Event) { RESET_AI_VALUE(GuidPosition, "rpg target"); rpg->OnExecute(""); @@ -142,7 +142,7 @@ bool RpgCancelAction::Execute(Event event) bool RpgTaxiAction::isUseful() { return rpg->InRange() && !botAI->HasRealPlayerMaster(); } -bool RpgTaxiAction::Execute(Event event) +bool RpgTaxiAction::Execute(Event) { GuidPosition guidP = rpg->guidP(); @@ -203,7 +203,7 @@ bool RpgTaxiAction::Execute(Event event) return true; } -bool RpgDiscoverAction::Execute(Event event) +bool RpgDiscoverAction::Execute(Event) { GuidPosition guidP = rpg->guidP(); @@ -222,7 +222,7 @@ bool RpgDiscoverAction::Execute(Event event) std::string const RpgStartQuestAction::ActionName() { return "accept all quests"; } -Event RpgStartQuestAction::ActionEvent(Event event) +Event RpgStartQuestAction::ActionEvent(Event) { WorldPacket p(CMSG_QUESTGIVER_ACCEPT_QUEST); p << rpg->guid(); @@ -232,7 +232,7 @@ Event RpgStartQuestAction::ActionEvent(Event event) std::string const RpgEndQuestAction::ActionName() { return "talk to quest giver"; } -Event RpgEndQuestAction::ActionEvent(Event event) +Event RpgEndQuestAction::ActionEvent(Event) { WorldPacket p(CMSG_QUESTGIVER_COMPLETE_QUEST); p << rpg->guid(); @@ -242,17 +242,17 @@ Event RpgEndQuestAction::ActionEvent(Event event) std::string const RpgBuyAction::ActionName() { return "buy"; } -Event RpgBuyAction::ActionEvent(Event event) { return Event("rpg action", "vendor"); } +Event RpgBuyAction::ActionEvent(Event) { return Event("rpg action", "vendor"); } std::string const RpgSellAction::ActionName() { return "sell"; } -Event RpgSellAction::ActionEvent(Event event) { return Event("rpg action", "vendor"); } +Event RpgSellAction::ActionEvent(Event) { return Event("rpg action", "vendor"); } std::string const RpgRepairAction::ActionName() { return "repair"; } std::string const RpgTrainAction::ActionName() { return "trainer"; } -bool RpgHealAction::Execute(Event event) +bool RpgHealAction::Execute(Event) { bool retVal = false; @@ -287,21 +287,21 @@ std::string const RpgBuyPetitionAction::ActionName() { return "buy petition"; } std::string const RpgUseAction::ActionName() { return "use"; } -Event RpgUseAction::ActionEvent(Event event) +Event RpgUseAction::ActionEvent(Event) { return Event("rpg action", chat->FormatWorldobject(rpg->guidP().GetWorldObject())); } std::string const RpgSpellAction::ActionName() { return "cast random spell"; } -Event RpgSpellAction::ActionEvent(Event event) +Event RpgSpellAction::ActionEvent(Event) { return Event("rpg action", chat->FormatWorldobject(rpg->guidP().GetWorldObject())); } std::string const RpgCraftAction::ActionName() { return "craft random item"; } -Event RpgCraftAction::ActionEvent(Event event) +Event RpgCraftAction::ActionEvent(Event) { return Event("rpg action", chat->FormatWorldobject(rpg->guidP().GetWorldObject())); } @@ -341,7 +341,7 @@ std::vector RpgTradeUsefulAction::CanGiveItems(GuidPosition guidPosition) return giveItems; } -bool RpgTradeUsefulAction::Execute(Event event) +bool RpgTradeUsefulAction::Execute(Event) { GuidPosition guidP = AI_VALUE(GuidPosition, "rpg target"); @@ -392,7 +392,7 @@ bool RpgTradeUsefulAction::Execute(Event event) bot->Say("Start trade with" + chat->FormatWorldobject(player), (bot->GetTeamId() == TEAM_ALLIANCE ? LANG_COMMON : LANG_ORCISH)); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->rpgDelay); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.rpgDelay); return true; } @@ -402,7 +402,7 @@ bool RpgTradeUsefulAction::Execute(Event event) bool RpgDuelAction::isUseful() { // do not offer duel in non pvp areas - if (sPlayerbotAIConfig->IsInPvpProhibitedZone(bot->GetZoneId())) + if (sPlayerbotAIConfig.IsInPvpProhibitedZone(bot->GetZoneId())) return false; // Players can only fight a duel with each other outside (=not inside dungeons and not in capital cities) @@ -416,7 +416,7 @@ bool RpgDuelAction::isUseful() return true; } -bool RpgDuelAction::Execute(Event event) +bool RpgDuelAction::Execute(Event) { GuidPosition guidP = AI_VALUE(GuidPosition, "rpg target"); @@ -434,7 +434,7 @@ bool RpgMountAnimAction::isUseful() return AI_VALUE2(bool, "mounted", "self target") && !AI_VALUE2(bool, "moving", "self target"); } -bool RpgMountAnimAction::Execute(Event event) +bool RpgMountAnimAction::Execute(Event) { WorldPacket p; bot->GetSession()->HandleMountSpecialAnimOpcode(p); diff --git a/src/Ai/Base/Actions/RtiAction.cpp b/src/Ai/Base/Actions/RtiAction.cpp index b34b3eec3d..84a6aeba56 100644 --- a/src/Ai/Base/Actions/RtiAction.cpp +++ b/src/Ai/Base/Actions/RtiAction.cpp @@ -55,7 +55,7 @@ void RtiAction::AppendRti(std::ostringstream& out, std::string const type) out << " (" << target->GetName() << ")"; } -bool MarkRtiAction::Execute(Event event) +bool MarkRtiAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) diff --git a/src/Ai/Base/Actions/SayAction.cpp b/src/Ai/Base/Actions/SayAction.cpp index 00fae65293..8dadca531a 100644 --- a/src/Ai/Base/Actions/SayAction.cpp +++ b/src/Ai/Base/Actions/SayAction.cpp @@ -9,9 +9,7 @@ #include #include -#include "ChannelMgr.h" #include "Event.h" -#include "GuildMgr.h" #include "PlayerbotTextMgr.h" #include "Playerbots.h" @@ -56,7 +54,7 @@ static const std::unordered_set noReplyMsgStarts = {"e ", "accept " SayAction::SayAction(PlayerbotAI* botAI) : Action(botAI, "say"), Qualified() {} -bool SayAction::Execute(Event event) +bool SayAction::Execute(Event) { std::string text = ""; std::map placeholders; @@ -92,7 +90,6 @@ bool SayAction::Execute(Event event) } // set delay before next say - time_t lastSaid = AI_VALUE2(time_t, "last said", qualifier); uint32 nextTime = time(nullptr) + urand(1, 30); botAI->GetAiObjectContext()->GetValue("last said", qualifier)->Set(nextTime); @@ -134,7 +131,7 @@ bool SayAction::Execute(Event event) } // load text based on chance - if (!sPlayerbotTextMgr->GetBotText(qualifier, text, placeholders)) + if (!PlayerbotTextMgr::instance().GetBotText(qualifier, text, placeholders)) return false; if (text.find("/y ") == 0) @@ -157,9 +154,8 @@ bool SayAction::isUseful() return (time(nullptr) - lastSaid) > 30; } -void ChatReplyAction::ChatReplyDo(Player* bot, uint32& type, uint32& guid1, uint32& guid2, std::string& msg, std::string& chanName, std::string& name) +void ChatReplyAction::ChatReplyDo(Player* bot, uint32& type, uint32& guid1, uint32&, std::string& msg, std::string& chanName, std::string& name) { - ChatReplyType replyType = REPLY_NOT_UNDERSTAND; // default not understand std::string respondsText = ""; // if we're just commanding bots around, don't respond... @@ -206,7 +202,7 @@ void ChatReplyAction::ChatReplyDo(Player* bot, uint32& type, uint32& guid1, uint } //toxic links - if (msg.starts_with(sPlayerbotAIConfig->toxicLinksPrefix) + if (msg.starts_with(sPlayerbotAIConfig.toxicLinksPrefix) && (GET_PLAYERBOT_AI(bot)->GetChatHelper()->ExtractAllItemIds(msg).size() > 0 || GET_PLAYERBOT_AI(bot)->GetChatHelper()->ExtractAllQuestIds(msg).size() > 0)) { HandleToxicLinksReply(bot, chatChannelSource, msg, name); @@ -224,13 +220,13 @@ void ChatReplyAction::ChatReplyDo(Player* bot, uint32& type, uint32& guid1, uint SendGeneralResponse(bot, chatChannelSource, messageRepy, name); } -bool ChatReplyAction::HandleThunderfuryReply(Player* bot, ChatChannelSource chatChannelSource, std::string& msg, std::string& name) +bool ChatReplyAction::HandleThunderfuryReply(Player* bot, ChatChannelSource chatChannelSource, std::string&, std::string&) { std::map placeholders; const auto thunderfury = sObjectMgr->GetItemTemplate(19019); placeholders["%thunderfury_link"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatItem(thunderfury); - std::string responseMessage = BOT_TEXT2("thunderfury_spam", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("thunderfury_spam", placeholders); switch (chatChannelSource) { @@ -252,7 +248,7 @@ bool ChatReplyAction::HandleThunderfuryReply(Player* bot, ChatChannelSource chat return true; } -bool ChatReplyAction::HandleToxicLinksReply(Player* bot, ChatChannelSource chatChannelSource, std::string& msg, std::string& name) +bool ChatReplyAction::HandleToxicLinksReply(Player* bot, ChatChannelSource chatChannelSource, std::string&, std::string&) { //quests std::vector incompleteQuests; @@ -271,8 +267,8 @@ bool ChatReplyAction::HandleToxicLinksReply(Player* bot, ChatChannelSource chatC std::vector botItems = GET_PLAYERBOT_AI(bot)->GetInventoryAndEquippedItems(); std::map placeholders; - placeholders["%random_inventory_item_link"] = botItems.size() > 0 ? GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatItem(botItems[rand() % botItems.size()]->GetTemplate()) : BOT_TEXT1("string_empty_link"); - placeholders["%prefix"] = sPlayerbotAIConfig->toxicLinksPrefix; + placeholders["%random_inventory_item_link"] = botItems.size() > 0 ? GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatItem(botItems[rand() % botItems.size()]->GetTemplate()) : PlayerbotTextMgr::instance().GetBotText("string_empty_link"); + placeholders["%prefix"] = sPlayerbotAIConfig.toxicLinksPrefix; if (incompleteQuests.size() > 0) { @@ -287,8 +283,8 @@ bool ChatReplyAction::HandleToxicLinksReply(Player* bot, ChatChannelSource chatC placeholders["%my_role"] = ChatHelper::FormatClass(bot, AiFactory::GetPlayerSpecTab(bot)); AreaTableEntry const* current_area = GET_PLAYERBOT_AI(bot)->GetCurrentArea(); AreaTableEntry const* current_zone = GET_PLAYERBOT_AI(bot)->GetCurrentZone(); - placeholders["%area_name"] = current_area ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); @@ -297,17 +293,17 @@ bool ChatReplyAction::HandleToxicLinksReply(Player* bot, ChatChannelSource chatC { case ChatChannelSource::SRC_WORLD: { - GET_PLAYERBOT_AI(bot)->SayToWorld(BOT_TEXT2("suggest_toxic_links", placeholders)); + GET_PLAYERBOT_AI(bot)->SayToWorld(PlayerbotTextMgr::instance().GetBotText("suggest_toxic_links", placeholders)); break; } case ChatChannelSource::SRC_GENERAL: { - GET_PLAYERBOT_AI(bot)->SayToChannel(BOT_TEXT2("suggest_toxic_links", placeholders), ChatChannelId::GENERAL); + GET_PLAYERBOT_AI(bot)->SayToChannel(PlayerbotTextMgr::instance().GetBotText("suggest_toxic_links", placeholders), ChatChannelId::GENERAL); break; } case ChatChannelSource::SRC_GUILD: { - GET_PLAYERBOT_AI(bot)->SayToGuild(BOT_TEXT2("suggest_toxic_links", placeholders)); + GET_PLAYERBOT_AI(bot)->SayToGuild(PlayerbotTextMgr::instance().GetBotText("suggest_toxic_links", placeholders)); break; } default: @@ -343,8 +339,8 @@ bool ChatReplyAction::HandleWTBItemsReply(Player* bot, ChatChannelSource chatCha placeholders["%other_name"] = name; AreaTableEntry const* current_area = GET_PLAYERBOT_AI(bot)->GetCurrentArea(); AreaTableEntry const* current_zone = GET_PLAYERBOT_AI(bot)->GetCurrentZone(); - placeholders["%area_name"] = current_area ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); @@ -365,12 +361,12 @@ bool ChatReplyAction::HandleWTBItemsReply(Player* bot, ChatChannelSource chatCha //may reply to the same channel or whisper if (urand(0, 1)) { - std::string responseMessage = BOT_TEXT2("response_wtb_items_channel", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_wtb_items_channel", placeholders); GET_PLAYERBOT_AI(bot)->SayToWorld(responseMessage); } else { - std::string responseMessage = BOT_TEXT2("response_wtb_items_whisper", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_wtb_items_whisper", placeholders); GET_PLAYERBOT_AI(bot)->Whisper(responseMessage, name); } break; @@ -380,12 +376,12 @@ bool ChatReplyAction::HandleWTBItemsReply(Player* bot, ChatChannelSource chatCha //may reply to the same channel or whisper if (urand(0, 1)) { - std::string responseMessage = BOT_TEXT2("response_wtb_items_channel", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_wtb_items_channel", placeholders); GET_PLAYERBOT_AI(bot)->SayToChannel(responseMessage, ChatChannelId::GENERAL); } else { - std::string responseMessage = BOT_TEXT2("response_wtb_items_whisper", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_wtb_items_whisper", placeholders); GET_PLAYERBOT_AI(bot)->Whisper(responseMessage, name); } break; @@ -395,12 +391,12 @@ bool ChatReplyAction::HandleWTBItemsReply(Player* bot, ChatChannelSource chatCha //may reply to the same channel or whisper if (urand(0, 1)) { - std::string responseMessage = BOT_TEXT2("response_wtb_items_channel", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_wtb_items_channel", placeholders); GET_PLAYERBOT_AI(bot)->SayToChannel(responseMessage, ChatChannelId::TRADE); } else { - std::string responseMessage = BOT_TEXT2("response_wtb_items_whisper", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_wtb_items_whisper", placeholders); GET_PLAYERBOT_AI(bot)->Whisper(responseMessage, name); } break; @@ -438,8 +434,8 @@ bool ChatReplyAction::HandleLFGQuestsReply(Player* bot, ChatChannelSource chatCh placeholders["%other_name"] = name; AreaTableEntry const* current_area = GET_PLAYERBOT_AI(bot)->GetCurrentArea(); AreaTableEntry const* current_zone = GET_PLAYERBOT_AI(bot)->GetCurrentZone(); - placeholders["%area_name"] = current_area ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? GET_PLAYERBOT_AI(bot)->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = GET_PLAYERBOT_AI(bot)->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); @@ -458,12 +454,12 @@ bool ChatReplyAction::HandleLFGQuestsReply(Player* bot, ChatChannelSource chatCh //may reply to the same channel or whisper if (urand(0, 1)) { - std::string responseMessage = BOT_TEXT2("response_lfg_quests_channel", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_lfg_quests_channel", placeholders); GET_PLAYERBOT_AI(bot)->SayToWorld(responseMessage); } else { - std::string responseMessage = BOT_TEXT2("response_lfg_quests_whisper", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_lfg_quests_whisper", placeholders); GET_PLAYERBOT_AI(bot)->Whisper(responseMessage, name); } break; @@ -473,12 +469,12 @@ bool ChatReplyAction::HandleLFGQuestsReply(Player* bot, ChatChannelSource chatCh //may reply to the same channel or whisper if (urand(0, 1)) { - std::string responseMessage = BOT_TEXT2("response_lfg_quests_channel", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_lfg_quests_channel", placeholders); GET_PLAYERBOT_AI(bot)->SayToChannel(responseMessage, ChatChannelId::GENERAL); } else { - std::string responseMessage = BOT_TEXT2("response_lfg_quests_whisper", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_lfg_quests_whisper", placeholders); GET_PLAYERBOT_AI(bot)->Whisper(responseMessage, name); } break; @@ -487,7 +483,7 @@ bool ChatReplyAction::HandleLFGQuestsReply(Player* bot, ChatChannelSource chatCh { //do not reply to the chat //may whisper - std::string responseMessage = BOT_TEXT2("response_lfg_quests_whisper", placeholders); + std::string responseMessage = PlayerbotTextMgr::instance().GetBotText("response_lfg_quests_whisper", placeholders); GET_PLAYERBOT_AI(bot)->Whisper(responseMessage, name); break; } @@ -1042,7 +1038,7 @@ std::string ChatReplyAction::GenerateReplyMessage(Player* bot, std::string& inco // load text if needed if (respondsText.empty()) { - respondsText = BOT_TEXT2(replyType, name); + respondsText = PlayerbotTextMgr::instance().GetBotText(replyType, name); } if (respondsText.size() > 255) diff --git a/src/Ai/Base/Actions/SayAction.h b/src/Ai/Base/Actions/SayAction.h index 5bf9a8f044..f0bf95ba54 100644 --- a/src/Ai/Base/Actions/SayAction.h +++ b/src/Ai/Base/Actions/SayAction.h @@ -29,7 +29,7 @@ class ChatReplyAction : public Action { public: ChatReplyAction(PlayerbotAI* ai) : Action(ai, "chat message") {} - virtual bool Execute(Event event) { return true; } + virtual bool Execute(Event) { return true; } bool isUseful() { return true; } static void ChatReplyDo(Player* bot, uint32& type, uint32& guid1, uint32& guid2, std::string& msg, std::string& chanName, std::string& name); diff --git a/src/Ai/Base/Actions/SecurityCheckAction.cpp b/src/Ai/Base/Actions/SecurityCheckAction.cpp index c47a6e52cb..a2c1cdf804 100644 --- a/src/Ai/Base/Actions/SecurityCheckAction.cpp +++ b/src/Ai/Base/Actions/SecurityCheckAction.cpp @@ -10,28 +10,47 @@ bool SecurityCheckAction::isUseful() { - return sRandomPlayerbotMgr->IsRandomBot(bot) && botAI->GetMaster() && - botAI->GetMaster()->GetSession()->GetSecurity() < SEC_GAMEMASTER && !GET_PLAYERBOT_AI(botAI->GetMaster()); -} + if (!RandomPlayerbotMgr::instance().IsRandomBot(this->bot)) + { + return false; + } -bool SecurityCheckAction::Execute(Event event) + Player* const master = this->botAI->GetMaster(); + + return master != nullptr + && master->GetSession()->GetSecurity() < SEC_GAMEMASTER + && !GET_PLAYERBOT_AI(master); +} +bool SecurityCheckAction::Execute(Event) { - if (Group* group = bot->GetGroup()) + const Group* const group = bot->GetGroup(); + + if (group == nullptr) + { + return false; + } + + const LootMethod method = group->GetLootMethod(); + const ItemQualities threshold = group->GetLootThreshold(); + + if (method != MASTER_LOOT && method != FREE_FOR_ALL && threshold <= ITEM_QUALITY_UNCOMMON) + { + return false; + } + + if (botAI->GetGroupLeader()->GetSession()->GetSecurity() != SEC_PLAYER) + { + return true; + } + + uint32_t guildId = this->bot->GetGuildId(); + + if (!guildId || guildId != botAI->GetGroupLeader()->GetGuildId()) { - LootMethod method = group->GetLootMethod(); - ItemQualities threshold = group->GetLootThreshold(); - if (method == MASTER_LOOT || method == FREE_FOR_ALL || threshold > ITEM_QUALITY_UNCOMMON) - { - if ((botAI->GetGroupLeader()->GetSession()->GetSecurity() == SEC_PLAYER) && - (!bot->GetGuildId() || bot->GetGuildId() != botAI->GetGroupLeader()->GetGuildId())) - { - botAI->TellError("I will play with this loot type only if I'm in your guild :/"); - botAI->ChangeStrategy("+passive,+stay", BOT_STATE_NON_COMBAT); - botAI->ChangeStrategy("+passive,+stay", BOT_STATE_COMBAT); - } - return true; - } + this->botAI->TellError("I will play with this loot type only if I'm in your guild :/"); + this->botAI->ChangeStrategy("+passive,+stay", BOT_STATE_NON_COMBAT); + this->botAI->ChangeStrategy("+passive,+stay", BOT_STATE_COMBAT); } - return false; + return true; } diff --git a/src/Ai/Base/Actions/SeeSpellAction.cpp b/src/Ai/Base/Actions/SeeSpellAction.cpp index 88848ca81f..b8d13974bf 100644 --- a/src/Ai/Base/Actions/SeeSpellAction.cpp +++ b/src/Ai/Base/Actions/SeeSpellAction.cpp @@ -7,7 +7,6 @@ #include "Event.h" #include "Formations.h" -#include "PathGenerator.h" #include "Playerbots.h" #include "RTSCValues.h" #include "RtscAction.h" @@ -16,11 +15,11 @@ std::set const FISHING_SPELLS = {7620, 7731, 7732, 18248, 33095, 51294}; -Creature* SeeSpellAction::CreateWps(Player* wpOwner, float x, float y, float z, float o, uint32 entry, Creature* lastWp, +Creature* SeeSpellAction::CreateWps(Player* wpOwner, float x, float y, float z, float o, uint32 entry, Creature*, bool important) { float dist = wpOwner->GetDistance(x, y, z); - float delay = 1000.0f * dist / wpOwner->GetSpeed(MOVE_RUN) + sPlayerbotAIConfig->reactDelay; + float delay = 1000.0f * dist / wpOwner->GetSpeed(MOVE_RUN) + sPlayerbotAIConfig.reactDelay; if (!important) delay *= 0.25; @@ -61,7 +60,7 @@ bool SeeSpellAction::Execute(Event event) if (FISHING_SPELLS.find(spellId) != FISHING_SPELLS.end()) { - if (AI_VALUE(bool, "can fish") && sPlayerbotAIConfig->enableFishingWithMaster) + if (AI_VALUE(bool, "can fish") && sPlayerbotAIConfig.enableFishingWithMaster) { botAI->ChangeStrategy("+master fishing", BOT_STATE_NON_COMBAT); return true; diff --git a/src/Ai/Base/Actions/SendMailAction.cpp b/src/Ai/Base/Actions/SendMailAction.cpp index c6184c4b98..9be9d553ab 100644 --- a/src/Ai/Base/Actions/SendMailAction.cpp +++ b/src/Ai/Base/Actions/SendMailAction.cpp @@ -14,7 +14,7 @@ bool SendMailAction::Execute(Event event) { uint32 account = bot->GetSession()->GetAccountId(); - bool randomBot = sPlayerbotAIConfig->IsInRandomAccountList(account); + bool randomBot = sPlayerbotAIConfig.IsInRandomAccountList(account); GuidVector gos = *context->GetValue("nearest game objects"); bool mailboxFound = false; diff --git a/src/Ai/Base/Actions/SetHomeAction.cpp b/src/Ai/Base/Actions/SetHomeAction.cpp index 44f3c7b49f..b7dff92054 100644 --- a/src/Ai/Base/Actions/SetHomeAction.cpp +++ b/src/Ai/Base/Actions/SetHomeAction.cpp @@ -8,7 +8,7 @@ #include "Event.h" #include "Playerbots.h" -bool SetHomeAction::Execute(Event event) +bool SetHomeAction::Execute(Event) { Player* master = GetMaster(); @@ -26,20 +26,10 @@ bool SetHomeAction::Execute(Event event) if (Unit* unit = botAI->GetUnit(selection)) if (unit->HasNpcFlag(UNIT_NPC_FLAG_INNKEEPER)) { - if (isRpgAction) - { - Creature* creature = botAI->GetCreature(selection); - bot->GetSession()->SendBindPoint(creature); - botAI->TellMaster("This inn is my new home"); - return true; - } - else - { - Creature* creature = botAI->GetCreature(selection); - bot->GetSession()->SendBindPoint(creature); - botAI->TellMaster("This inn is my new home"); - return true; - } + Creature* creature = botAI->GetCreature(selection); + bot->GetSession()->SendBindPoint(creature); + botAI->TellMaster("This inn is my new home"); + return true; } GuidVector npcs = AI_VALUE(GuidVector, "nearest npcs"); diff --git a/src/Ai/Base/Actions/ShareQuestAction.cpp b/src/Ai/Base/Actions/ShareQuestAction.cpp index d4b470b4c1..a778d33fb8 100644 --- a/src/Ai/Base/Actions/ShareQuestAction.cpp +++ b/src/Ai/Base/Actions/ShareQuestAction.cpp @@ -40,9 +40,8 @@ bool ShareQuestAction::Execute(Event event) return false; } -bool AutoShareQuestAction::Execute(Event event) +bool AutoShareQuestAction::Execute(Event) { - Player* requester = event.getOwner() ? event.getOwner() : GetMaster(); bool shared = false; for (uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot) @@ -109,4 +108,4 @@ bool AutoShareQuestAction::Execute(Event event) bool AutoShareQuestAction::isUseful() { return bot->GetGroup() && !botAI->HasActivePlayerMaster(); -} \ No newline at end of file +} diff --git a/src/Ai/Base/Actions/StatsAction.cpp b/src/Ai/Base/Actions/StatsAction.cpp index f6872c8468..caf367fb2e 100644 --- a/src/Ai/Base/Actions/StatsAction.cpp +++ b/src/Ai/Base/Actions/StatsAction.cpp @@ -7,9 +7,9 @@ #include "ChatHelper.h" #include "Event.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" -bool StatsAction::Execute(Event event) +bool StatsAction::Execute(Event) { std::ostringstream out; diff --git a/src/Ai/Base/Actions/StayActions.cpp b/src/Ai/Base/Actions/StayActions.cpp index 525ff8d53e..94e4290ac5 100644 --- a/src/Ai/Base/Actions/StayActions.cpp +++ b/src/Ai/Base/Actions/StayActions.cpp @@ -19,7 +19,7 @@ bool StayActionBase::Stay() if (bot->GetMotionMaster()->GetCurrentMovementGeneratorType() == FLIGHT_MOTION_TYPE) return false; - uint32 sitDelay = sPlayerbotAIConfig->sitDelay / 1000; + uint32 sitDelay = sPlayerbotAIConfig.sitDelay / 1000; time_t stayTime = AI_VALUE(time_t, "stay time"); time_t now = time(nullptr); if (!stayTime) @@ -39,7 +39,7 @@ bool StayActionBase::Stay() return true; } -bool StayAction::Execute(Event event) { return Stay(); } +bool StayAction::Execute(Event) { return Stay(); } bool StayAction::isUseful() { @@ -47,8 +47,7 @@ bool StayAction::isUseful() PositionInfo stayPosition = AI_VALUE(PositionMap&, "position")["stay"]; if (stayPosition.isSet()) { - const float distance = bot->GetDistance(stayPosition.x, stayPosition.y, stayPosition.z); - if (sPlayerbotAIConfig->followDistance) + if (sPlayerbotAIConfig.followDistance) { return false; } @@ -64,7 +63,7 @@ bool StayAction::isUseful() return AI_VALUE2(bool, "moving", "self target"); } -bool SitAction::Execute(Event event) +bool SitAction::Execute(Event) { if (bot->isMoving()) return false; diff --git a/src/Ai/Base/Actions/SuggestWhatToDoAction.cpp b/src/Ai/Base/Actions/SuggestWhatToDoAction.cpp index 159bfd4ebb..b3324c3cac 100644 --- a/src/Ai/Base/Actions/SuggestWhatToDoAction.cpp +++ b/src/Ai/Base/Actions/SuggestWhatToDoAction.cpp @@ -7,25 +7,19 @@ #include "SuggestWhatToDoAction.h" #include "ServerFacade.h" -#include "ChannelMgr.h" #include "Event.h" #include "ItemVisitors.h" #include "AiFactory.h" #include "ChatHelper.h" #include "Playerbots.h" -#include "PlayerbotTextMgr.h" -#include "Config.h" #include "BroadcastHelper.h" #include "AiFactory.h" -#include "ChannelMgr.h" #include "ChatHelper.h" -#include "Config.h" #include "Event.h" -#include "GuildMgr.h" #include "ItemVisitors.h" -#include "PlayerbotTextMgr.h" #include "Playerbots.h" #include "ServerFacade.h" +#include "Channel.h" enum eTalkType { @@ -54,7 +48,7 @@ SuggestWhatToDoAction::SuggestWhatToDoAction(PlayerbotAI* botAI, std::string con bool SuggestWhatToDoAction::isUseful() { - if (!sRandomPlayerbotMgr->IsRandomBot(bot) || bot->GetGroup() || bot->GetInstanceId() || bot->GetBattleground()) + if (!sRandomPlayerbotMgr.IsRandomBot(bot) || bot->GetGroup() || bot->GetInstanceId() || bot->GetBattleground()) return false; std::string qualifier = "suggest what to do"; @@ -62,14 +56,13 @@ bool SuggestWhatToDoAction::isUseful() return (time(0) - lastSaid) > 30; } -bool SuggestWhatToDoAction::Execute(Event event) +bool SuggestWhatToDoAction::Execute(Event) { uint32 index = rand() % suggestions.size(); auto fnct_ptr = suggestions[index]; fnct_ptr(); std::string const qualifier = "suggest what to do"; - time_t lastSaid = AI_VALUE2(time_t, "last said", qualifier); botAI->GetAiObjectContext()->GetValue("last said", qualifier)->Set(time(nullptr) + urand(1, 60)); return true; @@ -140,7 +133,7 @@ void SuggestWhatToDoAction::grindMaterials() placeholders["%role"] = chat->formatClass(bot, AiFactory::GetPlayerSpecTab(bot)); placeholders["%category"] = item; - spam(BOT_TEXT2("suggest_trade", placeholders), urand(0, 1) ? 0x3C : 0x18, !urand(0, 2), !urand(0, + spam(PlayerbotTextMgr::instance().GetBotText("suggest_trade", placeholders), urand(0, 1) ? 0x3C : 0x18, !urand(0, 2), !urand(0, 3)); return; } } @@ -227,7 +220,7 @@ void SuggestWhatToDoAction::thunderfury() class FindTradeItemsVisitor : public IterateItemsVisitor { public: - FindTradeItemsVisitor(uint32 quality) : quality(quality), IterateItemsVisitor() {} + FindTradeItemsVisitor(uint32 quality) : IterateItemsVisitor(), quality(quality) {} bool Visit(Item* item) override { @@ -258,11 +251,11 @@ class FindTradeItemsVisitor : public IterateItemsVisitor SuggestDungeonAction::SuggestDungeonAction(PlayerbotAI* botAI) : SuggestWhatToDoAction(botAI, "suggest dungeon") {} -bool SuggestDungeonAction::Execute(Event event) +bool SuggestDungeonAction::Execute(Event) { - // TODO: use sPlayerbotDungeonRepository + // TODO: use PlayerbotDungeonRepository::instance() - if (!sPlayerbotAIConfig->randomBotSuggestDungeons || bot->GetGroup()) + if (!sPlayerbotAIConfig.randomBotSuggestDungeons || bot->GetGroup()) return false; if (instances.empty()) @@ -325,7 +318,7 @@ bool SuggestDungeonAction::Execute(Event event) SuggestTradeAction::SuggestTradeAction(PlayerbotAI* botAI) : SuggestWhatToDoAction(botAI, "suggest trade") {} -bool SuggestTradeAction::Execute(Event event) +bool SuggestTradeAction::Execute(Event) { uint32 quality = urand(0, 100); if (quality > 95) @@ -373,7 +366,7 @@ bool SuggestTradeAction::Execute(Event event) if (!proto) return false; - uint32 price = proto->SellPrice * sRandomPlayerbotMgr->GetSellMultiplier(bot) * count; + uint32 price = proto->SellPrice * sRandomPlayerbotMgr.GetSellMultiplier(bot) * count; if (!price) return false; diff --git a/src/Ai/Base/Actions/TalkToQuestGiverAction.cpp b/src/Ai/Base/Actions/TalkToQuestGiverAction.cpp index 7f791d0d63..35e8584b82 100644 --- a/src/Ai/Base/Actions/TalkToQuestGiverAction.cpp +++ b/src/Ai/Base/Actions/TalkToQuestGiverAction.cpp @@ -24,7 +24,7 @@ bool TalkToQuestGiverAction::ProcessQuest(Quest const* quest, Object* questGiver QuestStatus status = bot->GetQuestStatus(quest->GetQuestId()); Player* master = GetMaster(); - if (sPlayerbotAIConfig->syncQuestForPlayer && master) + if (sPlayerbotAIConfig.syncQuestForPlayer && master) { PlayerbotAI* masterBotAI = GET_PLAYERBOT_AI(master); if (!masterBotAI || masterBotAI->IsRealPlayer()) @@ -35,7 +35,7 @@ bool TalkToQuestGiverAction::ProcessQuest(Quest const* quest, Object* questGiver } } - if (sPlayerbotAIConfig->syncQuestWithPlayer) + if (sPlayerbotAIConfig.syncQuestWithPlayer) { if (master && master->GetQuestStatus(quest->GetQuestId()) == QUEST_STATUS_COMPLETE && (status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_FAILED)) @@ -105,14 +105,14 @@ void TalkToQuestGiverAction::RewardNoItem(Quest const* quest, Object* questGiver if (bot->CanRewardQuest(quest, false)) { - out << BOT_TEXT2("quest_status_completed", args); + out << PlayerbotTextMgr::instance().GetBotText("quest_status_completed", args); BroadcastHelper::BroadcastQuestTurnedIn(botAI, bot, quest); bot->RewardQuest(quest, 0, questGiver, false); } else { - out << BOT_TEXT2("quest_status_unable_to_complete", args); + out << PlayerbotTextMgr::instance().GetBotText("quest_status_unable_to_complete", args); } } @@ -126,13 +126,13 @@ void TalkToQuestGiverAction::RewardSingleItem(Quest const* quest, Object* questG if (bot->CanRewardQuest(quest, index, false)) { - out << BOT_TEXT2("quest_status_complete_single_reward", args); + out << PlayerbotTextMgr::instance().GetBotText("quest_status_complete_single_reward", args); BroadcastHelper::BroadcastQuestTurnedIn(botAI, bot, quest); bot->RewardQuest(quest, index, questGiver, true); } else { - out << BOT_TEXT2("quest_status_unable_to_complete", args); + out << PlayerbotTextMgr::instance().GetBotText("quest_status_unable_to_complete", args); } } @@ -171,7 +171,7 @@ void TalkToQuestGiverAction::RewardMultipleItem(Quest const* quest, Object* ques std::set bestIds; std::ostringstream outid; - if (!botAI->IsAlt() || sPlayerbotAIConfig->autoPickReward == "yes") + if (!botAI->IsAlt() || sPlayerbotAIConfig.autoPickReward == "yes") { bestIds = BestRewards(quest); if (!bestIds.empty()) @@ -198,7 +198,7 @@ void TalkToQuestGiverAction::RewardMultipleItem(Quest const* quest, Object* ques AskToSelectReward(quest, out, true); } } - else if (sPlayerbotAIConfig->autoPickReward == "no") + else if (sPlayerbotAIConfig.autoPickReward == "no") { // Old functionality, list rewards. AskToSelectReward(quest, out, false); @@ -231,7 +231,6 @@ void TalkToQuestGiverAction::AskToSelectReward(Quest const* quest, std::ostrings for (uint8 i = 0; i < quest->GetRewChoiceItemsCount(); ++i) { ItemTemplate const* item = sObjectMgr->GetItemTemplate(quest->RewardChoiceItemId[i]); - ItemUsage usage = AI_VALUE2(ItemUsage, "item usage", quest->RewardChoiceItemId[i]); if (!forEquip || BestRewards(quest).count(i) > 0) { @@ -248,7 +247,6 @@ bool TurnInQueryQuestAction::Execute(Event event) WorldPacket pakcet = event.getPacket(); ObjectGuid guid; uint32 questId; - ObjectGuid unk1; pakcet >> guid >> questId; Object* object = ObjectAccessor::GetObjectByTypeMask(*bot, guid, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM); @@ -260,7 +258,7 @@ bool TurnInQueryQuestAction::Execute(Event event) QuestStatus status = bot->GetQuestStatus(quest->GetQuestId()); Player* master = GetMaster(); - if (sPlayerbotAIConfig->syncQuestForPlayer && master) + if (sPlayerbotAIConfig.syncQuestForPlayer && master) { PlayerbotAI* masterBotAI = GET_PLAYERBOT_AI(master); if (!masterBotAI || masterBotAI->IsRealPlayer()) @@ -271,7 +269,7 @@ bool TurnInQueryQuestAction::Execute(Event event) } } - if (sPlayerbotAIConfig->syncQuestWithPlayer) + if (sPlayerbotAIConfig.syncQuestWithPlayer) { if (status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_FAILED) { diff --git a/src/Ai/Base/Actions/TameAction.cpp b/src/Ai/Base/Actions/TameAction.cpp index 5b3eda1034..b19626e594 100644 --- a/src/Ai/Base/Actions/TameAction.cpp +++ b/src/Ai/Base/Actions/TameAction.cpp @@ -6,12 +6,10 @@ #include "TameAction.h" #include #include -#include #include #include #include #include "DBCStructure.h" -#include "Log.h" #include "ObjectMgr.h" #include "Pet.h" #include "Player.h" @@ -53,7 +51,6 @@ bool TameAction::Execute(Event event) { std::set normalFamilies; std::set exoticFamilies; - Player* bot = botAI->GetBot(); // Loop over all creature templates and collect tameable families CreatureTemplateContainer const* creatures = sObjectMgr->GetCreatureTemplates(); diff --git a/src/Ai/Base/Actions/TeleportAction.cpp b/src/Ai/Base/Actions/TeleportAction.cpp index 65aa24e09f..65a76b12d7 100644 --- a/src/Ai/Base/Actions/TeleportAction.cpp +++ b/src/Ai/Base/Actions/TeleportAction.cpp @@ -7,9 +7,12 @@ #include "Event.h" #include "LastMovementValue.h" -#include "Playerbots.h" +#include "AiObjectContext.h" +#include "PlayerbotAI.h" +#include "SpellMgr.h" +#include "Spell.h" -bool TeleportAction::Execute(Event event) +bool TeleportAction::Execute(Event) { /* // List of allowed portal entries (you can populate this dynamically) @@ -74,7 +77,7 @@ bool TeleportAction::Execute(Event event) continue; uint32 spellId = goInfo->spellcaster.spellId; - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); + SpellInfo const* spellInfo = SpellMgr::instance()->GetSpellInfo(spellId); if (!spellInfo || !spellInfo->HasEffect(SPELL_EFFECT_TELEPORT_UNITS)) continue; diff --git a/src/Ai/Base/Actions/TellLosAction.cpp b/src/Ai/Base/Actions/TellLosAction.cpp index 9cd12b02e3..330258b9c1 100644 --- a/src/Ai/Base/Actions/TellLosAction.cpp +++ b/src/Ai/Base/Actions/TellLosAction.cpp @@ -4,11 +4,9 @@ */ #include "TellLosAction.h" -#include #include #include "ChatHelper.h" -#include "DBCStores.h" #include "Event.h" #include "ItemTemplate.h" #include "ObjectMgr.h" @@ -77,7 +75,7 @@ void TellLosAction::ListGameObjects(std::string const title, GuidVector gos) } } -bool TellAuraAction::Execute(Event event) +bool TellAuraAction::Execute(Event) { botAI->TellMaster("--- Auras ---"); sLog->outMessage("playerbot", LOG_LEVEL_DEBUG, "--- Auras ---"); @@ -97,7 +95,6 @@ bool TellAuraAction::Execute(Event event) std::string caster_name = caster ? caster->GetName() : "unknown"; bool is_area = aura->IsArea(); int32 duration = aura->GetDuration(); - const SpellInfo* spellInfo = aura->GetSpellInfo(); int32 spellId = aura->GetSpellInfo()->Id; bool isPositive = aura->GetSpellInfo()->IsPositive(); sLog->outMessage("playerbot", LOG_LEVEL_DEBUG, @@ -130,7 +127,7 @@ bool TellAuraAction::Execute(Event event) return true; } -bool TellEstimatedDpsAction::Execute(Event event) +bool TellEstimatedDpsAction::Execute(Event) { float dps = AI_VALUE(float, "estimated group dps"); botAI->TellMaster("Estimated Group DPS: " + std::to_string(dps)); diff --git a/src/Ai/Base/Actions/TellMasterAction.cpp b/src/Ai/Base/Actions/TellMasterAction.cpp index 4b8d96d561..1da66554db 100644 --- a/src/Ai/Base/Actions/TellMasterAction.cpp +++ b/src/Ai/Base/Actions/TellMasterAction.cpp @@ -8,13 +8,13 @@ #include "Event.h" #include "Playerbots.h" -bool TellMasterAction::Execute(Event event) +bool TellMasterAction::Execute(Event) { botAI->TellMaster(text); return true; } -bool OutOfReactRangeAction::Execute(Event event) +bool OutOfReactRangeAction::Execute(Event) { botAI->TellMaster("Wait for me!"); return true; diff --git a/src/Ai/Base/Actions/TellReputationAction.cpp b/src/Ai/Base/Actions/TellReputationAction.cpp index e08a38d840..050a2457a5 100644 --- a/src/Ai/Base/Actions/TellReputationAction.cpp +++ b/src/Ai/Base/Actions/TellReputationAction.cpp @@ -6,10 +6,10 @@ #include "TellReputationAction.h" #include "Event.h" -#include "Playerbots.h" #include "ReputationMgr.h" +#include "PlayerbotAI.h" -bool TellReputationAction::Execute(Event event) +bool TellReputationAction::Execute(Event) { Player* master = GetMaster(); if (!master) diff --git a/src/Ai/Base/Actions/TellTargetAction.cpp b/src/Ai/Base/Actions/TellTargetAction.cpp index 7ecd8efb5a..8830618996 100644 --- a/src/Ai/Base/Actions/TellTargetAction.cpp +++ b/src/Ai/Base/Actions/TellTargetAction.cpp @@ -6,10 +6,11 @@ #include "TellTargetAction.h" #include "Event.h" -#include "Playerbots.h" #include "ThreatMgr.h" +#include "AiObjectContext.h" +#include "PlayerbotAI.h" -bool TellTargetAction::Execute(Event event) +bool TellTargetAction::Execute(Event) { Unit* target = context->GetValue("current target")->Get(); if (target) @@ -24,7 +25,7 @@ bool TellTargetAction::Execute(Event event) return true; } -bool TellAttackersAction::Execute(Event event) +bool TellAttackersAction::Execute(Event) { botAI->TellMaster("--- Attackers ---"); diff --git a/src/Ai/Base/Actions/TradeAction.cpp b/src/Ai/Base/Actions/TradeAction.cpp index ad81d9f93b..84faae89f4 100644 --- a/src/Ai/Base/Actions/TradeAction.cpp +++ b/src/Ai/Base/Actions/TradeAction.cpp @@ -8,14 +8,14 @@ #include "Event.h" #include "ItemCountValue.h" #include "ItemVisitors.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" bool TradeAction::Execute(Event event) { std::string const text = event.getParam(); // If text starts with any excluded prefix, don't process it further. - for (auto const& prefix : sPlayerbotAIConfig->tradeActionExcludedPrefixes) + for (auto const& prefix : sPlayerbotAIConfig.tradeActionExcludedPrefixes) { if (text.find(prefix) == 0) return false; @@ -56,7 +56,18 @@ bool TradeAction::Execute(Event event) } size_t pos = text.rfind(" "); - int count = pos != std::string::npos ? atoi(text.substr(pos + 1).c_str()) : 1; + + uint32_t count = 1; + + if (pos != std::string::npos) + { + const int32_t possibleValue = atoi(text.substr(pos + 1).c_str()); + + if (possibleValue > 0) + { + count = possibleValue; + } + } std::vector found = parseItems(text); if (found.empty()) diff --git a/src/Ai/Base/Actions/TradeStatusAction.cpp b/src/Ai/Base/Actions/TradeStatusAction.cpp index 16ad2ca79d..72ddb87109 100644 --- a/src/Ai/Base/Actions/TradeStatusAction.cpp +++ b/src/Ai/Base/Actions/TradeStatusAction.cpp @@ -32,7 +32,7 @@ bool TradeStatusAction::Execute(Event event) return false; } - if (sPlayerbotAIConfig->enableRandomBotTrading == 0 && (sRandomPlayerbotMgr->IsRandomBot(bot)|| sRandomPlayerbotMgr->IsAddclassBot(bot))) + if (sPlayerbotAIConfig.enableRandomBotTrading == 0 && (sRandomPlayerbotMgr.IsRandomBot(bot)|| sRandomPlayerbotMgr.IsAddclassBot(bot))) { bot->Whisper("Trading is disabled", LANG_UNIVERSAL, trader); return false; @@ -61,11 +61,9 @@ bool TradeStatusAction::Execute(Event event) uint32 status = 0; p << status; - uint32 discount = sRandomPlayerbotMgr->GetTradeDiscount(bot, trader); + uint32 discount = sRandomPlayerbotMgr.GetTradeDiscount(bot, trader); if (CheckTrade()) { - int32 botMoney = CalculateCost(bot, true); - std::map givenItemIds, takenItemIds; for (uint32 slot = 0; slot < TRADE_SLOT_TRADED_COUNT; ++slot) { @@ -81,7 +79,7 @@ bool TradeStatusAction::Execute(Event event) bot->GetSession()->HandleAcceptTradeOpcode(p); if (bot->GetTradeData()) { - sRandomPlayerbotMgr->SetTradeDiscount(bot, trader, discount); + sRandomPlayerbotMgr.SetTradeDiscount(bot, trader, discount); return false; } @@ -96,7 +94,7 @@ bool TradeStatusAction::Execute(Event event) craftData.AddObtained(itemId, count); } - sGuildTaskMgr->CheckItemTask(itemId, count, trader, bot); + GuildTaskMgr::instance().CheckItemTask(itemId, count, trader, bot); } for (std::map::iterator i = takenItemIds.begin(); i != takenItemIds.end(); ++i) @@ -116,7 +114,7 @@ bool TradeStatusAction::Execute(Event event) } else if (status == TRADE_STATUS_BEGIN_TRADE) { - if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, trader, sPlayerbotAIConfig->sightDistance)) + if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, trader, sPlayerbotAIConfig.sightDistance)) bot->SetFacingToObject(trader); BeginTrade(); @@ -141,9 +139,9 @@ void TradeStatusAction::BeginTrade() botAI->TellMaster("=== Inventory ==="); TellItems(visitor.items, visitor.soulbound); - if (sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sRandomPlayerbotMgr.IsRandomBot(bot)) { - uint32 discount = sRandomPlayerbotMgr->GetTradeDiscount(bot, botAI->GetMaster()); + uint32 discount = sRandomPlayerbotMgr.GetTradeDiscount(bot, botAI->GetMaster()); if (discount) { std::ostringstream out; @@ -161,13 +159,11 @@ bool TradeStatusAction::CheckTrade() if (!botAI->HasActivePlayerMaster() && GET_PLAYERBOT_AI(bot->GetTrader())) { - bool isGivingItem = false; for (uint32 slot = 0; slot < TRADE_SLOT_TRADED_COUNT; ++slot) { Item* item = bot->GetTradeData()->GetItem((TradeSlots)slot); if (item) { - isGivingItem = true; break; } } @@ -198,7 +194,7 @@ bool TradeStatusAction::CheckTrade() return false; } uint32 accountId = bot->GetSession()->GetAccountId(); - if (!sPlayerbotAIConfig->IsInRandomAccountList(accountId)) + if (!sPlayerbotAIConfig.IsInRandomAccountList(accountId)) { int32 botItemsMoney = CalculateCost(bot, true); int32 botMoney = bot->GetTradeData()->GetMoney() + botItemsMoney; @@ -214,12 +210,12 @@ bool TradeStatusAction::CheckTrade() int32 botMoney = bot->GetTradeData()->GetMoney() + botItemsMoney; int32 playerItemsMoney = CalculateCost(trader, false); int32 playerMoney = trader->GetTradeData()->GetMoney() + playerItemsMoney; - if (botItemsMoney > 0 && sPlayerbotAIConfig->enableRandomBotTrading == 2 && (sRandomPlayerbotMgr->IsRandomBot(bot)|| sRandomPlayerbotMgr->IsAddclassBot(bot))) + if (botItemsMoney > 0 && sPlayerbotAIConfig.enableRandomBotTrading == 2 && (sRandomPlayerbotMgr.IsRandomBot(bot)|| sRandomPlayerbotMgr.IsAddclassBot(bot))) { bot->Whisper("Selling is disabled.", LANG_UNIVERSAL, trader); return false; } - if (playerItemsMoney && sPlayerbotAIConfig->enableRandomBotTrading == 3 && (sRandomPlayerbotMgr->IsRandomBot(bot)|| sRandomPlayerbotMgr->IsAddclassBot(bot))) + if (playerItemsMoney && sPlayerbotAIConfig.enableRandomBotTrading == 3 && (sRandomPlayerbotMgr.IsRandomBot(bot)|| sRandomPlayerbotMgr.IsAddclassBot(bot))) { bot->Whisper("Buying is disabled.", LANG_UNIVERSAL, trader); return false; @@ -262,7 +258,7 @@ bool TradeStatusAction::CheckTrade() return false; } - int32 discount = (int32)sRandomPlayerbotMgr->GetTradeDiscount(bot, trader); + int32 discount = (int32)sRandomPlayerbotMgr.GetTradeDiscount(bot, trader); int32 delta = playerMoney - botMoney; int32 moneyDelta = (int32)trader->GetTradeData()->GetMoney() - (int32)bot->GetTradeData()->GetMoney(); bool success = false; @@ -287,7 +283,7 @@ bool TradeStatusAction::CheckTrade() if (success) { - sRandomPlayerbotMgr->AddTradeDiscount(bot, trader, delta); + sRandomPlayerbotMgr.AddTradeDiscount(bot, trader, delta); switch (urand(0, 4)) { case 0: @@ -353,11 +349,11 @@ int32 TradeStatusAction::CalculateCost(Player* player, bool sell) if (sell) { - sum += item->GetCount() * proto->SellPrice * sRandomPlayerbotMgr->GetSellMultiplier(bot); + sum += item->GetCount() * proto->SellPrice * sRandomPlayerbotMgr.GetSellMultiplier(bot); } else { - sum += item->GetCount() * proto->BuyPrice * sRandomPlayerbotMgr->GetBuyMultiplier(bot); + sum += item->GetCount() * proto->BuyPrice * sRandomPlayerbotMgr.GetBuyMultiplier(bot); } } diff --git a/src/Ai/Base/Actions/TrainerAction.cpp b/src/Ai/Base/Actions/TrainerAction.cpp index bca7406012..0155da5789 100644 --- a/src/Ai/Base/Actions/TrainerAction.cpp +++ b/src/Ai/Base/Actions/TrainerAction.cpp @@ -12,7 +12,7 @@ void TrainerAction::Learn(uint32 cost, const Trainer::Spell tSpell, std::ostringstream& msg) { - if (sPlayerbotAIConfig->autoTrainSpells != "free" && !botAI->HasCheat(BotCheatMask::gold)) + if (sPlayerbotAIConfig.autoTrainSpells != "free" && !botAI->HasCheat(BotCheatMask::gold)) { if (AI_VALUE2(uint32, "free money for", (uint32)NeedMoneyFor::spells) < cost) { @@ -126,8 +126,8 @@ bool TrainerAction::Execute(Event event) if (spell) spells.insert(spell); - if (text.find("learn") != std::string::npos || sRandomPlayerbotMgr->IsRandomBot(bot) || - (sPlayerbotAIConfig->autoTrainSpells != "no" && + if (text.find("learn") != std::string::npos || sRandomPlayerbotMgr.IsRandomBot(bot) || + (sPlayerbotAIConfig.autoTrainSpells != "no" && (trainer->GetTrainerType() != Trainer::Type::Tradeskill || !botAI->HasActivePlayerMaster()))) // Todo rewrite to only exclude start primary profession skills and make // config dependent. @@ -155,9 +155,9 @@ void TrainerAction::TellFooter(uint32 totalCost) } } -bool MaintenanceAction::Execute(Event event) +bool MaintenanceAction::Execute(Event) { - if (!sPlayerbotAIConfig->maintenanceCommand) + if (!sPlayerbotAIConfig.maintenanceCommand) { botAI->TellError("maintenance command is not allowed, please check the configuration."); return false; @@ -186,66 +186,66 @@ bool MaintenanceAction::Execute(Event event) factory.InitMounts(); factory.InitGlyphs(false); factory.InitKeyring(); - if (bot->GetLevel() >= sPlayerbotAIConfig->minEnchantingBotLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.minEnchantingBotLevel) factory.ApplyEnchantAndGemsNew(); } else { - if (sPlayerbotAIConfig->altMaintenanceAttunementQs) + if (sPlayerbotAIConfig.altMaintenanceAttunementQs) factory.InitAttunementQuests(); - if (sPlayerbotAIConfig->altMaintenanceBags) + if (sPlayerbotAIConfig.altMaintenanceBags) factory.InitBags(false); - if (sPlayerbotAIConfig->altMaintenanceAmmo) + if (sPlayerbotAIConfig.altMaintenanceAmmo) factory.InitAmmo(); - if (sPlayerbotAIConfig->altMaintenanceFood) + if (sPlayerbotAIConfig.altMaintenanceFood) factory.InitFood(); - if (sPlayerbotAIConfig->altMaintenanceReagents) + if (sPlayerbotAIConfig.altMaintenanceReagents) factory.InitReagents(); - if (sPlayerbotAIConfig->altMaintenanceConsumables) + if (sPlayerbotAIConfig.altMaintenanceConsumables) factory.InitConsumables(); - if (sPlayerbotAIConfig->altMaintenancePotions) + if (sPlayerbotAIConfig.altMaintenancePotions) factory.InitPotions(); - if (sPlayerbotAIConfig->altMaintenanceTalentTree) + if (sPlayerbotAIConfig.altMaintenanceTalentTree) factory.InitTalentsTree(true); - if (sPlayerbotAIConfig->altMaintenancePet) + if (sPlayerbotAIConfig.altMaintenancePet) factory.InitPet(); - if (sPlayerbotAIConfig->altMaintenancePetTalents) + if (sPlayerbotAIConfig.altMaintenancePetTalents) factory.InitPetTalents(); - if (sPlayerbotAIConfig->altMaintenanceSkills) + if (sPlayerbotAIConfig.altMaintenanceSkills) factory.InitSkills(); - if (sPlayerbotAIConfig->altMaintenanceClassSpells) + if (sPlayerbotAIConfig.altMaintenanceClassSpells) factory.InitClassSpells(); - if (sPlayerbotAIConfig->altMaintenanceAvailableSpells) + if (sPlayerbotAIConfig.altMaintenanceAvailableSpells) factory.InitAvailableSpells(); - if (sPlayerbotAIConfig->altMaintenanceReputation) + if (sPlayerbotAIConfig.altMaintenanceReputation) factory.InitReputation(); - if (sPlayerbotAIConfig->altMaintenanceSpecialSpells) + if (sPlayerbotAIConfig.altMaintenanceSpecialSpells) factory.InitSpecialSpells(); - if (sPlayerbotAIConfig->altMaintenanceMounts) + if (sPlayerbotAIConfig.altMaintenanceMounts) factory.InitMounts(); - if (sPlayerbotAIConfig->altMaintenanceGlyphs) + if (sPlayerbotAIConfig.altMaintenanceGlyphs) factory.InitGlyphs(false); - if (sPlayerbotAIConfig->altMaintenanceKeyring) + if (sPlayerbotAIConfig.altMaintenanceKeyring) factory.InitKeyring(); - if (sPlayerbotAIConfig->altMaintenanceGemsEnchants && bot->GetLevel() >= sPlayerbotAIConfig->minEnchantingBotLevel) + if (sPlayerbotAIConfig.altMaintenanceGemsEnchants && bot->GetLevel() >= sPlayerbotAIConfig.minEnchantingBotLevel) factory.ApplyEnchantAndGemsNew(); } @@ -255,7 +255,7 @@ bool MaintenanceAction::Execute(Event event) return true; } -bool RemoveGlyphAction::Execute(Event event) +bool RemoveGlyphAction::Execute(Event) { for (uint32 slotIndex = 0; slotIndex < MAX_GLYPH_SLOT_INDEX; ++slotIndex) { @@ -265,30 +265,30 @@ bool RemoveGlyphAction::Execute(Event event) return true; } -bool AutoGearAction::Execute(Event event) +bool AutoGearAction::Execute(Event) { - if (!sPlayerbotAIConfig->autoGearCommand) + if (!sPlayerbotAIConfig.autoGearCommand) { botAI->TellError("autogear command is not allowed, please check the configuration."); return false; } - if (!sPlayerbotAIConfig->autoGearCommandAltBots && - !sPlayerbotAIConfig->IsInRandomAccountList(bot->GetSession()->GetAccountId())) + if (!sPlayerbotAIConfig.autoGearCommandAltBots && + !sPlayerbotAIConfig.IsInRandomAccountList(bot->GetSession()->GetAccountId())) { botAI->TellError("You cannot use autogear on alt bots."); return false; } botAI->TellMaster("I'm auto gearing"); - uint32 gs = sPlayerbotAIConfig->autoGearScoreLimit == 0 + uint32 gs = sPlayerbotAIConfig.autoGearScoreLimit == 0 ? 0 - : PlayerbotFactory::CalcMixedGearScore(sPlayerbotAIConfig->autoGearScoreLimit, - sPlayerbotAIConfig->autoGearQualityLimit); - PlayerbotFactory factory(bot, bot->GetLevel(), sPlayerbotAIConfig->autoGearQualityLimit, gs); + : PlayerbotFactory::CalcMixedGearScore(sPlayerbotAIConfig.autoGearScoreLimit, + sPlayerbotAIConfig.autoGearQualityLimit); + PlayerbotFactory factory(bot, bot->GetLevel(), sPlayerbotAIConfig.autoGearQualityLimit, gs); factory.InitEquipment(true); factory.InitAmmo(); - if (bot->GetLevel() >= sPlayerbotAIConfig->minEnchantingBotLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.minEnchantingBotLevel) { factory.ApplyEnchantAndGemsNew(); } diff --git a/src/Ai/Base/Actions/TravelAction.cpp b/src/Ai/Base/Actions/TravelAction.cpp index a290605718..0038425f80 100644 --- a/src/Ai/Base/Actions/TravelAction.cpp +++ b/src/Ai/Base/Actions/TravelAction.cpp @@ -5,12 +5,13 @@ #include "TravelAction.h" -#include "CellImpl.h" #include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "Playerbots.h" +// Required due to a poor implementation by AC +#include "CellImpl.h" +#include "GridNotifiersImpl.h" -bool TravelAction::Execute(Event event) +bool TravelAction::Execute(Event) { TravelTarget* target = AI_VALUE(TravelTarget*, "travel target"); @@ -21,9 +22,9 @@ bool TravelAction::Execute(Event event) Unit* newTarget = nullptr; std::list targets; - Acore::AnyUnitInObjectRangeCheck u_check(bot, sPlayerbotAIConfig->sightDistance * 2); + Acore::AnyUnitInObjectRangeCheck u_check(bot, sPlayerbotAIConfig.sightDistance * 2); Acore::UnitListSearcher searcher(bot, targets, u_check); - Cell::VisitObjects(bot, searcher, sPlayerbotAIConfig->sightDistance); + Cell::VisitObjects(bot, searcher, sPlayerbotAIConfig.sightDistance); for (Unit* unit : targets) { @@ -37,7 +38,9 @@ bool TravelAction::Execute(Event event) if (!newTarget->IsAlive()) continue; - if (newTarget->GetEntry() == target->getDestination()->getEntry()) + const int64_t newTargetEntry = newTarget->GetEntry(); + + if (newTargetEntry == target->getDestination()->getEntry()) continue; if (newTarget->IsInCombat()) @@ -60,7 +63,7 @@ bool TravelAction::isUseful() (!AI_VALUE(GuidPosition, "rpg target") || !AI_VALUE(ObjectGuid, "pull target")); } -bool MoveToDarkPortalAction::Execute(Event event) +bool MoveToDarkPortalAction::Execute(Event) { if (bot->GetGroup()) if (bot->GetGroup()->GetLeaderGUID() != bot->GetGUID() && @@ -77,7 +80,7 @@ bool MoveToDarkPortalAction::Execute(Event event) if (bot->GetTeamId() == TEAM_ALLIANCE) { Quest const* quest = sObjectMgr->GetQuestTemplate(10119); - CreatureData const* creatureData = sRandomPlayerbotMgr->GetCreatureDataByEntry(16841); + CreatureData const* creatureData = sRandomPlayerbotMgr.GetCreatureDataByEntry(16841); if (quest && creatureData) { auto creatureBounds = @@ -89,7 +92,7 @@ bool MoveToDarkPortalAction::Execute(Event event) else { Quest const* quest = sObjectMgr->GetQuestTemplate(9407); - CreatureData const* creatureData = sRandomPlayerbotMgr->GetCreatureDataByEntry(19254); + CreatureData const* creatureData = sRandomPlayerbotMgr.GetCreatureDataByEntry(19254); if (quest && creatureData) { auto creatureBounds = @@ -111,7 +114,7 @@ bool MoveToDarkPortalAction::Execute(Event event) bool MoveToDarkPortalAction::isUseful() { return bot->GetLevel() > 54; } -bool DarkPortalAzerothAction::Execute(Event event) +bool DarkPortalAzerothAction::Execute(Event) { if (bot->GetLevel() > 57) { @@ -126,14 +129,14 @@ bool DarkPortalAzerothAction::Execute(Event event) bool DarkPortalAzerothAction::isUseful() { return bot->GetLevel() > 57; } -bool MoveFromDarkPortalAction::Execute(Event event) +bool MoveFromDarkPortalAction::Execute(Event) { RESET_AI_VALUE(GuidPosition, "rpg target"); if (bot->GetTeamId() == TEAM_ALLIANCE) + { return MoveTo(530, -319.261f, 1027.213, 54.172638f, false, true); - else - return MoveTo(530, -180.444f, 1027.947, 54.181538f, false, true); + } - return false; + return MoveTo(530, -180.444f, 1027.947, 54.181538f, false, true); } diff --git a/src/Ai/Base/Actions/UnlockItemAction.cpp b/src/Ai/Base/Actions/UnlockItemAction.cpp index 367a4fcbfb..0e869e72c6 100644 --- a/src/Ai/Base/Actions/UnlockItemAction.cpp +++ b/src/Ai/Base/Actions/UnlockItemAction.cpp @@ -1,38 +1,39 @@ #include "UnlockItemAction.h" #include "PlayerbotAI.h" #include "ItemTemplate.h" -#include "WorldPacket.h" #include "Player.h" #include "ObjectMgr.h" #include "SpellInfo.h" -#define PICK_LOCK_SPELL_ID 1804 +inline constexpr uint32_t PICK_LOCK_SPELL_ID = 1804; -bool UnlockItemAction::Execute(Event event) +bool UnlockItemAction::Execute(Event) { - bool foundLockedItem = false; + Item* const item = botAI->FindLockedItem(); - Item* item = botAI->FindLockedItem(); - if (item) + if (item == nullptr) { - UnlockItem(item); - foundLockedItem = true; + return false; } - return foundLockedItem; + this->UnlockItem(item); + + return true; } void UnlockItemAction::UnlockItem(Item* item) { // Use CastSpell to unlock the item - if (botAI->CastSpell(PICK_LOCK_SPELL_ID, bot, item)) + const bool unlocked = this->botAI->CastSpell(PICK_LOCK_SPELL_ID, bot, item); + + if (unlocked) { std::ostringstream out; out << "Used Pick Lock on: " << item->GetTemplate()->Name1; - botAI->TellMaster(out.str()); - } - else - { - botAI->TellError("Failed to cast Pick Lock."); + this->botAI->TellMaster(out.str()); + + return; } + + this->botAI->TellError("Failed to cast Pick Lock."); } diff --git a/src/Ai/Base/Actions/UnlockTradedItemAction.cpp b/src/Ai/Base/Actions/UnlockTradedItemAction.cpp index 047cd2e201..fbc527c7a5 100644 --- a/src/Ai/Base/Actions/UnlockTradedItemAction.cpp +++ b/src/Ai/Base/Actions/UnlockTradedItemAction.cpp @@ -1,11 +1,11 @@ #include "UnlockTradedItemAction.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" #include "TradeData.h" #include "SpellInfo.h" -#define PICK_LOCK_SPELL_ID 1804 +inline constexpr uint32_t PICK_LOCK_SPELL_ID = 1804; -bool UnlockTradedItemAction::Execute(Event event) +bool UnlockTradedItemAction::Execute(Event) { Player* trader = bot->GetTrader(); if (!trader) diff --git a/src/Ai/Base/Actions/UseItemAction.cpp b/src/Ai/Base/Actions/UseItemAction.cpp index bfb86ef0bd..ba828d962e 100644 --- a/src/Ai/Base/Actions/UseItemAction.cpp +++ b/src/Ai/Base/Actions/UseItemAction.cpp @@ -69,7 +69,6 @@ bool UseItemAction::UseItem(Item* item, ObjectGuid goGuid, Item* itemTarget, Uni uint8 bagIndex = item->GetBagSlot(); uint8 slot = item->GetSlot(); - uint8 spell_index = 0; uint8 cast_count = 1; ObjectGuid item_guid = item->GetGUID(); uint32 glyphIndex = 0; @@ -187,7 +186,7 @@ bool UseItemAction::UseItem(Item* item, ObjectGuid goGuid, Item* itemTarget, Uni if (bot->isMoving()) { bot->StopMoving(); - botAI->SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); return false; } @@ -229,7 +228,7 @@ bool UseItemAction::UseItem(Item* item, ObjectGuid goGuid, Item* itemTarget, Uni out << " on " << chat->FormatItem(itemForSpell->GetTemplate()); } uint32 castTime = spellInfo->CalcCastTime(); - botAI->SetNextCheckDelay(castTime + sPlayerbotAIConfig->reactDelay); + botAI->SetNextCheckDelay(castTime + sPlayerbotAIConfig.reactDelay); } break; @@ -307,7 +306,7 @@ bool UseItemAction::UseItem(Item* item, ObjectGuid goGuid, Item* itemTarget, Uni if (!spellId) return false; - // botAI->SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + // botAI->SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); botAI->TellMasterNoFacing(out.str()); bot->GetSession()->HandleUseItemOpcode(packet); return true; @@ -423,7 +422,7 @@ bool UseRandomRecipe::isUseful() bool UseRandomRecipe::isPossible() { return AI_VALUE2(uint32, "item count", "recipe") > 0; } -bool UseRandomRecipe::Execute(Event event) +bool UseRandomRecipe::Execute(Event) { std::vector recipes = AI_VALUE2(std::vector, "inventory items", "recipe"); @@ -452,7 +451,7 @@ bool UseRandomQuestItem::isUseful() bool UseRandomQuestItem::isPossible() { return AI_VALUE2(uint32, "item count", "quest") > 0; } -bool UseRandomQuestItem::Execute(Event event) +bool UseRandomQuestItem::Execute(Event) { Unit* unitTarget = nullptr; ObjectGuid goTarget; @@ -486,7 +485,7 @@ bool UseRandomQuestItem::Execute(Event event) bool used = UseItem(item, goTarget, nullptr, unitTarget); if (used) - botAI->SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + botAI->SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); return used; } diff --git a/src/Ai/Base/Actions/UseMeetingStoneAction.cpp b/src/Ai/Base/Actions/UseMeetingStoneAction.cpp index ec6a060ab1..a676b0cf28 100644 --- a/src/Ai/Base/Actions/UseMeetingStoneAction.cpp +++ b/src/Ai/Base/Actions/UseMeetingStoneAction.cpp @@ -5,14 +5,15 @@ #include "UseMeetingStoneAction.h" -#include "CellImpl.h" #include "Event.h" #include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "NearestGameObjects.h" #include "PlayerbotAIConfig.h" #include "Playerbots.h" #include "PositionValue.h" +// Required because of a poor implementation by AC +#include "GridNotifiersImpl.h" +#include "CellImpl.h" bool UseMeetingStoneAction::Execute(Event event) { @@ -55,13 +56,13 @@ bool UseMeetingStoneAction::Execute(Event event) return Teleport(master, bot, false); } -bool SummonAction::Execute(Event event) +bool SummonAction::Execute(Event) { Player* master = GetMaster(); if (!master) return false; - if (Pet* pet = bot->GetPet()) + if (bot->GetPet() != nullptr) { botAI->PetFollow(); } @@ -91,9 +92,9 @@ bool SummonAction::Execute(Event event) bool SummonAction::SummonUsingGos(Player* summoner, Player* player, bool preserveAuras) { std::list targets; - AnyGameObjectInObjectRangeCheck u_check(summoner, sPlayerbotAIConfig->sightDistance); + AnyGameObjectInObjectRangeCheck u_check(summoner, sPlayerbotAIConfig.sightDistance); Acore::GameObjectListSearcher searcher(summoner, targets, u_check); - Cell::VisitObjects(summoner, searcher, sPlayerbotAIConfig->sightDistance); + Cell::VisitObjects(summoner, searcher, sPlayerbotAIConfig.sightDistance); for (GameObject* go : targets) { @@ -107,13 +108,13 @@ bool SummonAction::SummonUsingGos(Player* summoner, Player* player, bool preserv bool SummonAction::SummonUsingNpcs(Player* summoner, Player* player, bool preserveAuras) { - if (!sPlayerbotAIConfig->summonAtInnkeepersEnabled) + if (!sPlayerbotAIConfig.summonAtInnkeepersEnabled) return false; std::list targets; - Acore::AnyUnitInObjectRangeCheck u_check(summoner, sPlayerbotAIConfig->sightDistance); + Acore::AnyUnitInObjectRangeCheck u_check(summoner, sPlayerbotAIConfig.sightDistance); Acore::UnitListSearcher searcher(summoner, targets, u_check); - Cell::VisitObjects(summoner, searcher, sPlayerbotAIConfig->sightDistance); + Cell::VisitObjects(summoner, searcher, sPlayerbotAIConfig.sightDistance); for (Unit* unit : targets) { @@ -165,38 +166,37 @@ bool SummonAction::Teleport(Player* summoner, Player* player, bool preserveAuras for (float angle = followAngle - M_PI; angle <= followAngle + M_PI; angle += M_PI / 4) { uint32 mapId = summoner->GetMapId(); - float x = summoner->GetPositionX() + cos(angle) * sPlayerbotAIConfig->followDistance; - float y = summoner->GetPositionY() + sin(angle) * sPlayerbotAIConfig->followDistance; + float x = summoner->GetPositionX() + cos(angle) * sPlayerbotAIConfig.followDistance; + float y = summoner->GetPositionY() + sin(angle) * sPlayerbotAIConfig.followDistance; float z = summoner->GetPositionZ(); if (summoner->IsWithinLOS(x, y, z)) { - if (sPlayerbotAIConfig - ->botRepairWhenSummon) // .conf option to repair bot gear when summoned 0 = off, 1 = on + if (sPlayerbotAIConfig.botRepairWhenSummon) // .conf option to repair bot gear when summoned 0 = off, 1 = on bot->DurabilityRepairAll(false, 1.0f, false); - if (summoner->IsInCombat() && !sPlayerbotAIConfig->allowSummonInCombat) + if (summoner->IsInCombat() && !sPlayerbotAIConfig.allowSummonInCombat) { botAI->TellError("You cannot summon me while you're in combat"); return false; } - if (!summoner->IsAlive() && !sPlayerbotAIConfig->allowSummonWhenMasterIsDead) + if (!summoner->IsAlive() && !sPlayerbotAIConfig.allowSummonWhenMasterIsDead) { botAI->TellError("You cannot summon me while you're dead"); return false; } if (bot->isDead() && !bot->HasPlayerFlag(PLAYER_FLAGS_GHOST) && - !sPlayerbotAIConfig->allowSummonWhenBotIsDead) + !sPlayerbotAIConfig.allowSummonWhenBotIsDead) { botAI->TellError("You cannot summon me while I'm dead, you need to release my spirit first"); return false; } bool revive = - sPlayerbotAIConfig->reviveBotWhenSummoned == 2 || - (sPlayerbotAIConfig->reviveBotWhenSummoned == 1 && !summoner->IsInCombat() && summoner->IsAlive()); + sPlayerbotAIConfig.reviveBotWhenSummoned == 2 || + (sPlayerbotAIConfig.reviveBotWhenSummoned == 1 && !summoner->IsInCombat() && summoner->IsAlive()); if (bot->isDead() && revive) { diff --git a/src/Ai/Base/Actions/VehicleActions.cpp b/src/Ai/Base/Actions/VehicleActions.cpp index ee1c6e2dd8..f5a43f899c 100644 --- a/src/Ai/Base/Actions/VehicleActions.cpp +++ b/src/Ai/Base/Actions/VehicleActions.cpp @@ -74,7 +74,7 @@ bool EnterVehicleAction::Execute(Event event) bool EnterVehicleAction::EnterVehicle(Unit* vehicleBase, bool moveIfFar) { - float dist = sServerFacade->GetDistance2d(bot, vehicleBase); + float dist = ServerFacade::instance().GetDistance2d(bot, vehicleBase); if (dist > 40.0f) return false; @@ -95,7 +95,7 @@ bool EnterVehicleAction::EnterVehicle(Unit* vehicleBase, bool moveIfFar) return true; } -bool LeaveVehicleAction::Execute(Event event) +bool LeaveVehicleAction::Execute(Event) { Vehicle* myVehicle = bot->GetVehicle(); if (!myVehicle) diff --git a/src/Ai/Base/Actions/WhoAction.cpp b/src/Ai/Base/Actions/WhoAction.cpp index edafdfcb27..1cc325038f 100644 --- a/src/Ai/Base/Actions/WhoAction.cpp +++ b/src/Ai/Base/Actions/WhoAction.cpp @@ -33,7 +33,7 @@ bool WhoAction::Execute(Event event) { out << QuerySkill(text); - if (sRandomPlayerbotMgr->IsRandomBot(bot)) + if (sRandomPlayerbotMgr.IsRandomBot(bot)) out << QueryTrade(text); } else @@ -74,7 +74,7 @@ std::string const WhoAction::QueryTrade(std::string const text) for (Item* sell : items) { int32 sellPrice = - sell->GetTemplate()->SellPrice * sRandomPlayerbotMgr->GetSellMultiplier(bot) * sell->GetCount(); + sell->GetTemplate()->SellPrice * sRandomPlayerbotMgr.GetSellMultiplier(bot) * sell->GetCount(); if (!sellPrice) continue; @@ -108,7 +108,7 @@ std::string const WhoAction::QuerySkill(std::string const text) return out.str(); } -std::string const WhoAction::QuerySpec(std::string const text) +std::string const WhoAction::QuerySpec(std::string) { std::ostringstream out; diff --git a/src/Ai/Base/Actions/WipeAction.cpp b/src/Ai/Base/Actions/WipeAction.cpp index bbd1997d6c..7101b9f2c0 100644 --- a/src/Ai/Base/Actions/WipeAction.cpp +++ b/src/Ai/Base/Actions/WipeAction.cpp @@ -8,11 +8,15 @@ bool WipeAction::Execute(Event event) { - Player* master = event.getOwner(); + const Player* const owner = event.getOwner(); + const Player* const master = this->botAI->GetMaster(); - if (botAI->GetMaster()->GetGUID() != event.getOwner()->GetGUID()) + if (owner != nullptr && master != nullptr && master->GetGUID() != owner->GetGUID()) + { return false; + } + + this->bot->Kill(this->bot, this->bot); - bot->Kill(bot, bot); return true; } diff --git a/src/Ai/Base/Actions/WorldBuffAction.cpp b/src/Ai/Base/Actions/WorldBuffAction.cpp index 3cd770e4d0..b2bf4e096f 100644 --- a/src/Ai/Base/Actions/WorldBuffAction.cpp +++ b/src/Ai/Base/Actions/WorldBuffAction.cpp @@ -25,7 +25,7 @@ std::vector WorldBuffAction::NeedWorldBuffs(Unit* unit) { std::vector retVec; - if (sPlayerbotAIConfig->worldBuffs.empty()) + if (sPlayerbotAIConfig.worldBuffs.empty()) return retVec; FactionTemplateEntry const* humanFaction = sFactionTemplateStore.LookupEntry(1); @@ -70,7 +70,7 @@ std::vector WorldBuffAction::NeedWorldBuffs(Unit* unit) // If tank, effectiveSpec remains unchanged } - for (auto const& wb : sPlayerbotAIConfig->worldBuffs) + for (auto const& wb : sPlayerbotAIConfig.worldBuffs) { // Faction check if (wb.factionId != 0 && wb.factionId != factionId) diff --git a/src/Ai/Base/Actions/WtsAction.cpp b/src/Ai/Base/Actions/WtsAction.cpp index a3c77c27f9..950ab7d05f 100644 --- a/src/Ai/Base/Actions/WtsAction.cpp +++ b/src/Ai/Base/Actions/WtsAction.cpp @@ -20,7 +20,7 @@ bool WtsAction::Execute(Event event) std::ostringstream out; std::string const text = event.getParam(); - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sRandomPlayerbotMgr.IsRandomBot(bot)) return false; std::string const link = event.getParam(); @@ -42,7 +42,7 @@ bool WtsAction::Execute(Event event) if (usage == ITEM_USAGE_NONE) continue; - int32 buyPrice = proto->BuyPrice * sRandomPlayerbotMgr->GetBuyMultiplier(bot); + int32 buyPrice = proto->BuyPrice * sRandomPlayerbotMgr.GetBuyMultiplier(bot); if (!buyPrice) continue; diff --git a/src/Ai/Base/Actions/XpGainAction.cpp b/src/Ai/Base/Actions/XpGainAction.cpp index 4048ce3af8..fba57180f2 100644 --- a/src/Ai/Base/Actions/XpGainAction.cpp +++ b/src/Ai/Base/Actions/XpGainAction.cpp @@ -40,14 +40,14 @@ bool XpGainAction::Execute(Event event) } // randomBotXPRate is now implemented in OnPlayerGiveXP script - // if (!sRandomPlayerbotMgr->IsRandomBot(bot) || sPlayerbotAIConfig->randomBotXPRate == 1) + // if (!sRandomPlayerbotMgr.IsRandomBot(bot) || sPlayerbotAIConfig.randomBotXPRate == 1) // return true; // Unit* victim = nullptr; // if (guid) // victim = botAI->GetUnit(guid); - // xpgain = xpgain * (sPlayerbotAIConfig->randomBotXPRate - 1); + // xpgain = xpgain * (sPlayerbotAIConfig.randomBotXPRate - 1); // GiveXP(xpgain, victim); return true; diff --git a/src/Ai/Base/SharedValueContext.h b/src/Ai/Base/SharedValueContext.h index 23b8266bdd..0ac35ab1b2 100644 --- a/src/Ai/Base/SharedValueContext.h +++ b/src/Ai/Base/SharedValueContext.h @@ -8,43 +8,18 @@ #include "LootValues.h" #include "NamedObjectContext.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" #include "PvpValues.h" #include "QuestValues.h" -class PlayerbotAI; - class SharedValueContext : public NamedObjectContext { public: - SharedValueContext() : NamedObjectContext(true) - { - creators["bg masters"] = &SharedValueContext::bg_masters; - creators["drop map"] = &SharedValueContext::drop_map; - creators["item drop list"] = &SharedValueContext::item_drop_list; - creators["entry loot list"] = &SharedValueContext::entry_loot_list; - - creators["entry quest relation"] = &SharedValueContext::entry_quest_relation; - creators["quest guidp map"] = &SharedValueContext::quest_guidp_map; - creators["quest givers"] = &SharedValueContext::quest_givers; - } - -private: - static UntypedValue* bg_masters(PlayerbotAI* botAI) { return new BgMastersValue(botAI); } - static UntypedValue* drop_map(PlayerbotAI* botAI) { return new DropMapValue(botAI); } - static UntypedValue* item_drop_list(PlayerbotAI* botAI) { return new ItemDropListValue(botAI); } - static UntypedValue* entry_loot_list(PlayerbotAI* botAI) { return new EntryLootListValue(botAI); } - - static UntypedValue* entry_quest_relation(PlayerbotAI* botAI) { return new EntryQuestRelationMapValue(botAI); } - static UntypedValue* quest_guidp_map(PlayerbotAI* botAI) { return new QuestGuidpMapValue(botAI); } - static UntypedValue* quest_givers(PlayerbotAI* botAI) { return new QuestGiversValue(botAI); } - - // Global acess functions -public: - static SharedValueContext* instance() + static SharedValueContext& instance() { static SharedValueContext instance; - return &instance; + + return instance; } template @@ -74,6 +49,36 @@ class SharedValueContext : public NamedObjectContext out << param; return getGlobalValue(name, out.str()); } + +private: + SharedValueContext() : NamedObjectContext(true) + { + creators["bg masters"] = &SharedValueContext::bg_masters; + creators["drop map"] = &SharedValueContext::drop_map; + creators["item drop list"] = &SharedValueContext::item_drop_list; + creators["entry loot list"] = &SharedValueContext::entry_loot_list; + + creators["entry quest relation"] = &SharedValueContext::entry_quest_relation; + creators["quest guidp map"] = &SharedValueContext::quest_guidp_map; + creators["quest givers"] = &SharedValueContext::quest_givers; + } + ~SharedValueContext() = default; + + SharedValueContext(const SharedValueContext&) = delete; + SharedValueContext& operator=(const SharedValueContext&) = delete; + + SharedValueContext(SharedValueContext&&) = delete; + SharedValueContext& operator=(SharedValueContext&&) = delete; + + static UntypedValue* bg_masters(PlayerbotAI* botAI) { return new BgMastersValue(botAI); } + static UntypedValue* drop_map(PlayerbotAI* botAI) { return new DropMapValue(botAI); } + static UntypedValue* item_drop_list(PlayerbotAI* botAI) { return new ItemDropListValue(botAI); } + static UntypedValue* entry_loot_list(PlayerbotAI* botAI) { return new EntryLootListValue(botAI); } + + static UntypedValue* entry_quest_relation(PlayerbotAI* botAI) { return new EntryQuestRelationMapValue(botAI); } + static UntypedValue* quest_guidp_map(PlayerbotAI* botAI) { return new QuestGuidpMapValue(botAI); } + static UntypedValue* quest_givers(PlayerbotAI* botAI) { return new QuestGiversValue(botAI); } + }; #define sSharedValueContext SharedValueContext::instance() diff --git a/src/Ai/Base/Strategy/CastTimeStrategy.cpp b/src/Ai/Base/Strategy/CastTimeStrategy.cpp index 042d1c9e41..7c70923d40 100644 --- a/src/Ai/Base/Strategy/CastTimeStrategy.cpp +++ b/src/Ai/Base/Strategy/CastTimeStrategy.cpp @@ -16,7 +16,7 @@ float CastTimeMultiplier::GetValue(Action* action) if (!action->GetTarget() || action->GetTarget() != AI_VALUE(Unit*, "current target")) return 1.0f; - if (/*targetHealth < sPlayerbotAIConfig->criticalHealth && */ dynamic_cast(action)) + if (/*targetHealth < sPlayerbotAIConfig.criticalHealth && */ dynamic_cast(action)) { CastSpellAction* spellAction = dynamic_cast(action); uint32 spellId = AI_VALUE2(uint32, "spell id", spellAction->getSpell()); diff --git a/src/Ai/Base/Strategy/ChatCommandHandlerStrategy.cpp b/src/Ai/Base/Strategy/ChatCommandHandlerStrategy.cpp index 0a81686a9d..7439494aff 100644 --- a/src/Ai/Base/Strategy/ChatCommandHandlerStrategy.cpp +++ b/src/Ai/Base/Strategy/ChatCommandHandlerStrategy.cpp @@ -5,15 +5,13 @@ #include "ChatCommandHandlerStrategy.h" -#include "Playerbots.h" - class ChatCommandActionNodeFactoryInternal : public NamedObjectFactory { public: ChatCommandActionNodeFactoryInternal() { creators["tank attack chat shortcut"] = &tank_attack_chat_shortcut; } private: - static ActionNode* tank_attack_chat_shortcut(PlayerbotAI* botAI) + static ActionNode* tank_attack_chat_shortcut(PlayerbotAI*) { return new ActionNode("tank attack chat shortcut", /*P*/ {}, diff --git a/src/Ai/Base/Strategy/CombatStrategy.cpp b/src/Ai/Base/Strategy/CombatStrategy.cpp index 75700e9a6d..c8a066f48d 100644 --- a/src/Ai/Base/Strategy/CombatStrategy.cpp +++ b/src/Ai/Base/Strategy/CombatStrategy.cpp @@ -5,7 +5,6 @@ #include "CombatStrategy.h" -#include "Playerbots.h" #include "Strategy.h" void CombatStrategy::InitTriggers(std::vector& triggers) @@ -65,11 +64,11 @@ std::vector AvoidAoeStrategy::getDefaultActions() }; } -void AvoidAoeStrategy::InitTriggers(std::vector& triggers) +void AvoidAoeStrategy::InitTriggers(std::vector&) { } -void AvoidAoeStrategy::InitMultipliers(std::vector& multipliers) +void AvoidAoeStrategy::InitMultipliers(std::vector&) { } @@ -82,7 +81,7 @@ std::vector TankFaceStrategy::getDefaultActions() }; } -void TankFaceStrategy::InitTriggers(std::vector& triggers) +void TankFaceStrategy::InitTriggers(std::vector&) { } diff --git a/src/Ai/Base/Strategy/ConserveManaStrategy.cpp b/src/Ai/Base/Strategy/ConserveManaStrategy.cpp index adc3cec884..9e646f118b 100644 --- a/src/Ai/Base/Strategy/ConserveManaStrategy.cpp +++ b/src/Ai/Base/Strategy/ConserveManaStrategy.cpp @@ -19,9 +19,9 @@ // uint8 targetHealth = AI_VALUE2(uint8, "health", "current target"); // uint8 mana = AI_VALUE2(uint8, "mana", "self target"); // bool hasMana = AI_VALUE2(bool, "has mana", "self target"); -// bool mediumMana = hasMana && mana < sPlayerbotAIConfig->mediumMana; +// bool mediumMana = hasMana && mana < sPlayerbotAIConfig.mediumMana; -// if (health < sPlayerbotAIConfig->lowHealth) +// if (health < sPlayerbotAIConfig.lowHealth) // return 1.0f; // Unit* target = AI_VALUE(Unit*, "current target"); @@ -92,7 +92,7 @@ float HealerAutoSaveManaMultiplier::GetValue(Action* action) { uint8 mana = bot->GetPowerPct(Powers::POWER_MANA); - if (mana > sPlayerbotAIConfig->saveManaThreshold) + if (mana > sPlayerbotAIConfig.saveManaThreshold) return 1.0f; CastHealingSpellAction* healingAction = dynamic_cast(action); @@ -110,16 +110,16 @@ float HealerAutoSaveManaMultiplier::GetValue(Action* action) if (isTank) { estAmount /= 1.5; // tanks have more health - if (health >= sPlayerbotAIConfig->mediumHealth && + if (health >= sPlayerbotAIConfig.mediumHealth && (lossAmount < estAmount || manaEfficiency <= HealingManaEfficiency::MEDIUM)) return 0.0f; - if (health >= sPlayerbotAIConfig->lowHealth && + if (health >= sPlayerbotAIConfig.lowHealth && (lossAmount < estAmount || manaEfficiency <= HealingManaEfficiency::LOW)) return 0.0f; } else { - if (health >= sPlayerbotAIConfig->mediumHealth && + if (health >= sPlayerbotAIConfig.mediumHealth && (lossAmount < estAmount || manaEfficiency <= HealingManaEfficiency::MEDIUM)) return 0.0f; if (lossAmount < estAmount || manaEfficiency <= HealingManaEfficiency::LOW) diff --git a/src/Ai/Base/Strategy/DuelStrategy.cpp b/src/Ai/Base/Strategy/DuelStrategy.cpp index 4c08397e6b..6c5ff2618c 100644 --- a/src/Ai/Base/Strategy/DuelStrategy.cpp +++ b/src/Ai/Base/Strategy/DuelStrategy.cpp @@ -5,8 +5,6 @@ #include "DuelStrategy.h" -#include "Playerbots.h" - void DuelStrategy::InitTriggers(std::vector& triggers) { PassTroughStrategy::InitTriggers(triggers); @@ -19,6 +17,6 @@ void DuelStrategy::InitTriggers(std::vector& triggers) DuelStrategy::DuelStrategy(PlayerbotAI* botAI) : PassTroughStrategy(botAI) {} -void StartDuelStrategy::InitTriggers(std::vector& triggers) {} +void StartDuelStrategy::InitTriggers(std::vector&) {} StartDuelStrategy::StartDuelStrategy(PlayerbotAI* botAI) : Strategy(botAI) {} diff --git a/src/Ai/Base/Strategy/EmoteStrategy.cpp b/src/Ai/Base/Strategy/EmoteStrategy.cpp index 9419e0c386..f2e002e8d7 100644 --- a/src/Ai/Base/Strategy/EmoteStrategy.cpp +++ b/src/Ai/Base/Strategy/EmoteStrategy.cpp @@ -9,7 +9,7 @@ void EmoteStrategy::InitTriggers(std::vector& triggers) { - if (sPlayerbotAIConfig->randomBotEmote) + if (sPlayerbotAIConfig.randomBotEmote) { triggers.push_back(new TriggerNode("often", { NextAction("talk", 1.0f) })); triggers.push_back(new TriggerNode("seldom", { NextAction("emote", 1.0f) })); @@ -19,7 +19,7 @@ void EmoteStrategy::InitTriggers(std::vector& triggers) new TriggerNode("receive emote", { NextAction("emote", 10.0f) })); } - if (sPlayerbotAIConfig->randomBotTalk) + if (sPlayerbotAIConfig.randomBotTalk) { triggers.push_back(new TriggerNode( "often", @@ -27,7 +27,7 @@ void EmoteStrategy::InitTriggers(std::vector& triggers) NextAction("suggest trade", 3.0f) })); } - if (sPlayerbotAIConfig->enableGreet) + if (sPlayerbotAIConfig.enableGreet) triggers.push_back( new TriggerNode("new player nearby", { NextAction("greet", 1.0f) })); diff --git a/src/Ai/Base/Strategy/FollowMasterStrategy.cpp b/src/Ai/Base/Strategy/FollowMasterStrategy.cpp index 0308b113f9..bd87b4c28c 100644 --- a/src/Ai/Base/Strategy/FollowMasterStrategy.cpp +++ b/src/Ai/Base/Strategy/FollowMasterStrategy.cpp @@ -5,8 +5,6 @@ #include "FollowMasterStrategy.h" -#include "Playerbots.h" - std::vector FollowMasterStrategy::getDefaultActions() { return { @@ -14,6 +12,6 @@ std::vector FollowMasterStrategy::getDefaultActions() }; } -void FollowMasterStrategy::InitTriggers(std::vector& triggers) +void FollowMasterStrategy::InitTriggers(std::vector&) { } diff --git a/src/Ai/Base/Strategy/GuardStrategy.cpp b/src/Ai/Base/Strategy/GuardStrategy.cpp index 9a396ac57f..70635d65cb 100644 --- a/src/Ai/Base/Strategy/GuardStrategy.cpp +++ b/src/Ai/Base/Strategy/GuardStrategy.cpp @@ -5,8 +5,6 @@ #include "GuardStrategy.h" -#include "Playerbots.h" - std::vector GuardStrategy::getDefaultActions() { return { @@ -14,4 +12,4 @@ std::vector GuardStrategy::getDefaultActions() }; } -void GuardStrategy::InitTriggers(std::vector& triggers) {} +void GuardStrategy::InitTriggers(std::vector&) {} diff --git a/src/Ai/Base/Strategy/NonCombatStrategy.cpp b/src/Ai/Base/Strategy/NonCombatStrategy.cpp index 6b8f76ac95..c37c558f42 100644 --- a/src/Ai/Base/Strategy/NonCombatStrategy.cpp +++ b/src/Ai/Base/Strategy/NonCombatStrategy.cpp @@ -5,8 +5,6 @@ #include "NonCombatStrategy.h" -#include "Playerbots.h" - void NonCombatStrategy::InitTriggers(std::vector& triggers) { triggers.push_back(new TriggerNode("random", { NextAction("clean quest log", 1.0f) })); @@ -19,7 +17,7 @@ void CollisionStrategy::InitTriggers(std::vector& triggers) new TriggerNode("collision", { NextAction("move out of collision", 2.0f) })); } -void MountStrategy::InitTriggers(std::vector& triggers) +void MountStrategy::InitTriggers(std::vector&) { } diff --git a/src/Ai/Base/Strategy/RTSCStrategy.cpp b/src/Ai/Base/Strategy/RTSCStrategy.cpp index 2c64092e3c..daf8bfc579 100644 --- a/src/Ai/Base/Strategy/RTSCStrategy.cpp +++ b/src/Ai/Base/Strategy/RTSCStrategy.cpp @@ -5,8 +5,6 @@ #include "RTSCStrategy.h" -#include "Playerbots.h" - RTSCStrategy::RTSCStrategy(PlayerbotAI* botAI) : Strategy(botAI) {} -void RTSCStrategy::InitTriggers(std::vector& triggers) {} +void RTSCStrategy::InitTriggers(std::vector&) {} diff --git a/src/Ai/Base/Strategy/RacialsStrategy.cpp b/src/Ai/Base/Strategy/RacialsStrategy.cpp index f4f270b1b0..68fa9af4cf 100644 --- a/src/Ai/Base/Strategy/RacialsStrategy.cpp +++ b/src/Ai/Base/Strategy/RacialsStrategy.cpp @@ -5,15 +5,13 @@ #include "RacialsStrategy.h" -#include "Playerbots.h" - class RacialsStrategyActionNodeFactory : public NamedObjectFactory { public: RacialsStrategyActionNodeFactory() { creators["lifeblood"] = &lifeblood; } private: - static ActionNode* lifeblood(PlayerbotAI* botAI) + static ActionNode* lifeblood(PlayerbotAI*) { return new ActionNode("lifeblood", /*P*/ {}, diff --git a/src/Ai/Base/Strategy/UsePotionsStrategy.cpp b/src/Ai/Base/Strategy/UsePotionsStrategy.cpp index b0e0049269..f252c91ccb 100644 --- a/src/Ai/Base/Strategy/UsePotionsStrategy.cpp +++ b/src/Ai/Base/Strategy/UsePotionsStrategy.cpp @@ -5,15 +5,13 @@ #include "UsePotionsStrategy.h" -#include "Playerbots.h" - class UsePotionsStrategyActionNodeFactory : public NamedObjectFactory { public: UsePotionsStrategyActionNodeFactory() { creators["healthstone"] = &healthstone; } private: - static ActionNode* healthstone(PlayerbotAI* botAI) + static ActionNode* healthstone(PlayerbotAI*) { return new ActionNode("healthstone", /*P*/ {}, diff --git a/src/Ai/Base/Trigger/GenericTriggers.cpp b/src/Ai/Base/Trigger/GenericTriggers.cpp index 988413b2f3..35041970cd 100644 --- a/src/Ai/Base/Trigger/GenericTriggers.cpp +++ b/src/Ai/Base/Trigger/GenericTriggers.cpp @@ -7,9 +7,7 @@ #include -#include "BattlegroundWS.h" #include "CreatureAI.h" -#include "GameTime.h" #include "ItemVisitors.h" #include "LastSpellCastValue.h" #include "ObjectGuid.h" @@ -22,17 +20,18 @@ #include "Timer.h" #include "PlayerbotAI.h" #include "Player.h" +#include "Corpse.h" bool LowManaTrigger::IsActive() { return AI_VALUE2(bool, "has mana", "self target") && - AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig->lowMana; + AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig.lowMana; } bool MediumManaTrigger::IsActive() { return AI_VALUE2(bool, "has mana", "self target") && - AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig->mediumMana; + AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig.mediumMana; } bool NoPetTrigger::IsActive() @@ -72,7 +71,7 @@ bool PetAttackTrigger::IsActive() bool HighManaTrigger::IsActive() { - return AI_VALUE2(bool, "has mana", "self target") && AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig->highMana; + return AI_VALUE2(bool, "has mana", "self target") && AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig.highMana; } bool AlmostFullManaTrigger::IsActive() @@ -82,7 +81,7 @@ bool AlmostFullManaTrigger::IsActive() bool EnoughManaTrigger::IsActive() { - return AI_VALUE2(bool, "has mana", "self target") && AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig->highMana; + return AI_VALUE2(bool, "has mana", "self target") && AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig.highMana; } bool RageAvailable::IsActive() { return AI_VALUE2(uint8, "rage", "self target") >= amount; } @@ -110,9 +109,9 @@ bool HasAggroTrigger::IsActive() { return AI_VALUE2(bool, "has aggro", "current bool PanicTrigger::IsActive() { - return AI_VALUE2(uint8, "health", "self target") < sPlayerbotAIConfig->criticalHealth && + return AI_VALUE2(uint8, "health", "self target") < sPlayerbotAIConfig.criticalHealth && (!AI_VALUE2(bool, "has mana", "self target") || - AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig->lowMana); + AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig.lowMana); } bool OutNumberedTrigger::IsActive() @@ -165,7 +164,10 @@ bool BuffTrigger::IsActive() Aura* aura = botAI->GetAura(spell, target, checkIsOwner, checkDuration); if (!aura) return true; - if (beforeDuration && aura->GetDuration() < beforeDuration) + + const int64_t signedBeforeDuration = this->beforeDuration; + + if (beforeDuration && aura->GetDuration() < signedBeforeDuration) return true; return false; } @@ -248,7 +250,7 @@ bool AoeTrigger::IsActive() bool NoFoodTrigger::IsActive() { - bool isRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot); + bool isRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot); if (isRandomBot && botAI->HasCheat(BotCheatMask::food)) return false; @@ -257,7 +259,7 @@ bool NoFoodTrigger::IsActive() bool NoDrinkTrigger::IsActive() { - bool isRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot); + bool isRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot); if (isRandomBot && botAI->HasCheat(BotCheatMask::food)) return false; @@ -319,11 +321,11 @@ RandomTrigger::RandomTrigger(PlayerbotAI* botAI, std::string const name, int32 p bool RandomTrigger::IsActive() { - if (getMSTime() - lastCheck < sPlayerbotAIConfig->repeatDelay) + if (getMSTime() - lastCheck < sPlayerbotAIConfig.repeatDelay) return false; lastCheck = getMSTime(); - int32 k = (int32)(probability / sPlayerbotAIConfig->randomChangeMultiplier); + int32 k = (int32)(probability / sPlayerbotAIConfig.randomChangeMultiplier); if (k < 1) k = 1; return (rand() % k) == 0; @@ -381,10 +383,10 @@ bool GenericBoostTrigger::IsActive() bool HealerShouldAttackTrigger::IsActive() { // nobody can help me - if (botAI->GetNearGroupMemberCount(sPlayerbotAIConfig->sightDistance) <= 1) + if (botAI->GetNearGroupMemberCount(sPlayerbotAIConfig.sightDistance) <= 1) return true; - if (AI_VALUE2(uint8, "health", "party member to heal") < sPlayerbotAIConfig->almostFullHealth) + if (AI_VALUE2(uint8, "health", "party member to heal") < sPlayerbotAIConfig.almostFullHealth) return false; // special check for resto druid (dont remove tree of life frequently) @@ -401,9 +403,9 @@ bool HealerShouldAttackTrigger::IsActive() if (balance <= 50) manaThreshold = 85; else if (balance <= 100) - manaThreshold = sPlayerbotAIConfig->highMana; + manaThreshold = sPlayerbotAIConfig.highMana; else - manaThreshold = sPlayerbotAIConfig->mediumMana; + manaThreshold = sPlayerbotAIConfig.mediumMana; if (AI_VALUE2(bool, "has mana", "self target") && AI_VALUE2(uint8, "mana", "self target") < manaThreshold) return false; @@ -411,7 +413,12 @@ bool HealerShouldAttackTrigger::IsActive() return true; } -bool ItemCountTrigger::IsActive() { return AI_VALUE2(uint32, "item count", item) < count; } +bool ItemCountTrigger::IsActive() +{ + const int64_t aiValue = this->context->GetValue("item count", item)->Get(); + + return aiValue < this->count; +} bool InterruptSpellTrigger::IsActive() { @@ -632,7 +639,7 @@ bool ReturnToStayPositionTrigger::IsActive() if (stayPosition.isSet()) { const float distance = bot->GetDistance(stayPosition.x, stayPosition.y, stayPosition.z); - return distance > sPlayerbotAIConfig->followDistance; + return distance > sPlayerbotAIConfig.followDistance; } return false; diff --git a/src/Ai/Base/Trigger/GenericTriggers.h b/src/Ai/Base/Trigger/GenericTriggers.h index 943e80b742..7b884fbf08 100644 --- a/src/Ai/Base/Trigger/GenericTriggers.h +++ b/src/Ai/Base/Trigger/GenericTriggers.h @@ -216,7 +216,7 @@ class DeflectSpellTrigger : public SpellTrigger class AttackerCountTrigger : public Trigger { public: - AttackerCountTrigger(PlayerbotAI* botAI, int32 amount, float distance = sPlayerbotAIConfig->sightDistance) + AttackerCountTrigger(PlayerbotAI* botAI, int32 amount, float distance = sPlayerbotAIConfig.sightDistance) : Trigger(botAI), amount(amount), distance(distance) { } @@ -836,7 +836,7 @@ class StayTimeTrigger : public Trigger class SitTrigger : public StayTimeTrigger { public: - SitTrigger(PlayerbotAI* botAI) : StayTimeTrigger(botAI, sPlayerbotAIConfig->sitDelay, "sit") {} + SitTrigger(PlayerbotAI* botAI) : StayTimeTrigger(botAI, sPlayerbotAIConfig.sitDelay, "sit") {} }; class ReturnToStayPositionTrigger : public Trigger @@ -850,7 +850,7 @@ class ReturnToStayPositionTrigger : public Trigger class ReturnTrigger : public StayTimeTrigger { public: - ReturnTrigger(PlayerbotAI* botAI) : StayTimeTrigger(botAI, sPlayerbotAIConfig->returnDelay, "return") {} + ReturnTrigger(PlayerbotAI* botAI) : StayTimeTrigger(botAI, sPlayerbotAIConfig.returnDelay, "return") {} }; class GiveItemTrigger : public Trigger diff --git a/src/Ai/Base/Trigger/HealthTriggers.h b/src/Ai/Base/Trigger/HealthTriggers.h index d8149bffdb..0fbd403d72 100644 --- a/src/Ai/Base/Trigger/HealthTriggers.h +++ b/src/Ai/Base/Trigger/HealthTriggers.h @@ -48,7 +48,7 @@ class LowHealthTrigger : public HealthInRangeTrigger { public: LowHealthTrigger(PlayerbotAI* botAI, std::string const name = "low health", - float value = sPlayerbotAIConfig->lowHealth, float minValue = 0) + float value = sPlayerbotAIConfig.lowHealth, float minValue = 0) : HealthInRangeTrigger(botAI, name, value, minValue) { } @@ -60,7 +60,7 @@ class CriticalHealthTrigger : public LowHealthTrigger { public: CriticalHealthTrigger(PlayerbotAI* botAI) - : LowHealthTrigger(botAI, "critical health", sPlayerbotAIConfig->criticalHealth, 0) + : LowHealthTrigger(botAI, "critical health", sPlayerbotAIConfig.criticalHealth, 0) { } }; @@ -69,7 +69,7 @@ class MediumHealthTrigger : public LowHealthTrigger { public: MediumHealthTrigger(PlayerbotAI* botAI) - : LowHealthTrigger(botAI, "medium health", sPlayerbotAIConfig->mediumHealth, 0) + : LowHealthTrigger(botAI, "medium health", sPlayerbotAIConfig.mediumHealth, 0) { } }; @@ -78,8 +78,8 @@ class AlmostFullHealthTrigger : public LowHealthTrigger { public: AlmostFullHealthTrigger(PlayerbotAI* botAI) - : LowHealthTrigger(botAI, "almost full health", sPlayerbotAIConfig->almostFullHealth, - sPlayerbotAIConfig->mediumHealth) + : LowHealthTrigger(botAI, "almost full health", sPlayerbotAIConfig.almostFullHealth, + sPlayerbotAIConfig.mediumHealth) { } }; @@ -88,7 +88,7 @@ class PartyMemberLowHealthTrigger : public HealthInRangeTrigger { public: PartyMemberLowHealthTrigger(PlayerbotAI* botAI, std::string const name = "party member low health", - float value = sPlayerbotAIConfig->lowHealth, + float value = sPlayerbotAIConfig.lowHealth, float minValue = 0) : HealthInRangeTrigger(botAI, name, value, minValue) { @@ -101,7 +101,7 @@ class PartyMemberCriticalHealthTrigger : public PartyMemberLowHealthTrigger { public: PartyMemberCriticalHealthTrigger(PlayerbotAI* botAI) - : PartyMemberLowHealthTrigger(botAI, "party member critical health", sPlayerbotAIConfig->criticalHealth, 0) + : PartyMemberLowHealthTrigger(botAI, "party member critical health", sPlayerbotAIConfig.criticalHealth, 0) { } }; @@ -110,7 +110,7 @@ class PartyMemberMediumHealthTrigger : public PartyMemberLowHealthTrigger { public: PartyMemberMediumHealthTrigger(PlayerbotAI* botAI) - : PartyMemberLowHealthTrigger(botAI, "party member medium health", sPlayerbotAIConfig->mediumHealth, + : PartyMemberLowHealthTrigger(botAI, "party member medium health", sPlayerbotAIConfig.mediumHealth, 0) { } @@ -120,7 +120,7 @@ class PartyMemberAlmostFullHealthTrigger : public PartyMemberLowHealthTrigger { public: PartyMemberAlmostFullHealthTrigger(PlayerbotAI* botAI) - : PartyMemberLowHealthTrigger(botAI, "party member almost full health", sPlayerbotAIConfig->almostFullHealth, + : PartyMemberLowHealthTrigger(botAI, "party member almost full health", sPlayerbotAIConfig.almostFullHealth, 0) { } diff --git a/src/Ai/Base/Trigger/LootTriggers.cpp b/src/Ai/Base/Trigger/LootTriggers.cpp index f422f386ee..0a4b7e4117 100644 --- a/src/Ai/Base/Trigger/LootTriggers.cpp +++ b/src/Ai/Base/Trigger/LootTriggers.cpp @@ -15,11 +15,11 @@ bool LootAvailableTrigger::IsActive() if (botAI->HasStrategy("stay", BOT_STATE_NON_COMBAT)) { distanceCheck = - sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "loot target"), CONTACT_DISTANCE); + ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "loot target"), CONTACT_DISTANCE); } else { - distanceCheck = sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "loot target"), + distanceCheck = ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "loot target"), INTERACTION_DISTANCE - 2.0f); } diff --git a/src/Ai/Base/Trigger/PvpTriggers.cpp b/src/Ai/Base/Trigger/PvpTriggers.cpp index c837d8b16c..31fcd0357e 100644 --- a/src/Ai/Base/Trigger/PvpTriggers.cpp +++ b/src/Ai/Base/Trigger/PvpTriggers.cpp @@ -247,7 +247,7 @@ bool EnemyFlagCarrierNear::IsActive() { Unit* carrier = AI_VALUE(Unit*, "enemy flag carrier"); - if (!carrier || !sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, carrier), 100.f)) + if (!carrier || !ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, carrier), 100.f)) return false; // Check if there is another enemy player target closer than the FC @@ -255,8 +255,8 @@ bool EnemyFlagCarrierNear::IsActive() if (nearbyEnemy) { - float distToFC = sServerFacade->GetDistance2d(bot, carrier); - float distToEnemy = sServerFacade->GetDistance2d(bot, nearbyEnemy); + float distToFC = ServerFacade::instance().GetDistance2d(bot, carrier); + float distToEnemy = ServerFacade::instance().GetDistance2d(bot, nearbyEnemy); // If the other enemy is significantly closer, don't pursue FC if (distToEnemy + 15.0f < distToFC) // Add small buffer @@ -283,7 +283,7 @@ bool TeamFlagCarrierNear::IsActive() } Unit* carrier = AI_VALUE(Unit*, "team flag carrier"); - return carrier && sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(bot, carrier), 200.f); + return carrier && ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(bot, carrier), 200.f); } bool PlayerWantsInBattlegroundTrigger::IsActive() diff --git a/src/Ai/Base/Trigger/RangeTriggers.cpp b/src/Ai/Base/Trigger/RangeTriggers.cpp index af29f984d1..d0d86d0148 100644 --- a/src/Ai/Base/Trigger/RangeTriggers.cpp +++ b/src/Ai/Base/Trigger/RangeTriggers.cpp @@ -11,10 +11,10 @@ #include "ServerFacade.h" #include "SharedDefines.h" -static float GetSpeedInMotion(Unit* target) -{ - return target->GetSpeed(Movement::SelectSpeedType(target->GetUnitMovementFlags())); -} +// static float GetSpeedInMotion(Unit* target) +// { +// return target->GetSpeed(Movement::SelectSpeedType(target->GetUnitMovementFlags())); +// } bool EnemyTooCloseForSpellTrigger::IsActive() { @@ -34,7 +34,7 @@ bool EnemyTooCloseForSpellTrigger::IsActive() // bool isBoss = false; // bool isRaid = false; // float combatReach = bot->GetCombatReach() + target->GetCombatReach(); - // float targetDistance = sServerFacade->GetDistance2d(bot, target) + combatReach; + // float targetDistance = ServerFacade::instance().GetDistance2d(bot, target) + combatReach; // if (target->IsCreature()) // { // Creature* creature = botAI->GetCreature(target->GetGUID()); @@ -48,10 +48,10 @@ bool EnemyTooCloseForSpellTrigger::IsActive() // isRaid = true; // // if (isBoss || isRaid) - // // return sServerFacade->IsDistanceLessThan(targetDistance, (sPlayerbotAIConfig->tooCloseDistance + + // // return ServerFacade::instance().IsDistanceLessThan(targetDistance, (sPlayerbotAIConfig.tooCloseDistance + // combatReach) / 2); - // return sServerFacade->IsDistanceLessOrEqualThan(targetDistance, (sPlayerbotAIConfig->tooCloseDistance + + // return ServerFacade::instance().IsDistanceLessOrEqualThan(targetDistance, (sPlayerbotAIConfig.tooCloseDistance + // combatReach / 2)); } @@ -80,7 +80,7 @@ bool EnemyTooCloseForAutoShotTrigger::IsActive() // bool isBoss = false; // bool isRaid = false; // float combatReach = bot->GetCombatReach() + target->GetCombatReach(); - // float targetDistance = sServerFacade->GetDistance2d(bot, target) + combatReach; + // float targetDistance = ServerFacade::instance().GetDistance2d(bot, target) + combatReach; // if (target->IsCreature()) // { // Creature* creature = botAI->GetCreature(target->GetGUID()); @@ -93,7 +93,7 @@ bool EnemyTooCloseForAutoShotTrigger::IsActive() // if (bot->GetMap() && bot->GetMap()->IsRaid()) // isRaid = true; - // return sServerFacade->IsDistanceLessOrEqualThan(targetDistance, 5.0f); + // return ServerFacade::instance().IsDistanceLessOrEqualThan(targetDistance, 5.0f); } bool EnemyTooCloseForShootTrigger::IsActive() @@ -115,7 +115,7 @@ bool EnemyTooCloseForShootTrigger::IsActive() // bool isBoss = false; // bool isRaid = false; // float combatReach = bot->GetCombatReach() + target->GetCombatReach(); - // float targetDistance = sServerFacade->GetDistance2d(bot, target) + combatReach; + // float targetDistance = ServerFacade::instance().GetDistance2d(bot, target) + combatReach; // if (target->IsCreature()) // { // Creature* creature = botAI->GetCreature(target->GetGUID()); @@ -129,9 +129,9 @@ bool EnemyTooCloseForShootTrigger::IsActive() // isRaid = true; // // if (isBoss || isRaid) - // // return sServerFacade->IsDistanceLessThan(targetDistance, botAI->GetRange("shoot") + combatReach); + // // return ServerFacade::instance().IsDistanceLessThan(targetDistance, botAI->GetRange("shoot") + combatReach); - // return sServerFacade->IsDistanceLessOrEqualThan(targetDistance, (botAI->GetRange("shoot") + combatReach / + // return ServerFacade::instance().IsDistanceLessOrEqualThan(targetDistance, (botAI->GetRange("shoot") + combatReach / // 2)); } @@ -147,8 +147,8 @@ bool EnemyTooCloseForMeleeTrigger::IsActive() bool EnemyIsCloseTrigger::IsActive() { Unit* target = AI_VALUE(Unit*, "current target"); - return target && sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "current target"), - sPlayerbotAIConfig->tooCloseDistance); + return target && ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "current target"), + sPlayerbotAIConfig.tooCloseDistance); } bool EnemyWithinMeleeTrigger::IsActive() @@ -165,7 +165,7 @@ bool OutOfRangeTrigger::IsActive() return target && !bot->IsWithinCombatRange( target, - dis); // sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", GetTargetName()), distance); + dis); // ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", GetTargetName()), distance); } EnemyOutOfSpellRangeTrigger::EnemyOutOfSpellRangeTrigger(PlayerbotAI* botAI) @@ -180,8 +180,8 @@ EnemyOutOfSpellRangeTrigger::EnemyOutOfSpellRangeTrigger(PlayerbotAI* botAI) // return false; // float combatReach = bot->GetCombatReach() + target->GetCombatReach(); -// return target && (sServerFacade->GetDistance2d(bot, target) > (distance + combatReach + -// sPlayerbotAIConfig->contactDistance) || !bot->IsWithinLOSInMap(target)); +// return target && (ServerFacade::instance().GetDistance2d(bot, target) > (distance + combatReach + +// sPlayerbotAIConfig.contactDistance) || !bot->IsWithinLOSInMap(target)); // } // bool EnemyOutOfMeleeTrigger::IsActive() @@ -190,7 +190,7 @@ EnemyOutOfSpellRangeTrigger::EnemyOutOfSpellRangeTrigger(PlayerbotAI* botAI) // if (!target) // return false; -// float targetDistance = sServerFacade->GetDistance2d(bot, target); +// float targetDistance = ServerFacade::instance().GetDistance2d(bot, target); // return target && (targetDistance > std::max(5.0f, bot->GetCombatReach() + target->GetCombatReach()) || // (!bot->IsWithinLOSInMap(target) && targetDistance > 5.0f)); // } @@ -201,8 +201,7 @@ bool PartyMemberToHealOutOfSpellRangeTrigger::IsActive() if (!target) return false; - float combatReach = bot->GetCombatReach() + target->GetCombatReach(); - return target && (sServerFacade->GetDistance2d(bot, target) > (distance + sPlayerbotAIConfig->contactDistance) || + return target && (ServerFacade::instance().GetDistance2d(bot, target) > (distance + sPlayerbotAIConfig.contactDistance) || !bot->IsWithinLOSInMap(target)); } @@ -213,7 +212,7 @@ PartyMemberToHealOutOfSpellRangeTrigger::PartyMemberToHealOutOfSpellRangeTrigger bool FarFromMasterTrigger::IsActive() { - return sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "group leader"), distance); + return ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "group leader"), distance); } bool TooCloseToCreatureTrigger::TooCloseToCreature(uint32 creatureId, float range, bool alive) diff --git a/src/Ai/Base/Trigger/RangeTriggers.h b/src/Ai/Base/Trigger/RangeTriggers.h index cc320ad027..62e1ae6e03 100644 --- a/src/Ai/Base/Trigger/RangeTriggers.h +++ b/src/Ai/Base/Trigger/RangeTriggers.h @@ -78,7 +78,7 @@ class EnemyOutOfMeleeTrigger : public OutOfRangeTrigger { public: EnemyOutOfMeleeTrigger(PlayerbotAI* botAI) - : OutOfRangeTrigger(botAI, "enemy out of melee range", sPlayerbotAIConfig->meleeDistance) + : OutOfRangeTrigger(botAI, "enemy out of melee range", sPlayerbotAIConfig.meleeDistance) { } diff --git a/src/Ai/Base/Trigger/RpgTriggers.cpp b/src/Ai/Base/Trigger/RpgTriggers.cpp index f390359be3..ed528d2b72 100644 --- a/src/Ai/Base/Trigger/RpgTriggers.cpp +++ b/src/Ai/Base/Trigger/RpgTriggers.cpp @@ -31,9 +31,16 @@ bool RpgTrigger::IsActive() { return true; } Event RpgTrigger::Check() { - if (!NoRpgTargetTrigger::IsActive() && (AI_VALUE(std::string, "next rpg action") == "choose rpg target") || - !FarFromRpgTargetTrigger::IsActive()) + if ( + ( + !NoRpgTargetTrigger::IsActive() + && (AI_VALUE(std::string, "next rpg action") == "choose rpg target") + ) + || !FarFromRpgTargetTrigger::IsActive() + ) + { return Trigger::Check(); + } return Event(); } diff --git a/src/Ai/Base/Trigger/TravelTriggers.cpp b/src/Ai/Base/Trigger/TravelTriggers.cpp index 88dfbb2b4b..ce036027c1 100644 --- a/src/Ai/Base/Trigger/TravelTriggers.cpp +++ b/src/Ai/Base/Trigger/TravelTriggers.cpp @@ -21,7 +21,7 @@ bool AtDarkPortalAzerothTrigger::IsActive() { if (bot->GetAreaId() == 72) { - if (sServerFacade->GetDistance2d(bot, -11906.9f, -3208.53f) < 20.0f) + if (ServerFacade::instance().GetDistance2d(bot, -11906.9f, -3208.53f) < 20.0f) { return true; } @@ -34,7 +34,7 @@ bool AtDarkPortalOutlandTrigger::IsActive() { if (bot->GetAreaId() == 3539) { - if (sServerFacade->GetDistance2d(bot, -248.1939f, 921.919f) < 10.0f) + if (ServerFacade::instance().GetDistance2d(bot, -248.1939f, 921.919f) < 10.0f) { return true; } diff --git a/src/Ai/Base/Value/AoeHealValues.cpp b/src/Ai/Base/Value/AoeHealValues.cpp index 06f0002056..2c56986678 100644 --- a/src/Ai/Base/Value/AoeHealValues.cpp +++ b/src/Ai/Base/Value/AoeHealValues.cpp @@ -16,13 +16,13 @@ uint8 AoeHealValue::Calculate() float range = 0; if (qualifier == "low") - range = sPlayerbotAIConfig->lowHealth; + range = sPlayerbotAIConfig.lowHealth; else if (qualifier == "medium") - range = sPlayerbotAIConfig->mediumHealth; + range = sPlayerbotAIConfig.mediumHealth; else if (qualifier == "critical") - range = sPlayerbotAIConfig->criticalHealth; + range = sPlayerbotAIConfig.criticalHealth; else if (qualifier == "almost full") - range = sPlayerbotAIConfig->almostFullHealth; + range = sPlayerbotAIConfig.almostFullHealth; uint8 count = 0; Group::MemberSlotList const& groupSlot = group->GetMemberSlots(); @@ -32,7 +32,7 @@ uint8 AoeHealValue::Calculate() if (!player || !player->IsAlive()) continue; - if (player->GetDistance(bot) >= sPlayerbotAIConfig->sightDistance) + if (player->GetDistance(bot) >= sPlayerbotAIConfig.sightDistance) continue; float percent = (static_cast(player->GetHealth()) / player->GetMaxHealth()) * 100; diff --git a/src/Ai/Base/Value/AoeValues.cpp b/src/Ai/Base/Value/AoeValues.cpp index d46dcb816f..d1b60b590b 100644 --- a/src/Ai/Base/Value/AoeValues.cpp +++ b/src/Ai/Base/Value/AoeValues.cpp @@ -29,8 +29,8 @@ GuidVector FindMaxDensity(Player* bot) if (!other) continue; - float d = sServerFacade->GetDistance2d(unit, other); - if (sServerFacade->IsDistanceLessOrEqualThan(d, sPlayerbotAIConfig->aoeRadius * 2)) + float d = ServerFacade::instance().GetDistance2d(unit, other); + if (ServerFacade::instance().IsDistanceLessOrEqualThan(d, sPlayerbotAIConfig.aoeRadius * 2)) groups[*i].push_back(*j); } diff --git a/src/Ai/Base/Value/Arrow.cpp b/src/Ai/Base/Value/Arrow.cpp index 15fc2e2959..25e3a03947 100644 --- a/src/Ai/Base/Value/Arrow.cpp +++ b/src/Ai/Base/Value/Arrow.cpp @@ -6,7 +6,8 @@ #include "Arrow.h" #include "Map.h" -#include "Playerbots.h" +#include "PlayerbotAI.h" +#include "Group.h" WorldLocation ArrowFormation::GetLocationInternal() { @@ -18,7 +19,6 @@ WorldLocation ArrowFormation::GetLocationInternal() uint32 tankLines = 1 + tanks.Size() / 6; uint32 meleeLines = 1 + melee.Size() / 6; uint32 rangedLines = 1 + ranged.Size() / 6; - uint32 healerLines = 1 + healers.Size() / 6; float offset = 0.f; Player* master = botAI->GetMaster(); @@ -31,15 +31,15 @@ WorldLocation ArrowFormation::GetLocationInternal() tanks.PlaceUnits(&placer); tanks.Move(-cos(orientation) * offset, -sin(orientation) * offset); - offset += tankLines * sPlayerbotAIConfig->followDistance + sPlayerbotAIConfig->tooCloseDistance / 2; + offset += tankLines * sPlayerbotAIConfig.followDistance + sPlayerbotAIConfig.tooCloseDistance / 2; melee.PlaceUnits(&placer); melee.Move(-cos(orientation) * offset, -sin(orientation) * offset); - offset += meleeLines * sPlayerbotAIConfig->followDistance + sPlayerbotAIConfig->tooCloseDistance / 2; + offset += meleeLines * sPlayerbotAIConfig.followDistance + sPlayerbotAIConfig.tooCloseDistance / 2; ranged.PlaceUnits(&placer); ranged.Move(-cos(orientation) * offset, -sin(orientation) * offset); - offset += rangedLines * sPlayerbotAIConfig->followDistance; + offset += rangedLines * sPlayerbotAIConfig.followDistance; healers.PlaceUnits(&placer); healers.Move(-cos(orientation) * offset, -sin(orientation) * offset); @@ -143,16 +143,14 @@ UnitPosition MultiLineUnitPlacer::Place(FormationUnit* unit, uint32 index, uint3 uint32 lineNo = index / 6; uint32 indexInLine = index % 6; uint32 lineSize = std::max(count - lineNo * 6, uint32(6)); - float x = cos(orientation) * sPlayerbotAIConfig->followDistance * lineNo; - float y = sin(orientation) * sPlayerbotAIConfig->followDistance * lineNo; return placer.Place(unit, indexInLine, lineSize); } -UnitPosition SingleLineUnitPlacer::Place(FormationUnit* unit, uint32 index, uint32 count) +UnitPosition SingleLineUnitPlacer::Place(FormationUnit*, uint32 index, uint32 count) { float angle = orientation - M_PI / 2.0f; - float x = cos(angle) * sPlayerbotAIConfig->followDistance * ((float)index - (float)count / 2); - float y = sin(angle) * sPlayerbotAIConfig->followDistance * ((float)index - (float)count / 2); + float x = cos(angle) * sPlayerbotAIConfig.followDistance * ((float)index - (float)count / 2); + float y = sin(angle) * sPlayerbotAIConfig.followDistance * ((float)index - (float)count / 2); return UnitPosition(x, y); } diff --git a/src/Ai/Base/Value/Arrow.h b/src/Ai/Base/Value/Arrow.h index 3e5a76b8fb..220cb370bd 100644 --- a/src/Ai/Base/Value/Arrow.h +++ b/src/Ai/Base/Value/Arrow.h @@ -16,11 +16,13 @@ class UnitPosition { public: UnitPosition(float x, float y) : x(x), y(y) {} - UnitPosition(UnitPosition const& other) - { - x = other.x; - y = other.y; - } + ~UnitPosition() = default; + + UnitPosition(UnitPosition const& other) = default; + UnitPosition& operator=(UnitPosition const& other) = default; + + UnitPosition(UnitPosition&&) = default; + UnitPosition& operator=(UnitPosition&&) = default; float x, y; }; @@ -102,7 +104,7 @@ class ArrowFormation : public MoveAheadFormation { public: ArrowFormation(PlayerbotAI* botAI) - : MoveAheadFormation(botAI, "arrow"), built(false), masterUnit(nullptr), botUnit(nullptr) + : MoveAheadFormation(botAI, "arrow"), masterUnit(nullptr), botUnit(nullptr), built(false) { } diff --git a/src/Ai/Base/Value/AttackerCountValues.cpp b/src/Ai/Base/Value/AttackerCountValues.cpp index 637fd72864..88c3cd1fb6 100644 --- a/src/Ai/Base/Value/AttackerCountValues.cpp +++ b/src/Ai/Base/Value/AttackerCountValues.cpp @@ -34,7 +34,7 @@ bool HasAggroValue::Calculate() uint8 AttackerCountValue::Calculate() { uint32 count = 0; - float range = sPlayerbotAIConfig->sightDistance; + float range = sPlayerbotAIConfig.sightDistance; GuidVector attackers = context->GetValue("attackers")->Get(); for (ObjectGuid const guid : attackers) diff --git a/src/Ai/Base/Value/AttackersValue.cpp b/src/Ai/Base/Value/AttackersValue.cpp index f6da0aa7a6..dbde7ab8df 100644 --- a/src/Ai/Base/Value/AttackersValue.cpp +++ b/src/Ai/Base/Value/AttackersValue.cpp @@ -71,7 +71,7 @@ void AttackersValue::AddAttackersOf(Group* group, std::unordered_set& tar { Player* member = ObjectAccessor::FindPlayer(itr->guid); if (!member || !member->IsAlive() || member == bot || member->GetMapId() != bot->GetMapId() || - sServerFacade->GetDistance2d(bot, member) > sPlayerbotAIConfig->sightDistance) + ServerFacade::instance().GetDistance2d(bot, member) > sPlayerbotAIConfig.sightDistance) continue; AddAttackersOf(member, targets); @@ -103,7 +103,7 @@ void AttackersValue::AddAttackersOf(Player* player, std::unordered_set& t Unit* attacker = threatMgr->GetOwner(); if (player->IsValidAttackTarget(attacker) && - player->GetDistance2d(attacker) < sPlayerbotAIConfig->sightDistance) + player->GetDistance2d(attacker) < sPlayerbotAIConfig.sightDistance) targets.insert(attacker); ref = ref->next(); @@ -176,8 +176,8 @@ bool AttackersValue::IsPossibleTarget(Unit* attacker, Player* bot, float /*range // PvP prohibition checks (skip for duels) if ((attacker->GetGUID().IsPlayer() || attacker->GetGUID().IsPet()) && (!bot->duel || bot->duel->Opponent != attacker) && - (sPlayerbotAIConfig->IsPvpProhibited(attacker->GetZoneId(), attacker->GetAreaId()) || - sPlayerbotAIConfig->IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()))) + (sPlayerbotAIConfig.IsPvpProhibited(attacker->GetZoneId(), attacker->GetAreaId()) || + sPlayerbotAIConfig.IsPvpProhibited(bot->GetZoneId(), bot->GetAreaId()))) { // This will stop aggresive pets from starting an attack. // This will stop currently attacking pets from continuing their attack. @@ -269,11 +269,11 @@ bool PossibleAddsValue::Calculate() if (!attacker) continue; - float dist = sServerFacade->GetDistance2d(attacker, add); - if (sServerFacade->IsDistanceLessOrEqualThan(dist, sPlayerbotAIConfig->aoeRadius * 1.5f)) + float dist = ServerFacade::instance().GetDistance2d(attacker, add); + if (ServerFacade::instance().IsDistanceLessOrEqualThan(dist, sPlayerbotAIConfig.aoeRadius * 1.5f)) continue; - if (sServerFacade->IsDistanceLessOrEqualThan(dist, sPlayerbotAIConfig->aggroDistance)) + if (ServerFacade::instance().IsDistanceLessOrEqualThan(dist, sPlayerbotAIConfig.aggroDistance)) return true; } } diff --git a/src/Ai/Base/Value/AttackersValue.h b/src/Ai/Base/Value/AttackersValue.h index 906db92a88..7e9397c86c 100644 --- a/src/Ai/Base/Value/AttackersValue.h +++ b/src/Ai/Base/Value/AttackersValue.h @@ -20,7 +20,7 @@ class AttackersValue : public ObjectGuidListCalculatedValue AttackersValue(PlayerbotAI* botAI) : ObjectGuidListCalculatedValue(botAI, "attackers", 1 * 1000) {} GuidVector Calculate(); - static bool IsPossibleTarget(Unit* attacker, Player* bot, float range = sPlayerbotAIConfig->sightDistance); + static bool IsPossibleTarget(Unit* attacker, Player* bot, float range = sPlayerbotAIConfig.sightDistance); static bool IsValidTarget(Unit* attacker, Player* bot); private: diff --git a/src/Ai/Base/Value/AvailableLootValue.cpp b/src/Ai/Base/Value/AvailableLootValue.cpp index 7f945d7e1e..75b4b599a4 100644 --- a/src/Ai/Base/Value/AvailableLootValue.cpp +++ b/src/Ai/Base/Value/AvailableLootValue.cpp @@ -26,5 +26,5 @@ bool CanLootValue::Calculate() { LootObject loot = AI_VALUE(LootObject, "loot target"); return !loot.IsEmpty() && loot.GetWorldObject(bot) && loot.IsLootPossible(bot) && - sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "loot target"), INTERACTION_DISTANCE - 2); + ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "loot target"), INTERACTION_DISTANCE - 2); } diff --git a/src/Ai/Base/Value/BudgetValues.cpp b/src/Ai/Base/Value/BudgetValues.cpp index daa7aca863..06b2e1d576 100644 --- a/src/Ai/Base/Value/BudgetValues.cpp +++ b/src/Ai/Base/Value/BudgetValues.cpp @@ -10,7 +10,7 @@ uint32 MaxGearRepairCostValue::Calculate() { uint32 TotalCost = 0; - for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) + for (uint32_t i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) { uint16 pos = ((INVENTORY_SLOT_BAG_0 << 8) | i); Item* item = bot->GetItemByPos(pos); diff --git a/src/Ai/Base/Value/CcTargetValue.cpp b/src/Ai/Base/Value/CcTargetValue.cpp index c47151ddfd..e84f4f4b70 100644 --- a/src/Ai/Base/Value/CcTargetValue.cpp +++ b/src/Ai/Base/Value/CcTargetValue.cpp @@ -6,7 +6,9 @@ #include "CcTargetValue.h" #include "Action.h" -#include "Playerbots.h" +#include "AiObjectContext.h" +#include "Group.h" +#include "PlayerbotAI.h" #include "ServerFacade.h" class FindTargetForCcStrategy : public FindTargetStrategy @@ -18,7 +20,7 @@ class FindTargetForCcStrategy : public FindTargetStrategy } public: - void CheckAttacker(Unit* creature, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* creature, ThreatMgr*) override { Player* bot = botAI->GetBot(); if (!botAI->CanCastSpell(spell, creature)) @@ -34,7 +36,7 @@ class FindTargetForCcStrategy : public FindTargetStrategy return; uint8 health = static_cast(creature->GetHealthPct()); - if (health < sPlayerbotAIConfig->mediumHealth) + if (health < sPlayerbotAIConfig.mediumHealth) return; float minDistance = botAI->GetRange("spell"); @@ -45,9 +47,9 @@ class FindTargetForCcStrategy : public FindTargetStrategy if (*botAI->GetAiObjectContext()->GetValue("aoe count") > 2) { WorldLocation aoe = *botAI->GetAiObjectContext()->GetValue("aoe position"); - if (sServerFacade->IsDistanceLessOrEqualThan( - sServerFacade->GetDistance2d(creature, aoe.GetPositionX(), aoe.GetPositionY()), - sPlayerbotAIConfig->aoeRadius)) + if (ServerFacade::instance().IsDistanceLessOrEqualThan( + ServerFacade::instance().GetDistance2d(creature, aoe.GetPositionX(), aoe.GetPositionY()), + sPlayerbotAIConfig.aoeRadius)) return; } @@ -70,7 +72,7 @@ class FindTargetForCcStrategy : public FindTargetStrategy if (!botAI->IsTank(member)) continue; - float distance = sServerFacade->GetDistance2d(member, creature); + float distance = ServerFacade::instance().GetDistance2d(member, creature); if (distance < minDistance) minDistance = distance; } diff --git a/src/Ai/Base/Value/CollisionValue.cpp b/src/Ai/Base/Value/CollisionValue.cpp index 7657742590..172a909b17 100644 --- a/src/Ai/Base/Value/CollisionValue.cpp +++ b/src/Ai/Base/Value/CollisionValue.cpp @@ -18,7 +18,7 @@ bool CollisionValue::Calculate() return false; std::list targets; - float range = sPlayerbotAIConfig->contactDistance; + float range = sPlayerbotAIConfig.contactDistance; Acore::AnyUnitInObjectRangeCheck u_check(bot, range); Acore::UnitListSearcher searcher(bot, targets, u_check); Cell::VisitObjects(bot, searcher, range); @@ -28,8 +28,8 @@ bool CollisionValue::Calculate() if (bot == target) continue; - float dist = sServerFacade->GetDistance2d(bot, target->GetPositionX(), target->GetPositionY()); - if (sServerFacade->IsDistanceLessThan(dist, target->GetCombatReach())) + float dist = ServerFacade::instance().GetDistance2d(bot, target->GetPositionX(), target->GetPositionY()); + if (ServerFacade::instance().IsDistanceLessThan(dist, target->GetCombatReach())) return true; } diff --git a/src/Ai/Base/Value/CraftValue.h b/src/Ai/Base/Value/CraftValue.h index d3311e6c8a..def3352b9c 100644 --- a/src/Ai/Base/Value/CraftValue.h +++ b/src/Ai/Base/Value/CraftValue.h @@ -16,11 +16,13 @@ class CraftData { public: CraftData() : itemId(0) {} - CraftData(CraftData const& other) : itemId(other.itemId) - { - required.insert(other.required.begin(), other.required.end()); - obtained.insert(other.obtained.begin(), other.obtained.end()); - } + ~CraftData() = default; + + CraftData(CraftData const& other) = default; + CraftData& operator=(CraftData const& other) = default; + + CraftData(CraftData&&) = default; + CraftData& operator=(CraftData&&) = default; uint32 itemId; std::map required, obtained; diff --git a/src/Ai/Base/Value/CurrentCcTargetValue.cpp b/src/Ai/Base/Value/CurrentCcTargetValue.cpp index 27b8100264..7739dd81b9 100644 --- a/src/Ai/Base/Value/CurrentCcTargetValue.cpp +++ b/src/Ai/Base/Value/CurrentCcTargetValue.cpp @@ -4,8 +4,7 @@ */ #include "CurrentCcTargetValue.h" - -#include "Playerbots.h" +#include "PlayerbotAI.h" class FindCurrentCcTargetStrategy : public FindTargetStrategy { @@ -14,7 +13,7 @@ class FindCurrentCcTargetStrategy : public FindTargetStrategy { } - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { if (botAI->HasAura(spell, attacker)) result = attacker; diff --git a/src/Ai/Base/Value/DistanceValue.cpp b/src/Ai/Base/Value/DistanceValue.cpp index 2c1e818b54..a5c6fe857a 100644 --- a/src/Ai/Base/Value/DistanceValue.cpp +++ b/src/Ai/Base/Value/DistanceValue.cpp @@ -24,7 +24,7 @@ float DistanceValue::Calculate() if (!obj || !obj->IsInWorld()) return 0.0f; - return sServerFacade->GetDistance2d(botAI->GetBot(), obj); + return ServerFacade::instance().GetDistance2d(botAI->GetBot(), obj); } if (qualifier.find("position_") == 0) @@ -37,7 +37,7 @@ float DistanceValue::Calculate() if (botAI->GetBot()->GetMapId() != pos.mapId) return 0.0f; - return sServerFacade->GetDistance2d(botAI->GetBot(), pos.x, pos.y); + return ServerFacade::instance().GetDistance2d(botAI->GetBot(), pos.x, pos.y); } Unit* target = nullptr; @@ -76,7 +76,7 @@ float DistanceValue::Calculate() { Formation* formation = AI_VALUE(Formation*, "formation"); WorldLocation loc = formation->GetLocation(); - return sServerFacade->GetDistance2d(botAI->GetBot(), loc.GetPositionX(), loc.GetPositionY()); + return ServerFacade::instance().GetDistance2d(botAI->GetBot(), loc.GetPositionX(), loc.GetPositionY()); } } @@ -86,7 +86,7 @@ float DistanceValue::Calculate() if (target == botAI->GetBot()) return 0.0f; - return sServerFacade->GetDistance2d(botAI->GetBot(), target); + return ServerFacade::instance().GetDistance2d(botAI->GetBot(), target); } bool InsideTargetValue::Calculate() @@ -95,6 +95,6 @@ bool InsideTargetValue::Calculate() if (!target || !target->IsInWorld() || target == botAI->GetBot()) return false; - float dist = sServerFacade->GetDistance2d(botAI->GetBot(), target->GetPositionX(), target->GetPositionY()); - return sServerFacade->IsDistanceLessThan(dist, target->GetCombatReach()); + float dist = ServerFacade::instance().GetDistance2d(botAI->GetBot(), target->GetPositionX(), target->GetPositionY()); + return ServerFacade::instance().IsDistanceLessThan(dist, target->GetCombatReach()); } diff --git a/src/Ai/Base/Value/DpsTargetValue.cpp b/src/Ai/Base/Value/DpsTargetValue.cpp index 55b47d7c01..d1bad8c17d 100644 --- a/src/Ai/Base/Value/DpsTargetValue.cpp +++ b/src/Ai/Base/Value/DpsTargetValue.cpp @@ -29,7 +29,6 @@ class FindMaxThreatGapTargetStrategy : public FindTargetStrategy foundHighPriority = true; return; } - Unit* victim = attacker->GetVictim(); if (!result || CalcThreatGap(attacker, threatMgr) > CalcThreatGap(result, &result->GetThreatMgr())) result = attacker; } @@ -53,7 +52,7 @@ class CasterFindTargetSmartStrategy : public FindTargetStrategy result = nullptr; } - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { if (Group* group = botAI->GetBot()->GetGroup()) { @@ -116,7 +115,7 @@ class CasterFindTargetSmartStrategy : public FindTargetStrategy float time = unit->GetHealth() / dps_; float dis = unit->GetDistance(botAI->GetBot()); float attackRange = - botAI->IsRanged(botAI->GetBot()) ? sPlayerbotAIConfig->spellDistance : sPlayerbotAIConfig->meleeDistance; + botAI->IsRanged(botAI->GetBot()) ? sPlayerbotAIConfig.spellDistance : sPlayerbotAIConfig.meleeDistance; attackRange += 5.0f; int level = dis < attackRange ? 10 : 0; if (time >= 5 && time <= 30) @@ -144,7 +143,7 @@ class GeneralFindTargetSmartStrategy : public FindTargetStrategy { } - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { if (Group* group = botAI->GetBot()->GetGroup()) { @@ -195,10 +194,9 @@ class GeneralFindTargetSmartStrategy : public FindTargetStrategy } int32_t GetIntervalLevel(Unit* unit) { - float time = unit->GetHealth() / dps_; float dis = unit->GetDistance(botAI->GetBot()); float attackRange = - botAI->IsRanged(botAI->GetBot()) ? sPlayerbotAIConfig->spellDistance : sPlayerbotAIConfig->meleeDistance; + botAI->IsRanged(botAI->GetBot()) ? sPlayerbotAIConfig.spellDistance : sPlayerbotAIConfig.meleeDistance; attackRange += 5.0f; int level = dis < attackRange ? 10 : 0; return level; @@ -218,7 +216,7 @@ class ComboFindTargetSmartStrategy : public FindTargetStrategy { } - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { if (Group* group = botAI->GetBot()->GetGroup()) { @@ -276,10 +274,9 @@ class ComboFindTargetSmartStrategy : public FindTargetStrategy } int32_t GetIntervalLevel(Unit* unit) { - float time = unit->GetHealth() / dps_; float dis = unit->GetDistance(botAI->GetBot()); float attackRange = - botAI->IsRanged(botAI->GetBot()) ? sPlayerbotAIConfig->spellDistance : sPlayerbotAIConfig->meleeDistance; + botAI->IsRanged(botAI->GetBot()) ? sPlayerbotAIConfig.spellDistance : sPlayerbotAIConfig.meleeDistance; attackRange += 5.0f; int level = dis < attackRange ? 10 : 0; return level; @@ -322,7 +319,7 @@ class FindMaxHpTargetStrategy : public FindTargetStrategy public: FindMaxHpTargetStrategy(PlayerbotAI* botAI) : FindTargetStrategy(botAI), maxHealth(0) {} - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { if (Group* group = botAI->GetBot()->GetGroup()) { diff --git a/src/Ai/Base/Value/EnemyHealerTargetValue.cpp b/src/Ai/Base/Value/EnemyHealerTargetValue.cpp index 6040c4fcb5..85559f7827 100644 --- a/src/Ai/Base/Value/EnemyHealerTargetValue.cpp +++ b/src/Ai/Base/Value/EnemyHealerTargetValue.cpp @@ -20,7 +20,7 @@ Unit* EnemyHealerTargetValue::Calculate() if (!unit || unit == target) continue; - if (sServerFacade->GetDistance2d(bot, unit) > botAI->GetRange("spell")) + if (ServerFacade::instance().GetDistance2d(bot, unit) > botAI->GetRange("spell")) continue; if (!botAI->IsInterruptableSpellCasting(unit, spell)) diff --git a/src/Ai/Base/Value/EnemyPlayerValue.cpp b/src/Ai/Base/Value/EnemyPlayerValue.cpp index 2325c9c09b..7de0cd670a 100644 --- a/src/Ai/Base/Value/EnemyPlayerValue.cpp +++ b/src/Ai/Base/Value/EnemyPlayerValue.cpp @@ -14,7 +14,7 @@ bool NearestEnemyPlayersValue::AcceptUnit(Unit* unit) bool inCannon = botAI->IsInVehicle(false, true); Player* enemy = dynamic_cast(unit); if (enemy && botAI->IsOpposing(enemy) && enemy->IsPvP() && - !sPlayerbotAIConfig->IsPvpProhibited(enemy->GetZoneId(), enemy->GetAreaId()) && + !sPlayerbotAIConfig.IsPvpProhibited(enemy->GetZoneId(), enemy->GetAreaId()) && !enemy->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NON_ATTACKABLE_2) && ((inCannon || !enemy->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE))) && /*!enemy->HasStealthAura() && !enemy->HasInvisibilityAura()*/ enemy->CanSeeOrDetect(bot) && @@ -131,7 +131,7 @@ Unit* EnemyPlayerValue::Calculate() if (pMember == bot) continue; - if (sServerFacade->GetDistance2d(bot, pMember) > 30.0f) + if (ServerFacade::instance().GetDistance2d(bot, pMember) > 30.0f) continue; if (Unit* pAttacker = pMember->getAttackerForHelper()) diff --git a/src/Ai/Base/Value/EnemyPlayerValue.h b/src/Ai/Base/Value/EnemyPlayerValue.h index f94f20265f..2ff56f4eb2 100644 --- a/src/Ai/Base/Value/EnemyPlayerValue.h +++ b/src/Ai/Base/Value/EnemyPlayerValue.h @@ -16,7 +16,7 @@ class Unit; class NearestEnemyPlayersValue : public PossibleTargetsValue { public: - NearestEnemyPlayersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->grindDistance) + NearestEnemyPlayersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.grindDistance) : PossibleTargetsValue(botAI, "nearest enemy players", range) { } diff --git a/src/Ai/Base/Value/EstimatedLifetimeValue.cpp b/src/Ai/Base/Value/EstimatedLifetimeValue.cpp index dd79207130..ee43a8c6c1 100644 --- a/src/Ai/Base/Value/EstimatedLifetimeValue.cpp +++ b/src/Ai/Base/Value/EstimatedLifetimeValue.cpp @@ -46,7 +46,7 @@ float EstimatedGroupDpsValue::Calculate() if (member->GetMapId() != bot->GetMapId()) continue; - if (member->GetExactDist(bot) > sPlayerbotAIConfig->sightDistance) + if (member->GetExactDist(bot) > sPlayerbotAIConfig.sightDistance) continue; groupPlayer.push_back(member); diff --git a/src/Ai/Base/Value/Formations.cpp b/src/Ai/Base/Value/Formations.cpp index 69869889d7..1394b9fbe0 100644 --- a/src/Ai/Base/Value/Formations.cpp +++ b/src/Ai/Base/Value/Formations.cpp @@ -64,8 +64,8 @@ WorldLocation MoveAheadFormation::GetLocation() // if (master->isMoving()) // { // float ori = master->GetOrientation(); - // float x1 = x + sPlayerbotAIConfig->tooCloseDistance * cos(ori); - // float y1 = y + sPlayerbotAIConfig->tooCloseDistance * sin(ori); + // float x1 = x + sPlayerbotAIConfig.tooCloseDistance * cos(ori); + // float y1 = y + sPlayerbotAIConfig.tooCloseDistance * sin(ori); // float ground = map->GetHeight(x1, y1, z); // if (ground > INVALID_HEIGHT) // { @@ -111,7 +111,7 @@ class NearFormation : public MoveAheadFormation if (!ValidateTargetContext(master, bot, map)) return Formation::NullLocation; - float range = sPlayerbotAIConfig->followDistance; + float range = sPlayerbotAIConfig.followDistance; float angle = GetFollowAngle(); float x = master->GetPositionX() + cos(angle) * range; float y = master->GetPositionY() + sin(angle) * range; @@ -127,7 +127,7 @@ class NearFormation : public MoveAheadFormation return WorldLocation(master->GetMapId(), x, y, z); } - float GetMaxDistance() override { return sPlayerbotAIConfig->followDistance; } + float GetMaxDistance() override { return sPlayerbotAIConfig.followDistance; } }; class ChaosFormation : public MoveAheadFormation @@ -142,7 +142,7 @@ class ChaosFormation : public MoveAheadFormation if (!ValidateTargetContext(master, bot, map)) return Formation::NullLocation; - float range = sPlayerbotAIConfig->followDistance; + float range = sPlayerbotAIConfig.followDistance; float angle = GetFollowAngle(); time_t now = time(nullptr); @@ -150,8 +150,8 @@ class ChaosFormation : public MoveAheadFormation { lastChangeTime = now; - dx = (urand(0, 10) / 10.0f - 0.5f) * sPlayerbotAIConfig->tooCloseDistance; - dy = (urand(0, 10) / 10.0f - 0.5f) * sPlayerbotAIConfig->tooCloseDistance; + dx = (urand(0, 10) / 10.0f - 0.5f) * sPlayerbotAIConfig.tooCloseDistance; + dy = (urand(0, 10) / 10.0f - 0.5f) * sPlayerbotAIConfig.tooCloseDistance; dr = std::sqrt(dx * dx + dy * dy); } @@ -173,7 +173,7 @@ class ChaosFormation : public MoveAheadFormation return WorldLocation(master->GetMapId(), x, y, z); } - float GetMaxDistance() override { return sPlayerbotAIConfig->followDistance + dr; } + float GetMaxDistance() override { return sPlayerbotAIConfig.followDistance + dr; } private: time_t lastChangeTime; @@ -287,7 +287,7 @@ class ShieldFormation : public MoveFormation if (!group) return Formation::NullLocation; - float range = sPlayerbotAIConfig->followDistance; + float range = sPlayerbotAIConfig.followDistance; Player* master = GetMaster(); if (!master) @@ -326,14 +326,14 @@ class ShieldFormation : public MoveFormation if (botAI->IsTank(bot) && !botAI->IsTank(master)) { - float diff = (tanks.size() % 2 == 0) ? -sPlayerbotAIConfig->tooCloseDistance / 2.0f : 0.0f; + float diff = (tanks.size() % 2 == 0) ? -sPlayerbotAIConfig.tooCloseDistance / 2.0f : 0.0f; return MoveLine(tanks, diff, x + cos(orientation) * range, y + sin(orientation) * range, z, orientation, range); } if (!botAI->IsTank(bot) && botAI->IsTank(master)) { - float diff = (dps.size() % 2 == 0) ? -sPlayerbotAIConfig->tooCloseDistance / 2.0f : 0.0f; + float diff = (dps.size() % 2 == 0) ? -sPlayerbotAIConfig.tooCloseDistance / 2.0f : 0.0f; return MoveLine(dps, diff, x - cos(orientation) * range, y - sin(orientation) * range, z, orientation, range); } @@ -354,10 +354,10 @@ class FarFormation : public FollowFormation if (!ValidateTargetContext(master, bot, map)) return Formation::NullLocation; - float range = sPlayerbotAIConfig->farDistance; - float followRange = sPlayerbotAIConfig->followDistance; + float range = sPlayerbotAIConfig.farDistance; + float followRange = sPlayerbotAIConfig.followDistance; - if (sServerFacade->GetDistance2d(bot, master) <= range) + if (ServerFacade::instance().GetDistance2d(bot, master) <= range) return Formation::NullLocation; float angleToBot = master->GetAngle(bot); @@ -378,7 +378,7 @@ class FarFormation : public FollowFormation float tx = master->GetPositionX() + cos(a) * range + cos(followAngle) * followRange; float ty = master->GetPositionY() + sin(a) * range + sin(followAngle) * followRange; - float dist = sServerFacade->GetDistance2d(bot, tx, ty); + float dist = ServerFacade::instance().GetDistance2d(bot, tx, ty); float tg = master->GetMapHeight(tx, ty, z + 30.0f); if (tg > INVALID_HEIGHT && (!minDist || dist < minDist)) diff --git a/src/Ai/Base/Value/Formations.h b/src/Ai/Base/Value/Formations.h index c44e1d0f42..3e5decf7f1 100644 --- a/src/Ai/Base/Value/Formations.h +++ b/src/Ai/Base/Value/Formations.h @@ -21,7 +21,7 @@ class Formation : public AiNamedObject virtual ~Formation() = default; virtual std::string const GetTargetName() { return ""; } virtual WorldLocation GetLocation() { return NullLocation; } - virtual float GetMaxDistance() { return sPlayerbotAIConfig->followDistance; } + virtual float GetMaxDistance() { return sPlayerbotAIConfig.followDistance; } static WorldLocation NullLocation; static bool IsNullLocation(WorldLocation const& loc); diff --git a/src/Ai/Base/Value/GrindTargetValue.cpp b/src/Ai/Base/Value/GrindTargetValue.cpp index 7e6168c776..d0c5095b8a 100644 --- a/src/Ai/Base/Value/GrindTargetValue.cpp +++ b/src/Ai/Base/Value/GrindTargetValue.cpp @@ -30,7 +30,6 @@ Unit* GrindTargetValue::Calculate() Unit* GrindTargetValue::FindTargetForGrinding(uint32 assistCount) { - uint32 memberCount = 1; Group* group = bot->GetGroup(); Player* master = GetMaster(); @@ -65,7 +64,6 @@ Unit* GrindTargetValue::FindTargetForGrinding(uint32 assistCount) if (!unit->IsInWorld() || unit->IsDuringRemoveFromWorld()) continue; - auto& rep = bot->ToPlayer()->GetReputationMgr(); if (unit->ToCreature() && !unit->ToCreature()->GetCreatureTemplate()->lootid && bot->GetReactionTo(unit) >= REP_NEUTRAL) continue; @@ -82,12 +80,12 @@ Unit* GrindTargetValue::FindTargetForGrinding(uint32 assistCount) if (!bot->InBattleground() && GetTargetingPlayerCount(unit) > assistCount) continue; - // if (!bot->InBattleground() && master && master->GetDistance(unit) >= sPlayerbotAIConfig->grindDistance && - // !sRandomPlayerbotMgr->IsRandomBot(bot)) continue; + // if (!bot->InBattleground() && master && master->GetDistance(unit) >= sPlayerbotAIConfig.grindDistance && + // !sRandomPlayerbotMgr.IsRandomBot(bot)) continue; // Bots in bot-groups no have a more limited range to look for grind target if (!bot->InBattleground() && master && botAI->HasStrategy("follow", BotState::BOT_STATE_NON_COMBAT) && - sServerFacade->GetDistance2d(master, unit) > sPlayerbotAIConfig->lootDistance) + ServerFacade::instance().GetDistance2d(master, unit) > sPlayerbotAIConfig.lootDistance) { if (botAI->HasStrategy("debug grind", BotState::BOT_STATE_NON_COMBAT)) botAI->TellMaster(chat->FormatWorldobject(unit) + " ignored (far from master)."); @@ -184,7 +182,9 @@ bool GrindTargetValue::needForQuest(Unit* target) int required = questTemplate->RequiredNpcOrGoCount[j]; int available = questStatus->CreatureOrGOCount[j]; - if (required && available < required && target->GetEntry() == entry) + const int64_t targetEntry = target->GetEntry(); + + if (required && available < required && targetEntry == entry) return true; } } diff --git a/src/Ai/Base/Value/GroupValues.cpp b/src/Ai/Base/Value/GroupValues.cpp index 01049a7969..460b9f334d 100644 --- a/src/Ai/Base/Value/GroupValues.cpp +++ b/src/Ai/Base/Value/GroupValues.cpp @@ -47,7 +47,7 @@ bool IsNearLeaderValue::Calculate() if (groupLeader == bot) return true; - return sServerFacade->GetDistance2d(bot, botAI->GetGroupLeader()) < sPlayerbotAIConfig->sightDistance; + return ServerFacade::instance().GetDistance2d(bot, botAI->GetGroupLeader()) < sPlayerbotAIConfig.sightDistance; } bool BoolANDValue::Calculate() @@ -155,10 +155,10 @@ bool GroupReadyValue::Calculate() // We only wait for members that are in range otherwise we might be waiting for bots stuck in dead loops // forever. if (botAI->GetGroupLeader() && - sServerFacade->GetDistance2d(member, botAI->GetGroupLeader()) > sPlayerbotAIConfig->sightDistance) + ServerFacade::instance().GetDistance2d(member, botAI->GetGroupLeader()) > sPlayerbotAIConfig.sightDistance) continue; - if (member->GetHealthPct() < sPlayerbotAIConfig->almostFullHealth) + if (member->GetHealthPct() < sPlayerbotAIConfig.almostFullHealth) return false; if (!member->GetPower(POWER_MANA)) @@ -166,7 +166,7 @@ bool GroupReadyValue::Calculate() float mana = (static_cast(member->GetPower(POWER_MANA)) / member->GetMaxPower(POWER_MANA)) * 100; - if (mana < sPlayerbotAIConfig->mediumMana) + if (mana < sPlayerbotAIConfig.mediumMana) return false; } diff --git a/src/Ai/Base/Value/HasAvailableLootValue.cpp b/src/Ai/Base/Value/HasAvailableLootValue.cpp index d687e1fc41..532e06afcd 100644 --- a/src/Ai/Base/Value/HasAvailableLootValue.cpp +++ b/src/Ai/Base/Value/HasAvailableLootValue.cpp @@ -11,5 +11,5 @@ bool HasAvailableLootValue::Calculate() { return !AI_VALUE(bool, "can loot") && - AI_VALUE(LootObjectStack*, "available loot")->CanLoot(sPlayerbotAIConfig->lootDistance); + AI_VALUE(LootObjectStack*, "available loot")->CanLoot(sPlayerbotAIConfig.lootDistance); } diff --git a/src/Ai/Base/Value/ItemCountValue.cpp b/src/Ai/Base/Value/ItemCountValue.cpp index 2c719d8f4d..9d4cb729f9 100644 --- a/src/Ai/Base/Value/ItemCountValue.cpp +++ b/src/Ai/Base/Value/ItemCountValue.cpp @@ -5,26 +5,12 @@ #include "ItemCountValue.h" -#include "Playerbots.h" - -std::vector InventoryItemValueBase::Find(std::string const qualifier) +uint32_t ItemCountValue::Calculate() { - std::vector result; - - Player* bot = InventoryAction::botAI->GetBot(); - + uint32_t count = 0; std::vector items = InventoryAction::parseItems(qualifier); - for (Item* item : items) - result.push_back(item); - - return result; -} -uint32 ItemCountValue::Calculate() -{ - uint32 count = 0; - std::vector items = Find(qualifier); - for (Item* item : items) + for (const Item* const item : items) { count += item->GetCount(); } @@ -32,4 +18,7 @@ uint32 ItemCountValue::Calculate() return count; } -std::vector InventoryItemValue::Calculate() { return Find(qualifier); } +std::vector InventoryItemValue::Calculate() +{ + return InventoryAction::parseItems(qualifier); +} diff --git a/src/Ai/Base/Value/ItemCountValue.h b/src/Ai/Base/Value/ItemCountValue.h index 6f7c593b23..41ac9a62f4 100644 --- a/src/Ai/Base/Value/ItemCountValue.h +++ b/src/Ai/Base/Value/ItemCountValue.h @@ -17,10 +17,7 @@ class InventoryItemValueBase : public InventoryAction public: InventoryItemValueBase(PlayerbotAI* botAI) : InventoryAction(botAI, "empty") {} - bool Execute(Event event) override { return false; } - -protected: - std::vector Find(std::string const qualifier); + bool Execute(Event) override { return false; } }; class ItemCountValue : public Uint32CalculatedValue, public Qualified, InventoryItemValueBase diff --git a/src/Ai/Base/Value/ItemUsageValue.cpp b/src/Ai/Base/Value/ItemUsageValue.cpp index 25866c8059..b0dcddb706 100644 --- a/src/Ai/Base/Value/ItemUsageValue.cpp +++ b/src/Ai/Base/Value/ItemUsageValue.cpp @@ -56,7 +56,7 @@ ItemUsage ItemUsageValue::Calculate() if (proto->Class == ITEM_CLASS_TRADE_GOODS || proto->Class == ITEM_CLASS_MISC || proto->Class == ITEM_CLASS_REAGENT) - needItem = IsItemNeededForUsefullSpell(proto, lowBagSpace); + needItem = IsItemNeededForUsefullSpell(*proto, lowBagSpace); else if (proto->Class == ITEM_CLASS_RECIPE) { if (bot->HasSpell(proto->Spells[2].SpellId)) @@ -79,8 +79,10 @@ ItemUsage ItemUsageValue::Calculate() if (proto->Class == ITEM_CLASS_KEY) return ITEM_USAGE_USE; + const uint32_t maxCount = proto->MaxCount; + if (proto->Class == ITEM_CLASS_CONSUMABLE && - (proto->MaxCount == 0 || bot->GetItemCount(itemId, false) < proto->MaxCount)) + (maxCount == 0 || bot->GetItemCount(itemId, false) < maxCount)) { std::string const foodType = GetConsumableType(proto, bot->GetPower(POWER_MANA)); @@ -99,7 +101,7 @@ ItemUsage ItemUsageValue::Calculate() } } - if (bot->GetGuildId() && sGuildTaskMgr->IsGuildTaskItem(itemId, bot->GetGuildId())) + if (bot->GetGuildId() && GuildTaskMgr::instance().IsGuildTaskItem(itemId, bot->GetGuildId())) return ITEM_USAGE_GUILD_TASK; ItemUsage equip = QueryItemUsageForEquip(proto, randomPropertyId); @@ -129,7 +131,7 @@ ItemUsage ItemUsageValue::Calculate() Player* master = botAI->GetMaster(); bool isSelfBot = (master == bot); bool botNeedsItemForQuest = IsItemUsefulForQuest(bot, proto); - bool masterNeedsItemForQuest = master && sPlayerbotAIConfig->syncQuestWithPlayer && IsItemUsefulForQuest(master, proto); + bool masterNeedsItemForQuest = master && sPlayerbotAIConfig.syncQuestWithPlayer && IsItemUsefulForQuest(master, proto); // Identify the source of loot LootObject lootObject = AI_VALUE(LootObject, "loot target"); @@ -304,7 +306,7 @@ ItemUsage ItemUsageValue::QueryItemUsageForEquip(ItemTemplate const* itemProto, } bool shouldEquip = false; - // uint32 statWeight = sRandomItemMgr->GetLiveStatWeight(bot, itemProto->ItemId); + // uint32 statWeight = sRandomItemMgr.GetLiveStatWeight(bot, itemProto->ItemId); StatsWeightCalculator calculator(bot); calculator.SetItemSetBonus(false); calculator.SetOverflowPenalty(false); @@ -314,10 +316,10 @@ ItemUsage ItemUsageValue::QueryItemUsageForEquip(ItemTemplate const* itemProto, if (itemScore) shouldEquip = true; - if (itemProto->Class == ITEM_CLASS_WEAPON && !sRandomItemMgr->CanEquipWeapon(bot->getClass(), itemProto)) + if (itemProto->Class == ITEM_CLASS_WEAPON && !sRandomItemMgr.CanEquipWeapon(bot->getClass(), itemProto)) shouldEquip = false; if (itemProto->Class == ITEM_CLASS_ARMOR && - !sRandomItemMgr->CanEquipArmor(bot->getClass(), bot->GetLevel(), itemProto)) + !sRandomItemMgr.CanEquipArmor(bot->getClass(), bot->GetLevel(), itemProto)) shouldEquip = false; uint8 possibleSlots = 1; @@ -396,10 +398,10 @@ ItemUsage ItemUsageValue::QueryItemUsageForEquip(ItemTemplate const* itemProto, float oldScore = calculator.CalculateItem(oldItemProto->ItemId, oldItem->GetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID)); if (oldItem) { - // uint32 oldStatWeight = sRandomItemMgr->GetLiveStatWeight(bot, oldItemProto->ItemId); + // uint32 oldStatWeight = sRandomItemMgr.GetLiveStatWeight(bot, oldItemProto->ItemId); if (itemScore || oldScore) { - shouldEquipInSlot = itemScore > oldScore * sPlayerbotAIConfig->equipUpgradeThreshold; + shouldEquipInSlot = itemScore > oldScore * sPlayerbotAIConfig.equipUpgradeThreshold; } } @@ -417,15 +419,15 @@ ItemUsage ItemUsageValue::QueryItemUsageForEquip(ItemTemplate const* itemProto, } bool existingShouldEquip = true; - if (oldItemProto->Class == ITEM_CLASS_WEAPON && !sRandomItemMgr->CanEquipWeapon(bot->getClass(), oldItemProto)) + if (oldItemProto->Class == ITEM_CLASS_WEAPON && !sRandomItemMgr.CanEquipWeapon(bot->getClass(), oldItemProto)) existingShouldEquip = false; if (oldItemProto->Class == ITEM_CLASS_ARMOR && - !sRandomItemMgr->CanEquipArmor(bot->getClass(), bot->GetLevel(), oldItemProto)) + !sRandomItemMgr.CanEquipArmor(bot->getClass(), bot->GetLevel(), oldItemProto)) existingShouldEquip = false; - // uint32 oldItemPower = sRandomItemMgr->GetLiveStatWeight(bot, oldItemProto->ItemId); - // uint32 newItemPower = sRandomItemMgr->GetLiveStatWeight(bot, itemProto->ItemId); + // uint32 oldItemPower = sRandomItemMgr.GetLiveStatWeight(bot, oldItemProto->ItemId); + // uint32 newItemPower = sRandomItemMgr.GetLiveStatWeight(bot, itemProto->ItemId); // Compare items based on item level, quality or itemId. bool isBetter = false; @@ -695,57 +697,86 @@ bool ItemUsageValue::IsItemUsefulForSkill(ItemTemplate const* proto) return false; } -bool ItemUsageValue::IsItemNeededForUsefullSpell(ItemTemplate const* proto, bool checkAllReagents) +bool ItemUsageValue::IsItemNeededForUsefullSpell(const ItemTemplate& itemTemplate, bool checkAllReagents) const { - for (auto spellId : SpellsUsingItem(proto->ItemId, bot)) + for (uint32_t spellId : SpellsUsingItem(itemTemplate.ItemId, bot)) { - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); - if (!spellInfo) + const SpellInfo* const spellInfo = SpellMgr::instance()->GetSpellInfo(spellId); + + if (spellInfo == nullptr) + { continue; + } - if (checkAllReagents && !HasItemsNeededForSpell(spellId, proto)) + if (checkAllReagents && !this->HasItemsNeededForSpell(spellId, itemTemplate)) + { continue; + } - if (SpellGivesSkillUp(spellId, bot)) + if (this->SpellGivesSkillUp(spellId, bot)) + { return true; + } - uint32 newItemId = spellInfo->Effects[EFFECT_0].ItemType; - if (newItemId && newItemId != proto->ItemId) + const uint32_t newItemId = spellInfo->Effects[EFFECT_0].ItemType; + + if (newItemId == 0 || newItemId == itemTemplate.ItemId) { - ItemUsage usage = AI_VALUE2(ItemUsage, "item usage", newItemId); + continue; + } - if (usage != ITEM_USAGE_REPLACE && usage != ITEM_USAGE_EQUIP && usage != ITEM_USAGE_AMMO && - usage != ITEM_USAGE_QUEST && usage != ITEM_USAGE_SKILL && usage != ITEM_USAGE_USE) - continue; + const ItemUsage usage = this->context->GetValue("item usage", newItemId)->Get(); - return true; + if (usage != ITEM_USAGE_REPLACE + && usage != ITEM_USAGE_EQUIP + && usage != ITEM_USAGE_AMMO + && usage != ITEM_USAGE_QUEST + && usage != ITEM_USAGE_SKILL + && usage != ITEM_USAGE_USE + ) + { + continue; } + + return true; } return false; } -bool ItemUsageValue::HasItemsNeededForSpell(uint32 spellId, ItemTemplate const* proto) +bool ItemUsageValue::HasItemsNeededForSpell(uint32_t spellId, const ItemTemplate& itemTemplate) const { - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); - if (!spellInfo) + const SpellInfo* const spellInfo = SpellMgr::instance()->GetSpellInfo(spellId); + + if (spellInfo == nullptr) + { return false; + } - for (uint8 i = 0; i < MAX_SPELL_REAGENTS; i++) - if (spellInfo->ReagentCount[i] > 0 && spellInfo->Reagent[i]) + for (uint8_t i = 0; i < MAX_SPELL_REAGENTS; i++) + { + if (spellInfo->ReagentCount[i] < 1 || spellInfo->Reagent[i] == 0) { - if (proto && proto->ItemId == spellInfo->Reagent[i] && - spellInfo->ReagentCount[i] == 1) // If we only need 1 item then current item does not need to be - // checked since we are looting/buying or already have it. - continue; + continue; + } + + const int64_t itemTemplateId = itemTemplate.ItemId; - ItemTemplate const* reqProto = sObjectMgr->GetItemTemplate(spellInfo->Reagent[i]); + // If we only need 1 item then current item does not need to be + // checked since we are looting/buying or already have it. + if (itemTemplateId == spellInfo->Reagent[i] && spellInfo->ReagentCount[i] == 1) + { + continue; + } - uint32 count = AI_VALUE2(uint32, "item count", reqProto->Name1); + const ItemTemplate* const requiredItemTemplate = ObjectMgr::instance()->GetItemTemplate(spellInfo->Reagent[i]); + const uint32_t count = this->context->GetValue("item count", requiredItemTemplate->Name1)->Get(); - if (count < spellInfo->ReagentCount[i]) - return false; + if (count < spellInfo->ReagentCount[i]) + { + return false; } + } return true; } @@ -809,7 +840,7 @@ float ItemUsageValue::BetterStacks(ItemTemplate const* proto, std::string const return stacks; } -std::vector ItemUsageValue::SpellsUsingItem(uint32 itemId, Player* bot) +std::vector ItemUsageValue::SpellsUsingItem(int64_t itemId, Player* bot) { std::vector retSpells; @@ -854,23 +885,27 @@ inline int32 SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLe return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_ORANGE) * 10; } -bool ItemUsageValue::SpellGivesSkillUp(uint32 spellId, Player* bot) +bool ItemUsageValue::SpellGivesSkillUp(const uint32_t spellId, const Player* const bot) { - SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellId); + const SkillLineAbilityMapBounds bounds = SpellMgr::instance()->GetSkillLineAbilityMapBounds(spellId); - for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx) + for (SkillLineAbilityMap::const_iterator spellIterator = bounds.first; spellIterator != bounds.second; ++spellIterator) { - SkillLineAbilityEntry const* skill = _spell_idx->second; - if (skill->SkillLine) + const SkillLineAbilityEntry* const skill = spellIterator->second; + + if (skill->SkillLine == 0) { - uint32 SkillValue = bot->GetPureSkillValue(skill->SkillLine); + continue; + } - uint32 craft_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_CRAFTING); + const uint32_t SkillValue = bot->GetPureSkillValue(skill->SkillLine); - if (SkillGainChance(SkillValue, skill->TrivialSkillLineRankHigh, - (skill->TrivialSkillLineRankHigh + skill->TrivialSkillLineRankLow) / 2, - skill->TrivialSkillLineRankLow) > 0) - return true; + if (SkillGainChance(SkillValue, skill->TrivialSkillLineRankHigh, + (skill->TrivialSkillLineRankHigh + skill->TrivialSkillLineRankLow) / 2, + skill->TrivialSkillLineRankLow) > 0 + ) + { + return true; } } diff --git a/src/Ai/Base/Value/ItemUsageValue.h b/src/Ai/Base/Value/ItemUsageValue.h index d50ea1b060..27cc724b72 100644 --- a/src/Ai/Base/Value/ItemUsageValue.h +++ b/src/Ai/Base/Value/ItemUsageValue.h @@ -48,15 +48,15 @@ class ItemUsageValue : public CalculatedValue, public Qualified bool IsItemUsefulForQuest(Player* player, ItemTemplate const* proto); bool IsItemNeededForSkill(ItemTemplate const* proto); bool IsItemUsefulForSkill(ItemTemplate const* proto); - bool IsItemNeededForUsefullSpell(ItemTemplate const* proto, bool checkAllReagents = false); - bool HasItemsNeededForSpell(uint32 spellId, ItemTemplate const* proto); + bool IsItemNeededForUsefullSpell(const ItemTemplate& proto, bool checkAllReagents = false) const; + bool HasItemsNeededForSpell(uint32_t spellId, const ItemTemplate& proto) const; Item* CurrentItem(ItemTemplate const* proto); float CurrentStacks(ItemTemplate const* proto); float BetterStacks(ItemTemplate const* proto, std::string const usageType = ""); public: - static std::vector SpellsUsingItem(uint32 itemId, Player* bot); - static bool SpellGivesSkillUp(uint32 spellId, Player* bot); + static std::vector SpellsUsingItem(int64_t itemId, Player* bot); + static bool SpellGivesSkillUp(const uint32_t spellId, const Player* const bot); static std::string const GetConsumableType(ItemTemplate const* proto, bool hasMana); }; diff --git a/src/Ai/Base/Value/LastMovementValue.cpp b/src/Ai/Base/Value/LastMovementValue.cpp index ba54020e39..34f554616a 100644 --- a/src/Ai/Base/Value/LastMovementValue.cpp +++ b/src/Ai/Base/Value/LastMovementValue.cpp @@ -5,7 +5,6 @@ #include "LastMovementValue.h" -#include "Playerbots.h" #include "Timer.h" LastMovement::LastMovement() { clear(); } @@ -15,11 +14,11 @@ LastMovement::LastMovement(LastMovement& other) taxiMaster(other.taxiMaster), lastFollow(other.lastFollow), lastAreaTrigger(other.lastAreaTrigger), + lastFlee(other.lastFlee), lastMoveToX(other.lastMoveToX), lastMoveToY(other.lastMoveToY), lastMoveToZ(other.lastMoveToZ), - lastMoveToOri(other.lastMoveToOri), - lastFlee(other.lastFlee) + lastMoveToOri(other.lastMoveToOri) { lastMoveShort = other.lastMoveShort; nextTeleport = other.nextTeleport; diff --git a/src/Ai/Base/Value/LeastHpTargetValue.cpp b/src/Ai/Base/Value/LeastHpTargetValue.cpp index 8b9f1a55fc..04b3fcefff 100644 --- a/src/Ai/Base/Value/LeastHpTargetValue.cpp +++ b/src/Ai/Base/Value/LeastHpTargetValue.cpp @@ -6,16 +6,14 @@ #include "LeastHpTargetValue.h" #include "AttackersValue.h" -#include "Playerbots.h" class FindLeastHpTargetStrategy : public FindNonCcTargetStrategy { public: FindLeastHpTargetStrategy(PlayerbotAI* botAI) : FindNonCcTargetStrategy(botAI), minHealth(0) {} - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { - Player* bot = botAI->GetBot(); if (IsCcTarget(attacker)) return; @@ -30,5 +28,6 @@ class FindLeastHpTargetStrategy : public FindNonCcTargetStrategy Unit* LeastHpTargetValue::Calculate() { FindLeastHpTargetStrategy strategy(botAI); + return FindTarget(&strategy); } diff --git a/src/Ai/Base/Value/LogLevelValue.h b/src/Ai/Base/Value/LogLevelValue.h index 18fdbddcee..f8515b13b2 100644 --- a/src/Ai/Base/Value/LogLevelValue.h +++ b/src/Ai/Base/Value/LogLevelValue.h @@ -6,6 +6,7 @@ #ifndef _PLAYERBOT_LOGLEVELVALUE_H #define _PLAYERBOT_LOGLEVELVALUE_H +#include "LogCommon.h" #include "Value.h" class PlayerbotAI; diff --git a/src/Ai/Base/Value/LootStrategyValue.cpp b/src/Ai/Base/Value/LootStrategyValue.cpp index 6a4f9b9b48..0ff6f7e98b 100644 --- a/src/Ai/Base/Value/LootStrategyValue.cpp +++ b/src/Ai/Base/Value/LootStrategyValue.cpp @@ -60,7 +60,7 @@ class DisenchantLootStrategy : public NormalLootStrategy class AllLootStrategy : public LootStrategy { public: - bool CanLoot(ItemTemplate const* proto, AiObjectContext* context) override { return true; } + bool CanLoot(ItemTemplate const*, AiObjectContext*) override { return true; } std::string const GetName() override { return "all"; } }; diff --git a/src/Ai/Base/Value/NearestAdsValue.h b/src/Ai/Base/Value/NearestAdsValue.h index 312d5596eb..b9e3fbe316 100644 --- a/src/Ai/Base/Value/NearestAdsValue.h +++ b/src/Ai/Base/Value/NearestAdsValue.h @@ -14,7 +14,7 @@ class PlayerbotAI; class NearestAddsValue : public PossibleTargetsValue { public: - NearestAddsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->tooCloseDistance) + NearestAddsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.tooCloseDistance) : PossibleTargetsValue(botAI, "nearest adds", range, true) { } diff --git a/src/Ai/Base/Value/NearestCorpsesValue.cpp b/src/Ai/Base/Value/NearestCorpsesValue.cpp index fec1aed21f..3e049ea24d 100644 --- a/src/Ai/Base/Value/NearestCorpsesValue.cpp +++ b/src/Ai/Base/Value/NearestCorpsesValue.cpp @@ -5,28 +5,30 @@ #include "NearestCorpsesValue.h" -#include "CellImpl.h" #include "GridNotifiers.h" +// Required due to +#include "CellImpl.h" #include "GridNotifiersImpl.h" -#include "Playerbots.h" class AnyDeadUnitInObjectRangeCheck { public: - AnyDeadUnitInObjectRangeCheck(WorldObject const* obj, float range) : i_obj(obj), i_range(range) {} + AnyDeadUnitInObjectRangeCheck(WorldObject const* obj) : i_obj(obj) {} WorldObject const& GetFocusObject() const { return *i_obj; } bool operator()(Unit* u) { return !u->IsAlive(); } private: WorldObject const* i_obj; - float i_range; }; void NearestCorpsesValue::FindUnits(std::list& targets) { - AnyDeadUnitInObjectRangeCheck u_check(bot, range); + AnyDeadUnitInObjectRangeCheck u_check(bot); Acore::UnitListSearcher searcher(bot, targets, u_check); Cell::VisitObjects(bot, searcher, range); } -bool NearestCorpsesValue::AcceptUnit(Unit* unit) { return true; } +bool NearestCorpsesValue::AcceptUnit(Unit*) +{ + return true; +} diff --git a/src/Ai/Base/Value/NearestCorpsesValue.h b/src/Ai/Base/Value/NearestCorpsesValue.h index 4c0716e299..f6a067c3fe 100644 --- a/src/Ai/Base/Value/NearestCorpsesValue.h +++ b/src/Ai/Base/Value/NearestCorpsesValue.h @@ -14,7 +14,7 @@ class PlayerbotAI; class NearestCorpsesValue : public NearestUnitsValue { public: - NearestCorpsesValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + NearestCorpsesValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : NearestUnitsValue(botAI, "nearest corpses", range, true) { } diff --git a/src/Ai/Base/Value/NearestFriendlyPlayersValue.h b/src/Ai/Base/Value/NearestFriendlyPlayersValue.h index 9876316929..2588409044 100644 --- a/src/Ai/Base/Value/NearestFriendlyPlayersValue.h +++ b/src/Ai/Base/Value/NearestFriendlyPlayersValue.h @@ -14,7 +14,7 @@ class PlayerbotAI; class NearestFriendlyPlayersValue : public NearestUnitsValue { public: - NearestFriendlyPlayersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + NearestFriendlyPlayersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : NearestUnitsValue(botAI, "nearest friendly players", range) { } diff --git a/src/Ai/Base/Value/NearestGameObjects.h b/src/Ai/Base/Value/NearestGameObjects.h index 2018e93eb1..9d1153aade 100644 --- a/src/Ai/Base/Value/NearestGameObjects.h +++ b/src/Ai/Base/Value/NearestGameObjects.h @@ -33,7 +33,7 @@ class AnyGameObjectInObjectRangeCheck class NearestGameObjects : public ObjectGuidListCalculatedValue { public: - NearestGameObjects(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance, bool ignoreLos = false, + NearestGameObjects(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance, bool ignoreLos = false, std::string const name = "nearest game objects") : ObjectGuidListCalculatedValue(botAI, name, 1 * 1000), range(range), ignoreLos(ignoreLos) { diff --git a/src/Ai/Base/Value/NearestNonBotPlayersValue.h b/src/Ai/Base/Value/NearestNonBotPlayersValue.h index 73d522c5fb..1980bcf2ba 100644 --- a/src/Ai/Base/Value/NearestNonBotPlayersValue.h +++ b/src/Ai/Base/Value/NearestNonBotPlayersValue.h @@ -14,7 +14,7 @@ class PlayerbotAI; class NearestNonBotPlayersValue : public NearestUnitsValue { public: - NearestNonBotPlayersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->grindDistance) + NearestNonBotPlayersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.grindDistance) : NearestUnitsValue(botAI, "nearest non bot players", range, true) { } diff --git a/src/Ai/Base/Value/NearestNpcsValue.h b/src/Ai/Base/Value/NearestNpcsValue.h index 6935026147..71e1d9de45 100644 --- a/src/Ai/Base/Value/NearestNpcsValue.h +++ b/src/Ai/Base/Value/NearestNpcsValue.h @@ -14,7 +14,7 @@ class PlayerbotAI; class NearestNpcsValue : public NearestUnitsValue { public: - NearestNpcsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + NearestNpcsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : NearestUnitsValue(botAI, "nearest npcs", range) { } @@ -27,7 +27,7 @@ class NearestNpcsValue : public NearestUnitsValue class NearestHostileNpcsValue : public NearestUnitsValue { public: - NearestHostileNpcsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + NearestHostileNpcsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : NearestUnitsValue(botAI, "nearest hostile npcs", range) { } @@ -40,7 +40,7 @@ class NearestHostileNpcsValue : public NearestUnitsValue class NearestVehiclesValue : public NearestUnitsValue { public: - NearestVehiclesValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + NearestVehiclesValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : NearestUnitsValue(botAI, "nearest vehicles", range) { } @@ -53,7 +53,7 @@ class NearestVehiclesValue : public NearestUnitsValue class NearestTriggersValue : public NearestUnitsValue { public: - NearestTriggersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + NearestTriggersValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : NearestUnitsValue(botAI, "nearest triggers", range) { } diff --git a/src/Ai/Base/Value/NearestUnitsValue.h b/src/Ai/Base/Value/NearestUnitsValue.h index 527925a0d7..5e00cb6d09 100644 --- a/src/Ai/Base/Value/NearestUnitsValue.h +++ b/src/Ai/Base/Value/NearestUnitsValue.h @@ -16,7 +16,7 @@ class NearestUnitsValue : public ObjectGuidListCalculatedValue { public: NearestUnitsValue(PlayerbotAI* botAI, std::string const name = "nearest units", - float range = sPlayerbotAIConfig->sightDistance, bool ignoreLos = false, uint32 checkInterval = 1) + float range = sPlayerbotAIConfig.sightDistance, bool ignoreLos = false, uint32 checkInterval = 1) : ObjectGuidListCalculatedValue(botAI, name, checkInterval), range(range), ignoreLos(ignoreLos) { } diff --git a/src/Ai/Base/Value/PartyMemberToDispel.cpp b/src/Ai/Base/Value/PartyMemberToDispel.cpp index 91b1955b27..d578052c10 100644 --- a/src/Ai/Base/Value/PartyMemberToDispel.cpp +++ b/src/Ai/Base/Value/PartyMemberToDispel.cpp @@ -4,14 +4,14 @@ */ #include "PartyMemberToDispel.h" +#include "PlayerbotAI.h" -#include "Playerbots.h" class PartyMemberToDispelPredicate : public FindPlayerPredicate, public PlayerbotAIAware { public: PartyMemberToDispelPredicate(PlayerbotAI* botAI, uint32 dispelType) - : PlayerbotAIAware(botAI), FindPlayerPredicate(), dispelType(dispelType) + : FindPlayerPredicate(), PlayerbotAIAware(botAI), dispelType(dispelType) { } diff --git a/src/Ai/Base/Value/PartyMemberToHeal.cpp b/src/Ai/Base/Value/PartyMemberToHeal.cpp index 47554c7c2b..b49c1cd419 100644 --- a/src/Ai/Base/Value/PartyMemberToHeal.cpp +++ b/src/Ai/Base/Value/PartyMemberToHeal.cpp @@ -46,10 +46,10 @@ Unit* PartyMemberToHeal::Calculate() if (player && player->IsAlive()) { uint8 health = player->GetHealthPct(); - if (isRaid || health < sPlayerbotAIConfig->mediumHealth || !IsTargetOfSpellCast(player, predicate)) + if (isRaid || health < sPlayerbotAIConfig.mediumHealth || !IsTargetOfSpellCast(player, predicate)) { uint32 probeValue = 100; - if (player->GetDistance2d(bot) > sPlayerbotAIConfig->healDistance) + if (player->GetDistance2d(bot) > sPlayerbotAIConfig.healDistance) { probeValue = health + 30; } @@ -70,7 +70,7 @@ Unit* PartyMemberToHeal::Calculate() { uint8 health = ((Unit*)pet)->GetHealthPct(); uint32 probeValue = 100; - if (isRaid || health < sPlayerbotAIConfig->mediumHealth) + if (isRaid || health < sPlayerbotAIConfig.mediumHealth) probeValue = health + 30; // delay Check pet to here for better performance if (probeValue < calc.minValue && Check(pet)) @@ -84,7 +84,7 @@ Unit* PartyMemberToHeal::Calculate() { uint8 health = charm->GetHealthPct(); uint32 probeValue = 100; - if (isRaid || health < sPlayerbotAIConfig->mediumHealth) + if (isRaid || health < sPlayerbotAIConfig.mediumHealth) probeValue = health + 30; // delay Check charm to here for better performance if (probeValue < calc.minValue && Check(charm)) @@ -99,10 +99,10 @@ Unit* PartyMemberToHeal::Calculate() bool PartyMemberToHeal::Check(Unit* player) { // return player && player != bot && player->GetMapId() == bot->GetMapId() && player->IsInWorld() && - // sServerFacade->GetDistance2d(bot, player) < (player->IsPlayer() && botAI->IsTank((Player*)player) ? 50.0f + // ServerFacade::instance().GetDistance2d(bot, player) < (player->IsPlayer() && botAI->IsTank((Player*)player) ? 50.0f // : 40.0f); return player->GetMapId() == bot->GetMapId() && !player->IsCharmed() && - bot->GetDistance2d(player) < sPlayerbotAIConfig->healDistance * 2 && bot->IsWithinLOSInMap(player); + bot->GetDistance2d(player) < sPlayerbotAIConfig.healDistance * 2 && bot->IsWithinLOSInMap(player); } Unit* PartyMemberToProtect::Calculate() @@ -129,7 +129,7 @@ Unit* PartyMemberToProtect::Calculate() continue; float attackDistance = 30.0f; - if (sServerFacade->GetDistance2d(pVictim, unit) > attackDistance) + if (ServerFacade::instance().GetDistance2d(pVictim, unit) > attackDistance) continue; if (botAI->IsTank((Player*)pVictim) && pVictim->GetHealthPct() > 10) diff --git a/src/Ai/Base/Value/PartyMemberValue.cpp b/src/Ai/Base/Value/PartyMemberValue.cpp index 4ae9be08ad..37602c02d1 100644 --- a/src/Ai/Base/Value/PartyMemberValue.cpp +++ b/src/Ai/Base/Value/PartyMemberValue.cpp @@ -4,9 +4,13 @@ */ #include "PartyMemberValue.h" +#include "Corpse.h" -#include "Playerbots.h" +#include "Group.h" +#include "PlayerbotAI.h" #include "ServerFacade.h" +#include "Pet.h" +#include "Spell.h" Unit* PartyMemberValue::FindPartyMember(std::vector* party, FindPlayerPredicate& predicate) { @@ -23,7 +27,7 @@ Unit* PartyMemberValue::FindPartyMember(std::vector* party, FindPlayerP return nullptr; } -Unit* PartyMemberValue::FindPartyMember(FindPlayerPredicate& predicate, bool ignoreOutOfGroup) +Unit* PartyMemberValue::FindPartyMember(FindPlayerPredicate& predicate, bool) { Player* master = GetMaster(); // GuidVector nearestPlayers; @@ -102,10 +106,10 @@ Unit* PartyMemberValue::FindPartyMember(FindPlayerPredicate& predicate, bool ign bool PartyMemberValue::Check(Unit* player) { // return player && player != bot && player->GetMapId() == bot->GetMapId() && bot->IsWithinDistInMap(player, - // sPlayerbotAIConfig->sightDistance, false); + // sPlayerbotAIConfig.sightDistance, false); bool isGM = player->ToPlayer() && player->ToPlayer()->IsGameMaster(); return player && player->GetMapId() == bot->GetMapId() && !isGM && - bot->GetDistance(player) < sPlayerbotAIConfig->spellDistance * 2 && + bot->GetDistance(player) < sPlayerbotAIConfig.spellDistance * 2 && bot->IsWithinLOS(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); } diff --git a/src/Ai/Base/Value/PartyMemberWithoutAuraValue.cpp b/src/Ai/Base/Value/PartyMemberWithoutAuraValue.cpp index f195a899bd..e9b181d791 100644 --- a/src/Ai/Base/Value/PartyMemberWithoutAuraValue.cpp +++ b/src/Ai/Base/Value/PartyMemberWithoutAuraValue.cpp @@ -13,7 +13,7 @@ class PlayerWithoutAuraPredicate : public FindPlayerPredicate, public PlayerbotA { public: PlayerWithoutAuraPredicate(PlayerbotAI* botAI, std::string const aura) - : PlayerbotAIAware(botAI), FindPlayerPredicate(), auras(split(aura, ',')) + : FindPlayerPredicate(), PlayerbotAIAware(botAI), auras(split(aura, ',')) { } diff --git a/src/Ai/Base/Value/PartyMemberWithoutAuraValue.h b/src/Ai/Base/Value/PartyMemberWithoutAuraValue.h index 57bb958c76..6d95a31313 100644 --- a/src/Ai/Base/Value/PartyMemberWithoutAuraValue.h +++ b/src/Ai/Base/Value/PartyMemberWithoutAuraValue.h @@ -8,7 +8,6 @@ #include "NamedObjectContext.h" #include "PartyMemberValue.h" -#include "PlayerbotAIConfig.h" class PlayerbotAI; class Unit; @@ -16,8 +15,7 @@ class Unit; class PartyMemberWithoutAuraValue : public PartyMemberValue, public Qualified { public: - PartyMemberWithoutAuraValue(PlayerbotAI* botAI, std::string const name = "party member without aura", - float range = sPlayerbotAIConfig->sightDistance) + PartyMemberWithoutAuraValue(PlayerbotAI* botAI, std::string const name = "party member without aura") : PartyMemberValue(botAI, name) { } diff --git a/src/Ai/Base/Value/PartyMemberWithoutItemValue.cpp b/src/Ai/Base/Value/PartyMemberWithoutItemValue.cpp index c9136c61a5..fe8032a459 100644 --- a/src/Ai/Base/Value/PartyMemberWithoutItemValue.cpp +++ b/src/Ai/Base/Value/PartyMemberWithoutItemValue.cpp @@ -11,7 +11,7 @@ class PlayerWithoutItemPredicate : public FindPlayerPredicate, public PlayerbotA { public: PlayerWithoutItemPredicate(PlayerbotAI* botAI, std::string const item) - : PlayerbotAIAware(botAI), FindPlayerPredicate(), item(item) + : FindPlayerPredicate(), PlayerbotAIAware(botAI), item(item) { } diff --git a/src/Ai/Base/Value/PartyMemberWithoutItemValue.h b/src/Ai/Base/Value/PartyMemberWithoutItemValue.h index 9ca128ff8d..379835543e 100644 --- a/src/Ai/Base/Value/PartyMemberWithoutItemValue.h +++ b/src/Ai/Base/Value/PartyMemberWithoutItemValue.h @@ -8,7 +8,6 @@ #include "NamedObjectContext.h" #include "PartyMemberValue.h" -#include "PlayerbotAIConfig.h" class PlayerbotAI; class Unit; @@ -16,8 +15,7 @@ class Unit; class PartyMemberWithoutItemValue : public PartyMemberValue, public Qualified { public: - PartyMemberWithoutItemValue(PlayerbotAI* botAI, std::string const name = "party member without item", - float range = sPlayerbotAIConfig->farDistance) + PartyMemberWithoutItemValue(PlayerbotAI* botAI, std::string const name = "party member without item") : PartyMemberValue(botAI, name) { } diff --git a/src/Ai/Base/Value/PositionValue.h b/src/Ai/Base/Value/PositionValue.h index 69e8e35943..9e613e1398 100644 --- a/src/Ai/Base/Value/PositionValue.h +++ b/src/Ai/Base/Value/PositionValue.h @@ -20,10 +20,12 @@ class PositionInfo : x(x), y(y), z(z), mapId(mapId), valueSet(valueSet) { } - PositionInfo(PositionInfo const& other) - : x(other.x), y(other.y), z(other.z), mapId(other.mapId), valueSet(other.valueSet) - { - } + + PositionInfo(PositionInfo const& other) = default; + PositionInfo& operator=(PositionInfo const& other) = default; + + PositionInfo(PositionInfo&& other) = default; + PositionInfo& operator=(PositionInfo&& other) = default; void Set(float newX, float newY, float newZ, uint32 newMapId) { @@ -71,7 +73,7 @@ class CurrentPositionValue : public LogCalculatedValue bool EqualToLast(WorldPosition value) override { - return value.fDist(lastValue) < sPlayerbotAIConfig->tooCloseDistance; + return value.fDist(lastValue) < sPlayerbotAIConfig.tooCloseDistance; } WorldPosition Calculate() override; diff --git a/src/Ai/Base/Value/PossibleRpgTargetsValue.cpp b/src/Ai/Base/Value/PossibleRpgTargetsValue.cpp index e9b79debf8..e0695e825d 100644 --- a/src/Ai/Base/Value/PossibleRpgTargetsValue.cpp +++ b/src/Ai/Base/Value/PossibleRpgTargetsValue.cpp @@ -5,14 +5,16 @@ #include "PossibleRpgTargetsValue.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "AiObjectContext.h" #include "ObjectGuid.h" -#include "Playerbots.h" #include "ServerFacade.h" #include "SharedDefines.h" #include "NearestGameObjects.h" +#include "GridNotifiers.h" +// Required due to a poor implementation by AC +#include "GridNotifiersImpl.h" +#include "CellImpl.h" +#include "TravelMgr.h" std::vector PossibleRpgTargetsValue::allowedNpcFlags; @@ -60,7 +62,7 @@ bool PossibleRpgTargetsValue::AcceptUnit(Unit* unit) if (unit->IsHostileTo(bot) || unit->IsPlayer()) return false; - if (sServerFacade->GetDistance2d(bot, unit) <= sPlayerbotAIConfig->tooCloseDistance) + if (ServerFacade::instance().GetDistance2d(bot, unit) <= sPlayerbotAIConfig.tooCloseDistance) return false; if (unit->HasNpcFlag(UNIT_NPC_FLAG_SPIRITHEALER)) @@ -73,9 +75,16 @@ bool PossibleRpgTargetsValue::AcceptUnit(Unit* unit) } TravelTarget* travelTarget = context->GetValue("travel target")->Get(); - if (travelTarget && travelTarget->getDestination() && - travelTarget->getDestination()->getEntry() == unit->GetEntry()) + + + if ( + travelTarget != nullptr + && travelTarget->getDestination() + && (uint32_t)travelTarget->getDestination()->getEntry() == unit->GetEntry() + ) + { return true; + } if (urand(1, 100) < 25 && unit->IsFriendlyTo(bot)) return true; diff --git a/src/Ai/Base/Value/PossibleTargetsValue.h b/src/Ai/Base/Value/PossibleTargetsValue.h index 13023b3bcb..c710c2676b 100644 --- a/src/Ai/Base/Value/PossibleTargetsValue.h +++ b/src/Ai/Base/Value/PossibleTargetsValue.h @@ -15,7 +15,7 @@ class PossibleTargetsValue : public NearestUnitsValue { public: PossibleTargetsValue(PlayerbotAI* botAI, std::string const name = "possible targets", - float range = sPlayerbotAIConfig->sightDistance, bool ignoreLos = false) + float range = sPlayerbotAIConfig.sightDistance, bool ignoreLos = false) : NearestUnitsValue(botAI, name, range, ignoreLos) { } @@ -28,7 +28,7 @@ class PossibleTargetsValue : public NearestUnitsValue class AllTargetsValue : public PossibleTargetsValue { public: - AllTargetsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig->sightDistance) + AllTargetsValue(PlayerbotAI* botAI, float range = sPlayerbotAIConfig.sightDistance) : PossibleTargetsValue(botAI, "all targets", range, true) { } diff --git a/src/Ai/Base/Value/PvpValues.cpp b/src/Ai/Base/Value/PvpValues.cpp index e01b56ef2c..c89b4b9f37 100644 --- a/src/Ai/Base/Value/PvpValues.cpp +++ b/src/Ai/Base/Value/PvpValues.cpp @@ -5,77 +5,57 @@ #include "PvpValues.h" -#include "BattlegroundEY.h" #include "BattlegroundMgr.h" -#include "BattlegroundWS.h" +#include "AreaDefines.h" #include "Playerbots.h" #include "ServerFacade.h" -Unit* FlagCarrierValue::Calculate() +Player* FlagCarrierValue::GetBattlegroundFlagCarrier(Battleground& battleground) const { - Unit* carrier = nullptr; + const uint32_t mapId = battleground.GetMapId(); - if (botAI->GetBot()->InBattleground()) + if (mapId != MAP_WARSONG_GULCH && mapId != MAP_EYE_OF_THE_STORM) { - if (botAI->GetBot()->GetBattlegroundTypeId() == BattlegroundTypeId::BATTLEGROUND_WS) - { - BattlegroundWS* bg = (BattlegroundWS*)botAI->GetBot()->GetBattleground(); + return nullptr; + } - if (!bg) - return nullptr; - - if ((!sameTeam && bot->GetTeamId() == TEAM_HORDE || (sameTeam && bot->GetTeamId() == TEAM_ALLIANCE)) && - !bg->GetFlagPickerGUID(TEAM_HORDE).IsEmpty()) - carrier = ObjectAccessor::GetPlayer(bg->GetBgMap(), bg->GetFlagPickerGUID(TEAM_HORDE)); - - if ((!sameTeam && bot->GetTeamId() == TEAM_ALLIANCE || (sameTeam && bot->GetTeamId() == TEAM_HORDE)) && - !bg->GetFlagPickerGUID(TEAM_ALLIANCE).IsEmpty()) - carrier = ObjectAccessor::GetPlayer(bg->GetBgMap(), bg->GetFlagPickerGUID(TEAM_ALLIANCE)); - - if (carrier) - { - if (ignoreRange || bot->IsWithinDistInMap(carrier, sPlayerbotAIConfig->sightDistance)) - { - return carrier; - } - else - return nullptr; - } - } + const TeamId botTeamId = this->bot->GetTeamId(); + const TeamId opposedTeamId = botTeamId == TEAM_ALLIANCE ? TEAM_HORDE : TEAM_ALLIANCE; - if (botAI->GetBot()->GetBattlegroundTypeId() == BATTLEGROUND_EY) - { - BattlegroundEY* bg = (BattlegroundEY*)botAI->GetBot()->GetBattleground(); + TeamId flagCarrierTeamIdLookup = TEAM_NEUTRAL; - if (!bg) - return nullptr; - - if (bg->GetFlagPickerGUID().IsEmpty()) - return nullptr; - - Player* fc = ObjectAccessor::GetPlayer(bg->GetBgMap(), bg->GetFlagPickerGUID()); - if (!fc) - return nullptr; - - if (!sameTeam && (fc->GetTeamId() != bot->GetTeamId())) - carrier = fc; - - if (sameTeam && (fc->GetTeamId() == bot->GetTeamId())) - carrier = fc; - - if (carrier) - { - if (ignoreRange || bot->IsWithinDistInMap(carrier, sPlayerbotAIConfig->sightDistance)) - { - return carrier; - } - else - return nullptr; - } - } + if (mapId == MAP_WARSONG_GULCH) + { + flagCarrierTeamIdLookup = this->sameTeam ? botTeamId : opposedTeamId; + } + + const ObjectGuid& flagCarrierGUID = battleground.GetFlagPickerGUID(flagCarrierTeamIdLookup); + + if (flagCarrierGUID.IsEmpty()) + { + return nullptr; + } + + Player* const flagCarrier = ObjectAccessor::GetPlayer(battleground.GetBgMap(), flagCarrierGUID); + + if (flagCarrier == nullptr) + { + return nullptr; + } + + return flagCarrier; +} + +Unit* FlagCarrierValue::Calculate() +{ + Battleground* const battleground = this->bot->GetBattleground(); + + if (battleground == nullptr) + { + return nullptr; } - return carrier; + return this->GetBattlegroundFlagCarrier(*battleground); } std::vector BgMastersValue::Calculate() @@ -84,7 +64,7 @@ std::vector BgMastersValue::Calculate() std::vector entries; std::map>> battleMastersCache = - sRandomPlayerbotMgr->getBattleMastersCache(); + sRandomPlayerbotMgr.getBattleMastersCache(); entries.insert(entries.end(), battleMastersCache[TEAM_NEUTRAL][bgTypeId].begin(), battleMastersCache[TEAM_NEUTRAL][bgTypeId].end()); entries.insert(entries.end(), battleMastersCache[TEAM_ALLIANCE][bgTypeId].begin(), @@ -199,7 +179,7 @@ BattlegroundTypeId RpgBgTypeValue::Calculate() continue; std::map>> battleMastersCache = - sRandomPlayerbotMgr->getBattleMastersCache(); + sRandomPlayerbotMgr.getBattleMastersCache(); for (auto& entry : battleMastersCache[TEAM_NEUTRAL][bgTypeId]) if (entry == guidPosition.GetEntry()) diff --git a/src/Ai/Base/Value/PvpValues.h b/src/Ai/Base/Value/PvpValues.h index bad46b951b..734567c411 100644 --- a/src/Ai/Base/Value/PvpValues.h +++ b/src/Ai/Base/Value/PvpValues.h @@ -59,13 +59,20 @@ class RpgBgTypeValue : public CalculatedValue class FlagCarrierValue : public UnitCalculatedValue { public: - FlagCarrierValue(PlayerbotAI* botAI, bool sameTeam = false, bool ignoreRange = false) + FlagCarrierValue( + PlayerbotAI* botAI, + bool sameTeam = false, + bool ignoreRange = false + ) : UnitCalculatedValue(botAI), sameTeam(sameTeam), ignoreRange(ignoreRange) { } Unit* Calculate() override; +protected: + Player* GetBattlegroundFlagCarrier(Battleground& battleground) const; + private: bool sameTeam; bool ignoreRange; diff --git a/src/Ai/Base/Value/RtiTargetValue.cpp b/src/Ai/Base/Value/RtiTargetValue.cpp index 205bcc3db0..4240e91c76 100644 --- a/src/Ai/Base/Value/RtiTargetValue.cpp +++ b/src/Ai/Base/Value/RtiTargetValue.cpp @@ -60,8 +60,8 @@ Unit* RtiTargetValue::Calculate() Unit* unit = botAI->GetUnit(guid); if (!unit || unit->isDead() || !bot->IsWithinLOSInMap(unit) || !AttackersValue::IsValidTarget(unit, bot) || - sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(bot, unit), - sPlayerbotAIConfig->sightDistance)) + ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(bot, unit), + sPlayerbotAIConfig.sightDistance)) return nullptr; // Also prevent chasing raid icon targets that are too far away from the master, @@ -69,8 +69,8 @@ Unit* RtiTargetValue::Calculate() if (Player* master = botAI->GetMaster()) { if (master->IsInWorld() && master->GetMapId() == unit->GetMapId() && - sServerFacade->IsDistanceGreaterThan(sServerFacade->GetDistance2d(master, unit), - sPlayerbotAIConfig->sightDistance)) + ServerFacade::instance().IsDistanceGreaterThan(ServerFacade::instance().GetDistance2d(master, unit), + sPlayerbotAIConfig.sightDistance)) return nullptr; } diff --git a/src/Ai/Base/Value/SnareTargetValue.cpp b/src/Ai/Base/Value/SnareTargetValue.cpp index 96e958c2d8..76be6c35de 100644 --- a/src/Ai/Base/Value/SnareTargetValue.cpp +++ b/src/Ai/Base/Value/SnareTargetValue.cpp @@ -5,15 +5,15 @@ #include "SnareTargetValue.h" -#include "Playerbots.h" +#include "AiObjectContext.h" +#include "PlayerbotAI.h" #include "ServerFacade.h" Unit* SnareTargetValue::Calculate() { std::string const spell = qualifier; - GuidVector attackers = botAI->GetAiObjectContext()->GetValue("attackers")->Get(); - Unit* target = botAI->GetAiObjectContext()->GetValue("current target")->Get(); + GuidVector attackers = this->botAI->GetAiObjectContext()->GetValue("attackers")->Get(); for (ObjectGuid const guid : attackers) { Unit* unit = botAI->GetUnit(guid); @@ -30,7 +30,7 @@ Unit* SnareTargetValue::Calculate() return unit; case CHASE_MOTION_TYPE: { - chaseTarget = sServerFacade->GetChaseTarget(unit); + chaseTarget = ServerFacade::instance().GetChaseTarget(unit); if (!chaseTarget) continue; Player* chaseTargetPlayer = ObjectAccessor::FindPlayer(chaseTarget->GetGUID()); diff --git a/src/Ai/Base/Value/SpellIdValue.cpp b/src/Ai/Base/Value/SpellIdValue.cpp index 682c0b3ffd..909a3a3075 100644 --- a/src/Ai/Base/Value/SpellIdValue.cpp +++ b/src/Ai/Base/Value/SpellIdValue.cpp @@ -8,7 +8,6 @@ #include "ChatHelper.h" #include "Playerbots.h" #include "Vehicle.h" -#include "World.h" SpellIdValue::SpellIdValue(PlayerbotAI* botAI) : CalculatedValue(botAI, "spell id", 20 * 1000) {} @@ -31,7 +30,7 @@ uint32 SpellIdValue::Calculate() wstrToLower(wnamepart); char firstSymbol = tolower(namepart[0]); - int spellLength = wnamepart.length(); + size_t spellLength = wnamepart.length(); LocaleConstant loc = LOCALE_enUS; @@ -98,7 +97,7 @@ uint32 SpellIdValue::Calculate() return 0; int32 saveMana = (int32)round(AI_VALUE(double, "mana save level")); - uint32 rank = 1; + int32 rank = 1; uint32 highestRank = 0; uint32 highestSpellId = 0; uint32 lowestRank = 0; @@ -128,21 +127,23 @@ uint32 SpellIdValue::Calculate() // convert the remaining text to an integer int id = atoi(spellName.c_str()); - if (!id) + if (id < 1) { highestSpellId = spellId; continue; } - if (!highestRank || id > highestRank) + const uint32_t unsignedId = id; + + if (!highestRank || unsignedId > highestRank) { - highestRank = id; + highestRank = unsignedId; highestSpellId = spellId; } - if (!lowestRank || (lowestRank && id < lowestRank)) + if (!lowestRank || (lowestRank && unsignedId < lowestRank)) { - lowestRank = id; + lowestRank = unsignedId; lowestSpellId = spellId; } } @@ -193,7 +194,7 @@ uint32 VehicleSpellIdValue::Calculate() wstrToLower(wnamepart); char firstSymbol = tolower(namepart[0]); - int spellLength = wnamepart.length(); + size_t spellLength = wnamepart.length(); const int loc = LocaleConstant::LOCALE_enUS; diff --git a/src/Ai/Base/Value/Stances.cpp b/src/Ai/Base/Value/Stances.cpp index 2e7a18d2b9..81d9b285c5 100644 --- a/src/Ai/Base/Value/Stances.cpp +++ b/src/Ai/Base/Value/Stances.cpp @@ -48,7 +48,7 @@ WorldLocation Stance::GetNearLocation(float angle, float distance) WorldLocation MoveStance::GetLocationInternal() { Unit* target = GetTarget(); - float distance = std::max(sPlayerbotAIConfig->meleeDistance, target->GetCombatReach()); + float distance = std::max(sPlayerbotAIConfig.meleeDistance, target->GetCombatReach()); float angle = GetAngle(); return GetNearLocation(angle, distance); @@ -56,7 +56,7 @@ WorldLocation MoveStance::GetLocationInternal() std::string const Stance::GetTargetName() { return "current target"; } -float Stance::GetMaxDistance() { return sPlayerbotAIConfig->contactDistance; } +float Stance::GetMaxDistance() { return sPlayerbotAIConfig.contactDistance; } StanceValue::~StanceValue() { diff --git a/src/Ai/Base/Value/StatsValues.cpp b/src/Ai/Base/Value/StatsValues.cpp index dc3499c683..941750d3b4 100644 --- a/src/Ai/Base/Value/StatsValues.cpp +++ b/src/Ai/Base/Value/StatsValues.cpp @@ -4,8 +4,12 @@ */ #include "StatsValues.h" -#include "Playerbots.h" +#include "AiObjectContext.h" +#include "Group.h" +#include "Pet.h" +#include "PlayerbotAIConfig.h" #include "ServerFacade.h" +#include "Player.h" Unit* HealthValue::GetTarget() { @@ -183,8 +187,8 @@ bool IsInCombatValue::Calculate() continue; if (member->IsInCombat() && - sServerFacade->IsDistanceLessOrEqualThan(sServerFacade->GetDistance2d(member, bot), - sPlayerbotAIConfig->reactDistance)) + ServerFacade::instance().IsDistanceLessOrEqualThan(ServerFacade::instance().GetDistance2d(member, bot), + PlayerbotAIConfig::instance().reactDistance)) return true; } } @@ -204,7 +208,6 @@ uint8 BagSpaceValue::Calculate() ++totalused; } - uint32 totalfree = 16 - totalused; for (uint8 bag = INVENTORY_SLOT_BAG_START; bag < INVENTORY_SLOT_BAG_END; ++bag) { const Bag* const pBag = (Bag*)bot->GetItemByPos(INVENTORY_SLOT_BAG_0, bag); @@ -214,7 +217,6 @@ uint8 BagSpaceValue::Calculate() if (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) { total += pBag->GetBagSize(); - totalfree += pBag->GetFreeSlots(); totalused += pBag->GetBagSize() - pBag->GetFreeSlots(); } } diff --git a/src/Ai/Base/Value/TankTargetValue.cpp b/src/Ai/Base/Value/TankTargetValue.cpp index ef2d1e959c..0bda67eae5 100644 --- a/src/Ai/Base/Value/TankTargetValue.cpp +++ b/src/Ai/Base/Value/TankTargetValue.cpp @@ -5,9 +5,10 @@ #include "TankTargetValue.h" +#include "AiObjectContext.h" #include "AttackersValue.h" -#include "PlayerbotAIConfig.h" -#include "Playerbots.h" +#include "Group.h" +#include "PlayerbotAI.h" class FindTargetForTankStrategy : public FindNonCcTargetStrategy { @@ -53,7 +54,7 @@ class FindTankTargetSmartStrategy : public FindTargetStrategy public: FindTankTargetSmartStrategy(PlayerbotAI* botAI) : FindTargetStrategy(botAI) {} - void CheckAttacker(Unit* attacker, ThreatMgr* threatMgr) override + void CheckAttacker(Unit* attacker, ThreatMgr*) override { if (Group* group = botAI->GetBot()->GetGroup()) { diff --git a/src/Ai/Base/Value/TargetValue.cpp b/src/Ai/Base/Value/TargetValue.cpp index 598b78441b..26e153ceba 100644 --- a/src/Ai/Base/Value/TargetValue.cpp +++ b/src/Ai/Base/Value/TargetValue.cpp @@ -161,7 +161,7 @@ Unit* FindTargetValue::Calculate() return nullptr; } -void FindBossTargetStrategy::CheckAttacker(Unit* attacker, ThreatMgr* threatManager) +void FindBossTargetStrategy::CheckAttacker(Unit* attacker, ThreatMgr*) { UnitAI* unitAI = attacker->GetAI(); BossAI* bossAI = dynamic_cast(unitAI); diff --git a/src/Ai/Base/ValueContext.h b/src/Ai/Base/ValueContext.h index 7349e9d614..82ef819ce2 100644 --- a/src/Ai/Base/ValueContext.h +++ b/src/Ai/Base/ValueContext.h @@ -51,6 +51,7 @@ #include "LineTargetValue.h" #include "LogLevelValue.h" #include "LootStrategyValue.h" +#include "LootValues.h" #include "MaintenanceValues.h" #include "ManaSaveLevelValue.h" #include "NearestAdsValue.h" @@ -396,7 +397,7 @@ class ValueContext : public NamedObjectContext static UntypedValue* nearest_game_objects(PlayerbotAI* botAI) { return new NearestGameObjects(botAI); } static UntypedValue* nearest_game_objects_no_los(PlayerbotAI* botAI) { - return new NearestGameObjects(botAI, sPlayerbotAIConfig->sightDistance, true); + return new NearestGameObjects(botAI, sPlayerbotAIConfig.sightDistance, true); } static UntypedValue* closest_game_objects(PlayerbotAI* botAI) { @@ -422,7 +423,7 @@ class ValueContext : public NamedObjectContext static UntypedValue* possible_triggers(PlayerbotAI* botAI) { return new PossibleTriggersValue(botAI); } static UntypedValue* possible_targets_no_los(PlayerbotAI* botAI) { - return new PossibleTargetsValue(botAI, "possible targets", sPlayerbotAIConfig->sightDistance, true); + return new PossibleTargetsValue(botAI, "possible targets", sPlayerbotAIConfig.sightDistance, true); } static UntypedValue* possible_adds(PlayerbotAI* botAI) { return new PossibleAddsValue(botAI); } static UntypedValue* prioritized_targets(PlayerbotAI* botAI) { return new PrioritizedTargetsValue(botAI); } diff --git a/src/Ai/Class/Dk/Strategy/GenericDKNonCombatStrategy.cpp b/src/Ai/Class/Dk/Strategy/GenericDKNonCombatStrategy.cpp index edead06755..3b1f18d729 100644 --- a/src/Ai/Class/Dk/Strategy/GenericDKNonCombatStrategy.cpp +++ b/src/Ai/Class/Dk/Strategy/GenericDKNonCombatStrategy.cpp @@ -5,8 +5,6 @@ #include "GenericDKNonCombatStrategy.h" -#include "Playerbots.h" - class GenericDKNonCombatStrategyActionNodeFactory : public NamedObjectFactory { public: @@ -55,7 +53,7 @@ void GenericDKNonCombatStrategy::InitTriggers(std::vector& trigger new TriggerNode("new pet", { NextAction("set pet stance", 60.0f) })); } -void DKBuffDpsStrategy::InitTriggers(std::vector& triggers) +void DKBuffDpsStrategy::InitTriggers(std::vector&) { } diff --git a/src/Ai/Class/Druid/Action/DruidActions.cpp b/src/Ai/Class/Druid/Action/DruidActions.cpp index 13336a674a..8d6073e3aa 100644 --- a/src/Ai/Class/Druid/Action/DruidActions.cpp +++ b/src/Ai/Class/Druid/Action/DruidActions.cpp @@ -28,11 +28,11 @@ Value* CastEntanglingRootsCcAction::GetTargetValue() return context->GetValue("cc target", "entangling roots"); } -bool CastEntanglingRootsCcAction::Execute(Event event) { return botAI->CastSpell("entangling roots", GetTarget()); } +bool CastEntanglingRootsCcAction::Execute(Event) { return botAI->CastSpell("entangling roots", GetTarget()); } Value* CastHibernateCcAction::GetTargetValue() { return context->GetValue("cc target", "hibernate"); } -bool CastHibernateCcAction::Execute(Event event) { return botAI->CastSpell("hibernate", GetTarget()); } +bool CastHibernateCcAction::Execute(Event) { return botAI->CastSpell("hibernate", GetTarget()); } bool CastStarfallAction::isUseful() { if (!CastSpellAction::isUseful()) @@ -43,8 +43,8 @@ bool CastStarfallAction::isUseful() Unit* ccTarget = context->GetValue("current cc target")->Get(); if (ccTarget && ccTarget->IsAlive()) { - float dist2d = sServerFacade->GetDistance2d(ccTarget, aoePos.GetPositionX(), aoePos.GetPositionY()); - if (sServerFacade->IsDistanceLessOrEqualThan(dist2d, sPlayerbotAIConfig->aoeRadius)) + float dist2d = ServerFacade::instance().GetDistance2d(ccTarget, aoePos.GetPositionX(), aoePos.GetPositionY()); + if (ServerFacade::instance().IsDistanceLessOrEqualThan(dist2d, sPlayerbotAIConfig.aoeRadius)) return false; } @@ -75,7 +75,7 @@ std::vector CastRebirthAction::getPrerequisites() bool CastRebirthAction::isUseful() { return CastSpellAction::isUseful() && - AI_VALUE2(float, "distance", GetTargetName()) <= sPlayerbotAIConfig->spellDistance; + AI_VALUE2(float, "distance", GetTargetName()) <= sPlayerbotAIConfig.spellDistance; } Unit* CastRejuvenationOnNotFullAction::GetTarget() @@ -91,7 +91,7 @@ Unit* CastRejuvenationOnNotFullAction::GetTarget() { continue; } - if (player->GetDistance2d(bot) > sPlayerbotAIConfig->spellDistance) + if (player->GetDistance2d(bot) > sPlayerbotAIConfig.spellDistance) { continue; } diff --git a/src/Ai/Class/Druid/Action/DruidShapeshiftActions.cpp b/src/Ai/Class/Druid/Action/DruidShapeshiftActions.cpp index 4f4a4e5968..6657139128 100644 --- a/src/Ai/Class/Druid/Action/DruidShapeshiftActions.cpp +++ b/src/Ai/Class/Druid/Action/DruidShapeshiftActions.cpp @@ -36,10 +36,10 @@ bool CastCasterFormAction::isUseful() { return botAI->HasAnyAuraOf(GetTarget(), "dire bear form", "bear form", "cat form", "travel form", "aquatic form", "flight form", "swift flight form", "moonkin form", nullptr) && - AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig->mediumHealth; + AI_VALUE2(uint8, "mana", "self target") > sPlayerbotAIConfig.mediumHealth; } -bool CastCasterFormAction::Execute(Event event) +bool CastCasterFormAction::Execute(Event) { botAI->RemoveShapeshift(); return true; @@ -50,7 +50,7 @@ bool CastCancelTreeFormAction::isUseful() return botAI->HasAura(33891, bot); } -bool CastCancelTreeFormAction::Execute(Event event) +bool CastCancelTreeFormAction::Execute(Event) { botAI->RemoveAura("tree of life"); return true; diff --git a/src/Ai/Class/Druid/Strategy/CatDpsDruidStrategy.cpp b/src/Ai/Class/Druid/Strategy/CatDpsDruidStrategy.cpp index fda1b5f94f..03b3b455ca 100644 --- a/src/Ai/Class/Druid/Strategy/CatDpsDruidStrategy.cpp +++ b/src/Ai/Class/Druid/Strategy/CatDpsDruidStrategy.cpp @@ -311,4 +311,4 @@ void CatDpsDruidStrategy::InitTriggers(std::vector& triggers) ); } -void CatAoeDruidStrategy::InitTriggers(std::vector& triggers) {} +void CatAoeDruidStrategy::InitTriggers(std::vector&) {} diff --git a/src/Ai/Class/Hunter/Action/HunterActions.cpp b/src/Ai/Class/Hunter/Action/HunterActions.cpp index a1588f8537..4cf55629a9 100644 --- a/src/Ai/Class/Hunter/Action/HunterActions.cpp +++ b/src/Ai/Class/Hunter/Action/HunterActions.cpp @@ -59,7 +59,7 @@ bool CastImmolationTrapAction::isUseful() Value* CastFreezingTrap::GetTargetValue() { return context->GetValue("cc target", "freezing trap"); } -bool FeedPetAction::Execute(Event event) +bool FeedPetAction::Execute(Event) { if (Pet* pet = bot->GetPet()) if (pet->getPetType() == HUNTER_PET && pet->GetHappinessState() != HAPPY) @@ -99,7 +99,7 @@ bool CastDisengageAction::isUseful() Value* CastScareBeastCcAction::GetTargetValue() { return context->GetValue("cc target", "scare beast"); } -bool CastScareBeastCcAction::Execute(Event event) { return botAI->CastSpell("scare beast", GetTarget()); } +bool CastScareBeastCcAction::Execute(Event) { return botAI->CastSpell("scare beast", GetTarget()); } bool CastWingClipAction::isUseful() { return CastSpellAction::isUseful() && !botAI->HasAura(spell, GetTarget()); } diff --git a/src/Ai/Class/Hunter/Action/HunterActions.h b/src/Ai/Class/Hunter/Action/HunterActions.h index 8e21135254..0a252d9c1f 100644 --- a/src/Ai/Class/Hunter/Action/HunterActions.h +++ b/src/Ai/Class/Hunter/Action/HunterActions.h @@ -352,7 +352,7 @@ class CastExplosiveShotRank4Action : public CastDebuffSpellAction public: CastExplosiveShotRank4Action(PlayerbotAI* botAI) : CastDebuffSpellAction(botAI, "explosive shot", true, 0.0f) {} - bool Execute(Event event) override { return botAI->CastSpell(60053, GetTarget()); } + bool Execute(Event) override { return botAI->CastSpell(60053, GetTarget()); } bool isUseful() override { Unit* target = GetTarget(); @@ -368,7 +368,7 @@ class CastExplosiveShotRank3Action : public CastDebuffSpellAction public: CastExplosiveShotRank3Action(PlayerbotAI* botAI) : CastDebuffSpellAction(botAI, "explosive shot", true, 0.0f) {} - bool Execute(Event event) override { return botAI->CastSpell(60052, GetTarget()); } + bool Execute(Event) override { return botAI->CastSpell(60052, GetTarget()); } bool isUseful() override { Unit* target = GetTarget(); @@ -384,7 +384,7 @@ class CastExplosiveShotRank2Action : public CastDebuffSpellAction public: CastExplosiveShotRank2Action(PlayerbotAI* botAI) : CastDebuffSpellAction(botAI, "explosive shot", true, 0.0f) {} - bool Execute(Event event) override { return botAI->CastSpell(60051, GetTarget()); } + bool Execute(Event) override { return botAI->CastSpell(60051, GetTarget()); } bool isUseful() override { Unit* target = GetTarget(); @@ -400,7 +400,7 @@ class CastExplosiveShotRank1Action : public CastDebuffSpellAction public: CastExplosiveShotRank1Action(PlayerbotAI* botAI) : CastDebuffSpellAction(botAI, "explosive shot", true, 0.0f) {} - bool Execute(Event event) override { return botAI->CastSpell(53301, GetTarget()); } + bool Execute(Event) override { return botAI->CastSpell(53301, GetTarget()); } bool isUseful() override { Unit* target = GetTarget(); diff --git a/src/Ai/Class/Hunter/Strategy/GenericHunterStrategy.cpp b/src/Ai/Class/Hunter/Strategy/GenericHunterStrategy.cpp index 04afc6f766..bd747416fc 100644 --- a/src/Ai/Class/Hunter/Strategy/GenericHunterStrategy.cpp +++ b/src/Ai/Class/Hunter/Strategy/GenericHunterStrategy.cpp @@ -5,9 +5,6 @@ #include "GenericHunterStrategy.h" -#include "Playerbots.h" -#include "Strategy.h" - class GenericHunterStrategyActionNodeFactory : public NamedObjectFactory { public: @@ -141,7 +138,7 @@ void AoEHunterStrategy::InitTriggers(std::vector& triggers) triggers.push_back(new TriggerNode("light aoe", { NextAction("multi-shot", 21.0f) })); } -void HunterBoostStrategy::InitTriggers(std::vector& triggers) +void HunterBoostStrategy::InitTriggers(std::vector&) { } diff --git a/src/Ai/Class/Hunter/Trigger/HunterTriggers.cpp b/src/Ai/Class/Hunter/Trigger/HunterTriggers.cpp index 091b8d5f72..84ece04b76 100644 --- a/src/Ai/Class/Hunter/Trigger/HunterTriggers.cpp +++ b/src/Ai/Class/Hunter/Trigger/HunterTriggers.cpp @@ -62,7 +62,7 @@ bool HuntersPetLowHealthTrigger::IsActive() bool HuntersPetMediumHealthTrigger::IsActive() { Unit* pet = AI_VALUE(Unit*, "pet target"); - return pet && AI_VALUE2(uint8, "health", "pet target") < sPlayerbotAIConfig->mediumHealth && + return pet && AI_VALUE2(uint8, "health", "pet target") < sPlayerbotAIConfig.mediumHealth && !AI_VALUE2(bool, "dead", "pet target") && !AI_VALUE2(bool, "mounted", "self target"); } @@ -74,7 +74,7 @@ bool HunterPetNotHappy::IsActive() bool HunterAspectOfTheViperTrigger::IsActive() { return SpellTrigger::IsActive() && !botAI->HasAura(spell, GetTarget()) && - AI_VALUE2(uint8, "mana", "self target") < (sPlayerbotAIConfig->lowMana / 2); + AI_VALUE2(uint8, "mana", "self target") < (sPlayerbotAIConfig.lowMana / 2); ; } @@ -96,7 +96,7 @@ bool SwitchToRangedTrigger::IsActive() Unit* target = AI_VALUE(Unit*, "current target"); return botAI->HasStrategy("close", BOT_STATE_COMBAT) && target && (target->GetVictim() != bot && - sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "current target"), 8.0f)); + ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "current target"), 8.0f)); } bool SwitchToMeleeTrigger::IsActive() @@ -104,7 +104,7 @@ bool SwitchToMeleeTrigger::IsActive() Unit* target = AI_VALUE(Unit*, "current target"); return botAI->HasStrategy("ranged", BOT_STATE_COMBAT) && target && (target->GetVictim() == bot && - sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "current target"), 8.0f)); + ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", "current target"), 8.0f)); } bool NoTrackTrigger::IsActive() diff --git a/src/Ai/Class/Mage/Action/MageActions.cpp b/src/Ai/Class/Mage/Action/MageActions.cpp index 67587e3213..5eb63ea866 100644 --- a/src/Ai/Class/Mage/Action/MageActions.cpp +++ b/src/Ai/Class/Mage/Action/MageActions.cpp @@ -61,13 +61,13 @@ bool CastFrostNovaAction::isUseful() if (target->isFrozen()) return false; - return sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", GetTargetName()), 10.f); + return ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", GetTargetName()), 10.f); } bool CastConeOfColdAction::isUseful() { bool facingTarget = AI_VALUE2(bool, "facing", "current target"); - bool targetClose = sServerFacade->IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", GetTargetName()), 10.f); + bool targetClose = ServerFacade::instance().IsDistanceLessOrEqualThan(AI_VALUE2(float, "distance", GetTargetName()), 10.f); return facingTarget && targetClose; } @@ -105,7 +105,7 @@ Unit* CastFocusMagicOnPartyAction::GetTarget() if (!member || member == bot || !member->IsAlive()) continue; - if (member->GetMap() != bot->GetMap() || bot->GetDistance(member) > sPlayerbotAIConfig->spellDistance) + if (member->GetMap() != bot->GetMap() || bot->GetDistance(member) > sPlayerbotAIConfig.spellDistance) continue; if (member->HasAura(54646)) diff --git a/src/Ai/Class/Paladin/Action/PaladinActions.cpp b/src/Ai/Class/Paladin/Action/PaladinActions.cpp index 190ecb264a..9b09f8b4dd 100644 --- a/src/Ai/Class/Paladin/Action/PaladinActions.cpp +++ b/src/Ai/Class/Paladin/Action/PaladinActions.cpp @@ -8,18 +8,14 @@ #include "AiFactory.h" #include "Event.h" #include "PlayerbotAI.h" -#include "PlayerbotAIConfig.h" -#include "PlayerbotFactory.h" #include "Playerbots.h" #include "SharedDefines.h" #include "../../../../../src/server/scripts/Spells/spell_generic.cpp" #include "GenericBuffUtils.h" -#include "Config.h" #include "Group.h" #include "ObjectAccessor.h" using ai::buff::MakeAuraQualifierForBuff; -using ai::buff::UpgradeToGroupIfAppropriate; // Helper : detect tank role on the target (player bot or not) return true if spec is tank or if the bot have tank strategies (bear/tank/tank face). static inline bool IsTankRole(Player* p) @@ -56,11 +52,6 @@ static inline bool IsOnlyPaladinInGroup(Player* bot) return pals == 1u; } -static inline bool GroupHasTankOfClass(Group* g, uint8 classId) -{ - return GroupHasTankOfClass(g, static_cast(classId)); -} - inline std::string const GetActualBlessingOfMight(Unit* target) { if (!target->ToPlayer()) @@ -167,7 +158,7 @@ Value* CastBlessingOnPartyAction::GetTargetValue() return context->GetValue("party member without aura", MakeAuraQualifierForBuff(spell)); } -bool CastBlessingOfMightAction::Execute(Event event) +bool CastBlessingOfMightAction::Execute(Event) { Unit* target = GetTarget(); if (!target) @@ -188,7 +179,7 @@ Value* CastBlessingOfMightOnPartyAction::GetTargetValue() ); } -bool CastBlessingOfMightOnPartyAction::Execute(Event event) +bool CastBlessingOfMightOnPartyAction::Execute(Event) { Unit* target = GetTarget(); if (!target) @@ -201,7 +192,7 @@ bool CastBlessingOfMightOnPartyAction::Execute(Event event) return botAI->CastSpell(castName, target); } -bool CastBlessingOfWisdomAction::Execute(Event event) +bool CastBlessingOfWisdomAction::Execute(Event) { Unit* target = GetTarget(); if (!target) @@ -222,7 +213,7 @@ Value* CastBlessingOfWisdomOnPartyAction::GetTargetValue() ); } -bool CastBlessingOfWisdomOnPartyAction::Execute(Event event) +bool CastBlessingOfWisdomOnPartyAction::Execute(Event) { Unit* target = GetTarget(); if (!target) @@ -258,7 +249,7 @@ Value* CastBlessingOfSanctuaryOnPartyAction::GetTargetValue() ); } -bool CastBlessingOfSanctuaryOnPartyAction::Execute(Event event) +bool CastBlessingOfSanctuaryOnPartyAction::Execute(Event) { if (!bot->HasSpell(SPELL_BLESSING_OF_SANCTUARY)) return false; @@ -382,7 +373,7 @@ Value* CastBlessingOfKingsOnPartyAction::GetTargetValue() ); } -bool CastBlessingOfKingsOnPartyAction::Execute(Event event) +bool CastBlessingOfKingsOnPartyAction::Execute(Event) { Unit* target = GetTarget(); if (!target) @@ -493,7 +484,7 @@ bool CastDivineSacrificeAction::isUseful() !botAI->HasAura("divine guardian", GetTarget(), false, false, -1, true); } -bool CastCancelDivineSacrificeAction::Execute(Event event) +bool CastCancelDivineSacrificeAction::Execute(Event) { botAI->RemoveAura("divine sacrifice"); return true; diff --git a/src/Ai/Class/Paladin/Strategy/GenericPaladinStrategy.cpp b/src/Ai/Class/Paladin/Strategy/GenericPaladinStrategy.cpp index 62d7dfb10b..ee2a192305 100644 --- a/src/Ai/Class/Paladin/Strategy/GenericPaladinStrategy.cpp +++ b/src/Ai/Class/Paladin/Strategy/GenericPaladinStrategy.cpp @@ -6,7 +6,6 @@ #include "GenericPaladinStrategy.h" #include "GenericPaladinStrategyActionNodeFactory.h" -#include "Playerbots.h" GenericPaladinStrategy::GenericPaladinStrategy(PlayerbotAI* botAI) : CombatStrategy(botAI) { @@ -59,7 +58,7 @@ void PaladinCureStrategy::InitTriggers(std::vector& triggers) { NextAction("cleanse magic on party", ACTION_DISPEL + 1) })); } -void PaladinBoostStrategy::InitTriggers(std::vector& triggers) +void PaladinBoostStrategy::InitTriggers(std::vector&) { // triggers.push_back(new TriggerNode("divine favor", { NextAction("divine favor", diff --git a/src/Ai/Class/Priest/Action/PriestActions.cpp b/src/Ai/Class/Priest/Action/PriestActions.cpp index e1c61033a1..0dbbd74cc5 100644 --- a/src/Ai/Class/Priest/Action/PriestActions.cpp +++ b/src/Ai/Class/Priest/Action/PriestActions.cpp @@ -12,7 +12,7 @@ bool CastRemoveShadowformAction::isUseful() { return botAI->HasAura("shadowform" bool CastRemoveShadowformAction::isPossible() { return true; } -bool CastRemoveShadowformAction::Execute(Event event) +bool CastRemoveShadowformAction::Execute(Event) { botAI->RemoveAura("shadowform"); return true; @@ -30,11 +30,11 @@ Unit* CastPowerWordShieldOnAlmostFullHealthBelowAction::GetTarget() { continue; } - if (player->GetHealthPct() > sPlayerbotAIConfig->almostFullHealth) + if (player->GetHealthPct() > sPlayerbotAIConfig.almostFullHealth) { continue; } - if (player->GetDistance2d(bot) > sPlayerbotAIConfig->spellDistance) + if (player->GetDistance2d(bot) > sPlayerbotAIConfig.spellDistance) { continue; } @@ -59,11 +59,11 @@ bool CastPowerWordShieldOnAlmostFullHealthBelowAction::isUseful() { continue; } - if (player->GetHealthPct() > sPlayerbotAIConfig->almostFullHealth) + if (player->GetHealthPct() > sPlayerbotAIConfig.almostFullHealth) { continue; } - if (player->GetDistance2d(bot) > sPlayerbotAIConfig->spellDistance) + if (player->GetDistance2d(bot) > sPlayerbotAIConfig.spellDistance) { continue; } @@ -89,7 +89,7 @@ Unit* CastPowerWordShieldOnNotFullAction::GetTarget() { continue; } - if (player->GetDistance2d(bot) > sPlayerbotAIConfig->spellDistance) + if (player->GetDistance2d(bot) > sPlayerbotAIConfig.spellDistance) { continue; } diff --git a/src/Ai/Class/Priest/Trigger/PriestTriggers.cpp b/src/Ai/Class/Priest/Trigger/PriestTriggers.cpp index 894780ad45..7f61ba6eec 100644 --- a/src/Ai/Class/Priest/Trigger/PriestTriggers.cpp +++ b/src/Ai/Class/Priest/Trigger/PriestTriggers.cpp @@ -68,14 +68,14 @@ bool ShadowformTrigger::IsActive() { return !botAI->HasAura("shadowform", bot); bool ShadowfiendTrigger::IsActive() { return BoostTrigger::IsActive() && !bot->HasSpellCooldown(34433); } BindingHealTrigger::BindingHealTrigger(PlayerbotAI* botAI) - : PartyMemberLowHealthTrigger(botAI, "binding heal", sPlayerbotAIConfig->lowHealth, 0) + : PartyMemberLowHealthTrigger(botAI, "binding heal", sPlayerbotAIConfig.lowHealth, 0) { } bool BindingHealTrigger::IsActive() { return PartyMemberLowHealthTrigger::IsActive() && - AI_VALUE2(uint8, "health", "self target") < sPlayerbotAIConfig->mediumHealth; + AI_VALUE2(uint8, "health", "self target") < sPlayerbotAIConfig.mediumHealth; } const std::set MindSearChannelCheckTrigger::MIND_SEAR_SPELL_IDS = { diff --git a/src/Ai/Class/Rogue/Action/RogueActions.cpp b/src/Ai/Class/Rogue/Action/RogueActions.cpp index 3019e0ec86..32759d6d63 100644 --- a/src/Ai/Class/Rogue/Action/RogueActions.cpp +++ b/src/Ai/Class/Rogue/Action/RogueActions.cpp @@ -14,7 +14,7 @@ bool CastStealthAction::isUseful() { Unit* target = AI_VALUE(Unit*, "current target"); - if (target && bot->GetDistance(target) >= sPlayerbotAIConfig->spellDistance) + if (target && bot->GetDistance(target) >= sPlayerbotAIConfig.spellDistance) return false; return true; } @@ -25,7 +25,7 @@ bool CastStealthAction::isPossible() return !botAI->HasAura(23333, bot) && !botAI->HasAura(23335, bot) && !botAI->HasAura(34976, bot); } -bool UnstealthAction::Execute(Event event) +bool UnstealthAction::Execute(Event) { botAI->RemoveAura("stealth"); // botAI->ChangeStrategy("+dps,-stealthed", BOT_STATE_COMBAT); @@ -33,7 +33,7 @@ bool UnstealthAction::Execute(Event event) return true; } -bool CheckStealthAction::Execute(Event event) +bool CheckStealthAction::Execute(Event) { if (botAI->HasAura("stealth", bot)) { @@ -69,7 +69,7 @@ bool CastTricksOfTheTradeOnMainTankAction::isUseful() return CastSpellAction::isUseful() && AI_VALUE2(float, "distance", GetTargetName()) < 20.0f; } -bool UseDeadlyPoisonAction::Execute(Event event) +bool UseDeadlyPoisonAction::Execute(Event) { std::vector poison_suffixs = {" IX", " VIII", " VII", " VI", " V", " IV", " III", " II", ""}; std::vector items; @@ -109,7 +109,7 @@ bool UseDeadlyPoisonAction::isPossible() return !items.empty(); } -bool UseInstantPoisonAction::Execute(Event event) +bool UseInstantPoisonAction::Execute(Event) { std::vector poison_suffixs = {" IX", " VIII", " VII", " VI", " V", " IV", " III", " II", ""}; std::vector items; @@ -148,7 +148,7 @@ bool UseInstantPoisonAction::isPossible() return !items.empty(); } -bool UseInstantPoisonOffHandAction::Execute(Event event) +bool UseInstantPoisonOffHandAction::Execute(Event) { std::vector poison_suffixs = {" IX", " VIII", " VII", " VI", " V", " IV", " III", " II", ""}; std::vector items; diff --git a/src/Ai/Class/Rogue/Trigger/RogueTriggers.cpp b/src/Ai/Class/Rogue/Trigger/RogueTriggers.cpp index fd9901552e..c33dbb7fe4 100644 --- a/src/Ai/Class/Rogue/Trigger/RogueTriggers.cpp +++ b/src/Ai/Class/Rogue/Trigger/RogueTriggers.cpp @@ -22,7 +22,7 @@ bool UnstealthTrigger::IsActive() return botAI->HasAura("stealth", bot) && !AI_VALUE(uint8, "attacker count") && (AI_VALUE2(bool, "moving", "self target") && ((botAI->GetMaster() && - sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "group leader"), 10.0f) && + ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "group leader"), 10.0f) && AI_VALUE2(bool, "moving", "group leader")) || !AI_VALUE(uint8, "attacker count"))); } @@ -60,7 +60,7 @@ bool StealthTrigger::IsActive() if (bot->InArena()) distance += 15; - return target && sServerFacade->GetDistance2d(bot, target) < distance; + return target && ServerFacade::instance().GetDistance2d(bot, target) < distance; } bool SapTrigger::IsPossible() { return bot->GetLevel() > 10 && bot->HasSpell(6770) && !bot->IsInCombat(); } @@ -99,8 +99,8 @@ bool SprintTrigger::IsActive() return AI_VALUE2(bool, "moving", "self target") && (AI_VALUE2(bool, "moving", "dps target") || AI_VALUE2(bool, "moving", "enemy player target")) && targeted && - (sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "dps target"), distance) || - sServerFacade->IsDistanceGreaterThan(AI_VALUE2(float, "distance", "enemy player target"), distance)); + (ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "dps target"), distance) || + ServerFacade::instance().IsDistanceGreaterThan(AI_VALUE2(float, "distance", "enemy player target"), distance)); } bool ExposeArmorTrigger::IsActive() diff --git a/src/Ai/Class/Shaman/Action/ShamanActions.cpp b/src/Ai/Class/Shaman/Action/ShamanActions.cpp index e8ed1234bf..943c10298e 100644 --- a/src/Ai/Class/Shaman/Action/ShamanActions.cpp +++ b/src/Ai/Class/Shaman/Action/ShamanActions.cpp @@ -6,7 +6,6 @@ #include "ShamanActions.h" #include "TotemsShamanStrategy.h" #include "Playerbots.h" -#include "Totem.h" #include "PlayerbotAI.h" #include "Action.h" @@ -71,7 +70,7 @@ bool CastLavaBurstAction::isUseful() // Logic for making a guardian (spirit wolf) use a spell (spirit walk) // There is no existing code for guardians casting spells in the AC/Playerbots repo. -bool CastSpiritWalkAction::Execute(Event event) +bool CastSpiritWalkAction::Execute(Event) { constexpr uint32 SPIRIT_WOLF = 29264; constexpr uint32 SPIRIT_WALK_SPELL = 58875; @@ -93,7 +92,7 @@ bool CastSpiritWalkAction::Execute(Event event) // Set Strategy Assigned Totems (Actions) - First, it checks // the highest-rank spell the bot knows for each totem type, // then adds it to the Call of the Elements bar. -bool SetTotemAction::Execute(Event event) +bool SetTotemAction::Execute(Event) { uint32 totemSpell = 0; for (size_t i = 0; i < totemSpellIdsCount; ++i) diff --git a/src/Ai/Class/Shaman/Strategy/TotemsShamanStrategy.h b/src/Ai/Class/Shaman/Strategy/TotemsShamanStrategy.h index 6d36f4a271..60488740c6 100644 --- a/src/Ai/Class/Shaman/Strategy/TotemsShamanStrategy.h +++ b/src/Ai/Class/Shaman/Strategy/TotemsShamanStrategy.h @@ -7,7 +7,6 @@ #define _PLAYERBOT_TOTEMSSHAMANSTRATEGY_H #include "GenericShamanStrategy.h" -#include #include #include diff --git a/src/Ai/Class/Shaman/Trigger/ShamanTriggers.cpp b/src/Ai/Class/Shaman/Trigger/ShamanTriggers.cpp index 753edb83fd..c8b36135a9 100644 --- a/src/Ai/Class/Shaman/Trigger/ShamanTriggers.cpp +++ b/src/Ai/Class/Shaman/Trigger/ShamanTriggers.cpp @@ -283,20 +283,6 @@ static uint32 GetRequiredTotemSpellId(PlayerbotAI* ai, const char* strategies[], return 0; // No relevant strategy active, or bot doesn't know any rank } -// Get the spellId of the currently summoned totem in the slot -static uint32 GetSummonedTotemSpellId(Player* bot, uint8 slot) -{ - ObjectGuid guid = bot->m_SummonSlot[slot]; - if (guid.IsEmpty()) - return 0; - - Creature* totem = bot->GetMap()->GetCreature(guid); - if (!totem) - return 0; - - return totem->GetUInt32Value(UNIT_CREATED_BY_SPELL); -} - bool NoEarthTotemTrigger::IsActive() { // Check if the bot has Stoneskin Totem (required level 4) and prevents the trigger firing if it doesn't diff --git a/src/Ai/Class/Shaman/Trigger/ShamanTriggers.h b/src/Ai/Class/Shaman/Trigger/ShamanTriggers.h index abf4ed566c..9e1a86aace 100644 --- a/src/Ai/Class/Shaman/Trigger/ShamanTriggers.h +++ b/src/Ai/Class/Shaman/Trigger/ShamanTriggers.h @@ -10,9 +10,7 @@ #include "GenericTriggers.h" #include "SharedDefines.h" #include "Trigger.h" -#include #include "TotemsShamanStrategy.h" -#include "Player.h" #include "PlayerbotAI.h" #include @@ -361,10 +359,8 @@ class SetTotemTrigger : public Trigger public: // Template constructor: infers N (size of the id array) at compile time template - SetTotemTrigger(PlayerbotAI* ai, std::string const& spellName, uint32 requiredSpellId, - const uint32 (&ids)[N], int actionButtonId) + SetTotemTrigger(PlayerbotAI* ai, std::string const& spellName, const uint32 (&ids)[N], int actionButtonId) : Trigger(ai, "set " + spellName) - , requiredSpellId(requiredSpellId) , totemSpellIds(ids) , totemSpellIdsCount(N) , actionButtonId(actionButtonId) @@ -372,7 +368,6 @@ class SetTotemTrigger : public Trigger bool IsActive() override; private: - uint32 requiredSpellId; uint32 const* totemSpellIds; size_t totemSpellIdsCount; int actionButtonId; @@ -382,119 +377,119 @@ class SetStrengthOfEarthTotemTrigger : public SetTotemTrigger { public: SetStrengthOfEarthTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "strength of earth totem", SPELL_STRENGTH_OF_EARTH_TOTEM_RANK_1, STRENGTH_OF_EARTH_TOTEM, TOTEM_BAR_SLOT_EARTH) {} + : SetTotemTrigger(ai, "strength of earth totem", STRENGTH_OF_EARTH_TOTEM, TOTEM_BAR_SLOT_EARTH) {} }; class SetStoneskinTotemTrigger : public SetTotemTrigger { public: SetStoneskinTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "stoneskin totem", SPELL_STONESKIN_TOTEM_RANK_1, STONESKIN_TOTEM, TOTEM_BAR_SLOT_EARTH) {} + : SetTotemTrigger(ai, "stoneskin totem", STONESKIN_TOTEM, TOTEM_BAR_SLOT_EARTH) {} }; class SetTremorTotemTrigger : public SetTotemTrigger { public: SetTremorTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "tremor totem", SPELL_TREMOR_TOTEM_RANK_1, TREMOR_TOTEM, TOTEM_BAR_SLOT_EARTH) {} + : SetTotemTrigger(ai, "tremor totem", TREMOR_TOTEM, TOTEM_BAR_SLOT_EARTH) {} }; class SetEarthbindTotemTrigger : public SetTotemTrigger { public: SetEarthbindTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "earthbind totem", SPELL_EARTHBIND_TOTEM_RANK_1, EARTHBIND_TOTEM, TOTEM_BAR_SLOT_EARTH) {} + : SetTotemTrigger(ai, "earthbind totem", EARTHBIND_TOTEM, TOTEM_BAR_SLOT_EARTH) {} }; class SetSearingTotemTrigger : public SetTotemTrigger { public: SetSearingTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "searing totem", SPELL_SEARING_TOTEM_RANK_1, SEARING_TOTEM, TOTEM_BAR_SLOT_FIRE) {} + : SetTotemTrigger(ai, "searing totem", SEARING_TOTEM, TOTEM_BAR_SLOT_FIRE) {} }; class SetMagmaTotemTrigger : public SetTotemTrigger { public: SetMagmaTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "magma totem", SPELL_MAGMA_TOTEM_RANK_1, MAGMA_TOTEM, TOTEM_BAR_SLOT_FIRE) {} + : SetTotemTrigger(ai, "magma totem", MAGMA_TOTEM, TOTEM_BAR_SLOT_FIRE) {} }; class SetFlametongueTotemTrigger : public SetTotemTrigger { public: SetFlametongueTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "flametongue totem", SPELL_FLAMETONGUE_TOTEM_RANK_1, FLAMETONGUE_TOTEM, TOTEM_BAR_SLOT_FIRE) {} + : SetTotemTrigger(ai, "flametongue totem", FLAMETONGUE_TOTEM, TOTEM_BAR_SLOT_FIRE) {} }; class SetTotemOfWrathTrigger : public SetTotemTrigger { public: SetTotemOfWrathTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "totem of wrath", SPELL_TOTEM_OF_WRATH_RANK_1, TOTEM_OF_WRATH, TOTEM_BAR_SLOT_FIRE) {} + : SetTotemTrigger(ai, "totem of wrath", TOTEM_OF_WRATH, TOTEM_BAR_SLOT_FIRE) {} }; class SetFrostResistanceTotemTrigger : public SetTotemTrigger { public: SetFrostResistanceTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "frost resistance totem", SPELL_FROST_RESISTANCE_TOTEM_RANK_1, FROST_RESISTANCE_TOTEM, TOTEM_BAR_SLOT_FIRE) {} + : SetTotemTrigger(ai, "frost resistance totem", FROST_RESISTANCE_TOTEM, TOTEM_BAR_SLOT_FIRE) {} }; class SetHealingStreamTotemTrigger : public SetTotemTrigger { public: SetHealingStreamTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "healing stream totem", SPELL_HEALING_STREAM_TOTEM_RANK_1, HEALING_STREAM_TOTEM, TOTEM_BAR_SLOT_WATER) {} + : SetTotemTrigger(ai, "healing stream totem", HEALING_STREAM_TOTEM, TOTEM_BAR_SLOT_WATER) {} }; class SetManaSpringTotemTrigger : public SetTotemTrigger { public: SetManaSpringTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "mana spring totem", SPELL_MANA_SPRING_TOTEM_RANK_1, MANA_SPRING_TOTEM, TOTEM_BAR_SLOT_WATER) {} + : SetTotemTrigger(ai, "mana spring totem", MANA_SPRING_TOTEM, TOTEM_BAR_SLOT_WATER) {} }; class SetCleansingTotemTrigger : public SetTotemTrigger { public: SetCleansingTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "cleansing totem", SPELL_CLEANSING_TOTEM_RANK_1, CLEANSING_TOTEM, TOTEM_BAR_SLOT_WATER) {} + : SetTotemTrigger(ai, "cleansing totem", CLEANSING_TOTEM, TOTEM_BAR_SLOT_WATER) {} }; class SetFireResistanceTotemTrigger : public SetTotemTrigger { public: SetFireResistanceTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "fire resistance totem", SPELL_FIRE_RESISTANCE_TOTEM_RANK_1, FIRE_RESISTANCE_TOTEM, TOTEM_BAR_SLOT_WATER) {} + : SetTotemTrigger(ai, "fire resistance totem", FIRE_RESISTANCE_TOTEM, TOTEM_BAR_SLOT_WATER) {} }; class SetWrathOfAirTotemTrigger : public SetTotemTrigger { public: SetWrathOfAirTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "wrath of air totem", SPELL_WRATH_OF_AIR_TOTEM_RANK_1, WRATH_OF_AIR_TOTEM, TOTEM_BAR_SLOT_AIR) {} + : SetTotemTrigger(ai, "wrath of air totem", WRATH_OF_AIR_TOTEM, TOTEM_BAR_SLOT_AIR) {} }; class SetWindfuryTotemTrigger : public SetTotemTrigger { public: SetWindfuryTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "windfury totem", SPELL_WINDFURY_TOTEM_RANK_1, WINDFURY_TOTEM, TOTEM_BAR_SLOT_AIR) {} + : SetTotemTrigger(ai, "windfury totem", WINDFURY_TOTEM, TOTEM_BAR_SLOT_AIR) {} }; class SetNatureResistanceTotemTrigger : public SetTotemTrigger { public: SetNatureResistanceTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "nature resistance totem", SPELL_NATURE_RESISTANCE_TOTEM_RANK_1, NATURE_RESISTANCE_TOTEM, TOTEM_BAR_SLOT_AIR) {} + : SetTotemTrigger(ai, "nature resistance totem", NATURE_RESISTANCE_TOTEM, TOTEM_BAR_SLOT_AIR) {} }; class SetGroundingTotemTrigger : public SetTotemTrigger { public: SetGroundingTotemTrigger(PlayerbotAI* ai) - : SetTotemTrigger(ai, "grounding totem", SPELL_GROUNDING_TOTEM_RANK_1, GROUNDING_TOTEM, TOTEM_BAR_SLOT_AIR) {} + : SetTotemTrigger(ai, "grounding totem", GROUNDING_TOTEM, TOTEM_BAR_SLOT_AIR) {} }; #endif diff --git a/src/Ai/Class/Warlock/Action/WarlockActions.cpp b/src/Ai/Class/Warlock/Action/WarlockActions.cpp index e899c7a2f6..a1163894fc 100644 --- a/src/Ai/Class/Warlock/Action/WarlockActions.cpp +++ b/src/Ai/Class/Warlock/Action/WarlockActions.cpp @@ -25,7 +25,7 @@ const int ITEM_SOUL_SHARD = 6265; bool CastDrainSoulAction::isUseful() { return AI_VALUE2(uint32, "item count", "soul shard") < 26; } // Checks if the bot's health is above a certain threshold, and if so, allows casting Life Tap -bool CastLifeTapAction::isUseful() { return AI_VALUE2(uint8, "health", "self target") > sPlayerbotAIConfig->lowHealth; } +bool CastLifeTapAction::isUseful() { return AI_VALUE2(uint8, "health", "self target") > sPlayerbotAIConfig.lowHealth; } // Checks if the target marked with the moon icon can be banished bool CastBanishOnCcAction::isPossible() @@ -116,7 +116,7 @@ bool CastSoulshatterAction::isUseful() } // Checks if the bot has enough bag space to create a soul shard, then does so -bool CreateSoulShardAction::Execute(Event event) +bool CreateSoulShardAction::Execute(Event) { Player* bot = botAI->GetBot(); if (!bot) @@ -188,7 +188,7 @@ bool CastCreateSoulstoneAction::isUseful() return hasSpace; } -bool DestroySoulShardAction::Execute(Event event) +bool DestroySoulShardAction::Execute(Event) { // Look for the first soul shard in any bag and destroy it for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) @@ -234,7 +234,7 @@ static bool HasSoulstoneAura(Unit* unit) } // Use the soulstone item on the bot itself with nc strategy "ss self" -bool UseSoulstoneSelfAction::Execute(Event event) +bool UseSoulstoneSelfAction::Execute(Event) { std::vector items = AI_VALUE2(std::vector, "inventory items", "soulstone"); if (items.empty()) @@ -266,7 +266,7 @@ void CleanupSoulstoneReservations() } // Use the soulstone item on the bot's master with nc strategy "ss master" -bool UseSoulstoneMasterAction::Execute(Event event) +bool UseSoulstoneMasterAction::Execute(Event) { CleanupSoulstoneReservations(); @@ -288,7 +288,7 @@ bool UseSoulstoneMasterAction::Execute(Event event) soulstoneReservations[master->GetGUID()] = now + 2500; // Reserve for 2.5 seconds } - float distance = sServerFacade->GetDistance2d(bot, master); + float distance = ServerFacade::instance().GetDistance2d(bot, master); if (distance >= 30.0f) return false; @@ -300,7 +300,7 @@ bool UseSoulstoneMasterAction::Execute(Event event) } // Use the soulstone item on a tank in the group with nc strategy "ss tank" -bool UseSoulstoneTankAction::Execute(Event event) +bool UseSoulstoneTankAction::Execute(Event) { CleanupSoulstoneReservations(); @@ -325,7 +325,7 @@ bool UseSoulstoneTankAction::Execute(Event event) if (soulstoneReservations.count(member->GetGUID()) && soulstoneReservations[member->GetGUID()] > now) continue; // Already being soulstoned - float distance = sServerFacade->GetDistance2d(bot, member); + float distance = ServerFacade::instance().GetDistance2d(bot, member); if (distance < 30.0f && bot->IsWithinLOSInMap(member)) { chosenTank = member; @@ -348,7 +348,7 @@ bool UseSoulstoneTankAction::Execute(Event event) soulstoneReservations[member->GetGUID()] > now) continue; // Already being soulstoned - float distance = sServerFacade->GetDistance2d(bot, member); + float distance = ServerFacade::instance().GetDistance2d(bot, member); if (distance < 30.0f && bot->IsWithinLOSInMap(member)) { chosenTank = member; @@ -368,7 +368,7 @@ bool UseSoulstoneTankAction::Execute(Event event) } // Use the soulstone item on a healer in the group with nc strategy "ss healer" -bool UseSoulstoneHealerAction::Execute(Event event) +bool UseSoulstoneHealerAction::Execute(Event) { CleanupSoulstoneReservations(); @@ -392,7 +392,7 @@ bool UseSoulstoneHealerAction::Execute(Event event) soulstoneReservations[member->GetGUID()] > now) continue; // Already being soulstoned - float distance = sServerFacade->GetDistance2d(bot, member); + float distance = ServerFacade::instance().GetDistance2d(bot, member); if (distance < 30.0f && bot->IsWithinLOSInMap(member)) { healer = member; @@ -425,7 +425,7 @@ CastCreateFirestoneAction::CastCreateFirestoneAction(PlayerbotAI* botAI) { } -bool CastCreateFirestoneAction::Execute(Event event) +bool CastCreateFirestoneAction::Execute(Event) { for (uint32 spellId : firestoneSpellIds) { diff --git a/src/Ai/Class/Warlock/Strategy/GenericWarlockStrategy.cpp b/src/Ai/Class/Warlock/Strategy/GenericWarlockStrategy.cpp index 1759776580..e135528e83 100644 --- a/src/Ai/Class/Warlock/Strategy/GenericWarlockStrategy.cpp +++ b/src/Ai/Class/Warlock/Strategy/GenericWarlockStrategy.cpp @@ -4,8 +4,6 @@ */ #include "GenericWarlockStrategy.h" -#include "Strategy.h" -#include "Playerbots.h" class GenericWarlockStrategyActionNodeFactory : public NamedObjectFactory { @@ -126,12 +124,12 @@ void AoEWarlockStrategy::InitTriggers(std::vector& triggers) ); } -void WarlockBoostStrategy::InitTriggers(std::vector& triggers) +void WarlockBoostStrategy::InitTriggers(std::vector&) { // Placeholder for future boost triggers } -void WarlockPetStrategy::InitTriggers(std::vector& triggers) +void WarlockPetStrategy::InitTriggers(std::vector&) { // Placeholder for future pet triggers } diff --git a/src/Ai/Class/Warlock/Strategy/TankWarlockStrategy.cpp b/src/Ai/Class/Warlock/Strategy/TankWarlockStrategy.cpp index c54fd59684..e3573e3be0 100644 --- a/src/Ai/Class/Warlock/Strategy/TankWarlockStrategy.cpp +++ b/src/Ai/Class/Warlock/Strategy/TankWarlockStrategy.cpp @@ -4,7 +4,6 @@ */ #include "TankWarlockStrategy.h" -#include "Playerbots.h" // Combat strategy for a Warlock Tank, for certain bosses like Twin Emperors // Priority is set to spam Searing Pain and use Shadow Ward on CD @@ -42,6 +41,6 @@ std::vector TankWarlockStrategy::getDefaultActions() }; } -void TankWarlockStrategy::InitTriggers(std::vector& triggers) +void TankWarlockStrategy::InitTriggers(std::vector&) { } diff --git a/src/Ai/Class/Warlock/Trigger/WarlockTriggers.cpp b/src/Ai/Class/Warlock/Trigger/WarlockTriggers.cpp index 04592c9b41..53e77669b2 100644 --- a/src/Ai/Class/Warlock/Trigger/WarlockTriggers.cpp +++ b/src/Ai/Class/Warlock/Trigger/WarlockTriggers.cpp @@ -96,7 +96,7 @@ bool DecimationTrigger::IsActive() // Checks if the bot's mana is below 85% and health is above a low health threshold bool LifeTapTrigger::IsActive() { - if (AI_VALUE2(uint8, "health", "self target") <= sPlayerbotAIConfig->lowHealth) + if (AI_VALUE2(uint8, "health", "self target") <= sPlayerbotAIConfig.lowHealth) return false; if (!AI_VALUE2(bool, "has mana", "self target")) diff --git a/src/Ai/Class/Warrior/Action/WarriorActions.cpp b/src/Ai/Class/Warrior/Action/WarriorActions.cpp index 9733226a95..f31dd1d9a1 100644 --- a/src/Ai/Class/Warrior/Action/WarriorActions.cpp +++ b/src/Ai/Class/Warrior/Action/WarriorActions.cpp @@ -93,7 +93,7 @@ Unit* CastVigilanceAction::GetTarget() return nullptr; } -bool CastVigilanceAction::Execute(Event event) +bool CastVigilanceAction::Execute(Event) { Unit* target = GetTarget(); if (!target || target == bot) @@ -234,7 +234,7 @@ bool CastShatteringThrowAction::isPossible() return true; } -bool CastShatteringThrowAction::Execute(Event event) +bool CastShatteringThrowAction::Execute(Event) { Unit* target = GetTarget(); if (!target) diff --git a/src/Ai/Class/Warrior/Strategy/ArmsWarriorStrategy.cpp b/src/Ai/Class/Warrior/Strategy/ArmsWarriorStrategy.cpp index eba5677e7f..4320563780 100644 --- a/src/Ai/Class/Warrior/Strategy/ArmsWarriorStrategy.cpp +++ b/src/Ai/Class/Warrior/Strategy/ArmsWarriorStrategy.cpp @@ -5,8 +5,6 @@ #include "ArmsWarriorStrategy.h" -#include "Playerbots.h" - class ArmsWarriorStrategyActionNodeFactory : public NamedObjectFactory { public: @@ -23,7 +21,7 @@ class ArmsWarriorStrategyActionNodeFactory : public NamedObjectFactory { public: @@ -20,7 +18,7 @@ class FuryWarriorStrategyActionNodeFactory : public NamedObjectFactory { public: @@ -26,7 +24,7 @@ class TankWarriorStrategyActionNodeFactory : public NamedObjectFactory= sPlayerbotAIConfig->mediumHealth && + return AI_VALUE2(uint8, "health", "self target") >= sPlayerbotAIConfig.mediumHealth && AI_VALUE2(uint8, "rage", "self target") < 20; } diff --git a/src/Ai/Dungeon/AzjolNerub/Action/AzjolNerubActions.cpp b/src/Ai/Dungeon/AzjolNerub/Action/AzjolNerubActions.cpp index e31ffd00f5..4d1f061f2f 100644 --- a/src/Ai/Dungeon/AzjolNerub/Action/AzjolNerubActions.cpp +++ b/src/Ai/Dungeon/AzjolNerub/Action/AzjolNerubActions.cpp @@ -1,9 +1,8 @@ #include "Playerbots.h" #include "AzjolNerubActions.h" -#include "AzjolNerubStrategy.h" bool AttackWebWrapAction::isUseful() { return !botAI->IsHeal(bot); } -bool AttackWebWrapAction::Execute(Event event) +bool AttackWebWrapAction::Execute(Event) { Unit* webWrap = nullptr; @@ -29,7 +28,7 @@ bool AttackWebWrapAction::Execute(Event event) } bool WatchersTargetAction::isUseful() { return !botAI->IsHeal(bot); } -bool WatchersTargetAction::Execute(Event event) +bool WatchersTargetAction::Execute(Event) { // Always prioritise web wraps Unit* currTarget = AI_VALUE(Unit*, "current target"); @@ -95,7 +94,7 @@ bool WatchersTargetAction::Execute(Event event) } bool AnubarakDodgePoundAction::isUseful() { return !AI_VALUE2(bool, "behind", "current target"); } -bool AnubarakDodgePoundAction::Execute(Event event) +bool AnubarakDodgePoundAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "anub'arak"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/CullingOfStratholme/Action/CullingOfStratholmeActions.cpp b/src/Ai/Dungeon/CullingOfStratholme/Action/CullingOfStratholmeActions.cpp index 15121f4a2e..97f27eefff 100644 --- a/src/Ai/Dungeon/CullingOfStratholme/Action/CullingOfStratholmeActions.cpp +++ b/src/Ai/Dungeon/CullingOfStratholme/Action/CullingOfStratholmeActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "CullingOfStratholmeActions.h" -#include "CullingOfStratholmeStrategy.h" -bool ExplodeGhoulSpreadAction::Execute(Event event) +bool ExplodeGhoulSpreadAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "salramm the fleshcrafter"); if (!boss) { return false; } @@ -38,7 +37,7 @@ bool EpochStackAction::isUseful() // else return !(bot->getClass() == CLASS_HUNTER) && AI_VALUE2(float, "distance", "current target") > 5.0f; } -bool EpochStackAction::Execute(Event event) +bool EpochStackAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "chrono-lord epoch"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/DraktharonKeep/Action/DrakTharonKeepActions.cpp b/src/Ai/Dungeon/DraktharonKeep/Action/DrakTharonKeepActions.cpp index 8cbbe49c2a..59d0091c4a 100644 --- a/src/Ai/Dungeon/DraktharonKeep/Action/DrakTharonKeepActions.cpp +++ b/src/Ai/Dungeon/DraktharonKeep/Action/DrakTharonKeepActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "DrakTharonKeepActions.h" -#include "DrakTharonKeepStrategy.h" -bool CorpseExplodeSpreadAction::Execute(Event event) +bool CorpseExplodeSpreadAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "trollgore"); if (!boss) { return false; } @@ -25,7 +24,7 @@ bool CorpseExplodeSpreadAction::Execute(Event event) return false; } -bool AvoidArcaneFieldAction::Execute(Event event) +bool AvoidArcaneFieldAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "novos the summoner"); if (!boss) { return false; } @@ -44,7 +43,7 @@ bool NovosDefaultPositionAction::isUseful() float threshold = 15.0f; return bot->GetDistance(NOVOS_PARTY_POSITION) > threshold; } -bool NovosDefaultPositionAction::Execute(Event event) +bool NovosDefaultPositionAction::Execute(Event) { float clusterDistance = 4.0f; // Only reposition if we're not killing anything @@ -59,7 +58,7 @@ bool NovosDefaultPositionAction::Execute(Event event) return false; } -bool NovosTargetPriorityAction::Execute(Event event) +bool NovosTargetPriorityAction::Execute(Event) { // TODO: This can be improved, some parts are still buggy. // But it works for now and this fight is very easy diff --git a/src/Ai/Dungeon/ForgeOfSouls/Action/ForgeOfSoulsActions.cpp b/src/Ai/Dungeon/ForgeOfSouls/Action/ForgeOfSoulsActions.cpp index e72fe98d5f..a22e5403db 100644 --- a/src/Ai/Dungeon/ForgeOfSouls/Action/ForgeOfSoulsActions.cpp +++ b/src/Ai/Dungeon/ForgeOfSouls/Action/ForgeOfSoulsActions.cpp @@ -1,9 +1,7 @@ #include "Playerbots.h" #include "ForgeOfSoulsActions.h" -#include "ForgeOfSoulsStrategy.h" -#include "SharedDefines.h" -bool MoveFromBronjahmAction::Execute(Event event) +bool MoveFromBronjahmAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "bronjahm"); if (!boss) @@ -17,13 +15,11 @@ bool MoveFromBronjahmAction::Execute(Event event) return false; } -bool AttackCorruptedSoulFragmentAction::Execute(Event event) +bool AttackCorruptedSoulFragmentAction::Execute(Event) { - Unit* currentTarget = AI_VALUE(Unit*, "current target"); GuidVector targets = AI_VALUE(GuidVector, "possible targets"); // If no valid skull target, search for corrupted soul fragment - Unit* empoweredPrince = nullptr; for (auto i = targets.begin(); i != targets.end(); ++i) { Unit* unit = botAI->GetUnit(*i); @@ -32,8 +28,6 @@ bool AttackCorruptedSoulFragmentAction::Execute(Event event) if (unit->GetEntry() == NPC_CORRUPTED_SOUL_FRAGMENT) { - empoweredPrince = unit; - // Mark corrupted soul fragment with skull if in group and not already marked if (Group* group = bot->GetGroup()) { @@ -51,7 +45,7 @@ bool AttackCorruptedSoulFragmentAction::Execute(Event event) return false; } -bool BronjahmGroupPositionAction::Execute(Event event) +bool BronjahmGroupPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "bronjahm"); if (!boss) @@ -141,7 +135,7 @@ bool BronjahmGroupPositionAction::Execute(Event event) bool BronjahmGroupPositionAction::isUseful() { return true; } -bool DevourerOfSoulsAction::Execute(Event event) +bool DevourerOfSoulsAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "devourer of souls"); if (!boss) diff --git a/src/Ai/Dungeon/Gundrak/Action/GundrakActions.cpp b/src/Ai/Dungeon/Gundrak/Action/GundrakActions.cpp index 4e9910993d..e9ff00ef68 100644 --- a/src/Ai/Dungeon/Gundrak/Action/GundrakActions.cpp +++ b/src/Ai/Dungeon/Gundrak/Action/GundrakActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "GundrakActions.h" -#include "GundrakStrategy.h" -bool AvoidPoisonNovaAction::Execute(Event event) +bool AvoidPoisonNovaAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "slad'ran"); if (!boss) { return false; } @@ -19,12 +18,11 @@ bool AvoidPoisonNovaAction::Execute(Event event) return false; } -bool AttackSnakeWrapAction::Execute(Event event) +bool AttackSnakeWrapAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "slad'ran"); if (!boss) { return false; } - Unit* snakeWrap = nullptr; // Target is not findable from threat table using AI_VALUE2(), // therefore need to search manually for the unit name GuidVector targets = AI_VALUE(GuidVector, "possible targets no los"); @@ -45,7 +43,7 @@ bool AttackSnakeWrapAction::Execute(Event event) return false; } -bool AvoidWhirlingSlashAction::Execute(Event event) +bool AvoidWhirlingSlashAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "gal'darah"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/HallsOfLightning/Action/HallsOfLightningActions.cpp b/src/Ai/Dungeon/HallsOfLightning/Action/HallsOfLightningActions.cpp index 047e0aee13..4613492ae8 100644 --- a/src/Ai/Dungeon/HallsOfLightning/Action/HallsOfLightningActions.cpp +++ b/src/Ai/Dungeon/HallsOfLightning/Action/HallsOfLightningActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "HallsOfLightningActions.h" -#include "HallsOfLightningStrategy.h" -bool BjarngrimTargetAction::Execute(Event event) +bool BjarngrimTargetAction::Execute(Event) { Unit* target = nullptr; @@ -35,7 +34,7 @@ bool BjarngrimTargetAction::Execute(Event event) return Attack(target); } -bool AvoidWhirlwindAction::Execute(Event event) +bool AvoidWhirlwindAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "general bjarngrim"); if (!boss) { return false; } @@ -52,7 +51,7 @@ bool AvoidWhirlwindAction::Execute(Event event) return false; } -bool VolkhanTargetAction::Execute(Event event) +bool VolkhanTargetAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "volkhan"); if (!boss || AI_VALUE(Unit*, "current target") == boss) @@ -63,7 +62,7 @@ bool VolkhanTargetAction::Execute(Event event) return Attack(boss); } -bool StaticOverloadSpreadAction::Execute(Event event) +bool StaticOverloadSpreadAction::Execute(Event) { float radius = 8.0f; float distanceExtra = 2.0f; @@ -86,7 +85,7 @@ bool StaticOverloadSpreadAction::Execute(Event event) return false; } -bool BallLightningSpreadAction::Execute(Event event) +bool BallLightningSpreadAction::Execute(Event) { float radius = 6.0f; float distanceExtra = 1.0f; @@ -108,14 +107,14 @@ bool BallLightningSpreadAction::Execute(Event event) } bool IonarTankPositionAction::isUseful() { return bot->GetExactDist2d(IONAR_TANK_POSITION) > 10.0f; } -bool IonarTankPositionAction::Execute(Event event) +bool IonarTankPositionAction::Execute(Event) { return MoveTo(bot->GetMapId(), IONAR_TANK_POSITION.GetPositionX(), IONAR_TANK_POSITION.GetPositionY(), IONAR_TANK_POSITION.GetPositionZ(), false, false, false, true, MovementPriority::MOVEMENT_COMBAT); } bool DispersePositionAction::isUseful() { return bot->GetExactDist2d(DISPERSE_POSITION) > 8.0f; } -bool DispersePositionAction::Execute(Event event) +bool DispersePositionAction::Execute(Event) { return MoveTo(bot->GetMapId(), DISPERSE_POSITION.GetPositionX(), DISPERSE_POSITION.GetPositionY(), DISPERSE_POSITION.GetPositionZ(), false, false, false, true, MovementPriority::MOVEMENT_COMBAT); @@ -133,7 +132,7 @@ bool LokenStackAction::isUseful() // else return AI_VALUE2(float, "distance", "current target") > 2.0f; } -bool LokenStackAction::Execute(Event event) +bool LokenStackAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "loken"); if (!boss) { return false; } @@ -152,7 +151,7 @@ bool LokenStackAction::Execute(Event event) return false; } -bool AvoidLightningNovaAction::Execute(Event event) +bool AvoidLightningNovaAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "loken"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/HallsOfStone/Action/HallsOfStoneActions.cpp b/src/Ai/Dungeon/HallsOfStone/Action/HallsOfStoneActions.cpp index 30562f090d..c43e23b66e 100644 --- a/src/Ai/Dungeon/HallsOfStone/Action/HallsOfStoneActions.cpp +++ b/src/Ai/Dungeon/HallsOfStone/Action/HallsOfStoneActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "HallsOfStoneActions.h" -#include "HallsOfStoneStrategy.h" -bool ShatterSpreadAction::Execute(Event event) +bool ShatterSpreadAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "krystallus"); if (!boss) { return false; } @@ -35,7 +34,7 @@ bool ShatterSpreadAction::Execute(Event event) return false; } -bool AvoidLightningRingAction::Execute(Event event) +bool AvoidLightningRingAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sjonnir the ironshaper"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/Nexus/Action/NexusActions.cpp b/src/Ai/Dungeon/Nexus/Action/NexusActions.cpp index f61a95aef4..fe7feed10d 100644 --- a/src/Ai/Dungeon/Nexus/Action/NexusActions.cpp +++ b/src/Ai/Dungeon/Nexus/Action/NexusActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "NexusActions.h" -#include "NexusStrategy.h" -bool MoveFromWhirlwindAction::Execute(Event event) +bool MoveFromWhirlwindAction::Execute(Event) { Unit* boss = nullptr; uint8 faction = bot->GetTeamId(); @@ -52,7 +51,7 @@ bool MoveFromWhirlwindAction::Execute(Event event) return MoveAway(boss, targetDist - bossDistance); } -bool FirebombSpreadAction::Execute(Event event) +bool FirebombSpreadAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "grand magus telestra"); float radius = 5.0f; @@ -74,7 +73,7 @@ bool FirebombSpreadAction::Execute(Event event) } bool TelestraSplitTargetAction::isUseful() { return !botAI->IsHeal(bot); } -bool TelestraSplitTargetAction::Execute(Event event) +bool TelestraSplitTargetAction::Execute(Event) { GuidVector attackers = AI_VALUE(GuidVector, "attackers"); Unit* splitTargets[3] = {nullptr, nullptr, nullptr}; @@ -121,7 +120,7 @@ bool TelestraSplitTargetAction::Execute(Event event) } bool ChaoticRiftTargetAction::isUseful() { return !botAI->IsHeal(bot); } -bool ChaoticRiftTargetAction::Execute(Event event) +bool ChaoticRiftTargetAction::Execute(Event) { Unit* chaoticRift = nullptr; @@ -152,7 +151,7 @@ bool DodgeSpikesAction::isUseful() return bot->GetExactDist2d(boss) > 0.5f; } -bool DodgeSpikesAction::Execute(Event event) +bool DodgeSpikesAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "ormorok the tree-shaper"); if (!boss) { return false; } @@ -160,7 +159,7 @@ bool DodgeSpikesAction::Execute(Event event) return Move(bot->GetAngle(boss), bot->GetExactDist2d(boss) - 0.3f); } -bool IntenseColdJumpAction::Execute(Event event) +bool IntenseColdJumpAction::Execute(Event) { // This needs improving but maybe it should be done in the playerbot core. // Jump doesn't seem to support zero offset (eg. jump on the spot) so need to add a tiny delta. diff --git a/src/Ai/Dungeon/Oculus/Action/OculusActions.cpp b/src/Ai/Dungeon/Oculus/Action/OculusActions.cpp index 414acc4bc9..1ea8f87618 100644 --- a/src/Ai/Dungeon/Oculus/Action/OculusActions.cpp +++ b/src/Ai/Dungeon/Oculus/Action/OculusActions.cpp @@ -1,9 +1,9 @@ +#include "OculusTriggers.h" #include "Playerbots.h" #include "OculusActions.h" -#include "OculusStrategy.h" #include "LastSpellCastValue.h" -bool AvoidUnstableSphereAction::Execute(Event event) +bool AvoidUnstableSphereAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "drakos the interrogator"); if (!boss) { return false; } @@ -34,7 +34,7 @@ bool AvoidUnstableSphereAction::Execute(Event event) } bool MountDrakeAction::isPossible() { return bot->GetMapId() == OCULUS_MAP_ID; } -bool MountDrakeAction::Execute(Event event) +bool MountDrakeAction::Execute(Event) { std::map drakeAssignments; // Composition can be adjusted - both 3/1/1 and 2/2/1 are good default comps @@ -88,7 +88,7 @@ bool MountDrakeAction::Execute(Event event) } // Correct/update the drake items in inventories incase assignments have changed - for (uint32 itemId : DRAKE_ITEMS) + for (int64_t itemId : DRAKE_ITEMS) { Item* item = bot->GetItemByEntry(itemId); if (!item) { continue; } @@ -109,7 +109,7 @@ bool MountDrakeAction::Execute(Event event) return false; } -bool DismountDrakeAction::Execute(Event event) +bool DismountDrakeAction::Execute(Event) { if (bot->GetVehicle()) { @@ -119,7 +119,7 @@ bool DismountDrakeAction::Execute(Event event) return false; } -bool OccFlyDrakeAction::Execute(Event event) +bool OccFlyDrakeAction::Execute(Event) { Player* master = botAI->GetMaster(); if (!master) { return false; } @@ -160,7 +160,7 @@ bool OccFlyDrakeAction::Execute(Event event) return false; } -bool OccDrakeAttackAction::Execute(Event event) +bool OccDrakeAttackAction::Execute(Event) { vehicleBase = bot->GetVehicleBase(); if (!vehicleBase) { return false; } @@ -319,7 +319,7 @@ bool OccDrakeAttackAction::RubyDrakeAction(Unit* target) return CastDrakeSpellAction(target, SPELL_SEARING_WRATH, 0); } -bool AvoidArcaneExplosionAction::Execute(Event event) +bool AvoidArcaneExplosionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "mage-lord urom"); if (!boss) { return false; } @@ -339,7 +339,7 @@ bool AvoidArcaneExplosionAction::Execute(Event event) return MoveNear(bot->GetMapId(), closestPos->GetPositionX(), closestPos->GetPositionY(), closestPos->GetPositionZ(), 2.0f, MovementPriority::MOVEMENT_COMBAT); } -bool TimeBombSpreadAction::Execute(Event event) +bool TimeBombSpreadAction::Execute(Event) { float radius = 10.0f; float distanceExtra = 2.0f; diff --git a/src/Ai/Dungeon/Oculus/Action/OculusActions.h b/src/Ai/Dungeon/Oculus/Action/OculusActions.h index 6b26b9ddbc..6616ce884b 100644 --- a/src/Ai/Dungeon/Oculus/Action/OculusActions.h +++ b/src/Ai/Dungeon/Oculus/Action/OculusActions.h @@ -4,8 +4,6 @@ #include "Action.h" #include "AttackAction.h" #include "PlayerbotAI.h" -#include "Playerbots.h" -#include "OculusTriggers.h" #include "UseItemAction.h" #include "GenericSpellActions.h" diff --git a/src/Ai/Dungeon/Oculus/Multiplier/OculusMultipliers.cpp b/src/Ai/Dungeon/Oculus/Multiplier/OculusMultipliers.cpp index 7be543ee70..e71067d0ce 100644 --- a/src/Ai/Dungeon/Oculus/Multiplier/OculusMultipliers.cpp +++ b/src/Ai/Dungeon/Oculus/Multiplier/OculusMultipliers.cpp @@ -6,6 +6,7 @@ #include "OculusTriggers.h" #include "FollowActions.h" #include "ReachTargetActions.h" +#include "Playerbots.h" float MountingDrakeMultiplier::GetValue(Action* action) { @@ -100,12 +101,22 @@ uint8 UromMultiplier::GetPhaseByCurrentPosition(Unit* unit) float EregosMultiplier::GetValue(Action* action) { - Unit* boss = AI_VALUE2(Unit*, "find target", "ley-guardian eregos"); - if (!boss) { return 1.0f; } + if (action == nullptr) + { + return 1.0f; + } + + const Unit* const boss = this->context->GetValue("find target", "ley-guardian eregos")->Get(); - if (boss->HasAura(SPELL_PLANAR_SHIFT && dynamic_cast(action))) + if (boss == nullptr) + { + return 1.0f; + } + + if (boss->HasAura(SPELL_PLANAR_SHIFT) && action->getName() == "occ drake attack") { return 0.0f; } + return 1.0f; } diff --git a/src/Ai/Dungeon/OldKingdom/Action/OldKingdomActions.cpp b/src/Ai/Dungeon/OldKingdom/Action/OldKingdomActions.cpp index 916bf29200..7755617758 100644 --- a/src/Ai/Dungeon/OldKingdom/Action/OldKingdomActions.cpp +++ b/src/Ai/Dungeon/OldKingdom/Action/OldKingdomActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "OldKingdomActions.h" -#include "OldKingdomStrategy.h" -bool AttackNadoxGuardianAction::Execute(Event event) +bool AttackNadoxGuardianAction::Execute(Event) { Unit* target = AI_VALUE2(Unit*, "find target", "ahn'kahar guardian"); if (!target || AI_VALUE(Unit*, "current target") == target) @@ -12,7 +11,7 @@ bool AttackNadoxGuardianAction::Execute(Event event) return Attack(target); } -bool AttackJedogaVolunteerAction::Execute(Event event) +bool AttackJedogaVolunteerAction::Execute(Event) { Unit* target = nullptr; // Target is not findable from threat table using AI_VALUE2(), @@ -40,7 +39,7 @@ bool AttackJedogaVolunteerAction::Execute(Event event) return Attack(target); } -bool AvoidShadowCrashAction::Execute(Event event) +bool AvoidShadowCrashAction::Execute(Event) { // Could check all enemy units in range as it's possible to pull multiple of these mobs. // They should really be killed 1 by 1, multipulls are messy so we just handle singles for now diff --git a/src/Ai/Dungeon/PitOfSaron/Action/PitOfSaronActions.cpp b/src/Ai/Dungeon/PitOfSaron/Action/PitOfSaronActions.cpp index f34b98462e..7053fc5b0d 100644 --- a/src/Ai/Dungeon/PitOfSaron/Action/PitOfSaronActions.cpp +++ b/src/Ai/Dungeon/PitOfSaron/Action/PitOfSaronActions.cpp @@ -1,9 +1,7 @@ #include "Playerbots.h" #include "PitOfSaronActions.h" -#include "PitOfSaronStrategy.h" -#include "SharedDefines.h" -bool IckAndKrickAction::Execute(Event event) +bool IckAndKrickAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "Ick"); if (!boss) @@ -26,7 +24,14 @@ bool IckAndKrickAction::Execute(Event event) bool pursuit = bot->HasAura(SPELL_PURSUIT) || (!botAI->IsTank(bot) && boss->HasUnitState(UNIT_STATE_CASTING) && boss->FindCurrentSpellBySpellId(SPELL_PURSUIT)); bool poisonNova = boss->HasUnitState(UNIT_STATE_CASTING) && (boss->FindCurrentSpellBySpellId(SPELL_POISON_NOVA_POS) || boss->FindCurrentSpellBySpellId(SPELL_POISON_NOVA_POS_HC)); - bool explosiveBarrage = orb || boss->HasUnitState(UNIT_STATE_CASTING) && (boss->FindCurrentSpellBySpellId(SPELL_EXPLOSIVE_BARRAGE_ICK) || boss->FindCurrentSpellBySpellId(SPELL_EXPLOSIVE_BARRAGE_KRICK)); + bool explosiveBarrage = orb + || ( + boss->HasUnitState(UNIT_STATE_CASTING) + && ( + boss->FindCurrentSpellBySpellId(SPELL_EXPLOSIVE_BARRAGE_ICK) + || boss->FindCurrentSpellBySpellId(SPELL_EXPLOSIVE_BARRAGE_KRICK) + ) + ); bool isTank = botAI->IsTank(bot); if (pursuit && Pursuit(pursuit, boss)) @@ -136,7 +141,7 @@ bool IckAndKrickAction::PoisonNova(bool poisonNova, Unit* boss) return false; } -bool IckAndKrickAction::ExplosiveBarrage(bool explosiveBarrage, Unit* boss) +bool IckAndKrickAction::ExplosiveBarrage(bool, Unit* boss) { std::vector orbs; Unit* closestOrb = nullptr; @@ -269,7 +274,7 @@ bool IckAndKrickAction::ExplosiveBarrage(bool explosiveBarrage, Unit* boss) return false; } -bool TyrannusAction::Execute(Event event) +bool TyrannusAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "scourgelord tyrannus"); if (!boss) diff --git a/src/Ai/Dungeon/PitOfSaron/Multiplier/PitOfSaronMultipliers.cpp b/src/Ai/Dungeon/PitOfSaron/Multiplier/PitOfSaronMultipliers.cpp index be36e480f2..f29fa4245b 100644 --- a/src/Ai/Dungeon/PitOfSaron/Multiplier/PitOfSaronMultipliers.cpp +++ b/src/Ai/Dungeon/PitOfSaron/Multiplier/PitOfSaronMultipliers.cpp @@ -27,7 +27,7 @@ float IckAndKrickMultiplier::GetValue(Action* action) return 1.0f; } -float GarfrostMultiplier::GetValue(Action* action) +float GarfrostMultiplier::GetValue(Action*) { Unit* boss = AI_VALUE2(Unit*, "find target", "garfrost"); if (!boss) diff --git a/src/Ai/Dungeon/TrialOfTheChampion/Action/TrialOfTheChampionActions.cpp b/src/Ai/Dungeon/TrialOfTheChampion/Action/TrialOfTheChampionActions.cpp index 92b687b292..5cdfb4f21a 100644 --- a/src/Ai/Dungeon/TrialOfTheChampion/Action/TrialOfTheChampionActions.cpp +++ b/src/Ai/Dungeon/TrialOfTheChampion/Action/TrialOfTheChampionActions.cpp @@ -1,15 +1,12 @@ #include "Playerbots.h" #include "TrialOfTheChampionActions.h" -#include "TrialOfTheChampionStrategy.h" #include "NearestNpcsValue.h" #include "ObjectAccessor.h" -#include "Timer.h" #include "Vehicle.h" #include "GenericSpellActions.h" #include "GenericActions.h" -#include -bool ToCLanceAction::Execute(Event event) +bool ToCLanceAction::Execute(Event) { // If already has lance equipped, do nothing if (bot->HasItemOrGemWithIdEquipped(ITEM_LANCE, 1)) @@ -58,10 +55,6 @@ bool ToCLanceAction::Execute(Event event) // If we found the lance, equip it if (lanceItem) { - // Store the lance's current position - uint8 srcBag = lanceItem->GetBagSlot(); - uint8 srcSlot = lanceItem->GetSlot(); - // First unequip current weapon if it exists if (oldWeapon) { @@ -105,7 +98,7 @@ bool ToCUELanceAction::Execute(Event event) return false; } -bool ToCMountedAction::Execute(Event event) +bool ToCMountedAction::Execute(Event) { Unit* vehicleBase = bot->GetVehicleBase(); Vehicle* vehicle = bot->GetVehicle(); @@ -179,7 +172,7 @@ bool ToCMountedAction::Execute(Event event) return false; } -bool ToCMountAction::Execute(Event event) +bool ToCMountAction::Execute(Event) { // do not switch vehicles yet if (bot->GetVehicle()) @@ -244,7 +237,7 @@ bool ToCMountAction::EnterVehicle(Unit* vehicleBase, bool moveIfFar) return true; } -bool ToCEadricAction::Execute(Event event) +bool ToCEadricAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "eadric the pure"); if (!boss) diff --git a/src/Ai/Dungeon/TrialOfTheChampion/Strategy/TrialOfTheChampionStrategy.cpp b/src/Ai/Dungeon/TrialOfTheChampion/Strategy/TrialOfTheChampionStrategy.cpp index bbccca71f3..6f19df472d 100644 --- a/src/Ai/Dungeon/TrialOfTheChampion/Strategy/TrialOfTheChampionStrategy.cpp +++ b/src/Ai/Dungeon/TrialOfTheChampion/Strategy/TrialOfTheChampionStrategy.cpp @@ -1,5 +1,4 @@ #include "TrialOfTheChampionStrategy.h" -#include "TrialOfTheChampionMultipliers.h" void WotlkDungeonToCStrategy::InitTriggers(std::vector &triggers) { @@ -16,6 +15,6 @@ void WotlkDungeonToCStrategy::InitTriggers(std::vector &triggers) } -void WotlkDungeonToCStrategy::InitMultipliers(std::vector &multipliers) +void WotlkDungeonToCStrategy::InitMultipliers(std::vector&) { } diff --git a/src/Ai/Dungeon/UtgardeKeep/Action/UtgardeKeepActions.cpp b/src/Ai/Dungeon/UtgardeKeep/Action/UtgardeKeepActions.cpp index 20a5f27b49..81865c750e 100644 --- a/src/Ai/Dungeon/UtgardeKeep/Action/UtgardeKeepActions.cpp +++ b/src/Ai/Dungeon/UtgardeKeep/Action/UtgardeKeepActions.cpp @@ -1,9 +1,8 @@ #include "Playerbots.h" #include "UtgardeKeepActions.h" -#include "UtgardeKeepStrategy.h" bool AttackFrostTombAction::isUseful() { return !botAI->IsHeal(bot); } -bool AttackFrostTombAction::Execute(Event event) +bool AttackFrostTombAction::Execute(Event) { Unit* frostTomb = nullptr; @@ -28,7 +27,7 @@ bool AttackFrostTombAction::Execute(Event event) } // TODO: Possibly add player stacking behaviour close to tank, to prevent Skarvald charging ranged -bool AttackDalronnAction::Execute(Event event) +bool AttackDalronnAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "dalronn the controller"); if (!boss) { return false; } @@ -40,7 +39,7 @@ bool AttackDalronnAction::Execute(Event event) return Attack(boss); } -bool IngvarStopCastingAction::Execute(Event event) +bool IngvarStopCastingAction::Execute(Event) { // Doesn't work, this action gets queued behind the current spell instead of interrupting it Unit* boss = AI_VALUE2(Unit*, "find target", "ingvar the plunderer"); @@ -64,7 +63,7 @@ bool IngvarStopCastingAction::Execute(Event event) } bool IngvarDodgeSmashAction::isUseful() { return !AI_VALUE2(bool, "behind", "current target"); } -bool IngvarDodgeSmashAction::Execute(Event event) +bool IngvarDodgeSmashAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "ingvar the plunderer"); if (!boss) { return false; } @@ -78,7 +77,7 @@ bool IngvarDodgeSmashAction::Execute(Event event) } bool IngvarSmashReturnAction::isUseful() { return AI_VALUE2(bool, "behind", "current target"); } -bool IngvarSmashReturnAction::Execute(Event event) +bool IngvarSmashReturnAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "ingvar the plunderer"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/UtgardePinnacle/Action/UtgardePinnacleActions.cpp b/src/Ai/Dungeon/UtgardePinnacle/Action/UtgardePinnacleActions.cpp index f084ca15b6..0b09459e71 100644 --- a/src/Ai/Dungeon/UtgardePinnacle/Action/UtgardePinnacleActions.cpp +++ b/src/Ai/Dungeon/UtgardePinnacle/Action/UtgardePinnacleActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "UtgardePinnacleActions.h" -#include "UtgardePinnacleStrategy.h" -bool AvoidFreezingCloudAction::Execute(Event event) +bool AvoidFreezingCloudAction::Execute(Event) { Unit* closestTrigger = nullptr; GuidVector objects = AI_VALUE(GuidVector, "nearest hostile npcs"); @@ -36,7 +35,7 @@ bool AvoidFreezingCloudAction::Execute(Event event) return false; } -bool AvoidSkadiWhirlwindAction::Execute(Event event) +bool AvoidSkadiWhirlwindAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "skadi the ruthless"); if (!boss) { return false; } diff --git a/src/Ai/Dungeon/VioletHold/Action/VioletHoldActions.cpp b/src/Ai/Dungeon/VioletHold/Action/VioletHoldActions.cpp index b590642d8b..157e24b2de 100644 --- a/src/Ai/Dungeon/VioletHold/Action/VioletHoldActions.cpp +++ b/src/Ai/Dungeon/VioletHold/Action/VioletHoldActions.cpp @@ -1,8 +1,7 @@ #include "Playerbots.h" #include "VioletHoldActions.h" -#include "VioletHoldStrategy.h" -bool AttackErekemAction::Execute(Event event) +bool AttackErekemAction::Execute(Event) { // Focus boss first, adds after Unit* boss = AI_VALUE2(Unit*, "find target", "erekem"); @@ -15,7 +14,7 @@ bool AttackErekemAction::Execute(Event event) return false; } -bool AttackIchorGlobuleAction::Execute(Event event) +bool AttackIchorGlobuleAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "ichoron"); if (!boss) { return false; } @@ -60,7 +59,7 @@ bool AttackIchorGlobuleAction::Execute(Event event) return false; } -bool AttackVoidSentryAction::Execute(Event event) +bool AttackVoidSentryAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "zuramat the obliterator"); if (!boss) { return false; } @@ -96,7 +95,7 @@ bool AttackVoidSentryAction::Execute(Event event) return false; } -bool StopAttackAction::Execute(Event event) +bool StopAttackAction::Execute(Event) { return bot->AttackStop(); } diff --git a/src/Ai/Raid/Aq20/Action/RaidAq20Actions.cpp b/src/Ai/Raid/Aq20/Action/RaidAq20Actions.cpp index 1bf33147f8..01ae38aa54 100644 --- a/src/Ai/Raid/Aq20/Action/RaidAq20Actions.cpp +++ b/src/Ai/Raid/Aq20/Action/RaidAq20Actions.cpp @@ -1,48 +1,63 @@ #include "RaidAq20Actions.h" -#include "Playerbots.h" #include "RaidAq20Utils.h" -bool Aq20UseCrystalAction::Execute(Event event) +bool Aq20UseCrystalAction::Execute(Event) { - if (Unit* boss = AI_VALUE2(Unit*, "find target", "ossirian the unscarred")) + Unit* const boss = context->GetValue("find target", "ossirian the unscarred")->Get(); + + if (boss == nullptr) + { + return false; + } + + const GameObject* const crystal = RaidAq20Utils::GetNearestCrystal(*boss); + + if (crystal == nullptr) { - if (GameObject* crystal = RaidAq20Utils::GetNearestCrystal(boss)) - { - float botDist = bot->GetDistance(crystal); - if (botDist > INTERACTION_DISTANCE) - return MoveTo(bot->GetMapId(), - crystal->GetPositionX() + frand(-3.5f, 3.5f), - crystal->GetPositionY() + frand(-3.5f, 3.5f), - crystal->GetPositionZ()); - - // if we're already in range just wait here until it's time to activate crystal - SetNextMovementDelay(500); - - // don't activate crystal if boss too far or its already been activated - if (boss->GetDistance(crystal) > 25.0f || - crystal->HasGameObjectFlag(GO_FLAG_IN_USE)) - return false; - - // don't activate crystal if boss doesn't have buff yet AND isn't going to have it soon - // (though ideally bot should activate it ~5 seconds early due to time it takes for - // crystal to activate and remove buff) - if (!RaidAq20Utils::IsOssirianBuffActive(boss) && - RaidAq20Utils::GetOssirianDebuffTimeRemaining(boss) > 5000) - return false; - - // this makes crystal do its animation (then disappear after) - WorldPacket data1(CMSG_GAMEOBJ_USE); - data1 << crystal->GetGUID(); - bot->GetSession()->HandleGameObjectUseOpcode(data1); - - // this makes crystal actually remove the buff and put on debuff (took a while to figure that out) - WorldPacket data2(CMSG_GAMEOBJ_USE); - data2 << crystal->GetGUID(); - bot->GetSession()->HandleGameobjectReportUse(data2); - - return true; - } + return false; } - return false; + + float botDist = this->bot->GetDistance(crystal); + + if (botDist > INTERACTION_DISTANCE) + { + return MoveTo( + this->bot->GetMapId(), + crystal->GetPositionX() + frand(-3.5f, 3.5f), + crystal->GetPositionY() + frand(-3.5f, 3.5f), + crystal->GetPositionZ() + ); + } + + // if we're already in range just wait here until it's time to activate crystal + this->SetNextMovementDelay(500); + + // don't activate crystal if boss too far or its already been activated + if (boss->GetDistance(crystal) > 25.0f + || crystal->HasGameObjectFlag(GO_FLAG_IN_USE)) + { + return false; + } + + // don't activate crystal if boss doesn't have buff yet AND isn't going to have it soon + // (though ideally bot should activate it ~5 seconds early due to time it takes for + // crystal to activate and remove buff) + if (!RaidAq20Utils::IsOssirianBuffActive(*boss) && + RaidAq20Utils::GetOssirianDebuffTimeRemaining(*boss) > 5000) + { + return false; + } + + // this makes crystal do its animation (then disappear after) + WorldPacket data1(CMSG_GAMEOBJ_USE); + data1 << crystal->GetGUID(); + bot->GetSession()->HandleGameObjectUseOpcode(data1); + + // this makes crystal actually remove the buff and put on debuff (took a while to figure that out) + WorldPacket data2(CMSG_GAMEOBJ_USE); + data2 << crystal->GetGUID(); + bot->GetSession()->HandleGameobjectReportUse(data2); + + return true; } diff --git a/src/Ai/Raid/Aq20/Trigger/RaidAq20Triggers.cpp b/src/Ai/Raid/Aq20/Trigger/RaidAq20Triggers.cpp index 1a580d6bd3..40f95c9369 100644 --- a/src/Ai/Raid/Aq20/Trigger/RaidAq20Triggers.cpp +++ b/src/Ai/Raid/Aq20/Trigger/RaidAq20Triggers.cpp @@ -1,36 +1,52 @@ #include "RaidAq20Triggers.h" -#include "SharedDefines.h" #include "RaidAq20Utils.h" bool Aq20MoveToCrystalTrigger::IsActive() { - if (Unit* boss = AI_VALUE2(Unit*, "find target", "ossirian the unscarred")) + Unit* const boss = context->GetValue("find target", "ossirian the unscarred")->Get(); + + if (boss == nullptr) { - if (boss->IsInCombat()) + return false; + } + + if (!boss->IsInCombat()) + { + return false; + } + + // if buff is active move to crystal + if (RaidAq20Utils::IsOssirianBuffActive(*boss)) + { + return true; + } + + // if buff is not active a debuff will be, buff becomes active once debuff expires + // so move to crystal when debuff almost done, or based debuff time left and + // distance bot is from crystal (ie: start moving early enough to make it) + int32_t debuffTimeRemaining = RaidAq20Utils::GetOssirianDebuffTimeRemaining(*boss); + + if (debuffTimeRemaining < 5000) + { + return true; + } + + if (debuffTimeRemaining < 30000) + { + const GameObject* const crystal = RaidAq20Utils::GetNearestCrystal(*boss); + + if (crystal == nullptr) { - // if buff is active move to crystal - if (RaidAq20Utils::IsOssirianBuffActive(boss)) - return true; - - // if buff is not active a debuff will be, buff becomes active once debuff expires - // so move to crystal when debuff almost done, or based debuff time left and - // distance bot is from crystal (ie: start moving early enough to make it) - int32 debuffTimeRemaining = RaidAq20Utils::GetOssirianDebuffTimeRemaining(boss); - if (debuffTimeRemaining < 5000) - return true; - if (debuffTimeRemaining < 30000) - { - if (GameObject* crystal = RaidAq20Utils::GetNearestCrystal(boss)) - { - float botDist = bot->GetDistance(crystal); - float timeToReach = botDist / bot->GetSpeed(MOVE_RUN); - // bot should ideally activate crystal a ~5 seconds early (due to time it takes for crystal - // to activate) so aim to get there in time to do so - return debuffTimeRemaining - 5000 < timeToReach * 1000.0f; - } - } + return false; } + + float botDist = this->bot->GetDistance(crystal); + float timeToReach = botDist / this->bot->GetSpeed(MOVE_RUN); + // bot should ideally activate crystal a ~5 seconds early (due to time it takes for crystal + // to activate) so aim to get there in time to do so + return debuffTimeRemaining - 5000 < timeToReach * 1000.0f; } + return false; } diff --git a/src/Ai/Raid/Aq20/Util/RaidAq20Utils.cpp b/src/Ai/Raid/Aq20/Util/RaidAq20Utils.cpp index 41637af7b4..fe005820a5 100644 --- a/src/Ai/Raid/Aq20/Util/RaidAq20Utils.cpp +++ b/src/Ai/Raid/Aq20/Util/RaidAq20Utils.cpp @@ -6,33 +6,43 @@ uint32 const OSSIRIAN_BUFF = 25176; uint32 const OSSIRIAN_DEBUFFS[] = {25177, 25178, 25180, 25181, 25183}; uint32 const OSSIRIAN_CRYSTAL_GO_ENTRY = 180619; -bool RaidAq20Utils::IsOssirianBuffActive(Unit* ossirian) +bool RaidAq20Utils::IsOssirianBuffActive(Unit& ossirian) { - return ossirian && ossirian->HasAura(OSSIRIAN_BUFF); + return ossirian.HasAura(OSSIRIAN_BUFF); } -int32 RaidAq20Utils::GetOssirianDebuffTimeRemaining(Unit* ossirian) +int32_t RaidAq20Utils::GetOssirianDebuffTimeRemaining(Unit& ossirian) { - int32 retVal = 0xffffff; - if (ossirian) + int32_t retVal = 0xffffff; + + for (uint32_t debuff : OSSIRIAN_DEBUFFS) { - for (uint32 debuff : OSSIRIAN_DEBUFFS) + const AuraApplication* const auraApplication = ossirian.GetAuraApplication(debuff); + + if (auraApplication == nullptr) + { + continue; + } + + const Aura* const aura = auraApplication->GetBase(); + + if (aura == nullptr) { - if (AuraApplication* auraApplication = ossirian->GetAuraApplication(debuff)) - { - if (Aura* aura = auraApplication->GetBase()) - { - int32 duration = aura->GetDuration(); - if (retVal > duration) - retVal = duration; - } - } + continue; + } + + int32_t duration = aura->GetDuration(); + + if (retVal > duration) + { + retVal = duration; } } + return retVal; } -GameObject* RaidAq20Utils::GetNearestCrystal(Unit* ossirian) +GameObject* RaidAq20Utils::GetNearestCrystal(Unit& ossirian) { - return ossirian ? ossirian->FindNearestGameObject(OSSIRIAN_CRYSTAL_GO_ENTRY, 200.0f) : nullptr; + return ossirian.FindNearestGameObject(OSSIRIAN_CRYSTAL_GO_ENTRY, 200.0f); } diff --git a/src/Ai/Raid/Aq20/Util/RaidAq20Utils.h b/src/Ai/Raid/Aq20/Util/RaidAq20Utils.h index b78340d0e1..bfa6e43c48 100644 --- a/src/Ai/Raid/Aq20/Util/RaidAq20Utils.h +++ b/src/Ai/Raid/Aq20/Util/RaidAq20Utils.h @@ -7,9 +7,9 @@ class RaidAq20Utils { public: - static bool IsOssirianBuffActive(Unit* ossirian); - static int32 GetOssirianDebuffTimeRemaining(Unit* ossirian); - static GameObject* GetNearestCrystal(Unit* ossirian); + static bool IsOssirianBuffActive(Unit& ossirian); + static int32 GetOssirianDebuffTimeRemaining(Unit& ossirian); + static GameObject* GetNearestCrystal(Unit& ossirian); }; #endif diff --git a/src/Ai/Raid/BlackwingLair/Action/RaidBwlActions.cpp b/src/Ai/Raid/BlackwingLair/Action/RaidBwlActions.cpp index 54b21791e8..795f6c9e89 100644 --- a/src/Ai/Raid/BlackwingLair/Action/RaidBwlActions.cpp +++ b/src/Ai/Raid/BlackwingLair/Action/RaidBwlActions.cpp @@ -2,7 +2,7 @@ #include "Playerbots.h" -bool BwlOnyxiaScaleCloakAuraCheckAction::Execute(Event event) +bool BwlOnyxiaScaleCloakAuraCheckAction::Execute(Event) { bot->AddAura(22683, bot); return true; @@ -10,7 +10,7 @@ bool BwlOnyxiaScaleCloakAuraCheckAction::Execute(Event event) bool BwlOnyxiaScaleCloakAuraCheckAction::isUseful() { return !bot->HasAura(22683); } -bool BwlTurnOffSuppressionDeviceAction::Execute(Event event) +bool BwlTurnOffSuppressionDeviceAction::Execute(Event) { GuidVector gos = AI_VALUE(GuidVector, "nearest game objects"); for (GuidVector::iterator i = gos.begin(); i != gos.end(); i++) @@ -29,4 +29,4 @@ bool BwlTurnOffSuppressionDeviceAction::Execute(Event event) return true; } -bool BwlUseHourglassSandAction::Execute(Event event) { return botAI->CastSpell(23645, bot); } +bool BwlUseHourglassSandAction::Execute(Event) { return botAI->CastSpell(23645, bot); } diff --git a/src/Ai/Raid/EyeOfEternity/Action/RaidEoEActions.cpp b/src/Ai/Raid/EyeOfEternity/Action/RaidEoEActions.cpp index 3547388426..0f47adda71 100644 --- a/src/Ai/Raid/EyeOfEternity/Action/RaidEoEActions.cpp +++ b/src/Ai/Raid/EyeOfEternity/Action/RaidEoEActions.cpp @@ -2,7 +2,7 @@ #include "RaidEoEActions.h" #include "RaidEoETriggers.h" -bool MalygosPositionAction::Execute(Event event) +bool MalygosPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "malygos"); if (!boss) { return false; } @@ -65,7 +65,7 @@ bool MalygosPositionAction::Execute(Event event) return false; } -bool MalygosTargetAction::Execute(Event event) +bool MalygosTargetAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "malygos"); if (!boss) { return false; } @@ -229,7 +229,7 @@ bool EoEFlyDrakeAction::isPossible() Unit* vehicleBase = bot->GetVehicleBase(); return (vehicleBase && vehicleBase->GetEntry() == NPC_WYRMREST_SKYTALON); } -bool EoEFlyDrakeAction::Execute(Event event) +bool EoEFlyDrakeAction::Execute(Event) { Player* master = botAI->GetMaster(); if (!master) { return false; } @@ -279,7 +279,7 @@ bool EoEDrakeAttackAction::isPossible() return (vehicleBase && vehicleBase->GetEntry() == NPC_WYRMREST_SKYTALON); } -bool EoEDrakeAttackAction::Execute(Event event) +bool EoEDrakeAttackAction::Execute(Event) { vehicleBase = bot->GetVehicleBase(); if (!vehicleBase) @@ -367,8 +367,6 @@ bool EoEDrakeAttackAction::DrakeDpsAction(Unit* target) Unit* vehicleBase = bot->GetVehicleBase(); if (!vehicleBase) { return false; } - Vehicle* veh = bot->GetVehicle(); - uint8 comboPoints = vehicleBase->GetComboPoints(target); if (comboPoints >= 2) { diff --git a/src/Ai/Raid/GruulsLair/Action/RaidGruulsLairActions.cpp b/src/Ai/Raid/GruulsLair/Action/RaidGruulsLairActions.cpp index 1a98135cac..b4ffd799df 100644 --- a/src/Ai/Raid/GruulsLair/Action/RaidGruulsLairActions.cpp +++ b/src/Ai/Raid/GruulsLair/Action/RaidGruulsLairActions.cpp @@ -9,7 +9,7 @@ using namespace GruulsLairHelpers; // High King Maulgar Actions // Main tank on Maulgar -bool HighKingMaulgarMainTankAttackMaulgarAction::Execute(Event event) +bool HighKingMaulgarMainTankAttackMaulgarAction::Execute(Event) { Unit* maulgar = AI_VALUE2(Unit*, "find target", "high king maulgar"); @@ -52,7 +52,7 @@ bool HighKingMaulgarMainTankAttackMaulgarAction::Execute(Event event) } // First offtank on Olm -bool HighKingMaulgarFirstAssistTankAttackOlmAction::Execute(Event event) +bool HighKingMaulgarFirstAssistTankAttackOlmAction::Execute(Event) { Unit* olm = AI_VALUE2(Unit*, "find target", "olm the summoner"); @@ -92,7 +92,7 @@ bool HighKingMaulgarFirstAssistTankAttackOlmAction::Execute(Event event) } // Second offtank on Blindeye -bool HighKingMaulgarSecondAssistTankAttackBlindeyeAction::Execute(Event event) +bool HighKingMaulgarSecondAssistTankAttackBlindeyeAction::Execute(Event) { Unit* blindeye = AI_VALUE2(Unit*, "find target", "blindeye the seer"); @@ -135,7 +135,7 @@ bool HighKingMaulgarSecondAssistTankAttackBlindeyeAction::Execute(Event event) } // Mage with highest max HP on Krosh -bool HighKingMaulgarMageTankAttackKroshAction::Execute(Event event) +bool HighKingMaulgarMageTankAttackKroshAction::Execute(Event) { Unit* krosh = AI_VALUE2(Unit*, "find target", "krosh firehand"); @@ -189,7 +189,7 @@ bool HighKingMaulgarMageTankAttackKroshAction::Execute(Event event) } // Moonkin with highest max HP on Kiggler -bool HighKingMaulgarMoonkinTankAttackKigglerAction::Execute(Event event) +bool HighKingMaulgarMoonkinTankAttackKigglerAction::Execute(Event) { Unit* kiggler = AI_VALUE2(Unit*, "find target", "kiggler the crazed"); @@ -212,7 +212,7 @@ bool HighKingMaulgarMoonkinTankAttackKigglerAction::Execute(Event event) return false; } -bool HighKingMaulgarAssignDPSPriorityAction::Execute(Event event) +bool HighKingMaulgarAssignDPSPriorityAction::Execute(Event) { // Target priority 1: Blindeye Unit* blindeye = AI_VALUE2(Unit*, "find target", "blindeye the seer"); @@ -336,7 +336,7 @@ bool HighKingMaulgarAssignDPSPriorityAction::Execute(Event event) } // Avoid Whirlwind and Blast Wave and generally try to stay near the center of the room -bool HighKingMaulgarHealerFindSafePositionAction::Execute(Event event) +bool HighKingMaulgarHealerFindSafePositionAction::Execute(Event) { const Location& fightCenter = GruulsLairLocations::MaulgarRoomCenter; const float maxDistanceFromFight = 50.0f; @@ -370,7 +370,7 @@ bool HighKingMaulgarHealerFindSafePositionAction::Execute(Event event) } // Run away from Maulgar during Whirlwind (logic for after all other ogres are dead) -bool HighKingMaulgarRunAwayFromWhirlwindAction::Execute(Event event) +bool HighKingMaulgarRunAwayFromWhirlwindAction::Execute(Event) { Unit* maulgar = AI_VALUE2(Unit*, "find target", "high king maulgar"); @@ -403,7 +403,7 @@ bool HighKingMaulgarRunAwayFromWhirlwindAction::Execute(Event event) return false; } -bool HighKingMaulgarBanishFelstalkerAction::Execute(Event event) +bool HighKingMaulgarBanishFelstalkerAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -436,7 +436,9 @@ bool HighKingMaulgarBanishFelstalkerAction::Execute(Event event) } } - if (warlockIndex >= 0 && warlockIndex < felStalkers.size()) + const int64_t felStalkersSize = felStalkers.size(); + + if (warlockIndex >= 0 && warlockIndex < felStalkersSize) { Unit* assignedFelStalker = felStalkers[warlockIndex]; if (!assignedFelStalker->HasAura(SPELL_BANISH) && botAI->CanCastSpell(SPELL_BANISH, assignedFelStalker, true)) @@ -448,7 +450,7 @@ bool HighKingMaulgarBanishFelstalkerAction::Execute(Event event) // Hunter 1: Misdirect Olm to first offtank and have pet attack Blindeye // Hunter 2: Misdirect Blindeye to second offtank -bool HighKingMaulgarMisdirectOlmAndBlindeyeAction::Execute(Event event) +bool HighKingMaulgarMisdirectOlmAndBlindeyeAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -528,7 +530,7 @@ bool HighKingMaulgarMisdirectOlmAndBlindeyeAction::Execute(Event event) // Gruul the Dragonkiller Actions // Position in center of the room -bool GruulTheDragonkillerMainTankPositionBossAction::Execute(Event event) +bool GruulTheDragonkillerMainTankPositionBossAction::Execute(Event) { Unit* gruul = AI_VALUE2(Unit*, "find target", "gruul the dragonkiller"); @@ -546,7 +548,6 @@ bool GruulTheDragonkillerMainTankPositionBossAction::Execute(Event event) if (distanceToTankPosition > maxDistance) { - float step = std::min(maxDistance, distanceToTankPosition); float moveX = bot->GetPositionX() + (dX / distanceToTankPosition) * maxDistance; float moveY = bot->GetPositionY() + (dY / distanceToTankPosition) * maxDistance; const float moveZ = tankPosition.z; @@ -569,7 +570,7 @@ bool GruulTheDragonkillerMainTankPositionBossAction::Execute(Event event) // Ranged will take initial positions around the middle of the room, 25-40 yards from center // Ranged should spread out 10 yards from each other -bool GruulTheDragonkillerSpreadRangedAction::Execute(Event event) +bool GruulTheDragonkillerSpreadRangedAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -662,7 +663,7 @@ bool GruulTheDragonkillerSpreadRangedAction::Execute(Event event) } // Try to get away from other group members when Ground Slam is cast -bool GruulTheDragonkillerShatterSpreadAction::Execute(Event event) +bool GruulTheDragonkillerShatterSpreadAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) diff --git a/src/Ai/Raid/GruulsLair/Util/RaidGruulsLairHelpers.cpp b/src/Ai/Raid/GruulsLair/Util/RaidGruulsLairHelpers.cpp index 0c8a23a19c..d10c1c1209 100644 --- a/src/Ai/Raid/GruulsLair/Util/RaidGruulsLairHelpers.cpp +++ b/src/Ai/Raid/GruulsLair/Util/RaidGruulsLairHelpers.cpp @@ -95,7 +95,7 @@ namespace GruulsLairHelpers } } - bool IsKroshMageTank(PlayerbotAI* botAI, Player* bot) + bool IsKroshMageTank(PlayerbotAI*, Player* bot) { Group* group = bot->GetGroup(); if (!group) @@ -123,7 +123,7 @@ namespace GruulsLairHelpers return highestHpMage == bot; } - bool IsKigglerMoonkinTank(PlayerbotAI* botAI, Player* bot) + bool IsKigglerMoonkinTank(PlayerbotAI*, Player* bot) { Group* group = bot->GetGroup(); if (!group) diff --git a/src/Ai/Raid/Icecrown/Action/RaidIccActions.cpp b/src/Ai/Raid/Icecrown/Action/RaidIccActions.cpp index 14c8ada9ac..7876187a63 100644 --- a/src/Ai/Raid/Icecrown/Action/RaidIccActions.cpp +++ b/src/Ai/Raid/Icecrown/Action/RaidIccActions.cpp @@ -1,19 +1,16 @@ #include "RaidIccActions.h" #include "NearestNpcsValue.h" #include "ObjectAccessor.h" -#include "RaidIccStrategy.h" #include "Playerbots.h" -#include "Timer.h" #include "Vehicle.h" #include "RtiValue.h" #include "GenericSpellActions.h" #include "GenericActions.h" -#include #include "RaidIccTriggers.h" #include "Multiplier.h" // Lord Marrowgwar -bool IccLmTankPositionAction::Execute(Event event) +bool IccLmTankPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "lord marrowgar"); if (!boss) @@ -73,7 +70,7 @@ bool IccLmTankPositionAction::MoveTowardPosition(const Position& position, float MovementPriority::MOVEMENT_COMBAT); } -bool IccSpikeAction::Execute(Event event) +bool IccSpikeAction::Execute(Event) { // If we're impaled, we can't do anything if (botAI->GetAura("Impaled", bot)) @@ -183,7 +180,7 @@ void IccSpikeAction::UpdateRaidTargetIcon(Unit* target) } // Lady Deathwhisper -bool IccDarkReckoningAction::Execute(Event event) +bool IccDarkReckoningAction::Execute(Event) { constexpr float SAFE_DISTANCE_THRESHOLD = 2.0f; @@ -201,7 +198,7 @@ bool IccDarkReckoningAction::Execute(Event event) return false; } -bool IccRangedPositionLadyDeathwhisperAction::Execute(Event event) +bool IccRangedPositionLadyDeathwhisperAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "lady deathwhisper"); if (!boss) @@ -301,7 +298,7 @@ bool IccRangedPositionLadyDeathwhisperAction::MaintainRangedSpacing() return false; // Everyone is properly spaced } -bool IccAddsLadyDeathwhisperAction::Execute(Event event) +bool IccAddsLadyDeathwhisperAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "lady deathwhisper"); if (!boss) @@ -419,7 +416,7 @@ void IccAddsLadyDeathwhisperAction::UpdateRaidTargetIcon(Unit* target) } } -bool IccShadeLadyDeathwhisperAction::Execute(Event event) +bool IccShadeLadyDeathwhisperAction::Execute(Event) { static constexpr uint32 VENGEFUL_SHADE_ID = NPC_SHADE; static constexpr float SAFE_DISTANCE = 12.0f; @@ -473,7 +470,7 @@ bool IccShadeLadyDeathwhisperAction::Execute(Event event) return false; } -bool IccRottingFrostGiantTankPositionAction::Execute(Event event) +bool IccRottingFrostGiantTankPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "rotting frost giant"); if (!boss) @@ -696,7 +693,7 @@ bool IccRottingFrostGiantTankPositionAction::Execute(Event event) } //Gunship -bool IccCannonFireAction::Execute(Event event) +bool IccCannonFireAction::Execute(Event) { Unit* vehicleBase = bot->GetVehicleBase(); Vehicle* vehicle = bot->GetVehicle(); @@ -755,7 +752,7 @@ bool IccCannonFireAction::TryCastCannonSpell(uint32 spellId, Unit* target, Unit* return false; } -bool IccGunshipEnterCannonAction::Execute(Event event) +bool IccGunshipEnterCannonAction::Execute(Event) { // Do not switch vehicles if already in one if (bot->GetVehicle()) @@ -855,7 +852,7 @@ bool IccGunshipEnterCannonAction::EnterVehicle(Unit* vehicleBase, bool moveIfFar return true; } -bool IccGunshipTeleportAllyAction::Execute(Event event) +bool IccGunshipTeleportAllyAction::Execute(Event) { static constexpr float MAX_WAITING_DISTANCE = 45.0f; static constexpr float MAX_ATTACK_DISTANCE = 15.0f; @@ -922,7 +919,7 @@ void IccGunshipTeleportAllyAction::UpdateBossSkullIcon(Unit* boss, uint8_t SKULL } } -bool IccGunshipTeleportHordeAction::Execute(Event event) +bool IccGunshipTeleportHordeAction::Execute(Event) { static constexpr float MAX_WAITING_DISTANCE = 45.0f; static constexpr float MAX_ATTACK_DISTANCE = 15.0f; @@ -990,7 +987,7 @@ void IccGunshipTeleportHordeAction::UpdateBossSkullIcon(Unit* boss, uint8_t SKUL } //DBS -bool IccDbsTankPositionAction::Execute(Event event) +bool IccDbsTankPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "deathbringer saurfang"); if (!boss) @@ -1037,8 +1034,6 @@ bool IccDbsTankPositionAction::CrowdControlBloodBeasts() NPC_BLOOD_BEAST4}; const GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); - bool appliedCC = false; - for (auto const& npc : npcs) { Unit* unit = botAI->GetUnit(npc); @@ -1059,70 +1054,60 @@ bool IccDbsTankPositionAction::CrowdControlBloodBeasts() if (!botAI->HasAura("Frost Nova", unit)) { botAI->CastSpell("Frost Nova", unit); - appliedCC = true; } break; case CLASS_DRUID: if (!botAI->HasAura("Entangling Roots", unit)) { botAI->CastSpell("Entangling Roots", unit); - appliedCC = true; } break; case CLASS_PALADIN: if (!botAI->HasAura("Hammer of Justice", unit)) { botAI->CastSpell("Hammer of Justice", unit); - appliedCC = true; } break; case CLASS_WARRIOR: if (!botAI->HasAura("Hamstring", unit)) { botAI->CastSpell("Hamstring", unit); - appliedCC = true; } break; case CLASS_HUNTER: if (!botAI->HasAura("Concussive Shot", unit)) { botAI->CastSpell("Concussive Shot", unit); - appliedCC = true; } break; case CLASS_ROGUE: if (!botAI->HasAura("Kidney Shot", unit)) { botAI->CastSpell("Kidney Shot", unit); - appliedCC = true; } break; case CLASS_SHAMAN: if (!botAI->HasAura("Frost Shock", unit)) { botAI->CastSpell("Frost Shock", unit); - appliedCC = true; } break; case CLASS_DEATH_KNIGHT: if (!botAI->HasAura("Chains of Ice", unit)) { botAI->CastSpell("Chains of Ice", unit); - appliedCC = true; } break; case CLASS_PRIEST: if (!botAI->HasAura("Psychic Scream", unit)) { botAI->CastSpell("Psychic Scream", unit); - appliedCC = true; } break; case CLASS_WARLOCK: if (!botAI->HasAura("Fear", unit)) { botAI->CastSpell("Fear", unit); - appliedCC = true; } break; default: @@ -1231,7 +1216,7 @@ bool IccDbsTankPositionAction::PositionInRangedFormation() return false; } -bool IccAddsDbsAction::Execute(Event event) +bool IccAddsDbsAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "deathbringer saurfang"); if (!boss) @@ -1295,7 +1280,7 @@ void IccAddsDbsAction::UpdateSkullMarker(Unit* priorityTarget) } // Festergut -bool IccFestergutGroupPositionAction::Execute(Event event) +bool IccFestergutGroupPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "festergut"); if (!boss) @@ -1467,7 +1452,6 @@ int IccFestergutGroupPositionAction::CalculatePositionIndex(Group* group) else { // Fill remaining spots in second row - int spotsInFirstRow = 6; int spotsInSecondRow = healerSpotsUsed - 6; int remainingInSecondRow = 6 - spotsInSecondRow; @@ -1511,10 +1495,9 @@ int IccFestergutGroupPositionAction::CalculatePositionIndex(Group* group) return -1; } -bool IccFestergutSporeAction::Execute(Event event) +bool IccFestergutSporeAction::Execute(Event) { constexpr float POSITION_TOLERANCE = 4.0f; - constexpr float SPREAD_RADIUS = 2.0f; // Check if bot has spore bool hasSpore = bot->HasAura(SPELL_GAS_SPORE); // gas spore @@ -1624,7 +1607,7 @@ bool IccFestergutSporeAction::CheckMainTankSpore() } // Rotface -bool IccRotfaceTankPositionAction::Execute(Event event) +bool IccRotfaceTankPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "rotface"); if (!boss) @@ -1662,7 +1645,7 @@ bool IccRotfaceTankPositionAction::PositionMainTankAndMelee(Unit* boss) { bool isBossCasting = false; if (boss && boss->HasUnitState(UNIT_STATE_CASTING) && boss->GetCurrentSpell(SPELL_SLIME_SPRAY)) - bool isBossCasting = true; + isBossCasting = true; if (bot->GetExactDist2d(ICC_ROTFACE_CENTER_POSITION) > 7.0f && botAI->HasAggro(boss) && botAI->IsMainTank(bot)) MoveTo(bot->GetMapId(), ICC_ROTFACE_CENTER_POSITION.GetPositionX(), @@ -1700,7 +1683,7 @@ bool IccRotfaceTankPositionAction::HandleAssistTankPositioning(Unit* boss) return HandleBigOozePositioning(boss); } -bool IccRotfaceTankPositionAction::HandleBigOozePositioning(Unit* boss) +bool IccRotfaceTankPositionAction::HandleBigOozePositioning(Unit*) { // Find all big oozes GuidVector bigOozes = AI_VALUE(GuidVector, "nearest hostile npcs"); @@ -1824,28 +1807,21 @@ bool IccRotfaceTankPositionAction::HandleBigOozePositioning(Unit* boss) return false; } -bool IccRotfaceGroupPositionAction::Execute(Event event) +bool IccRotfaceGroupPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "rotface"); if (!boss) return false; const GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); - bool floodPresent = false; for (auto const& npc : npcs) { Unit* unit = botAI->GetUnit(npc); if (!unit || !botAI->HasAura("Ooze Flood", unit)) continue; - - float puddleDistance = bot->GetExactDist2d(unit); - - if (puddleDistance < 30.0f) - floodPresent = true; } - Unit* bigOoze = AI_VALUE2(Unit*, "find target", "big ooze"); bool hasOozeFlood = botAI->HasAura("Ooze Flood", bot); Unit* smallOoze = AI_VALUE2(Unit*, "find target", "little ooze"); bool hasMutatedInfection = botAI->HasAura("Mutated Infection", bot); @@ -1891,7 +1867,7 @@ bool IccRotfaceGroupPositionAction::HandlePuddleAvoidance(Unit* boss) return false; } -bool IccRotfaceGroupPositionAction::MoveAwayFromPuddle(Unit* boss, Unit* puddle, float puddleDistance) +bool IccRotfaceGroupPositionAction::MoveAwayFromPuddle(Unit* boss, Unit* puddle, float) { if (!boss || !puddle) return false; @@ -2017,7 +1993,7 @@ bool IccRotfaceGroupPositionAction::PositionRangedAndHealers(Unit* boss,Unit *sm Difficulty diff = bot->GetRaidDifficulty(); bool isBossCasting = false; if (boss && boss->HasUnitState(UNIT_STATE_CASTING) && boss->GetCurrentSpell(SPELL_SLIME_SPRAY)) - bool isBossCasting = true; + isBossCasting = true; bool isHeroic = (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC); @@ -2052,7 +2028,7 @@ bool IccRotfaceGroupPositionAction::PositionRangedAndHealers(Unit* boss,Unit *sm return FindAndMoveFromClosestMember(boss, smallOoze); } -bool IccRotfaceGroupPositionAction::FindAndMoveFromClosestMember(Unit* boss, Unit* smallOoze) +bool IccRotfaceGroupPositionAction::FindAndMoveFromClosestMember(Unit*, Unit* smallOoze) { const GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); @@ -2073,7 +2049,6 @@ bool IccRotfaceGroupPositionAction::FindAndMoveFromClosestMember(Unit* boss, Uni const float maxMoveDistance = 12.0f; // Limit maximum movement distance const float puddleSafeDistance = 30.0f; // Minimum distance to stay away from puddle const float minCenterDistance = 20.0f; // Minimum distance from center position - const bool isRanged = botAI->IsRanged(bot) || botAI->IsHeal(bot); // Ranged: spread from other members const GuidVector members = AI_VALUE(GuidVector, "group members"); @@ -2175,7 +2150,7 @@ bool IccRotfaceGroupPositionAction::FindAndMoveFromClosestMember(Unit* boss, Uni return false; // Everyone is properly spaced } -bool IccRotfaceMoveAwayFromExplosionAction::Execute(Event event) +bool IccRotfaceMoveAwayFromExplosionAction::Execute(Event) { // Skip if main tank or ooze flood if (botAI->IsMainTank(bot)) @@ -2238,7 +2213,6 @@ bool IccRotfaceMoveAwayFromExplosionAction::MoveToRandomSafeLocation() // Move in increments of 5.0f towards the calculated position float currentX = bot->GetPositionX(); float currentY = bot->GetPositionY(); - float currentZ = bot->GetPositionZ(); float directionX = moveX - currentX; float directionY = moveY - currentY; @@ -2258,7 +2232,7 @@ bool IccRotfaceMoveAwayFromExplosionAction::MoveToRandomSafeLocation() } // Proffesor Putricide -bool IccPutricideGrowingOozePuddleAction::Execute(Event event) +bool IccPutricideGrowingOozePuddleAction::Execute(Event) { Unit* closestPuddle = FindClosestThreateningPuddle(); if (!closestPuddle) @@ -2281,7 +2255,6 @@ Unit* IccPutricideGrowingOozePuddleAction::FindClosestThreateningPuddle() Unit* closestPuddle = nullptr; float closestDistance = FLT_MAX; - float closestSafeDistance = BASE_RADIUS; for (auto const& npc : npcs) { @@ -2298,7 +2271,6 @@ Unit* IccPutricideGrowingOozePuddleAction::FindClosestThreateningPuddle() if (currentDistance < safeDistance && currentDistance < closestDistance) { closestDistance = currentDistance; - closestSafeDistance = safeDistance; closestPuddle = unit; } } @@ -2416,7 +2388,7 @@ bool IccPutricideGrowingOozePuddleAction::IsPositionTooCloseToOtherPuddles(float return false; } -bool IccPutricideVolatileOozeAction::Execute(Event event) +bool IccPutricideVolatileOozeAction::Execute(Event) { static const float STACK_DISTANCE = 7.0f; @@ -2529,7 +2501,7 @@ Unit* IccPutricideVolatileOozeAction::FindAuraTarget() return nullptr; } -bool IccPutricideGasCloudAction::Execute(Event event) +bool IccPutricideGasCloudAction::Execute(Event) { Unit* gasCloud = AI_VALUE2(Unit*, "find target", "gas cloud"); if (!gasCloud) @@ -2806,7 +2778,6 @@ Position IccPutricideGasCloudAction::CalculateEmergencyPosition(const Position& Position bestPos = Position(botPos.GetPositionX() + dx * 15.0f, botPos.GetPositionY() + dy * 15.0f, botPos.GetPositionZ()); float bestFreedom = 0.0f; - static const float MOVEMENT_INCREMENT = 5.0f; // Fixed movement increment // Try fewer directions for emergency but still avoid corners for (int i = 0; i < 8; i++) @@ -2942,7 +2913,7 @@ bool IccPutricideGasCloudAction::GroupHasGaseousBloat(Group* group) return false; } -bool IccPutricideAvoidMalleableGooAction::Execute(Event event) +bool IccPutricideAvoidMalleableGooAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "professor putricide"); if (!boss) @@ -2964,7 +2935,7 @@ bool IccPutricideAvoidMalleableGooAction::Execute(Event event) return HandleBossPositioning(boss); } -bool IccPutricideAvoidMalleableGooAction::HandleTankPositioning(Unit* boss) +bool IccPutricideAvoidMalleableGooAction::HandleTankPositioning(Unit*) { if (!botAI->IsTank(bot)) return false; @@ -3229,7 +3200,7 @@ Position IccPutricideAvoidMalleableGooAction::CalculateIncrementalMove(const Pos } // BPC -bool IccBpcKelesethTankAction::Execute(Event event) +bool IccBpcKelesethTankAction::Execute(Event) { if (!botAI->IsAssistTank(bot)) return false; @@ -3310,7 +3281,7 @@ bool IccBpcKelesethTankAction::Execute(Event event) return false; } -bool IccBpcMainTankAction::Execute(Event event) +bool IccBpcMainTankAction::Execute(Event) { // Main tank specific behavior (higher priority) if (botAI->IsMainTank(bot)) @@ -3427,7 +3398,7 @@ void IccBpcMainTankAction::MarkEmpoweredPrince() } } -bool IccBpcEmpoweredVortexAction::Execute(Event event) +bool IccBpcEmpoweredVortexAction::Execute(Event) { Unit* valanar = AI_VALUE2(Unit*, "find target", "prince valanar"); if (!valanar) @@ -3612,7 +3583,7 @@ bool IccBpcEmpoweredVortexAction::HandleEmpoweredVortexSpread() return false; // Everyone is properly spaced } -bool IccBpcKineticBombAction::Execute(Event event) +bool IccBpcKineticBombAction::Execute(Event) { // Early exit if not ranged DPS if (!botAI->IsRangedDps(bot)) @@ -3657,7 +3628,6 @@ bool IccBpcKineticBombAction::Execute(Event event) Unit* IccBpcKineticBombAction::FindOptimalKineticBomb() { - static constexpr float MAX_HEIGHT_DIFF = 20.0f; static constexpr std::array KINETIC_BOMB_ENTRIES = {NPC_KINETIC_BOMB1, NPC_KINETIC_BOMB2, NPC_KINETIC_BOMB3, NPC_KINETIC_BOMB4}; @@ -3758,7 +3728,7 @@ bool IccBpcKineticBombAction::IsBombAlreadyHandled(Unit* bomb, Group* group) return false; } -bool IccBpcBallOfFlameAction::Execute(Event event) +bool IccBpcBallOfFlameAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "prince taldaram"); if (!boss) @@ -3839,7 +3809,7 @@ bool IccBpcBallOfFlameAction::Execute(Event event) } // Blood Queen Lana'thel -bool IccBqlGroupPositionAction::Execute(Event event) +bool IccBqlGroupPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "blood-queen lana'thel"); if (!boss) @@ -3920,7 +3890,8 @@ bool IccBqlGroupPositionAction::HandleShadowsMovement() GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); Unit* shadows[100]{}; // Reasonable max estimate int shadowCount = 0; - for (int i = 0; i < npcs.size() && shadowCount < 100; i++) + + for (uint64_t i = 0; i < npcs.size() && shadowCount < 100; i++) { Unit* unit = botAI->GetUnit(npcs[i]); if (unit && unit->IsAlive() && unit->GetEntry() == NPC_SWARMING_SHADOWS) @@ -4021,7 +3992,6 @@ bool IccBqlGroupPositionAction::HandleShadowsMovement() // Find closest safe point by searching in both directions from closest point Position safeMoveTarget = closestPoint; - float safeMoveTargetDist = FLT_MAX; bool foundSafe = closestIsSafe; // Only search for safe spots if the closest point isn't already safe @@ -4092,7 +4062,6 @@ bool IccBqlGroupPositionAction::HandleShadowsMovement() if (foundSafe) { // If we found a safe point, penalize based on travel distance along the curve to reach it - float stepsToCurve = minDist / 2.0f; // Approximate steps to reach the curve float safeDist = bot->GetExactDist2d(safeMoveTarget); // Add distance penalty based on how far we need to move along the curve @@ -4373,7 +4342,6 @@ bool IccBqlGroupPositionAction::HandleGroupPosition(Unit* boss, Aura* frenzyAura rangedBots.erase(std::remove(rangedBots.begin(), rangedBots.end(), h), rangedBots.end()); // Distribute remaining ranged evenly - size_t totalRanged = leftSide.size() + rightSide.size() + rangedBots.size(); size_t leftCount = leftSide.size(); size_t rightCount = rightSide.size(); for (Player* p : rangedBots) @@ -4532,14 +4500,14 @@ bool IccBqlGroupPositionAction::HandleGroupPosition(Unit* boss, Aura* frenzyAura // Find all swarming shadows GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); std::vector swarmingShadows; - for (int i = 0; i < npcs.size(); ++i) + for (uint64_t i = 0; i < npcs.size(); ++i) { Unit* unit = botAI->GetUnit(npcs[i]); if (unit && unit->IsAlive() && unit->GetEntry() == NPC_SWARMING_SHADOWS) swarmingShadows.push_back(unit); } - for (int i = 0; i < members.size(); i++) + for (uint64_t i = 0; i < members.size(); i++) { Unit* member = botAI->GetUnit(members[i]); if (!member || !member->IsAlive() || member == bot || botAI->GetAura("Frenzied Bloodthirst", member) || @@ -4601,7 +4569,7 @@ bool IccBqlGroupPositionAction::HandleGroupPosition(Unit* boss, Aura* frenzyAura return false; } -bool IccBqlPactOfDarkfallenAction::Execute(Event event) +bool IccBqlPactOfDarkfallenAction::Execute(Event) { // Check if bot has Pact of the Darkfallen if (!botAI->GetAura("Pact of the Darkfallen", bot)) @@ -4720,7 +4688,7 @@ bool IccBqlPactOfDarkfallenAction::MoveToTargetPosition(const Position& targetPo return false; } -bool IccBqlVampiricBiteAction::Execute(Event event) +bool IccBqlVampiricBiteAction::Execute(Event) { // Only act when bot has Frenzied Bloodthirst if (!botAI->GetAura("Frenzied Bloodthirst", bot)) @@ -4857,7 +4825,7 @@ bool IccBqlVampiricBiteAction::CastVampiricBite(Player* target) } // Sister Svalna -bool IccValkyreSpearAction::Execute(Event event) +bool IccValkyreSpearAction::Execute(Event) { // Find the nearest spear Creature* spear = bot->FindNearestCreature(NPC_SPEAR, 100.0f); @@ -4883,7 +4851,7 @@ bool IccValkyreSpearAction::Execute(Event event) return false; } -bool IccSisterSvalnaAction::Execute(Event event) +bool IccSisterSvalnaAction::Execute(Event) { Unit* svalna = AI_VALUE2(Unit*, "find target", "sister svalna"); if (!svalna || !svalna->HasAura(SPELL_AETHER_SHIELD)) // Check for Aether Shield aura @@ -4908,7 +4876,7 @@ bool IccSisterSvalnaAction::Execute(Event event) } // VDW -bool IccValithriaGroupAction::Execute(Event event) +bool IccValithriaGroupAction::Execute(Event) { // Helper lambda to find nearest creature of given entries auto findNearestCreature = [this](std::initializer_list entries, float range) -> Creature* @@ -5318,7 +5286,7 @@ bool IccValithriaGroupAction::Handle10ManGroupLogic() return false; } -bool IccValithriaPortalAction::Execute(Event event) +bool IccValithriaPortalAction::Execute(Event) { // Only healers should take portals, and not if already inside if (!botAI->IsHeal(bot) || bot->HasAura(SPELL_DREAM_STATE)) @@ -5451,7 +5419,7 @@ bool IccValithriaPortalAction::Execute(Event event) return false; } -bool IccValithriaHealAction::Execute(Event event) +bool IccValithriaHealAction::Execute(Event) { // Early validation checks if (!botAI->IsHeal(bot) || bot->GetHealthPct() < 50.0f) @@ -5541,7 +5509,7 @@ bool IccValithriaHealAction::Execute(Event event) return false; } -bool IccValithriaDreamCloudAction::Execute(Event event) +bool IccValithriaDreamCloudAction::Execute(Event) { // Only execute if we're in dream state if (!bot->HasAura(SPELL_DREAM_STATE)) @@ -5572,7 +5540,6 @@ bool IccValithriaDreamCloudAction::Execute(Event event) auto it = std::find(dreamBots.begin(), dreamBots.end(), bot); if (it == dreamBots.end()) return false; - size_t myIndex = std::distance(dreamBots.begin(), it); // Check if all dream bots are stacked within 3f of the current leader (lowest guid) constexpr float STACK_RADIUS = 2.0f; @@ -5612,7 +5579,7 @@ bool IccValithriaDreamCloudAction::Execute(Event event) std::vector dreamClouds; std::vector nightmareClouds; - for (int i = 0; i < npcs.size(); ++i) + for (uint64_t i = 0; i < npcs.size(); ++i) { Unit* unit = botAI->GetUnit(npcs[i]); if (unit && unit->IsAlive()) @@ -5824,7 +5791,7 @@ bool IccValithriaDreamCloudAction::Execute(Event event) } // Sindragosa -bool IccSindragosaGroupPositionAction::Execute(Event event) +bool IccSindragosaGroupPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss || boss->HasUnitMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY)) @@ -6083,7 +6050,7 @@ bool IccSindragosaGroupPositionAction::MoveIncrementallyToPosition(const Positio MovementPriority::MOVEMENT_COMBAT); } -bool IccSindragosaTankSwapPositionAction::Execute(Event event) +bool IccSindragosaTankSwapPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss) @@ -6107,7 +6074,7 @@ bool IccSindragosaTankSwapPositionAction::Execute(Event event) return false; } -bool IccSindragosaFrostBeaconAction::Execute(Event event) +bool IccSindragosaFrostBeaconAction::Execute(Event) { const Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss) @@ -6341,7 +6308,7 @@ bool IccSindragosaFrostBeaconAction::IsBossFlying(const Unit* boss) ICC_SINDRAGOSA_FLYING_POSITION.GetPositionY()) < 30.0f; } -bool IccSindragosaBlisteringColdAction::Execute(Event event) +bool IccSindragosaBlisteringColdAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss) @@ -6389,7 +6356,7 @@ bool IccSindragosaBlisteringColdAction::Execute(Event event) return false; } -bool IccSindragosaUnchainedMagicAction::Execute(Event event) +bool IccSindragosaUnchainedMagicAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss) @@ -6411,7 +6378,7 @@ bool IccSindragosaUnchainedMagicAction::Execute(Event event) return false; } -bool IccSindragosaChilledToTheBoneAction::Execute(Event event) +bool IccSindragosaChilledToTheBoneAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss) @@ -6434,7 +6401,7 @@ bool IccSindragosaChilledToTheBoneAction::Execute(Event event) return false; } -bool IccSindragosaMysticBuffetAction::Execute(Event event) +bool IccSindragosaMysticBuffetAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); if (!boss || !bot || !bot->IsAlive()) @@ -6517,7 +6484,7 @@ bool IccSindragosaMysticBuffetAction::Execute(Event event) return false; } -bool IccSindragosaFrostBombAction::Execute(Event event) +bool IccSindragosaFrostBombAction::Execute(Event) { if (!bot || !bot->IsAlive() || bot->HasAura(SPELL_ICE_TOMB)) // Skip if dead or in Ice Tomb return false; @@ -6709,7 +6676,6 @@ bool IccSindragosaFrostBombAction::Execute(Event event) } } Unit* losTomb = myTombs[bestIdx]; - ObjectGuid losTombGuid = myTombGuids[bestIdx]; // Calculate position for LOS (stand at least 6.5f behind the tomb from the bomb) float angle = marker->GetAngle(losTomb); @@ -6792,7 +6758,6 @@ bool IccSindragosaFrostBombAction::Execute(Event event) // Clear the marker for our group's icon group->SetTargetIcon(iconIndex, bot->GetGUID(), ObjectGuid::Empty); } - Unit* boss = AI_VALUE2(Unit*, "find target", "sindragosa"); bot->AttackStop(); return true; } @@ -6802,7 +6767,7 @@ bool IccSindragosaFrostBombAction::Execute(Event event) } // The Lich King -bool IccLichKingShadowTrapAction::Execute(Event event) +bool IccLichKingShadowTrapAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "the lich king"); if (!boss || !botAI->IsTank(bot)) @@ -6810,7 +6775,7 @@ bool IccLichKingShadowTrapAction::Execute(Event event) Difficulty diff = bot->GetRaidDifficulty(); - if (sPlayerbotAIConfig->EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) + if (sPlayerbotAIConfig.EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { //-------CHEAT------- if (!bot->HasAura(SPELL_EXPERIENCED)) @@ -6929,7 +6894,7 @@ bool IccLichKingShadowTrapAction::Execute(Event event) return false; } -bool IccLichKingNecroticPlagueAction::Execute(Event event) +bool IccLichKingNecroticPlagueAction::Execute(Event) { bool hasPlague = botAI->HasAura("Necrotic Plague", bot); // Only execute if we have the plague @@ -6981,7 +6946,7 @@ bool IccLichKingNecroticPlagueAction::Execute(Event event) return false; } -bool IccLichKingWinterAction::Execute(Event event) +bool IccLichKingWinterAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "the lich king"); if (!boss) @@ -7006,7 +6971,7 @@ bool IccLichKingWinterAction::Execute(Event event) Difficulty diff = bot->GetRaidDifficulty(); - if (sPlayerbotAIConfig->EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) + if (sPlayerbotAIConfig.EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { //------CHEAT------- if (!bot->HasAura(SPELL_EXPERIENCED)) @@ -7032,7 +6997,6 @@ bool IccLichKingWinterAction::Execute(Event event) const ObjectGuid currentSkullTarget = group->GetTargetIcon(7); if (!currentSkullTarget.IsEmpty()) { - Unit* skullTarget = ObjectAccessor::GetUnit(*bot, currentSkullTarget); group->SetTargetIcon(7, bot->GetGUID(), ObjectGuid::Empty); } } @@ -7196,7 +7160,7 @@ const Position* IccLichKingWinterAction::GetMainTankRangedPosition() return &ICC_LK_FROSTR3_POSITION; } -bool IccLichKingWinterAction::IsPositionSafeFromDefile(float x, float y, float z, float minSafeDistance) +bool IccLichKingWinterAction::IsPositionSafeFromDefile(float x, float y, float, float minSafeDistance) { Unit* boss = AI_VALUE2(Unit*, "find target", "the lich king"); if (!boss) @@ -7556,7 +7520,7 @@ void IccLichKingWinterAction::HandleRangedPositioning() } } -void IccLichKingWinterAction::HandleMainTankAddManagement(Unit* boss, const Position* tankPos) +void IccLichKingWinterAction::HandleMainTankAddManagement(Unit*, const Position* tankPos) { if (!botAI->IsMainTank(bot)) return; @@ -7679,7 +7643,7 @@ void IccLichKingWinterAction::HandleMainTankAddManagement(Unit* boss, const Posi } } -void IccLichKingWinterAction::HandleAssistTankAddManagement(Unit* boss, const Position* tankPos) +void IccLichKingWinterAction::HandleAssistTankAddManagement(Unit*, const Position* tankPos) { if (!botAI->IsAssistTank(bot)) return; @@ -7783,7 +7747,7 @@ void IccLichKingWinterAction::HandleAssistTankAddManagement(Unit* boss, const Po } } -bool IccLichKingAddsAction::Execute(Event event) +bool IccLichKingAddsAction::Execute(Event) { if (bot->HasAura(SPELL_HARVEST_SOUL_VALKYR)) // Don't process actions if bot is picked up by Val'kyr return false; @@ -7792,7 +7756,7 @@ bool IccLichKingAddsAction::Execute(Event event) Difficulty diff = bot->GetRaidDifficulty(); - if (sPlayerbotAIConfig->EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) + if (sPlayerbotAIConfig.EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { //------CHEAT------- if (!bot->HasAura(SPELL_EXPERIENCED)) @@ -7812,7 +7776,6 @@ bool IccLichKingAddsAction::Execute(Event event) //------CHEAT------- } - Unit* spiritWarden = AI_VALUE2(Unit*, "find target", "spirit warden"); bool hasPlague = botAI->HasAura("Necrotic Plague", bot); Unit* terenasMenethilHC = bot->FindNearestCreature(NPC_TERENAS_MENETHIL_HC, 55.0f); @@ -8324,7 +8287,7 @@ bool IccLichKingAddsAction::HandleQuakeMechanics(Unit* boss) return false; } -void IccLichKingAddsAction::HandleShamblingHorrors(Unit* boss, bool hasPlague) +void IccLichKingAddsAction::HandleShamblingHorrors(Unit*, bool) { // Find closest shambling horror GuidVector npcs2 = AI_VALUE(GuidVector, "nearest hostile npcs"); @@ -8485,8 +8448,6 @@ bool IccLichKingAddsAction::HandleAssistTankAddManagement(Unit* boss, Difficulty // In heroic mode, stay at melee position if (diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { - Unit* mainTank = AI_VALUE(Unit*, "main tank"); - if (bot->GetExactDist2d(ICC_LICH_KING_ASSISTHC_POSITION.GetPositionX(), ICC_LICH_KING_ASSISTHC_POSITION.GetPositionY()) > 2.0f) { @@ -8723,7 +8684,6 @@ void IccLichKingAddsAction::HandleDefileMechanics(Unit* boss, Difficulty diff) // Gather all defile units std::vector defiles; - Unit* closestDefile = nullptr; float closestDistance = std::numeric_limits::max(); GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); @@ -8737,7 +8697,6 @@ void IccLichKingAddsAction::HandleDefileMechanics(Unit* boss, Difficulty diff) if (dist < closestDistance) { closestDistance = dist; - closestDefile = unit; } } } @@ -9078,7 +9037,6 @@ void IccLichKingAddsAction::HandleValkyrMarking(const std::vector& grabbi std::sort(sortedValkyrs.begin(), sortedValkyrs.end(), [](Unit* a, Unit* b) { return a->GetGUID() < b->GetGUID(); }); static constexpr uint8_t ICON_INDICES[] = {7, 6, 0}; // Skull, Cross, Star - static constexpr const char* ICON_NAMES[] = {"skull", "cross", "star"}; // In heroic mode, clean up invalid markers for all possible icons if (diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) @@ -9192,7 +9150,7 @@ void IccLichKingAddsAction::HandleValkyrAssignment(const std::vector& gra bot->SetFacingToObject(myValkyr); Difficulty diff = bot->GetRaidDifficulty(); - if (sPlayerbotAIConfig->EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) + if (sPlayerbotAIConfig.EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { //---------CHEAT--------- if (!myValkyr->HasAura(SPELL_HAMMER_OF_JUSTICE)) diff --git a/src/Ai/Raid/Icecrown/Multiplier/RaidIccMultipliers.cpp b/src/Ai/Raid/Icecrown/Multiplier/RaidIccMultipliers.cpp index fc02d56bea..c7f25e3317 100644 --- a/src/Ai/Raid/Icecrown/Multiplier/RaidIccMultipliers.cpp +++ b/src/Ai/Raid/Icecrown/Multiplier/RaidIccMultipliers.cpp @@ -15,7 +15,6 @@ #include "RaidIccActions.h" #include "ReachTargetActions.h" #include "RogueActions.h" -#include "ScriptedCreature.h" #include "ShamanActions.h" #include "UseMeetingStoneAction.h" #include "WarriorActions.h" @@ -25,8 +24,6 @@ // LK global variables namespace { -uint32 g_lastPlagueTime = 0; -bool g_plagueAllowedToCure = false; std::map g_plagueTimes; std::map g_allowCure; std::mutex g_plagueMutex; // Lock before accessing shared variables diff --git a/src/Ai/Raid/Icecrown/Trigger/RaidIccTriggers.cpp b/src/Ai/Raid/Icecrown/Trigger/RaidIccTriggers.cpp index b9ebb8ca8d..8fdef577ec 100644 --- a/src/Ai/Raid/Icecrown/Trigger/RaidIccTriggers.cpp +++ b/src/Ai/Raid/Icecrown/Trigger/RaidIccTriggers.cpp @@ -4,14 +4,9 @@ #include "PlayerbotAIConfig.h" #include "ObjectAccessor.h" #include "GenericTriggers.h" -#include "DungeonStrategyUtils.h" -#include "EventMap.h" #include "Playerbots.h" -#include "ScriptedCreature.h" #include "Trigger.h" -#include "CellImpl.h" #include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "Vehicle.h" //Lord Marrogwar @@ -287,7 +282,7 @@ bool IccPutricideGrowingOozePuddleTrigger::IsActive() Difficulty diff = bot->GetRaidDifficulty(); - if (sPlayerbotAIConfig->EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) + if (sPlayerbotAIConfig.EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { //-------CHEAT------- if (!bot->HasAura(SPELL_EXPERIENCED)) @@ -564,10 +559,7 @@ bool IccBqlVampiricBiteTrigger::IsActive() bool IccValkyreSpearTrigger::IsActive() { // Check if there's a spear nearby - if (Creature* spear = bot->FindNearestCreature(NPC_SPEAR, 100.0f)) - return true; - - return false; + return bot->FindNearestCreature(NPC_SPEAR, 100.0f) != nullptr; } bool IccSisterSvalnaTrigger::IsActive() @@ -834,7 +826,7 @@ bool IccSindragosaGroupPositionTrigger::IsActive() Difficulty diff = bot->GetRaidDifficulty(); - if (sPlayerbotAIConfig->EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) + if (sPlayerbotAIConfig.EnableICCBuffs && diff && (diff == RAID_DIFFICULTY_10MAN_HEROIC || diff == RAID_DIFFICULTY_25MAN_HEROIC)) { //-------CHEAT------- if (!bot->HasAura(SPELL_EXPERIENCED)) @@ -1107,7 +1099,6 @@ bool IccLichKingShadowTrapTrigger::IsActive() // search for all nearby traps GuidVector npcs = AI_VALUE(GuidVector, "nearest hostile npcs"); std::vector nearbyTraps; - bool needToMove = false; for (auto& npc : npcs) { @@ -1151,15 +1142,21 @@ bool IccLichKingWinterTrigger::IsActive() isCasting = true; bool isWinter = false; - if (boss && boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER1) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER2) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER5) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER6) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER3) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER4) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER7) || - boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER8)) + if (boss + && ( + boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER1) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER2) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER5) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER6) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER3) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER4) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER7) + || boss->FindCurrentSpellBySpellId(SPELL_REMORSELESS_WINTER8) + ) + ) + { isWinter = true; + } if (hasWinterAura || hasWinter2Aura) return true; diff --git a/src/Ai/Raid/Karazhan/Action/RaidKarazhanActions.cpp b/src/Ai/Raid/Karazhan/Action/RaidKarazhanActions.cpp index 2e5d7abcfd..b9f85b1cfd 100644 --- a/src/Ai/Raid/Karazhan/Action/RaidKarazhanActions.cpp +++ b/src/Ai/Raid/Karazhan/Action/RaidKarazhanActions.cpp @@ -9,7 +9,7 @@ using namespace KarazhanHelpers; // Mana Warps blow up when they die for massive raid damage // But they cannot cast the ability if they are stunned -bool ManaWarpStunCreatureBeforeWarpBreachAction::Execute(Event event) +bool ManaWarpStunCreatureBeforeWarpBreachAction::Execute(Event) { Unit* manaWarp = GetFirstAliveUnitByEntry(botAI, NPC_MANA_WARP); if (!manaWarp) @@ -39,7 +39,7 @@ bool ManaWarpStunCreatureBeforeWarpBreachAction::Execute(Event event) // Attumen the Huntsman // Prioritize Midnight until Attumen is mounted -bool AttumenTheHuntsmanMarkTargetAction::Execute(Event event) +bool AttumenTheHuntsmanMarkTargetAction::Execute(Event) { Unit* attumenMounted = GetFirstAliveUnitByEntry(botAI, NPC_ATTUMEN_THE_HUNTSMAN_MOUNTED); if (attumenMounted) @@ -76,7 +76,7 @@ bool AttumenTheHuntsmanMarkTargetAction::Execute(Event event) } // Off tank should move Attumen out of the way so he doesn't cleave bots -bool AttumenTheHuntsmanSplitBossesAction::Execute(Event event) +bool AttumenTheHuntsmanSplitBossesAction::Execute(Event) { Unit* midnight = AI_VALUE2(Unit*, "find target", "midnight"); if (!midnight) @@ -104,7 +104,7 @@ bool AttumenTheHuntsmanSplitBossesAction::Execute(Event event) } // Stack behind mounted Attumen (inside minimum range of Berserker Charge) -bool AttumenTheHuntsmanStackBehindAction::Execute(Event event) +bool AttumenTheHuntsmanStackBehindAction::Execute(Event) { Unit* attumenMounted = GetFirstAliveUnitByEntry(botAI, NPC_ATTUMEN_THE_HUNTSMAN_MOUNTED); if (!attumenMounted) @@ -125,7 +125,7 @@ bool AttumenTheHuntsmanStackBehindAction::Execute(Event event) } // Reset timer for bots to pause DPS when Attumen mounts Midnight -bool AttumenTheHuntsmanManageDpsTimerAction::Execute(Event event) +bool AttumenTheHuntsmanManageDpsTimerAction::Execute(Event) { Unit* midnight = AI_VALUE2(Unit*, "find target", "midnight"); if (!midnight) @@ -152,7 +152,7 @@ bool AttumenTheHuntsmanManageDpsTimerAction::Execute(Event event) // Moroes -bool MoroesMainTankAttackBossAction::Execute(Event event) +bool MoroesMainTankAttackBossAction::Execute(Event) { Unit* moroes = AI_VALUE2(Unit*, "find target", "moroes"); if (!moroes) @@ -168,7 +168,7 @@ bool MoroesMainTankAttackBossAction::Execute(Event event) } // Mark targets with skull in the recommended kill order -bool MoroesMarkTargetAction::Execute(Event event) +bool MoroesMarkTargetAction::Execute(Event) { Unit* dorothea = AI_VALUE2(Unit*, "find target", "baroness dorothea millstipe"); Unit* catriona = AI_VALUE2(Unit*, "find target", "lady catriona von'indi"); @@ -193,7 +193,7 @@ bool MoroesMarkTargetAction::Execute(Event event) // Tank the boss in the center of the room // Move to healers after Repentenace to break the stun -bool MaidenOfVirtueMoveBossToHealerAction::Execute(Event event) +bool MaidenOfVirtueMoveBossToHealerAction::Execute(Event) { Unit* maiden = AI_VALUE2(Unit*, "find target", "maiden of virtue"); if (!maiden) @@ -247,7 +247,7 @@ bool MaidenOfVirtueMoveBossToHealerAction::Execute(Event event) } // Spread out ranged DPS between the pillars -bool MaidenOfVirtuePositionRangedAction::Execute(Event event) +bool MaidenOfVirtuePositionRangedAction::Execute(Event) { const uint8 maxIndex = 7; uint8 index = 0; @@ -287,7 +287,7 @@ bool MaidenOfVirtuePositionRangedAction::Execute(Event event) // The Big Bad Wolf // Tank the boss at the front left corner of the stage -bool BigBadWolfPositionBossAction::Execute(Event event) +bool BigBadWolfPositionBossAction::Execute(Event) { Unit* wolf = AI_VALUE2(Unit*, "find target", "the big bad wolf"); if (!wolf) @@ -318,7 +318,7 @@ bool BigBadWolfPositionBossAction::Execute(Event event) } // Run away, little girl, run away -bool BigBadWolfRunAwayFromBossAction::Execute(Event event) +bool BigBadWolfRunAwayFromBossAction::Execute(Event) { const ObjectGuid botGuid = bot->GetGUID(); uint8 index = bigBadWolfRunIndex.count(botGuid) ? bigBadWolfRunIndex[botGuid] : 0; @@ -341,7 +341,7 @@ bool BigBadWolfRunAwayFromBossAction::Execute(Event event) // Romulo and Julianne // Keep the couple within 10% HP of each other -bool RomuloAndJulianneMarkTargetAction::Execute(Event event) +bool RomuloAndJulianneMarkTargetAction::Execute(Event) { Unit* romulo = AI_VALUE2(Unit*, "find target", "romulo"); if (!romulo) @@ -370,7 +370,7 @@ bool RomuloAndJulianneMarkTargetAction::Execute(Event event) // The Wizard of Oz // Mark targets with skull in the recommended kill order -bool WizardOfOzMarkTargetAction::Execute(Event event) +bool WizardOfOzMarkTargetAction::Execute(Event) { Unit* dorothee = AI_VALUE2(Unit*, "find target", "dorothee"); Unit* tito = AI_VALUE2(Unit*, "find target", "tito"); @@ -387,7 +387,7 @@ bool WizardOfOzMarkTargetAction::Execute(Event event) } // Mages spam Scorch on Strawman to disorient him -bool WizardOfOzScorchStrawmanAction::Execute(Event event) +bool WizardOfOzScorchStrawmanAction::Execute(Event) { Unit* strawman = AI_VALUE2(Unit*, "find target", "strawman"); if (strawman && botAI->CanCastSpell("scorch", strawman)) @@ -399,7 +399,7 @@ bool WizardOfOzScorchStrawmanAction::Execute(Event event) // The Curator // Prioritize destroying Astral Flares -bool TheCuratorMarkAstralFlareAction::Execute(Event event) +bool TheCuratorMarkAstralFlareAction::Execute(Event) { Unit* flare = AI_VALUE2(Unit*, "find target", "astral flare"); if (!flare) @@ -415,7 +415,7 @@ bool TheCuratorMarkAstralFlareAction::Execute(Event event) // Tank the boss in the center of the hallway near the Guardian's Library // Main tank and off tank will attack the boss; others will focus on Astral Flares -bool TheCuratorPositionBossAction::Execute(Event event) +bool TheCuratorPositionBossAction::Execute(Event) { Unit* curator = AI_VALUE2(Unit*, "find target", "the curator"); if (!curator) @@ -449,7 +449,7 @@ bool TheCuratorPositionBossAction::Execute(Event event) } // Spread out ranged DPS to avoid Arcing Sear damage -bool TheCuratorSpreadRangedAction::Execute(Event event) +bool TheCuratorSpreadRangedAction::Execute(Event) { const float minDistance = 5.0f; Unit* nearestPlayer = GetNearestPlayerInRadius(bot, minDistance); @@ -467,7 +467,7 @@ bool TheCuratorSpreadRangedAction::Execute(Event event) // Terestian Illhoof // Prioritize (1) Demon Chains, (2) Kil'rek, (3) Illhoof -bool TerestianIllhoofMarkTargetAction::Execute(Event event) +bool TerestianIllhoofMarkTargetAction::Execute(Event) { Unit* demonChains = AI_VALUE2(Unit*, "find target", "demon chains"); Unit* kilrek = AI_VALUE2(Unit*, "find target", "kil'rek"); @@ -483,7 +483,7 @@ bool TerestianIllhoofMarkTargetAction::Execute(Event event) // Shade of Aran // Run to the edge of the room to avoid Arcane Explosion -bool ShadeOfAranRunAwayFromArcaneExplosionAction::Execute(Event event) +bool ShadeOfAranRunAwayFromArcaneExplosionAction::Execute(Event) { Unit* aran = AI_VALUE2(Unit*, "find target", "shade of aran"); if (!aran) @@ -502,7 +502,7 @@ bool ShadeOfAranRunAwayFromArcaneExplosionAction::Execute(Event event) } // I will not move when Flame Wreath is cast or the raid blows up -bool ShadeOfAranStopMovingDuringFlameWreathAction::Execute(Event event) +bool ShadeOfAranStopMovingDuringFlameWreathAction::Execute(Event) { AI_VALUE(LastMovement&, "last movement").Set(nullptr); @@ -517,7 +517,7 @@ bool ShadeOfAranStopMovingDuringFlameWreathAction::Execute(Event event) } // Mark Conjured Elementals with skull so DPS can burn them down -bool ShadeOfAranMarkConjuredElementalAction::Execute(Event event) +bool ShadeOfAranMarkConjuredElementalAction::Execute(Event) { Unit* elemental = GetFirstAliveUnitByEntry(botAI, NPC_CONJURED_ELEMENTAL); @@ -529,7 +529,7 @@ bool ShadeOfAranMarkConjuredElementalAction::Execute(Event event) // Don't get closer than 11 yards to Aran to avoid counterspell // Don't get farther than 15 yards from Aran to avoid getting stuck in alcoves -bool ShadeOfAranRangedMaintainDistanceAction::Execute(Event event) +bool ShadeOfAranRangedMaintainDistanceAction::Execute(Event) { Unit* aran = AI_VALUE2(Unit*, "find target", "shade of aran"); if (!aran) @@ -593,7 +593,7 @@ bool ShadeOfAranRangedMaintainDistanceAction::Execute(Event event) // One tank bot per phase will dance in and out of the red beam (5 seconds in, 5 seconds out) // Tank bots will ignore void zones--their positioning is too important to risk losing beam control -bool NetherspiteBlockRedBeamAction::Execute(Event event) +bool NetherspiteBlockRedBeamAction::Execute(Event) { Unit* netherspite = AI_VALUE2(Unit*, "find target", "netherspite"); if (!netherspite) @@ -617,7 +617,7 @@ bool NetherspiteBlockRedBeamAction::Execute(Event event) if (!wasBlocking) { std::map placeholders{{"%player", bot->GetName()}}; - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "netherspite_beam_blocking_red", "%player is moving to block the red beam!", placeholders); bot->Yell(text, LANG_UNIVERSAL); } @@ -680,7 +680,7 @@ Position NetherspiteBlockRedBeamAction::GetPositionOnBeam(Unit* netherspite, Uni // Two non-Rogue/Warrior DPS bots will block the blue beam for each phase (swap at 25 debuff stacks) // When avoiding void zones, blocking bots will move along the beam to continue blocking -bool NetherspiteBlockBlueBeamAction::Execute(Event event) +bool NetherspiteBlockBlueBeamAction::Execute(Event) { Unit* netherspite = AI_VALUE2(Unit*, "find target", "netherspite"); if (!netherspite) @@ -700,7 +700,7 @@ bool NetherspiteBlockBlueBeamAction::Execute(Event event) if (wasBlocking && !isBlockingNow) { std::map placeholders{{"%player", bot->GetName()}}; - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "netherspite_beam_leaving_blue", "%player is leaving the blue beam--next blocker up!", placeholders); bot->Yell(text, LANG_UNIVERSAL); _wasBlockingBlueBeam[botGuid] = false; @@ -711,7 +711,7 @@ bool NetherspiteBlockBlueBeamAction::Execute(Event event) if (!wasBlocking) { std::map placeholders{{"%player", bot->GetName()}}; - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "netherspite_beam_blocking_blue", "%player is moving to block the blue beam!", placeholders); bot->Yell(text, LANG_UNIVERSAL); } @@ -773,7 +773,7 @@ bool NetherspiteBlockBlueBeamAction::Execute(Event event) // Two healer bots will block the green beam for each phase (swap at 25 debuff stacks) // OR one rogue or DPS warrior bot will block the green beam for an entire phase (if they begin the phase as the blocker) // When avoiding void zones, blocking bots will move along the beam to continue blocking -bool NetherspiteBlockGreenBeamAction::Execute(Event event) +bool NetherspiteBlockGreenBeamAction::Execute(Event) { Unit* netherspite = AI_VALUE2(Unit*, "find target", "netherspite"); if (!netherspite) @@ -793,7 +793,7 @@ bool NetherspiteBlockGreenBeamAction::Execute(Event event) if (wasBlocking && !isBlockingNow) { std::map placeholders{{"%player", bot->GetName()}}; - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "netherspite_beam_leaving_green", "%player is leaving the green beam--next blocker up!", placeholders); bot->Yell(text, LANG_UNIVERSAL); _wasBlockingGreenBeam[botGuid] = false; @@ -804,7 +804,7 @@ bool NetherspiteBlockGreenBeamAction::Execute(Event event) if (!wasBlocking) { std::map placeholders{{"%player", bot->GetName()}}; - std::string text = sPlayerbotTextMgr->GetBotTextOrDefault( + std::string text = PlayerbotTextMgr::instance().GetBotTextOrDefault( "netherspite_beam_blocking_green", "%player is moving to block the green beam!", placeholders); bot->Yell(text, LANG_UNIVERSAL); } @@ -863,13 +863,12 @@ bool NetherspiteBlockGreenBeamAction::Execute(Event event) } // All bots not currently blocking a beam will avoid beams and void zones -bool NetherspiteAvoidBeamAndVoidZoneAction::Execute(Event event) +bool NetherspiteAvoidBeamAndVoidZoneAction::Execute(Event) { Unit* netherspite = AI_VALUE2(Unit*, "find target", "netherspite"); if (!netherspite) return false; - auto [redBlocker, greenBlocker, blueBlocker] = GetCurrentBeamBlockers(botAI, bot); std::vector voidZones = GetAllVoidZones(botAI, bot); bool nearVoidZone = !IsSafePosition(bot->GetPositionX(), bot->GetPositionY(), @@ -979,7 +978,7 @@ bool NetherspiteAvoidBeamAndVoidZoneAction::IsAwayFromBeams( return true; } -bool NetherspiteBanishPhaseAvoidVoidZoneAction::Execute(Event event) +bool NetherspiteBanishPhaseAvoidVoidZoneAction::Execute(Event) { std::vector voidZones = GetAllVoidZones(botAI, bot); @@ -992,7 +991,7 @@ bool NetherspiteBanishPhaseAvoidVoidZoneAction::Execute(Event event) return false; } -bool NetherspiteManageTimersAndTrackersAction::Execute(Event event) +bool NetherspiteManageTimersAndTrackersAction::Execute(Event) { Unit* netherspite = AI_VALUE2(Unit*, "find target", "netherspite"); if (!netherspite) @@ -1044,7 +1043,7 @@ bool NetherspiteManageTimersAndTrackersAction::Execute(Event event) // Move away from the boss to avoid Shadow Nova when Enfeebled // Do not cross within Infernal Hellfire radius while doing so -bool PrinceMalchezaarEnfeebledAvoidHazardAction::Execute(Event event) +bool PrinceMalchezaarEnfeebledAvoidHazardAction::Execute(Event) { Unit* malchezaar = AI_VALUE2(Unit*, "find target", "prince malchezaar"); if (!malchezaar) @@ -1056,7 +1055,6 @@ bool PrinceMalchezaarEnfeebledAvoidHazardAction::Execute(Event event) const float minSafeBossDistanceSq = minSafeBossDistance * minSafeBossDistance; const float maxSafeBossDistance = 60.0f; const float safeInfernalDistance = 23.0f; - const float safeInfernalDistanceSq = safeInfernalDistance * safeInfernalDistance; const float distIncrement = 0.5f; const uint8 numAngles = 64; @@ -1121,7 +1119,7 @@ bool PrinceMalchezaarEnfeebledAvoidHazardAction::Execute(Event event) // Move away from infernals while staying within range of the boss // Prioritize finding a safe path to the new location, but will fallback to just finding a safe location if needed -bool PrinceMalchezaarNonTankAvoidInfernalAction::Execute(Event event) +bool PrinceMalchezaarNonTankAvoidInfernalAction::Execute(Event) { Unit* malchezaar = AI_VALUE2(Unit*, "find target", "prince malchezaar"); if (!malchezaar) @@ -1188,7 +1186,7 @@ bool PrinceMalchezaarNonTankAvoidInfernalAction::Execute(Event event) // This is similar to the non-tank avoid infernal action, but the movement is based on the bot's location // And the safe distance from infernals is larger to give melee more room to maneuver -bool PrinceMalchezaarMainTankMovementAction::Execute(Event event) +bool PrinceMalchezaarMainTankMovementAction::Execute(Event) { Unit* malchezaar = AI_VALUE2(Unit*, "find target", "prince malchezaar"); if (!malchezaar) @@ -1254,7 +1252,7 @@ bool PrinceMalchezaarMainTankMovementAction::Execute(Event event) // The tank position is near the Southeastern area of the Master's Terrace // The tank moves Nightbane into position in two steps to try to get Nightbane to face sideways to the raid -bool NightbaneGroundPhasePositionBossAction::Execute(Event event) +bool NightbaneGroundPhasePositionBossAction::Execute(Event) { Unit* nightbane = AI_VALUE2(Unit*, "find target", "nightbane"); if (!nightbane) @@ -1300,7 +1298,7 @@ bool NightbaneGroundPhasePositionBossAction::Execute(Event event) // Ranged bots rotate between 3 positions to avoid standing in Charred Earth, which lasts for // 30s and has a minimum cooldown of 18s (so there can be 2 active at once) // Ranged positions are near the Northeastern door to the tower -bool NightbaneGroundPhaseRotateRangedPositionsAction::Execute(Event event) +bool NightbaneGroundPhaseRotateRangedPositionsAction::Execute(Event) { const ObjectGuid botGuid = bot->GetGUID(); uint8 index = nightbaneRangedStep.count(botGuid) ? nightbaneRangedStep[botGuid] : 0; @@ -1344,7 +1342,7 @@ bool NightbaneGroundPhaseRotateRangedPositionsAction::Execute(Event event) } // For countering Bellowing Roars during the ground phase -bool NightbaneCastFearWardOnMainTankAction::Execute(Event event) +bool NightbaneCastFearWardOnMainTankAction::Execute(Event) { Player* mainTank = nullptr; if (Group* group = bot->GetGroup()) @@ -1367,7 +1365,7 @@ bool NightbaneCastFearWardOnMainTankAction::Execute(Event event) } // Put pets on passive during the flight phase so they don't try to chase Nightbane off the map -bool NightbaneControlPetAggressionAction::Execute(Event event) +bool NightbaneControlPetAggressionAction::Execute(Event) { Unit* nightbane = AI_VALUE2(Unit*, "find target", "nightbane"); if (!nightbane) @@ -1393,7 +1391,7 @@ bool NightbaneControlPetAggressionAction::Execute(Event event) // 2. Once Rain of Bones hits, the whole party moves to a new stack position // This action lasts for the first 35 seconds of the flight phase, after which Nightbane gets // ready to land, and the player will need to lead the bots over near the ground phase position -bool NightbaneFlightPhaseMovementAction::Execute(Event event) +bool NightbaneFlightPhaseMovementAction::Execute(Event) { Unit* nightbane = AI_VALUE2(Unit*, "find target", "nightbane"); if (!nightbane || nightbane->GetPositionZ() <= NIGHTBANE_FLIGHT_Z) @@ -1439,7 +1437,7 @@ bool NightbaneFlightPhaseMovementAction::Execute(Event event) return false; } -bool NightbaneManageTimersAndTrackersAction::Execute(Event event) +bool NightbaneManageTimersAndTrackersAction::Execute(Event) { Unit* nightbane = AI_VALUE2(Unit*, "find target", "nightbane"); if (!nightbane) diff --git a/src/Ai/Raid/Karazhan/Util/RaidKarazhanHelpers.cpp b/src/Ai/Raid/Karazhan/Util/RaidKarazhanHelpers.cpp index 821cc67019..037bf2e9e6 100644 --- a/src/Ai/Raid/Karazhan/Util/RaidKarazhanHelpers.cpp +++ b/src/Ai/Raid/Karazhan/Util/RaidKarazhanHelpers.cpp @@ -1,5 +1,4 @@ #include "RaidKarazhanHelpers.h" -#include "RaidKarazhanActions.h" #include "Playerbots.h" #include "RtiTargetValue.h" @@ -381,7 +380,7 @@ namespace KarazhanHelpers return voidZones; } - bool IsSafePosition(float x, float y, float z, const std::vector& hazards, float hazardRadius) + bool IsSafePosition(float x, float y, float, const std::vector& hazards, float hazardRadius) { for (Unit* hazard : hazards) { @@ -412,10 +411,8 @@ namespace KarazhanHelpers { float sx = start.GetPositionX(); float sy = start.GetPositionY(); - float sz = start.GetPositionZ(); float tx = target.GetPositionX(); float ty = target.GetPositionY(); - float tz = target.GetPositionZ(); const float totalDist = start.GetExactDist2d(target.GetPositionX(), target.GetPositionY()); if (totalDist == 0.0f) @@ -426,7 +423,6 @@ namespace KarazhanHelpers float t = checkDist / totalDist; float checkX = sx + (tx - sx) * t; float checkY = sy + (ty - sy) * t; - float checkZ = sz + (tz - sz) * t; for (Unit* hazard : hazards) { const float hx = checkX - hazard->GetPositionX(); diff --git a/src/Ai/Raid/Magtheridon/Action/RaidMagtheridonActions.cpp b/src/Ai/Raid/Magtheridon/Action/RaidMagtheridonActions.cpp index 69fc862442..5ad70ca292 100644 --- a/src/Ai/Raid/Magtheridon/Action/RaidMagtheridonActions.cpp +++ b/src/Ai/Raid/Magtheridon/Action/RaidMagtheridonActions.cpp @@ -7,7 +7,7 @@ using namespace MagtheridonHelpers; -bool MagtheridonMainTankAttackFirstThreeChannelersAction::Execute(Event event) +bool MagtheridonMainTankAttackFirstThreeChannelersAction::Execute(Event) { Unit* magtheridon = AI_VALUE2(Unit*, "find target", "magtheridon"); if (!magtheridon) @@ -67,7 +67,7 @@ bool MagtheridonMainTankAttackFirstThreeChannelersAction::Execute(Event event) return false; } -bool MagtheridonFirstAssistTankAttackNWChannelerAction::Execute(Event event) +bool MagtheridonFirstAssistTankAttackNWChannelerAction::Execute(Event) { Creature* channelerDiamond = GetChanneler(bot, NORTHWEST_CHANNELER); if (!channelerDiamond || !channelerDiamond->IsAlive()) @@ -100,7 +100,7 @@ bool MagtheridonFirstAssistTankAttackNWChannelerAction::Execute(Event event) return false; } -bool MagtheridonSecondAssistTankAttackNEChannelerAction::Execute(Event event) +bool MagtheridonSecondAssistTankAttackNEChannelerAction::Execute(Event) { Creature* channelerTriangle = GetChanneler(bot, NORTHEAST_CHANNELER); if (!channelerTriangle || !channelerTriangle->IsAlive()) @@ -134,7 +134,7 @@ bool MagtheridonSecondAssistTankAttackNEChannelerAction::Execute(Event event) } // Misdirect West & East Channelers to Main Tank -bool MagtheridonMisdirectHellfireChannelers::Execute(Event event) +bool MagtheridonMisdirectHellfireChannelers::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -211,7 +211,7 @@ bool MagtheridonMisdirectHellfireChannelers::Execute(Event event) return false; } -bool MagtheridonAssignDPSPriorityAction::Execute(Event event) +bool MagtheridonAssignDPSPriorityAction::Execute(Event) { // Listed in order of priority Creature* channelerSquare = GetChanneler(bot, SOUTH_CHANNELER); @@ -306,7 +306,7 @@ bool MagtheridonAssignDPSPriorityAction::Execute(Event event) // Assign Burning Abyssals to Warlocks to Banish // Burning Abyssals in excess of Warlocks in party will be Feared -bool MagtheridonWarlockCCBurningAbyssalAction::Execute(Event event) +bool MagtheridonWarlockCCBurningAbyssalAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -340,7 +340,9 @@ bool MagtheridonWarlockCCBurningAbyssalAction::Execute(Event event) } } - if (warlockIndex >= 0 && warlockIndex < abyssals.size()) + const int64_t abyssalSize = abyssals.size(); + + if (warlockIndex >= 0 && warlockIndex < abyssalSize) { Unit* assignedAbyssal = abyssals[warlockIndex]; if (!assignedAbyssal->HasAura(SPELL_BANISH) && botAI->CanCastSpell(SPELL_BANISH, assignedAbyssal, true)) @@ -359,7 +361,7 @@ bool MagtheridonWarlockCCBurningAbyssalAction::Execute(Event event) } // Main tank will back up to the Northern point of the room -bool MagtheridonMainTankPositionBossAction::Execute(Event event) +bool MagtheridonMainTankPositionBossAction::Execute(Event) { Unit* magtheridon = AI_VALUE2(Unit*, "find target", "magtheridon"); if (!magtheridon) @@ -399,7 +401,7 @@ bool MagtheridonMainTankPositionBossAction::Execute(Event event) std::unordered_map MagtheridonSpreadRangedAction::initialPositions; std::unordered_map MagtheridonSpreadRangedAction::hasReachedInitialPosition; -bool MagtheridonSpreadRangedAction::Execute(Event event) +bool MagtheridonSpreadRangedAction::Execute(Event) { Unit* magtheridon = AI_VALUE2(Unit*, "find target", "magtheridon"); if (!magtheridon) @@ -456,7 +458,7 @@ bool MagtheridonSpreadRangedAction::Execute(Event event) uint8 count = members.size(); float angle = 2 * M_PI * botIndex / count; - float radius = static_cast(rand()) / RAND_MAX * maxSpreadRadius; + float radius = static_cast(rand()) / static_cast(RAND_MAX) * maxSpreadRadius; float targetX = centerX + radius * cos(angle); float targetY = centerY + radius * sin(angle); @@ -489,8 +491,8 @@ bool MagtheridonSpreadRangedAction::Execute(Event event) if (distToCenter > maxSpreadRadius + radiusBuffer) { - float angle = static_cast(rand()) / RAND_MAX * 2.0f * M_PI; - float radius = static_cast(rand()) / RAND_MAX * maxSpreadRadius; + float angle = static_cast(rand()) / static_cast(RAND_MAX) * 2.0f * M_PI; + float radius = static_cast(rand()) / static_cast(RAND_MAX) * maxSpreadRadius; float targetX = centerX + radius * cos(angle); float targetY = centerY + radius * sin(angle); @@ -509,7 +511,7 @@ bool MagtheridonSpreadRangedAction::Execute(Event event) // For bots that are assigned to click cubes // Magtheridon casts Blast Nova every 54.35 to 55.40s, with a 2s cast time -bool MagtheridonUseManticronCubeAction::Execute(Event event) +bool MagtheridonUseManticronCubeAction::Execute(Event) { Unit* magtheridon = AI_VALUE2(Unit*, "find target", "magtheridon"); if (!magtheridon) @@ -543,7 +545,7 @@ bool MagtheridonUseManticronCubeAction::Execute(Event event) return false; } -bool MagtheridonUseManticronCubeAction::HandleCubeRelease(Unit* magtheridon, GameObject* cube) +bool MagtheridonUseManticronCubeAction::HandleCubeRelease(Unit* magtheridon, GameObject*) { if (bot->HasAura(SPELL_SHADOW_GRASP) && !(magtheridon->HasUnitState(UNIT_STATE_CASTING) && @@ -598,7 +600,7 @@ bool MagtheridonUseManticronCubeAction::HandleWaitingPhase(const CubeInfo& cubeI } } - float angle = static_cast(rand()) / RAND_MAX * 2.0f * M_PI; + float angle = static_cast(rand()) / static_cast(RAND_MAX) * 2.0f * M_PI; float fallbackX = cubeInfo.x + cos(angle) * safeWaitDistance; float fallbackY = cubeInfo.y + sin(angle) * safeWaitDistance; float fallbackZ = bot->GetPositionZ(); @@ -650,7 +652,7 @@ bool MagtheridonUseManticronCubeAction::HandleCubeInteraction(const CubeInfo& cu // is not interrupted or takes too long to interrupt, the timer will be thrown off for the rest of the encounter. // Correcting this issue is complicated and probably would need some rewriting--I have not done so and // and view the current solution as sufficient since in TBC a missed Blast Nova would be a guaranteed wipe anyway. -bool MagtheridonManageTimersAndAssignmentsAction::Execute(Event event) +bool MagtheridonManageTimersAndAssignmentsAction::Execute(Event) { Unit* magtheridon = AI_VALUE2(Unit*, "find target", "magtheridon"); if (!magtheridon) diff --git a/src/Ai/Raid/Magtheridon/Multiplier/RaidMagtheridonMultipliers.cpp b/src/Ai/Raid/Magtheridon/Multiplier/RaidMagtheridonMultipliers.cpp index 9580fd923a..cfc0ec2abb 100644 --- a/src/Ai/Raid/Magtheridon/Multiplier/RaidMagtheridonMultipliers.cpp +++ b/src/Ai/Raid/Magtheridon/Multiplier/RaidMagtheridonMultipliers.cpp @@ -59,7 +59,6 @@ float MagtheridonWaitToAttackMultiplier::GetValue(Action* action) float MagtheridonDisableOffTankAssistMultiplier::GetValue(Action* action) { Unit* magtheridon = AI_VALUE2(Unit*, "find target", "magtheridon"); - Unit* channeler = AI_VALUE2(Unit*, "find target", "hellfire channeler"); if (!magtheridon) return 1.0f; diff --git a/src/Ai/Raid/Magtheridon/Util/RaidMagtheridonHelpers.cpp b/src/Ai/Raid/Magtheridon/Util/RaidMagtheridonHelpers.cpp index dc88d2a192..d7113e9b6b 100644 --- a/src/Ai/Raid/Magtheridon/Util/RaidMagtheridonHelpers.cpp +++ b/src/Ai/Raid/Magtheridon/Util/RaidMagtheridonHelpers.cpp @@ -174,7 +174,7 @@ namespace MagtheridonHelpers std::unordered_map spreadWaitTimer; std::unordered_map dpsWaitTimer; - bool IsSafeFromMagtheridonHazards(PlayerbotAI* botAI, Player* bot, float x, float y, float z) + bool IsSafeFromMagtheridonHazards(PlayerbotAI* botAI, Player*, float x, float y, float) { // Debris std::vector debrisHazards; diff --git a/src/Ai/Raid/MoltenCore/Action/RaidMcActions.cpp b/src/Ai/Raid/MoltenCore/Action/RaidMcActions.cpp index b18c8b8534..f0a2b99cfb 100644 --- a/src/Ai/Raid/MoltenCore/Action/RaidMcActions.cpp +++ b/src/Ai/Raid/MoltenCore/Action/RaidMcActions.cpp @@ -2,7 +2,6 @@ #include "Playerbots.h" #include "RtiTargetValue.h" -#include "RaidMcTriggers.h" #include "RaidMcHelpers.h" static constexpr float LIVING_BOMB_DISTANCE = 20.0f; @@ -20,12 +19,12 @@ static constexpr float CORE_RAGER_STEP_DISTANCE = 5.0f; using namespace MoltenCoreHelpers; -bool McMoveFromGroupAction::Execute(Event event) +bool McMoveFromGroupAction::Execute(Event) { return MoveFromGroup(LIVING_BOMB_DISTANCE); } -bool McMoveFromBaronGeddonAction::Execute(Event event) +bool McMoveFromBaronGeddonAction::Execute(Event) { if (Unit* boss = AI_VALUE2(Unit*, "find target", "baron geddon")) { @@ -42,7 +41,7 @@ bool McMoveFromBaronGeddonAction::Execute(Event event) return false; } -bool McShazzrahMoveAwayAction::Execute(Event event) +bool McShazzrahMoveAwayAction::Execute(Event) { if (Unit* boss = AI_VALUE2(Unit*, "find target", "shazzrah")) { @@ -53,7 +52,7 @@ bool McShazzrahMoveAwayAction::Execute(Event event) return false; } -bool McGolemaggMarkBossAction::Execute(Event event) +bool McGolemaggMarkBossAction::Execute(Event) { if (Unit* boss = AI_VALUE2(Unit*, "find target", "golemagg the incinerator")) { @@ -115,7 +114,7 @@ bool McGolemaggTankAction::FindCoreRagers(Unit*& coreRager1, Unit*& coreRager2) return coreRager1 != nullptr && coreRager2 != nullptr; } -bool McGolemaggMainTankAttackGolemaggAction::Execute(Event event) +bool McGolemaggMainTankAttackGolemaggAction::Execute(Event) { // At this point, we know we are not the last living tank in the group. if (Unit* boss = AI_VALUE2(Unit*, "find target", "golemagg the incinerator")) diff --git a/src/Ai/Raid/ObsidianSanctum/Action/RaidOsActions.cpp b/src/Ai/Raid/ObsidianSanctum/Action/RaidOsActions.cpp index 724b91902f..c6834925f1 100644 --- a/src/Ai/Raid/ObsidianSanctum/Action/RaidOsActions.cpp +++ b/src/Ai/Raid/ObsidianSanctum/Action/RaidOsActions.cpp @@ -3,14 +3,11 @@ #include "Playerbots.h" -bool SartharionTankPositionAction::Execute(Event event) +bool SartharionTankPositionAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sartharion"); if (!boss) { return false; } - // Unit* shadron = AI_VALUE2(Unit*, "find target", "shadron"); - // Unit* tenebron = AI_VALUE2(Unit*, "find target", "tenebron"); - // Unit* vesperon = AI_VALUE2(Unit*, "find target", "vesperon"); Unit* shadron = nullptr; Unit* tenebron = nullptr; Unit* vesperon = nullptr; @@ -84,7 +81,7 @@ bool SartharionTankPositionAction::Execute(Event event) return false; } -bool AvoidTwilightFissureAction::Execute(Event event) +bool AvoidTwilightFissureAction::Execute(Event) { const float radius = 5.0f; @@ -104,7 +101,7 @@ bool AvoidTwilightFissureAction::Execute(Event event) return false; } -bool AvoidFlameTsunamiAction::Execute(Event event) +bool AvoidFlameTsunamiAction::Execute(Event) { // Adjustable, this is the acceptable distance to stack point that will be accepted as "safe" float looseDistance = 4.0f; @@ -167,7 +164,7 @@ bool AvoidFlameTsunamiAction::Execute(Event event) return false; } -bool SartharionAttackPriorityAction::Execute(Event event) +bool SartharionAttackPriorityAction::Execute(Event) { Unit* sartharion = AI_VALUE2(Unit*, "find target", "sartharion"); Unit* shadron = AI_VALUE2(Unit*, "find target", "shadron"); @@ -206,7 +203,7 @@ bool SartharionAttackPriorityAction::Execute(Event event) return false; } -bool EnterTwilightPortalAction::Execute(Event event) +bool EnterTwilightPortalAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "sartharion"); if (!boss || !boss->HasAura(SPELL_GIFT_OF_TWILIGHT_FIRE)) { return false; } @@ -227,7 +224,7 @@ bool EnterTwilightPortalAction::Execute(Event event) return true; } -bool ExitTwilightPortalAction::Execute(Event event) +bool ExitTwilightPortalAction::Execute(Event) { GameObject* portal = bot->FindNearestGameObject(GO_NORMAL_PORTAL, 100.0f); if (!portal) { return false; } diff --git a/src/Ai/Raid/Onyxia/Action/RaidOnyxiaActions.cpp b/src/Ai/Raid/Onyxia/Action/RaidOnyxiaActions.cpp index 9fa4612bf6..aa2eb31229 100644 --- a/src/Ai/Raid/Onyxia/Action/RaidOnyxiaActions.cpp +++ b/src/Ai/Raid/Onyxia/Action/RaidOnyxiaActions.cpp @@ -1,4 +1,3 @@ -// RaidOnyxiaActions.cpp #include "RaidOnyxiaActions.h" #include "GenericSpellActions.h" @@ -7,7 +6,7 @@ #include "Playerbots.h" #include "PositionAction.h" -bool RaidOnyxiaMoveToSideAction::Execute(Event event) +bool RaidOnyxiaMoveToSideAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "onyxia"); if (!boss) @@ -38,7 +37,7 @@ bool RaidOnyxiaMoveToSideAction::Execute(Event event) return false; } -bool RaidOnyxiaSpreadOutAction::Execute(Event event) +bool RaidOnyxiaSpreadOutAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "onyxia"); @@ -64,7 +63,7 @@ bool RaidOnyxiaSpreadOutAction::Execute(Event event) return MoveFromGroup(9.0f); // move 9 yards } -bool RaidOnyxiaMoveToSafeZoneAction::Execute(Event event) +bool RaidOnyxiaMoveToSafeZoneAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "onyxia"); if (!boss) @@ -105,7 +104,7 @@ bool RaidOnyxiaMoveToSafeZoneAction::Execute(Event event) false, false, false, false, MovementPriority::MOVEMENT_COMBAT); } -bool RaidOnyxiaKillWhelpsAction::Execute(Event event) +bool RaidOnyxiaKillWhelpsAction::Execute(Event) { Unit* currentTarget = AI_VALUE(Unit*, "current target"); // If already attacking a whelp, don't swap targets @@ -129,7 +128,7 @@ bool RaidOnyxiaKillWhelpsAction::Execute(Event event) return false; } -bool OnyxiaAvoidEggsAction::Execute(Event event) +bool OnyxiaAvoidEggsAction::Execute(Event) { Position botPos = Position(bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ()); diff --git a/src/Ai/Raid/Onyxia/Strategy/RaidOnyxiaStrategy.cpp b/src/Ai/Raid/Onyxia/Strategy/RaidOnyxiaStrategy.cpp index b1217f59eb..8cee2d1df9 100644 --- a/src/Ai/Raid/Onyxia/Strategy/RaidOnyxiaStrategy.cpp +++ b/src/Ai/Raid/Onyxia/Strategy/RaidOnyxiaStrategy.cpp @@ -24,7 +24,7 @@ void RaidOnyxiaStrategy::InitTriggers(std::vector& triggers) "ony whelps spawn", { NextAction("ony kill whelps", ACTION_RAID + 1) })); } -void RaidOnyxiaStrategy::InitMultipliers(std::vector& multipliers) +void RaidOnyxiaStrategy::InitMultipliers(std::vector&) { // Empty for now } diff --git a/src/Ai/Raid/Ulduar/Action/RaidUlduarActions.cpp b/src/Ai/Raid/Ulduar/Action/RaidUlduarActions.cpp index b7c3723bb3..8f25582307 100644 --- a/src/Ai/Raid/Ulduar/Action/RaidUlduarActions.cpp +++ b/src/Ai/Raid/Ulduar/Action/RaidUlduarActions.cpp @@ -18,16 +18,14 @@ #include "Playerbots.h" #include "Position.h" #include "RaidUlduarBossHelper.h" -#include "RaidUlduarScripts.h" -#include "RaidUlduarStrategy.h" #include "RtiValue.h" -#include "ScriptedCreature.h" #include "ServerFacade.h" #include "SharedDefines.h" #include "Unit.h" #include "Vehicle.h" #include #include +#include "../../../../../../src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h" const std::string ADD_STRATEGY_CHAR = "+"; const std::string REMOVE_STRATEGY_CHAR = "-"; @@ -50,7 +48,7 @@ const Position yoggPortalLoc[] = { {1960.62f, -32.00f, 325.5f}, {1981.98f, -5.69f, 325.5f}, {1982.78f, -45.73f, 325.5f}, {2000.66f, -29.68f, 325.5f}, {1999.88f, -19.61f, 325.5f}, {1961.37f, -19.54f, 325.5f}}; -bool FlameLeviathanVehicleAction::Execute(Event event) +bool FlameLeviathanVehicleAction::Execute(Event) { vehicleBase_ = bot->GetVehicleBase(); vehicle_ = bot->GetVehicle(); @@ -109,7 +107,7 @@ bool FlameLeviathanVehicleAction::MoveAvoidChasing(Unit* target) return false; if (avoidChaseIdx == -1) { - for (int i = 0; i < corners.size(); i++) + for (uint64_t i = 0; i < corners.size(); i++) { if (bot->GetExactDist(corners[i]) > target->GetExactDist(corners[i])) continue; @@ -272,7 +270,7 @@ bool FlameLeviathanVehicleAction::ChopperAction(Unit* target) return false; } -bool FlameLeviathanEnterVehicleAction::Execute(Event event) +bool FlameLeviathanEnterVehicleAction::Execute(Event) { // do not switch vehicles yet if (bot->GetVehicle()) @@ -417,7 +415,7 @@ bool FlameLeviathanEnterVehicleAction::AllMainVehiclesOnUse() return demolisher >= maxC && siege >= maxC; } -bool RazorscaleAvoidDevouringFlameAction::Execute(Event event) +bool RazorscaleAvoidDevouringFlameAction::Execute(Event) { RazorscaleBossHelper razorscaleHelper(botAI); @@ -498,7 +496,7 @@ bool RazorscaleAvoidDevouringFlameAction::isUseful() return false; // No nearby flames or bot is at a safe distance } -bool RazorscaleAvoidSentinelAction::Execute(Event event) +bool RazorscaleAvoidSentinelAction::Execute(Event) { bool isMainTank = botAI->IsMainTank(bot); bool isRanged = botAI->IsRanged(bot); @@ -620,7 +618,7 @@ bool RazorscaleAvoidSentinelAction::isUseful() return false; } -bool RazorscaleAvoidWhirlwindAction::Execute(Event event) +bool RazorscaleAvoidWhirlwindAction::Execute(Event) { if (botAI->IsTank(bot)) { @@ -737,7 +735,7 @@ bool RazorscaleIgnoreBossAction::isUseful() return false; } -bool RazorscaleIgnoreBossAction::Execute(Event event) +bool RazorscaleIgnoreBossAction::Execute(Event) { if (!bot) { @@ -894,7 +892,7 @@ bool RazorscaleGroundedAction::isUseful() return false; } -bool RazorscaleGroundedAction::Execute(Event event) +bool RazorscaleGroundedAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "razorscale"); if (!boss || !boss->IsAlive() || boss->GetPositionZ() > RazorscaleBossHelper::RAZORSCALE_FLYING_Z_THRESHOLD) @@ -977,7 +975,7 @@ bool RazorscaleGroundedAction::Execute(Event event) return false; } -bool RazorscaleHarpoonAction::Execute(Event event) +bool RazorscaleHarpoonAction::Execute(Event) { if (!bot) { @@ -1145,7 +1143,7 @@ bool RazorscaleFuseArmorAction::isUseful() return false; } -bool RazorscaleFuseArmorAction::Execute(Event event) +bool RazorscaleFuseArmorAction::Execute(Event) { // We already know from isUseful() that: // 1) This bot can tank, AND @@ -1164,7 +1162,7 @@ bool IronAssemblyLightningTendrilsAction::isUseful() return ironAssemblyLightningTendrilsTrigger.IsActive(); } -bool IronAssemblyLightningTendrilsAction::Execute(Event event) +bool IronAssemblyLightningTendrilsAction::Execute(Event) { const float radius = 18.0f + 10.0f; // 18 yards + 10 yards for safety @@ -1188,7 +1186,7 @@ bool IronAssemblyOverloadAction::isUseful() return ironAssemblyOverloadTrigger.IsActive(); } -bool IronAssemblyOverloadAction::Execute(Event event) +bool IronAssemblyOverloadAction::Execute(Event) { const float radius = 20.0f + 5.0f; // 20 yards + 5 yards for safety @@ -1212,7 +1210,7 @@ bool IronAssemblyRuneOfPowerAction::isUseful() return ironAssemblyRuneOfPowerTrigger.IsActive(); } -bool IronAssemblyRuneOfPowerAction::Execute(Event event) +bool IronAssemblyRuneOfPowerAction::Execute(Event) { Unit* target = botAI->GetUnit(bot->GetTarget()); if (!target || !target->IsAlive()) @@ -1227,7 +1225,7 @@ bool KologarnMarkDpsTargetAction::isUseful() return kologarnMarkDpsTargetTrigger.IsActive(); } -bool KologarnMarkDpsTargetAction::Execute(Event event) +bool KologarnMarkDpsTargetAction::Execute(Event) { Unit* targetToMark = nullptr; Unit* additionalTargetToMark = nullptr; @@ -1249,7 +1247,6 @@ bool KologarnMarkDpsTargetAction::Execute(Event event) if (!target) continue; - uint32 creatureId = target->GetEntry(); if (target->GetEntry() == NPC_RUBBLE && target->IsAlive()) { targetToMark = target; @@ -1362,7 +1359,7 @@ bool KologarnMarkDpsTargetAction::Execute(Event event) return false; } -bool KologarnFallFromFloorAction::Execute(Event event) +bool KologarnFallFromFloorAction::Execute(Event) { return bot->TeleportTo(bot->GetMapId(), ULDUAR_KOLOGARN_RESTORE_POSITION.GetPositionX(), ULDUAR_KOLOGARN_RESTORE_POSITION.GetPositionY(), @@ -1376,7 +1373,7 @@ bool KologarnFallFromFloorAction::isUseful() return kologarnFallFromFloorTrigger.IsActive(); } -bool KologarnRubbleSlowdownAction::Execute(Event event) +bool KologarnRubbleSlowdownAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -1391,7 +1388,7 @@ bool KologarnRubbleSlowdownAction::Execute(Event event) return botAI->CastSpell("frost trap", currentSkullUnit); } -bool KologarnEyebeamAction::Execute(Event event) +bool KologarnEyebeamAction::Execute(Event) { float distanceToLeftPoint = bot->GetExactDist(ULDUAR_KOLOGARN_EYEBEAM_LEFT_POSITION); float distanceToRightPoint = bot->GetExactDist(ULDUAR_KOLOGARN_EYEBEAM_RIGHT_POSITION); @@ -1450,7 +1447,7 @@ bool KologarnRtiTargetAction::isUseful() return kologarnRtiTargetTrigger.IsActive(); } -bool KologarnRtiTargetAction::Execute(Event event) +bool KologarnRtiTargetAction::Execute(Event) { if (botAI->IsMainTank(bot) || botAI->IsAssistTankOfIndex(bot, 0)) { @@ -1473,13 +1470,13 @@ bool KologarnCrunchArmorAction::isUseful() return botAI->HasCheat(BotCheatMask::raid); } -bool KologarnCrunchArmorAction::Execute(Event event) +bool KologarnCrunchArmorAction::Execute(Event) { bot->RemoveAura(SPELL_CRUNCH_ARMOR); return true; } -bool AuriayaFallFromFloorAction::Execute(Event event) +bool AuriayaFallFromFloorAction::Execute(Event) { Player* master = botAI->GetMaster(); @@ -1525,7 +1522,7 @@ bool HodirMoveSnowpackedIcicleAction::isUseful() return true; } -bool HodirMoveSnowpackedIcicleAction::Execute(Event event) +bool HodirMoveSnowpackedIcicleAction::Execute(Event) { Creature* target = bot->FindNearestCreature(NPC_SNOWPACKED_ICICLE, 100.0f); if (!target) @@ -1535,7 +1532,7 @@ bool HodirMoveSnowpackedIcicleAction::Execute(Event event) false, false, true, MovementPriority::MOVEMENT_NORMAL, true); } -bool HodirBitingColdJumpAction::Execute(Event event) +bool HodirBitingColdJumpAction::Execute(Event) { bot->RemoveAurasDueToSpell(SPELL_BITING_COLD_PLAYER_AURA); @@ -1591,7 +1588,7 @@ bool FreyaMoveAwayNatureBombAction::isUseful() return true; } -bool FreyaMoveAwayNatureBombAction::Execute(Event event) +bool FreyaMoveAwayNatureBombAction::Execute(Event) { GameObject* target = bot->FindNearestGameObject(GOBJECT_NATURE_BOMB, 12.0f); if (!target) @@ -1606,7 +1603,7 @@ bool FreyaMarkDpsTargetAction::isUseful() return freyaMarkDpsTargetTrigger.IsActive(); } -bool FreyaMarkDpsTargetAction::Execute(Event event) +bool FreyaMarkDpsTargetAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "freya"); if (!boss || !boss->IsAlive()) @@ -1762,7 +1759,7 @@ bool FreyaMoveToHealingSporeAction::isUseful() return freyaMoveToHealingSporeTrigger.IsActive(); } -bool FreyaMoveToHealingSporeAction::Execute(Event event) +bool FreyaMoveToHealingSporeAction::Execute(Event) { GuidVector targets = AI_VALUE(GuidVector, "nearest npcs"); Creature* nearestSpore = nullptr; @@ -1804,7 +1801,7 @@ bool ThorimUnbalancingStrikeAction::isUseful() return botAI->HasCheat(BotCheatMask::raid); } -bool ThorimUnbalancingStrikeAction::Execute(Event event) +bool ThorimUnbalancingStrikeAction::Execute(Event) { bot->RemoveAura(SPELL_UNBALANCING_STRIKE); return true; @@ -1816,7 +1813,7 @@ bool ThorimMarkDpsTargetAction::isUseful() return thorimMarkDpsTargetTrigger.IsActive(); } -bool ThorimMarkDpsTargetAction::Execute(Event event) +bool ThorimMarkDpsTargetAction::Execute(Event) { Unit* targetToMark = nullptr; @@ -1917,7 +1914,7 @@ bool ThorimArenaPositioningAction::isUseful() return thorimArenaPositioningTrigger.IsActive(); } -bool ThorimArenaPositioningAction::Execute(Event event) +bool ThorimArenaPositioningAction::Execute(Event) { FollowMasterStrategy followMasterStrategy(botAI); @@ -1939,7 +1936,7 @@ bool ThorimGauntletPositioningAction::isUseful() return thorimGauntletPositioningTrigger.IsActive(); } -bool ThorimGauntletPositioningAction::Execute(Event event) +bool ThorimGauntletPositioningAction::Execute(Event) { FollowMasterStrategy followMasterStrategy(botAI); @@ -2113,7 +2110,7 @@ bool ThorimGauntletPositioningAction::Execute(Event event) return false; } -bool ThorimFallFromFloorAction::Execute(Event event) +bool ThorimFallFromFloorAction::Execute(Event) { Player* master = botAI->GetMaster(); @@ -2130,7 +2127,7 @@ bool ThorimFallFromFloorAction::isUseful() return thorimFallFromFloorTrigger.IsActive(); } -bool ThorimPhase2PositioningAction::Execute(Event event) +bool ThorimPhase2PositioningAction::Execute(Event) { Position targetPosition; bool backward = false; @@ -2190,7 +2187,7 @@ bool ThorimPhase2PositioningAction::isUseful() return thorimPhase2PositioningTrigger.IsActive(); } -bool MimironShockBlastAction::Execute(Event event) +bool MimironShockBlastAction::Execute(Event) { Unit* leviathanMkII = nullptr; Unit* vx001 = nullptr; @@ -2264,7 +2261,7 @@ bool MimironShockBlastAction::isUseful() return mimironShockBlastTrigger.IsActive(); } -bool MimironPhase1PositioningAction::Execute(Event event) +bool MimironPhase1PositioningAction::Execute(Event) { SET_AI_VALUE(float, "disperse distance", 6.0f); return true; @@ -2276,7 +2273,7 @@ bool MimironPhase1PositioningAction::isUseful() return mimironPhase1PositioningTrigger.IsActive(); } -bool MimironP3Wx2LaserBarrageAction::Execute(Event event) +bool MimironP3Wx2LaserBarrageAction::Execute(Event) { auto master = botAI->GetMaster(); if (!master || !master->IsAlive()) @@ -2300,7 +2297,7 @@ bool MimironRapidBurstAction::isUseful() return mimironRapidBurstTrigger.IsActive(); } -bool MimironRapidBurstAction::Execute(Event event) +bool MimironRapidBurstAction::Execute(Event) { Unit* leviathanMkII = nullptr; @@ -2407,7 +2404,7 @@ bool MimironRapidBurstAction::Execute(Event event) return true; } -bool MimironAerialCommandUnitAction::Execute(Event event) +bool MimironAerialCommandUnitAction::Execute(Event) { Unit* boss = nullptr; Unit* bombBot = nullptr; @@ -2479,9 +2476,8 @@ bool MimironRocketStrikeAction::isUseful() return mimironRocketStrikeTrigger.IsActive(); } -bool MimironRocketStrikeAction::Execute(Event event) +bool MimironRocketStrikeAction::Execute(Event) { - Unit* leviathanMkII = nullptr; Unit* vx001 = nullptr; Unit* aerialCommandUnit = nullptr; @@ -2493,11 +2489,7 @@ bool MimironRocketStrikeAction::Execute(Event event) if (!target || !target->IsAlive()) continue; - if (target->GetEntry() == NPC_LEVIATHAN_MKII) - { - leviathanMkII = target; - } - else if (target->GetEntry() == NPC_VX001) + if (target->GetEntry() == NPC_VX001) { vx001 = target; } @@ -2540,7 +2532,7 @@ bool MimironRocketStrikeAction::Execute(Event event) } } -bool MimironPhase4MarkDpsAction::Execute(Event event) +bool MimironPhase4MarkDpsAction::Execute(Event) { Unit* leviathanMkII = nullptr; Unit* vx001 = nullptr; @@ -2629,7 +2621,7 @@ bool MimironPhase4MarkDpsAction::Execute(Event event) } } -bool MimironCheatAction::Execute(Event event) +bool MimironCheatAction::Execute(Event) { GuidVector targets = AI_VALUE(GuidVector, "nearest npcs"); for (const ObjectGuid& guid : targets) @@ -2651,7 +2643,7 @@ bool MimironCheatAction::Execute(Event event) return true; } -bool VezaxCheatAction::Execute(Event event) +bool VezaxCheatAction::Execute(Event) { // Restore bot's mana to full uint32 maxMana = bot->GetMaxPower(POWER_MANA); @@ -2663,7 +2655,7 @@ bool VezaxCheatAction::Execute(Event event) return true; } -bool VezaxShadowCrashAction::Execute(Event event) +bool VezaxShadowCrashAction::Execute(Event) { // Find General Vezax boss Unit* boss = AI_VALUE2(Unit*, "find target", "general vezax"); @@ -2707,7 +2699,7 @@ bool VezaxShadowCrashAction::Execute(Event event) true); } -bool VezaxMarkOfTheFacelessAction::Execute(Event event) +bool VezaxMarkOfTheFacelessAction::Execute(Event) { return MoveTo(bot->GetMapId(), ULDUAR_VEZAX_MARK_OF_THE_FACELESS_SPOT.GetPositionX(), ULDUAR_VEZAX_MARK_OF_THE_FACELESS_SPOT.GetPositionY(), @@ -2715,7 +2707,7 @@ bool VezaxMarkOfTheFacelessAction::Execute(Event event) MovementPriority::MOVEMENT_FORCED, true, false); } -bool YoggSaronOminousCloudCheatAction::Execute(Event event) +bool YoggSaronOminousCloudCheatAction::Execute(Event) { YoggSaronTrigger yoggSaronTrigger(botAI); @@ -2735,14 +2727,14 @@ bool YoggSaronOminousCloudCheatAction::Execute(Event event) return true; } -bool YoggSaronGuardianPositioningAction::Execute(Event event) +bool YoggSaronGuardianPositioningAction::Execute(Event) { return MoveTo(bot->GetMapId(), ULDUAR_YOGG_SARON_MIDDLE.GetPositionX(), ULDUAR_YOGG_SARON_MIDDLE.GetPositionY(), ULDUAR_YOGG_SARON_MIDDLE.GetPositionZ(), false, false, false, true, MovementPriority::MOVEMENT_FORCED, true, false); } -bool YoggSaronSanityAction::Execute(Event event) +bool YoggSaronSanityAction::Execute(Event) { Creature* sanityWell = bot->FindNearestCreature(NPC_SANITY_WELL, 200.0f); @@ -2751,7 +2743,7 @@ bool YoggSaronSanityAction::Execute(Event event) true, false); } -bool YoggSaronMarkTargetAction::Execute(Event event) +bool YoggSaronMarkTargetAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -2820,7 +2812,7 @@ bool YoggSaronMarkTargetAction::Execute(Event event) GuidVector targets = AI_VALUE(GuidVector, "nearest npcs"); - int lowestHealth = std::numeric_limits::max(); + uint64_t lowestHealth = std::numeric_limits::max(); Unit* lowestHealthUnit = nullptr; for (const ObjectGuid& guid : targets) { @@ -2880,7 +2872,7 @@ bool YoggSaronMarkTargetAction::Execute(Event event) return false; } -bool YoggSaronBrainLinkAction::Execute(Event event) +bool YoggSaronBrainLinkAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -2900,7 +2892,7 @@ bool YoggSaronBrainLinkAction::Execute(Event event) return false; } -bool YoggSaronMoveToEnterPortalAction::Execute(Event event) +bool YoggSaronMoveToEnterPortalAction::Execute(Event) { Group* group = bot->GetGroup(); if (!group) @@ -2964,12 +2956,12 @@ bool YoggSaronMoveToEnterPortalAction::Execute(Event event) { return MoveNear(bot->GetMapId(), assignedPortalPosition.GetPositionX(), assignedPortalPosition.GetPositionY(), - assignedPortalPosition.GetPositionZ(), sPlayerbotAIConfig->contactDistance, + assignedPortalPosition.GetPositionZ(), sPlayerbotAIConfig.contactDistance, MovementPriority::MOVEMENT_FORCED); } } -bool YoggSaronFallFromFloorAction::Execute(Event event) +bool YoggSaronFallFromFloorAction::Execute(Event) { std::string rtiMark = AI_VALUE(std::string, "rti"); if (rtiMark == "skull") @@ -3001,7 +2993,7 @@ bool YoggSaronFallFromFloorAction::Execute(Event event) return false; } -bool YoggSaronBossRoomMovementCheatAction::Execute(Event event) +bool YoggSaronBossRoomMovementCheatAction::Execute(Event) { FollowMasterStrategy followMasterStrategy(botAI); if (botAI->HasStrategy(followMasterStrategy.getName(), BotState::BOT_STATE_NON_COMBAT)) @@ -3037,7 +3029,7 @@ bool YoggSaronBossRoomMovementCheatAction::Execute(Event event) currentSkullUnit->GetPositionZ(), bot->GetOrientation()); } -bool YoggSaronUsePortalAction::Execute(Event event) +bool YoggSaronUsePortalAction::Execute(Event) { Creature* assignedPortal = bot->FindNearestCreature(NPC_DESCEND_INTO_MADNESS, 2.0f, true); if (!assignedPortal) @@ -3054,7 +3046,7 @@ bool YoggSaronUsePortalAction::Execute(Event event) return assignedPortal->HandleSpellClick(bot); } -bool YoggSaronIllusionRoomAction::Execute(Event event) +bool YoggSaronIllusionRoomAction::Execute(Event) { YoggSaronTrigger yoggSaronTrigger(botAI); @@ -3176,7 +3168,7 @@ bool YoggSaronIllusionRoomAction::SetBrainRtiTarget(YoggSaronTrigger yoggSaronTr return true; } -bool YoggSaronMoveToExitPortalAction::Execute(Event event) +bool YoggSaronMoveToExitPortalAction::Execute(Event) { GameObject* portal = bot->FindNearestGameObject(GO_FLEE_TO_THE_SURFACE_PORTAL, 100.0f); if (!portal) @@ -3207,7 +3199,7 @@ bool YoggSaronMoveToExitPortalAction::Execute(Event event) return true; } -bool YoggSaronLunaticGazeAction::Execute(Event event) +bool YoggSaronLunaticGazeAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "yogg-saron"); if (!boss || !boss->IsAlive()) @@ -3229,7 +3221,7 @@ bool YoggSaronLunaticGazeAction::Execute(Event event) return true; } -bool YoggSaronPhase3PositioningAction::Execute(Event event) +bool YoggSaronPhase3PositioningAction::Execute(Event) { if (botAI->IsRanged(bot)) { diff --git a/src/Ai/Raid/Ulduar/Multiplier/RaidUlduarMultipliers.cpp b/src/Ai/Raid/Ulduar/Multiplier/RaidUlduarMultipliers.cpp index 16df9c9af2..88387e339a 100644 --- a/src/Ai/Raid/Ulduar/Multiplier/RaidUlduarMultipliers.cpp +++ b/src/Ai/Raid/Ulduar/Multiplier/RaidUlduarMultipliers.cpp @@ -1,28 +1,6 @@ #include "RaidUlduarMultipliers.h" -#include "ChooseTargetActions.h" -#include "DKActions.h" -#include "DruidActions.h" -#include "DruidBearActions.h" -#include "FollowActions.h" -#include "GenericActions.h" -#include "GenericSpellActions.h" -#include "HunterActions.h" -#include "MageActions.h" -#include "MovementActions.h" -#include "PaladinActions.h" -#include "PriestActions.h" -#include "RaidUlduarActions.h" -#include "ReachTargetActions.h" -#include "RogueActions.h" -#include "ScriptedCreature.h" -#include "ShamanActions.h" -#include "UseMeetingStoneAction.h" -#include "WarriorActions.h" - -float FlameLeviathanMultiplier::GetValue(Action* action) +float FlameLeviathanMultiplier::GetValue(Action*) { - // if (dynamic_cast(action)) - // return 0.0f; return 1.0f; } \ No newline at end of file diff --git a/src/Ai/Raid/Ulduar/Trigger/RaidUlduarTriggers.cpp b/src/Ai/Raid/Ulduar/Trigger/RaidUlduarTriggers.cpp index f883917ed0..e58edb3f6d 100644 --- a/src/Ai/Raid/Ulduar/Trigger/RaidUlduarTriggers.cpp +++ b/src/Ai/Raid/Ulduar/Trigger/RaidUlduarTriggers.cpp @@ -1,19 +1,17 @@ #include "RaidUlduarTriggers.h" -#include "EventMap.h" #include "GameObject.h" #include "Object.h" #include "PlayerbotAI.h" #include "Playerbots.h" #include "RaidUlduarBossHelper.h" -#include "RaidUlduarScripts.h" -#include "ScriptedCreature.h" #include "SharedDefines.h" #include "Trigger.h" #include "Vehicle.h" #include #include #include +#include "../../../../../../../src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h" const std::vector availableVehicles = {NPC_VEHICLE_CHOPPER, NPC_SALVAGED_DEMOLISHER, NPC_SALVAGED_DEMOLISHER_TURRET, NPC_SALVAGED_SIEGE_ENGINE, @@ -350,7 +348,6 @@ bool KologarnMarkDpsTargetTrigger::IsActive() if (!target) continue; - uint32 creatureId = target->GetEntry(); if (target->GetEntry() == NPC_RUBBLE && target->IsAlive()) { return true; // Found a rubble to mark @@ -854,8 +851,6 @@ bool ThorimMarkDpsTargetTrigger::IsActive() Unit* runicColossus = AI_VALUE2(Unit*, "find target", "runic colossus"); Unit* ancientRuneGiant = AI_VALUE2(Unit*, "find target", "ancient rune giant"); - Unit* ironHonorGuard = AI_VALUE2(Unit*, "find target", "iron ring guard"); - Unit* ironRingGuard = AI_VALUE2(Unit*, "find target", "iron honor guard"); if (acolyte && acolyte->IsAlive() && (!currentCrossUnit || currentCrossUnit->GetEntry() != acolyte->GetEntry())) return true; @@ -1094,7 +1089,7 @@ bool ThorimPhase2PositioningTrigger::IsActive() Unit* boss = AI_VALUE2(Unit*, "find target", "thorim"); if (!boss || !boss->IsInWorld() || boss->IsDuringRemoveFromWorld()) - return false; + return false; if (!boss->IsAlive()) return false; @@ -1181,8 +1176,6 @@ bool MimironPhase1PositioningTrigger::IsActive() } Unit* leviathanMkII = nullptr; - Unit* vx001 = nullptr; - Unit* aerialCommandUnit = nullptr; GuidVector targets = AI_VALUE(GuidVector, "possible targets"); Unit* target = nullptr; @@ -1621,7 +1614,7 @@ bool VezaxCheatTrigger::IsActive() return false; } - return AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig->lowMana; + return AI_VALUE2(uint8, "mana", "self target") < sPlayerbotAIConfig.lowMana; } bool VezaxShadowCrashTrigger::IsActive() @@ -1796,7 +1789,7 @@ Unit* YoggSaronTrigger::GetIllusionRoomRtiTarget() return nullptr; } - uint8 rtiIndex = RtiTargetValue::GetRtiIndex(AI_VALUE(std::string, "rti")); + int32_t rtiIndex = RtiTargetValue::GetRtiIndex(AI_VALUE(std::string, "rti")); if (rtiIndex == -1) { return nullptr; // Invalid RTI mark diff --git a/src/Ai/Raid/VaultOfArchavon/Action/RaidVoAActions.cpp b/src/Ai/Raid/VaultOfArchavon/Action/RaidVoAActions.cpp index 05d6328e5c..14bd727784 100644 --- a/src/Ai/Raid/VaultOfArchavon/Action/RaidVoAActions.cpp +++ b/src/Ai/Raid/VaultOfArchavon/Action/RaidVoAActions.cpp @@ -10,7 +10,7 @@ const Position VOA_EMALON_RESTORE_POSITION = Position(-221.8f, -243.8f, 96.8f, 4.7f); -bool EmalonMarkBossAction::Execute(Event event) +bool EmalonMarkBossAction::Execute(Event) { Unit* boss = AI_VALUE2(Unit*, "find target", "emalon the storm watcher"); if (!boss || !boss->IsAlive()) @@ -72,7 +72,7 @@ bool EmalonMarkBossAction::isUseful() return emalonMarkBossTrigger.IsActive(); } -bool EmalonLightingNovaAction::Execute(Event event) +bool EmalonLightingNovaAction::Execute(Event) { const float radius = 25.0f; // 20 yards + 5 yard for safety for 10 man. For 25man there is no maximum range but 25 yards should be ok @@ -96,7 +96,7 @@ bool EmalonLightingNovaAction::isUseful() return emalonLightingNovaTrigger.IsActive(); } -bool EmalonOverchargeAction::Execute(Event event) +bool EmalonOverchargeAction::Execute(Event) { // Check if there is any overcharged minion Unit* minion = nullptr; @@ -173,7 +173,7 @@ bool EmalonOverchargeAction::isUseful() return emalonOverchargeTrigger.IsActive(); } -bool EmalonFallFromFloorAction::Execute(Event event) +bool EmalonFallFromFloorAction::Execute(Event) { return bot->TeleportTo(bot->GetMapId(), VOA_EMALON_RESTORE_POSITION.GetPositionX(), VOA_EMALON_RESTORE_POSITION.GetPositionY(), VOA_EMALON_RESTORE_POSITION.GetPositionZ(), diff --git a/src/Ai/World/Rpg/Action/NewRpgAction.cpp b/src/Ai/World/Rpg/Action/NewRpgAction.cpp index 01595edf79..391144c33b 100644 --- a/src/Ai/World/Rpg/Action/NewRpgAction.cpp +++ b/src/Ai/World/Rpg/Action/NewRpgAction.cpp @@ -1,12 +1,10 @@ #include "NewRpgAction.h" #include -#include #include #include "BroadcastHelper.h" #include "ChatHelper.h" -#include "DBCStores.h" #include "G3D/Vector2.h" #include "GossipDef.h" #include "IVMapMgr.h" @@ -20,16 +18,11 @@ #include "PathGenerator.h" #include "Player.h" #include "PlayerbotAI.h" -#include "Playerbots.h" -#include "Position.h" #include "QuestDef.h" #include "Random.h" -#include "RandomPlayerbotMgr.h" #include "SharedDefines.h" -#include "StatsWeightCalculator.h" #include "Timer.h" #include "TravelMgr.h" -#include "World.h" bool TellRpgStatusAction::Execute(Event event) { @@ -61,7 +54,7 @@ bool StartRpgDoQuestAction::Execute(Event event) return false; } -bool NewRpgStatusUpdateAction::Execute(Event event) +bool NewRpgStatusUpdateAction::Execute(Event) { NewRpgInfo& info = botAI->rpgInfo; switch (info.status) @@ -150,7 +143,7 @@ bool NewRpgStatusUpdateAction::Execute(Event event) return false; } -bool NewRpgGoGrindAction::Execute(Event event) +bool NewRpgGoGrindAction::Execute(Event) { if (SearchQuestGiverAndAcceptOrReward()) return true; @@ -158,7 +151,7 @@ bool NewRpgGoGrindAction::Execute(Event event) return MoveFarTo(botAI->rpgInfo.go_grind.pos); } -bool NewRpgGoCampAction::Execute(Event event) +bool NewRpgGoCampAction::Execute(Event) { if (SearchQuestGiverAndAcceptOrReward()) return true; @@ -166,7 +159,7 @@ bool NewRpgGoCampAction::Execute(Event event) return MoveFarTo(botAI->rpgInfo.go_camp.pos); } -bool NewRpgWanderRandomAction::Execute(Event event) +bool NewRpgWanderRandomAction::Execute(Event) { if (SearchQuestGiverAndAcceptOrReward()) return true; @@ -174,7 +167,7 @@ bool NewRpgWanderRandomAction::Execute(Event event) return MoveRandomNear(); } -bool NewRpgWanderNpcAction::Execute(Event event) +bool NewRpgWanderNpcAction::Execute(Event) { NewRpgInfo& info = botAI->rpgInfo; if (!info.wander_npc.npcOrGo) @@ -216,14 +209,12 @@ bool NewRpgWanderNpcAction::Execute(Event event) return true; } -bool NewRpgDoQuestAction::Execute(Event event) +bool NewRpgDoQuestAction::Execute(Event) { if (SearchQuestGiverAndAcceptOrReward()) return true; - NewRpgInfo& info = botAI->rpgInfo; uint32 questId = RPG_INFO(quest, questId); - const Quest* quest = RPG_INFO(quest, quest); uint8 questStatus = bot->GetQuestStatus(questId); switch (questStatus) { @@ -408,7 +399,7 @@ bool NewRpgDoQuestAction::DoCompletedQuest() return false; } -bool NewRpgTravelFlightAction::Execute(Event event) +bool NewRpgTravelFlightAction::Execute(Event) { if (bot->IsInFlight()) { @@ -421,7 +412,6 @@ bool NewRpgTravelFlightAction::Execute(Event event) botAI->rpgInfo.ChangeToIdle(); return true; } - const TaxiNodesEntry* entry = sTaxiNodesStore.LookupEntry(botAI->rpgInfo.flight.toNode); if (bot->GetDistance(flightMaster) > INTERACTION_DISTANCE) { return MoveFarTo(flightMaster); diff --git a/src/Ai/World/Rpg/Action/NewRpgBaseAction.cpp b/src/Ai/World/Rpg/Action/NewRpgBaseAction.cpp index 4898d7e36c..5a1ff2dc46 100644 --- a/src/Ai/World/Rpg/Action/NewRpgBaseAction.cpp +++ b/src/Ai/World/Rpg/Action/NewRpgBaseAction.cpp @@ -371,7 +371,6 @@ bool NewRpgBaseAction::IsWithinInteractionDist(Object* questGiver) case TYPEID_GAMEOBJECT: { ObjectGuid guid = questGiver->GetGUID(); - GameobjectTypes type = GAMEOBJECT_TYPE_QUESTGIVER; if (GameObject* go = bot->GetMap()->GetGameObject(guid)) { if (go->IsWithinDistInMap(bot)) @@ -557,7 +556,9 @@ bool NewRpgBaseAction::OrganizeQuestLog() continue; const Quest* quest = sObjectMgr->GetQuestTemplate(questId); - if (quest->GetZoneOrSort() < 0 || (quest->GetZoneOrSort() > 0 && quest->GetZoneOrSort() != bot->GetZoneId())) + const int64_t botZoneId = this->bot->GetZoneId(); + + if (quest->GetZoneOrSort() < 0 || (quest->GetZoneOrSort() > 0 && quest->GetZoneOrSort() != botZoneId)) { LOG_DEBUG("playerbots", "[New RPG] {} drop quest {}", bot->GetName(), questId); WorldPacket packet(CMSG_QUESTLOG_REMOVE_QUEST); @@ -820,7 +821,7 @@ bool NewRpgBaseAction::GetQuestPOIPosAndObjectiveIdx(uint32 questId, std::vector continue; bool inComplete = false; - for (uint32 objective : incompleteObjectiveIdx) + for (int64_t objective : incompleteObjectiveIdx) { if (qPoi.ObjectiveIndex == objective) { @@ -866,7 +867,7 @@ bool NewRpgBaseAction::GetQuestPOIPosAndObjectiveIdx(uint32 questId, std::vector WorldPosition NewRpgBaseAction::SelectRandomGrindPos(Player* bot) { - const std::vector& locs = sRandomPlayerbotMgr->locsPerLevelCache[bot->GetLevel()]; + const std::vector& locs = sRandomPlayerbotMgr.locsPerLevelCache[bot->GetLevel()]; float hiRange = 500.0f; float loRange = 2500.0f; if (bot->GetLevel() < 5) @@ -925,8 +926,8 @@ WorldPosition NewRpgBaseAction::SelectRandomGrindPos(Player* bot) WorldPosition NewRpgBaseAction::SelectRandomCampPos(Player* bot) { const std::vector& locs = IsAlliance(bot->getRace()) - ? sRandomPlayerbotMgr->allianceStarterPerLevelCache[bot->GetLevel()] - : sRandomPlayerbotMgr->hordeStarterPerLevelCache[bot->GetLevel()]; + ? sRandomPlayerbotMgr.allianceStarterPerLevelCache[bot->GetLevel()] + : sRandomPlayerbotMgr.hordeStarterPerLevelCache[bot->GetLevel()]; bool inCity = false; @@ -969,7 +970,7 @@ WorldPosition NewRpgBaseAction::SelectRandomCampPos(Player* bot) bool NewRpgBaseAction::SelectRandomFlightTaxiNode(ObjectGuid& flightMaster, uint32& fromNode, uint32& toNode) { - Creature* nearestFlightMaster = sFlightMasterCache->GetNearestFlightMaster(bot); + Creature* nearestFlightMaster = FlightMasterCache::Instance().GetNearestFlightMaster(bot); if (!nearestFlightMaster || bot->GetDistance(nearestFlightMaster) > 500.0f) return false; @@ -1015,8 +1016,8 @@ bool NewRpgBaseAction::SelectRandomFlightTaxiNode(ObjectGuid& flightMaster, uint capital = zone->flags & AREA_FLAG_CAPITAL; } - auto itr = sRandomPlayerbotMgr->zone2LevelBracket.find(nodeZoneId); - if (!capital && itr == sRandomPlayerbotMgr->zone2LevelBracket.end()) + auto itr = sRandomPlayerbotMgr.zone2LevelBracket.find(nodeZoneId); + if (!capital && itr == sRandomPlayerbotMgr.zone2LevelBracket.end()) continue; if (!capital && (bot->GetLevel() < itr->second.low || bot->GetLevel() > itr->second.high)) @@ -1040,13 +1041,13 @@ bool NewRpgBaseAction::RandomChangeStatus(std::vector candidateSta uint32 probSum = 0; for (NewRpgStatus status : candidateStatus) { - if (sPlayerbotAIConfig->RpgStatusProbWeight[status] == 0) + if (sPlayerbotAIConfig.RpgStatusProbWeight[status] == 0) continue; if (CheckRpgStatusAvailable(status)) { availableStatus.push_back(status); - probSum += sPlayerbotAIConfig->RpgStatusProbWeight[status]; + probSum += sPlayerbotAIConfig.RpgStatusProbWeight[status]; } } // Safety check. Default to "rest" if all RPG weights = 0 @@ -1061,7 +1062,7 @@ bool NewRpgBaseAction::RandomChangeStatus(std::vector candidateSta NewRpgStatus chosenStatus = RPG_STATUS_END; for (NewRpgStatus status : availableStatus) { - accumulate += sPlayerbotAIConfig->RpgStatusProbWeight[status]; + accumulate += sPlayerbotAIConfig.RpgStatusProbWeight[status]; if (accumulate >= rand) { chosenStatus = status; diff --git a/src/Ai/World/Rpg/NewRpgInfo.cpp b/src/Ai/World/Rpg/NewRpgInfo.cpp index ff830464a5..18500331c4 100644 --- a/src/Ai/World/Rpg/NewRpgInfo.cpp +++ b/src/Ai/World/Rpg/NewRpgInfo.cpp @@ -66,7 +66,7 @@ void NewRpgInfo::ChangeToIdle() status = RPG_IDLE; } -bool NewRpgInfo::CanChangeTo(NewRpgStatus status) { return true; } +bool NewRpgInfo::CanChangeTo(NewRpgStatus) { return true; } void NewRpgInfo::Reset() { diff --git a/src/Ai/World/Rpg/Strategy/NewRpgStrategy.cpp b/src/Ai/World/Rpg/Strategy/NewRpgStrategy.cpp index 030ad6b4fc..3216486593 100644 --- a/src/Ai/World/Rpg/Strategy/NewRpgStrategy.cpp +++ b/src/Ai/World/Rpg/Strategy/NewRpgStrategy.cpp @@ -5,8 +5,6 @@ #include "NewRpgStrategy.h" -#include "Playerbots.h" - NewRpgStrategy::NewRpgStrategy(PlayerbotAI* botAI) : Strategy(botAI) {} std::vector NewRpgStrategy::getDefaultActions() @@ -69,7 +67,7 @@ void NewRpgStrategy::InitTriggers(std::vector& triggers) ); } -void NewRpgStrategy::InitMultipliers(std::vector& multipliers) +void NewRpgStrategy::InitMultipliers(std::vector&) { } diff --git a/src/Bot/Cmd/PlayerbotCommandServer.cpp b/src/Bot/Cmd/PlayerbotCommandServer.cpp index 83931229a0..ac6f5a7431 100644 --- a/src/Bot/Cmd/PlayerbotCommandServer.cpp +++ b/src/Bot/Cmd/PlayerbotCommandServer.cpp @@ -10,10 +10,9 @@ #include #include #include -#include +#include "RandomPlayerbotMgr.h" #include "IoContext.h" -#include "Playerbots.h" using boost::asio::ip::tcp; typedef boost::shared_ptr socket_ptr; @@ -27,7 +26,7 @@ bool ReadLine(socket_ptr sock, std::string* buffer, std::string* line) char buf[1025]; boost::system::error_code error; size_t n = sock->read_some(boost::asio::buffer(buf), error); - if (n == -1 || error == boost::asio::error::eof) + if (error == boost::asio::error::eof) return false; else if (error) throw boost::system::system_error(error); // Some other error. @@ -48,7 +47,7 @@ void session(socket_ptr sock) std::string buffer, request; while (ReadLine(sock, &buffer, &request)) { - std::string const response = sRandomPlayerbotMgr->HandleRemoteCommand(request) + "\n"; + std::string const response = RandomPlayerbotMgr::instance().HandleRemoteCommand(request) + "\n"; boost::asio::write(*sock, boost::asio::buffer(response.c_str(), response.size())); request = ""; } @@ -72,19 +71,19 @@ void server(Acore::Asio::IoContext& io_service, short port) void Run() { - if (!sPlayerbotAIConfig->commandServerPort) + if (!sPlayerbotAIConfig.commandServerPort) { return; } std::ostringstream s; - s << "Starting Playerbots Command Server on port " << sPlayerbotAIConfig->commandServerPort; + s << "Starting Playerbots Command Server on port " << sPlayerbotAIConfig.commandServerPort; LOG_INFO("playerbots", "{}", s.str().c_str()); try { Acore::Asio::IoContext io_service; - server(io_service, sPlayerbotAIConfig->commandServerPort); + server(io_service, sPlayerbotAIConfig.commandServerPort); } catch (std::exception& e) diff --git a/src/Bot/Cmd/PlayerbotCommandServer.h b/src/Bot/Cmd/PlayerbotCommandServer.h index e1b93a338e..eb410c644c 100644 --- a/src/Bot/Cmd/PlayerbotCommandServer.h +++ b/src/Bot/Cmd/PlayerbotCommandServer.h @@ -9,17 +9,24 @@ class PlayerbotCommandServer { public: - PlayerbotCommandServer() {} - virtual ~PlayerbotCommandServer() {} - static PlayerbotCommandServer* instance() + static PlayerbotCommandServer& instance() { static PlayerbotCommandServer instance; - return &instance; + + return instance; } void Start(); -}; -#define sPlayerbotCommandServer PlayerbotCommandServer::instance() +private: + PlayerbotCommandServer() = default; + ~PlayerbotCommandServer() = default; + + PlayerbotCommandServer(const PlayerbotCommandServer&) = delete; + PlayerbotCommandServer& operator=(const PlayerbotCommandServer&) = delete; + + PlayerbotCommandServer(PlayerbotCommandServer&&) = delete; + PlayerbotCommandServer& operator=(PlayerbotCommandServer&&) = delete; +}; #endif diff --git a/src/Bot/Debug/PerfMonitor.cpp b/src/Bot/Debug/PerfMonitor.cpp index c6d134edb9..82eece916f 100644 --- a/src/Bot/Debug/PerfMonitor.cpp +++ b/src/Bot/Debug/PerfMonitor.cpp @@ -10,7 +10,7 @@ PerfMonitorOperation* PerfMonitor::start(PerformanceMetric metric, std::string const name, PerformanceStack* stack) { - if (!sPlayerbotAIConfig->perfMonEnabled) + if (!sPlayerbotAIConfig.perfMonEnabled) return nullptr; std::string stackName = name; diff --git a/src/Bot/Debug/PerfMonitor.h b/src/Bot/Debug/PerfMonitor.h index 0d3eb8aad1..156392ee21 100644 --- a/src/Bot/Debug/PerfMonitor.h +++ b/src/Bot/Debug/PerfMonitor.h @@ -11,17 +11,16 @@ #include #include #include - -#include "Common.h" +#include typedef std::vector PerformanceStack; struct PerformanceData { - uint64 minTime; - uint64 maxTime; - uint64 totalTime; - uint32 count; + uint64_t minTime; + uint64_t maxTime; + uint64_t totalTime; + uint32_t count; std::mutex lock; }; @@ -50,21 +49,28 @@ class PerfMonitorOperation class PerfMonitor { public: - PerfMonitor(){}; - virtual ~PerfMonitor(){}; - static PerfMonitor* instance() + static PerfMonitor& instance() { static PerfMonitor instance; - return &instance; + + return instance; } -public: PerfMonitorOperation* start(PerformanceMetric metric, std::string const name, PerformanceStack* stack = nullptr); void PrintStats(bool perTick = false, bool fullStack = false); void Reset(); private: + PerfMonitor() = default; + virtual ~PerfMonitor() = default; + + PerfMonitor(const PerfMonitor&) = delete; + PerfMonitor& operator=(const PerfMonitor&) = delete; + + PerfMonitor(PerfMonitor&&) = delete; + PerfMonitor& operator=(PerfMonitor&&) = delete; + std::map > data; std::mutex lock; }; diff --git a/src/Bot/Engine/Action/Action.h b/src/Bot/Engine/Action/Action.h index 2395c5ea87..dd66338738 100644 --- a/src/Bot/Engine/Action/Action.h +++ b/src/Bot/Engine/Action/Action.h @@ -6,7 +6,6 @@ #pragma once #include "AiObject.h" -#include "Common.h" #include "Event.h" #include "Value.h" @@ -17,8 +16,10 @@ class NextAction { public: NextAction(std::string const name, float relevance = 0.0f) - : relevance(relevance), name(name) {} // name after relevance - whipowill - NextAction(NextAction const& o) : relevance(o.relevance), name(o.name) {} // name after relevance - whipowill + : relevance(relevance), name(name) {} + + NextAction(NextAction const&) = default; + NextAction& operator=(NextAction const&) = default; std::string const getName() { return name; } float getRelevance() { return relevance; } diff --git a/src/Bot/Engine/AiObjectContext.h b/src/Bot/Engine/AiObjectContext.h index 3ffd1850ff..e5e68fc01c 100644 --- a/src/Bot/Engine/AiObjectContext.h +++ b/src/Bot/Engine/AiObjectContext.h @@ -19,6 +19,8 @@ class PlayerbotAI; +class Strategy; + typedef Strategy* (*StrategyCreator)(PlayerbotAI* botAI); typedef Action* (*ActionCreator)(PlayerbotAI* botAI); typedef Trigger* (*TriggerCreator)(PlayerbotAI* botAI); diff --git a/src/Bot/Engine/Engine.cpp b/src/Bot/Engine/Engine.cpp index 6ed61a1a4b..0458d1151c 100644 --- a/src/Bot/Engine/Engine.cpp +++ b/src/Bot/Engine/Engine.cpp @@ -138,11 +138,11 @@ void Engine::Init() } } -bool Engine::DoNextAction(Unit* unit, uint32 depth, bool minimal) +bool Engine::DoNextAction(Unit*, uint32, bool minimal) { LogAction("--- AI Tick ---"); - if (sPlayerbotAIConfig->logValuesPerTick) + if (sPlayerbotAIConfig.logValuesPerTick) LogValues(); bool actionExecuted = false; @@ -154,7 +154,7 @@ bool Engine::DoNextAction(Unit* unit, uint32 depth, bool minimal) PushDefaultActions(); uint32 iterations = 0; - uint32 iterationsPerTick = queue.Size() * (minimal ? 2 : sPlayerbotAIConfig->iterationsPerTick); + uint32 iterationsPerTick = queue.Size() * (minimal ? 2 : sPlayerbotAIConfig.iterationsPerTick); while (++iterations <= iterationsPerTick) { @@ -204,7 +204,7 @@ bool Engine::DoNextAction(Unit* unit, uint32 depth, bool minimal) } } - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_ACTION, action->getName(), &aiObjectContext->performanceStack); + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_ACTION, action->getName(), &aiObjectContext->performanceStack); actionExecuted = ListenAndExecute(action, event); if (pmo) pmo->finish(); @@ -457,7 +457,7 @@ void Engine::ProcessTriggers(bool minimal) continue; PerfMonitorOperation* pmo = - sPerfMonitor->start(PERF_MON_TRIGGER, trigger->getName(), &aiObjectContext->performanceStack); + sPerfMonitor.start(PERF_MON_TRIGGER, trigger->getName(), &aiObjectContext->performanceStack); Event event = trigger->Check(); if (pmo) pmo->finish(); @@ -599,7 +599,7 @@ bool Engine::ListenAndExecute(Action* action, Event event) void Engine::LogAction(char const* format, ...) { Player* bot = botAI->GetBot(); - if (sPlayerbotAIConfig->logInGroupOnly && (!bot->GetGroup() || !botAI->HasRealPlayerMaster()) && !testMode) + if (sPlayerbotAIConfig.logInGroupOnly && (!bot->GetGroup() || !botAI->HasRealPlayerMaster()) && !testMode) return; char buf[1024]; @@ -661,7 +661,7 @@ void Engine::LogValues() return; Player* bot = botAI->GetBot(); - if (sPlayerbotAIConfig->logInGroupOnly && (!bot->GetGroup() || !botAI->HasRealPlayerMaster())) + if (sPlayerbotAIConfig.logInGroupOnly && (!bot->GetGroup() || !botAI->HasRealPlayerMaster())) return; std::string const text = botAI->GetAiObjectContext()->FormatValues(); diff --git a/src/Bot/Engine/PlayerbotAIBase.cpp b/src/Bot/Engine/PlayerbotAIBase.cpp index c034979340..cf4ad172cc 100644 --- a/src/Bot/Engine/PlayerbotAIBase.cpp +++ b/src/Bot/Engine/PlayerbotAIBase.cpp @@ -14,7 +14,7 @@ void PlayerbotAIBase::UpdateAI(uint32 elapsed, bool minimal) if (totalPmo) totalPmo->finish(); - totalPmo = sPerfMonitor->start(PERF_MON_TOTAL, "PlayerbotAIBase::FullTick"); + totalPmo = sPerfMonitor.start(PERF_MON_TOTAL, "PlayerbotAIBase::FullTick"); if (nextAICheckDelay > elapsed) nextAICheckDelay -= elapsed; @@ -35,7 +35,7 @@ void PlayerbotAIBase::SetNextCheckDelay(uint32 const delay) nextAICheckDelay = delay; - // if (nextAICheckDelay > sPlayerbotAIConfig->globalCoolDown) + // if (nextAICheckDelay > sPlayerbotAIConfig.globalCoolDown) // LOG_DEBUG("playerbots", "std::set next check delay: {}", nextAICheckDelay); } @@ -43,7 +43,7 @@ void PlayerbotAIBase::IncreaseNextCheckDelay(uint32 delay) { nextAICheckDelay += delay; - // if (nextAICheckDelay > sPlayerbotAIConfig->globalCoolDown) + // if (nextAICheckDelay > sPlayerbotAIConfig.globalCoolDown) // LOG_DEBUG("playerbots", "increase next check delay: {}", nextAICheckDelay); } @@ -55,6 +55,6 @@ void PlayerbotAIBase::YieldThread(uint32 delay) nextAICheckDelay = delay; } -bool PlayerbotAIBase::IsActive() { return nextAICheckDelay < sPlayerbotAIConfig->maxWaitForMove; } +bool PlayerbotAIBase::IsActive() { return nextAICheckDelay < sPlayerbotAIConfig.maxWaitForMove; } bool PlayerbotAIBase::IsBotAI() const { return _isBotAI; } diff --git a/src/Bot/Engine/PlayerbotAIBase.h b/src/Bot/Engine/PlayerbotAIBase.h index 03c762a58f..d0e0b775b2 100644 --- a/src/Bot/Engine/PlayerbotAIBase.h +++ b/src/Bot/Engine/PlayerbotAIBase.h @@ -17,7 +17,7 @@ class PlayerbotAIBase bool CanUpdateAI(); void SetNextCheckDelay(uint32 const delay); void IncreaseNextCheckDelay(uint32 delay); - void YieldThread(uint32 delay = sPlayerbotAIConfig->reactDelay); + void YieldThread(uint32 delay = sPlayerbotAIConfig.reactDelay); virtual void UpdateAI(uint32 elapsed, bool minimal = false); virtual void UpdateAIInternal(uint32 elapsed, bool minimal = false) = 0; bool IsActive(); diff --git a/src/Bot/Engine/Strategy/CustomStrategy.cpp b/src/Bot/Engine/Strategy/CustomStrategy.cpp index d4dd3e514e..1e54787ec4 100644 --- a/src/Bot/Engine/Strategy/CustomStrategy.cpp +++ b/src/Bot/Engine/Strategy/CustomStrategy.cpp @@ -35,7 +35,7 @@ std::vector toNextActionArray(const std::string actions) const std::vector tokens = split(actions, ','); std::vector res = {}; - for (const std::string token : tokens) + for (const std::string& token : tokens) { res.push_back(toNextAction(token)); } diff --git a/src/Bot/Engine/Trigger/Trigger.cpp b/src/Bot/Engine/Trigger/Trigger.cpp index 07105be299..3166001c2f 100644 --- a/src/Bot/Engine/Trigger/Trigger.cpp +++ b/src/Bot/Engine/Trigger/Trigger.cpp @@ -5,9 +5,8 @@ #include "Trigger.h" +#include "AiObjectContext.h" #include "Event.h" -#include "Playerbots.h" -#include "Timer.h" Trigger::Trigger(PlayerbotAI* botAI, std::string const name, int32 checkInterval) : AiNamedObject(botAI, name), @@ -28,18 +27,20 @@ Event Trigger::Check() return event; } -Value* Trigger::GetTargetValue() { return context->GetValue(GetTargetName()); } +Value* Trigger::GetTargetValue() { return this->context->GetValue(GetTargetName()); } Unit* Trigger::GetTarget() { return GetTargetValue()->Get(); } bool Trigger::needCheck(uint32 now) { - if (checkInterval < 2) + if (this->checkInterval < 2) return true; - if (!lastCheckTime || now - lastCheckTime >= checkInterval) + const int64_t signedLastCheckTime = this->lastCheckTime; + + if (!this->lastCheckTime || now - signedLastCheckTime >= this->checkInterval) { - lastCheckTime = now; + this->lastCheckTime = now; return true; } diff --git a/src/Bot/Engine/Trigger/Trigger.h b/src/Bot/Engine/Trigger/Trigger.h index d32845dc52..8878530f8d 100644 --- a/src/Bot/Engine/Trigger/Trigger.h +++ b/src/Bot/Engine/Trigger/Trigger.h @@ -6,7 +6,6 @@ #pragma once #include "Action.h" -#include "Common.h" class PlayerbotAI; class Unit; diff --git a/src/Bot/Engine/Value/Value.cpp b/src/Bot/Engine/Value/Value.cpp index c559e03816..ae14d15286 100644 --- a/src/Bot/Engine/Value/Value.cpp +++ b/src/Bot/Engine/Value/Value.cpp @@ -123,7 +123,7 @@ Unit* UnitCalculatedValue::Get() { if (checkInterval < 2) { - PerfMonitorOperation* pmo = sPerfMonitor->start( + PerfMonitorOperation* pmo = sPerfMonitor.start( PERF_MON_VALUE, this->getName(), this->context ? &this->context->performanceStack : nullptr); value = Calculate(); if (pmo) @@ -135,7 +135,7 @@ Unit* UnitCalculatedValue::Get() if (!lastCheckTime || now - lastCheckTime >= checkInterval) { lastCheckTime = now; - PerfMonitorOperation* pmo = sPerfMonitor->start( + PerfMonitorOperation* pmo = sPerfMonitor.start( PERF_MON_VALUE, this->getName(), this->context ? &this->context->performanceStack : nullptr); value = Calculate(); if (pmo) diff --git a/src/Bot/Engine/Value/Value.h b/src/Bot/Engine/Value/Value.h index b37e162050..4ab7b3fbb0 100644 --- a/src/Bot/Engine/Value/Value.h +++ b/src/Bot/Engine/Value/Value.h @@ -72,7 +72,7 @@ class CalculatedValue : public UntypedValue, public Value { if (checkInterval < 2) { - // PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_VALUE, this->getName(), + // PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_VALUE, this->getName(), // this->context ? &this->context->performanceStack : nullptr); value = Calculate(); // if (pmo) @@ -84,7 +84,7 @@ class CalculatedValue : public UntypedValue, public Value if (!lastCheckTime || now - lastCheckTime >= checkInterval) { lastCheckTime = now; - // PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_VALUE, this->getName(), + // PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_VALUE, this->getName(), // this->context ? &this->context->performanceStack : nullptr); value = Calculate(); // if (pmo) @@ -105,7 +105,7 @@ class CalculatedValue : public UntypedValue, public Value { if (checkInterval < 2) { - // PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_VALUE, this->getName(), + // PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_VALUE, this->getName(), // this->context ? &this->context->performanceStack : nullptr); value = Calculate(); // if (pmo) @@ -117,7 +117,7 @@ class CalculatedValue : public UntypedValue, public Value if (!lastCheckTime || now - lastCheckTime >= checkInterval) { lastCheckTime = now; - // PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_VALUE, this->getName(), + // PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_VALUE, this->getName(), // this->context ? &this->context->performanceStack : nullptr); value = Calculate(); // if (pmo) @@ -154,11 +154,11 @@ class SingleCalculatedValue : public CalculatedValue { this->lastCheckTime = now; - PerfMonitorOperation* pmo = sPerfMonitor->start( - PERF_MON_VALUE, this->getName(), this->context ? &this->context->performanceStack : nullptr); + // PerfMonitorOperation* pmo = sPerfMonitor.start( + // PERF_MON_VALUE, this->getName(), this->context ? &this->context->performanceStack : nullptr); this->value = this->Calculate(); - if (pmo) - pmo->finish(); + // if (pmo) + // pmo->finish(); } return this->value; diff --git a/src/Bot/Factory/AiFactory.cpp b/src/Bot/Factory/AiFactory.cpp index 8ca3534b1d..84b3a7dc53 100644 --- a/src/Bot/Factory/AiFactory.cpp +++ b/src/Bot/Factory/AiFactory.cpp @@ -281,7 +281,7 @@ void AiFactory::AddDefaultCombatStrategies(Player* player, PlayerbotAI* const fa if (!player->InBattleground()) engine->addStrategiesNoInit("racials", "chat", "default", "cast time", "potions", "duel", "boost", nullptr); - if (sPlayerbotAIConfig->autoAvoidAoe && facade->HasRealPlayerMaster()) + if (sPlayerbotAIConfig.autoAvoidAoe && facade->HasRealPlayerMaster()) engine->addStrategy("avoid aoe", false); engine->addStrategy("formation", false); @@ -399,13 +399,13 @@ void AiFactory::AddDefaultCombatStrategies(Player* player, PlayerbotAI* const fa if (PlayerbotAI::IsHeal(player, true)) { - if (sPlayerbotAIConfig->autoSaveMana) + if (sPlayerbotAIConfig.autoSaveMana) engine->addStrategy("save mana", false); - if (!sPlayerbotAIConfig->IsRestrictedHealerDPSMap(player->GetMapId())) + if (!sPlayerbotAIConfig.IsRestrictedHealerDPSMap(player->GetMapId())) engine->addStrategy("healer dps", false); } - if (facade->IsRealPlayer() || sRandomPlayerbotMgr->IsRandomBot(player)) + if (facade->IsRealPlayer() || sRandomPlayerbotMgr.IsRandomBot(player)) { if (!player->GetGroup()) { @@ -448,10 +448,10 @@ void AiFactory::AddDefaultCombatStrategies(Player* player, PlayerbotAI* const fa } } } - if (sRandomPlayerbotMgr->IsRandomBot(player)) - engine->ChangeStrategy(sPlayerbotAIConfig->randomBotCombatStrategies); + if (sRandomPlayerbotMgr.IsRandomBot(player)) + engine->ChangeStrategy(sPlayerbotAIConfig.randomBotCombatStrategies); else - engine->ChangeStrategy(sPlayerbotAIConfig->combatStrategies); + engine->ChangeStrategy(sPlayerbotAIConfig.combatStrategies); // Battleground switch if (player->InBattleground() && player->GetBattleground()) @@ -586,10 +586,10 @@ void AiFactory::AddDefaultNonCombatStrategies(Player* player, PlayerbotAI* const "gather", "duel", "pvp", "buff", "mount", "emote", nullptr); } - if (sPlayerbotAIConfig->autoSaveMana && PlayerbotAI::IsHeal(player, true)) + if (sPlayerbotAIConfig.autoSaveMana && PlayerbotAI::IsHeal(player, true)) nonCombatEngine->addStrategy("save mana", false); - if ((sRandomPlayerbotMgr->IsRandomBot(player)) && !player->InBattleground()) + if ((sRandomPlayerbotMgr.IsRandomBot(player)) && !player->InBattleground()) { Player* master = facade->GetMaster(); @@ -597,7 +597,7 @@ void AiFactory::AddDefaultNonCombatStrategies(Player* player, PlayerbotAI* const if (!urand(0, 3)) nonCombatEngine->addStrategy("start duel", false); - if (sPlayerbotAIConfig->randomBotJoinLfg) + if (sPlayerbotAIConfig.randomBotJoinLfg) nonCombatEngine->addStrategy("lfg", false); if (!player->GetGroup() || player->GetGroup()->GetLeaderGUID() == player->GetGUID()) @@ -612,9 +612,9 @@ void AiFactory::AddDefaultNonCombatStrategies(Player* player, PlayerbotAI* const // nonCombatEngine->addStrategy("guild"); nonCombatEngine->addStrategy("grind", false); - if (sPlayerbotAIConfig->enableNewRpgStrategy) + if (sPlayerbotAIConfig.enableNewRpgStrategy) nonCombatEngine->addStrategy("new rpg", false); - else if (sPlayerbotAIConfig->autoDoQuests) + else if (sPlayerbotAIConfig.autoDoQuests) { // nonCombatEngine->addStrategy("travel"); nonCombatEngine->addStrategy("rpg", false); @@ -622,13 +622,13 @@ void AiFactory::AddDefaultNonCombatStrategies(Player* player, PlayerbotAI* const else nonCombatEngine->addStrategy("move random", false); - if (sPlayerbotAIConfig->randomBotJoinBG) + if (sPlayerbotAIConfig.randomBotJoinBG) nonCombatEngine->addStrategy("bg", false); // if (!master || GET_PLAYERBOT_AI(master)) // nonCombatEngine->addStrategy("maintenance"); - nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig->randomBotNonCombatStrategies); + nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig.randomBotNonCombatStrategies); } else { @@ -637,14 +637,14 @@ void AiFactory::AddDefaultNonCombatStrategies(Player* player, PlayerbotAI* const if (master) { PlayerbotAI* masterBotAI = GET_PLAYERBOT_AI(master); - if (masterBotAI || sRandomPlayerbotMgr->IsRandomBot(player)) + if (masterBotAI || sRandomPlayerbotMgr.IsRandomBot(player)) { // nonCombatEngine->addStrategy("pvp", false); // nonCombatEngine->addStrategy("collision"); // nonCombatEngine->addStrategy("group"); // nonCombatEngine->addStrategy("guild"); - // if (sPlayerbotAIConfig->autoDoQuests) + // if (sPlayerbotAIConfig.autoDoQuests) // { // // nonCombatEngine->addStrategy("travel"); // nonCombatEngine->addStrategy("rpg"); @@ -657,19 +657,19 @@ void AiFactory::AddDefaultNonCombatStrategies(Player* player, PlayerbotAI* const // if (masterBotAI) // nonCombatEngine->addStrategy("maintenance"); - nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig->randomBotNonCombatStrategies); + nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig.randomBotNonCombatStrategies); } else { // nonCombatEngine->addStrategy("pvp", false); - nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig->nonCombatStrategies); + nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig.nonCombatStrategies); } } } } } else - nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig->nonCombatStrategies); + nonCombatEngine->ChangeStrategy(sPlayerbotAIConfig.nonCombatStrategies); // Battleground switch if (player->InBattleground() && player->GetBattleground()) @@ -726,7 +726,7 @@ void AiFactory::AddDefaultDeadStrategies(Player* player, PlayerbotAI* const faca (void)facade; // unused and remove warning deadEngine->addStrategiesNoInit("dead", "stay", "chat", "default", "follow", nullptr); - if (sRandomPlayerbotMgr->IsRandomBot(player) && !player->GetGroup()) + if (sRandomPlayerbotMgr.IsRandomBot(player) && !player->GetGroup()) deadEngine->removeStrategy("follow", false); } diff --git a/src/Bot/Factory/AiFactory.h b/src/Bot/Factory/AiFactory.h index 3d11d80aeb..052aefc4b5 100644 --- a/src/Bot/Factory/AiFactory.h +++ b/src/Bot/Factory/AiFactory.h @@ -6,16 +6,16 @@ #ifndef _PLAYERBOT_AIFACTORY_H #define _PLAYERBOT_AIFACTORY_H +#include #include - -#include "Common.h" +#include class AiObjectContext; class Engine; class Player; class PlayerbotAI; -enum BotRoles : uint8; +enum BotRoles : uint8_t; class AiFactory { @@ -28,8 +28,8 @@ class AiFactory static void AddDefaultDeadStrategies(Player* player, PlayerbotAI* const facade, Engine* deadEngine); static void AddDefaultCombatStrategies(Player* player, PlayerbotAI* const facade, Engine* engine); - static uint8 GetPlayerSpecTab(Player* player); - static std::map GetPlayerSpecTabs(Player* player); + static uint8_t GetPlayerSpecTab(Player* player); + static std::map GetPlayerSpecTabs(Player* player); static BotRoles GetPlayerRoles(Player* player); static std::string GetPlayerSpecName(Player* player); }; diff --git a/src/Bot/Factory/PlayerbotFactory.cpp b/src/Bot/Factory/PlayerbotFactory.cpp index 67f5909c11..1c9c76ef3c 100644 --- a/src/Bot/Factory/PlayerbotFactory.cpp +++ b/src/Bot/Factory/PlayerbotFactory.cpp @@ -5,7 +5,6 @@ #include "PlayerbotFactory.h" -#include #include #include "AccountMgr.h" @@ -20,9 +19,7 @@ #include "ItemTemplate.h" #include "ItemVisitors.h" #include "Log.h" -#include "LogCommon.h" #include "LootMgr.h" -#include "MapMgr.h" #include "ObjectMgr.h" #include "PerfMonitor.h" #include "PetDefines.h" @@ -37,7 +34,6 @@ #include "RandomPlayerbotFactory.h" #include "ReputationMgr.h" #include "SharedDefines.h" -#include "SpellAuraDefines.h" #include "StatsWeightCalculator.h" #include "World.h" #include "AiObjectContext.h" @@ -68,18 +64,18 @@ PlayerbotFactory::PlayerbotFactory(Player* bot, uint32 level, uint32 itemQuality botAI = GET_PLAYERBOT_AI(bot); if (!this->itemQuality) { - uint32 gs = sPlayerbotAIConfig->randomGearScoreLimit == 0 + uint32 gs = sPlayerbotAIConfig.randomGearScoreLimit == 0 ? 0 - : PlayerbotFactory::CalcMixedGearScore(sPlayerbotAIConfig->randomGearScoreLimit, - sPlayerbotAIConfig->randomGearQualityLimit); - this->itemQuality = sPlayerbotAIConfig->randomGearQualityLimit; + : PlayerbotFactory::CalcMixedGearScore(sPlayerbotAIConfig.randomGearScoreLimit, + sPlayerbotAIConfig.randomGearQualityLimit); + this->itemQuality = sPlayerbotAIConfig.randomGearQualityLimit; this->gearScoreLimit = gs; } } void PlayerbotFactory::Init() { - if (sPlayerbotAIConfig->randomBotPreQuests) + if (sPlayerbotAIConfig.randomBotPreQuests) { ObjectMgr::QuestMap const& questTemplates = sObjectMgr->GetQuestTemplates(); for (ObjectMgr::QuestMap::const_iterator i = questTemplates.begin(); i != questTemplates.end(); ++i) @@ -111,8 +107,8 @@ void PlayerbotFactory::Init() } } - for (std::vector::iterator i = sPlayerbotAIConfig->randomBotQuestIds.begin(); - i != sPlayerbotAIConfig->randomBotQuestIds.end(); ++i) + for (std::vector::iterator i = sPlayerbotAIConfig.randomBotQuestIds.begin(); + i != sPlayerbotAIConfig.randomBotQuestIds.end(); ++i) { uint32 questId = *i; AddPrevQuests(questId, specialQuestIds); @@ -190,7 +186,7 @@ void PlayerbotFactory::Init() continue; } - if (sRandomItemMgr->IsTestItem(gemId)) + if (sRandomItemMgr.IsTestItem(gemId)) { continue; } @@ -218,12 +214,12 @@ void PlayerbotFactory::Prepare() { bot->SetUInt32Value(PLAYER_XP, 0); } - if (!sPlayerbotAIConfig->randomBotShowHelmet || !urand(0, 4)) + if (!sPlayerbotAIConfig.randomBotShowHelmet || !urand(0, 4)) { bot->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM); } - if (!sPlayerbotAIConfig->randomBotShowCloak || !urand(0, 4)) + if (!sPlayerbotAIConfig.randomBotShowCloak || !urand(0, 4)) { bot->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK); } @@ -231,7 +227,7 @@ void PlayerbotFactory::Prepare() void PlayerbotFactory::Randomize(bool incremental) { - // if (sPlayerbotAIConfig->disableRandomLevels) + // if (sPlayerbotAIConfig.disableRandomLevels) // { // return; // } @@ -240,17 +236,21 @@ void PlayerbotFactory::Randomize(bool incremental) // LOG_DEBUG("playerbots", "Preparing to {} randomize...", (incremental ? "incremental" : "full")); Prepare(); LOG_DEBUG("playerbots", "Resetting player..."); - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Reset"); - if (!sPlayerbotAIConfig->equipmentPersistence || level < sPlayerbotAIConfig->equipmentPersistenceLevel) + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Reset"); + + const int64_t botLevel = this->level; + + if (!PlayerbotAIConfig::instance().equipmentPersistence || botLevel < PlayerbotAIConfig::instance().equipmentPersistenceLevel) { bot->resetTalents(true); } + if (!incremental) { ClearSkills(); ClearSpells(); ResetQuests(); - if (!sPlayerbotAIConfig->equipmentPersistence || level < sPlayerbotAIConfig->equipmentPersistenceLevel) + if (!PlayerbotAIConfig::instance().equipmentPersistence || botLevel < PlayerbotAIConfig::instance().equipmentPersistenceLevel) { ClearAllItems(); } @@ -266,15 +266,15 @@ void PlayerbotFactory::Randomize(bool incremental) if (pmo) pmo->finish(); - // pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Immersive"); + // pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Immersive"); // LOG_INFO("playerbots", "Initializing immersive..."); // InitImmersive(); // if (pmo) // pmo->finish(); - if (sPlayerbotAIConfig->randomBotPreQuests) + if (sPlayerbotAIConfig.randomBotPreQuests) { - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Quests"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Quests"); InitInstanceQuests(); InitAttunementQuests(); if (pmo) @@ -282,157 +282,157 @@ void PlayerbotFactory::Randomize(bool incremental) } else { - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Quests"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Quests"); InitAttunementQuests(); if (pmo) pmo->finish(); } LOG_DEBUG("playerbots", "Initializing skills (step 1)..."); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Skills1"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Skills1"); bot->LearnDefaultSkills(); InitSkills(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Spells1"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Spells1"); LOG_DEBUG("playerbots", "Initializing spells (step 1)..."); InitClassSpells(); InitAvailableSpells(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Talents"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Talents"); LOG_DEBUG("playerbots", "Initializing talents..."); - if (!incremental || !sPlayerbotAIConfig->equipmentPersistence || - bot->GetLevel() < sPlayerbotAIConfig->equipmentPersistenceLevel) + if (!incremental || !sPlayerbotAIConfig.equipmentPersistence || + bot->GetLevel() < sPlayerbotAIConfig.equipmentPersistenceLevel) { InitTalentsTree(); } - sRandomPlayerbotMgr->SetValue(bot->GetGUID().GetCounter(), "specNo", 0); + sRandomPlayerbotMgr.SetValue(bot->GetGUID().GetCounter(), "specNo", 0); if (botAI) { - sPlayerbotRepository->Reset(botAI); + PlayerbotRepository::instance().Reset(botAI); // botAI->DoSpecificAction("auto talents"); botAI->ResetStrategies(false); // fix wrong stored strategy } if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Spells2"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Spells2"); LOG_DEBUG("playerbots", "Initializing spells (step 2)..."); InitAvailableSpells(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Reputation"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Reputation"); LOG_DEBUG("playerbots", "Initializing reputation..."); InitReputation(); if (pmo) pmo->finish(); LOG_DEBUG("playerbots", "Initializing special spells..."); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Spells3"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Spells3"); InitSpecialSpells(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Mounts"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Mounts"); LOG_DEBUG("playerbots", "Initializing mounts..."); InitMounts(); // bot->SaveToDB(false, false); if (pmo) pmo->finish(); - // pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Skills2"); + // pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Skills2"); // LOG_INFO("playerbots", "Initializing skills (step 2)..."); // UpdateTradeSkills(); // if (pmo) // pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Equip"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Equip"); LOG_DEBUG("playerbots", "Initializing equipmemt..."); - if (!incremental || !sPlayerbotAIConfig->equipmentPersistence || - bot->GetLevel() < sPlayerbotAIConfig->equipmentPersistenceLevel) + if (!incremental || !sPlayerbotAIConfig.equipmentPersistence || + bot->GetLevel() < sPlayerbotAIConfig.equipmentPersistenceLevel) { - if (sPlayerbotAIConfig->incrementalGearInit || !incremental) - InitEquipment(incremental, incremental ? false : sPlayerbotAIConfig->twoRoundsGearInit); + if (sPlayerbotAIConfig.incrementalGearInit || !incremental) + InitEquipment(incremental, incremental ? false : sPlayerbotAIConfig.twoRoundsGearInit); } // bot->SaveToDB(false, false); if (pmo) pmo->finish(); - // if (bot->GetLevel() >= sPlayerbotAIConfig->minEnchantingBotLevel) + // if (bot->GetLevel() >= sPlayerbotAIConfig.minEnchantingBotLevel) // { - // pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Enchant"); + // pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Enchant"); // LOG_INFO("playerbots", "Initializing enchant templates..."); // LoadEnchantContainer(); // if (pmo) // pmo->finish(); // } - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Bags"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Bags"); LOG_DEBUG("playerbots", "Initializing bags..."); InitBags(); // bot->SaveToDB(false, false); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Ammo"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Ammo"); LOG_DEBUG("playerbots", "Initializing ammo..."); InitAmmo(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Food"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Food"); LOG_DEBUG("playerbots", "Initializing food..."); InitFood(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Potions"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Potions"); LOG_DEBUG("playerbots", "Initializing potions..."); InitPotions(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Reagents"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Reagents"); LOG_DEBUG("playerbots", "Initializing reagents..."); InitReagents(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Keys"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Keys"); LOG_DEBUG("playerbots", "Initializing keys..."); InitKeyring(); if (pmo) pmo->finish(); - // pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_EqSets"); + // pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_EqSets"); // LOG_DEBUG("playerbots", "Initializing second equipment set..."); // InitSecondEquipmentSet(); // if (pmo) // pmo->finish(); - if (bot->GetLevel() >= sPlayerbotAIConfig->minEnchantingBotLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.minEnchantingBotLevel) { ApplyEnchantAndGemsNew(); } // { - // pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_EnchantTemplate"); + // pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_EnchantTemplate"); // LOG_INFO("playerbots", "Initializing enchant templates..."); // ApplyEnchantTemplate(); // if (pmo) // pmo->finish(); // } - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Inventory"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Inventory"); LOG_DEBUG("playerbots", "Initializing inventory..."); // InitInventory(); if (pmo) pmo->finish(); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Consumable"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Consumable"); LOG_DEBUG("playerbots", "Initializing consumables..."); InitConsumables(); if (pmo) @@ -442,9 +442,9 @@ void PlayerbotFactory::Randomize(bool incremental) InitGlyphs(); // bot->SaveToDB(false, false); - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Guilds"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Guilds"); // bot->SaveToDB(false, false); - if (sPlayerbotAIConfig->randomBotGuildCount > 0) + if (sPlayerbotAIConfig.randomBotGuildCount > 0) { LOG_DEBUG("playerbots", "Initializing guilds..."); InitGuild(); @@ -455,7 +455,7 @@ void PlayerbotFactory::Randomize(bool incremental) if (bot->GetLevel() >= 70) { - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Arenas"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Arenas"); // LOG_INFO("playerbots", "Initializing arena teams..."); InitArenaTeam(); if (pmo) @@ -470,7 +470,7 @@ void PlayerbotFactory::Randomize(bool incremental) } if (bot->GetLevel() >= 10) { - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Pet"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Pet"); LOG_DEBUG("playerbots", "Initializing pet..."); InitPet(); // bot->SaveToDB(false, false); @@ -479,7 +479,7 @@ void PlayerbotFactory::Randomize(bool incremental) pmo->finish(); } - pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "PlayerbotFactory_Save"); + pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "PlayerbotFactory_Save"); LOG_DEBUG("playerbots", "Saving to DB..."); bot->SetMoney(urand(level * 100000, level * 5 * 100000)); bot->SetHealth(bot->GetMaxHealth()); @@ -493,7 +493,7 @@ void PlayerbotFactory::Randomize(bool incremental) void PlayerbotFactory::Refresh() { // Prepare(); - // if (!sPlayerbotAIConfig->equipmentPersistence || bot->GetLevel() < sPlayerbotAIConfig->equipmentPersistenceLevel) + // if (!sPlayerbotAIConfig.equipmentPersistence || bot->GetLevel() < sPlayerbotAIConfig.equipmentPersistenceLevel) // { // InitEquipment(true); // } @@ -513,11 +513,11 @@ void PlayerbotFactory::Refresh() InitSpecialSpells(); InitMounts(); InitKeyring(); - if (!sPlayerbotAIConfig->equipmentPersistence || bot->GetLevel() < sPlayerbotAIConfig->equipmentPersistenceLevel) + if (!sPlayerbotAIConfig.equipmentPersistence || bot->GetLevel() < sPlayerbotAIConfig.equipmentPersistenceLevel) { InitTalentsTree(true, true, true); } - if (bot->GetLevel() >= sPlayerbotAIConfig->minEnchantingBotLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.minEnchantingBotLevel) { ApplyEnchantAndGemsNew(); } @@ -746,7 +746,7 @@ void PlayerbotFactory::InitConsumables() void PlayerbotFactory::InitPetTalents() { - if (bot->GetLevel() <= 70 && sPlayerbotAIConfig->limitTalentsExpansion) + if (bot->GetLevel() <= 70 && sPlayerbotAIConfig.limitTalentsExpansion) return; Pet* pet = bot->GetPet(); @@ -794,7 +794,7 @@ void PlayerbotFactory::InitPetTalents() } std::vector> order = - sPlayerbotAIConfig->parsedHunterPetLinkOrder[pet_family->petTalentType][20]; + sPlayerbotAIConfig.parsedHunterPetLinkOrder[pet_family->petTalentType][20]; uint32 maxTalentPoints = pet->GetMaxTalentPointsForLevel(pet->GetLevel()); if (order.empty()) @@ -817,7 +817,7 @@ void PlayerbotFactory::InitPetTalents() int index = urand(0, spells_row.size() - 1); TalentEntry const* talentInfo = spells_row[index]; int maxRank = 0; - for (int rank = 0; rank < std::min((uint32)MAX_TALENT_RANK, (uint32)pet->GetFreeTalentPoints()); ++rank) + for (uint8_t rank = 0; rank < std::min((uint32)MAX_TALENT_RANK, (uint32)pet->GetFreeTalentPoints()); ++rank) { uint32 spellId = talentInfo->RankID[rank]; if (!spellId) @@ -842,16 +842,16 @@ void PlayerbotFactory::InitPetTalents() uint32 spec = pet_family->petTalentType; uint32 startPoints = pet->GetMaxTalentPointsForLevel(pet->GetLevel()); while (startPoints > 1 && startPoints < 20 && - sPlayerbotAIConfig->parsedHunterPetLinkOrder[spec][startPoints].size() == 0) + sPlayerbotAIConfig.parsedHunterPetLinkOrder[spec][startPoints].size() == 0) { startPoints--; } for (uint32 points = startPoints; points <= 20; points++) { - if (sPlayerbotAIConfig->parsedHunterPetLinkOrder[spec][points].size() == 0) + if (sPlayerbotAIConfig.parsedHunterPetLinkOrder[spec][points].size() == 0) continue; - for (std::vector& p : sPlayerbotAIConfig->parsedHunterPetLinkOrder[spec][points]) + for (std::vector& p : sPlayerbotAIConfig.parsedHunterPetLinkOrder[spec][points]) { uint32 row = p[0], col = p[1], lvl = p[2]; uint32 talentID = 0; @@ -924,17 +924,17 @@ void PlayerbotFactory::InitPet() if (itr->second.minlevel > bot->GetLevel()) continue; - bool onlyWolf = sPlayerbotAIConfig->hunterWolfPet == 2 || - (sPlayerbotAIConfig->hunterWolfPet == 1 && + bool onlyWolf = sPlayerbotAIConfig.hunterWolfPet == 2 || + (sPlayerbotAIConfig.hunterWolfPet == 1 && bot->GetLevel() >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)); // Wolf only (for higher dps) if (onlyWolf && itr->second.family != CREATURE_FAMILY_WOLF) continue; // Exclude configured pet families - if (std::find(sPlayerbotAIConfig->excludedHunterPetFamilies.begin(), - sPlayerbotAIConfig->excludedHunterPetFamilies.end(), - itr->second.family) != sPlayerbotAIConfig->excludedHunterPetFamilies.end()) + if (std::find(sPlayerbotAIConfig.excludedHunterPetFamilies.begin(), + sPlayerbotAIConfig.excludedHunterPetFamilies.end(), + itr->second.family) != sPlayerbotAIConfig.excludedHunterPetFamilies.end()) continue; ids.push_back(itr->first); @@ -954,8 +954,6 @@ void PlayerbotFactory::InitPet() continue; if (co->Name.size() > 21) continue; - uint32 guid = map->GenerateLowGuid(); - uint32 pet_number = sObjectMgr->GeneratePetNumber(); if (bot->GetPetStable() && bot->GetPetStable()->CurrentPet) { auto petGuid = bot->GetPetStable()->CurrentPet.value(); // To correct the build warnin in VS @@ -1123,8 +1121,8 @@ void PlayerbotFactory::InitTalentsTree(bool increment /*false*/, bool use_templa bool isCat = !bot->HasAura(16931); if (!isCat && bot->GetLevel() == 20) { - uint32 bearP = sPlayerbotAIConfig->randomClassSpecProb[cls][1]; - uint32 catP = sPlayerbotAIConfig->randomClassSpecProb[cls][3]; + uint32 bearP = sPlayerbotAIConfig.randomClassSpecProb[cls][1]; + uint32 catP = sPlayerbotAIConfig.randomClassSpecProb[cls][3]; if (urand(1, bearP + catP) <= catP) isCat = true; } @@ -1139,14 +1137,14 @@ void PlayerbotFactory::InitTalentsTree(bool increment /*false*/, bool use_templa uint32 pointSum = 0; for (int i = 0; i < MAX_SPECNO; i++) { - pointSum += sPlayerbotAIConfig->randomClassSpecProb[cls][i]; + pointSum += sPlayerbotAIConfig.randomClassSpecProb[cls][i]; } uint32 point = urand(1, pointSum); uint32 currentP = 0; int i; for (i = 0; i < MAX_SPECNO; i++) { - currentP += sPlayerbotAIConfig->randomClassSpecProb[cls][i]; + currentP += sPlayerbotAIConfig.randomClassSpecProb[cls][i]; if (point <= currentP) { specTab = i; @@ -1204,17 +1202,17 @@ void PlayerbotFactory::InitTalentsBySpecNo(Player* bot, int specNo, bool reset) spells_row[talentInfo->Row].push_back(talentInfo); } while (startLevel > 1 && startLevel < 80 && - sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specNo][startLevel].size() == 0) + sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specNo][startLevel].size() == 0) { startLevel--; } for (int level = startLevel; level <= 80; level++) { - if (sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specNo][level].size() == 0) + if (sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specNo][level].size() == 0) { continue; } - for (std::vector& p : sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specNo][level]) + for (std::vector& p : sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specNo][level]) { uint32 tab = p[0], row = p[1], col = p[2], lvl = p[3]; uint32 talentID = -1; @@ -1341,7 +1339,7 @@ class DestroyItemsVisitor : public IterateItemsVisitor if (keep.find(id) != keep.end()) return false; - if (sPlayerbotAIConfig->IsInRandomQuestItemList(id)) + if (sPlayerbotAIConfig.IsInRandomQuestItemList(id)) return true; return false; @@ -1603,7 +1601,7 @@ void Shuffle(std::vector& items) // bool noItem = false; // uint32 quality = urand(ITEM_QUALITY_UNCOMMON, ITEM_QUALITY_EPIC); // uint32 attempts = 10; -// if (urand(0, 100) < 100 * sPlayerbotAIConfig->randomGearLoweringChance && quality > ITEM_QUALITY_NORMAL) +// if (urand(0, 100) < 100 * sPlayerbotAIConfig.randomGearLoweringChance && quality > ITEM_QUALITY_NORMAL) // { // quality--; // } @@ -1614,11 +1612,11 @@ void Shuffle(std::vector& items) // uint32 itemInSlot = isUpgrade ? oldItem->GetTemplate()->ItemId : 0; -// uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; +// uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; // if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) // maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); -// uint32 minLevel = sPlayerbotAIConfig->randomBotMinLevel; +// uint32 minLevel = sPlayerbotAIConfig.randomBotMinLevel; // if (minLevel < sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL)) // minLevel = sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL); @@ -1627,7 +1625,7 @@ void Shuffle(std::vector& items) // { // if (isUpgrade) // { -// std::vector ids = sRandomItemMgr->GetUpgradeList(bot, specName, slot, 0, itemInSlot); +// std::vector ids = sRandomItemMgr.GetUpgradeList(bot, specName, slot, 0, itemInSlot); // if (!ids.empty()) // Shuffle(ids); @@ -1667,7 +1665,7 @@ void Shuffle(std::vector& items) // } // else // { -// std::vector ids = sRandomItemMgr->GetUpgradeList(bot, specName, slot, quality, itemInSlot); +// std::vector ids = sRandomItemMgr.GetUpgradeList(bot, specName, slot, quality, itemInSlot); // if (!ids.empty()) // Shuffle(ids); @@ -1706,7 +1704,7 @@ void Shuffle(std::vector& items) void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) { - if (incremental && !sPlayerbotAIConfig->incrementalGearInit) + if (incremental && !sPlayerbotAIConfig.incrementalGearInit) return; if (level < 5) @@ -1785,19 +1783,19 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) oldItem = bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot); - int32 desiredQuality = itemQuality; - if (urand(0, 100) < 100 * sPlayerbotAIConfig->randomGearLoweringChance && desiredQuality > ITEM_QUALITY_NORMAL) + uint32_t desiredQuality = itemQuality; + if (urand(0, 100) < 100 * sPlayerbotAIConfig.randomGearLoweringChance && desiredQuality > ITEM_QUALITY_NORMAL) { desiredQuality--; } do { - for (uint32 requiredLevel = bot->GetLevel(); requiredLevel > std::max((int32)bot->GetLevel() - delta, 0); + for (uint32 requiredLevel = bot->GetLevel(); requiredLevel > std::max((int32)bot->GetLevel() - delta, 0); requiredLevel--) { for (InventoryType inventoryType : GetPossibleInventoryTypeListBySlot((EquipmentSlots)slot)) { - for (uint32 itemId : sRandomItemMgr->GetCachedEquipments(requiredLevel, inventoryType)) + for (uint32 itemId : sRandomItemMgr.GetCachedEquipments(requiredLevel, inventoryType)) { if (itemId == 46978) // shaman earth ring totem { @@ -1808,10 +1806,10 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) continue; // disable next expansion gear - if (sPlayerbotAIConfig->limitGearExpansion && bot->GetLevel() <= 60 && itemId >= 23728) + if (sPlayerbotAIConfig.limitGearExpansion && bot->GetLevel() <= 60 && itemId >= 23728) continue; - if (sPlayerbotAIConfig->limitGearExpansion && bot->GetLevel() <= 70 && itemId >= 35570 && + if (sPlayerbotAIConfig.limitGearExpansion && bot->GetLevel() <= 70 && itemId >= 35570 && itemId != 36737 && itemId != 37739 && itemId != 37740) // transition point from TBC -> WOTLK isn't as clear, and there are other // wearable TBC items above 35570 but nothing of significance @@ -1862,7 +1860,7 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) float bestScoreForSlot = -1; uint32 bestItemForSlot = 0; - for (int index = 0; index < ids.size(); index++) + for (size_t index = 0; index < ids.size(); index++) { uint32 newItemId = ids[index]; @@ -1916,7 +1914,7 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) if (oldItem) continue; - Item* newItem = bot->EquipNewItem(dest, bestItemForSlot, true); + bot->EquipNewItem(dest, bestItemForSlot, true); bot->AutoUnequipOffhandIfNeed(); // if (newItem) // { @@ -1947,7 +1945,7 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) (slot != EQUIPMENT_SLOT_RANGED)) continue; - if (Item* oldItem = bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) + if (bot->GetItemByPos(INVENTORY_SLOT_BAG_0, slot) != nullptr) bot->DestroyItem(INVENTORY_SLOT_BAG_0, slot, true); std::vector& ids = items[slot]; @@ -1956,7 +1954,7 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) float bestScoreForSlot = -1; uint32 bestItemForSlot = 0; - for (int index = 0; index < ids.size(); index++) + for (size_t index = 0; index < ids.size(); index++) { uint32 newItemId = ids[index]; @@ -1985,7 +1983,7 @@ void PlayerbotFactory::InitEquipment(bool incremental, bool second_chance) { continue; } - Item* newItem = bot->EquipNewItem(dest, bestItemForSlot, true); + bot->EquipNewItem(dest, bestItemForSlot, true); bot->AutoUnequipOffhandIfNeed(); // if (newItem) // { @@ -2009,11 +2007,11 @@ bool PlayerbotFactory::IsDesiredReplacement(Item* item) } // if (!requiredLevel) // { - // requiredLevel = sRandomItemMgr->GetMinLevelFromCache(proto->ItemId); + // requiredLevel = sRandomItemMgr.GetMinLevelFromCache(proto->ItemId); // } uint32 delta = 1 + (80 - bot->GetLevel()) / 10; - return proto->Quality < ITEM_QUALITY_RARE || int32(bot->GetLevel() - requiredLevel) > delta; + return proto->Quality < ITEM_QUALITY_RARE || (bot->GetLevel() - requiredLevel) > delta; } inline Item* StoreNewItemInInventorySlot(Player* player, uint32 newItemId, uint32 count) @@ -2039,7 +2037,7 @@ inline Item* StoreNewItemInInventorySlot(Player* player, uint32 newItemId, uint3 // std::map> items; // uint32 desiredQuality = itemQuality; -// while (urand(0, 100) < 100 * sPlayerbotAIConfig->randomGearLoweringChance && desiredQuality > +// while (urand(0, 100) < 100 * sPlayerbotAIConfig.randomGearLoweringChance && desiredQuality > // ITEM_QUALITY_NORMAL) // { // desiredQuality--; @@ -2061,9 +2059,9 @@ inline Item* StoreNewItemInInventorySlot(Player* player, uint32 newItemId, uint3 // //if (!CanEquipWeapon(proto)) // // continue; -// if (sRandomItemMgr->HasStatWeight(proto->ItemId)) +// if (sRandomItemMgr.HasStatWeight(proto->ItemId)) // { -// if (!sRandomItemMgr->GetLiveStatWeight(bot, proto->ItemId)) +// if (!sRandomItemMgr.GetLiveStatWeight(bot, proto->ItemId)) // continue; // } @@ -2096,9 +2094,9 @@ inline Item* StoreNewItemInInventorySlot(Player* player, uint32 newItemId, uint3 // //if (!CanEquipArmor(proto)) // // continue; -// if (sRandomItemMgr->HasStatWeight(proto->ItemId)) +// if (sRandomItemMgr.HasStatWeight(proto->ItemId)) // { -// if (!sRandomItemMgr->GetLiveStatWeight(bot, proto->ItemId)) +// if (!sRandomItemMgr.GetLiveStatWeight(bot, proto->ItemId)) // continue; // } @@ -2162,7 +2160,9 @@ void PlayerbotFactory::InitBags(bool destroyOld) { continue; } - Item* newItem = bot->EquipNewItem(dest, newItemId, true); + + bot->EquipNewItem(dest, newItemId, true); + // if (newItem) // { // newItem->AddToWorld(); @@ -2173,10 +2173,10 @@ void PlayerbotFactory::InitBags(bool destroyOld) void PlayerbotFactory::EnchantItem(Item* item) { - if (bot->GetLevel() < sPlayerbotAIConfig->minEnchantingBotLevel) + if (bot->GetLevel() < sPlayerbotAIConfig.minEnchantingBotLevel) return; - if (urand(0, 100) < 100 * sPlayerbotAIConfig->randomGearLoweringChance) + if (urand(0, 100) < 100 * sPlayerbotAIConfig.randomGearLoweringChance) return; ItemTemplate const* proto = item->GetTemplate(); @@ -2279,8 +2279,8 @@ bool PlayerbotFactory::CanEquipUnseenItem(uint8 slot, uint16& dest, uint32 item) void PlayerbotFactory::InitTradeSkills() { - uint16 firstSkill = sRandomPlayerbotMgr->GetValue(bot, "firstSkill"); - uint16 secondSkill = sRandomPlayerbotMgr->GetValue(bot, "secondSkill"); + uint16 firstSkill = sRandomPlayerbotMgr.GetValue(bot, "firstSkill"); + uint16 secondSkill = sRandomPlayerbotMgr.GetValue(bot, "secondSkill"); if (!firstSkill || !secondSkill) { std::vector firstSkills; @@ -2332,8 +2332,8 @@ void PlayerbotFactory::InitTradeSkills() break; } - sRandomPlayerbotMgr->SetValue(bot, "firstSkill", firstSkill); - sRandomPlayerbotMgr->SetValue(bot, "secondSkill", secondSkill); + sRandomPlayerbotMgr.SetValue(bot, "firstSkill", firstSkill); + sRandomPlayerbotMgr.SetValue(bot, "secondSkill", secondSkill); } SetRandomSkill(SKILL_FIRST_AID); @@ -2359,13 +2359,13 @@ void PlayerbotFactory::InitSkills() bot->UpdateSkillsForLevel(); bot->SetSkill(SKILL_RIDING, 0, 0, 0); - if (bot->GetLevel() >= sPlayerbotAIConfig->useGroundMountAtMinLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.useGroundMountAtMinLevel) bot->learnSpell(33388); - if (bot->GetLevel() >= sPlayerbotAIConfig->useFastGroundMountAtMinLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.useFastGroundMountAtMinLevel) bot->learnSpell(33391); - if (bot->GetLevel() >= sPlayerbotAIConfig->useFlyMountAtMinLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.useFlyMountAtMinLevel) bot->learnSpell(34090); - if (bot->GetLevel() >= sPlayerbotAIConfig->useFastFlyMountAtMinLevel) + if (bot->GetLevel() >= sPlayerbotAIConfig.useFastFlyMountAtMinLevel) bot->learnSpell(34091); uint32 skillLevel = bot->GetLevel() < 40 ? 0 : 1; @@ -2680,8 +2680,8 @@ void PlayerbotFactory::InitClassSpells() void PlayerbotFactory::InitSpecialSpells() { - for (std::vector::iterator i = sPlayerbotAIConfig->randomBotSpellIds.begin(); - i != sPlayerbotAIConfig->randomBotSpellIds.end(); ++i) + for (std::vector::iterator i = sPlayerbotAIConfig.randomBotSpellIds.begin(); + i != sPlayerbotAIConfig.randomBotSpellIds.end(); ++i) { uint32 spellId = *i; bot->learnSpell(spellId); @@ -2729,7 +2729,7 @@ void PlayerbotFactory::InitTalents(uint32 specNo) int index = urand(0, spells_row.size() - 1); TalentEntry const* talentInfo = spells_row[index]; int maxRank = 0; - for (int rank = 0; rank < std::min((uint32)MAX_TALENT_RANK, bot->GetFreeTalentPoints()); ++rank) + for (uint32_t rank = 0; rank < std::min((uint32)MAX_TALENT_RANK, bot->GetFreeTalentPoints()); ++rank) { uint32 spellId = talentInfo->RankID[rank]; if (!spellId) @@ -2752,13 +2752,13 @@ void PlayerbotFactory::InitTalents(uint32 specNo) void PlayerbotFactory::InitTalentsByTemplate(uint32 specTab) { - // if (sPlayerbotAIConfig->parsedSpecLinkOrder[bot->getClass()][specNo][80].size() == 0) + // if (sPlayerbotAIConfig.parsedSpecLinkOrder[bot->getClass()][specNo][80].size() == 0) // { // return; // } uint32 cls = bot->getClass(); int startLevel = bot->GetLevel(); - uint32 specIndex = sPlayerbotAIConfig->randomClassSpecIndex[cls][specTab]; + uint32 specIndex = sPlayerbotAIConfig.randomClassSpecIndex[cls][specTab]; uint32 classMask = bot->getClassMask(); std::unordered_map> spells_row; for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) @@ -2777,23 +2777,23 @@ void PlayerbotFactory::InitTalentsByTemplate(uint32 specTab) spells_row[talentInfo->Row].push_back(talentInfo); } while (startLevel > 1 && startLevel < 80 && - sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specIndex][startLevel].size() == 0) + sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specIndex][startLevel].size() == 0) { startLevel--; } for (int level = startLevel; level <= 80; level++) { - if (sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specIndex][level].size() == 0) + if (sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specIndex][level].size() == 0) { continue; } - for (std::vector& p : sPlayerbotAIConfig->parsedSpecLinkOrder[cls][specIndex][level]) + for (std::vector& p : sPlayerbotAIConfig.parsedSpecLinkOrder[cls][specIndex][level]) { uint32 tab = p[0], row = p[1], col = p[2], lvl = p[3]; - if (sPlayerbotAIConfig->limitTalentsExpansion && bot->GetLevel() <= 60 && (row > 6 || (row == 6 && col != 1))) + if (sPlayerbotAIConfig.limitTalentsExpansion && bot->GetLevel() <= 60 && (row > 6 || (row == 6 && col != 1))) continue; - if (sPlayerbotAIConfig->limitTalentsExpansion && bot->GetLevel() <= 70 && (row > 8 || (row == 8 && col != 1))) + if (sPlayerbotAIConfig.limitTalentsExpansion && bot->GetLevel() <= 70 && (row > 8 || (row == 8 && col != 1))) continue; uint32 talentID = 0; @@ -2848,8 +2848,8 @@ void PlayerbotFactory::InitTalentsByTemplate(uint32 specTab) ObjectGuid PlayerbotFactory::GetRandomBot() { GuidVector guids; - for (std::vector::iterator i = sPlayerbotAIConfig->randomBotAccounts.begin(); - i != sPlayerbotAIConfig->randomBotAccounts.end(); i++) + for (std::vector::iterator i = sPlayerbotAIConfig.randomBotAccounts.begin(); + i != sPlayerbotAIConfig.randomBotAccounts.end(); i++) { uint32 accountId = *i; if (!AccountMgr::GetCharactersCount(accountId)) @@ -2891,7 +2891,6 @@ void PlayerbotFactory::AddPrevQuests(uint32 questId, std::list& questIds void PlayerbotFactory::InitQuests(std::list& questMap, bool withRewardItem) { - uint32 count = 0; for (std::list::iterator i = questMap.begin(); i != questMap.end(); ++i) { uint32 questId = *i; @@ -2981,7 +2980,7 @@ void PlayerbotFactory::InitAmmo() if (!subClass) return; - std::vector ammoEntryList = sRandomItemMgr->GetAmmo(level, subClass); + std::vector ammoEntryList = sRandomItemMgr.GetAmmo(level, subClass); uint32 entry = 0; for (uint32 tEntry : ammoEntryList) { @@ -2990,10 +2989,10 @@ void PlayerbotFactory::InitAmmo() continue; // disable next expansion ammo - if (sPlayerbotAIConfig->limitGearExpansion && bot->GetLevel() <= 60 && tEntry >= 23728) + if (sPlayerbotAIConfig.limitGearExpansion && bot->GetLevel() <= 60 && tEntry >= 23728) continue; - if (sPlayerbotAIConfig->limitGearExpansion && bot->GetLevel() <= 70 && tEntry >= 35570) + if (sPlayerbotAIConfig.limitGearExpansion && bot->GetLevel() <= 70 && tEntry >= 35570) continue; entry = tEntry; @@ -3023,10 +3022,10 @@ uint32 PlayerbotFactory::CalcMixedGearScore(uint32 gs, uint32 quality) void PlayerbotFactory::InitMounts() { - uint32 firstmount = sPlayerbotAIConfig->useGroundMountAtMinLevel; - uint32 secondmount = sPlayerbotAIConfig->useFastGroundMountAtMinLevel; - uint32 thirdmount = sPlayerbotAIConfig->useFlyMountAtMinLevel; - uint32 fourthmount = sPlayerbotAIConfig->useFastFlyMountAtMinLevel; + uint32 firstmount = sPlayerbotAIConfig.useGroundMountAtMinLevel; + uint32 secondmount = sPlayerbotAIConfig.useFastGroundMountAtMinLevel; + uint32 thirdmount = sPlayerbotAIConfig.useFlyMountAtMinLevel; + uint32 fourthmount = sPlayerbotAIConfig.useFastFlyMountAtMinLevel; if (bot->GetLevel() < firstmount) return; @@ -3165,7 +3164,7 @@ void PlayerbotFactory::InitPotions() if (!visitor.GetResult().empty()) continue; - uint32 itemId = sRandomItemMgr->GetRandomPotion(level, effect); + uint32 itemId = sRandomItemMgr.GetRandomPotion(level, effect); if (!itemId) { // LOG_INFO("playerbots", "No potions (type {}) available for bot {} ({} level)", effect, @@ -3263,7 +3262,7 @@ void PlayerbotFactory::InitFood() } uint32 categories[] = {11, 59}; - for (int i = 0; i < sizeof(categories) / sizeof(uint32); ++i) + for (uint64_t i = 0; i < sizeof(categories) / sizeof(uint32); ++i) { uint32 category = categories[i]; std::vector& ids = items[category]; @@ -3296,7 +3295,6 @@ void PlayerbotFactory::InitFood() void PlayerbotFactory::InitReagents() { - int specTab = AiFactory::GetPlayerSpecTab(bot); std::vector> items; switch (bot->getClass()) { @@ -3499,7 +3497,7 @@ void PlayerbotFactory::InitGlyphs(bool increment) } } - if (sPlayerbotAIConfig->limitTalentsExpansion && bot->GetLevel() <= 70) + if (sPlayerbotAIConfig.limitTalentsExpansion && bot->GetLevel() <= 70) { bot->SendTalentsInfoData(false); return; @@ -3722,10 +3720,10 @@ void PlayerbotFactory::InitGlyphs(bool increment) // GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(slot); // if (!gs) // continue; - if (sPlayerbotAIConfig->parsedSpecGlyph[cls][tab].size() > slotIndex && - sPlayerbotAIConfig->parsedSpecGlyph[cls][tab][slotIndex] != 0) + if (sPlayerbotAIConfig.parsedSpecGlyph[cls][tab].size() > slotIndex && + sPlayerbotAIConfig.parsedSpecGlyph[cls][tab][slotIndex] != 0) { - uint32 itemId = sPlayerbotAIConfig->parsedSpecGlyph[cls][tab][slotIndex]; + uint32 itemId = sPlayerbotAIConfig.parsedSpecGlyph[cls][tab][slotIndex]; ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId); if (proto->Class != ITEM_CLASS_GLYPH) continue; @@ -3859,7 +3857,7 @@ Item* PlayerbotFactory::StoreItem(uint32 itemId, uint32 count) void PlayerbotFactory::InitInventoryTrade() { - uint32 itemId = sRandomItemMgr->GetRandomTrade(level); + uint32 itemId = sRandomItemMgr.GetRandomTrade(level); if (!itemId) { LOG_ERROR("playerbots", "No trade items available for bot {} ({} level)", bot->GetName().c_str(), @@ -3895,7 +3893,7 @@ void PlayerbotFactory::InitInventoryEquip() std::vector ids; uint32 desiredQuality = itemQuality; - if (urand(0, 100) < 100 * sPlayerbotAIConfig->randomGearLoweringChance && desiredQuality > ITEM_QUALITY_NORMAL) + if (urand(0, 100) < 100 * sPlayerbotAIConfig.randomGearLoweringChance && desiredQuality > ITEM_QUALITY_NORMAL) { desiredQuality--; } @@ -3949,21 +3947,21 @@ void PlayerbotFactory::InitGuild() return; } - std::string guildName = sPlayerbotGuildMgr->AssignToGuild(bot); + std::string guildName = PlayerbotGuildMgr::instance().AssignToGuild(bot); if (guildName.empty()) return; Guild* guild = sGuildMgr->GetGuildByName(guildName); if (!guild) { - if (!sPlayerbotGuildMgr->CreateGuild(bot, guildName)) + if (!PlayerbotGuildMgr::instance().CreateGuild(bot, guildName)) LOG_ERROR("playerbots","Failed to create guild {} for bot {}", guildName, bot->GetName()); return; } else { if (guild->AddMember(bot->GetGUID(),urand(GR_OFFICER, GR_INITIATE))) - sPlayerbotGuildMgr->OnGuildUpdate(guild); + PlayerbotGuildMgr::instance().OnGuildUpdate(guild); else LOG_ERROR("playerbots","Bot {} failed to join guild {}.", bot->GetName(), guildName); } @@ -3985,7 +3983,7 @@ void PlayerbotFactory::InitImmersive() std::ostringstream name; name << "immersive_stat_" << i; - uint32 value = sRandomPlayerbotMgr->GetValue(owner, name.str()); + uint32 value = sRandomPlayerbotMgr.GetValue(owner, name.str()); if (value) initialized = true; @@ -4058,7 +4056,7 @@ void PlayerbotFactory::InitImmersive() std::ostringstream name; name << "immersive_stat_" << i; - sRandomPlayerbotMgr->SetValue(owner, name.str(), percentMap[type]); + sRandomPlayerbotMgr.SetValue(owner, name.str(), percentMap[type]); } } } @@ -4066,15 +4064,15 @@ void PlayerbotFactory::InitImmersive() void PlayerbotFactory::InitArenaTeam() { - if (!sPlayerbotAIConfig->IsInRandomAccountList(bot->GetSession()->GetAccountId())) + if (!sPlayerbotAIConfig.IsInRandomAccountList(bot->GetSession()->GetAccountId())) return; // Currently the teams are only remade after a server restart and if deleteRandomBotArenaTeams = 1 // This is because randomBotArenaTeams is only empty on server restart. // A manual reinitalization (.playerbots rndbot init) is also required after the teams have been deleted. - if (sPlayerbotAIConfig->randomBotArenaTeams.empty()) + if (sPlayerbotAIConfig.randomBotArenaTeams.empty()) { - if (sPlayerbotAIConfig->deleteRandomBotArenaTeams) + if (sPlayerbotAIConfig.deleteRandomBotArenaTeams) { LOG_INFO("playerbots", "Deleting random bot arena teams..."); @@ -4099,14 +4097,14 @@ void PlayerbotFactory::InitArenaTeam() LOG_INFO("playerbots", "Random bot arena teams deleted"); } - RandomPlayerbotFactory::CreateRandomArenaTeams(ARENA_TYPE_2v2, sPlayerbotAIConfig->randomBotArenaTeam2v2Count); - RandomPlayerbotFactory::CreateRandomArenaTeams(ARENA_TYPE_3v3, sPlayerbotAIConfig->randomBotArenaTeam3v3Count); - RandomPlayerbotFactory::CreateRandomArenaTeams(ARENA_TYPE_5v5, sPlayerbotAIConfig->randomBotArenaTeam5v5Count); + RandomPlayerbotFactory::CreateRandomArenaTeams(ARENA_TYPE_2v2, sPlayerbotAIConfig.randomBotArenaTeam2v2Count); + RandomPlayerbotFactory::CreateRandomArenaTeams(ARENA_TYPE_3v3, sPlayerbotAIConfig.randomBotArenaTeam3v3Count); + RandomPlayerbotFactory::CreateRandomArenaTeams(ARENA_TYPE_5v5, sPlayerbotAIConfig.randomBotArenaTeam5v5Count); } std::vector arenateams; - for (std::vector::iterator i = sPlayerbotAIConfig->randomBotArenaTeams.begin(); - i != sPlayerbotAIConfig->randomBotArenaTeams.end(); ++i) + for (std::vector::iterator i = sPlayerbotAIConfig.randomBotArenaTeams.begin(); + i != sPlayerbotAIConfig.randomBotArenaTeams.end(); ++i) arenateams.push_back(*i); if (arenateams.empty()) @@ -4282,13 +4280,13 @@ void PlayerbotFactory::ApplyEnchantTemplate(uint8 spec) // const SpellItemEnchantmentEntry* a = sSpellItemEnchantmentStore.LookupEntry(1); } -void PlayerbotFactory::ApplyEnchantAndGemsNew(bool destroyOld) +void PlayerbotFactory::ApplyEnchantAndGemsNew(bool) { //int32 bestGemEnchantId[4] = {-1, -1, -1, -1}; // 1, 2, 4, 8 color //not used, line marked for removal. //float bestGemScore[4] = {0, 0, 0, 0}; //not used, line marked for removal. std::vector curCount = GetCurrentGemsCount(); uint8 jewelersCount = 0; - int requiredActive = 2; + const uint8_t requiredActive = 2; std::vector availableGems; for (const uint32& enchantGem : enchantGemIdCache) { @@ -4300,7 +4298,7 @@ void PlayerbotFactory::ApplyEnchantAndGemsNew(bool destroyOld) if (!gemProperties) continue; - if (sPlayerbotAIConfig->limitEnchantExpansion && bot->GetLevel() <= 70 && enchantGem >= 39900) + if (sPlayerbotAIConfig.limitEnchantExpansion && bot->GetLevel() <= 70 && enchantGem >= 39900) continue; uint32 requiredLevel = gemTemplate->ItemLevel; @@ -4363,10 +4361,10 @@ void PlayerbotFactory::ApplyEnchantAndGemsNew(bool destroyOld) } // disable next expansion enchantments - if (sPlayerbotAIConfig->limitEnchantExpansion && bot->GetLevel() <= 60 && enchantSpell >= 27899) + if (sPlayerbotAIConfig.limitEnchantExpansion && bot->GetLevel() <= 60 && enchantSpell >= 27899) continue; - if (sPlayerbotAIConfig->limitEnchantExpansion && bot->GetLevel() <= 70 && enchantSpell >= 44483) + if (sPlayerbotAIConfig.limitEnchantExpansion && bot->GetLevel() <= 70 && enchantSpell >= 44483) continue; for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) @@ -4419,7 +4417,6 @@ void PlayerbotFactory::ApplyEnchantAndGemsNew(bool destroyOld) continue; } int32 enchantIdChosen = -1; - int32 colorChosen; bool jewelersGemChosen; float bestGemScore = -1; for (uint32& enchantGem : availableGems) @@ -4450,7 +4447,7 @@ void PlayerbotFactory::ApplyEnchantAndGemsNew(bool destroyOld) if (curCount[0] != 0) { // Ensure meta gem activation - for (int i = 1; i < curCount.size(); i++) + for (size_t i = 1; i < curCount.size(); i++) { if (curCount[i] < requiredActive && (gemProperties->color & (1 << i))) { @@ -4464,7 +4461,6 @@ void PlayerbotFactory::ApplyEnchantAndGemsNew(bool destroyOld) if (score > bestGemScore) { enchantIdChosen = enchant_id; - colorChosen = gemProperties->color; bestGemScore = score; jewelersGemChosen = isJewelersGem; } diff --git a/src/Bot/Factory/RandomPlayerbotFactory.cpp b/src/Bot/Factory/RandomPlayerbotFactory.cpp index 5a4672f5eb..997182012f 100644 --- a/src/Bot/Factory/RandomPlayerbotFactory.cpp +++ b/src/Bot/Factory/RandomPlayerbotFactory.cpp @@ -8,17 +8,12 @@ #include "AccountMgr.h" #include "ArenaTeamMgr.h" #include "DatabaseEnv.h" -#include "GuildMgr.h" -#include "PlayerbotFactory.h" -#include "Playerbots.h" -#include "PlayerbotGuildMgr.h" +#include "PlayerbotAI.h" #include "ScriptMgr.h" #include "SharedDefines.h" #include "SocialMgr.h" #include "Timer.h" -#include "Guild.h" // EmblemInfo::SaveToDB #include "Log.h" -#include "GuildMgr.h" constexpr RandomPlayerbotFactory::NameRaceAndGender RandomPlayerbotFactory::CombineRaceAndGender(uint8 race, uint8 gender) @@ -244,7 +239,7 @@ std::string const RandomPlayerbotFactory::CreateRandomBotName(NameRaceAndGender botName += (botName.size() < 2) ? groupFormEnd[gender][rand() % 4] : ""; // Replace Catagory value with random Letter from that Catagory's Letter string for a given bot gender - for (int i = 0; i < botName.size(); i++) + for (size_t i = 0; i < botName.size(); i++) { botName[i] = groupLetter[gender][groupCategory.find(botName[i])] [rand() % groupLetter[gender][groupCategory.find(botName[i])].size()]; @@ -277,7 +272,7 @@ std::string const RandomPlayerbotFactory::CreateRandomBotName(NameRaceAndGender botName.clear(); continue; } - return std::move(botName); + return botName; } // TRUE RANDOM NAME GENERATION @@ -302,11 +297,11 @@ std::string const RandomPlayerbotFactory::CreateRandomBotName(NameRaceAndGender botName.clear(); continue; } - return std::move(botName); + return botName; } LOG_ERROR("playerbots", "Random name generation failed."); botName.clear(); - return std::move(botName); + return botName; } // Calculates the total number of required accounts, either using the specified randomBotAccountCount @@ -317,14 +312,14 @@ uint32 RandomPlayerbotFactory::CalculateTotalAccountCount() { // Reset account types if features are disabled // Reset is done here to precede needed accounts calculations - if (sPlayerbotAIConfig->maxRandomBots == 0 || sPlayerbotAIConfig->addClassAccountPoolSize == 0) + if (sPlayerbotAIConfig.maxRandomBots == 0 || sPlayerbotAIConfig.addClassAccountPoolSize == 0) { - if (sPlayerbotAIConfig->maxRandomBots == 0) + if (sPlayerbotAIConfig.maxRandomBots == 0) { PlayerbotsDatabase.Execute("UPDATE playerbots_account_type SET account_type = 0 WHERE account_type = 1"); LOG_INFO("playerbots", "MaxRandomBots set to 0, any RNDbot accounts (type 1) will be unassigned (type 0)"); } - if (sPlayerbotAIConfig->addClassAccountPoolSize == 0) + if (sPlayerbotAIConfig.addClassAccountPoolSize == 0) { PlayerbotsDatabase.Execute("UPDATE playerbots_account_type SET account_type = 0 WHERE account_type = 2"); LOG_INFO("playerbots", "AddClassAccountPoolSize set to 0, any AddClass accounts (type 2) will be unassigned (type 0)"); @@ -334,8 +329,8 @@ uint32 RandomPlayerbotFactory::CalculateTotalAccountCount() for (int waited = 0; waited < 1000; waited += 50) { QueryResult res = PlayerbotsDatabase.Query("SELECT COUNT(*) FROM playerbots_account_type WHERE account_type IN ({}, {})", - sPlayerbotAIConfig->maxRandomBots == 0 ? 1 : -1, - sPlayerbotAIConfig->addClassAccountPoolSize == 0 ? 2 : -1); + sPlayerbotAIConfig.maxRandomBots == 0 ? 1 : -1, + sPlayerbotAIConfig.addClassAccountPoolSize == 0 ? 2 : -1); if (!res || res->Fetch()[0].Get() == 0) { @@ -347,8 +342,8 @@ uint32 RandomPlayerbotFactory::CalculateTotalAccountCount() } // Checks if randomBotAccountCount is set, otherwise calculate it dynamically. - if (sPlayerbotAIConfig->randomBotAccountCount > 0) - return sPlayerbotAIConfig->randomBotAccountCount; + if (sPlayerbotAIConfig.randomBotAccountCount > 0) + return sPlayerbotAIConfig.randomBotAccountCount; // Check existing account types uint32 existingRndBotAccounts = 0; @@ -374,17 +369,17 @@ uint32 RandomPlayerbotFactory::CalculateTotalAccountCount() int divisor = CalculateAvailableCharsPerAccount(); // Calculate max bots - int maxBots = sPlayerbotAIConfig->maxRandomBots; + int maxBots = sPlayerbotAIConfig.maxRandomBots; // Take periodic online - offline into account - if (sPlayerbotAIConfig->enablePeriodicOnlineOffline) + if (sPlayerbotAIConfig.enablePeriodicOnlineOffline) { - maxBots *= sPlayerbotAIConfig->periodicOnlineOfflineRatio; + maxBots *= sPlayerbotAIConfig.periodicOnlineOfflineRatio; } // Calculate number of accounts needed for RNDbots // Result is rounded up for maxBots not cleanly divisible by the divisor uint32 neededRndBotAccounts = (maxBots + divisor - 1) / divisor; - uint32 neededAddClassAccounts = sPlayerbotAIConfig->addClassAccountPoolSize; + uint32 neededAddClassAccounts = sPlayerbotAIConfig.addClassAccountPoolSize; // Start with existing total uint32 existingTotal = existingRndBotAccounts + existingAddClassAccounts + existingUnassignedAccounts; @@ -425,12 +420,12 @@ uint32 RandomPlayerbotFactory::CalculateTotalAccountCount() uint32 RandomPlayerbotFactory::CalculateAvailableCharsPerAccount() { - bool noDK = sPlayerbotAIConfig->disableDeathKnightLogin || sWorld->getIntConfig(CONFIG_EXPANSION) != EXPANSION_WRATH_OF_THE_LICH_KING; + bool noDK = sPlayerbotAIConfig.disableDeathKnightLogin || sWorld->getIntConfig(CONFIG_EXPANSION) != EXPANSION_WRATH_OF_THE_LICH_KING; uint32 availableChars = noDK ? 9 : 10; - uint32 hordeRatio = sPlayerbotAIConfig->randomBotHordeRatio; - uint32 allianceRatio = sPlayerbotAIConfig->randomBotAllianceRatio; + uint32 hordeRatio = sPlayerbotAIConfig.randomBotHordeRatio; + uint32 allianceRatio = sPlayerbotAIConfig.randomBotAllianceRatio; // horde : alliance = 50 : 50 -> 0% // horde : alliance = 0 : 50 -> 50% @@ -451,7 +446,7 @@ void RandomPlayerbotFactory::CreateRandomBots() { /* multi-thread here is meaningless? since the async db operations */ - if (sPlayerbotAIConfig->deleteRandomBotAccounts) + if (sPlayerbotAIConfig.deleteRandomBotAccounts) { std::vector botAccounts; std::vector botFriends; @@ -462,7 +457,7 @@ void RandomPlayerbotFactory::CreateRandomBots() for (uint32 accountNumber = 0; accountNumber < totalAccountCount; ++accountNumber) { std::ostringstream out; - out << sPlayerbotAIConfig->randomBotAccountPrefix << accountNumber; + out << sPlayerbotAIConfig.randomBotAccountPrefix << accountNumber; std::string const accountName = out.str(); if (uint32 accountId = AccountMgr::GetId(accountName)) @@ -482,7 +477,7 @@ void RandomPlayerbotFactory::CreateRandomBots() // Delete all characters from bot accounts CharacterDatabase.Execute("DELETE FROM characters WHERE account IN (SELECT id FROM " + loginDBName + ".account WHERE username LIKE '{}%%')", - sPlayerbotAIConfig->randomBotAccountPrefix.c_str()); + sPlayerbotAIConfig.randomBotAccountPrefix.c_str()); // Wait for the characters to be deleted before proceeding to dependent deletes while (CharacterDatabase.QueueSize()) @@ -496,7 +491,7 @@ void RandomPlayerbotFactory::CreateRandomBots() // Clean up orphaned entries in playerbots_db_store PlayerbotsDatabase.Execute("DELETE FROM playerbots_db_store WHERE guid NOT IN (SELECT guid FROM " + characterDBName + ".characters WHERE account IN (SELECT id FROM " + loginDBName + ".account WHERE username NOT LIKE '{}%%'))", - sPlayerbotAIConfig->randomBotAccountPrefix.c_str()); + sPlayerbotAIConfig.randomBotAccountPrefix.c_str()); // Clean up orphaned records in character-related tables CharacterDatabase.Execute("DELETE FROM arena_team_member WHERE guid NOT IN (SELECT guid FROM characters)"); @@ -551,7 +546,7 @@ void RandomPlayerbotFactory::CreateRandomBots() // Finally, delete the bot accounts themselves LOG_INFO("playerbots", "Deleting random bot accounts..."); QueryResult results = LoginDatabase.Query("SELECT id FROM account WHERE username LIKE '{}%%'", - sPlayerbotAIConfig->randomBotAccountPrefix.c_str()); + sPlayerbotAIConfig.randomBotAccountPrefix.c_str()); int32 deletion_count = 0; if (results) { @@ -601,7 +596,7 @@ void RandomPlayerbotFactory::CreateRandomBots() for (uint32 accountNumber = 0; accountNumber < totalAccountCount; ++accountNumber) { std::ostringstream out; - out << sPlayerbotAIConfig->randomBotAccountPrefix << accountNumber; + out << sPlayerbotAIConfig.randomBotAccountPrefix << accountNumber; std::string const accountName = out.str(); LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME); @@ -613,7 +608,7 @@ void RandomPlayerbotFactory::CreateRandomBots() } account_creation++; std::string password = ""; - if (sPlayerbotAIConfig->randomBotRandomPassword) + if (sPlayerbotAIConfig.randomBotRandomPassword) { for (int i = 0; i < 10; i++) { @@ -649,7 +644,7 @@ void RandomPlayerbotFactory::CreateRandomBots() for (uint32 accountNumber = 0; accountNumber < totalAccountCount; ++accountNumber) { std::ostringstream out; - out << sPlayerbotAIConfig->randomBotAccountPrefix << accountNumber; + out << sPlayerbotAIConfig.randomBotAccountPrefix << accountNumber; std::string const accountName = out.str(); LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME); @@ -661,7 +656,7 @@ void RandomPlayerbotFactory::CreateRandomBots() Field* fields = result->Fetch(); uint32 accountId = fields[0].Get(); - sPlayerbotAIConfig->randomBotAccounts.push_back(accountId); + sPlayerbotAIConfig.randomBotAccounts.push_back(accountId); uint32 count = AccountMgr::GetCharactersCount(accountId); if (count >= 10) @@ -746,13 +741,13 @@ void RandomPlayerbotFactory::CreateRandomBots() for (WorldSession* session : sessionBots) delete session; - for (uint32 accountId : sPlayerbotAIConfig->randomBotAccounts) + for (uint32 accountId : sPlayerbotAIConfig.randomBotAccounts) { totalRandomBotChars += AccountMgr::GetCharactersCount(accountId); } LOG_INFO("server.loading", ">> {} random bot accounts with {} characters available", - sPlayerbotAIConfig->randomBotAccounts.size(), totalRandomBotChars); + sPlayerbotAIConfig.randomBotAccounts.size(), totalRandomBotChars); } std::string const RandomPlayerbotFactory::CreateRandomGuildName() @@ -763,7 +758,7 @@ std::string const RandomPlayerbotFactory::CreateRandomGuildName() if (!result) { LOG_ERROR("playerbots", "No more names left for random guilds"); - return std::move(guildName); + return guildName; } Field* fields = result->Fetch(); @@ -777,13 +772,13 @@ std::string const RandomPlayerbotFactory::CreateRandomGuildName() if (!result) { LOG_ERROR("playerbots", "No more names left for random guilds"); - return std::move(guildName); + return guildName; } fields = result->Fetch(); guildName = fields[0].Get(); - return std::move(guildName); + return guildName; } void RandomPlayerbotFactory::CreateRandomArenaTeams(ArenaType type, uint32 count) @@ -811,7 +806,7 @@ void RandomPlayerbotFactory::CreateRandomArenaTeams(ArenaType type, uint32 count if (arenateam) { ++arenaTeamNumber; - sPlayerbotAIConfig->randomBotArenaTeams.push_back(arenateam->GetId()); + sPlayerbotAIConfig.randomBotArenaTeams.push_back(arenateam->GetId()); } else { @@ -872,7 +867,7 @@ void RandomPlayerbotFactory::CreateRandomArenaTeams(ArenaType type, uint32 count // set random rating arenateam->SetRatingForAll( - urand(sPlayerbotAIConfig->randomBotArenaTeamMinRating, sPlayerbotAIConfig->randomBotArenaTeamMaxRating)); + urand(sPlayerbotAIConfig.randomBotArenaTeamMinRating, sPlayerbotAIConfig.randomBotArenaTeamMaxRating)); // set random emblem uint32 backgroundColor = urand(0xFF000000, 0xFFFFFFFF); @@ -891,7 +886,7 @@ void RandomPlayerbotFactory::CreateRandomArenaTeams(ArenaType type, uint32 count arenateam->SaveToDB(); sArenaTeamMgr->AddArenaTeam(arenateam); - sPlayerbotAIConfig->randomBotArenaTeams.push_back(arenateam->GetId()); + sPlayerbotAIConfig.randomBotArenaTeams.push_back(arenateam->GetId()); } LOG_DEBUG("playerbots", "{} random bot {}vs{} arena teams available", arenaTeamNumber, type, type); @@ -905,7 +900,7 @@ std::string const RandomPlayerbotFactory::CreateRandomArenaTeamName() if (!result) { LOG_ERROR("playerbots", "No more names left for random arena teams"); - return std::move(arenaTeamName); + return arenaTeamName; } Field* fields = result->Fetch(); @@ -920,11 +915,11 @@ std::string const RandomPlayerbotFactory::CreateRandomArenaTeamName() if (!result) { LOG_ERROR("playerbots", "No more names left for random arena teams"); - return std::move(arenaTeamName); + return arenaTeamName; } fields = result->Fetch(); arenaTeamName = fields[0].Get(); - return std::move(arenaTeamName); + return arenaTeamName; } diff --git a/src/Bot/PlayerbotAI.cpp b/src/Bot/PlayerbotAI.cpp index 39db7c5948..5bd1c2f371 100644 --- a/src/Bot/PlayerbotAI.cpp +++ b/src/Bot/PlayerbotAI.cpp @@ -16,7 +16,6 @@ #include "CharacterPackets.h" #include "ChatHelper.h" #include "Common.h" -#include "CreatureAIImpl.h" #include "CreatureData.h" #include "EmoteAction.h" #include "Engine.h" @@ -25,7 +24,6 @@ #include "GameObjectData.h" #include "GameTime.h" #include "GuildMgr.h" -#include "GuildTaskMgr.h" #include "LFGMgr.h" #include "LastMovementValue.h" #include "LastSpellCastValue.h" @@ -33,7 +31,6 @@ #include "LootObjectStack.h" #include "MapMgr.h" #include "MotionMaster.h" -#include "MoveSpline.h" #include "MoveSplineInit.h" #include "NewRpgStrategy.h" #include "ObjectGuid.h" @@ -41,11 +38,9 @@ #include "PerfMonitor.h" #include "Player.h" #include "PlayerbotAIConfig.h" -#include "PlayerbotRepository.h" #include "PlayerbotMgr.h" #include "PlayerbotGuildMgr.h" #include "Playerbots.h" -#include "PointMovementGenerator.h" #include "PositionValue.h" #include "RandomPlayerbotMgr.h" #include "SayAction.h" @@ -59,6 +54,7 @@ #include "Unit.h" #include "UpdateTime.h" #include "Vehicle.h" +#include "GlobalPlayerInspector.h" const int SPELL_TITAN_GRIP = 49152; @@ -153,7 +149,7 @@ PlayerbotAI::PlayerbotAI(Player* bot) engines[BOT_STATE_COMBAT] = AiFactory::createCombatEngine(bot, this, aiObjectContext); engines[BOT_STATE_NON_COMBAT] = AiFactory::createNonCombatEngine(bot, this, aiObjectContext); engines[BOT_STATE_DEAD] = AiFactory::createDeadEngine(bot, this, aiObjectContext); - if (sPlayerbotAIConfig->applyInstanceStrategies) + if (sPlayerbotAIConfig.applyInstanceStrategies) ApplyInstanceStrategies(bot->GetMapId()); currentEngine = engines[BOT_STATE_NON_COMBAT]; currentState = BOT_STATE_NON_COMBAT; @@ -233,7 +229,7 @@ PlayerbotAI::~PlayerbotAI() delete aiObjectContext; if (bot) - sPlayerbotsMgr->RemovePlayerBotData(bot->GetGUID(), true); + PlayerbotsMgr::instance().RemovePlayerBotData(bot->GetGUID(), true); } void PlayerbotAI::UpdateAI(uint32 elapsed, bool minimal) @@ -251,7 +247,7 @@ void PlayerbotAI::UpdateAI(uint32 elapsed, bool minimal) // Handle cheat options (set bot health and power if cheats are enabled) if (bot->IsAlive() && - (static_cast(GetCheat()) > 0 || static_cast(sPlayerbotAIConfig->botCheatMask) > 0)) + (static_cast(GetCheat()) > 0 || static_cast(sPlayerbotAIConfig.botCheatMask) > 0)) { if (HasCheat(BotCheatMask::health)) bot->SetFullHealth(); @@ -332,7 +328,7 @@ void PlayerbotAI::UpdateAI(uint32 elapsed, bool minimal) if (spellTarget && !bot->HasInArc(CAST_ANGLE_IN_FRONT, spellTarget) && (spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT)) { - sServerFacade->SetFacingTo(bot, spellTarget); + ServerFacade::instance().SetFacingTo(bot, spellTarget); } // Wait for spell cast @@ -387,7 +383,7 @@ void PlayerbotAI::UpdateAIGroupMaster() Group* group = bot->GetGroup(); - bool IsRandomBot = sRandomPlayerbotMgr->IsRandomBot(bot); + bool IsRandomBot = sRandomPlayerbotMgr.IsRandomBot(bot); // If bot is not in group verify that for is RandomBot before clearing master and resetting. if (!group) @@ -451,7 +447,7 @@ void PlayerbotAI::UpdateAIInternal([[maybe_unused]] uint32 elapsed, bool minimal std::string const mapString = WorldPosition(bot).isOverworld() ? std::to_string(bot->GetMapId()) : "I"; PerfMonitorOperation* pmo = - sPerfMonitor->start(PERF_MON_TOTAL, "PlayerbotAI::UpdateAIInternal " + mapString); + sPerfMonitor.start(PERF_MON_TOTAL, "PlayerbotAI::UpdateAIInternal " + mapString); ExternalEventHelper helper(aiObjectContext); // chat replies @@ -503,12 +499,12 @@ void PlayerbotAI::UpdateAIInternal([[maybe_unused]] uint32 elapsed, bool minimal } else { - sRandomPlayerbotMgr->LogoutPlayerBot(bot->GetGUID()); + sRandomPlayerbotMgr.LogoutPlayerBot(bot->GetGUID()); } return; } - SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); return; } @@ -583,10 +579,10 @@ void PlayerbotAI::HandleCommand(uint32 type, const std::string& text, Player& fr if (type == CHAT_MSG_SYSTEM) return; - if (filtered.find(sPlayerbotAIConfig->commandSeparator) != std::string::npos) + if (filtered.find(sPlayerbotAIConfig.commandSeparator) != std::string::npos) { std::vector commands; - split(commands, filtered, sPlayerbotAIConfig->commandSeparator.c_str()); + split(commands, filtered, sPlayerbotAIConfig.commandSeparator.c_str()); for (std::vector::iterator i = commands.begin(); i != commands.end(); ++i) { HandleCommand(type, *i, fromPlayer); @@ -594,12 +590,12 @@ void PlayerbotAI::HandleCommand(uint32 type, const std::string& text, Player& fr return; } - if (!sPlayerbotAIConfig->commandPrefix.empty()) + if (!sPlayerbotAIConfig.commandPrefix.empty()) { - if (filtered.find(sPlayerbotAIConfig->commandPrefix) != 0) + if (filtered.find(sPlayerbotAIConfig.commandPrefix) != 0) return; - filtered = filtered.substr(sPlayerbotAIConfig->commandPrefix.size()); + filtered = filtered.substr(sPlayerbotAIConfig.commandPrefix.size()); } if (chatMap.empty()) @@ -631,7 +627,7 @@ void PlayerbotAI::HandleCommand(uint32 type, const std::string& text, Player& fr WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_ADDON, response.c_str(), LANG_ADDON, CHAT_TAG_NONE, bot->GetGUID(), bot->GetName()); - sServerFacade->SendPacket(&fromPlayer, &data); + ServerFacade::instance().SendPacket(&fromPlayer, &data); return; } @@ -761,10 +757,10 @@ void PlayerbotAI::HandleTeleportAck() } // apply instance-related strategies after map attach - if (sPlayerbotAIConfig->applyInstanceStrategies) + if (sPlayerbotAIConfig.applyInstanceStrategies) ApplyInstanceStrategies(bot->GetMapId(), true); - if (sPlayerbotAIConfig->restrictHealerDPS) + if (sPlayerbotAIConfig.restrictHealerDPS) EvaluateHealerDpsStrategy(); // reset AI state after teleport @@ -855,7 +851,7 @@ void PlayerbotAI::Reset(bool full) aiObjectContext->GetValue("last taxi")->Get().Set(nullptr); aiObjectContext->GetValue("travel target") ->Get() - ->setTarget(sTravelMgr->nullTravelDestination, sTravelMgr->nullWorldPosition, true); + ->setTarget(TravelMgr::instance().nullTravelDestination, TravelMgr::instance().nullWorldPosition, true); aiObjectContext->GetValue("travel target")->Get()->setStatus(TRAVEL_STATUS_EXPIRED); aiObjectContext->GetValue("travel target")->Get()->setExpireIn(1000); rpgInfo = NewRpgInfo(); @@ -920,10 +916,10 @@ void PlayerbotAI::HandleCommand(uint32 type, std::string const text, Player* fro if (type == CHAT_MSG_SYSTEM) return; - if (text.find(sPlayerbotAIConfig->commandSeparator) != std::string::npos) + if (text.find(sPlayerbotAIConfig.commandSeparator) != std::string::npos) { std::vector commands; - split(commands, text, sPlayerbotAIConfig->commandSeparator.c_str()); + split(commands, text, sPlayerbotAIConfig.commandSeparator.c_str()); for (std::vector::iterator i = commands.begin(); i != commands.end(); ++i) { HandleCommand(type, *i, fromPlayer); @@ -933,12 +929,12 @@ void PlayerbotAI::HandleCommand(uint32 type, std::string const text, Player* fro } std::string filtered = text; - if (!sPlayerbotAIConfig->commandPrefix.empty()) + if (!sPlayerbotAIConfig.commandPrefix.empty()) { - if (filtered.find(sPlayerbotAIConfig->commandPrefix) != 0) + if (filtered.find(sPlayerbotAIConfig.commandPrefix) != 0) return; - filtered = filtered.substr(sPlayerbotAIConfig->commandPrefix.size()); + filtered = filtered.substr(sPlayerbotAIConfig.commandPrefix.size()); } if (chatMap.empty()) @@ -1100,7 +1096,7 @@ void PlayerbotAI::HandleBotOutgoingPacket(WorldPacket const& packet) } case SMSG_MESSAGECHAT: // do not react to self or if not ready to reply { - if (!sPlayerbotAIConfig->randomBotTalk) + if (!sPlayerbotAIConfig.randomBotTalk) return; if (!AllowActivity()) @@ -1156,7 +1152,7 @@ void PlayerbotAI::HandleBotOutgoingPacket(WorldPacket const& packet) bool isFromFreeBot = false; sCharacterCache->GetCharacterNameByGuid(guid1, name); uint32 accountId = sCharacterCache->GetCharacterAccountIdByGuid(guid1); - isFromFreeBot = sPlayerbotAIConfig->IsInRandomAccountList(accountId); + isFromFreeBot = sPlayerbotAIConfig.IsInRandomAccountList(accountId); bool isMentioned = message.find(bot->GetName()) != std::string::npos; // ChatChannelSource chatChannelSource = GetChatChannelSource(bot, msgtype, chanName); @@ -1174,20 +1170,20 @@ void PlayerbotAI::HandleBotOutgoingPacket(WorldPacket const& packet) if (lang == LANG_ADDON) return; - if (message.starts_with(sPlayerbotAIConfig->toxicLinksPrefix) && + if (message.starts_with(sPlayerbotAIConfig.toxicLinksPrefix) && (GetChatHelper()->ExtractAllItemIds(message).size() > 0 || GetChatHelper()->ExtractAllQuestIds(message).size() > 0) && - sPlayerbotAIConfig->toxicLinksRepliesChance) + sPlayerbotAIConfig.toxicLinksRepliesChance) { - if (urand(0, 50) > 0 || urand(1, 100) > sPlayerbotAIConfig->toxicLinksRepliesChance) + if (urand(0, 50) > 0 || urand(1, 100) > sPlayerbotAIConfig.toxicLinksRepliesChance) { return; } } else if ((GetChatHelper()->ExtractAllItemIds(message).count(19019) && - sPlayerbotAIConfig->thunderfuryRepliesChance)) + sPlayerbotAIConfig.thunderfuryRepliesChance)) { - if (urand(0, 60) > 0 || urand(1, 100) > sPlayerbotAIConfig->thunderfuryRepliesChance) + if (urand(0, 60) > 0 || urand(1, 100) > sPlayerbotAIConfig.thunderfuryRepliesChance) { return; } @@ -1197,8 +1193,8 @@ void PlayerbotAI::HandleBotOutgoingPacket(WorldPacket const& packet) if (isFromFreeBot && urand(0, 20)) return; - // if (msgtype == CHAT_MSG_GUILD && (!sPlayerbotAIConfig->guildRepliesRate || urand(1, 100) >= - // sPlayerbotAIConfig->guildRepliesRate)) return; + // if (msgtype == CHAT_MSG_GUILD && (!sPlayerbotAIConfig.guildRepliesRate || urand(1, 100) >= + // sPlayerbotAIConfig.guildRepliesRate)) return; if (!isFromFreeBot) { @@ -1285,7 +1281,7 @@ void PlayerbotAI::HandleBotOutgoingPacket(WorldPacket const& packet) // bot->GetMotionMaster()->MoveKnockbackFrom(fx, fy, horizontalSpeed, verticalSpeed); // // set delay based on actual distance - // float newdis = sqrt(sServerFacade->GetDistance2d(bot, fx, fy)); + // float newdis = sqrt(ServerFacade::instance().GetDistance2d(bot, fx, fy)); // SetNextCheckDelay((uint32)((newdis / dis) * moveTimeHalf * 4 * IN_MILLISECONDS)); // // add moveflags @@ -1347,9 +1343,9 @@ int32 PlayerbotAI::CalculateGlobalCooldown(uint32 spellid) return 0; if (bot->HasSpellCooldown(spellid)) - return sPlayerbotAIConfig->globalCoolDown; + return sPlayerbotAIConfig.globalCoolDown; - return sPlayerbotAIConfig->reactDelay; + return sPlayerbotAIConfig.reactDelay; } void PlayerbotAI::HandleMasterIncomingPacket(WorldPacket const& packet) @@ -1410,7 +1406,7 @@ void PlayerbotAI::DoNextAction(bool min) { if (!bot->IsInWorld() || bot->IsBeingTeleported() || (GetMaster() && GetMaster()->IsBeingTeleported())) { - SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); return; } @@ -1454,7 +1450,16 @@ void PlayerbotAI::DoNextAction(bool min) } } - bool minimal = !AllowActivity(); + bool minimal = !this->AllowActivity(); + + const GlobalPlayerInspector playerInspector(this->bot->GetGUID().GetRawValue()); + + if (!minimal && playerInspector.isDrinking() && playerInspector.shouldBeDrinking(95.0f)) + { + this->SetNextCheckDelay(500); + + return; + } currentEngine->DoNextAction(nullptr, 0, (minimal || min)); @@ -1463,7 +1468,7 @@ void PlayerbotAI::DoNextAction(bool min) if (!bot->isAFK() && !bot->InBattleground() && !HasRealPlayerMaster()) bot->ToggleAFK(); - SetNextCheckDelay(sPlayerbotAIConfig->passiveDelay); + SetNextCheckDelay(sPlayerbotAIConfig.passiveDelay); return; } else if (bot->isAFK()) @@ -1471,7 +1476,8 @@ void PlayerbotAI::DoNextAction(bool min) if (master && master->IsInWorld()) { - float distance = sServerFacade->GetDistance2d(bot, master); + float distance = ServerFacade::instance().GetDistance2d(bot, master); + if (master->m_movementInfo.HasMovementFlag(MOVEMENTFLAG_WALKING) && distance < 20.0f) bot->m_movementInfo.AddMovementFlag(MOVEMENTFLAG_WALKING); else @@ -1704,7 +1710,7 @@ bool PlayerbotAI::PlayEmote(uint32 emote) WorldPacket data(SMSG_TEXT_EMOTE); data << (TextEmotes)emote; data << EmoteAction::GetNumberOfEmoteVariants((TextEmotes)emote, bot->getRace(), bot->getGender()); - data << ((master && (sServerFacade->GetDistance2d(bot, master) < 30.0f) && urand(0, 1)) ? master->GetGUID() + data << ((master && (ServerFacade::instance().GetDistance2d(bot, master) < 30.0f) && urand(0, 1)) ? master->GetGUID() : (bot->GetTarget() && urand(0, 1)) ? bot->GetTarget() : ObjectGuid::Empty); bot->GetSession()->HandleTextEmoteOpcode(data); @@ -1725,7 +1731,7 @@ bool PlayerbotAI::ContainsStrategy(StrategyType type) bool PlayerbotAI::HasStrategy(std::string const name, BotState type) { return engines[type]->HasStrategy(name); } -void PlayerbotAI::ResetStrategies(bool load) +void PlayerbotAI::ResetStrategies(bool) { for (uint8 i = 0; i < BOT_STATE_MAX; i++) engines[i]->removeAllStrategies(); @@ -1733,14 +1739,14 @@ void PlayerbotAI::ResetStrategies(bool load) AiFactory::AddDefaultCombatStrategies(bot, this, engines[BOT_STATE_COMBAT]); AiFactory::AddDefaultNonCombatStrategies(bot, this, engines[BOT_STATE_NON_COMBAT]); AiFactory::AddDefaultDeadStrategies(bot, this, engines[BOT_STATE_DEAD]); - if (sPlayerbotAIConfig->applyInstanceStrategies) + if (sPlayerbotAIConfig.applyInstanceStrategies) ApplyInstanceStrategies(bot->GetMapId()); for (uint8 i = 0; i < BOT_STATE_MAX; i++) engines[i]->Init(); // if (load) - // sPlayerbotRepository->Load(this); + // PlayerbotRepository::instance().Load(this); } bool PlayerbotAI::IsRanged(Player* player, bool bySpec) @@ -2718,7 +2724,7 @@ bool PlayerbotAI::SayToParty(const std::string& msg) for (auto reciever : GetPlayersInGroup()) { - sServerFacade->SendPacket(reciever, &data); + ServerFacade::instance().SendPacket(reciever, &data); } return true; @@ -2735,7 +2741,7 @@ bool PlayerbotAI::SayToRaid(const std::string& msg) for (auto reciever : GetPlayersInGroup()) { - sServerFacade->SendPacket(reciever, &data); + ServerFacade::instance().SendPacket(reciever, &data); } return true; @@ -2802,7 +2808,7 @@ bool PlayerbotAI::TellMasterNoFacing(std::string const text, PlayerbotSecurityLe masterBotAI = GET_PLAYERBOT_AI(master); if ((!master || (masterBotAI && !masterBotAI->IsRealPlayer())) && - (sPlayerbotAIConfig->randomBotSayWithoutMaster || HasStrategy("debug", BOT_STATE_NON_COMBAT))) + (sPlayerbotAIConfig.randomBotSayWithoutMaster || HasStrategy("debug", BOT_STATE_NON_COMBAT))) { bot->Say(text, (bot->GetTeamId() == TEAM_ALLIANCE ? LANG_COMMON : LANG_ORCISH)); return true; @@ -2813,7 +2819,7 @@ bool PlayerbotAI::TellMasterNoFacing(std::string const text, PlayerbotSecurityLe time_t lastSaid = whispers[text]; - if (!lastSaid || (time(nullptr) - lastSaid) >= sPlayerbotAIConfig->repeatDelay / 1000) + if (!lastSaid || (time(nullptr) - lastSaid) >= sPlayerbotAIConfig.repeatDelay / 1000) { whispers[text] = time(nullptr); @@ -2851,10 +2857,10 @@ bool PlayerbotAI::IsTellAllowed(PlayerbotSecurityLevel securityLevel) if (!GetSecurity()->CheckLevelFor(securityLevel, true, master)) return false; - if (sPlayerbotAIConfig->whisperDistance && !bot->GetGroup() && sRandomPlayerbotMgr->IsRandomBot(bot) && + if (sPlayerbotAIConfig.whisperDistance && !bot->GetGroup() && sRandomPlayerbotMgr.IsRandomBot(bot) && master->GetSession()->GetSecurity() < SEC_GAMEMASTER && (bot->GetMapId() != master->GetMapId() || - sServerFacade->GetDistance2d(bot, master) > sPlayerbotAIConfig->whisperDistance)) + ServerFacade::instance().GetDistance2d(bot, master) > sPlayerbotAIConfig.whisperDistance)) return false; return true; @@ -2869,7 +2875,7 @@ bool PlayerbotAI::TellMaster(std::string const text, PlayerbotSecurityLevel secu { if (!master) { - if (sPlayerbotAIConfig->randomBotSayWithoutMaster) + if (sPlayerbotAIConfig.randomBotSayWithoutMaster) return TellMasterNoFacing(text, securityLevel); } if (!TellMasterNoFacing(text, securityLevel)) @@ -2878,7 +2884,7 @@ bool PlayerbotAI::TellMaster(std::string const text, PlayerbotSecurityLevel secu if (!bot->isMoving() && !bot->IsInCombat() && bot->GetMapId() == master->GetMapId() && !bot->HasUnitState(UNIT_STATE_IN_FLIGHT) && !bot->IsFlying()) { - if (!bot->HasInArc(EMOTE_ANGLE_IN_FRONT, master, sPlayerbotAIConfig->sightDistance)) + if (!bot->HasInArc(EMOTE_ANGLE_IN_FRONT, master, sPlayerbotAIConfig.sightDistance)) bot->SetFacingToObject(master); bot->HandleEmoteCommand(EMOTE_ONESHOT_TALK); @@ -3092,7 +3098,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, { if (!spellid) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. No spellid. - spellid: {}, bot name: {}", spellid, bot->GetName()); @@ -3102,7 +3108,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, if (bot->HasUnitState(UNIT_STATE_LOST_CONTROL)) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. Unit state lost control. - spellid: {}, bot name: {}", spellid, bot->GetName()); @@ -3122,7 +3128,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, if (checkHasSpell && !bot->HasSpell(spellid)) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. Bot not has spell. - target name: {}, spellid: {}, bot name: {}", @@ -3133,7 +3139,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, if (bot->GetCurrentSpell(CURRENT_CHANNELED_SPELL) != nullptr) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG( "playerbots", @@ -3145,7 +3151,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, if (bot->HasSpellCooldown(spellid)) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. Spell not has cooldown. - target name: {}, spellid: {}, bot name: {}", @@ -3157,7 +3163,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid); if (!spellInfo) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Can cast spell failed. No spellInfo. - target name: {}, spellid: {}, bot name: {}", target->GetName(), spellid, bot->GetName()); @@ -3167,7 +3173,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, if ((bot->GetShapeshiftForm() == FORM_FLIGHT || bot->GetShapeshiftForm() == FORM_FLIGHT_EPIC) && !bot->IsInCombat()) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG( "playerbots", @@ -3181,7 +3187,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, // bool interruptOnMove = spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT; if ((CastingTime || spellInfo->IsAutoRepeatRangedSpell()) && bot->isMoving()) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "Casting time and bot is moving - target name: {}, spellid: {}, bot name: {}", target->GetName(), spellid, bot->GetName()); @@ -3196,7 +3202,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, { if (spellid != 44572) // Deep Freeze { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "target is immuned to spell - target name: {}, spellid: {}, bot name: {}", target->GetName(), spellid, bot->GetName()); @@ -3206,9 +3212,9 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, // Otherwise, allow Deep Freeze even if immune } - if (bot != target && sServerFacade->GetDistance2d(bot, target) > sPlayerbotAIConfig->sightDistance) + if (bot != target && ServerFacade::instance().GetDistance2d(bot, target) > sPlayerbotAIConfig.sightDistance) { - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "target is out of sight distance - target name: {}, spellid: {}, bot name: {}", target->GetName(), spellid, bot->GetName()); @@ -3234,7 +3240,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, SpellCastResult result = spell->CheckCast(true); delete spell; - // if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + // if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) // { // if (result != SPELL_FAILED_NOT_READY && result != SPELL_CAST_OK) // { @@ -3258,7 +3264,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, Unit* target, bool checkHasSpell, case SPELL_FAILED_OUT_OF_RANGE: return true; default: - if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) { LOG_DEBUG("playerbots", "CanCastSpell Check Failed. - target name: {}, spellid: {}, bot name: {}, result: {}", @@ -3294,7 +3300,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, GameObject* goTarget, bool checkH if (CastingTime > 0 && bot->isMoving()) return false; - if (sServerFacade->GetDistance2d(bot, goTarget) > sPlayerbotAIConfig->sightDistance) + if (ServerFacade::instance().GetDistance2d(bot, goTarget) > sPlayerbotAIConfig.sightDistance) return false; // ObjectGuid oldSel = bot->GetTarget(); @@ -3347,7 +3353,7 @@ bool PlayerbotAI::CanCastSpell(uint32 spellid, float x, float y, float z, bool c if (!itemTarget) { - if (bot->GetDistance(x, y, z) > sPlayerbotAIConfig->sightDistance) + if (bot->GetDistance(x, y, z) > sPlayerbotAIConfig.sightDistance) return false; } @@ -3449,7 +3455,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) if (bot->IsFlying() || bot->HasUnitState(UNIT_STATE_IN_FLIGHT)) { - // if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + // if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) // { // LOG_DEBUG("playerbots", "Spell cast is flying - target name: {}, spellid: {}, bot name: {}}", // target->GetName(), spellId, bot->GetName()); @@ -3472,13 +3478,13 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) WorldObject* faceTo = target; if (!bot->HasInArc(CAST_ANGLE_IN_FRONT, faceTo) && (spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT)) { - sServerFacade->SetFacingTo(bot, faceTo); + ServerFacade::instance().SetFacingTo(bot, faceTo); // failWithDelay = true; } if (failWithDelay) { - SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); return false; } @@ -3495,7 +3501,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) { bot->GetTradeData()->SetSpell(spellId); delete spell; - // if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + // if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) // { // LOG_DEBUG("playerbots", "Spell cast no item - target name: {}, spellid: {}, bot name: {}", // target->GetName(), spellId, bot->GetName()); @@ -3557,7 +3563,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) if (bot->isMoving() && spell->GetCastTime()) { // bot->StopMoving(); - SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); spell->cancel(); delete spell; return false; @@ -3565,7 +3571,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) // spell->m_targets.SetUnitTarget(target); // SpellCastResult spellSuccess = spell->CheckCast(true); - // if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + // if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) // { // LOG_DEBUG("playerbots", "Spell cast result - target name: {}, spellid: {}, bot name: {}, result: {}", // target->GetName(), spellId, bot->GetName(), spellSuccess); @@ -3577,7 +3583,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) if (result != SPELL_CAST_OK) { - // if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + // if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) // { // LOG_DEBUG("playerbots", "Spell cast failed. - target name: {}, spellid: {}, bot name: {}, result: {}", // target->GetName(), spellId, bot->GetName(), result); @@ -3645,7 +3651,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, Unit* target, Item* itemTarget) // { // spell->cancel(); // delete spell; - // if (!sPlayerbotAIConfig->logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) + // if (!sPlayerbotAIConfig.logInGroupOnly || (bot->GetGroup() && HasRealPlayerMaster())) // { // LOG_DEBUG("playerbots", "Spell cast loot - target name: {}, spellid: {}, bot name: {}", // target->GetName(), spellId, bot->GetName()); @@ -3725,7 +3731,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, float x, float y, float z, Item* ite if (failWithDelay) { - SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); return false; } @@ -3768,7 +3774,7 @@ bool PlayerbotAI::CastSpell(uint32 spellId, float x, float y, float z, Item* ite if (bot->isMoving() && spell->GetCastTime()) { // bot->StopMoving(); - SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); spell->cancel(); delete spell; return false; @@ -3846,12 +3852,12 @@ bool PlayerbotAI::CanCastVehicleSpell(uint32 spellId, Unit* target) if (CastingTime && vehicleBase->isMoving()) return false; - if (vehicleBase != spellTarget && sServerFacade->GetDistance2d(vehicleBase, spellTarget) > 120.0f) + if (vehicleBase != spellTarget && ServerFacade::instance().GetDistance2d(vehicleBase, spellTarget) > 120.0f) return false; if (!target && siegePos.isSet()) { - if (sServerFacade->GetDistance2d(vehicleBase, siegePos.x, siegePos.y) > 120.0f) + if (ServerFacade::instance().GetDistance2d(vehicleBase, siegePos.x, siegePos.y) > 120.0f) return false; } @@ -3921,7 +3927,7 @@ bool PlayerbotAI::CastVehicleSpell(uint32 spellId, Unit* target) PositionInfo siegePos = GetAiObjectContext()->GetValue("position")->Get()["bg siege"]; if (!target && siegePos.isSet()) { - if (sServerFacade->GetDistance2d(vehicleBase, siegePos.x, siegePos.y) > 120.0f) + if (ServerFacade::instance().GetDistance2d(vehicleBase, siegePos.x, siegePos.y) > 120.0f) return false; } @@ -3959,7 +3965,7 @@ bool PlayerbotAI::CastVehicleSpell(uint32 spellId, Unit* target) if (failWithDelay) { - SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); return false; } @@ -4000,7 +4006,7 @@ bool PlayerbotAI::CastVehicleSpell(uint32 spellId, Unit* target) if (seat->CanControl() && vehicleBase->isMoving() && spell->GetCastTime()) { vehicleBase->StopMoving(); - SetNextCheckDelay(sPlayerbotAIConfig->globalCoolDown); + SetNextCheckDelay(sPlayerbotAIConfig.globalCoolDown); spell->cancel(); // delete spell; return false; @@ -4077,7 +4083,7 @@ void PlayerbotAI::WaitForSpellCast(Spell* spell) castTime += duration; } - SetNextCheckDelay(castTime + sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(castTime + sPlayerbotAIConfig.reactDelay); } void PlayerbotAI::InterruptSpell() @@ -4169,8 +4175,8 @@ bool PlayerbotAI::HasAuraToDispel(Unit* target, uint32 dispelType) if (!aura || aura->IsPassive() || aura->IsRemoved()) continue; - if (sPlayerbotAIConfig->dispelAuraDuration && aura->GetDuration() && - aura->GetDuration() < (int32)sPlayerbotAIConfig->dispelAuraDuration) + if (sPlayerbotAIConfig.dispelAuraDuration && aura->GetDuration() && + aura->GetDuration() < (int32)sPlayerbotAIConfig.dispelAuraDuration) continue; SpellInfo const* spellInfo = aura->GetSpellInfo(); @@ -4290,7 +4296,7 @@ bool PlayerbotAI::HasRealPlayerMaster() bool PlayerbotAI::HasActivePlayerMaster() { return master && !GET_PLAYERBOT_AI(master); } -bool PlayerbotAI::IsAlt() { return HasRealPlayerMaster() && !sRandomPlayerbotMgr->IsRandomBot(bot); } +bool PlayerbotAI::IsAlt() { return HasRealPlayerMaster() && !sRandomPlayerbotMgr.IsRandomBot(bot); } Player* PlayerbotAI::GetGroupLeader() { @@ -4379,7 +4385,7 @@ bool PlayerbotAI::HasPlayerNearby(WorldPosition* pos, float range) { float sqRange = range * range; bool nearPlayer = false; - for (auto& player : sRandomPlayerbotMgr->GetPlayers()) + for (auto& player : sRandomPlayerbotMgr.GetPlayers()) { if (!player->IsGameMaster() || player->isGMVisible()) { @@ -4413,9 +4419,9 @@ bool PlayerbotAI::HasManyPlayersNearby(uint32 trigerrValue, float range) float sqRange = range * range; uint32 found = 0; - for (auto& player : sRandomPlayerbotMgr->GetPlayers()) + for (auto& player : sRandomPlayerbotMgr.GetPlayers()) { - if ((!player->IsGameMaster() || player->isGMVisible()) && sServerFacade->GetDistance2d(player, bot) < sqRange) + if ((!player->IsGameMaster() || player->isGMVisible()) && ServerFacade::instance().GetDistance2d(player, bot) < sqRange) { found++; @@ -4461,7 +4467,7 @@ inline bool ZoneHasRealPlayers(Player* bot) return false; } - for (Player* player : sRandomPlayerbotMgr->GetPlayers()) + for (Player* player : sRandomPlayerbotMgr.GetPlayers()) { if (player->GetMapId() != bot->GetMapId()) continue; @@ -4492,7 +4498,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) return false; // when botActiveAlone is 100% and smartScale disabled - if (sPlayerbotAIConfig->botActiveAlone >= 100 && !sPlayerbotAIConfig->botActiveAloneSmartScale) + if (sPlayerbotAIConfig.botActiveAlone >= 100 && !sPlayerbotAIConfig.botActiveAloneSmartScale) { return true; } @@ -4510,7 +4516,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) // which prevents unneeded expensive GameTime calls. if (_isBotInitializing) { - _isBotInitializing = GameTime::GetUptime().count() < sPlayerbotAIConfig->maxRandomBots * 0.11; + _isBotInitializing = GameTime::GetUptime().count() < sPlayerbotAIConfig.maxRandomBots * 0.11; // no activity allowed during bot initialization if (_isBotInitializing) @@ -4532,7 +4538,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) } // bot map has active players. - if (sPlayerbotAIConfig->BotActiveAloneForceWhenInMap) + if (sPlayerbotAIConfig.BotActiveAloneForceWhenInMap) { if (HasRealPlayers(bot->GetMap())) { @@ -4541,7 +4547,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) } // bot zone has active players. - if (sPlayerbotAIConfig->BotActiveAloneForceWhenInZone) + if (sPlayerbotAIConfig.BotActiveAloneForceWhenInZone) { if (ZoneHasRealPlayers(bot)) { @@ -4550,7 +4556,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) } // when in real guild - if (sPlayerbotAIConfig->BotActiveAloneForceWhenInGuild) + if (sPlayerbotAIConfig.BotActiveAloneForceWhenInGuild) { if (IsInRealGuild()) { @@ -4559,7 +4565,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) } // Player is near. Always active. - if (HasPlayerNearby(sPlayerbotAIConfig->BotActiveAloneForceWhenInRadius)) + if (HasPlayerNearby(sPlayerbotAIConfig.BotActiveAloneForceWhenInRadius)) { return true; } @@ -4631,13 +4637,13 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) } // HasFriend - if (sPlayerbotAIConfig->BotActiveAloneForceWhenIsFriend) + if (sPlayerbotAIConfig.BotActiveAloneForceWhenIsFriend) { // shouldnt be needed analyse in future if (!bot->GetGUID()) return false; - for (auto& player : sRandomPlayerbotMgr->GetPlayers()) + for (auto& player : sRandomPlayerbotMgr.GetPlayers()) { if (!player || !player->GetSession() || !player->IsInWorld() || player->IsDuringRemoveFromWorld() || player->GetSession()->isLogingOut()) @@ -4669,7 +4675,7 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) return false; } - if (sPlayerbotAIConfig->botActiveAlone <= 0) + if (sPlayerbotAIConfig.botActiveAlone <= 0) { return false; } @@ -4681,19 +4687,19 @@ bool PlayerbotAI::AllowActive(ActivityType activityType) // Below is code to have a specified % of bots active at all times. // The default is 100%. With 1% of all bots going active or inactive each minute. - uint32 mod = sPlayerbotAIConfig->botActiveAlone > 100 ? 100 : sPlayerbotAIConfig->botActiveAlone; - if (sPlayerbotAIConfig->botActiveAloneSmartScale && - bot->GetLevel() >= sPlayerbotAIConfig->botActiveAloneSmartScaleWhenMinLevel && - bot->GetLevel() <= sPlayerbotAIConfig->botActiveAloneSmartScaleWhenMaxLevel) + uint32 mod = sPlayerbotAIConfig.botActiveAlone > 100 ? 100 : sPlayerbotAIConfig.botActiveAlone; + if (sPlayerbotAIConfig.botActiveAloneSmartScale && + bot->GetLevel() >= sPlayerbotAIConfig.botActiveAloneSmartScaleWhenMinLevel && + bot->GetLevel() <= sPlayerbotAIConfig.botActiveAloneSmartScaleWhenMaxLevel) { mod = AutoScaleActivity(mod); } uint32 ActivityNumber = - GetFixedBotNumer(100, sPlayerbotAIConfig->botActiveAlone * static_cast(mod) / 100 * 0.01f); + GetFixedBotNumer(100, sPlayerbotAIConfig.botActiveAlone * static_cast(mod) / 100 * 0.01f); return ActivityNumber <= - (sPlayerbotAIConfig->botActiveAlone * mod) / + (sPlayerbotAIConfig.botActiveAlone * mod) / 100; // The given percentage of bots should be active and rotate 1% of those active bots each minute. } @@ -4725,8 +4731,8 @@ uint32 PlayerbotAI::AutoScaleActivity(uint32 mod) { // Current max server update time (ms), and the configured floor/ceiling values for bot scaling uint32 maxDiff = sWorldUpdateTime.GetMaxUpdateTimeOfCurrentTable(); - uint32 diffLimitFloor = sPlayerbotAIConfig->botActiveAloneSmartScaleDiffLimitfloor; - uint32 diffLimitCeiling = sPlayerbotAIConfig->botActiveAloneSmartScaleDiffLimitCeiling; + uint32 diffLimitFloor = sPlayerbotAIConfig.botActiveAloneSmartScaleDiffLimitfloor; + uint32 diffLimitCeiling = sPlayerbotAIConfig.botActiveAloneSmartScaleDiffLimitCeiling; if (diffLimitCeiling <= diffLimitFloor) { @@ -5318,19 +5324,19 @@ float PlayerbotAI::GetRange(std::string const type) return val; if (type == "spell") - return sPlayerbotAIConfig->spellDistance; + return sPlayerbotAIConfig.spellDistance; if (type == "shoot") - return sPlayerbotAIConfig->shootDistance; + return sPlayerbotAIConfig.shootDistance; if (type == "flee") - return sPlayerbotAIConfig->fleeDistance; + return sPlayerbotAIConfig.fleeDistance; if (type == "heal") - return sPlayerbotAIConfig->healDistance; + return sPlayerbotAIConfig.healDistance; if (type == "melee") - return sPlayerbotAIConfig->meleeDistance; + return sPlayerbotAIConfig.meleeDistance; return 0; } @@ -5999,7 +6005,7 @@ bool PlayerbotAI::IsInRealGuild() if (!bot->GetGuildId()) return false; - return sPlayerbotGuildMgr->IsRealGuild(bot->GetGuildId()); + return PlayerbotGuildMgr::instance().IsRealGuild(bot->GetGuildId()); } void PlayerbotAI::QueueChatResponse(const ChatQueuedReply chatReply) { chatReplies.push_back(std::move(chatReply)); } @@ -6553,17 +6559,17 @@ std::set PlayerbotAI::GetCurrentIncompleteQuestIds() uint32 PlayerbotAI::GetReactDelay() { - uint32 base = sPlayerbotAIConfig->reactDelay; // Default 100(ms) + uint32 base = sPlayerbotAIConfig.reactDelay; // Default 100(ms) // If dynamic react delay is disabled, use a static calculation - if (!sPlayerbotAIConfig->dynamicReactDelay) + if (!sPlayerbotAIConfig.dynamicReactDelay) { if (HasRealPlayerMaster()) return base; bool inBG = bot->InBattleground() || bot->InArena(); - if (sPlayerbotAIConfig->fastReactInBG && inBG) + if (sPlayerbotAIConfig.fastReactInBG && inBG) return base; bool inCombat = bot->IsInCombat(); @@ -6588,11 +6594,11 @@ uint32 PlayerbotAI::GetReactDelay() { if (bot->IsInCombat() || currentState == BOT_STATE_COMBAT) { - return static_cast(base * (sPlayerbotAIConfig->fastReactInBG ? 2.5f : 5.0f)); + return static_cast(base * (sPlayerbotAIConfig.fastReactInBG ? 2.5f : 5.0f)); } else { - return static_cast(base * (sPlayerbotAIConfig->fastReactInBG ? 1.0f : 10.0f)); + return static_cast(base * (sPlayerbotAIConfig.fastReactInBG ? 1.0f : 10.0f)); } } @@ -6765,7 +6771,7 @@ void PlayerbotAI::EvaluateHealerDpsStrategy() if (!IsHeal(bot, true)) return; - if (sPlayerbotAIConfig->IsRestrictedHealerDPSMap(bot->GetMapId())) + if (sPlayerbotAIConfig.IsRestrictedHealerDPSMap(bot->GetMapId())) ChangeStrategy("-healer dps", BOT_STATE_COMBAT); else ChangeStrategy("+healer dps", BOT_STATE_COMBAT); diff --git a/src/Bot/PlayerbotAI.h b/src/Bot/PlayerbotAI.h index b2df4352cc..b7274732b3 100644 --- a/src/Bot/PlayerbotAI.h +++ b/src/Bot/PlayerbotAI.h @@ -6,13 +6,11 @@ #ifndef _PLAYERBOT_PLAYERbotAI_H #define _PLAYERBOT_PLAYERbotAI_H -#include #include #include "Chat.h" #include "ChatFilter.h" #include "ChatHelper.h" -#include "Common.h" #include "CreatureData.h" #include "Event.h" #include "Item.h" @@ -491,7 +489,7 @@ class PlayerbotAI : public PlayerbotAIBase void ImbueItem(Item* item); void EnchantItemT(uint32 spellid, uint8 slot); uint32 GetBuffedCount(Player* player, std::string const spellname); - int32 GetNearGroupMemberCount(float dis = sPlayerbotAIConfig->sightDistance); + int32 GetNearGroupMemberCount(float dis = sPlayerbotAIConfig.sightDistance); virtual bool CanCastSpell(std::string const name, Unit* target, Item* itemTarget = nullptr); virtual bool CastSpell(std::string const name, Unit* target, Item* itemTarget = nullptr); @@ -545,9 +543,9 @@ class PlayerbotAI : public PlayerbotAIBase uint32 GetFixedBotNumer(uint32 maxNum = 100, float cyclePerMin = 1); GrouperType GetGrouperType(); GuilderType GetGuilderType(); - bool HasPlayerNearby(WorldPosition* pos, float range = sPlayerbotAIConfig->reactDistance); - bool HasPlayerNearby(float range = sPlayerbotAIConfig->reactDistance); - bool HasManyPlayersNearby(uint32 trigerrValue = 20, float range = sPlayerbotAIConfig->sightDistance); + bool HasPlayerNearby(WorldPosition* pos, float range = sPlayerbotAIConfig.reactDistance); + bool HasPlayerNearby(float range = sPlayerbotAIConfig.reactDistance); + bool HasManyPlayersNearby(uint32 trigerrValue = 20, float range = sPlayerbotAIConfig.sightDistance); bool AllowActive(ActivityType activityType); bool AllowActivity(ActivityType activityType = ALL_ACTIVITY, bool checkNow = false); uint32 AutoScaleActivity(uint32 mod); @@ -562,7 +560,7 @@ class PlayerbotAI : public PlayerbotAIBase bool HasCheat(BotCheatMask mask) { return ((uint32)mask & (uint32)cheatMask) != 0 || - ((uint32)mask & (uint32)sPlayerbotAIConfig->botCheatMask) != 0; + ((uint32)mask & (uint32)sPlayerbotAIConfig.botCheatMask) != 0; } BotCheatMask GetCheat() { return cheatMask; } void SetCheat(BotCheatMask mask) { cheatMask = mask; } diff --git a/src/Bot/PlayerbotMgr.cpp b/src/Bot/PlayerbotMgr.cpp index e01afb0f7c..7e081a4fc9 100644 --- a/src/Bot/PlayerbotMgr.cpp +++ b/src/Bot/PlayerbotMgr.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -20,11 +19,9 @@ #include "Common.h" #include "Define.h" #include "Group.h" -#include "GroupMgr.h" #include "GuildMgr.h" #include "ObjectAccessor.h" #include "ObjectGuid.h" -#include "ObjectMgr.h" #include "PlayerbotAIConfig.h" #include "PlayerbotRepository.h" #include "PlayerbotFactory.h" @@ -74,7 +71,6 @@ class PlayerbotLoginQueryHolder : public LoginQueryHolder { private: uint32 masterAccountId; - PlayerbotHolder* playerbotHolder; public: PlayerbotLoginQueryHolder(uint32 masterAccount, uint32 accountId, ObjectGuid guid) : LoginQueryHolder(accountId, guid), masterAccountId(masterAccount) @@ -102,11 +98,11 @@ void PlayerbotHolder::AddPlayerBot(ObjectGuid playerGuid, uint32 masterAccountId Player* masterPlayer = masterSession ? masterSession->GetPlayer() : nullptr; bool isRndbot = !masterAccountId; - bool sameAccount = sPlayerbotAIConfig->allowAccountBots && accountId == masterAccountId; + bool sameAccount = sPlayerbotAIConfig.allowAccountBots && accountId == masterAccountId; Guild* guild = masterPlayer ? sGuildMgr->GetGuildById(masterPlayer->GetGuildId()) : nullptr; - bool sameGuild = sPlayerbotAIConfig->allowGuildBots && guild && guild->GetMember(playerGuid); - bool addClassBot = sRandomPlayerbotMgr->IsAddclassBot(playerGuid.GetCounter()); - bool linkedAccount = sPlayerbotAIConfig->allowTrustedAccountBots && IsAccountLinked(accountId, masterAccountId); + bool sameGuild = sPlayerbotAIConfig.allowGuildBots && guild && guild->GetMember(playerGuid); + bool addClassBot = sRandomPlayerbotMgr.IsAddclassBot(playerGuid.GetCounter()); + bool linkedAccount = sPlayerbotAIConfig.allowTrustedAccountBots && IsAccountLinked(accountId, masterAccountId); bool allowed = true; std::ostringstream out; @@ -125,11 +121,11 @@ void PlayerbotHolder::AddPlayerBot(ObjectGuid playerGuid, uint32 masterAccountId LOG_DEBUG("playerbots", "PlayerbotMgr not found for master player with GUID: {}", masterPlayer->GetGUID().GetRawValue()); return; } - uint32 count = mgr->GetPlayerbotsCount() + botLoading.size(); - if (count >= sPlayerbotAIConfig->maxAddedBots) + int64_t count = mgr->GetPlayerbotsCount() + botLoading.size(); + if (count >= PlayerbotAIConfig::instance().maxAddedBots) { allowed = false; - out << "Failure: You have added too many bots (more than " << sPlayerbotAIConfig->maxAddedBots << ")"; + out << "Failure: You have added too many bots (more than " << sPlayerbotAIConfig.maxAddedBots << ")"; } } if (!allowed) @@ -156,7 +152,6 @@ void PlayerbotHolder::AddPlayerBot(ObjectGuid playerGuid, uint32 masterAccountId [](SQLQueryHolderBase const& queryHolder) { PlayerbotLoginQueryHolder const& holder = static_cast(queryHolder); - PlayerbotHolder* mgr = sRandomPlayerbotMgr; // could be null uint32 masterAccountId = holder.GetMasterAccountId(); if (masterAccountId) @@ -164,14 +159,25 @@ void PlayerbotHolder::AddPlayerBot(ObjectGuid playerGuid, uint32 masterAccountId // verify and find current world session of master WorldSession* masterSession = sWorldSessionMgr->FindSession(masterAccountId); Player* masterPlayer = masterSession ? masterSession->GetPlayer() : nullptr; + if (masterPlayer) - mgr = GET_PLAYERBOT_MGR(masterPlayer); + { + PlayerbotHolder* mgr = PlayerbotsMgr::instance().GetPlayerbotMgr(masterPlayer); + + if (mgr != nullptr) + { + mgr->HandlePlayerBotLoginCallback(holder); + + return; + } + + PlayerbotHolder::botLoading.erase(holder.GetGuid()); + + return; + } } - if (mgr) - mgr->HandlePlayerBotLoginCallback(holder); - else - PlayerbotHolder::botLoading.erase(holder.GetGuid()); + RandomPlayerbotMgr ::instance().HandlePlayerBotLoginCallback(holder); }); } @@ -216,9 +222,9 @@ void PlayerbotHolder::HandlePlayerBotLoginCallback(PlayerbotLoginQueryHolder con masterAccountId); } - sRandomPlayerbotMgr->OnPlayerLogin(bot); + sRandomPlayerbotMgr.OnPlayerLogin(bot); auto op = std::make_unique(bot->GetGUID(), masterAccountId); - sPlayerbotWorldProcessor->QueueOperation(std::move(op)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(op)); PlayerbotHolder::botLoading.erase(holder.GetGuid()); } @@ -312,8 +318,8 @@ void PlayerbotMgr::CancelLogout() } } - for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr->GetPlayerBotsBegin(); - it != sRandomPlayerbotMgr->GetPlayerBotsEnd(); ++it) + for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr.GetPlayerBotsBegin(); + it != sRandomPlayerbotMgr.GetPlayerBotsEnd(); ++it) { Player* const bot = it->second; PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); @@ -341,7 +347,7 @@ void PlayerbotHolder::LogoutPlayerBot(ObjectGuid guid) // Queue group cleanup operation for world thread auto cleanupOp = std::make_unique(guid); - sPlayerbotWorldProcessor->QueueOperation(std::move(cleanupOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(cleanupOp)); LOG_DEBUG("playerbots", "Bot {} logging out", bot->GetName().c_str()); bot->SaveToDB(false, false); @@ -442,7 +448,7 @@ void PlayerbotHolder::DisablePlayerBot(ObjectGuid guid) Group* group = bot->GetGroup(); if (group && !bot->InBattleground() && !bot->InBattlegroundQueue() && botAI->HasActivePlayerMaster()) { - sPlayerbotRepository->Save(botAI); + PlayerbotRepository::instance().Save(botAI); } LOG_DEBUG("playerbots", "Bot {} logged out", bot->GetName().c_str()); @@ -488,7 +494,7 @@ void PlayerbotHolder::OnBotLogin(Player* const bot) return; } - sPlayerbotsMgr->AddPlayerbotData(bot, true); + PlayerbotsMgr::instance().AddPlayerbotData(bot, true); playerBots[bot->GetGUID()] = bot; OnBotLoginInternal(bot); @@ -528,10 +534,10 @@ void PlayerbotHolder::OnBotLogin(Player* const bot) // Don't disband alt groups when master goes away // Controlled by config - if (sPlayerbotAIConfig->KeepAltsInGroup()) + if (sPlayerbotAIConfig.KeepAltsInGroup()) { uint32 account = sCharacterCache->GetCharacterAccountIdByGuid(member); - if (!sPlayerbotAIConfig->IsInRandomAccountList(account)) + if (!sPlayerbotAIConfig.IsInRandomAccountList(account)) { groupValid = true; break; @@ -552,9 +558,9 @@ void PlayerbotHolder::OnBotLogin(Player* const bot) } else { - botAI->ResetStrategies(!sRandomPlayerbotMgr->IsRandomBot(bot)); + botAI->ResetStrategies(!sRandomPlayerbotMgr.IsRandomBot(bot)); } - sPlayerbotRepository->Load(botAI); + PlayerbotRepository::instance().Load(botAI); if (master && !master->HasUnitState(UNIT_STATE_IN_FLIGHT)) { @@ -580,52 +586,52 @@ void PlayerbotHolder::OnBotLogin(Player* const bot) { // Queue ConvertToRaid operation auto convertOp = std::make_unique(master->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(convertOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(convertOp)); } if (mgroup->isRaidGroup()) { // Queue AddMember operation auto addOp = std::make_unique(master->GetGUID(), bot->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(addOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(addOp)); } } else { // Queue AddMember operation auto addOp = std::make_unique(master->GetGUID(), bot->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(addOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(addOp)); } } else if (master && !group) { // Queue group creation and AddMember operation auto inviteOp = std::make_unique(master->GetGUID(), bot->GetGUID()); - sPlayerbotWorldProcessor->QueueOperation(std::move(inviteOp)); + PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(inviteOp)); } // if (master) // { // // bot->TeleportTo(master); // } uint32 accountId = bot->GetSession()->GetAccountId(); - bool isRandomAccount = sPlayerbotAIConfig->IsInRandomAccountList(accountId); + bool isRandomAccount = sPlayerbotAIConfig.IsInRandomAccountList(accountId); - if (isRandomAccount && sPlayerbotAIConfig->randomBotFixedLevel) + if (isRandomAccount && sPlayerbotAIConfig.randomBotFixedLevel) { bot->SetPlayerFlag(PLAYER_FLAGS_NO_XP_GAIN); } - else if (isRandomAccount && !sPlayerbotAIConfig->randomBotFixedLevel) + else if (isRandomAccount && !sPlayerbotAIConfig.randomBotFixedLevel) { bot->RemovePlayerFlag(PLAYER_FLAGS_NO_XP_GAIN); } bot->SaveToDB(false, false); - bool addClassBot = sRandomPlayerbotMgr->IsAccountType(accountId, 2); + bool addClassBot = sRandomPlayerbotMgr.IsAccountType(accountId, 2); if (addClassBot && master && abs((int)master->GetLevel() - (int)bot->GetLevel()) > 3) { // PlayerbotFactory factory(bot, master->GetLevel()); // factory.Randomize(false); uint32 mixedGearScore = - PlayerbotAI::GetMixedGearScore(master, true, false, 12) * sPlayerbotAIConfig->autoInitEquipLevelLimitRatio; + PlayerbotAI::GetMixedGearScore(master, true, false, 12) * sPlayerbotAIConfig.autoInitEquipLevelLimitRatio; // work around: distinguish from 0 if no gear if (mixedGearScore == 0) mixedGearScore = 1; @@ -634,7 +640,7 @@ void PlayerbotHolder::OnBotLogin(Player* const bot) } // bots join World chat if not solo oriented - if (bot->GetLevel() >= 10 && sRandomPlayerbotMgr->IsRandomBot(bot) && GET_PLAYERBOT_AI(bot) && + if (bot->GetLevel() >= 10 && sRandomPlayerbotMgr.IsRandomBot(bot) && GET_PLAYERBOT_AI(bot) && GET_PLAYERBOT_AI(bot)->GetGrouperType() != GrouperType::SOLO) { // TODO make action/config @@ -700,14 +706,13 @@ void PlayerbotHolder::OnBotLogin(Player* const bot) } std::string const PlayerbotHolder::ProcessBotCommand(std::string const cmd, ObjectGuid guid, ObjectGuid masterguid, - bool admin, uint32 masterAccountId, uint32 masterGuildId) + bool admin, uint32 masterAccountId, uint32) { - if (!sPlayerbotAIConfig->enabled || guid.IsEmpty()) + if (!sPlayerbotAIConfig.enabled || guid.IsEmpty()) return "bot system is disabled"; - uint32 botAccount = sCharacterCache->GetCharacterAccountIdByGuid(guid); - //bool isRandomBot = sRandomPlayerbotMgr->IsRandomBot(guid.GetCounter()); //not used, line marked for removal. - //bool isRandomAccount = sPlayerbotAIConfig->IsInRandomAccountList(botAccount); //not used, shadowed, line marked for removal. + //bool isRandomBot = sRandomPlayerbotMgr.IsRandomBot(guid.GetCounter()); //not used, line marked for removal. + //bool isRandomAccount = sPlayerbotAIConfig.IsInRandomAccountList(botAccount); //not used, shadowed, line marked for removal. //bool isMasterAccount = (masterAccountId == botAccount); //not used, line marked for removal. if (cmd == "add" || cmd == "addaccount" || cmd == "login") @@ -720,13 +725,15 @@ std::string const PlayerbotHolder::ProcessBotCommand(std::string const cmd, Obje { uint32 accountId = sCharacterCache->GetCharacterAccountIdByGuid(guid); if (!accountId) + { return "character not found"; + } - if (!sPlayerbotAIConfig->allowAccountBots && accountId != masterAccountId && - !(sPlayerbotAIConfig->allowTrustedAccountBots && IsAccountLinked(accountId, masterAccountId))) - { - return "you can only add bots from your own account or linked accounts"; - } + if (!sPlayerbotAIConfig.allowAccountBots && accountId != masterAccountId && + !(sPlayerbotAIConfig.allowTrustedAccountBots && IsAccountLinked(accountId, masterAccountId))) + { + return "you can only add bots from your own account or linked accounts"; + } } AddPlayerBot(guid, masterAccountId); @@ -748,12 +755,12 @@ std::string const PlayerbotHolder::ProcessBotCommand(std::string const cmd, Obje // { Player* bot = GetPlayerBot(guid); if (!bot) - bot = sRandomPlayerbotMgr->GetPlayerBot(guid); + bot = sRandomPlayerbotMgr.GetPlayerBot(guid); if (!bot) return "bot not found"; - bool addClassBot = sRandomPlayerbotMgr->IsAddclassBot(guid.GetCounter()); + bool addClassBot = sRandomPlayerbotMgr.IsAddclassBot(guid.GetCounter()); if (!addClassBot) return "ERROR: You can not use this command on non-addclass bot."; @@ -771,7 +778,7 @@ std::string const PlayerbotHolder::ProcessBotCommand(std::string const cmd, Obje { if (Player* master = GET_PLAYERBOT_AI(bot)->GetMaster()) { - if (master->GetSession()->GetSecurity() <= SEC_PLAYER && sPlayerbotAIConfig->autoInitOnly && + if (master->GetSession()->GetSecurity() <= SEC_PLAYER && sPlayerbotAIConfig.autoInitOnly && cmd != "init=auto") { return "The command is not allowed, use init=auto instead."; @@ -818,7 +825,7 @@ std::string const PlayerbotHolder::ProcessBotCommand(std::string const cmd, Obje else if (cmd == "init=auto") { uint32 mixedGearScore = PlayerbotAI::GetMixedGearScore(master, true, false, 12) * - sPlayerbotAIConfig->autoInitEquipLevelLimitRatio; + sPlayerbotAIConfig.autoInitEquipLevelLimitRatio; // work around: distinguish from 0 if no gear if (mixedGearScore == 0) mixedGearScore = 1; @@ -858,7 +865,7 @@ std::string const PlayerbotHolder::ProcessBotCommand(std::string const cmd, Obje } else if (cmd == "random") { - sRandomPlayerbotMgr->Randomize(bot); + sRandomPlayerbotMgr.Randomize(bot); return "ok"; } else if (cmd == "quests") @@ -886,7 +893,7 @@ static uint8 GetOfflinePlayerGender(ObjectGuid guid) bool PlayerbotMgr::HandlePlayerbotMgrCommand(ChatHandler* handler, char const* args) { - if (!sPlayerbotAIConfig->enabled) + if (!sPlayerbotAIConfig.enabled) { handler->PSendSysMessage("|cffff0000Playerbot system is currently disabled!"); return false; @@ -1052,7 +1059,7 @@ std::vector PlayerbotHolder::HandlePlayerbotCommand(char const* arg { if (master->GetSession()->GetSecurity() >= SEC_GAMEMASTER) { - sPlayerbotAIConfig->Initialize(); + sPlayerbotAIConfig.Initialize(); messages.push_back("Config reloaded."); return messages; } @@ -1065,11 +1072,11 @@ std::vector PlayerbotHolder::HandlePlayerbotCommand(char const* arg if (!strcmp(cmd, "tweak")) { - sPlayerbotAIConfig->tweakValue = sPlayerbotAIConfig->tweakValue++; - if (sPlayerbotAIConfig->tweakValue > 2) - sPlayerbotAIConfig->tweakValue = 0; + sPlayerbotAIConfig.tweakValue = sPlayerbotAIConfig.tweakValue++; + if (sPlayerbotAIConfig.tweakValue > 2) + sPlayerbotAIConfig.tweakValue = 0; - messages.push_back("Set tweakvalue to " + std::to_string(sPlayerbotAIConfig->tweakValue)); + messages.push_back("Set tweakvalue to " + std::to_string(sPlayerbotAIConfig.tweakValue)); return messages; } @@ -1080,14 +1087,14 @@ std::vector PlayerbotHolder::HandlePlayerbotCommand(char const* arg messages.push_back("Disable player botAI"); delete GET_PLAYERBOT_AI(master); } - else if (sPlayerbotAIConfig->selfBotLevel == 0) + else if (sPlayerbotAIConfig.selfBotLevel == 0) messages.push_back("Self-bot is disabled"); - else if (sPlayerbotAIConfig->selfBotLevel == 1 && master->GetSession()->GetSecurity() < SEC_GAMEMASTER) + else if (sPlayerbotAIConfig.selfBotLevel == 1 && master->GetSession()->GetSecurity() < SEC_GAMEMASTER) messages.push_back("You do not have permission to enable player botAI"); else { messages.push_back("Enable player botAI"); - sPlayerbotsMgr->AddPlayerbotData(master, true); + PlayerbotsMgr::instance().AddPlayerbotData(master, true); GET_PLAYERBOT_AI(master)->SetMaster(master); } @@ -1102,7 +1109,7 @@ std::vector PlayerbotHolder::HandlePlayerbotCommand(char const* arg if (!strcmp(cmd, "addclass")) { - if (sPlayerbotAIConfig->addClassCommand == 0 && master->GetSession()->GetSecurity() < SEC_GAMEMASTER) + if (sPlayerbotAIConfig.addClassCommand == 0 && master->GetSession()->GetSecurity() < SEC_GAMEMASTER) { messages.push_back("You do not have permission to create bot by addclass command"); return messages; @@ -1183,7 +1190,7 @@ std::vector PlayerbotHolder::HandlePlayerbotCommand(char const* arg return messages; } uint8 teamId = master->GetTeamId(true); - const std::unordered_set &guidCache = sRandomPlayerbotMgr->addclassCache[RandomPlayerbotMgr::GetTeamClassIdx(teamId == TEAM_ALLIANCE, claz)]; + const std::unordered_set &guidCache = sRandomPlayerbotMgr.addclassCache[RandomPlayerbotMgr::GetTeamClassIdx(teamId == TEAM_ALLIANCE, claz)]; for (const ObjectGuid &guid: guidCache) { // If the user requested a specific gender, skip any character that doesn't match. @@ -1194,7 +1201,7 @@ std::vector PlayerbotHolder::HandlePlayerbotCommand(char const* arg if (ObjectAccessor::FindConnectedPlayer(guid)) continue; uint32 guildId = sCharacterCache->GetCharacterGuildIdByGuid(guid); - if (guildId && sPlayerbotGuildMgr->IsRealGuild(guildId)) + if (guildId && PlayerbotGuildMgr::instance().IsRealGuild(guildId)) continue; AddPlayerBot(guid, master->GetSession()->GetAccountId()); messages.push_back("Add class " + std::string(charname)); @@ -1424,7 +1431,7 @@ std::string const PlayerbotHolder::ListBots(Player* master) for (Group::member_citerator itr = groupSlot.begin(); itr != groupSlot.end(); itr++) { Player* member = ObjectAccessor::FindPlayer(itr->guid); - if (member && sRandomPlayerbotMgr->IsRandomBot(member)) + if (member && sRandomPlayerbotMgr.IsRandomBot(member)) { std::string const name = member->GetName(); @@ -1452,7 +1459,7 @@ std::string const PlayerbotHolder::ListBots(Player* master) return out.str(); } -std::string const PlayerbotHolder::LookupBots(Player* master) +std::string const PlayerbotHolder::LookupBots(Player*) { std::list messages; messages.push_back("Classes Available:"); @@ -1494,12 +1501,12 @@ PlayerbotMgr::PlayerbotMgr(Player* const master) : PlayerbotHolder(), master(mas PlayerbotMgr::~PlayerbotMgr() { if (master) - sPlayerbotsMgr->RemovePlayerBotData(master->GetGUID(), false); + PlayerbotsMgr::instance().RemovePlayerBotData(master->GetGUID(), false); } void PlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) { - SetNextCheckDelay(sPlayerbotAIConfig->reactDelay); + SetNextCheckDelay(sPlayerbotAIConfig.reactDelay); CheckTellErrors(elapsed); } @@ -1509,10 +1516,10 @@ void PlayerbotMgr::HandleCommand(uint32 type, std::string const text) if (!master) return; - if (text.find(sPlayerbotAIConfig->commandSeparator) != std::string::npos) + if (text.find(sPlayerbotAIConfig.commandSeparator) != std::string::npos) { std::vector commands; - split(commands, text, sPlayerbotAIConfig->commandSeparator.c_str()); + split(commands, text, sPlayerbotAIConfig.commandSeparator.c_str()); for (std::vector::iterator i = commands.begin(); i != commands.end(); ++i) { HandleCommand(type, *i); @@ -1529,8 +1536,8 @@ void PlayerbotMgr::HandleCommand(uint32 type, std::string const text) botAI->HandleCommand(type, text, master); } - for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr->GetPlayerBotsBegin(); - it != sRandomPlayerbotMgr->GetPlayerBotsEnd(); ++it) + for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr.GetPlayerBotsBegin(); + it != sRandomPlayerbotMgr.GetPlayerBotsEnd(); ++it) { Player* const bot = it->second; PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); @@ -1551,8 +1558,8 @@ void PlayerbotMgr::HandleMasterIncomingPacket(WorldPacket const& packet) botAI->HandleMasterIncomingPacket(packet); } - for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr->GetPlayerBotsBegin(); - it != sRandomPlayerbotMgr->GetPlayerBotsEnd(); ++it) + for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr.GetPlayerBotsBegin(); + it != sRandomPlayerbotMgr.GetPlayerBotsEnd(); ++it) { Player* const bot = it->second; PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); @@ -1587,8 +1594,8 @@ void PlayerbotMgr::HandleMasterOutgoingPacket(WorldPacket const& packet) botAI->HandleMasterOutgoingPacket(packet); } - for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr->GetPlayerBotsBegin(); - it != sRandomPlayerbotMgr->GetPlayerBotsEnd(); ++it) + for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr.GetPlayerBotsBegin(); + it != sRandomPlayerbotMgr.GetPlayerBotsEnd(); ++it) { Player* const bot = it->second; PlayerbotAI* botAI = GET_PLAYERBOT_AI(bot); @@ -1605,8 +1612,8 @@ void PlayerbotMgr::SaveToDB() bot->SaveToDB(false, false); } - for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr->GetPlayerBotsBegin(); - it != sRandomPlayerbotMgr->GetPlayerBotsEnd(); ++it) + for (PlayerBotMap::const_iterator it = sRandomPlayerbotMgr.GetPlayerBotsBegin(); + it != sRandomPlayerbotMgr.GetPlayerBotsEnd(); ++it) { Player* const bot = it->second; if (GET_PLAYERBOT_AI(bot) && GET_PLAYERBOT_AI(bot)->GetMaster() == GetMaster()) @@ -1648,12 +1655,12 @@ void PlayerbotMgr::OnPlayerLogin(Player* player) usedLocale = LOCALE_enUS; // fallback // set locale priority for bot texts - sPlayerbotTextMgr->AddLocalePriority(usedLocale); + PlayerbotTextMgr::instance().AddLocalePriority(usedLocale); - if (sPlayerbotAIConfig->selfBotLevel > 2) + if (sPlayerbotAIConfig.selfBotLevel > 2) HandlePlayerbotCommand("self", player); - if (!sPlayerbotAIConfig->botAutologin) + if (!sPlayerbotAIConfig.botAutologin) return; uint32 accountId = session->GetAccountId(); @@ -1690,10 +1697,10 @@ void PlayerbotMgr::TellError(std::string const botName, std::string const text) errors[text] = names; } -void PlayerbotMgr::CheckTellErrors(uint32 elapsed) +void PlayerbotMgr::CheckTellErrors(uint32) { time_t now = time(nullptr); - if ((now - lastErrorTell) < sPlayerbotAIConfig->errorDelay / 1000) + if ((now - lastErrorTell) < sPlayerbotAIConfig.errorDelay / 1000) return; lastErrorTell = now; @@ -1777,7 +1784,7 @@ void PlayerbotsMgr::RemovePlayerBotData(ObjectGuid const& guid, bool is_AI) PlayerbotAI* PlayerbotsMgr::GetPlayerbotAI(Player* player) { - if (!(sPlayerbotAIConfig->enabled) || !player) + if (!(sPlayerbotAIConfig.enabled) || !player) { return nullptr; } @@ -1797,7 +1804,7 @@ PlayerbotAI* PlayerbotsMgr::GetPlayerbotAI(Player* player) PlayerbotMgr* PlayerbotsMgr::GetPlayerbotMgr(Player* player) { - if (!(sPlayerbotAIConfig->enabled) || !player) + if (!(sPlayerbotAIConfig.enabled) || !player) { return nullptr; } diff --git a/src/Bot/PlayerbotMgr.h b/src/Bot/PlayerbotMgr.h index 7ee576006b..b80f6f2363 100644 --- a/src/Bot/PlayerbotMgr.h +++ b/src/Bot/PlayerbotMgr.h @@ -6,12 +6,9 @@ #ifndef _PLAYERBOT_PLAYERBOTMGR_H #define _PLAYERBOT_PLAYERBOTMGR_H -#include "Common.h" #include "ObjectGuid.h" #include "Player.h" #include "PlayerbotAIBase.h" -#include "QueryHolder.h" -#include "QueryResult.h" class ChatHandler; class PlayerbotAI; @@ -101,13 +98,10 @@ class PlayerbotMgr : public PlayerbotHolder class PlayerbotsMgr { public: - PlayerbotsMgr() {} - ~PlayerbotsMgr() {} - - static PlayerbotsMgr* instance() + static PlayerbotsMgr& instance() { static PlayerbotsMgr instance; - return &instance; + return instance; } void AddPlayerbotData(Player* player, bool isBotAI); @@ -117,6 +111,15 @@ class PlayerbotsMgr PlayerbotMgr* GetPlayerbotMgr(Player* player); private: + PlayerbotsMgr() = default; + ~PlayerbotsMgr() = default; + + PlayerbotsMgr(const PlayerbotsMgr&) = delete; + PlayerbotsMgr& operator=(const PlayerbotsMgr&) = delete; + + PlayerbotsMgr(PlayerbotsMgr&&) = delete; + PlayerbotsMgr& operator=(PlayerbotsMgr&&) = delete; + std::unordered_map _playerbotsAIMap; std::unordered_map _playerbotsMgrMap; }; diff --git a/src/Bot/RandomPlayerbotMgr.cpp b/src/Bot/RandomPlayerbotMgr.cpp index 4d589ef1b4..ed2de50d16 100644 --- a/src/Bot/RandomPlayerbotMgr.cpp +++ b/src/Bot/RandomPlayerbotMgr.cpp @@ -14,12 +14,9 @@ #include #include -#include "AccountMgr.h" #include "AiFactory.h" -#include "ArenaTeamMgr.h" #include "Battleground.h" #include "BattlegroundMgr.h" -#include "CellImpl.h" #include "ChannelMgr.h" #include "DBCStores.h" #include "DBCStructure.h" @@ -28,9 +25,6 @@ #include "FleeManager.h" #include "FlightMasterCache.h" #include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "GuildMgr.h" -#include "GuildTaskMgr.h" #include "LFGMgr.h" #include "MapMgr.h" #include "NewRpgInfo.h" @@ -40,7 +34,6 @@ #include "Player.h" #include "PlayerbotAI.h" #include "PlayerbotAIConfig.h" -#include "PlayerbotCommandServer.h" #include "PlayerbotFactory.h" #include "Playerbots.h" #include "Position.h" @@ -50,8 +43,13 @@ #include "SharedDefines.h" #include "TravelMgr.h" #include "Unit.h" -#include "UpdateTime.h" #include "World.h" +#include "Cell.h" +#include "GridNotifiers.h" +// Required for Cell because of poor AC implementation +#include "CellImpl.h" +// Required for GridNotifiers because of poor AC implementation +#include "GridNotifiersImpl.h" struct GuidClassRaceInfo { @@ -102,7 +100,7 @@ static const std::unordered_map> cityToBankers = { // Quick lookup map: banker entry → location static std::unordered_map bankerEntryToLocation; -void PrintStatsThread() { sRandomPlayerbotMgr->PrintStats(); } +void PrintStatsThread() { sRandomPlayerbotMgr.PrintStats(); } void activatePrintStatsThread() { @@ -110,7 +108,7 @@ void activatePrintStatsThread() t.detach(); } -void CheckBgQueueThread() { sRandomPlayerbotMgr->CheckBgQueue(); } +void CheckBgQueueThread() { sRandomPlayerbotMgr.CheckBgQueue(); } void activateCheckBgQueueThread() { @@ -118,7 +116,7 @@ void activateCheckBgQueueThread() t.detach(); } -void CheckLfgQueueThread() { sRandomPlayerbotMgr->CheckLfgQueue(); } +void CheckLfgQueueThread() { sRandomPlayerbotMgr.CheckLfgQueue(); } void activateCheckLfgQueueThread() { @@ -126,7 +124,7 @@ void activateCheckLfgQueueThread() t.detach(); } -void CheckPlayersThread() { sRandomPlayerbotMgr->CheckPlayers(); } +void CheckPlayersThread() { sRandomPlayerbotMgr.CheckPlayers(); } void activateCheckPlayersThread() { @@ -215,36 +213,6 @@ double botPIDImpl::calculate(double setpoint, double pv) botPIDImpl::~botPIDImpl() {} -RandomPlayerbotMgr::RandomPlayerbotMgr() : PlayerbotHolder(), processTicks(0) -{ - playersLevel = sPlayerbotAIConfig->randombotStartingLevel; - - if (sPlayerbotAIConfig->enabled || sPlayerbotAIConfig->randomBotAutologin) - { - sPlayerbotCommandServer->Start(); - } - - BattlegroundData.clear(); // Clear here and here only. - - // Cleanup on server start: orphaned pet data that's often left behind by bot pets that no longer exist in the DB - CharacterDatabase.Execute("DELETE FROM pet_aura WHERE guid NOT IN (SELECT id FROM character_pet)"); - CharacterDatabase.Execute("DELETE FROM pet_spell WHERE guid NOT IN (SELECT id FROM character_pet)"); - CharacterDatabase.Execute("DELETE FROM pet_spell_cooldown WHERE guid NOT IN (SELECT id FROM character_pet)"); - - for (int bracket = BG_BRACKET_ID_FIRST; bracket < MAX_BATTLEGROUND_BRACKETS; ++bracket) - { - for (int queueType = BATTLEGROUND_QUEUE_AV; queueType < MAX_BATTLEGROUND_QUEUE_TYPES; ++queueType) - { - BattlegroundData[queueType][bracket] = BattlegroundInfo(); - } - } - BgCheckTimer = 0; - LfgCheckTimer = 0; - PlayersCheckTimer = 0; -} - -RandomPlayerbotMgr::~RandomPlayerbotMgr() {} - uint32 RandomPlayerbotMgr::GetMaxAllowedBotCount() { return GetEventValue(0, "bot_count"); } void RandomPlayerbotMgr::LogPlayerLocation() @@ -253,9 +221,9 @@ void RandomPlayerbotMgr::LogPlayerLocation() try { - sPlayerbotAIConfig->openLog("player_location.csv", "w"); + sPlayerbotAIConfig.openLog("player_location.csv", "w"); - if (sPlayerbotAIConfig->randomBotAutologin) + if (sPlayerbotAIConfig.randomBotAutologin) { for (auto i : GetAllBots()) { @@ -264,7 +232,7 @@ void RandomPlayerbotMgr::LogPlayerLocation() continue; std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr() << "+00,"; + out << sPlayerbotAIConfig.GetTimestampStr() << "+00,"; out << "RND" << ","; out << bot->GetName() << ","; @@ -298,7 +266,7 @@ void RandomPlayerbotMgr::LogPlayerLocation() out << (bot->IsInCombat() ? "combat" : "safe") << ","; out << (bot->isDead() ? (bot->GetCorpse() ? "ghost" : "dead") : "alive"); - sPlayerbotAIConfig->log("player_location.csv", out.str().c_str()); + sPlayerbotAIConfig.log("player_location.csv", out.str().c_str()); } for (auto i : GetPlayers()) @@ -308,7 +276,7 @@ void RandomPlayerbotMgr::LogPlayerLocation() continue; std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr() << "+00,"; + out << sPlayerbotAIConfig.GetTimestampStr() << "+00,"; out << "PLR" << ","; out << bot->GetName() << ","; @@ -342,7 +310,7 @@ void RandomPlayerbotMgr::LogPlayerLocation() out << (bot->IsInCombat() ? "combat" : "safe") << ","; out << (bot->isDead() ? (bot->GetCorpse() ? "ghost" : "dead") : "alive"); - sPlayerbotAIConfig->log("player_location.csv", out.str().c_str()); + sPlayerbotAIConfig.log("player_location.csv", out.str().c_str()); } } } @@ -354,17 +322,17 @@ void RandomPlayerbotMgr::LogPlayerLocation() } } -void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) +void RandomPlayerbotMgr::UpdateAIInternal(uint32, bool /*minimal*/) { if (totalPmo) totalPmo->finish(); - totalPmo = sPerfMonitor->start(PERF_MON_TOTAL, "RandomPlayerbotMgr::FullTick"); + totalPmo = sPerfMonitor.start(PERF_MON_TOTAL, "RandomPlayerbotMgr::FullTick"); - if (!sPlayerbotAIConfig->randomBotAutologin || !sPlayerbotAIConfig->enabled) + if (!sPlayerbotAIConfig.randomBotAutologin || !sPlayerbotAIConfig.enabled) return; - /*if (sPlayerbotAIConfig->enablePrototypePerformanceDiff) + /*if (sPlayerbotAIConfig.enablePrototypePerformanceDiff) { LOG_INFO("playerbots", "---------------------------------------"); LOG_INFO("playerbots", @@ -374,13 +342,13 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) }*/ uint32 maxAllowedBotCount = GetEventValue(0, "bot_count"); - if (!maxAllowedBotCount || (maxAllowedBotCount < sPlayerbotAIConfig->minRandomBots || - maxAllowedBotCount > sPlayerbotAIConfig->maxRandomBots)) + if (!maxAllowedBotCount || (maxAllowedBotCount < sPlayerbotAIConfig.minRandomBots || + maxAllowedBotCount > sPlayerbotAIConfig.maxRandomBots)) { - maxAllowedBotCount = urand(sPlayerbotAIConfig->minRandomBots, sPlayerbotAIConfig->maxRandomBots); + maxAllowedBotCount = urand(sPlayerbotAIConfig.minRandomBots, sPlayerbotAIConfig.maxRandomBots); SetEventValue(0, "bot_count", maxAllowedBotCount, - urand(sPlayerbotAIConfig->randomBotCountChangeMinInterval, - sPlayerbotAIConfig->randomBotCountChangeMaxInterval)); + urand(sPlayerbotAIConfig.randomBotCountChangeMinInterval, + sPlayerbotAIConfig.randomBotCountChangeMaxInterval)); } GetBots(); @@ -389,25 +357,25 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) uint32 onlineBotCount = playerBots.size(); uint32 onlineBotFocus = 75; - if (onlineBotCount < (uint32)(sPlayerbotAIConfig->minRandomBots * 90 / 100)) + if (onlineBotCount < (uint32)(sPlayerbotAIConfig.minRandomBots * 90 / 100)) onlineBotFocus = 25; // only keep updating till initializing time has completed, // which prevents unneeded expensive GameTime calls. if (_isBotInitializing) { - _isBotInitializing = GameTime::GetUptime().count() < sPlayerbotAIConfig->maxRandomBots * (0.11 + 0.4); + _isBotInitializing = GameTime::GetUptime().count() < sPlayerbotAIConfig.maxRandomBots * (0.11 + 0.4); } - uint32 updateIntervalTurboBoost = _isBotInitializing ? 1 : sPlayerbotAIConfig->randomBotUpdateInterval; + uint32 updateIntervalTurboBoost = _isBotInitializing ? 1 : sPlayerbotAIConfig.randomBotUpdateInterval; SetNextCheckDelay(updateIntervalTurboBoost * (onlineBotFocus + 25) * 10); - PerfMonitorOperation* pmo = sPerfMonitor->start( + PerfMonitorOperation* pmo = sPerfMonitor.start( PERF_MON_TOTAL, onlineBotCount < maxAllowedBotCount ? "RandomPlayerbotMgr::Login" : "RandomPlayerbotMgr::UpdateAIInternal"); bool realPlayerIsLogged = false; - if (sPlayerbotAIConfig->disabledWithoutRealPlayer) + if (sPlayerbotAIConfig.disabledWithoutRealPlayer) { if (sWorldSessionMgr->GetActiveAndQueuedSessionCount() > 0) { @@ -416,7 +384,7 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) if (DelayLoginBotsTimer == 0) { - DelayLoginBotsTimer = time(nullptr) + sPlayerbotAIConfig->disabledWithoutRealPlayerLoginDelay; + DelayLoginBotsTimer = time(nullptr) + sPlayerbotAIConfig.disabledWithoutRealPlayerLoginDelay; } } else @@ -427,7 +395,7 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) } if (RealPlayerLastTimeSeen != 0 && onlineBotCount > 0 && - time(nullptr) > RealPlayerLastTimeSeen + sPlayerbotAIConfig->disabledWithoutRealPlayerLogoutDelay) + time(nullptr) > RealPlayerLastTimeSeen + sPlayerbotAIConfig.disabledWithoutRealPlayerLogoutDelay) { LogoutAllBots(); LOG_INFO("playerbots", "Logout all bots due no real player session."); @@ -435,7 +403,7 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) } if (availableBotCount < maxAllowedBotCount && - (sPlayerbotAIConfig->disabledWithoutRealPlayer == false || + (sPlayerbotAIConfig.disabledWithoutRealPlayer == false || (realPlayerIsLogged && DelayLoginBotsTimer != 0 && time(nullptr) >= DelayLoginBotsTimer))) { AddRandomBots(); @@ -446,25 +414,25 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) AddRandomBots(); } - if (sPlayerbotAIConfig->syncLevelWithPlayers && !players.empty()) + if (sPlayerbotAIConfig.syncLevelWithPlayers && !players.empty()) { if (time(nullptr) > (PlayersCheckTimer + 60)) - sRandomPlayerbotMgr->CheckPlayers(); + sRandomPlayerbotMgr.CheckPlayers(); } - if (sPlayerbotAIConfig->randomBotJoinBG /* && !players.empty()*/) + if (sPlayerbotAIConfig.randomBotJoinBG /* && !players.empty()*/) { if (time(nullptr) > (BgCheckTimer + 35)) - sRandomPlayerbotMgr->CheckBgQueue(); + sRandomPlayerbotMgr.CheckBgQueue(); } - if (sPlayerbotAIConfig->randomBotJoinLfg /* && !players.empty()*/) + if (sPlayerbotAIConfig.randomBotJoinLfg /* && !players.empty()*/) { if (time(nullptr) > (LfgCheckTimer + 30)) - sRandomPlayerbotMgr->CheckLfgQueue(); + sRandomPlayerbotMgr.CheckLfgQueue(); } - if (sPlayerbotAIConfig->randomBotAutologin && time(nullptr) > (printStatsTimer + 300)) + if (sPlayerbotAIConfig.randomBotAutologin && time(nullptr) > (printStatsTimer + 300)) { if (!printStatsTimer) { @@ -472,18 +440,18 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) } else { - sRandomPlayerbotMgr->PrintStats(); + sRandomPlayerbotMgr.PrintStats(); // activatePrintStatsThread(); } } - uint32 updateBots = sPlayerbotAIConfig->randomBotsPerInterval * onlineBotFocus / 100; + uint32 updateBots = sPlayerbotAIConfig.randomBotsPerInterval * onlineBotFocus / 100; uint32 maxNewBots = onlineBotCount < maxAllowedBotCount && - (sPlayerbotAIConfig->disabledWithoutRealPlayer == false || + (sPlayerbotAIConfig.disabledWithoutRealPlayer == false || (realPlayerIsLogged && DelayLoginBotsTimer != 0 && time(nullptr) >= DelayLoginBotsTimer)) ? maxAllowedBotCount - onlineBotCount : 0; - uint32 loginBots = std::min(sPlayerbotAIConfig->randomBotsPerInterval - updateBots, maxNewBots); + uint32 loginBots = std::min(sPlayerbotAIConfig.randomBotsPerInterval - updateBots, maxNewBots); if (!availableBots.empty()) { @@ -531,7 +499,7 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) if (pmo) pmo->finish(); - if (sPlayerbotAIConfig->hasLog("player_location.csv")) + if (sPlayerbotAIConfig.hasLog("player_location.csv")) { LogPlayerLocation(); } @@ -546,8 +514,8 @@ void RandomPlayerbotMgr::UpdateAIInternal(uint32 elapsed, bool /*minimal*/) // // // % increase/decrease wanted diff , avg diff // float activityPercentageMod = pid.calculate( -// sRandomPlayerbotMgr->GetPlayers().empty() ? sPlayerbotAIConfig->diffEmpty : -// sPlayerbotAIConfig->diffWithPlayer, sWorldUpdateTime.GetAverageUpdateTime()); +// sRandomPlayerbotMgr.GetPlayers().empty() ? sPlayerbotAIConfig.diffEmpty : +// sPlayerbotAIConfig.diffWithPlayer, sWorldUpdateTime.GetAverageUpdateTime()); // // activityPercentage = activityPercentageMod + 50; // @@ -573,7 +541,7 @@ void RandomPlayerbotMgr::AssignAccountTypes() std::vector allRandomBotAccounts; QueryResult allAccounts = LoginDatabase.Query( "SELECT id FROM account WHERE username LIKE '{}%%' ORDER BY id", - sPlayerbotAIConfig->randomBotAccountPrefix.c_str()); + sPlayerbotAIConfig.randomBotAccountPrefix.c_str()); if (allAccounts) { @@ -614,15 +582,15 @@ void RandomPlayerbotMgr::AssignAccountTypes() // Calculate needed RNDbot accounts uint32 neededRndBotAccounts = 0; - if (sPlayerbotAIConfig->maxRandomBots > 0) + if (sPlayerbotAIConfig.maxRandomBots > 0) { int divisor = RandomPlayerbotFactory::CalculateAvailableCharsPerAccount(); - int maxBots = sPlayerbotAIConfig->maxRandomBots; + int maxBots = sPlayerbotAIConfig.maxRandomBots; // Take periodic online-offline into account - if (sPlayerbotAIConfig->enablePeriodicOnlineOffline) + if (sPlayerbotAIConfig.enablePeriodicOnlineOffline) { - maxBots *= sPlayerbotAIConfig->periodicOnlineOfflineRatio; + maxBots *= sPlayerbotAIConfig.periodicOnlineOfflineRatio; } // Calculate base accounts needed for RNDbots, ensuring round up for maxBots not cleanly divisible by the divisor @@ -663,7 +631,7 @@ void RandomPlayerbotMgr::AssignAccountTypes() } // Assign AddClass accounts from highest position if needed - uint32 neededAddClassAccounts = sPlayerbotAIConfig->addClassAccountPoolSize; + uint32 neededAddClassAccounts = sPlayerbotAIConfig.addClassAccountPoolSize; if (existingAddClassAccounts < neededAddClassAccounts) { @@ -719,16 +687,16 @@ uint32 RandomPlayerbotMgr::AddRandomBots() { // Calculate how many bots to add maxAllowedBotCount -= currentBots.size(); - maxAllowedBotCount = std::min(sPlayerbotAIConfig->randomBotsPerInterval, maxAllowedBotCount); + maxAllowedBotCount = std::min(sPlayerbotAIConfig.randomBotsPerInterval, maxAllowedBotCount); // Single RNG instance for all shuffling std::mt19937 rng(std::chrono::steady_clock::now().time_since_epoch().count()); // Only need to track the Alliance count, as it's in Phase 1 - uint32 totalRatio = sPlayerbotAIConfig->randomBotAllianceRatio + sPlayerbotAIConfig->randomBotHordeRatio; - uint32 allowedAllianceCount = maxAllowedBotCount * (sPlayerbotAIConfig->randomBotAllianceRatio) / totalRatio; + uint32 totalRatio = sPlayerbotAIConfig.randomBotAllianceRatio + sPlayerbotAIConfig.randomBotHordeRatio; + uint32 allowedAllianceCount = maxAllowedBotCount * (sPlayerbotAIConfig.randomBotAllianceRatio) / totalRatio; - uint32 remainder = maxAllowedBotCount * (sPlayerbotAIConfig->randomBotAllianceRatio) % totalRatio; + uint32 remainder = maxAllowedBotCount * (sPlayerbotAIConfig.randomBotAllianceRatio) % totalRatio; // Fix #1082: Randomly add one based on reminder if (remainder && urand(1, totalRatio) <= remainder) @@ -738,13 +706,13 @@ uint32 RandomPlayerbotMgr::AddRandomBots() // Determine which accounts to use based on EnablePeriodicOnlineOffline std::vector accountsToUse; - if (sPlayerbotAIConfig->enablePeriodicOnlineOffline) + if (sPlayerbotAIConfig.enablePeriodicOnlineOffline) { // Calculate how many accounts can be used // With enablePeriodicOnlineOffline, don't use all of rndBotTypeAccounts right away. Fraction results are rounded up - uint32 accountsToUseCount = (rndBotTypeAccounts.size() + sPlayerbotAIConfig->periodicOnlineOfflineRatio - 1) - / sPlayerbotAIConfig->periodicOnlineOfflineRatio; + uint32 accountsToUseCount = (rndBotTypeAccounts.size() + sPlayerbotAIConfig.periodicOnlineOfflineRatio - 1) + / sPlayerbotAIConfig.periodicOnlineOfflineRatio; // Randomly select accounts std::vector shuffledAccounts = rndBotTypeAccounts; @@ -814,15 +782,15 @@ uint32 RandomPlayerbotMgr::AddRandomBots() GetEventValue(charInfo.guid, "logout") || GetPlayerBot(charInfo.guid) || std::find(currentBots.begin(), currentBots.end(), charInfo.guid) != currentBots.end() || - (sPlayerbotAIConfig->disableDeathKnightLogin && charInfo.rClass == CLASS_DEATH_KNIGHT)) + (sPlayerbotAIConfig.disableDeathKnightLogin && charInfo.rClass == CLASS_DEATH_KNIGHT)) { return false; } - uint32 add_time = sPlayerbotAIConfig->enablePeriodicOnlineOffline - ? urand(sPlayerbotAIConfig->minRandomBotInWorldTime, - sPlayerbotAIConfig->maxRandomBotInWorldTime) - : sPlayerbotAIConfig->permanentlyInWorldTime; + uint32 add_time = sPlayerbotAIConfig.enablePeriodicOnlineOffline + ? urand(sPlayerbotAIConfig.minRandomBotInWorldTime, + sPlayerbotAIConfig.maxRandomBotInWorldTime) + : sPlayerbotAIConfig.permanentlyInWorldTime; SetEventValue(charInfo.guid, "add", 1, add_time); SetEventValue(charInfo.guid, "logout", 0, 0); @@ -1026,7 +994,7 @@ void RandomPlayerbotMgr::CheckBgQueue() // Arena logic bool isRated = false; - if (uint8 arenaType = BattlegroundMgr::BGArenaType(queueTypeId)) + if (BattlegroundMgr::BGArenaType(queueTypeId)) { BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(queueTypeId); GroupQueueInfo ginfo; @@ -1113,7 +1081,7 @@ void RandomPlayerbotMgr::CheckBgQueue() BattlegroundData[queueTypeId][bracketId].minLevel = pvpDiff->minLevel; BattlegroundData[queueTypeId][bracketId].maxLevel = pvpDiff->maxLevel; - if (uint8 arenaType = BattlegroundMgr::BGArenaType(queueTypeId)) + if (BattlegroundMgr::BGArenaType(queueTypeId)) { bool isRated = false; BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(queueTypeId); @@ -1187,24 +1155,24 @@ void RandomPlayerbotMgr::CheckBgQueue() } // If enabled, wait for all bots to have logged in before queueing for Arena's / BG's - if (sPlayerbotAIConfig->randomBotAutoJoinBG && playerBots.size() >= GetMaxAllowedBotCount()) + if (sPlayerbotAIConfig.randomBotAutoJoinBG && playerBots.size() >= GetMaxAllowedBotCount()) { - uint32 randomBotAutoJoinArenaBracket = sPlayerbotAIConfig->randomBotAutoJoinArenaBracket; - uint32 randomBotAutoJoinBGRatedArena2v2Count = sPlayerbotAIConfig->randomBotAutoJoinBGRatedArena2v2Count; - uint32 randomBotAutoJoinBGRatedArena3v3Count = sPlayerbotAIConfig->randomBotAutoJoinBGRatedArena3v3Count; - uint32 randomBotAutoJoinBGRatedArena5v5Count = sPlayerbotAIConfig->randomBotAutoJoinBGRatedArena5v5Count; + uint32 randomBotAutoJoinArenaBracket = sPlayerbotAIConfig.randomBotAutoJoinArenaBracket; + uint32 randomBotAutoJoinBGRatedArena2v2Count = sPlayerbotAIConfig.randomBotAutoJoinBGRatedArena2v2Count; + uint32 randomBotAutoJoinBGRatedArena3v3Count = sPlayerbotAIConfig.randomBotAutoJoinBGRatedArena3v3Count; + uint32 randomBotAutoJoinBGRatedArena5v5Count = sPlayerbotAIConfig.randomBotAutoJoinBGRatedArena5v5Count; - uint32 randomBotAutoJoinBGICCount = sPlayerbotAIConfig->randomBotAutoJoinBGICCount; - uint32 randomBotAutoJoinBGEYCount = sPlayerbotAIConfig->randomBotAutoJoinBGEYCount; - uint32 randomBotAutoJoinBGAVCount = sPlayerbotAIConfig->randomBotAutoJoinBGAVCount; - uint32 randomBotAutoJoinBGABCount = sPlayerbotAIConfig->randomBotAutoJoinBGABCount; - uint32 randomBotAutoJoinBGWSCount = sPlayerbotAIConfig->randomBotAutoJoinBGWSCount; + uint32 randomBotAutoJoinBGICCount = sPlayerbotAIConfig.randomBotAutoJoinBGICCount; + uint32 randomBotAutoJoinBGEYCount = sPlayerbotAIConfig.randomBotAutoJoinBGEYCount; + uint32 randomBotAutoJoinBGAVCount = sPlayerbotAIConfig.randomBotAutoJoinBGAVCount; + uint32 randomBotAutoJoinBGABCount = sPlayerbotAIConfig.randomBotAutoJoinBGABCount; + uint32 randomBotAutoJoinBGWSCount = sPlayerbotAIConfig.randomBotAutoJoinBGWSCount; - std::vector icBrackets = parseBrackets(sPlayerbotAIConfig->randomBotAutoJoinICBrackets); - std::vector eyBrackets = parseBrackets(sPlayerbotAIConfig->randomBotAutoJoinEYBrackets); - std::vector avBrackets = parseBrackets(sPlayerbotAIConfig->randomBotAutoJoinAVBrackets); - std::vector abBrackets = parseBrackets(sPlayerbotAIConfig->randomBotAutoJoinABBrackets); - std::vector wsBrackets = parseBrackets(sPlayerbotAIConfig->randomBotAutoJoinWSBrackets); + std::vector icBrackets = parseBrackets(sPlayerbotAIConfig.randomBotAutoJoinICBrackets); + std::vector eyBrackets = parseBrackets(sPlayerbotAIConfig.randomBotAutoJoinEYBrackets); + std::vector avBrackets = parseBrackets(sPlayerbotAIConfig.randomBotAutoJoinAVBrackets); + std::vector abBrackets = parseBrackets(sPlayerbotAIConfig.randomBotAutoJoinABBrackets); + std::vector wsBrackets = parseBrackets(sPlayerbotAIConfig.randomBotAutoJoinWSBrackets); // Check both bgInstanceCount / bgInstances.size // to help counter against potentional inconsistencies @@ -1369,7 +1337,7 @@ void RandomPlayerbotMgr::CheckPlayers() LOG_INFO("playerbots", "Checking Players..."); if (!playersLevel) - playersLevel = sPlayerbotAIConfig->randombotStartingLevel; + playersLevel = sPlayerbotAIConfig.randombotStartingLevel; for (std::vector::iterator i = players.begin(); i != players.end(); ++i) { @@ -1393,7 +1361,7 @@ void RandomPlayerbotMgr::ScheduleRandomize(uint32 bot, uint32 time) { SetEventVa void RandomPlayerbotMgr::ScheduleTeleport(uint32 bot, uint32 time) { if (!time) - time = 60 + urand(sPlayerbotAIConfig->randomBotUpdateInterval, sPlayerbotAIConfig->randomBotUpdateInterval * 3); + time = 60 + urand(sPlayerbotAIConfig.randomBotUpdateInterval, sPlayerbotAIConfig.randomBotUpdateInterval * 3); SetEventValue(bot, "teleport", 1, time); } @@ -1401,8 +1369,8 @@ void RandomPlayerbotMgr::ScheduleTeleport(uint32 bot, uint32 time) void RandomPlayerbotMgr::ScheduleChangeStrategy(uint32 bot, uint32 time) { if (!time) - time = urand(sPlayerbotAIConfig->minRandomBotChangeStrategyTime, - sPlayerbotAIConfig->maxRandomBotChangeStrategyTime); + time = urand(sPlayerbotAIConfig.minRandomBotChangeStrategyTime, + sPlayerbotAIConfig.maxRandomBotChangeStrategyTime); SetEventValue(bot, "change_strategy", 1, time); } @@ -1440,7 +1408,7 @@ bool RandomPlayerbotMgr::ProcessBot(uint32 bot) AddPlayerBot(botGUID, 0); randomTime = urand(1, 2); - uint32 randomBotUpdateInterval = _isBotInitializing ? 1 : sPlayerbotAIConfig->randomBotUpdateInterval; + uint32 randomBotUpdateInterval = _isBotInitializing ? 1 : sPlayerbotAIConfig.randomBotUpdateInterval; randomTime = urand(std::max(5, static_cast(randomBotUpdateInterval * 0.5)), std::max(12, static_cast(randomBotUpdateInterval * 2))); SetEventValue(bot, "update", 1, randomTime); @@ -1477,7 +1445,7 @@ bool RandomPlayerbotMgr::ProcessBot(uint32 bot) if (botAI) { // botAI->GetAiObjectContext()->GetValue("random bot update")->Set(true); - if (!sRandomPlayerbotMgr->IsRandomBot(player)) + if (!sRandomPlayerbotMgr.IsRandomBot(player)) update = false; if (player->GetGroup() && botAI->GetGroupLeader()) @@ -1489,14 +1457,14 @@ bool RandomPlayerbotMgr::ProcessBot(uint32 bot) } } - // if (botAI->HasPlayerNearby(sPlayerbotAIConfig->grindDistance)) + // if (botAI->HasPlayerNearby(sPlayerbotAIConfig.grindDistance)) // update = false; } if (update) ProcessBot(player); - randomTime = urand(sPlayerbotAIConfig->minRandomBotReviveTime, sPlayerbotAIConfig->maxRandomBotReviveTime); + randomTime = urand(sPlayerbotAIConfig.minRandomBotReviveTime, sPlayerbotAIConfig.maxRandomBotReviveTime); SetEventValue(bot, "update", 1, randomTime); return true; @@ -1510,7 +1478,7 @@ bool RandomPlayerbotMgr::ProcessBot(uint32 bot) LogoutPlayerBot(botGUID); currentBots.remove(bot); SetEventValue(bot, "logout", 1, - urand(sPlayerbotAIConfig->minRandomBotInWorldTime, sPlayerbotAIConfig->maxRandomBotInWorldTime)); + urand(sPlayerbotAIConfig.minRandomBotInWorldTime, sPlayerbotAIConfig.maxRandomBotInWorldTime)); return true; } @@ -1538,10 +1506,10 @@ bool RandomPlayerbotMgr::ProcessBot(Player* bot) if (!GetEventValue(botId, "dead")) { uint32 randomTime = - urand(sPlayerbotAIConfig->minRandomBotReviveTime, sPlayerbotAIConfig->maxRandomBotReviveTime); + urand(sPlayerbotAIConfig.minRandomBotReviveTime, sPlayerbotAIConfig.maxRandomBotReviveTime); LOG_DEBUG("playerbots", "Mark bot {} as dead, will be revived in {}s.", bot->GetName().c_str(), randomTime); - SetEventValue(botId, "dead", 1, sPlayerbotAIConfig->maxRandomBotInWorldTime); + SetEventValue(botId, "dead", 1, sPlayerbotAIConfig.maxRandomBotInWorldTime); SetEventValue(botId, "revive", 1, randomTime); return false; } @@ -1591,11 +1559,11 @@ bool RandomPlayerbotMgr::ProcessBot(Player* bot) // if (guild->GetLeaderGUID() == player->GetGUID()) // { // for (std::vector::iterator i = players.begin(); i != players.end(); ++i) - // sGuildTaskMgr->Update(*i, player); + // GuildTaskMgr::instance().Update(*i, player); // } // uint32 accountId = sCharacterCache->GetCharacterAccountIdByGuid(guild->GetLeaderGUID()); - // if (!sPlayerbotAIConfig->IsInRandomAccountList(accountId)) + // if (!sPlayerbotAIConfig.IsInRandomAccountList(accountId)) // { // uint8 rank = player->GetRank(); // randomiser = rank < 4 ? false : true; @@ -1608,7 +1576,7 @@ bool RandomPlayerbotMgr::ProcessBot(Player* bot) LOG_DEBUG("playerbots", "Bot #{} {}:{} <{}>: randomized", botId, bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->GetLevel(), bot->GetName()); uint32 randomTime = - urand(sPlayerbotAIConfig->minRandomBotRandomizeTime, sPlayerbotAIConfig->maxRandomBotRandomizeTime); + urand(sPlayerbotAIConfig.minRandomBotRandomizeTime, sPlayerbotAIConfig.maxRandomBotRandomizeTime); ScheduleRandomize(botId, randomTime); return true; } @@ -1627,8 +1595,8 @@ bool RandomPlayerbotMgr::ProcessBot(Player* bot) LOG_DEBUG("playerbots", "Bot #{} <{}>: teleport for level and refresh", botId, bot->GetName()); Refresh(bot); RandomTeleportForLevel(bot); - uint32 time = urand(sPlayerbotAIConfig->minRandomBotTeleportInterval, - sPlayerbotAIConfig->maxRandomBotTeleportInterval); + uint32 time = urand(sPlayerbotAIConfig.minRandomBotTeleportInterval, + sPlayerbotAIConfig.maxRandomBotTeleportInterval); ScheduleTeleport(botId, time); return true; } @@ -1680,7 +1648,7 @@ void RandomPlayerbotMgr::RandomTeleport(Player* bot, std::vector& return; } - // if (sPlayerbotAIConfig->randomBotRpgChance < 0) + // if (sPlayerbotAIConfig.randomBotRpgChance < 0) // return; if (locs.empty()) @@ -1694,12 +1662,12 @@ void RandomPlayerbotMgr::RandomTeleport(Player* bot, std::vector& tlocs.push_back(WorldPosition(loc)); // Do not teleport to maps disabled in config tlocs.erase(std::remove_if(tlocs.begin(), tlocs.end(), - [bot](WorldPosition l) + [](WorldPosition l) { std::vector::iterator i = - find(sPlayerbotAIConfig->randomBotMaps.begin(), - sPlayerbotAIConfig->randomBotMaps.end(), l.getMapId()); - return i == sPlayerbotAIConfig->randomBotMaps.end(); + find(sPlayerbotAIConfig.randomBotMaps.begin(), + sPlayerbotAIConfig.randomBotMaps.end(), l.getMapId()); + return i == sPlayerbotAIConfig.randomBotMaps.end(); }), tlocs.end()); if (tlocs.empty()) @@ -1708,17 +1676,17 @@ void RandomPlayerbotMgr::RandomTeleport(Player* bot, std::vector& return; } - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "RandomTeleportByLocations"); + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "RandomTeleportByLocations"); std::shuffle(std::begin(tlocs), std::end(tlocs), RandomEngine::Instance()); for (uint32 i = 0; i < tlocs.size(); i++) { WorldLocation loc = tlocs[i]; - float x = loc.GetPositionX(); // + (attemtps > 0 ? urand(0, sPlayerbotAIConfig->grindDistance) - - // sPlayerbotAIConfig->grindDistance / 2 : 0); - float y = loc.GetPositionY(); // + (attemtps > 0 ? urand(0, sPlayerbotAIConfig->grindDistance) - - // sPlayerbotAIConfig->grindDistance / 2 : 0); + float x = loc.GetPositionX(); // + (attemtps > 0 ? urand(0, sPlayerbotAIConfig.grindDistance) - + // sPlayerbotAIConfig.grindDistance / 2 : 0); + float y = loc.GetPositionY(); // + (attemtps > 0 ? urand(0, sPlayerbotAIConfig.grindDistance) - + // sPlayerbotAIConfig.grindDistance / 2 : 0); float z = loc.GetPositionZ(); Map* map = sMapMgr->FindMap(loc.GetMapId(), 0); @@ -1869,7 +1837,7 @@ void RandomPlayerbotMgr::PrepareZone2LevelBracket() zone2LevelBracket[4197] = {79, 80}; // Wintergrasp // Override with values from config - for (auto const& [zoneId, bracketPair] : sPlayerbotAIConfig->zoneBrackets) + for (auto const& [zoneId, bracketPair] : sPlayerbotAIConfig.zoneBrackets) { zone2LevelBracket[zoneId] = {bracketPair.first, bracketPair.second}; } @@ -1877,7 +1845,7 @@ void RandomPlayerbotMgr::PrepareZone2LevelBracket() void RandomPlayerbotMgr::PrepareTeleportCache() { - uint32 maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); + int64_t maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); LOG_INFO("playerbots", "Preparing random teleport caches for {} levels...", maxLevel); @@ -1920,7 +1888,7 @@ void RandomPlayerbotMgr::PrepareTeleportCache() "INNER JOIN creature_template t on c.id1 = t.entry " "ORDER BY " "t.minlevel;", - sPlayerbotAIConfig->randomBotMapsAsString.c_str()); + sPlayerbotAIConfig.randomBotMapsAsString.c_str()); uint32 collected_locs = 0; if (results) { @@ -1931,13 +1899,13 @@ void RandomPlayerbotMgr::PrepareTeleportCache() float x = fields[1].Get(); float y = fields[2].Get(); float z = fields[3].Get(); - uint32 min_level = fields[4].Get(); - uint32 max_level = fields[5].Get(); - uint32 level = (min_level + max_level + 1) / 2; + int64_t min_level = fields[4].Get(); + int64_t max_level = fields[5].Get(); + int64_t level = (min_level + max_level + 1) / 2; WorldLocation loc(mapId, x, y, z, 0); collected_locs++; - for (int32 l = (int32)level - (int32)sPlayerbotAIConfig->randomBotTeleLowerLevel; - l <= (int32)level + (int32)sPlayerbotAIConfig->randomBotTeleHigherLevel; l++) + for (int32 l = (int32)level - (int32)sPlayerbotAIConfig.randomBotTeleLowerLevel; + l <= (int32)level + (int32)sPlayerbotAIConfig.randomBotTeleHigherLevel; l++) { if (l < 1 || l > maxLevel) { @@ -1949,7 +1917,7 @@ void RandomPlayerbotMgr::PrepareTeleportCache() } LOG_INFO("playerbots", ">> {} locations for level collected.", collected_locs); - if (sPlayerbotAIConfig->enableNewRpgStrategy) + if (sPlayerbotAIConfig.enableNewRpgStrategy) { PrepareZone2LevelBracket(); LOG_INFO("playerbots", "Preparing innkeepers / flightmasters locations for level..."); @@ -1972,7 +1940,7 @@ void RandomPlayerbotMgr::PrepareTeleportCache() "AND map IN ({}) " "ORDER BY " "t.minlevel;", - sPlayerbotAIConfig->randomBotMapsAsString.c_str()); + sPlayerbotAIConfig.randomBotMapsAsString.c_str()); collected_locs = 0; if (results) { @@ -2005,17 +1973,17 @@ void RandomPlayerbotMgr::PrepareTeleportCache() { WorldPosition pos(mapId, x, y, z, orient); if (forHorde) - sFlightMasterCache->AddHordeFlightMaster(guid, pos); + FlightMasterCache::Instance().AddHordeFlightMaster(guid, pos); if (forAlliance) - sFlightMasterCache->AddAllianceFlightMaster(guid, pos); + FlightMasterCache::Instance().AddAllianceFlightMaster(guid, pos); } const AreaTableEntry* area = sAreaTableStore.LookupEntry(map->GetAreaId(PHASEMASK_NORMAL, x, y, z)); uint32 zoneId = area->zone ? area->zone : area->ID; if (zone2LevelBracket.find(zoneId) == zone2LevelBracket.end()) continue; LevelBracket bracket = zone2LevelBracket[zoneId]; - for (int i = bracket.low; i <= bracket.high; i++) + for (uint32_t i = bracket.low; i <= bracket.high; i++) { if (forHorde) { @@ -2077,7 +2045,7 @@ void RandomPlayerbotMgr::PrepareTeleportCache() "AND map IN ({}) " "ORDER BY " "t.minlevel;", - sPlayerbotAIConfig->randomBotMapsAsString.c_str()); + sPlayerbotAIConfig.randomBotMapsAsString.c_str()); collected_locs = 0; if (results) { @@ -2157,16 +2125,16 @@ void RandomPlayerbotMgr::PrepareAddclassCache() void RandomPlayerbotMgr::Init() { - if (sPlayerbotAIConfig->addClassCommand) - sRandomPlayerbotMgr->PrepareAddclassCache(); + if (sPlayerbotAIConfig.addClassCommand) + sRandomPlayerbotMgr.PrepareAddclassCache(); - if (sPlayerbotAIConfig->enabled) + if (sPlayerbotAIConfig.enabled) { - sRandomPlayerbotMgr->PrepareTeleportCache(); + sRandomPlayerbotMgr.PrepareTeleportCache(); } - if (sPlayerbotAIConfig->randomBotJoinBG) - sRandomPlayerbotMgr->LoadBattleMastersCache(); + if (sPlayerbotAIConfig.randomBotJoinBG) + sRandomPlayerbotMgr.LoadBattleMastersCache(); PlayerbotsDatabase.Execute("DELETE FROM playerbots_random_bots WHERE event = 'add'"); } @@ -2179,17 +2147,17 @@ void RandomPlayerbotMgr::RandomTeleportForLevel(Player* bot) uint32 level = bot->GetLevel(); uint8 race = bot->getRace(); std::vector* locs = nullptr; - if (sPlayerbotAIConfig->enableNewRpgStrategy) + if (sPlayerbotAIConfig.enableNewRpgStrategy) locs = IsAlliance(race) ? &allianceStarterPerLevelCache[level] : &hordeStarterPerLevelCache[level]; else locs = &locsPerLevelCache[level]; - if (level >= 10 && urand(0, 100) < sPlayerbotAIConfig->probTeleToBankers * 100) + if (level >= 10 && urand(0, 100) < sPlayerbotAIConfig.probTeleToBankers * 100) { std::vector fallbackLocs; for (auto& bLoc : bankerLocsPerLevelCache[level]) fallbackLocs.push_back(bLoc.loc); - if (!sPlayerbotAIConfig->enableWeightTeleToCityBankers) + if (!sPlayerbotAIConfig.enableWeightTeleToCityBankers) { RandomTeleport(bot, fallbackLocs, true); return; @@ -2227,16 +2195,16 @@ void RandomPlayerbotMgr::RandomTeleportForLevel(Player* bot) int weight = 0; switch (city) { - case CityId::STORMWIND: weight = sPlayerbotAIConfig->weightTeleToStormwind; break; - case CityId::IRONFORGE: weight = sPlayerbotAIConfig->weightTeleToIronforge; break; - case CityId::DARNASSUS: weight = sPlayerbotAIConfig->weightTeleToDarnassus; break; - case CityId::EXODAR: weight = sPlayerbotAIConfig->weightTeleToExodar; break; - case CityId::ORGRIMMAR: weight = sPlayerbotAIConfig->weightTeleToOrgrimmar; break; - case CityId::UNDERCITY: weight = sPlayerbotAIConfig->weightTeleToUndercity; break; - case CityId::THUNDER_BLUFF: weight = sPlayerbotAIConfig->weightTeleToThunderBluff; break; - case CityId::SILVERMOON_CITY: weight = sPlayerbotAIConfig->weightTeleToSilvermoonCity; break; - case CityId::SHATTRATH_CITY: weight = sPlayerbotAIConfig->weightTeleToShattrathCity; break; - case CityId::DALARAN: weight = sPlayerbotAIConfig->weightTeleToDalaran; break; + case CityId::STORMWIND: weight = sPlayerbotAIConfig.weightTeleToStormwind; break; + case CityId::IRONFORGE: weight = sPlayerbotAIConfig.weightTeleToIronforge; break; + case CityId::DARNASSUS: weight = sPlayerbotAIConfig.weightTeleToDarnassus; break; + case CityId::EXODAR: weight = sPlayerbotAIConfig.weightTeleToExodar; break; + case CityId::ORGRIMMAR: weight = sPlayerbotAIConfig.weightTeleToOrgrimmar; break; + case CityId::UNDERCITY: weight = sPlayerbotAIConfig.weightTeleToUndercity; break; + case CityId::THUNDER_BLUFF: weight = sPlayerbotAIConfig.weightTeleToThunderBluff; break; + case CityId::SILVERMOON_CITY: weight = sPlayerbotAIConfig.weightTeleToSilvermoonCity; break; + case CityId::SHATTRATH_CITY: weight = sPlayerbotAIConfig.weightTeleToShattrathCity; break; + case CityId::DALARAN: weight = sPlayerbotAIConfig.weightTeleToDalaran; break; default: weight = 0; break; } if (weight <= 0) continue; @@ -2284,7 +2252,7 @@ void RandomPlayerbotMgr::RandomTeleportGrindForLevel(Player* bot) uint32 level = bot->GetLevel(); uint8 race = bot->getRace(); std::vector* locs = nullptr; - if (sPlayerbotAIConfig->enableNewRpgStrategy) + if (sPlayerbotAIConfig.enableNewRpgStrategy) locs = IsAlliance(race) ? &allianceStarterPerLevelCache[level] : &hordeStarterPerLevelCache[level]; else locs = &locsPerLevelCache[level]; @@ -2299,11 +2267,11 @@ void RandomPlayerbotMgr::RandomTeleport(Player* bot) if (bot->InBattleground()) return; - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "RandomTeleport"); + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "RandomTeleport"); std::vector locs; std::list targets; - float range = sPlayerbotAIConfig->randomBotTeleportDistance; + float range = sPlayerbotAIConfig.randomBotTeleportDistance; Acore::AnyUnitInObjectRangeCheck u_check(bot, range); Acore::UnitListSearcher searcher(bot, targets, u_check); Cell::VisitObjects(bot, searcher, range); @@ -2313,7 +2281,7 @@ void RandomPlayerbotMgr::RandomTeleport(Player* bot) for (Unit* unit : targets) { bot->UpdatePosition(*unit); - FleeManager manager(bot, sPlayerbotAIConfig->sightDistance, 0, true); + FleeManager manager(bot, sPlayerbotAIConfig.sightDistance, 0, true); float rx, ry, rz; if (manager.CalculateDestination(&rx, &ry, &rz)) { @@ -2342,7 +2310,7 @@ void RandomPlayerbotMgr::Randomize(Player* bot) { RandomizeFirst(bot); } - else if (bot->GetLevel() < sPlayerbotAIConfig->randomBotMaxLevel || !sPlayerbotAIConfig->downgradeMaxLevelBot) + else if (bot->GetLevel() < sPlayerbotAIConfig.randomBotMaxLevel || !sPlayerbotAIConfig.downgradeMaxLevelBot) { uint8 level = bot->GetLevel(); PlayerbotFactory factory(bot, level); @@ -2357,11 +2325,11 @@ void RandomPlayerbotMgr::Randomize(Player* bot) void RandomPlayerbotMgr::IncreaseLevel(Player* bot) { - uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; + uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "IncreaseLevel"); + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "IncreaseLevel"); uint32 lastLevel = GetValue(bot, "level"); uint8 level = bot->GetLevel() + 1; if (level > maxLevel) @@ -2384,27 +2352,27 @@ void RandomPlayerbotMgr::RandomizeFirst(Player* bot) if (!botAI) return; - uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; + uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); // if lvl sync is enabled, max level is limited by online players lvl - if (sPlayerbotAIConfig->syncLevelWithPlayers) - maxLevel = std::max(sPlayerbotAIConfig->randomBotMinLevel, + if (sPlayerbotAIConfig.syncLevelWithPlayers) + maxLevel = std::max(sPlayerbotAIConfig.randomBotMinLevel, std::min(playersLevel, sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))); - uint32 minLevel = sPlayerbotAIConfig->randomBotMinLevel; + uint32 minLevel = sPlayerbotAIConfig.randomBotMinLevel; if (bot->getClass() == CLASS_DEATH_KNIGHT) { maxLevel = std::max(maxLevel, sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)); minLevel = std::max(minLevel, sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)); } - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "RandomizeFirst"); + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "RandomizeFirst"); uint32 level; - if (sPlayerbotAIConfig->downgradeMaxLevelBot && bot->GetLevel() >= sPlayerbotAIConfig->randomBotMaxLevel) + if (sPlayerbotAIConfig.downgradeMaxLevelBot && bot->GetLevel() >= sPlayerbotAIConfig.randomBotMaxLevel) { if (bot->getClass() == CLASS_DEATH_KNIGHT) { @@ -2412,18 +2380,18 @@ void RandomPlayerbotMgr::RandomizeFirst(Player* bot) } else { - level = sPlayerbotAIConfig->randomBotMinLevel; + level = sPlayerbotAIConfig.randomBotMinLevel; } } else { uint32 roll = urand(1, 100); - if (roll <= 100 * sPlayerbotAIConfig->randomBotMaxLevelChance) + if (roll <= 100 * sPlayerbotAIConfig.randomBotMaxLevelChance) { level = maxLevel; } else if (roll <= - (100 * (sPlayerbotAIConfig->randomBotMaxLevelChance + sPlayerbotAIConfig->randomBotMinLevelChance))) + (100 * (sPlayerbotAIConfig.randomBotMaxLevelChance + sPlayerbotAIConfig.randomBotMinLevelChance))) { level = minLevel; } @@ -2433,11 +2401,11 @@ void RandomPlayerbotMgr::RandomizeFirst(Player* bot) } } - if (sPlayerbotAIConfig->disableRandomLevels) + if (sPlayerbotAIConfig.disableRandomLevels) { - level = bot->getClass() == CLASS_DEATH_KNIGHT ? std::max(sPlayerbotAIConfig->randombotStartingLevel, + level = bot->getClass() == CLASS_DEATH_KNIGHT ? std::max(sPlayerbotAIConfig.randombotStartingLevel, sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)) - : sPlayerbotAIConfig->randombotStartingLevel; + : sPlayerbotAIConfig.randombotStartingLevel; } SetValue(bot, "level", level); @@ -2445,9 +2413,9 @@ void RandomPlayerbotMgr::RandomizeFirst(Player* bot) factory.Randomize(false); uint32 randomTime = - urand(sPlayerbotAIConfig->minRandomBotRandomizeTime, sPlayerbotAIConfig->maxRandomBotRandomizeTime); + urand(sPlayerbotAIConfig.minRandomBotRandomizeTime, sPlayerbotAIConfig.maxRandomBotRandomizeTime); uint32 inworldTime = - urand(sPlayerbotAIConfig->minRandomBotInWorldTime, sPlayerbotAIConfig->maxRandomBotInWorldTime); + urand(sPlayerbotAIConfig.minRandomBotInWorldTime, sPlayerbotAIConfig.maxRandomBotInWorldTime); PlayerbotsDatabasePreparedStatement* stmt = PlayerbotsDatabase.GetPreparedStatement(PLAYERBOTS_UPD_RANDOM_BOTS); stmt->SetData(0, randomTime); @@ -2479,16 +2447,16 @@ void RandomPlayerbotMgr::RandomizeMin(Player* bot) if (!botAI) return; - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "RandomizeMin"); - uint32 level = sPlayerbotAIConfig->randomBotMinLevel; + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "RandomizeMin"); + uint32 level = sPlayerbotAIConfig.randomBotMinLevel; SetValue(bot, "level", level); PlayerbotFactory factory(bot, level); factory.Randomize(false); uint32 randomTime = - urand(sPlayerbotAIConfig->minRandomBotRandomizeTime, sPlayerbotAIConfig->maxRandomBotRandomizeTime); + urand(sPlayerbotAIConfig.minRandomBotRandomizeTime, sPlayerbotAIConfig.maxRandomBotRandomizeTime); uint32 inworldTime = - urand(sPlayerbotAIConfig->minRandomBotInWorldTime, sPlayerbotAIConfig->maxRandomBotInWorldTime); + urand(sPlayerbotAIConfig.minRandomBotInWorldTime, sPlayerbotAIConfig.maxRandomBotInWorldTime); PlayerbotsDatabasePreparedStatement* stmt = PlayerbotsDatabase.GetPreparedStatement(PLAYERBOTS_UPD_RANDOM_BOTS); stmt->SetData(0, randomTime); @@ -2518,7 +2486,7 @@ void RandomPlayerbotMgr::Clear(Player* bot) factory.ClearEverything(); } -uint32 RandomPlayerbotMgr::GetZoneLevel(uint16 mapId, float teleX, float teleY, float teleZ) +uint32 RandomPlayerbotMgr::GetZoneLevel(uint16 mapId, float teleX, float teleY, float) { uint32 maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); @@ -2527,8 +2495,8 @@ uint32 RandomPlayerbotMgr::GetZoneLevel(uint16 mapId, float teleX, float teleY, "SELECT AVG(t.minlevel) minlevel, AVG(t.maxlevel) maxlevel FROM creature c " "INNER JOIN creature_template t ON c.id1 = t.entry WHERE map = {} AND minlevel > 1 AND ABS(position_x - {}) < " "{} AND ABS(position_y - {}) < {}", - mapId, teleX, sPlayerbotAIConfig->randomBotTeleportDistance / 2, teleY, - sPlayerbotAIConfig->randomBotTeleportDistance / 2); + mapId, teleX, sPlayerbotAIConfig.randomBotTeleportDistance / 2, teleY, + sPlayerbotAIConfig.randomBotTeleportDistance / 2); if (results) { @@ -2560,7 +2528,7 @@ void RandomPlayerbotMgr::Refresh(Player* bot) botAI->ResetStrategies(false); } - // if (sPlayerbotAIConfig->disableRandomLevels) + // if (sPlayerbotAIConfig.disableRandomLevels) // return; if (bot->InBattleground()) @@ -2568,7 +2536,7 @@ void RandomPlayerbotMgr::Refresh(Player* bot) LOG_DEBUG("playerbots", "Refreshing bot {} <{}>", bot->GetGUID().ToString().c_str(), bot->GetName().c_str()); - PerfMonitorOperation* pmo = sPerfMonitor->start(PERF_MON_RNDBOT, "Refresh"); + PerfMonitorOperation* pmo = sPerfMonitor.start(PERF_MON_RNDBOT, "Refresh"); botAI->Reset(); @@ -2612,7 +2580,7 @@ bool RandomPlayerbotMgr::IsRandomBot(Player* bot) bool RandomPlayerbotMgr::IsRandomBot(ObjectGuid::LowType bot) { ObjectGuid guid = ObjectGuid::Create(bot); - if (!sPlayerbotAIConfig->IsInRandomAccountList(sCharacterCache->GetCharacterAccountIdByGuid(guid))) + if (!sPlayerbotAIConfig.IsInRandomAccountList(sCharacterCache->GetCharacterAccountIdByGuid(guid))) return false; if (std::find(currentBots.begin(), currentBots.end(), bot) != currentBots.end()) @@ -2711,7 +2679,7 @@ std::vector RandomPlayerbotMgr::GetBgBots(uint32 bracket) } while (result->NextRow()); } - return std::move(BgBots); + return BgBots; } CachedEvent* RandomPlayerbotMgr::FindEvent(uint32 bot, std::string const& event) @@ -2841,7 +2809,7 @@ std::string RandomPlayerbotMgr::GetData(uint32 bot, std::string const& type) { r void RandomPlayerbotMgr::SetValue(uint32 bot, std::string const& type, uint32 value, std::string const& data) { - SetEventValue(bot, type, value, sPlayerbotAIConfig->maxRandomBotInWorldTime, data); + SetEventValue(bot, type, value, sPlayerbotAIConfig.maxRandomBotInWorldTime, data); } void RandomPlayerbotMgr::SetValue(Player* bot, std::string const& type, uint32 value, std::string const& data) @@ -2849,9 +2817,9 @@ void RandomPlayerbotMgr::SetValue(Player* bot, std::string const& type, uint32 v SetValue(bot->GetGUID().GetCounter(), type, value, data); } -bool RandomPlayerbotMgr::HandlePlayerbotConsoleCommand(ChatHandler* handler, char const* args) +bool RandomPlayerbotMgr::HandlePlayerbotConsoleCommand(ChatHandler*, char const* args) { - if (!sPlayerbotAIConfig->enabled) + if (!sPlayerbotAIConfig.enabled) { LOG_ERROR("playerbots", "Playerbots system is currently disabled!"); return false; @@ -2868,27 +2836,27 @@ bool RandomPlayerbotMgr::HandlePlayerbotConsoleCommand(ChatHandler* handler, cha if (cmd == "reset") { PlayerbotsDatabase.Execute(PlayerbotsDatabase.GetPreparedStatement(PLAYERBOTS_DEL_RANDOM_BOTS)); - sRandomPlayerbotMgr->eventCache.clear(); + sRandomPlayerbotMgr.eventCache.clear(); LOG_INFO("playerbots", "Random bots were reset for all players. Please restart the Server."); return true; } if (cmd == "stats") { - sRandomPlayerbotMgr->PrintStats(); + sRandomPlayerbotMgr.PrintStats(); // activatePrintStatsThread(); return true; } if (cmd == "reload") { - sPlayerbotAIConfig->Initialize(); + sPlayerbotAIConfig.Initialize(); return true; } if (cmd == "update") { - sRandomPlayerbotMgr->UpdateAIInternal(0); + sRandomPlayerbotMgr.UpdateAIInternal(0); return true; } @@ -2913,8 +2881,8 @@ bool RandomPlayerbotMgr::HandlePlayerbotConsoleCommand(ChatHandler* handler, cha std::string const name = cmd.size() > prefix.size() + 1 ? cmd.substr(1 + prefix.size()) : "%"; std::vector botIds; - for (std::vector::iterator i = sPlayerbotAIConfig->randomBotAccounts.begin(); - i != sPlayerbotAIConfig->randomBotAccounts.end(); ++i) + for (std::vector::iterator i = sPlayerbotAIConfig.randomBotAccounts.begin(); + i != sPlayerbotAIConfig.randomBotAccounts.end(); ++i) { uint32 account = *i; if (QueryResult results = CharacterDatabase.Query( @@ -2926,7 +2894,7 @@ bool RandomPlayerbotMgr::HandlePlayerbotConsoleCommand(ChatHandler* handler, cha uint32 botId = fields[0].Get(); ObjectGuid guid = ObjectGuid::Create(botId); - if (!sRandomPlayerbotMgr->IsRandomBot(guid.GetCounter())) + if (!sRandomPlayerbotMgr.IsRandomBot(guid.GetCounter())) { continue; } @@ -2957,13 +2925,13 @@ bool RandomPlayerbotMgr::HandlePlayerbotConsoleCommand(ChatHandler* handler, cha bot->GetName().c_str()); ConsoleCommandHandler handler = j->second; - (sRandomPlayerbotMgr->*handler)(bot); + (sRandomPlayerbotMgr.*handler)(bot); } return true; } - // std::vector messages = sRandomPlayerbotMgr->HandlePlayerbotCommand(args); + // std::vector messages = sRandomPlayerbotMgr.HandlePlayerbotCommand(args); // for (std::vector::iterator i = messages.begin(); i != messages.end(); ++i) // { // LOG_INFO("playerbots", "{}", i->c_str()); @@ -3021,15 +2989,15 @@ void RandomPlayerbotMgr::OnBotLoginInternal(Player* const bot) if (_isBotLogging) { LOG_INFO("playerbots", "{}/{} Bot {} logged in", playerBots.size(), - sRandomPlayerbotMgr->GetMaxAllowedBotCount(), bot->GetName().c_str()); + sRandomPlayerbotMgr.GetMaxAllowedBotCount(), bot->GetName().c_str()); - if (playerBots.size() == sRandomPlayerbotMgr->GetMaxAllowedBotCount()) + if (playerBots.size() == sRandomPlayerbotMgr.GetMaxAllowedBotCount()) { _isBotLogging = false; } } - if (sPlayerbotAIConfig->randomBotFixedLevel) + if (sPlayerbotAIConfig.randomBotFixedLevel) { bot->SetPlayerFlag(PLAYER_FLAGS_NO_XP_GAIN); } @@ -3081,18 +3049,18 @@ void RandomPlayerbotMgr::OnPlayerLogin(Player* player) { WorldPosition botPos(player); - // botPos.GetReachableRandomPointOnGround(player, sPlayerbotAIConfig->reactDistance * 2, true); + // botPos.GetReachableRandomPointOnGround(player, sPlayerbotAIConfig.reactDistance * 2, true); // player->TeleportTo(botPos); // player->Relocate(botPos.coord_x, botPos.coord_y, botPos.coord_z, botPos.orientation); if (!player->GetFactionTemplateEntry()) { - botPos.GetReachableRandomPointOnGround(player, sPlayerbotAIConfig->reactDistance * 2, true); + botPos.GetReachableRandomPointOnGround(player, sPlayerbotAIConfig.reactDistance * 2, true); } else { - std::vector dests = sTravelMgr->getRpgTravelDestinations(player, true, true, 200000.0f); + std::vector dests = TravelMgr::instance().getRpgTravelDestinations(player, true, true, 200000.0f); do { @@ -3178,10 +3146,6 @@ void RandomPlayerbotMgr::PrintStats() uint32 heal = 0; uint32 tank = 0; uint32 active = 0; - uint32 update = 0; - uint32 randomize = 0; - uint32 teleport = 0; - uint32 changeStrategy = 0; uint32 dead = 0; uint32 combat = 0; // uint32 revive = 0; //not used, line marked for removal. @@ -3222,19 +3186,6 @@ void RandomPlayerbotMgr::PrintStats() if (botAI->AllowActivity()) ++active; - if (botAI->GetAiObjectContext()->GetValue("random bot update")->Get()) - ++update; - - uint32 botId = bot->GetGUID().GetCounter(); - if (!GetEventValue(botId, "randomize")) - ++randomize; - - if (!GetEventValue(botId, "teleport")) - ++teleport; - - if (!GetEventValue(botId, "change_strategy")) - ++changeStrategy; - if (bot->isDead()) { ++dead; @@ -3281,7 +3232,7 @@ void RandomPlayerbotMgr::PrintStats() zoneCount[bot->GetZoneId()]++; - if (sPlayerbotAIConfig->enableNewRpgStrategy) + if (sPlayerbotAIConfig.enableNewRpgStrategy) { rpgStatusCount[botAI->rpgInfo.status]++; rpgStasticTotal += botAI->rpgStatistic; @@ -3355,7 +3306,7 @@ void RandomPlayerbotMgr::PrintStats() LOG_INFO("playerbots", " In Rest: {}", rest); LOG_INFO("playerbots", " Dead: {}", dead); - if (sPlayerbotAIConfig->enableNewRpgStrategy) + if (sPlayerbotAIConfig.enableNewRpgStrategy) { LOG_INFO("playerbots", "Bots rpg status:"); LOG_INFO("playerbots", @@ -3381,8 +3332,8 @@ double RandomPlayerbotMgr::GetBuyMultiplier(Player* bot) if (!value) { value = urand(50, 120); - uint32 validIn = urand(sPlayerbotAIConfig->minRandomBotsPriceChangeInterval, - sPlayerbotAIConfig->maxRandomBotsPriceChangeInterval); + uint32 validIn = urand(sPlayerbotAIConfig.minRandomBotsPriceChangeInterval, + sPlayerbotAIConfig.maxRandomBotsPriceChangeInterval); SetEventValue(id, "buymultiplier", value, validIn); } @@ -3396,8 +3347,8 @@ double RandomPlayerbotMgr::GetSellMultiplier(Player* bot) if (!value) { value = urand(80, 250); - uint32 validIn = urand(sPlayerbotAIConfig->minRandomBotsPriceChangeInterval, - sPlayerbotAIConfig->maxRandomBotsPriceChangeInterval); + uint32 validIn = urand(sPlayerbotAIConfig.minRandomBotsPriceChangeInterval, + sPlayerbotAIConfig.maxRandomBotsPriceChangeInterval); SetEventValue(id, "sellmultiplier", value, validIn); } @@ -3426,7 +3377,7 @@ void RandomPlayerbotMgr::SetTradeDiscount(Player* bot, Player* master, uint32 va std::ostringstream name; name << "trade_discount_" << masterId; - SetEventValue(botId, name.str(), value, sPlayerbotAIConfig->maxRandomBotInWorldTime); + SetEventValue(botId, name.str(), value, sPlayerbotAIConfig.maxRandomBotInWorldTime); } uint32 RandomPlayerbotMgr::GetTradeDiscount(Player* bot, Player* master) @@ -3469,7 +3420,7 @@ void RandomPlayerbotMgr::ChangeStrategy(Player* player) { uint32 bot = player->GetGUID().GetCounter(); - if (frand(0.f, 100.f) > sPlayerbotAIConfig->randomBotRpgChance) + if (frand(0.f, 100.f) > sPlayerbotAIConfig.randomBotRpgChance) { LOG_INFO("playerbots", "Bot #{} <{}>: sent to grind spot", bot, player->GetName().c_str()); ScheduleTeleport(bot, 30); @@ -3479,7 +3430,7 @@ void RandomPlayerbotMgr::ChangeStrategy(Player* player) LOG_INFO("playerbots", "Changing strategy for bot #{} <{}> to RPG", bot, player->GetName().c_str()); LOG_INFO("playerbots", "Bot #{} <{}>: sent to inn", bot, player->GetName().c_str()); RandomTeleportForLevel(player); - SetEventValue(bot, "teleport", 1, sPlayerbotAIConfig->maxRandomBotInWorldTime); + SetEventValue(bot, "teleport", 1, sPlayerbotAIConfig.maxRandomBotInWorldTime); } ScheduleChangeStrategy(bot); @@ -3489,7 +3440,7 @@ void RandomPlayerbotMgr::ChangeStrategyOnce(Player* player) { uint32 bot = player->GetGUID().GetCounter(); - if (frand(0.f, 100.f) > sPlayerbotAIConfig->randomBotRpgChance) // select grind / pvp + if (frand(0.f, 100.f) > sPlayerbotAIConfig.randomBotRpgChance) // select grind / pvp { LOG_INFO("playerbots", "Bot #{} <{}>: sent to grind spot", bot, player->GetName().c_str()); RandomTeleportForLevel(player); @@ -3565,7 +3516,7 @@ ObjectGuid RandomPlayerbotMgr::GetBattleMasterGUID(Player* bot, BattlegroundType for (auto i = begin(Bms); i != end(Bms); ++i) { - CreatureData const* data = sRandomPlayerbotMgr->GetCreatureDataByEntry(*i); + CreatureData const* data = sRandomPlayerbotMgr.GetCreatureDataByEntry(*i); if (!data) continue; @@ -3596,7 +3547,7 @@ ObjectGuid RandomPlayerbotMgr::GetBattleMasterGUID(Player* bot, BattlegroundType if (Bm->getDeathState() == DeathState::Dead) continue; - float dist2 = sServerFacade->GetDistance2d(bot, data->posX, data->posY); + float dist2 = ServerFacade::instance().GetDistance2d(bot, data->posX, data->posY); if (dist2 < dist1) { dist1 = dist2; diff --git a/src/Bot/RandomPlayerbotMgr.h b/src/Bot/RandomPlayerbotMgr.h index 26d09d454e..94c0a01513 100644 --- a/src/Bot/RandomPlayerbotMgr.h +++ b/src/Bot/RandomPlayerbotMgr.h @@ -10,6 +10,7 @@ #include "ObjectGuid.h" #include "PlayerbotMgr.h" #include "GameTime.h" +#include "PlayerbotCommandServer.h" struct BattlegroundInfo { @@ -88,12 +89,11 @@ class botPID class RandomPlayerbotMgr : public PlayerbotHolder { public: - RandomPlayerbotMgr(); - virtual ~RandomPlayerbotMgr(); - static RandomPlayerbotMgr* instance() + static RandomPlayerbotMgr& instance() { static RandomPlayerbotMgr instance; - return &instance; + + return instance; } void LogPlayerLocation(); @@ -192,6 +192,43 @@ class RandomPlayerbotMgr : public PlayerbotHolder void OnBotLoginInternal(Player* const bot) override; private: + RandomPlayerbotMgr() : PlayerbotHolder(), processTicks(0) + { + this->playersLevel = sPlayerbotAIConfig.randombotStartingLevel; + + if (sPlayerbotAIConfig.enabled || sPlayerbotAIConfig.randomBotAutologin) + { + PlayerbotCommandServer::instance().Start(); + } + + BattlegroundData.clear(); // Clear here and here only. + + // Cleanup on server start: orphaned pet data that's often left behind by bot pets that no longer exist in the DB + CharacterDatabase.Execute("DELETE FROM pet_aura WHERE guid NOT IN (SELECT id FROM character_pet)"); + CharacterDatabase.Execute("DELETE FROM pet_spell WHERE guid NOT IN (SELECT id FROM character_pet)"); + CharacterDatabase.Execute("DELETE FROM pet_spell_cooldown WHERE guid NOT IN (SELECT id FROM character_pet)"); + + for (int bracket = BG_BRACKET_ID_FIRST; bracket < MAX_BATTLEGROUND_BRACKETS; ++bracket) + { + for (int queueType = BATTLEGROUND_QUEUE_AV; queueType < MAX_BATTLEGROUND_QUEUE_TYPES; ++queueType) + { + this->BattlegroundData[queueType][bracket] = BattlegroundInfo(); + } + } + + this->BgCheckTimer = 0; + this->LfgCheckTimer = 0; + this->PlayersCheckTimer = 0; + } + + ~RandomPlayerbotMgr() = default; + + RandomPlayerbotMgr(const RandomPlayerbotMgr&) = delete; + RandomPlayerbotMgr& operator=(const RandomPlayerbotMgr&) = delete; + + RandomPlayerbotMgr(RandomPlayerbotMgr&&) = delete; + RandomPlayerbotMgr& operator=(RandomPlayerbotMgr&&) = delete; + // pid values are set in constructor botPID pid = botPID(1, 50, -50, 0, 0, 0); float activityMod = 0.25; diff --git a/src/Db/FlightMasterCache.cpp b/src/Db/FlightMasterCache.cpp index c708e09cb8..effe249936 100644 --- a/src/Db/FlightMasterCache.cpp +++ b/src/Db/FlightMasterCache.cpp @@ -13,7 +13,7 @@ void FlightMasterCache::AddAllianceFlightMaster(uint32 entry, WorldPosition pos) Creature* FlightMasterCache::GetNearestFlightMaster(Player* bot) { std::map& flightMasterCache = - (bot->GetTeamId() == ALLIANCE) ? allianceFlightMasterCache : hordeFlightMasterCache; + (bot->GetTeamId() == TEAM_ALLIANCE) ? allianceFlightMasterCache : hordeFlightMasterCache; Creature* nearestFlightMaster = nullptr; float nearestDistance = std::numeric_limits::max(); diff --git a/src/Db/FlightMasterCache.h b/src/Db/FlightMasterCache.h index 519d6fc7c8..7f8b95310d 100644 --- a/src/Db/FlightMasterCache.h +++ b/src/Db/FlightMasterCache.h @@ -8,10 +8,11 @@ class FlightMasterCache { public: - static FlightMasterCache* Instance() + static FlightMasterCache& Instance() { static FlightMasterCache instance; - return &instance; + + return instance; } Creature* GetNearestFlightMaster(Player* bot); @@ -19,9 +20,17 @@ class FlightMasterCache void AddAllianceFlightMaster(uint32 entry, WorldPosition pos); private: + FlightMasterCache() = default; + ~FlightMasterCache() = default; + + FlightMasterCache(const FlightMasterCache&) = delete; + FlightMasterCache& operator=(const FlightMasterCache&) = delete; + + FlightMasterCache(FlightMasterCache&&) = delete; + FlightMasterCache& operator=(FlightMasterCache&&) = delete; + std::map allianceFlightMasterCache; std::map hordeFlightMasterCache; }; -#define sFlightMasterCache FlightMasterCache::Instance() #endif diff --git a/src/Db/PlayerbotDungeonRepository.cpp b/src/Db/PlayerbotDungeonRepository.cpp index 3ee40e5616..5e1f370b6a 100644 --- a/src/Db/PlayerbotDungeonRepository.cpp +++ b/src/Db/PlayerbotDungeonRepository.cpp @@ -3,9 +3,15 @@ * and/or modify it under version 3 of the License, or (at your option), any later version. */ -#include "PlayerbotDungeonRepository.h" +#include "Log.h" +#include "Timer.h" +#include "DatabaseEnv.h" +#include "Field.h" +#include "World.h" +// Required import due to poor implementation by AC +#include "QueryResult.h" -#include "Playerbots.h" +#include "PlayerbotDungeonRepository.h" std::vector const PlayerbotDungeonRepository::GetDungeonSuggestions() { diff --git a/src/Db/PlayerbotDungeonRepository.h b/src/Db/PlayerbotDungeonRepository.h index 8c709152a8..160a7622c3 100644 --- a/src/Db/PlayerbotDungeonRepository.h +++ b/src/Db/PlayerbotDungeonRepository.h @@ -6,10 +6,9 @@ #ifndef _PLAYERBOT_PLAYERBOTDUNGEONREPOSITORY_H #define _PLAYERBOT_PLAYERBOTDUNGEONREPOSITORY_H -#include #include +#include -#include "Common.h" #include "DBCEnums.h" struct DungeonSuggestion @@ -22,24 +21,31 @@ struct DungeonSuggestion std::string strategy; }; +// @TODO: Completely unused at this moment. class PlayerbotDungeonRepository { public: - PlayerbotDungeonRepository(){}; - ~PlayerbotDungeonRepository(){}; - static PlayerbotDungeonRepository* instance() + static PlayerbotDungeonRepository& instance() { static PlayerbotDungeonRepository instance; - return &instance; + + return instance; } void LoadDungeonSuggestions(); std::vector const GetDungeonSuggestions(); private: + PlayerbotDungeonRepository() = default; + ~PlayerbotDungeonRepository() = default; + + PlayerbotDungeonRepository(const PlayerbotDungeonRepository&) = delete; + PlayerbotDungeonRepository& operator=(const PlayerbotDungeonRepository&) = delete; + + PlayerbotDungeonRepository(PlayerbotDungeonRepository&&) = delete; + PlayerbotDungeonRepository& operator=(PlayerbotDungeonRepository&&) = delete; + std::vector m_dungeonSuggestions; }; -#define sPlayerbotDungeonRepository PlayerbotDungeonRepository::instance() - #endif diff --git a/src/Db/PlayerbotRepository.cpp b/src/Db/PlayerbotRepository.cpp index 886cebb833..6d2d519d86 100644 --- a/src/Db/PlayerbotRepository.cpp +++ b/src/Db/PlayerbotRepository.cpp @@ -4,10 +4,7 @@ */ #include "PlayerbotRepository.h" - -#include - -#include "Playerbots.h" +#include "AiObjectContext.h" void PlayerbotRepository::Load(PlayerbotAI* botAI) { @@ -68,7 +65,7 @@ void PlayerbotRepository::Save(PlayerbotAI* botAI) SaveValue(guid, "dead", FormatStrategies("dead", botAI->GetStrategies(BOT_STATE_DEAD))); } -std::string const PlayerbotRepository::FormatStrategies(std::string const type, std::vector strategies) +std::string const PlayerbotRepository::FormatStrategies(std::string const, std::vector strategies) { std::ostringstream out; for (std::vector::iterator i = strategies.begin(); i != strategies.end(); ++i) diff --git a/src/Db/PlayerbotRepository.h b/src/Db/PlayerbotRepository.h index 90dbce54af..b7b9b4b3cc 100644 --- a/src/Db/PlayerbotRepository.h +++ b/src/Db/PlayerbotRepository.h @@ -6,21 +6,20 @@ #ifndef _PLAYERBOT_PLAYERBOTREPOSITORY_H #define _PLAYERBOT_PLAYERBOTREPOSITORY_H +#include +#include #include -#include "Common.h" - -class PlayerbotAI; +#include "PlayerbotAI.h" class PlayerbotRepository { public: - PlayerbotRepository() {} - virtual ~PlayerbotRepository() {} - static PlayerbotRepository* instance() + static PlayerbotRepository& instance() { static PlayerbotRepository instance; - return &instance; + + return instance; } void Save(PlayerbotAI* botAI); @@ -28,10 +27,17 @@ class PlayerbotRepository void Reset(PlayerbotAI* botAI); private: - void SaveValue(uint32 guid, std::string const key, std::string const value); + PlayerbotRepository() = default; + ~PlayerbotRepository() = default; + + PlayerbotRepository(const PlayerbotRepository&) = delete; + PlayerbotRepository& operator=(const PlayerbotRepository&) = delete; + + PlayerbotRepository(PlayerbotRepository&&) = delete; + PlayerbotRepository& operator=(PlayerbotRepository&&) = delete; + + void SaveValue(uint32_t guid, std::string const key, std::string const value); std::string const FormatStrategies(std::string const type, std::vector strategies); }; -#define sPlayerbotRepository PlayerbotRepository::instance() - #endif diff --git a/src/Db/PlayerbotSpellRepository.cpp b/src/Db/PlayerbotSpellRepository.cpp index 6642eeeea2..7cb6dfaffc 100644 --- a/src/Db/PlayerbotSpellRepository.cpp +++ b/src/Db/PlayerbotSpellRepository.cpp @@ -1,5 +1,13 @@ +#include "Log.h" +#include "DBCStores.h" +#include "DatabaseEnv.h" +#include "Field.h" +// Required due to poor implementation on AC side +#include "QueryResult.h" + #include "PlayerbotSpellRepository.h" + // caches the result set void PlayerbotSpellRepository::Initialize() { diff --git a/src/Db/PlayerbotSpellRepository.h b/src/Db/PlayerbotSpellRepository.h index 55046e5956..7b026dd296 100644 --- a/src/Db/PlayerbotSpellRepository.h +++ b/src/Db/PlayerbotSpellRepository.h @@ -6,29 +6,37 @@ #ifndef _PLAYERBOT_PLAYERBOTSPELLREPOSITORY_H #define _PLAYERBOT_PLAYERBOTSPELLREPOSITORY_H -#include "Playerbots.h" +#include + +#include "DBCStructure.h" class PlayerbotSpellRepository { public: - static PlayerbotSpellRepository* Instance() + static PlayerbotSpellRepository& Instance() { static PlayerbotSpellRepository instance; - return &instance; + + return instance; } - void Initialize(); // call once on startup + void Initialize(); - SkillLineAbilityEntry const* GetSkillLine(uint32 spellId) const; - bool IsItemBuyable(uint32 itemId) const; + SkillLineAbilityEntry const* GetSkillLine(uint32_t spellId) const; + bool IsItemBuyable(uint32_t itemId) const; private: PlayerbotSpellRepository() = default; + ~PlayerbotSpellRepository() = default; - std::map skillSpells; - std::set vendorItems; -}; + PlayerbotSpellRepository(const PlayerbotSpellRepository&) = delete; + PlayerbotSpellRepository& operator=(const PlayerbotSpellRepository&) = delete; -#define sPlayerbotSpellRepository PlayerbotSpellRepository::Instance() + PlayerbotSpellRepository(PlayerbotSpellRepository&&) = delete; + PlayerbotSpellRepository& operator=(PlayerbotSpellRepository&&) = delete; + + std::map skillSpells; + std::set vendorItems; +}; #endif diff --git a/src/Mgr/Guild/GuildTaskMgr.cpp b/src/Mgr/Guild/GuildTaskMgr.cpp index 8fb4711dd7..96162c044a 100644 --- a/src/Mgr/Guild/GuildTaskMgr.cpp +++ b/src/Mgr/Guild/GuildTaskMgr.cpp @@ -26,14 +26,14 @@ enum GuildTaskType void GuildTaskMgr::Update(Player* player, Player* guildMaster) { - if (!sPlayerbotAIConfig->guildTaskEnabled) + if (!sPlayerbotAIConfig.guildTaskEnabled) return; if (!GetTaskValue(0, 0, "advert_cleanup")) { CleanupAdverts(); RemoveDuplicatedAdverts(); - SetTaskValue(0, 0, "advert_cleanup", 1, sPlayerbotAIConfig->guildTaskAdvertCleanupTime); + SetTaskValue(0, 0, "advert_cleanup", 1, sPlayerbotAIConfig.guildTaskAdvertCleanupTime); } PlayerbotAI* masterBotAI = GET_PLAYERBOT_AI(guildMaster); @@ -69,8 +69,8 @@ void GuildTaskMgr::Update(Player* player, Player* guildMaster) SetTaskValue(owner, guildId, "killTask", 0, 0); SetTaskValue(owner, guildId, "killCount", 0, 0); SetTaskValue(owner, guildId, "payment", 0, 0); - SetTaskValue(owner, guildId, "thanks", 1, 2 * sPlayerbotAIConfig->maxGuildTaskChangeTime); - SetTaskValue(owner, guildId, "reward", 1, 2 * sPlayerbotAIConfig->maxGuildTaskChangeTime); + SetTaskValue(owner, guildId, "thanks", 1, 2 * sPlayerbotAIConfig.maxGuildTaskChangeTime); + SetTaskValue(owner, guildId, "reward", 1, 2 * sPlayerbotAIConfig.maxGuildTaskChangeTime); uint32 task = CreateTask(player, guildId); @@ -80,11 +80,11 @@ void GuildTaskMgr::Update(Player* player, Player* guildMaster) player->GetName().c_str()); } - uint32 time = urand(sPlayerbotAIConfig->minGuildTaskChangeTime, sPlayerbotAIConfig->maxGuildTaskChangeTime); + uint32 time = urand(sPlayerbotAIConfig.minGuildTaskChangeTime, sPlayerbotAIConfig.maxGuildTaskChangeTime); SetTaskValue(owner, guildId, "activeTask", task, time); SetTaskValue(owner, guildId, "advertisement", 1, - urand(sPlayerbotAIConfig->minGuildTaskAdvertisementTime, - sPlayerbotAIConfig->maxGuildTaskAdvertisementTime)); + urand(sPlayerbotAIConfig.minGuildTaskAdvertisementTime, + sPlayerbotAIConfig.maxGuildTaskAdvertisementTime)); LOG_DEBUG("playerbots", "{} / {}: guild task {} is set for {} secs", guild->GetName().c_str(), player->GetName().c_str(), task, time); @@ -101,8 +101,8 @@ void GuildTaskMgr::Update(Player* player, Player* guildMaster) if (SendAdvertisement(trans, owner, guildId)) { SetTaskValue(owner, guildId, "advertisement", 1, - urand(sPlayerbotAIConfig->minGuildTaskAdvertisementTime, - sPlayerbotAIConfig->maxGuildTaskAdvertisementTime)); + urand(sPlayerbotAIConfig.minGuildTaskAdvertisementTime, + sPlayerbotAIConfig.maxGuildTaskAdvertisementTime)); } else { @@ -118,7 +118,7 @@ void GuildTaskMgr::Update(Player* player, Player* guildMaster) if (SendThanks(trans, owner, guildId, GetTaskValue(owner, guildId, "payment"))) { - SetTaskValue(owner, guildId, "thanks", 1, 2 * sPlayerbotAIConfig->maxGuildTaskChangeTime); + SetTaskValue(owner, guildId, "thanks", 1, 2 * sPlayerbotAIConfig.maxGuildTaskChangeTime); SetTaskValue(owner, guildId, "payment", 0, 0); } else @@ -135,7 +135,7 @@ void GuildTaskMgr::Update(Player* player, Player* guildMaster) if (Reward(trans, owner, guildId)) { - SetTaskValue(owner, guildId, "reward", 1, 2 * sPlayerbotAIConfig->maxGuildTaskChangeTime); + SetTaskValue(owner, guildId, "reward", 1, 2 * sPlayerbotAIConfig.maxGuildTaskChangeTime); SetTaskValue(owner, guildId, "payment", 0, 0); } else @@ -190,7 +190,7 @@ bool GuildTaskMgr::CreateItemTask(Player* player, uint32 guildId) return false; RandomItemBySkillGuildTaskPredicate predicate(player); - uint32 itemId = sRandomItemMgr->GetRandomItem(player->GetLevel() - 5, RANDOM_ITEM_GUILD_TASK, &predicate); + uint32 itemId = sRandomItemMgr.GetRandomItem(player->GetLevel() - 5, RANDOM_ITEM_GUILD_TASK, &predicate); if (!itemId) { LOG_ERROR("playerbots", "{} / {}: no items avaible for item task", @@ -204,9 +204,9 @@ bool GuildTaskMgr::CreateItemTask(Player* player, uint32 guildId) player->GetName().c_str(), itemId, count); SetTaskValue(player->GetGUID().GetCounter(), guildId, "itemCount", count, - sPlayerbotAIConfig->maxGuildTaskChangeTime); + sPlayerbotAIConfig.maxGuildTaskChangeTime); SetTaskValue(player->GetGUID().GetCounter(), guildId, "itemTask", itemId, - sPlayerbotAIConfig->maxGuildTaskChangeTime); + sPlayerbotAIConfig.maxGuildTaskChangeTime); return true; } @@ -239,8 +239,8 @@ bool GuildTaskMgr::CreateKillTask(Player* player, uint32 guildId) if (strstr(name.c_str(), "UNUSED")) continue; - float dist = sServerFacade->GetDistance2d(player, x, y); - if (dist > sPlayerbotAIConfig->guildTaskKillTaskDistance || player->GetMapId() != map) + float dist = ServerFacade::instance().GetDistance2d(player, x, y); + if (dist > sPlayerbotAIConfig.guildTaskKillTaskDistance || player->GetMapId() != map) continue; if (find(ids.begin(), ids.end(), id) == ids.end()) @@ -262,7 +262,7 @@ bool GuildTaskMgr::CreateKillTask(Player* player, uint32 guildId) player->GetName().c_str(), creatureId); SetTaskValue(player->GetGUID().GetCounter(), guildId, "killTask", creatureId, - sPlayerbotAIConfig->maxGuildTaskChangeTime); + sPlayerbotAIConfig.maxGuildTaskChangeTime); return true; } @@ -525,7 +525,7 @@ uint32 GuildTaskMgr::GetMaxItemTaskCount(uint32 itemId) bool GuildTaskMgr::IsGuildTaskItem(uint32 itemId, uint32 guildId) { - if (!sPlayerbotAIConfig->guildTaskEnabled) + if (!sPlayerbotAIConfig.guildTaskEnabled) { return 0; } @@ -553,7 +553,7 @@ bool GuildTaskMgr::IsGuildTaskItem(uint32 itemId, uint32 guildId) std::map GuildTaskMgr::GetTaskValues(uint32 owner, std::string const type, [[maybe_unused]] uint32* validIn /* = nullptr */) { - if (!sPlayerbotAIConfig->guildTaskEnabled) + if (!sPlayerbotAIConfig.guildTaskEnabled) { return std::map(); } @@ -586,7 +586,7 @@ std::map GuildTaskMgr::GetTaskValues(uint32 owner, std::string c uint32 GuildTaskMgr::GetTaskValue(uint32 owner, uint32 guildId, std::string const type, [[maybe_unused]] uint32* validIn /* = nullptr */) { - if (!sPlayerbotAIConfig->guildTaskEnabled) + if (!sPlayerbotAIConfig.guildTaskEnabled) { return 0; } @@ -639,7 +639,7 @@ uint32 GuildTaskMgr::SetTaskValue(uint32 owner, uint32 guildId, std::string cons bool GuildTaskMgr::HandleConsoleCommand(ChatHandler* /* handler */, char const* args) { - if (!sPlayerbotAIConfig->guildTaskEnabled) + if (!sPlayerbotAIConfig.guildTaskEnabled) { LOG_ERROR("playerbots", "Guild task system is currently disabled!"); return false; @@ -703,8 +703,8 @@ bool GuildTaskMgr::HandleConsoleCommand(ChatHandler* /* handler */, char const* if (value == GUILD_TASK_TYPE_ITEM) { name << "ItemTask"; - uint32 itemId = sGuildTaskMgr->GetTaskValue(owner, guildId, "itemTask"); - uint32 itemCount = sGuildTaskMgr->GetTaskValue(owner, guildId, "itemCount"); + uint32 itemId = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "itemTask"); + uint32 itemCount = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "itemCount"); if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId)) { @@ -735,7 +735,7 @@ bool GuildTaskMgr::HandleConsoleCommand(ChatHandler* /* handler */, char const* else if (value == GUILD_TASK_TYPE_KILL) { name << "KillTask"; - uint32 creatureId = sGuildTaskMgr->GetTaskValue(owner, guildId, "killTask"); + uint32 creatureId = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "killTask"); if (CreatureTemplate const* proto = sObjectMgr->GetCreatureTemplate(creatureId)) { @@ -758,22 +758,22 @@ bool GuildTaskMgr::HandleConsoleCommand(ChatHandler* /* handler */, char const* continue; uint32 advertValidIn = 0; - uint32 advert = sGuildTaskMgr->GetTaskValue(owner, guildId, "advertisement", &advertValidIn); + uint32 advert = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "advertisement", &advertValidIn); if (advert && advertValidIn < validIn) name << " advert in " << formatTime(advertValidIn); uint32 thanksValidIn = 0; - uint32 thanks = sGuildTaskMgr->GetTaskValue(owner, guildId, "thanks", &thanksValidIn); + uint32 thanks = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "thanks", &thanksValidIn); if (thanks && thanksValidIn < validIn) name << " thanks in " << formatTime(thanksValidIn); uint32 rewardValidIn = 0; - uint32 reward = sGuildTaskMgr->GetTaskValue(owner, guildId, "reward", &rewardValidIn); + uint32 reward = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "reward", &rewardValidIn); if (reward && rewardValidIn < validIn) name << " reward in " << formatTime(rewardValidIn); uint32 paymentValidIn = 0; - uint32 payment = sGuildTaskMgr->GetTaskValue(owner, guildId, "payment", &paymentValidIn); + uint32 payment = GuildTaskMgr::instance().GetTaskValue(owner, guildId, "payment", &paymentValidIn); if (payment && paymentValidIn < validIn) name << " payment " << ChatHelper::formatMoney(payment) << " in " << formatTime(paymentValidIn); @@ -788,8 +788,8 @@ bool GuildTaskMgr::HandleConsoleCommand(ChatHandler* /* handler */, char const* if (cmd == "cleanup") { - sGuildTaskMgr->CleanupAdverts(); - sGuildTaskMgr->RemoveDuplicatedAdverts(); + GuildTaskMgr::instance().CleanupAdverts(); + GuildTaskMgr::instance().RemoveDuplicatedAdverts(); return true; } @@ -840,10 +840,10 @@ bool GuildTaskMgr::HandleConsoleCommand(ChatHandler* /* handler */, char const* continue; if (reward) - sGuildTaskMgr->Reward(trans, owner, guildId); + GuildTaskMgr::instance().Reward(trans, owner, guildId); if (advert) - sGuildTaskMgr->SendAdvertisement(trans, owner, guildId); + GuildTaskMgr::instance().SendAdvertisement(trans, owner, guildId); } while (result->NextRow()); CharacterDatabase.CommitTransaction(trans); @@ -868,7 +868,7 @@ bool GuildTaskMgr::CheckItemTask(uint32 itemId, uint32 obtained, Player* ownerPl if (!guild) return false; - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sRandomPlayerbotMgr.IsRandomBot(bot)) return false; LOG_DEBUG("playerbots", "{} / {}: checking guild task", guild->GetName().c_str(), ownerPlayer->GetName().c_str()); @@ -891,7 +891,7 @@ bool GuildTaskMgr::CheckItemTask(uint32 itemId, uint32 obtained, Player* ownerPl return false; } - uint32 rewardTime = urand(sPlayerbotAIConfig->minGuildTaskRewardTime, sPlayerbotAIConfig->maxGuildTaskRewardTime); + uint32 rewardTime = urand(sPlayerbotAIConfig.minGuildTaskRewardTime, sPlayerbotAIConfig.maxGuildTaskRewardTime); if (byMail) { ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId); @@ -915,7 +915,7 @@ bool GuildTaskMgr::CheckItemTask(uint32 itemId, uint32 obtained, Player* ownerPl { LOG_DEBUG("playerbots", "{} / {}: guild task progress {}/{}", guild->GetName().c_str(), ownerPlayer->GetName().c_str(), obtained, count); - SetTaskValue(owner, guildId, "itemCount", count - obtained, sPlayerbotAIConfig->maxGuildTaskChangeTime); + SetTaskValue(owner, guildId, "itemCount", count - obtained, sPlayerbotAIConfig.maxGuildTaskChangeTime); SetTaskValue(owner, guildId, "thanks", 1, rewardTime - 30); SendCompletionMessage(ownerPlayer, "made a progress with"); } @@ -961,7 +961,7 @@ bool GuildTaskMgr::Reward(CharacterDatabaseTransaction& trans, uint32 owner, uin body << leader->GetName() << "\n"; rewardType = proto->Quality > ITEM_QUALITY_NORMAL ? RANDOM_ITEM_GUILD_TASK_REWARD_EQUIP_BLUE : RANDOM_ITEM_GUILD_TASK_REWARD_EQUIP_GREEN; - itemId = sRandomItemMgr->GetRandomItem(player->GetLevel() - 5, rewardType); + itemId = sRandomItemMgr.GetRandomItem(player->GetLevel() - 5, rewardType); } else if (killTask) { @@ -977,7 +977,7 @@ bool GuildTaskMgr::Reward(CharacterDatabaseTransaction& trans, uint32 owner, uin body << leader->GetName() << "\n"; rewardType = proto->rank == CREATURE_ELITE_RARE ? RANDOM_ITEM_GUILD_TASK_REWARD_TRADE : RANDOM_ITEM_GUILD_TASK_REWARD_TRADE_RARE; - itemId = sRandomItemMgr->GetRandomItem(player->GetLevel(), rewardType); + itemId = sRandomItemMgr.GetRandomItem(player->GetLevel(), rewardType); if (itemId) { ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(itemId); @@ -1086,7 +1086,7 @@ void GuildTaskMgr::CheckKillTaskInternal(Player* player, Unit* victim) LOG_DEBUG("playerbots", "{} / {}: guild task complete", guild->GetName().c_str(), player->GetName().c_str()); SetTaskValue(owner, guildId, "reward", 1, - urand(sPlayerbotAIConfig->minGuildTaskRewardTime, sPlayerbotAIConfig->maxGuildTaskRewardTime)); + urand(sPlayerbotAIConfig.minGuildTaskRewardTime, sPlayerbotAIConfig.maxGuildTaskRewardTime)); SendCompletionMessage(player, "completed"); } @@ -1094,7 +1094,7 @@ void GuildTaskMgr::CheckKillTaskInternal(Player* player, Unit* victim) void GuildTaskMgr::CleanupAdverts() { - uint32 deliverTime = time(nullptr) - sPlayerbotAIConfig->minGuildTaskChangeTime; + uint32 deliverTime = time(nullptr) - sPlayerbotAIConfig.minGuildTaskChangeTime; QueryResult result = CharacterDatabase.Query( "SELECT id, receiver FROM mail WHERE subject LIKE 'Guild Task%%' AND deliver_time <= {}", deliverTime); if (!result) @@ -1200,7 +1200,7 @@ bool GuildTaskMgr::CheckTaskTransfer(std::string const text, Player* ownerPlayer if (!guild) return false; - if (!sRandomPlayerbotMgr->IsRandomBot(bot)) + if (!sRandomPlayerbotMgr.IsRandomBot(bot)) return false; if (text.empty()) diff --git a/src/Mgr/Guild/GuildTaskMgr.h b/src/Mgr/Guild/GuildTaskMgr.h index c050281ca6..6251f2c1e2 100644 --- a/src/Mgr/Guild/GuildTaskMgr.h +++ b/src/Mgr/Guild/GuildTaskMgr.h @@ -7,56 +7,61 @@ #define _PLAYERBOT_GUILDTASKMGR_H #include +#include +#include -#include "Common.h" -#include "Transaction.h" - -class ChatHandler; -class Player; -class Unit; +#include "DatabaseEnvFwd.h" +#include "Unit.h" +#include "Player.h" +#include "Chat.h" class GuildTaskMgr { public: - GuildTaskMgr(){}; - virtual ~GuildTaskMgr(){}; - - static GuildTaskMgr* instance() + static GuildTaskMgr& instance() { static GuildTaskMgr instance; - return &instance; + + return instance; } void Update(Player* owner, Player* guildMaster); static bool HandleConsoleCommand(ChatHandler* handler, char const* args); - bool IsGuildTaskItem(uint32 itemId, uint32 guildId); - bool CheckItemTask(uint32 itemId, uint32 obtained, Player* owner, Player* bot, bool byMail = false); + bool IsGuildTaskItem(uint32_t itemId, uint32_t guildId); + bool CheckItemTask(uint32_t itemId, uint32_t obtained, Player* owner, Player* bot, bool byMail = false); void CheckKillTask(Player* owner, Unit* victim); void CheckKillTaskInternal(Player* owner, Unit* victim); bool CheckTaskTransfer(std::string const text, Player* owner, Player* bot); private: - std::map GetTaskValues(uint32 owner, std::string const type, uint32* validIn = nullptr); - uint32 GetTaskValue(uint32 owner, uint32 guildId, std::string const type, uint32* validIn = nullptr); - uint32 SetTaskValue(uint32 owner, uint32 guildId, std::string const type, uint32 value, uint32 validIn); - uint32 CreateTask(Player* owner, uint32 guildId); - bool SendAdvertisement(CharacterDatabaseTransaction& trans, uint32 owner, uint32 guildId); - bool SendItemAdvertisement(CharacterDatabaseTransaction& trans, uint32 itemId, uint32 owner, uint32 guildId, - uint32 validIn); - bool SendKillAdvertisement(CharacterDatabaseTransaction& trans, uint32 creatureId, uint32 owner, uint32 guildId, - uint32 validIn); - bool SendThanks(CharacterDatabaseTransaction& trans, uint32 owner, uint32 guildId, uint32 payment); - bool Reward(CharacterDatabaseTransaction& trans, uint32 owner, uint32 guildId); - bool CreateItemTask(Player* owner, uint32 guildId); - bool CreateKillTask(Player* owner, uint32 guildId); - uint32 GetMaxItemTaskCount(uint32 itemId); + GuildTaskMgr() = default; + ~GuildTaskMgr() = default; + + GuildTaskMgr(const GuildTaskMgr&) = delete; + GuildTaskMgr& operator=(const GuildTaskMgr&) = delete; + + GuildTaskMgr(GuildTaskMgr&&) = delete; + GuildTaskMgr& operator=(GuildTaskMgr&&) = delete; + + std::map GetTaskValues(uint32_t owner, std::string const type, uint32_t* validIn = nullptr); + uint32_t GetTaskValue(uint32_t owner, uint32_t guildId, std::string const type, uint32_t* validIn = nullptr); + uint32_t SetTaskValue(uint32_t owner, uint32_t guildId, std::string const type, uint32_t value, uint32_t validIn); + uint32_t CreateTask(Player* owner, uint32_t guildId); + bool SendAdvertisement(CharacterDatabaseTransaction& trans, uint32_t owner, uint32_t guildId); + bool SendItemAdvertisement(CharacterDatabaseTransaction& trans, uint32_t itemId, uint32_t owner, uint32_t guildId, + uint32_t validIn); + bool SendKillAdvertisement(CharacterDatabaseTransaction& trans, uint32_t creatureId, uint32_t owner, uint32_t guildId, + uint32_t validIn); + bool SendThanks(CharacterDatabaseTransaction& trans, uint32_t owner, uint32_t guildId, uint32_t payment); + bool Reward(CharacterDatabaseTransaction& trans, uint32_t owner, uint32_t guildId); + bool CreateItemTask(Player* owner, uint32_t guildId); + bool CreateKillTask(Player* owner, uint32_t guildId); + uint32_t GetMaxItemTaskCount(uint32_t itemId); void CleanupAdverts(); void RemoveDuplicatedAdverts(); - void DeleteMail(std::vector buffer); + void DeleteMail(std::vector buffer); void SendCompletionMessage(Player* player, std::string const verb); }; -#define sGuildTaskMgr GuildTaskMgr::instance() - #endif diff --git a/src/Mgr/Guild/PlayerbotGuildMgr.cpp b/src/Mgr/Guild/PlayerbotGuildMgr.cpp index c1f7aa5b2d..0885e7ed30 100644 --- a/src/Mgr/Guild/PlayerbotGuildMgr.cpp +++ b/src/Mgr/Guild/PlayerbotGuildMgr.cpp @@ -4,15 +4,12 @@ #include "DatabaseEnv.h" #include "Guild.h" #include "GuildMgr.h" -#include "RandomPlayerbotMgr.h" #include "ScriptMgr.h" -PlayerbotGuildMgr::PlayerbotGuildMgr(){} - void PlayerbotGuildMgr::Init() { _guildCache.clear(); - if (sPlayerbotAIConfig->deleteRandomBotGuilds) + if (sPlayerbotAIConfig.deleteRandomBotGuilds) DeleteBotGuilds(); LoadGuildNames(); @@ -38,7 +35,7 @@ bool PlayerbotGuildMgr::CreateGuild(Player* player, std::string guildName) entry.name = guildName; entry.memberCount = 1; entry.status = 1; - entry.maxMembers = sPlayerbotAIConfig->randomBotGuildSizeMax; + entry.maxMembers = sPlayerbotAIConfig.randomBotGuildSizeMax; entry.faction = player->GetTeamId(); _guildCache[guild->GetId()] = entry; @@ -113,7 +110,7 @@ std::string PlayerbotGuildMgr::AssignToGuild(Player* player) } ); - if (count < sPlayerbotAIConfig->randomBotGuildCount) + if (count < sPlayerbotAIConfig.randomBotGuildCount) { for (auto& key : _shuffled_guild_keys) { @@ -214,7 +211,7 @@ void PlayerbotGuildMgr::ValidateGuildCache() uint32 guildId = it->first; GuildCache cache; cache.name = it->second; - cache.maxMembers = sPlayerbotAIConfig->randomBotGuildSizeMax; + cache.maxMembers = sPlayerbotAIConfig.randomBotGuildSizeMax; Guild* guild = sGuildMgr ->GetGuildById(guildId); if (!guild) @@ -224,7 +221,7 @@ void PlayerbotGuildMgr::ValidateGuildCache() ObjectGuid leaderGuid = guild->GetLeaderGUID(); CharacterCacheEntry const* leaderEntry = sCharacterCache->GetCharacterCacheByGuid(leaderGuid); uint32 leaderAccount = leaderEntry->AccountId; - cache.hasRealPlayer = !(sPlayerbotAIConfig->IsInRandomAccountList(leaderAccount)); + cache.hasRealPlayer = !(sPlayerbotAIConfig.IsInRandomAccountList(leaderAccount)); cache.faction = Player::TeamIdForRace(leaderEntry->Race); if (cache.memberCount == 0) cache.status = 0; // empty @@ -306,7 +303,7 @@ class BotGuildCacheWorldScript : public WorldScript if (_validateTimer >= _validateInterval) // Validate every hour { _validateTimer = 0; - sPlayerbotGuildMgr->ValidateGuildCache(); + PlayerbotGuildMgr::instance().ValidateGuildCache(); LOG_INFO("playerbots", "Scheduled guild cache validation"); } } diff --git a/src/Mgr/Guild/PlayerbotGuildMgr.h b/src/Mgr/Guild/PlayerbotGuildMgr.h index 0df0df7371..499a33e606 100644 --- a/src/Mgr/Guild/PlayerbotGuildMgr.h +++ b/src/Mgr/Guild/PlayerbotGuildMgr.h @@ -5,15 +5,14 @@ #include "Player.h" #include "PlayerbotAI.h" -class PlayerbotAI; - class PlayerbotGuildMgr { public: - static PlayerbotGuildMgr* instance() + static PlayerbotGuildMgr& instance() { static PlayerbotGuildMgr instance; - return &instance; + + return instance; } void Init(); @@ -29,7 +28,15 @@ class PlayerbotGuildMgr bool IsRealGuild(Player* bot); private: - PlayerbotGuildMgr(); + PlayerbotGuildMgr() = default; + ~PlayerbotGuildMgr() = default; + + PlayerbotGuildMgr(const PlayerbotGuildMgr&) = delete; + PlayerbotGuildMgr& operator=(const PlayerbotGuildMgr&) = delete; + + PlayerbotGuildMgr(PlayerbotGuildMgr&&) = delete; + PlayerbotGuildMgr& operator=(PlayerbotGuildMgr&&) = delete; + std::unordered_map _guildNames; struct GuildCache @@ -47,6 +54,4 @@ class PlayerbotGuildMgr void PlayerBotsGuildValidationScript(); -#define sPlayerbotGuildMgr PlayerbotGuildMgr::instance() - #endif \ No newline at end of file diff --git a/src/Mgr/Item/RandomItemMgr.cpp b/src/Mgr/Item/RandomItemMgr.cpp index 87b8379355..8939e349b0 100644 --- a/src/Mgr/Item/RandomItemMgr.cpp +++ b/src/Mgr/Item/RandomItemMgr.cpp @@ -7,7 +7,9 @@ #include "ItemTemplate.h" #include "LootValues.h" -#include "Playerbots.h" +#include "Player.h" +#include "PlayerbotAIConfig.h" +#include "SpellMgr.h" char* strstri(char const* str1, char const* str2); std::set RandomItemMgr::itemCache; @@ -176,7 +178,7 @@ RandomItemMgr::~RandomItemMgr() predicates.clear(); } -bool RandomItemMgr::HandleConsoleCommand(ChatHandler* handler, char const* args) +bool RandomItemMgr::HandleConsoleCommand(ChatHandler*, char const* args) { if (!args || !*args) { @@ -272,7 +274,7 @@ void RandomItemMgr::BuildRandomItemCache() } } - uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; + uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); @@ -1269,7 +1271,7 @@ void RandomItemMgr::BuildItemInfoCache() uint32 RandomItemMgr::CalculateStatWeight(uint8 playerclass, uint8 spec, ItemTemplate const* proto) { - uint32 statWeight = 0; + int64_t statWeight = 0; bool isCasterItem = false; bool isAttackItem = false; bool noCaster = (Classes)playerclass == CLASS_WARRIOR || (Classes)playerclass == CLASS_ROGUE || @@ -1700,7 +1702,7 @@ std::vector RandomItemMgr::GetQuestIdsForItem(uint32 itemId) } } - return std::move(questIds); + return questIds; } uint32 RandomItemMgr::GetUpgrade(Player* player, std::string spec, uint8 slot, uint32 quality, uint32 itemId) @@ -1782,10 +1784,19 @@ uint32 RandomItemMgr::GetUpgrade(Player* player, std::string spec, uint8 slot, u } // skip no stats trinkets - if (info.weights[specId] == 1 && info.slot == EQUIPMENT_SLOT_NECK || info.slot == EQUIPMENT_SLOT_TRINKET1 || - info.slot == EQUIPMENT_SLOT_TRINKET2 || info.slot == EQUIPMENT_SLOT_FINGER1 || - info.slot == EQUIPMENT_SLOT_FINGER2) + if ( + info.weights[specId] == 1 + && ( + info.slot == EQUIPMENT_SLOT_NECK + || info.slot == EQUIPMENT_SLOT_TRINKET1 + || info.slot == EQUIPMENT_SLOT_TRINKET2 + || info.slot == EQUIPMENT_SLOT_FINGER1 + || info.slot == EQUIPMENT_SLOT_FINGER2 + ) + ) + { continue; + } // check if item stat score is the best among class specs uint32 bestSpecId = 0; @@ -1823,16 +1834,15 @@ uint32 RandomItemMgr::GetUpgrade(Player* player, std::string spec, uint8 slot, u } std::vector RandomItemMgr::GetUpgradeList(Player* player, std::string spec, uint8 slot, uint32 quality, - uint32 itemId, uint32 amount) + uint32 itemId, uint32) { std::vector listItems; if (!player) - return std::move(listItems); + return listItems; // get old item statWeight uint32 oldStatWeight = 0; uint32 specId = 0; - uint32 closestUpgrade = 0; uint32 closestUpgradeWeight = 0; std::vector classspecs; @@ -1848,7 +1858,7 @@ std::vector RandomItemMgr::GetUpgradeList(Player* player, std::string sp } if (!specId) - return std::move(listItems); + return listItems; if (itemId && itemInfoCache.find(itemId) != itemInfoCache.end()) { @@ -1933,7 +1943,6 @@ std::vector RandomItemMgr::GetUpgradeList(Player* player, std::string sp // pick closest upgrade if (info.weights[specId] > closestUpgradeWeight) { - closestUpgrade = info.itemId; closestUpgradeWeight = info.weights[specId]; } } @@ -1942,7 +1951,7 @@ std::vector RandomItemMgr::GetUpgradeList(Player* player, std::string sp LOG_INFO("playerbots", "New Items: {}, Old item:%d, New items max: {}", listItems.size(), oldStatWeight, closestUpgradeWeight); - return std::move(listItems); + return listItems; } bool RandomItemMgr::HasStatWeight(uint32 itemId) @@ -2092,7 +2101,7 @@ uint32 RandomItemMgr::GetLiveStatWeight(Player* player, uint32 itemId) void RandomItemMgr::BuildEquipCache() { - uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; + uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); @@ -2218,7 +2227,7 @@ void RandomItemMgr::BuildEquipCacheNew() if (quest->GetRequiredClasses()) continue; - for (int j = 0; j < quest->GetRewChoiceItemsCount(); j++) + for (uint32_t j = 0; j < quest->GetRewChoiceItemsCount(); j++) if (uint32 itemId = quest->RewardChoiceItemId[j]) { ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId); @@ -2229,7 +2238,7 @@ void RandomItemMgr::BuildEquipCacheNew() questItemIds.insert(itemId); } - for (int j = 0; j < quest->GetRewItemsCount(); j++) + for (uint32_t j = 0; j < quest->GetRewItemsCount(); j++) if (uint32 itemId = quest->RewardItemId[j]) { ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemId); @@ -2374,9 +2383,6 @@ void RandomItemMgr::BuildPotionCache() if (proto->Duration & 0x80000000) continue; - if (proto->AllowableClass != -1) - continue; - bool hybrid = false; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(proto->Spells[0].SpellId); if (!spellInfo) @@ -2415,7 +2421,7 @@ void RandomItemMgr::BuildPotionCache() void RandomItemMgr::BuildFoodCache() { - uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; + uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); @@ -2548,7 +2554,7 @@ uint32 RandomItemMgr::GetRandomFood(uint32 level, uint32 category) void RandomItemMgr::BuildTradeCache() { - uint32 maxLevel = sPlayerbotAIConfig->randomBotMaxLevel; + uint32 maxLevel = sPlayerbotAIConfig.randomBotMaxLevel; if (maxLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) maxLevel = sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL); @@ -2767,7 +2773,9 @@ inline bool IsCraftedBySpellInfo(ItemTemplate const* proto, SpellInfo const* spe continue; } - if (proto->ItemId == spellInfo->Reagent[x]) + const int64_t itemTemplateId = proto->ItemId; + + if (itemTemplateId == spellInfo->Reagent[x]) { return true; } diff --git a/src/Mgr/Item/RandomItemMgr.h b/src/Mgr/Item/RandomItemMgr.h index 216ddf9bfc..54e2e63516 100644 --- a/src/Mgr/Item/RandomItemMgr.h +++ b/src/Mgr/Item/RandomItemMgr.h @@ -12,7 +12,6 @@ #include #include "AiFactory.h" -#include "Common.h" #include "ItemTemplate.h" class ChatHandler; @@ -135,12 +134,11 @@ typedef std::map BotEquipCache; class RandomItemMgr { public: - RandomItemMgr(); - virtual ~RandomItemMgr(); - static RandomItemMgr* instance() + static RandomItemMgr& instance() { static RandomItemMgr instance; - return &instance; + + return instance; } public: @@ -191,6 +189,17 @@ class RandomItemMgr bool CheckItemStats(uint8 clazz, uint8 sp, uint8 ap, uint8 tank); private: + // Implemented in RandomItemMgr.cpp + RandomItemMgr(); + // Implemented in RandomItemMgr.cpp + ~RandomItemMgr(); + + RandomItemMgr(const RandomItemMgr&) = delete; + RandomItemMgr& operator=(const RandomItemMgr&) = delete; + + RandomItemMgr(RandomItemMgr&&) = delete; + RandomItemMgr& operator=(RandomItemMgr&&) = delete; + std::map randomItemCache; std::map predicates; BotEquipCache equipCache; diff --git a/src/Mgr/Item/StatsCollector.cpp b/src/Mgr/Item/StatsCollector.cpp index 4f719fea4e..efc2420889 100644 --- a/src/Mgr/Item/StatsCollector.cpp +++ b/src/Mgr/Item/StatsCollector.cpp @@ -1,18 +1,13 @@ #include "StatsCollector.h" -#include - #include "DBCStores.h" -#include "ItemEnchantmentMgr.h" #include "ItemTemplate.h" -#include "ObjectMgr.h" #include "PlayerbotAI.h" #include "PlayerbotAIAware.h" #include "SharedDefines.h" #include "SpellAuraDefines.h" #include "SpellInfo.h" #include "SpellMgr.h" -#include "UpdateFields.h" #include "Util.h" StatsCollector::StatsCollector(CollectorType type, int32 cls) : type_(type), cls_(cls) { Reset(); } @@ -39,7 +34,7 @@ void StatsCollector::CollectItemStats(ItemTemplate const* proto) } stats[STATS_TYPE_ARMOR] += proto->Armor; stats[STATS_TYPE_BLOCK_VALUE] += proto->Block; - for (int i = 0; i < proto->StatsCount; i++) + for (uint32_t i = 0; i < proto->StatsCount; i++) { const _ItemStat& stat = proto->ItemStat[i]; const int32& val = stat.ItemStatValue; diff --git a/src/Mgr/Item/StatsWeightCalculator.cpp b/src/Mgr/Item/StatsWeightCalculator.cpp index 1b3f3dcfcb..777f1fb847 100644 --- a/src/Mgr/Item/StatsWeightCalculator.cpp +++ b/src/Mgr/Item/StatsWeightCalculator.cpp @@ -500,7 +500,7 @@ void StatsWeightCalculator::CalculateItemSetMod(Player* player, ItemTemplate con weight_ *= multiplier; } -void StatsWeightCalculator::CalculateSocketBonus(Player* player, ItemTemplate const* proto) +void StatsWeightCalculator::CalculateSocketBonus(Player*, ItemTemplate const* proto) { uint32 socketNum = 0; for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; diff --git a/src/Mgr/Move/FleeManager.cpp b/src/Mgr/Move/FleeManager.cpp index 34e17fe391..d3d1a8bb02 100644 --- a/src/Mgr/Move/FleeManager.cpp +++ b/src/Mgr/Move/FleeManager.cpp @@ -34,7 +34,7 @@ void FleeManager::calculateDistanceToCreatures(FleePoint* point) if (!unit) continue; - float d = sServerFacade->GetDistance2d(unit, point->x, point->y); + float d = ServerFacade::instance().GetDistance2d(unit, point->x, point->y); point->sumDistance += d; if (point->minDistance < 0 || point->minDistance > d) point->minDistance = d; @@ -81,11 +81,11 @@ void FleeManager::calculatePossibleDestinations(std::vector& points) enemyOri.push_back(ori); } - float distIncrement = std::max(sPlayerbotAIConfig->followDistance, - (maxAllowedDistance - sPlayerbotAIConfig->tooCloseDistance) / 10.0f); - for (float dist = maxAllowedDistance; dist >= sPlayerbotAIConfig->tooCloseDistance; dist -= distIncrement) + float distIncrement = std::max(sPlayerbotAIConfig.followDistance, + (maxAllowedDistance - sPlayerbotAIConfig.tooCloseDistance) / 10.0f); + for (float dist = maxAllowedDistance; dist >= sPlayerbotAIConfig.tooCloseDistance; dist -= distIncrement) { - float angleIncrement = std::max(M_PI / 20, M_PI / 4 / (1.0 + dist - sPlayerbotAIConfig->tooCloseDistance)); + float angleIncrement = std::max(M_PI / 20, M_PI / 4 / (1.0 + dist - sPlayerbotAIConfig.tooCloseDistance)); for (float add = 0.0f; add < M_PI / 4 + angleIncrement; add += angleIncrement) { for (float angle = add; angle < add + 2 * static_cast(M_PI) + angleIncrement; @@ -97,8 +97,8 @@ void FleeManager::calculatePossibleDestinations(std::vector& points) float x = botPosX + cos(angle) * maxAllowedDistance, y = botPosY + sin(angle) * maxAllowedDistance, z = botPosZ + CONTACT_DISTANCE; if (forceMaxDistance && - sServerFacade->IsDistanceLessThan(sServerFacade->GetDistance2d(bot, x, y), - maxAllowedDistance - sPlayerbotAIConfig->tooCloseDistance)) + ServerFacade::instance().IsDistanceLessThan(ServerFacade::instance().GetDistance2d(bot, x, y), + maxAllowedDistance - sPlayerbotAIConfig.tooCloseDistance)) continue; bot->UpdateAllowedPositionZ(x, y, z); @@ -113,8 +113,8 @@ void FleeManager::calculatePossibleDestinations(std::vector& points) FleePoint* point = new FleePoint(botAI, x, y, z); calculateDistanceToCreatures(point); - if (sServerFacade->IsDistanceGreaterOrEqualThan(point->minDistance - start.minDistance, - sPlayerbotAIConfig->followDistance)) + if (ServerFacade::instance().IsDistanceGreaterOrEqualThan(point->minDistance - start.minDistance, + sPlayerbotAIConfig.followDistance)) points.push_back(point); else delete point; @@ -189,8 +189,8 @@ bool FleeManager::isUseful() creature->GetAttackDistance(bot) * creature->GetAttackDistance(bot)) return true; - // float d = sServerFacade->GetDistance2d(unit, bot); - // if (sServerFacade->IsDistanceLessThan(d, sPlayerbotAIConfig->aggroDistance)) return true; + // float d = ServerFacade::instance().GetDistance2d(unit, bot); + // if (ServerFacade::instance().IsDistanceLessThan(d, sPlayerbotAIConfig.aggroDistance)) return true; } return false; diff --git a/src/Mgr/Security/PlayerbotSecurity.cpp b/src/Mgr/Security/PlayerbotSecurity.cpp index 68bb2db29a..4a3bd36553 100644 --- a/src/Mgr/Security/PlayerbotSecurity.cpp +++ b/src/Mgr/Security/PlayerbotSecurity.cpp @@ -47,7 +47,7 @@ PlayerbotSecurityLevel PlayerbotSecurity::LevelFor(Player* from, DenyReason* rea return PLAYERBOT_SECURITY_DENY_ALL; } - if (sPlayerbotAIConfig->IsInRandomAccountList(account)) + if (sPlayerbotAIConfig.IsInRandomAccountList(account)) { // (duplicate check in case of faction change) if (botAI->IsOpposing(from)) @@ -72,7 +72,7 @@ PlayerbotSecurityLevel PlayerbotSecurity::LevelFor(Player* from, DenyReason* rea return PLAYERBOT_SECURITY_TALK; } - if (sPlayerbotAIConfig->groupInvitationPermission <= 0) + if (sPlayerbotAIConfig.groupInvitationPermission <= 0) { if (reason) *reason = PLAYERBOT_DENY_NONE; @@ -80,7 +80,7 @@ PlayerbotSecurityLevel PlayerbotSecurity::LevelFor(Player* from, DenyReason* rea return PLAYERBOT_SECURITY_TALK; } - if (sPlayerbotAIConfig->groupInvitationPermission <= 1) + if (sPlayerbotAIConfig.groupInvitationPermission <= 1) { int32 levelDiff = int32(bot->GetLevel()) - int32(from->GetLevel()); if (levelDiff > 5) @@ -98,7 +98,7 @@ PlayerbotSecurityLevel PlayerbotSecurity::LevelFor(Player* from, DenyReason* rea int32 botGS = static_cast(botAI->GetEquipGearScore(bot)); int32 fromGS = static_cast(botAI->GetEquipGearScore(from)); - if (sPlayerbotAIConfig->gearscorecheck && botGS && bot->GetLevel() > 15 && botGS > fromGS) + if (sPlayerbotAIConfig.gearscorecheck && botGS && bot->GetLevel() > 15 && botGS > fromGS) { uint32 diffPct = uint32(100 * (botGS - fromGS) / botGS); uint32 reqPct = uint32(12 * sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL) / from->GetLevel()); @@ -277,7 +277,7 @@ bool PlayerbotSecurity::CheckLevelFor(PlayerbotSecurityLevel level, bool silent, ObjectGuid guid = from->GetGUID(); time_t lastSaid = whispers[guid][text]; - if (!lastSaid || (time(nullptr) - lastSaid) >= sPlayerbotAIConfig->repeatDelay / 1000) + if (!lastSaid || (time(nullptr) - lastSaid) >= sPlayerbotAIConfig.repeatDelay / 1000) { whispers[guid][text] = time(nullptr); diff --git a/src/Mgr/Talent/Talentspec.cpp b/src/Mgr/Talent/Talentspec.cpp index 06e70b841c..74106d25bb 100644 --- a/src/Mgr/Talent/Talentspec.cpp +++ b/src/Mgr/Talent/Talentspec.cpp @@ -6,7 +6,9 @@ #include "Talentspec.h" #include "Event.h" -#include "Playerbots.h" +#include "Player.h" +#include "SpellMgr.h" +#include "World.h" uint32 TalentSpec::TalentListEntry::tabPage() const { @@ -140,7 +142,7 @@ bool TalentSpec::CheckTalents(uint32 level, std::ostringstream* out) } // Set the talents for the bots to the current spec. -void TalentSpec::ApplyTalents(Player* bot, std::ostringstream* out) +void TalentSpec::ApplyTalents(Player* bot, std::ostringstream*) { for (auto& entry : talents) { @@ -317,7 +319,7 @@ std::vector TalentSpec::GetTalentTree(uint32 tabpag if (entry.tabPage() == tabpage) retList.push_back(entry); - return std::move(retList); + return retList; } uint32 TalentSpec::GetTalentPoints(int32 tabpage) { return GetTalentPoints(talents, tabpage); }; @@ -330,8 +332,14 @@ uint32 TalentSpec::GetTalentPoints(std::vector& talents, int32 uint32 tPoints = 0; for (auto& entry : talents) - if (entry.tabPage() == tabpage) + { + const int64_t entryTabPage = entry.tabPage(); + + if (entryTabPage == tabpage) + { tPoints = tPoints + entry.rank; + } + } return tPoints; } @@ -368,7 +376,7 @@ std::string const TalentSpec::GetTalentLink() if (treeLink[2] != "0") link = link + "-" + treeLink[2]; - return std::move(link); + return link; } uint32 TalentSpec::highestTree() @@ -395,7 +403,7 @@ uint32 TalentSpec::highestTree() return 0; } -std::string const TalentSpec::FormatSpec(Player* bot) +std::string const TalentSpec::FormatSpec(Player*) { // uint8 cls = bot->getClass(); //not used, (used in lined 403), line marked for removal. @@ -446,7 +454,7 @@ std::vector TalentSpec::SubTalentList(std::vector +#include +#include "Player.h" struct TalentEntry; struct TalentTabEntry; @@ -25,17 +27,17 @@ class TalentSpec public: struct TalentListEntry { - uint32 entry; - uint32 rank; - uint32 maxRank; + uint32_t entry; + uint32_t rank; + uint32_t maxRank; TalentEntry const* talentInfo; TalentTabEntry const* talentTabInfo; - uint32 tabPage() const; + uint32_t tabPage() const; }; TalentSpec(){}; virtual ~TalentSpec() {} - TalentSpec(uint32 classMask); + TalentSpec(uint32_t classMask); TalentSpec(TalentSpec* base, std::string const link); TalentSpec(Player* bot); TalentSpec(Player* bot, std::string const link); diff --git a/src/Mgr/Text/PlayerbotTextMgr.cpp b/src/Mgr/Text/PlayerbotTextMgr.cpp index 1dce9a29a5..0998a5392f 100644 --- a/src/Mgr/Text/PlayerbotTextMgr.cpp +++ b/src/Mgr/Text/PlayerbotTextMgr.cpp @@ -2,12 +2,14 @@ * Copyright (C) 2016+ AzerothCore , released under GNU AGPL v3 license, you may redistribute it * and/or modify it under version 3 of the License, or (at your option), any later version. */ +#include "DatabaseEnv.h" +#include "WorldSessionMgr.h" +#include "Random.h" +// Required due to a poor implementation by AC +#include "QueryResult.h" #include "PlayerbotTextMgr.h" -#include "Playerbots.h" -#include "WorldSessionMgr.h" - void PlayerbotTextMgr::replaceAll(std::string& str, const std::string& from, const std::string& to) { if (from.empty()) diff --git a/src/Mgr/Text/PlayerbotTextMgr.h b/src/Mgr/Text/PlayerbotTextMgr.h index f4ec2c403c..5f173fdd16 100644 --- a/src/Mgr/Text/PlayerbotTextMgr.h +++ b/src/Mgr/Text/PlayerbotTextMgr.h @@ -11,9 +11,6 @@ #include "Common.h" -#define BOT_TEXT1(name) sPlayerbotTextMgr->GetBotText(name) -#define BOT_TEXT2(name, replace) sPlayerbotTextMgr->GetBotText(name, replace) - struct BotTextEntry { BotTextEntry(std::string name, std::map text, uint32 say_type, uint32 reply_type) @@ -63,18 +60,11 @@ enum ChatReplyType class PlayerbotTextMgr { public: - PlayerbotTextMgr() - { - for (uint8 i = 0; i < MAX_LOCALES; ++i) - { - botTextLocalePriority[i] = 0; - } - }; - virtual ~PlayerbotTextMgr(){}; - static PlayerbotTextMgr* instance() + static PlayerbotTextMgr& instance() { static PlayerbotTextMgr instance; - return &instance; + + return instance; } std::string GetBotText(std::string name, std::map placeholders); @@ -95,11 +85,25 @@ class PlayerbotTextMgr void ResetLocalePriority(); private: + PlayerbotTextMgr() + { + for (uint8 i = 0; i < MAX_LOCALES; ++i) + { + botTextLocalePriority[i] = 0; + } + }; + ~PlayerbotTextMgr() = default; + + PlayerbotTextMgr(const PlayerbotTextMgr&) = delete; + PlayerbotTextMgr& operator=(const PlayerbotTextMgr&) = delete; + + PlayerbotTextMgr(PlayerbotTextMgr&&) = delete; + PlayerbotTextMgr& operator=(PlayerbotTextMgr&&) = delete; + + std::map> botTexts; std::map botTextChance; uint32 botTextLocalePriority[MAX_LOCALES]; }; -#define sPlayerbotTextMgr PlayerbotTextMgr::instance() - #endif diff --git a/src/Mgr/Travel/TravelMgr.cpp b/src/Mgr/Travel/TravelMgr.cpp index ab70576502..02f6602b42 100644 --- a/src/Mgr/Travel/TravelMgr.cpp +++ b/src/Mgr/Travel/TravelMgr.cpp @@ -8,17 +8,17 @@ #include #include -#include "CellImpl.h" +#include "Talentspec.h" #include "ChatHelper.h" #include "MMapFactory.h" #include "MapMgr.h" #include "PathGenerator.h" #include "Playerbots.h" -#include "StrategyContext.h" #include "TransportMgr.h" -#include "VMapFactory.h" #include "VMapMgr2.h" +#include "Map.h" #include "Corpse.h" +#include "CellImpl.h" WorldPosition::WorldPosition(std::string const str) { @@ -116,16 +116,18 @@ WorldPosition::WorldPosition(std::vector list, WorldPositionConst } } +// We have to disable this Clang rule because the bug resides in AC which we cannot act on. + WorldPosition::WorldPosition(uint32 mapid, GridCoord grid) - : WorldLocation(mapid, (int32(grid.x_coord) - CENTER_GRID_ID - 0.5) * SIZE_OF_GRIDS + CENTER_GRID_OFFSET, - (int32(grid.y_coord) - CENTER_GRID_ID - 0.5) * SIZE_OF_GRIDS + CENTER_GRID_OFFSET, 0, 0) + : WorldLocation(mapid, (int32(grid.x_coord) - CENTER_GRID_ID - 0.5) * SIZE_OF_GRIDS + CENTER_GRID_OFFSET, // NOLINT(bugprone-integer-division) + (int32(grid.y_coord) - CENTER_GRID_ID - 0.5) * SIZE_OF_GRIDS + CENTER_GRID_OFFSET, 0, 0) // NOLINT(bugprone-integer-division) { } WorldPosition::WorldPosition(uint32 mapid, CellCoord cell) : WorldLocation( - mapid, (int32(cell.x_coord) - CENTER_GRID_CELL_ID - 0.5) * SIZE_OF_GRID_CELL + CENTER_GRID_CELL_OFFSET, - (int32(cell.y_coord) - CENTER_GRID_CELL_ID - 0.5) * SIZE_OF_GRID_CELL + CENTER_GRID_CELL_OFFSET, 0, 0) + mapid, (int32(cell.x_coord) - CENTER_GRID_CELL_ID - 0.5) * SIZE_OF_GRID_CELL + CENTER_GRID_CELL_OFFSET, // NOLINT(bugprone-integer-division) + (int32(cell.y_coord) - CENTER_GRID_CELL_ID - 0.5) * SIZE_OF_GRID_CELL + CENTER_GRID_CELL_OFFSET, 0, 0) // NOLINT(bugprone-integer-division) { } @@ -246,7 +248,7 @@ float WorldPosition::distance(WorldPosition* center) return relPoint(center).size(); // this -> mapTransfer | mapTransfer -> center - return sTravelMgr->mapTransDistance(*this, *center); + return TravelMgr::instance().mapTransDistance(*this, *center); }; float WorldPosition::fDist(WorldPosition* center) @@ -255,7 +257,7 @@ float WorldPosition::fDist(WorldPosition* center) return sqrt(sqDistance2d(center)); // this -> mapTransfer | mapTransfer -> center - return sTravelMgr->fastMapTransDistance(*this, *center); + return TravelMgr::instance().fastMapTransDistance(*this, *center); }; float mapTransfer::fDist(WorldPosition start, WorldPosition end) @@ -428,7 +430,7 @@ void WorldPosition::printWKT(std::vector points, std::ostringstre WorldPosition WorldPosition::getDisplayLocation() { - WorldPosition pos = sTravelNodeMap->getMapOffset(getMapId()); + WorldPosition pos = TravelNodeMap::instance().getMapOffset(getMapId()); return offset(const_cast(&pos)); } @@ -479,10 +481,10 @@ std::string const WorldPosition::getAreaName(bool fullName, bool zoneName) } } - return std::move(areaName); + return areaName; } -std::set WorldPosition::getTransports(uint32 entry) +std::set WorldPosition::getTransports(uint32) { /* if (!entry) @@ -627,78 +629,78 @@ void WorldPosition::loadMapAndVMap(uint32 mapId, uint8 x, uint8 y) { std::string const fileName = "load_map_grid.csv"; - if (isOverworld() && false || false) - { - if (!MMAP::MMapFactory::createOrGetMMapMgr()->loadMap(mapId, x, y)) - if (sPlayerbotAIConfig->hasLog(fileName)) - { - std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); - out << "+00,\"mmap\", " << x << "," << y << "," << (sTravelMgr->isBadMmap(mapId, x, y) ? "0" : "1") - << ","; - printWKT(fromGridCoord(GridCoord(x, y)), out, 1, true); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); - } - } - else - { + // if (isOverworld() && false || false) + // { + // if (!MMAP::MMapFactory::createOrGetMMapMgr()->loadMap(mapId, x, y)) + // if (sPlayerbotAIConfig.hasLog(fileName)) + // { + // std::ostringstream out; + // out << sPlayerbotAIConfig.GetTimestampStr(); + // out << "+00,\"mmap\", " << x << "," << y << "," << (TravelMgr::instance().isBadMmap(mapId, x, y) ? "0" : "1") + // << ","; + // printWKT(fromGridCoord(GridCoord(x, y)), out, 1, true); + // sPlayerbotAIConfig.log(fileName, out.str().c_str()); + // } + // } + // else + // { // This needs to be disabled or maps will not load. // Needs more testing to check for impact on movement. - if (false) - if (!sTravelMgr->isBadVmap(mapId, x, y)) - { - // load VMAPs for current map/grid... - const MapEntry* i_mapEntry = sMapStore.LookupEntry(mapId); - //const char* mapName = i_mapEntry ? i_mapEntry->name[sWorld->GetDefaultDbcLocale()] : "UNNAMEDMAP\x0"; //not used, (usage are commented out below), line marked for removal. - - int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapMgr()->loadMap( - (sWorld->GetDataPath() + "vmaps").c_str(), mapId, x, y); - switch (vmapLoadResult) - { - case VMAP::VMAP_LOAD_RESULT_OK: - // LOG_ERROR("playerbots", "VMAP loaded name:{}, id:{}, x:{}, y:{} (vmap rep.: x:{}, y:{})", - // mapName, mapId, x, y, x, y); - break; - case VMAP::VMAP_LOAD_RESULT_ERROR: - // LOG_ERROR("playerbots", "Could not load VMAP name:{}, id:{}, x:{}, y:{} (vmap rep.: x:{}, - // y:{})", mapName, mapId, x, y, x, y); - sTravelMgr->addBadVmap(mapId, x, y); - break; - case VMAP::VMAP_LOAD_RESULT_IGNORED: - sTravelMgr->addBadVmap(mapId, x, y); - // LOG_INFO("playerbots", "Ignored VMAP name:{}, id:{}, x:{}, y:{} (vmap rep.: x:{}, y:{})", - // mapName, mapId, x, y, x, y); - break; - } - - if (sPlayerbotAIConfig->hasLog(fileName)) - { - std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); - out << "+00,\"vmap\", " << x << "," << y << ", " << (sTravelMgr->isBadVmap(mapId, x, y) ? "0" : "1") - << ","; - printWKT(frommGridCoord(mGridCoord(x, y)), out, 1, true); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); - } - } - - if (!sTravelMgr->isBadMmap(mapId, x, y)) + // if (false) + // if (!TravelMgr::instance().isBadVmap(mapId, x, y)) + // { + // // load VMAPs for current map/grid... + // const MapEntry* i_mapEntry = sMapStore.LookupEntry(mapId); + // //const char* mapName = i_mapEntry ? i_mapEntry->name[sWorld->GetDefaultDbcLocale()] : "UNNAMEDMAP\x0"; //not used, (usage are commented out below), line marked for removal. + + // int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapMgr()->loadMap( + // (sWorld->GetDataPath() + "vmaps").c_str(), mapId, x, y); + // switch (vmapLoadResult) + // { + // case VMAP::VMAP_LOAD_RESULT_OK: + // // LOG_ERROR("playerbots", "VMAP loaded name:{}, id:{}, x:{}, y:{} (vmap rep.: x:{}, y:{})", + // // mapName, mapId, x, y, x, y); + // break; + // case VMAP::VMAP_LOAD_RESULT_ERROR: + // // LOG_ERROR("playerbots", "Could not load VMAP name:{}, id:{}, x:{}, y:{} (vmap rep.: x:{}, + // // y:{})", mapName, mapId, x, y, x, y); + // TravelMgr::instance().addBadVmap(mapId, x, y); + // break; + // case VMAP::VMAP_LOAD_RESULT_IGNORED: + // TravelMgr::instance().addBadVmap(mapId, x, y); + // // LOG_INFO("playerbots", "Ignored VMAP name:{}, id:{}, x:{}, y:{} (vmap rep.: x:{}, y:{})", + // // mapName, mapId, x, y, x, y); + // break; + // } + + // if (sPlayerbotAIConfig.hasLog(fileName)) + // { + // std::ostringstream out; + // out << sPlayerbotAIConfig.GetTimestampStr(); + // out << "+00,\"vmap\", " << x << "," << y << ", " << (TravelMgr::instance().isBadVmap(mapId, x, y) ? "0" : "1") + // << ","; + // printWKT(frommGridCoord(mGridCoord(x, y)), out, 1, true); + // sPlayerbotAIConfig.log(fileName, out.str().c_str()); + // } + // } + + if (!TravelMgr::instance().isBadMmap(mapId, x, y)) { // load navmesh if (!MMAP::MMapFactory::createOrGetMMapMgr()->loadMap(mapId, x, y)) - sTravelMgr->addBadMmap(mapId, x, y); + TravelMgr::instance().addBadMmap(mapId, x, y); - if (sPlayerbotAIConfig->hasLog(fileName)) + if (sPlayerbotAIConfig.hasLog(fileName)) { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); - out << "+00,\"mmap\", " << x << "," << y << "," << (sTravelMgr->isBadMmap(mapId, x, y) ? "0" : "1") + out << sPlayerbotAIConfig.GetTimestampStr(); + out << "+00,\"mmap\", " << x << "," << y << "," << (TravelMgr::instance().isBadMmap(mapId, x, y) ? "0" : "1") << ","; printWKT(fromGridCoord(GridCoord(x, y)), out, 1, true); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); + sPlayerbotAIConfig.log(fileName, out.str().c_str()); } } - } + // } } void WorldPosition::loadMapAndVMaps(WorldPosition secondPos) @@ -733,21 +735,21 @@ std::vector WorldPosition::getPathStepFrom(WorldPosition startPos Movement::PointsArray points = path.GetPath(); PathType type = path.GetPathType(); - if (sPlayerbotAIConfig->hasLog("pathfind_attempt_point.csv")) + if (sPlayerbotAIConfig.hasLog("pathfind_attempt_point.csv")) { std::ostringstream out; out << std::fixed << std::setprecision(1); printWKT({startPos, *this}, out); - sPlayerbotAIConfig->log("pathfind_attempt_point.csv", out.str().c_str()); + sPlayerbotAIConfig.log("pathfind_attempt_point.csv", out.str().c_str()); } - if (sPlayerbotAIConfig->hasLog("pathfind_attempt.csv") && (type == PATHFIND_INCOMPLETE || type == PATHFIND_NORMAL)) + if (sPlayerbotAIConfig.hasLog("pathfind_attempt.csv") && (type == PATHFIND_INCOMPLETE || type == PATHFIND_NORMAL)) { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr() << "+00,"; + out << sPlayerbotAIConfig.GetTimestampStr() << "+00,"; out << std::fixed << std::setprecision(1) << type << ","; printWKT(fromPointsArray(points), out, 1); - sPlayerbotAIConfig->log("pathfind_attempt.csv", out.str().c_str()); + sPlayerbotAIConfig.log("pathfind_attempt.csv", out.str().c_str()); } if (type == PATHFIND_INCOMPLETE || type == PATHFIND_NORMAL) @@ -796,7 +798,7 @@ std::vector WorldPosition::getPathFromPath(std::vectortargetPosRecalcDistance) + if (subPath.empty() || currentPos.distance(&subPath.back()) < sPlayerbotAIConfig.targetPosRecalcDistance) break; // Append the path excluding the start (this should be the same as the end of the startPath) @@ -1071,7 +1073,7 @@ std::vector TravelDestination::sortedPoints(WorldPosition* pos) std::vector TravelDestination::nextPoint(WorldPosition* pos, bool ignoreFull) { - return sTravelMgr->getNextPoint(pos, ignoreFull ? points : getPoints()); + return TravelMgr::instance().getNextPoint(pos, ignoreFull ? points : getPoints()); } bool TravelDestination::isFull(bool ignoreFull) @@ -1108,7 +1110,7 @@ bool QuestRelationTravelDestination::isActive(Player* bot) if (!bot->GetMap()->GetEntry()->IsWorldMap() || !bot->CanTakeQuest(questTemplate, false)) return false; - //uint32 dialogStatus = sTravelMgr->getDialogStatus(bot, entry, questTemplate); //not used, shadowed by the next declaration, line marked for removal. + //uint32 dialogStatus = TravelMgr::instance().getDialogStatus(bot, entry, questTemplate); //not used, shadowed by the next declaration, line marked for removal. if (AI_VALUE(bool, "can fight equal")) { @@ -1197,7 +1199,7 @@ bool QuestObjectiveTravelDestination::isActive(Player* bot) if (questTemplate->GetType() == QUEST_TYPE_ELITE && !AI_VALUE(bool, "can fight elite")) return false; - if (!sTravelMgr->getObjectiveStatus(bot, questTemplate, objective)) + if (!TravelMgr::instance().getObjectiveStatus(bot, questTemplate, objective)) return false; WorldPosition botPos(bot); @@ -1207,9 +1209,13 @@ bool QuestObjectiveTravelDestination::isActive(Player* bot) GuidVector targets = AI_VALUE(GuidVector, "possible targets"); for (auto& target : targets) - if (target.GetEntry() == getEntry() && target.IsCreature() && botAI->GetCreature(target) && + { + const int64_t targetEntry = target.GetEntry(); + + if (targetEntry == getEntry() && target.IsCreature() && botAI->GetCreature(target) && botAI->GetCreature(target)->IsAlive()) return true; + } return false; } @@ -1259,7 +1265,9 @@ bool RpgTravelDestination::isActive(Player* bot) for (ObjectGuid const guid : ignoreList) { - if (guid.GetEntry() == getEntry()) + const int64_t guidGetEntry = guid.GetEntry(); + + if (guidGetEntry == getEntry()) { return false; } @@ -1405,9 +1413,13 @@ bool BossTravelDestination::isActive(Player* bot) GuidVector targets = AI_VALUE(GuidVector, "possible targets"); for (auto& target : targets) - if (target.GetEntry() == getEntry() && target.IsCreature() && botAI->GetCreature(target) && + { + const int64_t targetEntry = target.GetEntry(); + + if (targetEntry == getEntry() && target.IsCreature() && botAI->GetCreature(target) && botAI->GetCreature(target)->IsAlive()) return true; + } return false; } @@ -1435,8 +1447,8 @@ TravelTarget::~TravelTarget() return; releaseVisitors(); - // sTravelMgr->botTargets.erase(std::remove(sTravelMgr->botTargets.begin(), sTravelMgr->botTargets.end(), this), - // sTravelMgr->botTargets.end()); + // TravelMgr::instance().botTargets.erase(std::remove(TravelMgr::instance().botTargets.begin(), TravelMgr::instance().botTargets.end(), this), + // TravelMgr::instance().botTargets.end()); } void TravelTarget::setTarget(TravelDestination* tDestination1, WorldPosition* wPosition1, bool groupCopy1) @@ -1509,7 +1521,7 @@ void TravelTarget::setStatus(TravelStatus status) statusTime = 1; break; case TRAVEL_STATUS_TRAVEL: - statusTime = getMaxTravelTime() * 2 + sPlayerbotAIConfig->maxWaitForMove; + statusTime = getMaxTravelTime() * 2 + sPlayerbotAIConfig.maxWaitForMove; break; case TRAVEL_STATUS_WORK: statusTime = tDestination->getExpireDelay(); @@ -1578,7 +1590,7 @@ bool TravelTarget::isTraveling() if (!botAI->HasStrategy("travel", BOT_STATE_NON_COMBAT)) { - setTarget(sTravelMgr->nullTravelDestination, sTravelMgr->nullWorldPosition, true); + setTarget(TravelMgr::instance().nullTravelDestination, TravelMgr::instance().nullWorldPosition, true); return false; } @@ -1610,7 +1622,7 @@ bool TravelTarget::isWorking() if (!botAI->HasStrategy("travel", BOT_STATE_NON_COMBAT)) { - setTarget(sTravelMgr->nullTravelDestination, sTravelMgr->nullWorldPosition, true); + setTarget(TravelMgr::instance().nullTravelDestination, TravelMgr::instance().nullWorldPosition, true); return false; } @@ -1767,7 +1779,7 @@ void TravelMgr::logQuestError(uint32 errorNr, Quest* quest, uint32 objective, ui void TravelMgr::LoadQuestTravelTable() { - if (!sTravelMgr->quests.empty()) + if (!TravelMgr::instance().quests.empty()) return; // Clearing store (for reloading case) @@ -1960,7 +1972,7 @@ void TravelMgr::LoadQuestTravelTable() bool loadQuestData = true; if (loadQuestData) { - questGuidpMap questMap = GAI_VALUE(questGuidpMap, "quest guidp map"); + questGuidpMap questMap = SharedValueContext::instance().getGlobalValue("quest guidp map")->Get(); for (auto& q : questMap) { @@ -1982,7 +1994,7 @@ void TravelMgr::LoadQuestTravelTable() if (flag & (uint32)QuestRelationFlag::questGiver) { loc = new QuestRelationTravelDestination( - questId, entry, 0, sPlayerbotAIConfig->tooCloseDistance, sPlayerbotAIConfig->sightDistance); + questId, entry, 0, sPlayerbotAIConfig.tooCloseDistance, sPlayerbotAIConfig.sightDistance); loc->setExpireDelay(5 * 60 * 1000); loc->setMaxVisitors(15, 0); container->questGivers.push_back(loc); @@ -1991,7 +2003,7 @@ void TravelMgr::LoadQuestTravelTable() if (flag & (uint32)QuestRelationFlag::questTaker) { loc = new QuestRelationTravelDestination( - questId, entry, 1, sPlayerbotAIConfig->tooCloseDistance, sPlayerbotAIConfig->sightDistance); + questId, entry, 1, sPlayerbotAIConfig.tooCloseDistance, sPlayerbotAIConfig.sightDistance); loc->setExpireDelay(5 * 60 * 1000); loc->setMaxVisitors(15, 0); container->questTakers.push_back(loc); @@ -2010,8 +2022,8 @@ void TravelMgr::LoadQuestTravelTable() objective = 3; loc = new QuestObjectiveTravelDestination(questId, entry, objective, - sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); + sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); loc->setExpireDelay(1 * 60 * 1000); loc->setMaxVisitors(100, 1); container->questObjectives.push_back(loc); @@ -2060,8 +2072,8 @@ void TravelMgr::LoadQuestTravelTable() int32 entry = r.type == 0 ? r.entry : r.entry * -1; - loc = new QuestRelationTravelDestination(r.questId, entry, r.role, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); loc->setExpireDelay(5 * 60 * 1000); loc->setMaxVisitors(15, 0); + loc = new QuestRelationTravelDestination(r.questId, entry, r.role, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); loc->setExpireDelay(5 * 60 * 1000); loc->setMaxVisitors(15, 0); for (auto& u : units) { @@ -2098,8 +2110,8 @@ void TravelMgr::LoadQuestTravelTable() uint32 reqEntry = quest->RequiredNpcOrGo[i]; - loc = new QuestObjectiveTravelDestination(questId, reqEntry, i, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); loc->setExpireDelay(1 * 60 * 1000); loc->setMaxVisitors(100, 1); + loc = new QuestObjectiveTravelDestination(questId, reqEntry, i, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); loc->setExpireDelay(1 * 60 * 1000); loc->setMaxVisitors(100, 1); for (auto& u : units) { @@ -2149,8 +2161,8 @@ void TravelMgr::LoadQuestTravelTable() int32 entry = l.type == 0 ? l.entry : l.entry * -1; - loc = new QuestObjectiveTravelDestination(questId, entry, i, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance, l.item); loc->setExpireDelay(1 * 60 * 1000); loc->setMaxVisitors(100, 1); + loc = new QuestObjectiveTravelDestination(questId, entry, i, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance, l.item); loc->setExpireDelay(1 * 60 * 1000); loc->setMaxVisitors(100, 1); for (auto& u : units) { @@ -2238,8 +2250,8 @@ void TravelMgr::LoadQuestTravelTable() { if ((cInfo->npcflag & *i) != 0) { - rLoc = new RpgTravelDestination(u.entry, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); + rLoc = new RpgTravelDestination(u.entry, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); rLoc->setExpireDelay(5 * 60 * 1000); rLoc->setMaxVisitors(15, 0); @@ -2251,8 +2263,8 @@ void TravelMgr::LoadQuestTravelTable() if (cInfo->mingold > 0) { - gLoc = new GrindTravelDestination(u.entry, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); + gLoc = new GrindTravelDestination(u.entry, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); gLoc->setExpireDelay(5 * 60 * 1000); gLoc->setMaxVisitors(100, 0); @@ -2265,8 +2277,8 @@ void TravelMgr::LoadQuestTravelTable() { std::string const nodeName = cInfo->Name; - bLoc = new BossTravelDestination(u.entry, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); + bLoc = new BossTravelDestination(u.entry, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); bLoc->setExpireDelay(5 * 60 * 1000); bLoc->setMaxVisitors(0, 0); @@ -2298,8 +2310,8 @@ void TravelMgr::LoadQuestTravelTable() if (iloc == exploreLocs.end()) { - loc = new ExploreTravelDestination(area->ID, sPlayerbotAIConfig->tooCloseDistance, - sPlayerbotAIConfig->sightDistance); + loc = new ExploreTravelDestination(area->ID, sPlayerbotAIConfig.tooCloseDistance, + sPlayerbotAIConfig.sightDistance); loc->setMaxVisitors(1000, 0); loc->setCooldownDelay(1000); loc->setExpireDelay(1000); @@ -2315,23 +2327,23 @@ void TravelMgr::LoadQuestTravelTable() } // Clear these logs files - sPlayerbotAIConfig->openLog("zones.csv", "w"); - sPlayerbotAIConfig->openLog("creatures.csv", "w"); - sPlayerbotAIConfig->openLog("gos.csv", "w"); - sPlayerbotAIConfig->openLog("bot_movement.csv", "w"); - sPlayerbotAIConfig->openLog("bot_pathfinding.csv", "w"); - sPlayerbotAIConfig->openLog("pathfind_attempt.csv", "w"); - sPlayerbotAIConfig->openLog("pathfind_attempt_point.csv", "w"); - sPlayerbotAIConfig->openLog("pathfind_result.csv", "w"); - sPlayerbotAIConfig->openLog("load_map_grid.csv", "w"); - sPlayerbotAIConfig->openLog("strategy.csv", "w"); + sPlayerbotAIConfig.openLog("zones.csv", "w"); + sPlayerbotAIConfig.openLog("creatures.csv", "w"); + sPlayerbotAIConfig.openLog("gos.csv", "w"); + sPlayerbotAIConfig.openLog("bot_movement.csv", "w"); + sPlayerbotAIConfig.openLog("bot_pathfinding.csv", "w"); + sPlayerbotAIConfig.openLog("pathfind_attempt.csv", "w"); + sPlayerbotAIConfig.openLog("pathfind_attempt_point.csv", "w"); + sPlayerbotAIConfig.openLog("pathfind_result.csv", "w"); + sPlayerbotAIConfig.openLog("load_map_grid.csv", "w"); + sPlayerbotAIConfig.openLog("strategy.csv", "w"); - sPlayerbotAIConfig->openLog("unload_grid.csv", "w"); - sPlayerbotAIConfig->openLog("unload_obj.csv", "w"); + sPlayerbotAIConfig.openLog("unload_grid.csv", "w"); + sPlayerbotAIConfig.openLog("unload_obj.csv", "w"); - sTravelNodeMap->loadNodeStore(); + TravelNodeMap::instance().loadNodeStore(); - sTravelNodeMap->generateAll(); + TravelNodeMap::instance().generateAll(); /* bool fullNavPointReload = false; @@ -2340,9 +2352,9 @@ void TravelMgr::LoadQuestTravelTable() if (!fullNavPointReload && true) TravelNodeStore::loadNodes(); - //sTravelNodeMap->loadNodeStore(); + //TravelNodeMap::instance().loadNodeStore(); - for (auto node : sTravelNodeMap->getNodes()) + for (auto node : TravelNodeMap::instance().getNodes()) { node->setLinked(true); } @@ -2384,7 +2396,7 @@ void TravelMgr::LoadQuestTravelTable() else nodeName += " flightMaster"; - sTravelNodeMap->addNode(&pos, nodeName, true, true); + TravelNodeMap::instance().addNode(&pos, nodeName, true, true); break; } @@ -2414,8 +2426,8 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition startPos(startTaxiNode->map_id, startTaxiNode->x, startTaxiNode->y, startTaxiNode->z); WorldPosition endPos(endTaxiNode->map_id, endTaxiNode->x, endTaxiNode->y, endTaxiNode->z); - TravelNode* startNode = sTravelNodeMap->getNode(&startPos, nullptr, 15.0f); - TravelNode* endNode = sTravelNodeMap->getNode(&endPos, nullptr, 15.0f); + TravelNode* startNode = TravelNodeMap::instance().getNode(&startPos, nullptr, 15.0f); + TravelNode* endNode = TravelNodeMap::instance().getNode(&endPos, nullptr, 15.0f); if (!startNode || !endNode) continue; @@ -2448,7 +2460,7 @@ void TravelMgr::LoadQuestTravelTable() if (cInfo->rank == 3 || (cInfo->rank == 1 && !pos.isOverworld() && u.c == 1)) { std::string const nodeName = cInfo->Name; - sTravelNodeMap->addNode(&pos, nodeName, true, true); + TravelNodeMap::instance().addNode(&pos, nodeName, true, true); } } @@ -2475,7 +2487,7 @@ void TravelMgr::LoadQuestTravelTable() pos = WorldPosition(info->mapId, info->positionX, info->positionY, info->positionZ, info->orientation); std::string const nodeName = startNames[i] + " start"; - sTravelNodeMap->addNode(&pos, nodeName, true, true); + TravelNodeMap::instance().addNode(&pos, nodeName, true, true); } } @@ -2530,7 +2542,7 @@ void TravelMgr::LoadQuestTravelTable() if (pos.distance(&lPos) == 0) { - TravelNode* node = sTravelNodeMap->addNode(&pos, data->name, true, true, true, + TravelNode* node = TravelNodeMap::instance().addNode(&pos, data->name, true, true, true, iter.first); if (!prevNode) @@ -2566,7 +2578,7 @@ void TravelMgr::LoadQuestTravelTable() if (pos.distance(&lPos) == 0) { - TravelNode* node = sTravelNodeMap->addNode(&pos, data->name, true, true, true, + TravelNode* node = TravelNodeMap::instance().addNode(&pos, data->name, true, true, true, iter.first); if (node != prevNode) { float totalTime = (p.second->TimeSeg - timeStart) / 1000.0f; @@ -2605,7 +2617,7 @@ void TravelMgr::LoadQuestTravelTable() if (p->delay > 0) { - TravelNode* node = sTravelNodeMap->addNode(&pos, data->name, true, true, true, iter.first); + TravelNode* node = TravelNodeMap::instance().addNode(&pos, data->name, true, true, true, iter.first); if (!prevNode) { @@ -2638,7 +2650,7 @@ void TravelMgr::LoadQuestTravelTable() if (p->delay > 0) { - TravelNode* node = sTravelNodeMap->getNode(&pos, nullptr, 5.0f); + TravelNode* node = TravelNodeMap::instance().getNode(&pos, nullptr, 5.0f); if (node != prevNode) { TravelNodePath travelPath(0.1f, 0.0, (uint8) TravelNodePathType::transport, entry, @@ -2667,13 +2679,13 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition pos = WorldPosition(points, WP_MEAN_CENTROID); - TravelNode* node = sTravelNodeMap->addNode(&pos, pos.getAreaName(), true, true, false); + TravelNode* node = TravelNodeMap::instance().addNode(&pos, pos.getAreaName(), true, true, false); } - LOG_INFO("playerbots", ">> Loaded {} navigation points.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Loaded {} navigation points.", TravelNodeMap::instance().getNodes().size()); } - sTravelNodeMap->calcMapOffset(); + TravelNodeMap::instance().calcMapOffset(); loadMapTransfers(); */ @@ -2692,14 +2704,14 @@ void TravelMgr::LoadQuestTravelTable() //PathGenerator std::vector ppath; - uint32 cur = 0, max = sTravelNodeMap->getNodes().size(); + uint32 cur = 0, max = TravelNodeMap::instance().getNodes().size(); - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { if (!preloadReLinkFullyLinked && startNode->isLinked()) continue; - for (auto& endNode : sTravelNodeMap->getNodes()) + for (auto& endNode : TravelNodeMap::instance().getNodes()) { if (startNode == endNode) continue; @@ -2734,18 +2746,18 @@ void TravelMgr::LoadQuestTravelTable() if (preloadSubPrint && (cur * 50) / max > ((cur - 1) * 50) / max) { - sTravelNodeMap->printMap(); - sTravelNodeMap->printNodeStore(); + TravelNodeMap::instance().printMap(); + TravelNodeMap::instance().printNodeStore(); } } if (!preloadSubPrint) { - sTravelNodeMap->printNodeStore(); - sTravelNodeMap->printMap(); + TravelNodeMap::instance().printNodeStore(); + TravelNodeMap::instance().printMap(); } - LOG_INFO("playerbots", ">> Loaded paths for {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Loaded paths for {} nodes.", TravelNodeMap::instance().getNodes().size()); } bool removeLowLinkNodes = false || fullNavPointReload || storeNavPointReload; @@ -2754,7 +2766,7 @@ void TravelMgr::LoadQuestTravelTable() { std::vector goodNodes; std::vector remNodes; - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) { if (!node->getPosition()->isOverworld()) continue; @@ -2774,9 +2786,9 @@ void TravelMgr::LoadQuestTravelTable() } for (auto& node : remNodes) - sTravelNodeMap->removeNode(node); + TravelNodeMap::instance().removeNode(node); - LOG_INFO("playerbots", ">> Checked {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Checked {} nodes.", TravelNodeMap::instance().getNodes().size()); } bool cleanUpNodeLinks = false || fullNavPointReload || storeNavPointReload; @@ -2786,22 +2798,22 @@ void TravelMgr::LoadQuestTravelTable() { //Routes uint32 cur = 0; - uint32 max = sTravelNodeMap->getNodes().size(); + uint32 max = TravelNodeMap::instance().getNodes().size(); //Clean up node links - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { startNode->cropUselessLinks(); cur++; if (cleanUpSubPrint && (cur * 10) / max > ((cur - 1) * 10) / max) { - sTravelNodeMap->printMap(); - sTravelNodeMap->printNodeStore(); + TravelNodeMap::instance().printMap(); + TravelNodeMap::instance().printNodeStore(); } } - LOG_INFO("playerbots", ">> Cleaned paths for {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Cleaned paths for {} nodes.", TravelNodeMap::instance().getNodes().size()); } bool reCalculateCost = false || fullNavPointReload || storeNavPointReload; @@ -2809,7 +2821,7 @@ void TravelMgr::LoadQuestTravelTable() if (reCalculateCost) { - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { for (auto& path : *startNode->getLinks()) { @@ -2825,14 +2837,14 @@ void TravelMgr::LoadQuestTravelTable() } } - LOG_INFO("playerbots", ">> Calculated pathcost for {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Calculated pathcost for {} nodes.", TravelNodeMap::instance().getNodes().size()); } bool mirrorMissingPaths = true || fullNavPointReload || storeNavPointReload; if (mirrorMissingPaths) { - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { for (auto& path : *startNode->getLinks()) { @@ -2855,16 +2867,16 @@ void TravelMgr::LoadQuestTravelTable() } } - LOG_INFO("playerbots", ">> Reversed missing paths for {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Reversed missing paths for {} nodes.", TravelNodeMap::instance().getNodes().size()); } */ - sTravelNodeMap->printMap(); - sTravelNodeMap->printNodeStore(); - sTravelNodeMap->saveNodeStore(); + TravelNodeMap::instance().printMap(); + TravelNodeMap::instance().printNodeStore(); + TravelNodeMap::instance().saveNodeStore(); // Creature/gos/zone export. - if (sPlayerbotAIConfig->hasLog("creatures.csv")) + if (sPlayerbotAIConfig.hasLog("creatures.csv")) { for (CreatureData const* cData : WorldPosition().getCreaturesNear()) { @@ -2889,11 +2901,11 @@ void TravelMgr::LoadQuestTravelTable() out << point.getAreaName() << ","; out << std::fixed; - sPlayerbotAIConfig->log("creatures.csv", out.str().c_str()); + sPlayerbotAIConfig.log("creatures.csv", out.str().c_str()); } } - if (sPlayerbotAIConfig->hasLog("vmangoslines.csv")) + if (sPlayerbotAIConfig.hasLog("vmangoslines.csv")) { uint32 mapId = 0; std::vector pos; @@ -2924,7 +2936,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const ironforgeAreaSouthLimit[] = { -7491.33f, 3093.740f, -7472.04f, -391.880f, -6366.68f, -730.100f, -6063.96f, -1411.76f, @@ -2951,7 +2963,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const stormwindAreaNorthLimit[] = { -8004.250f, 3714.110f, -8075.000f, -179.000f, -8638.000f, 169.0000f, -9044.000f, 35.00000f, @@ -2979,7 +2991,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const stormwindAreaSouthLimit[] = { -8725.3378910f, 3535.62402300f, -9525.6992190f, 910.13256800f, -9796.9531250f, 839.06958000f, @@ -3010,7 +3022,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); mapId = 1; @@ -3044,7 +3056,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const durotarSouthLimit[] = { 2755.0f, -3766.f, 2225.0f, -3596.f, 1762.0f, -3746.f, 1564.0f, -3943.f, 1184.0f, -3915.f, 737.00f, @@ -3072,7 +3084,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const valleyoftrialsSouthLimit[] = {-324.f, -3869.f, -774.f, -3992.f, -965.f, -4290.f, -932.f, -4349.f, -828.f, -4414.f, -661.f, -4541.f, -521.f, -4582.f}; @@ -3097,7 +3109,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const middleToSouthLimit[] = { -2402.010000f, 4255.7000000f, -2475.933105f, 3199.5683590f, // Desolace @@ -3129,7 +3141,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const orgrimmarSouthLimit[] = { 2132.5076f, -3912.2478f, 1944.4298f, -3855.2583f, 1735.6906f, -3834.2417f, 1654.3671f, -3380.9902f, @@ -3157,7 +3169,7 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); static float const feralasThousandNeedlesSouthLimit[] = { -6495.4995f, -4711.9810f, -6674.9995f, -4515.0019f, -6769.5717f, -4122.4272f, -6838.2651f, -3874.2792f, @@ -3187,10 +3199,10 @@ void TravelMgr::LoadQuestTravelTable() WorldPosition().printWKT(pos, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("vmangoslines.csv", out.str().c_str()); + sPlayerbotAIConfig.log("vmangoslines.csv", out.str().c_str()); } - if (sPlayerbotAIConfig->hasLog("gos.csv")) + if (sPlayerbotAIConfig.hasLog("gos.csv")) { for (GameObjectData const* gData : WorldPosition().getGameObjectsNear()) { @@ -3212,11 +3224,11 @@ void TravelMgr::LoadQuestTravelTable() out << point.getAreaName() << ","; out << std::fixed; - sPlayerbotAIConfig->log("gos.csv", out.str().c_str()); + sPlayerbotAIConfig.log("gos.csv", out.str().c_str()); } } - if (sPlayerbotAIConfig->hasLog("zones.csv")) + if (sPlayerbotAIConfig.hasLog("zones.csv")) { std::unordered_map> zoneLocs; @@ -3238,7 +3250,7 @@ void TravelMgr::LoadQuestTravelTable() if (loc.second.empty()) continue; - if (!sTravelNodeMap->getMapOffset(loc.second.front().getMapId()) && loc.second.front().getMapId() != 0) + if (!TravelNodeMap::instance().getMapOffset(loc.second.front().getMapId()) && loc.second.front().getMapId() != 0) continue; std::vector points = loc.second; @@ -3266,13 +3278,13 @@ void TravelMgr::LoadQuestTravelTable() point.printWKT(points, out, 0); - sPlayerbotAIConfig->log("zones.csv", out.str().c_str()); + sPlayerbotAIConfig.log("zones.csv", out.str().c_str()); } } bool printStrategyMap = false; - if (printStrategyMap && sPlayerbotAIConfig->hasLog("strategy.csv")) + if (printStrategyMap && sPlayerbotAIConfig.hasLog("strategy.csv")) { static std::map classes; static std::map> specs; @@ -3328,7 +3340,7 @@ void TravelMgr::LoadQuestTravelTable() // Use randombot 0. std::ostringstream cout; - cout << sPlayerbotAIConfig->randomBotAccountPrefix << 0; + cout << sPlayerbotAIConfig.randomBotAccountPrefix << 0; std::string const accountName = cout.str(); LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME); @@ -3502,7 +3514,7 @@ void TravelMgr::LoadQuestTravelTable() return false; }); - sPlayerbotAIConfig->log("strategy.csv", "relevance, action, trigger, strategy, classes"); + sPlayerbotAIConfig.log("strategy.csv", "relevance, action, trigger, strategy, classes"); for (auto& actionkey : actionKeys) { @@ -3607,17 +3619,17 @@ void TravelMgr::LoadQuestTravelTable() out << actionkey << "\n"; } - sPlayerbotAIConfig->log("strategy.csv", out.str().c_str()); + sPlayerbotAIConfig.log("strategy.csv", out.str().c_str()); } } /* - sPlayerbotAIConfig->openLog(7, "w"); + sPlayerbotAIConfig.openLog(7, "w"); //Zone area map REMOVE! uint32 k = 0; - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) { WorldPosition* pos = node->getPosition(); //map area @@ -3642,7 +3654,7 @@ void TravelMgr::LoadQuestTravelTable() std::ostringstream out; out << std::fixed << area << "," << npos.getDisplayX() << "," << npos.getDisplayY(); - sPlayerbotAIConfig->log(7, out.str().c_str()); + sPlayerbotAIConfig.log(7, out.str().c_str()); } } k++; @@ -3653,7 +3665,7 @@ void TravelMgr::LoadQuestTravelTable() //Explore map output (REMOVE!) - sPlayerbotAIConfig->openLog(5, "w"); + sPlayerbotAIConfig.openLog(5, "w"); for (auto i : exploreLocs) { for (auto j : i.second->getPoints()) @@ -3662,7 +3674,7 @@ void TravelMgr::LoadQuestTravelTable() std::string const name = i.second->getTitle(); name.erase(remove(name.begin(), name.end(), '\"'), name.end()); out << std::fixed << std::setprecision(2) << name.c_str() << "," << i.first << "," << j->getDisplayX() << - "," << j->getDisplayY() << "," << j->getX() << "," << j->getY() << "," << j->getZ(); sPlayerbotAIConfig->log(5, + "," << j->getDisplayY() << "," << j->getX() << "," << j->getY() << "," << j->getZ(); sPlayerbotAIConfig.log(5, out.str().c_str()); } } @@ -3783,7 +3795,7 @@ uint32 TravelMgr::getDialogStatus(Player* pPlayer, int32 questgiver, Quest const // Selects a random WorldPosition from a list. Use a distance weighted distribution. std::vector TravelMgr::getNextPoint(WorldPosition* center, std::vector points, - uint32 amount) + uint32) { std::vector retVec; @@ -3897,7 +3909,7 @@ bool TravelMgr::getObjectiveStatus(Player* bot, Quest const* pQuest, uint32 obje if (bot->GetQuestStatus(questId) != QUEST_STATUS_INCOMPLETE) return false; - QuestStatusData* questStatus = sTravelMgr->getQuestStatus(bot, questId); + QuestStatusData* questStatus = TravelMgr::instance().getQuestStatus(bot, questId); uint32 reqCount = pQuest->RequiredItemCount[objective]; uint32 hasCount = questStatus->ItemCount[objective]; @@ -4037,7 +4049,7 @@ std::vector TravelMgr::getRpgTravelDestinations(Player* bot, retTravelLocations.push_back(dest); } - return std::move(retTravelLocations); + return retTravelLocations; } std::vector TravelMgr::getExploreTravelDestinations(Player* bot, bool ignoreFull, @@ -4097,7 +4109,7 @@ void TravelMgr::setNullTravelTarget(Player* player) TravelTarget* target = playerBotAI->GetAiObjectContext()->GetValue("travel target")->Get(); if (target) - target->setTarget(sTravelMgr->nullTravelDestination, sTravelMgr->nullWorldPosition, true); + target->setTarget(TravelMgr::instance().nullTravelDestination, TravelMgr::instance().nullWorldPosition, true); } void TravelMgr::addMapTransfer(WorldPosition start, WorldPosition end, float portalDistance, bool makeShortcuts) @@ -4146,7 +4158,7 @@ void TravelMgr::addMapTransfer(WorldPosition start, WorldPosition end, float por void TravelMgr::loadMapTransfers() { - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) { for (auto& link : *node->getLinks()) { @@ -4233,15 +4245,15 @@ void TravelMgr::printGrid(uint32 mapId, int x, int y, std::string const type) { std::string const fileName = "unload_grid.csv"; - if (sPlayerbotAIConfig->hasLog(fileName)) + if (sPlayerbotAIConfig.hasLog(fileName)) { WorldPosition p = WorldPosition(mapId, 0, 0, 0, 0); std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); + out << sPlayerbotAIConfig.GetTimestampStr(); out << "+00, " << 0 << 0 << x << "," << y << ", " << type << ","; p.printWKT(p.fromGridCoord(GridCoord(x, y)), out, 1, true); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); + sPlayerbotAIConfig.log(fileName, out.str().c_str()); } } @@ -4249,7 +4261,7 @@ void TravelMgr::printObj(WorldObject* obj, std::string const type) { std::string fileName = "unload_grid.csv"; - if (sPlayerbotAIConfig->hasLog(fileName)) + if (sPlayerbotAIConfig.hasLog(fileName)) { WorldPosition p = WorldPosition(obj); @@ -4261,40 +4273,40 @@ void TravelMgr::printObj(WorldObject* obj, std::string const type) { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); + out << sPlayerbotAIConfig.GetTimestampStr(); out << "+00, " << obj->GetGUID().GetEntry() << "," << obj->GetGUID().GetCounter() << "," << cell.GridX() << "," << cell.GridY() << ", " << type << ","; p.printWKT(vcell, out, 1, true); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); + sPlayerbotAIConfig.log(fileName, out.str().c_str()); } { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); + out << sPlayerbotAIConfig.GetTimestampStr(); out << "+00, " << obj->GetGUID().GetEntry() << "," << obj->GetGUID().GetCounter() << "," << cell.GridX() << "," << cell.GridY() << ", " << type << ","; p.printWKT(vgrid, out, 1, true); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); + sPlayerbotAIConfig.log(fileName, out.str().c_str()); } } fileName = "unload_obj.csv"; - if (sPlayerbotAIConfig->hasLog(fileName)) + if (sPlayerbotAIConfig.hasLog(fileName)) { WorldPosition p = WorldPosition(obj); Cell cell(obj->GetPositionX(), obj->GetPositionY()); { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); + out << sPlayerbotAIConfig.GetTimestampStr(); out << "+00, " << obj->GetGUID().GetEntry() << "," << obj->GetGUID().GetCounter() << "," << cell.GridX() << "," << cell.GridY() << ", " << type << ","; p.printWKT({p}, out, 0); - sPlayerbotAIConfig->log(fileName, out.str().c_str()); + sPlayerbotAIConfig.log(fileName, out.str().c_str()); } } } diff --git a/src/Mgr/Travel/TravelMgr.h b/src/Mgr/Travel/TravelMgr.h index 39a79a4078..3223444bfe 100644 --- a/src/Mgr/Travel/TravelMgr.h +++ b/src/Mgr/Travel/TravelMgr.h @@ -10,7 +10,6 @@ #include #include "AiObject.h" -#include "Corpse.h" #include "CreatureData.h" #include "GameObject.h" #include "GridDefines.h" @@ -298,11 +297,11 @@ class WorldPosition : public WorldLocation std::vector getPathTo(WorldPosition endPos, Unit* bot) { return endPos.getPathFrom(*this, bot); } - bool isPathTo(std::vector path, float maxDistance = sPlayerbotAIConfig->targetPosRecalcDistance) + bool isPathTo(std::vector path, float maxDistance = sPlayerbotAIConfig.targetPosRecalcDistance) { return !path.empty() && distance(path.back()) < maxDistance; }; - bool cropPathTo(std::vector& path, float maxDistance = sPlayerbotAIConfig->targetPosRecalcDistance); + bool cropPathTo(std::vector& path, float maxDistance = sPlayerbotAIConfig.targetPosRecalcDistance); bool canPathTo(WorldPosition endPos, Unit* bot) { return endPos.isPathTo(getPathTo(endPos, bot)); } float getPathLength(std::vector points) @@ -848,12 +847,11 @@ class TravelTarget : AiObject class TravelMgr { public: - TravelMgr(){}; - - static TravelMgr* instance() + static TravelMgr& instance() { static TravelMgr instance; - return &instance; + + return instance; } void Clear(); @@ -922,7 +920,6 @@ class TravelMgr void printGrid(uint32 mapId, int x, int y, std::string const type); void printObj(WorldObject* obj, std::string const type); - // protected: void logQuestError(uint32 errorNr, Quest* quest, uint32 objective = 0, uint32 unitId = 0, uint32 itemId = 0); std::vector avoidLoaded; @@ -939,8 +936,16 @@ class TravelMgr std::unordered_map, std::vector, boost::hash>> mapTransfersMap; -}; -#define sTravelMgr TravelMgr::instance() +private: + TravelMgr() = default; + ~TravelMgr() = default; + + TravelMgr(const TravelMgr&) = delete; + TravelMgr& operator=(const TravelMgr&) = delete; + + TravelMgr(TravelMgr&&) = delete; + TravelMgr& operator=(TravelMgr&&) = delete; +}; #endif diff --git a/src/Mgr/Travel/TravelNode.cpp b/src/Mgr/Travel/TravelNode.cpp index d3c03ed97e..0cb88f9b11 100644 --- a/src/Mgr/Travel/TravelNode.cpp +++ b/src/Mgr/Travel/TravelNode.cpp @@ -323,7 +323,7 @@ void TravelNode::removeLinkTo(TravelNode* node, bool removePaths) else { // Remove all references to this node. - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) { if (node->hasPathTo(this)) node->removeLinkTo(this, removePaths); @@ -364,7 +364,7 @@ std::vector TravelNode::getNodeMap(bool importantOnly, std::vector< } } - return std::move(closeList); + return closeList; } bool TravelNode::isUselessLink(TravelNode* farNode) @@ -397,7 +397,7 @@ bool TravelNode::isUselessLink(TravelNode* farNode) } else { - TravelNodeRoute route = sTravelNodeMap->getRoute(nearNode, farNode, nullptr); + TravelNodeRoute route = TravelNodeMap::instance().getRoute(nearNode, farNode, nullptr); if (route.isEmpty()) continue; @@ -432,7 +432,7 @@ bool TravelNode::cropUselessLinks() this->removeLinkTo(farNode); hasRemoved = true; - if (sPlayerbotAIConfig->hasLog("crop.csv")) + if (sPlayerbotAIConfig.hasLog("crop.csv")) { std::ostringstream out; out << getName() << ","; @@ -440,7 +440,7 @@ bool TravelNode::cropUselessLinks() WorldPosition().printWKT({*getPosition(), *farNode->getPosition()}, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("crop.csv", out.str().c_str()); + sPlayerbotAIConfig.log("crop.csv", out.str().c_str()); } } @@ -449,7 +449,7 @@ bool TravelNode::cropUselessLinks() farNode->removeLinkTo(this); hasRemoved = true; - if (sPlayerbotAIConfig->hasLog("crop.csv")) + if (sPlayerbotAIConfig.hasLog("crop.csv")) { std::ostringstream out; out << getName() << ","; @@ -457,7 +457,7 @@ bool TravelNode::cropUselessLinks() WorldPosition().printWKT({*getPosition(), *farNode->getPosition()}, out, 1); out << std::fixed; - sPlayerbotAIConfig->log("crop.csv", out.str().c_str()); + sPlayerbotAIConfig.log("crop.csv", out.str().c_str()); } } } @@ -496,7 +496,7 @@ bool TravelNode::cropUselessLinks() } else { - TravelNodeRoute route = sTravelNodeMap->getRoute(firstNode, secondNode, false); + TravelNodeRoute route = TravelNodeMap::instance().getRoute(firstNode, secondNode, false); if (route.isEmpty()) continue; @@ -544,7 +544,7 @@ bool TravelNode::cropUselessLinks() } else { - TravelNodeRoute route = sTravelNodeMap->getRoute(firstNode, secondNode, false); + TravelNodeRoute route = TravelNodeMap::instance().getRoute(firstNode, secondNode, false); if (route.isEmpty()) continue; @@ -579,7 +579,7 @@ bool TravelNode::isEqual(TravelNode* compareNode) if (!compareNode->hasLinkTo(this)) return false; - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) { if (node == this || node == compareNode) continue; @@ -611,11 +611,11 @@ void TravelNode::print([[maybe_unused]] bool printFailed) out << (isImportant() ? 1 : 0) << ","; out << mapSize; - sPlayerbotAIConfig->log("travelNodes.csv", out.str().c_str()); + sPlayerbotAIConfig.log("travelNodes.csv", out.str().c_str()); std::vector ppath; - for (auto& endNode : sTravelNodeMap->getNodes()) + for (auto& endNode : TravelNodeMap::instance().getNodes()) { if (endNode == this) continue; @@ -665,7 +665,7 @@ void TravelNode::print([[maybe_unused]] bool printFailed) out << std::to_string(path->getMaxLevelCreature()[1]) << ","; out << std::to_string(path->getMaxLevelCreature()[2]); - sPlayerbotAIConfig->log("travelPaths.csv", out.str().c_str()); + sPlayerbotAIConfig.log("travelPaths.csv", out.str().c_str()); } } } @@ -695,8 +695,8 @@ bool TravelPath::makeShortCut(WorldPosition startPos, float maxDist) totalDist += p.point.sqDistance(std::prev(&p)->point); if (curDist < - sPlayerbotAIConfig->tooCloseDistance * - sPlayerbotAIConfig->tooCloseDistance) // We are on the path. This is a good starting point + sPlayerbotAIConfig.tooCloseDistance * + sPlayerbotAIConfig.tooCloseDistance) // We are on the path. This is a good starting point { minDist = curDist; totalDist = curDist; @@ -731,11 +731,11 @@ bool TravelPath::makeShortCut(WorldPosition startPos, float maxDist) WorldPosition beginPos = newPath.begin()->point; // The old path seems to be the best. - if (beginPos.distance(firstNode) < sPlayerbotAIConfig->tooCloseDistance) + if (beginPos.distance(firstNode) < sPlayerbotAIConfig.tooCloseDistance) return false; // We are (nearly) on the new path. Just follow the rest. - if (beginPos.distance(startPos) < sPlayerbotAIConfig->tooCloseDistance) + if (beginPos.distance(startPos) < sPlayerbotAIConfig.tooCloseDistance) { fullPath = newPath; return true; @@ -891,7 +891,7 @@ WorldPosition TravelPath::getNextPoint(WorldPosition startPos, float maxDist, Tr } // We have to move far for next point. Try to make a cropped path. - if (moveDist < sPlayerbotAIConfig->targetPosRecalcDistance && std::next(startP) != ed) + if (moveDist < sPlayerbotAIConfig.targetPosRecalcDistance && std::next(startP) != ed) { // std::vector path = startPos.getPathTo(std::next(startP)->point, nullptr); // startP->point = startPos.lastInRange(path, -1, maxDist); @@ -905,7 +905,7 @@ std::ostringstream const TravelPath::print() { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); + out << sPlayerbotAIConfig.GetTimestampStr(); out << "+00," << "1,"; out << std::fixed; @@ -1031,7 +1031,7 @@ std::ostringstream const TravelNodeRoute::print() { std::ostringstream out; - out << sPlayerbotAIConfig->GetTimestampStr(); + out << sPlayerbotAIConfig.GetTimestampStr(); out << "+00" << ",0," << "\"LINESTRING("; @@ -1046,34 +1046,6 @@ std::ostringstream const TravelNodeRoute::print() return out; } -TravelNodeMap::TravelNodeMap(TravelNodeMap* baseMap) -{ - TravelNode* newNode; - - baseMap->m_nMapMtx.lock_shared(); - - for (auto& node : baseMap->getNodes()) - { - newNode = new TravelNode(node); - - m_nodes.push_back(newNode); - } - - for (auto& node : baseMap->getNodes()) - { - newNode = getNode(node); - - for (auto& path : *node->getPaths()) - { - TravelNode* endNode = getNode(path.first); - - newNode->setPathTo(endNode, path.second); - } - } - - baseMap->m_nMapMtx.unlock_shared(); -} - TravelNode* TravelNodeMap::addNode(WorldPosition pos, std::string const preferedName, bool isImportant, bool checkDuplicate, [[maybe_unused]] bool transport, [[maybe_unused]] uint32 transportId) @@ -1163,7 +1135,7 @@ std::vector TravelNodeMap::getNodes(WorldPosition pos, float range) [pos](TravelNode* i, TravelNode* j) { return i->getPosition()->distance(pos) < j->getPosition()->distance(pos); }); - return std::move(retVec); + return retVec; } TravelNode* TravelNodeMap::getNode(WorldPosition pos, [[maybe_unused]] std::vector& ppath, Unit* bot, @@ -1178,7 +1150,7 @@ TravelNode* TravelNodeMap::getNode(WorldPosition pos, [[maybe_unused]] std::vect uint32 c = 0; - std::vector nodes = sTravelNodeMap->getNodes(pos, range); + std::vector nodes = TravelNodeMap::instance().getNodes(pos, range); for (auto& node : nodes) { if (!bot || pos.canPathTo(*node->getPosition(), bot)) @@ -1233,14 +1205,14 @@ TravelNodeRoute TravelNodeMap::getRoute(TravelNode* start, TravelNode* goal, Pla { AiObjectContext* context = botAI->GetAiObjectContext(); - TravelNode* homeNode = sTravelNodeMap->getNode(AI_VALUE(WorldPosition, "home bind"), nullptr, 10.0f); + TravelNode* homeNode = TravelNodeMap::instance().getNode(AI_VALUE(WorldPosition, "home bind"), nullptr, 10.0f); if (homeNode) { - PortalNode* portNode = (PortalNode*)sTravelNodeMap->teleportNodes[bot->GetGUID()][8690]; + PortalNode* portNode = (PortalNode*)TravelNodeMap::instance().teleportNodes[bot->GetGUID()][8690]; { portNode = new PortalNode(start); - sTravelNodeMap->teleportNodes[bot->GetGUID()][8690] = portNode; + TravelNodeMap::instance().teleportNodes[bot->GetGUID()][8690] = portNode; } portNode->SetPortal(start, homeNode, 8690); @@ -1370,7 +1342,7 @@ TravelNodeRoute TravelNodeMap::getRoute(WorldPosition startPos, WorldPosition en WorldPosition startNodePosition = *startNode->getPosition(); WorldPosition endNodePosition = *endNode->getPosition(); - float maxStartDistance = startNode->isTransport() ? 20.0f : sPlayerbotAIConfig->targetPosRecalcDistance; + float maxStartDistance = startNode->isTransport() ? 20.0f : sPlayerbotAIConfig.targetPosRecalcDistance; TravelNodeRoute route = getRoute(startNode, endNode, bot); @@ -1403,10 +1375,10 @@ TravelNodeRoute TravelNodeMap::getRoute(WorldPosition startPos, WorldPosition en if (bot && !bot->HasSpellCooldown(8690)) { startPath.clear(); - TravelNode* botNode = sTravelNodeMap->teleportNodes[bot->GetGUID()][0]; + TravelNode* botNode = TravelNodeMap::instance().teleportNodes[bot->GetGUID()][0]; { botNode = new TravelNode(startPos, "Bot Pos", false); - sTravelNodeMap->teleportNodes[bot->GetGUID()][0] = botNode; + TravelNodeMap::instance().teleportNodes[bot->GetGUID()][0] = botNode; } botNode->setPoint(startPos); @@ -1440,37 +1412,37 @@ TravelPath TravelNodeMap::getFullPath(WorldPosition startPos, WorldPosition endP //[[Node pathfinding system]] // We try to find nodes near the bot and near the end position that have a route between them. // Then bot has to move towards/along the route. - sTravelNodeMap->m_nMapMtx.lock_shared(); + TravelNodeMap::instance().m_nMapMtx.lock_shared(); // Find the route of nodes starting at a node closest to the start position and ending at a node closest to the // endposition. Also returns longPath: The path from the start position to the first node in the route. - TravelNodeRoute route = sTravelNodeMap->getRoute(startPos, endPos, beginPath, bot); + TravelNodeRoute route = TravelNodeMap::instance().getRoute(startPos, endPos, beginPath, bot); if (route.isEmpty()) return movePath; - if (sPlayerbotAIConfig->hasLog("bot_pathfinding.csv")) + if (sPlayerbotAIConfig.hasLog("bot_pathfinding.csv")) { if (botAI->HasStrategy("debug move", BOT_STATE_NON_COMBAT)) { - sPlayerbotAIConfig->openLog("bot_pathfinding.csv", "w"); - sPlayerbotAIConfig->log("bot_pathfinding.csv", route.print().str().c_str()); + sPlayerbotAIConfig.openLog("bot_pathfinding.csv", "w"); + sPlayerbotAIConfig.log("bot_pathfinding.csv", route.print().str().c_str()); } } endPath = route.getNodes().back()->getPosition()->getPathTo(endPos, nullptr); movePath = route.buildPath(beginPath, endPath); - if (sPlayerbotAIConfig->hasLog("bot_pathfinding.csv")) + if (sPlayerbotAIConfig.hasLog("bot_pathfinding.csv")) { if (botAI->HasStrategy("debug move", BOT_STATE_NON_COMBAT)) { - sPlayerbotAIConfig->openLog("bot_pathfinding.csv", "w"); - sPlayerbotAIConfig->log("bot_pathfinding.csv", movePath.print().str().c_str()); + sPlayerbotAIConfig.openLog("bot_pathfinding.csv", "w"); + sPlayerbotAIConfig.log("bot_pathfinding.csv", movePath.print().str().c_str()); } } - sTravelNodeMap->m_nMapMtx.unlock_shared(); + TravelNodeMap::instance().m_nMapMtx.unlock_shared(); return movePath; } @@ -1511,7 +1483,7 @@ TravelNode* TravelNodeMap::addZoneLinkNode(TravelNode* startNode) if (!getNode(pos, nullptr, 100.0f)) { std::string const nodeName = zoneName + " to " + newZoneName; - return sTravelNodeMap->addNode(pos, nodeName, false, true); + return TravelNodeMap::instance().addNode(pos, nodeName, false, true); } zoneName = newZoneName; @@ -1550,7 +1522,7 @@ TravelNode* TravelNodeMap::addRandomExtNode(TravelNode* startNode) WorldPosition point = path[urand(0, path.size() - 1)]; if (!getNode(point, nullptr, 100.0f)) - return sTravelNodeMap->addNode(point, startNode->getName(), false, true); + return TravelNodeMap::instance().addNode(point, startNode->getName(), false, true); } return nullptr; @@ -1606,7 +1578,7 @@ void TravelNodeMap::manageNodes(Unit* bot, bool mapFull) m_nMapMtx.unlock(); } - sTravelNodeMap->m_nMapMtx.lock_shared(); + TravelNodeMap::instance().m_nMapMtx.lock_shared(); if (!rePrint && mapFull) printMap(); @@ -1643,13 +1615,13 @@ void TravelNodeMap::generateNpcNodes() else if (cInfo->npcflag & UNIT_NPC_FLAG_SPIRITGUIDE) nodeName += " spiritguide"; - /*TravelNode* node = */ sTravelNodeMap->addNode(guidP, nodeName, true, true); //node not used, fragment marked for removal. + /*TravelNode* node = */ TravelNodeMap::instance().addNode(guidP, nodeName, true, true); //node not used, fragment marked for removal. } else if (cInfo->rank == 3) { std::string const nodeName = cInfo->Name; - sTravelNodeMap->addNode(guidP, nodeName, true, true); + TravelNodeMap::instance().addNode(guidP, nodeName, true, true); } else if (cInfo->rank == 1 && !guidP.isOverworld()) { @@ -1672,7 +1644,7 @@ void TravelNodeMap::generateNpcNodes() std::string const nodeName = cInfo->Name; - sTravelNodeMap->addNode(guidP, nodeName, true, true); + TravelNodeMap::instance().addNode(guidP, nodeName, true, true); } } @@ -1701,7 +1673,7 @@ void TravelNodeMap::generateStartNodes() std::string const nodeName = startNames[i] + " start"; - sTravelNodeMap->addNode(pos, nodeName, true, true); + TravelNodeMap::instance().addNode(pos, nodeName, true, true); break; } @@ -1733,7 +1705,7 @@ void TravelNodeMap::generateAreaTriggerNodes() else nodeName = inPos.getAreaName(false) + " portal"; - sTravelNodeMap->addNode(inPos, nodeName, true, true); + TravelNodeMap::instance().addNode(inPos, nodeName, true, true); } // Exit nodes @@ -1759,11 +1731,11 @@ void TravelNodeMap::generateAreaTriggerNodes() else nodeName = inPos.getAreaName(false) + " portal"; - //TravelNode* entryNode = sTravelNodeMap->getNode(outPos, nullptr, 20.0f); // Entry side, portal exit. //not used, line marked for removal. + //TravelNode* entryNode = TravelNodeMap::instance().getNode(outPos, nullptr, 20.0f); // Entry side, portal exit. //not used, line marked for removal. - TravelNode* outNode = sTravelNodeMap->addNode(outPos, nodeName, true, true); // Exit size, portal exit. + TravelNode* outNode = TravelNodeMap::instance().addNode(outPos, nodeName, true, true); // Exit size, portal exit. - TravelNode* inNode = sTravelNodeMap->getNode(inPos, nullptr, 5.0f); // Entry side, portal center. + TravelNode* inNode = TravelNodeMap::instance().getNode(inPos, nullptr, 5.0f); // Entry side, portal center. // Portal link from area trigger to area trigger destination. if (outNode && inNode) @@ -1826,7 +1798,7 @@ void TravelNodeMap::generateTransportNodes() if (pos.distance(&lPos) == 0) { TravelNode* node = - sTravelNodeMap->addNode(pos, data->name, true, true, true, itr.first); + TravelNodeMap::instance().addNode(pos, data->name, true, true, true, itr.first); if (!prevNode) { @@ -1866,7 +1838,7 @@ void TravelNodeMap::generateTransportNodes() if (pos.distance(&lPos) == 0) { TravelNode* node = - sTravelNodeMap->addNode(pos, data->name, true, true, true, itr.first); + TravelNodeMap::instance().addNode(pos, data->name, true, true, true, itr.first); if (node != prevNode) { if (p.second->TimeSeg < timeStart) @@ -1911,7 +1883,7 @@ void TravelNodeMap::generateTransportNodes() if (p->delay > 0) { - TravelNode* node = sTravelNodeMap->addNode(pos, data->name, true, true, true, itr.first); + TravelNode* node = TravelNodeMap::instance().addNode(pos, data->name, true, true, true, itr.first); if (!prevNode) { @@ -1946,7 +1918,7 @@ void TravelNodeMap::generateTransportNodes() if (p->delay > 0) { - TravelNode* node = sTravelNodeMap->getNode(pos, nullptr, 5.0f); + TravelNode* node = TravelNodeMap::instance().getNode(pos, nullptr, 5.0f); if (node != prevNode) { @@ -1968,7 +1940,7 @@ void TravelNodeMap::generateTransportNodes() void TravelNodeMap::generateZoneMeanNodes() { // Zone means - for (auto& loc : sTravelMgr->exploreLocs) + for (auto& loc : TravelMgr::instance().exploreLocs) { std::vector points; @@ -1981,7 +1953,7 @@ void TravelNodeMap::generateZoneMeanNodes() WorldPosition pos = WorldPosition(points, WP_MEAN_CENTROID); - /*TravelNode* node = */sTravelNodeMap->addNode(pos, pos.getAreaName(), true, true, false); //node not used, but addNode as side effect, fragment marked for removal. + /*TravelNode* node = */TravelNodeMap::instance().addNode(pos, pos.getAreaName(), true, true, false); //node not used, but addNode as side effect, fragment marked for removal. } } @@ -2006,19 +1978,19 @@ void TravelNodeMap::generateWalkPaths() std::map nodeMaps; - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { nodeMaps[startNode->getMapId()] = true; } for (auto& map : nodeMaps) { - for (auto& startNode : sTravelNodeMap->getNodes(WorldPosition(map.first, 1, 1))) + for (auto& startNode : TravelNodeMap::instance().getNodes(WorldPosition(map.first, 1, 1))) { if (startNode->isLinked()) continue; - for (auto& endNode : sTravelNodeMap->getNodes(*startNode->getPosition(), 2000.0f)) + for (auto& endNode : TravelNodeMap::instance().getNodes(*startNode->getPosition(), 2000.0f)) { if (startNode == endNode) continue; @@ -2036,7 +2008,7 @@ void TravelNodeMap::generateWalkPaths() } } - LOG_INFO("playerbots", ">> Generated paths for {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Generated paths for {} nodes.", TravelNodeMap::instance().getNodes().size()); } void TravelNodeMap::generateTaxiPaths() @@ -2066,8 +2038,8 @@ void TravelNodeMap::generateTaxiPaths() WorldPosition startPos(startTaxiNode->map_id, startTaxiNode->x, startTaxiNode->y, startTaxiNode->z); WorldPosition endPos(endTaxiNode->map_id, endTaxiNode->x, endTaxiNode->y, endTaxiNode->z); - TravelNode* startNode = sTravelNodeMap->getNode(startPos, nullptr, 15.0f); - TravelNode* endNode = sTravelNodeMap->getNode(endPos, nullptr, 15.0f); + TravelNode* startNode = TravelNodeMap::instance().getNode(startPos, nullptr, 15.0f); + TravelNode* endNode = TravelNodeMap::instance().getNode(endPos, nullptr, 15.0f); if (!startNode || !endNode) continue; @@ -2090,7 +2062,7 @@ void TravelNodeMap::removeLowNodes() { std::vector goodNodes; std::vector remNodes; - for (auto& node : sTravelNodeMap->getNodes()) + for (auto& node : TravelNodeMap::instance().getNodes()) { if (!node->getPosition()->isOverworld()) continue; @@ -2110,13 +2082,13 @@ void TravelNodeMap::removeLowNodes() } for (auto& node : remNodes) - sTravelNodeMap->removeNode(node); + TravelNodeMap::instance().removeNode(node); } void TravelNodeMap::removeUselessPaths() { // Clean up node links - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { for (auto& path : *startNode->getPaths()) if (path.second.getComplete() && startNode->hasLinkTo(path.first)) @@ -2127,7 +2099,7 @@ void TravelNodeMap::removeUselessPaths() { uint32 rem = 0; // Clean up node links - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { if (startNode->cropUselessLinks()) rem++; @@ -2146,7 +2118,7 @@ void TravelNodeMap::removeUselessPaths() void TravelNodeMap::calculatePathCosts() { - for (auto& startNode : sTravelNodeMap->getNodes()) + for (auto& startNode : TravelNodeMap::instance().getNodes()) { for (auto& path : *startNode->getLinks()) { @@ -2162,7 +2134,7 @@ void TravelNodeMap::calculatePathCosts() } } - LOG_INFO("playerbots", ">> Calculated pathcost for {} nodes.", sTravelNodeMap->getNodes().size()); + LOG_INFO("playerbots", ">> Calculated pathcost for {} nodes.", TravelNodeMap::instance().getNodes().size()); } void TravelNodeMap::generatePaths() @@ -2188,7 +2160,7 @@ void TravelNodeMap::generateAll() calcMapOffset(); LOG_INFO("playerbots", "-Generating maptransfers"); - sTravelMgr->loadMapTransfers(); + TravelMgr::instance().loadMapTransfers(); if (hasToGen || hasToFullGen) { @@ -2201,14 +2173,14 @@ void TravelNodeMap::generateAll() void TravelNodeMap::printMap() { - if (!sPlayerbotAIConfig->hasLog("travelNodes.csv") && !sPlayerbotAIConfig->hasLog("travelPaths.csv")) + if (!sPlayerbotAIConfig.hasLog("travelNodes.csv") && !sPlayerbotAIConfig.hasLog("travelPaths.csv")) return; printf("\r [Qgis] \r\x3D"); fflush(stdout); - sPlayerbotAIConfig->openLog("travelNodes.csv", "w"); - sPlayerbotAIConfig->openLog("travelPaths.csv", "w"); + sPlayerbotAIConfig.openLog("travelNodes.csv", "w"); + sPlayerbotAIConfig.openLog("travelPaths.csv", "w"); std::vector anodes = getNodes(); @@ -2224,26 +2196,26 @@ void TravelNodeMap::printNodeStore() { std::string const nodeStore = "TravelNodeStore.h"; - if (!sPlayerbotAIConfig->hasLog(nodeStore)) + if (!sPlayerbotAIConfig.hasLog(nodeStore)) return; printf("\r [Map] \r\x3D"); fflush(stdout); - sPlayerbotAIConfig->openLog(nodeStore, "w"); + sPlayerbotAIConfig.openLog(nodeStore, "w"); std::unordered_map saveNodes; std::vector anodes = getNodes(); - sPlayerbotAIConfig->log(nodeStore, "#pragma once"); - sPlayerbotAIConfig->log(nodeStore, "#include \"TravelMgr.h\""); - sPlayerbotAIConfig->log(nodeStore, "class TravelNodeStore"); - sPlayerbotAIConfig->log(nodeStore, " {"); - sPlayerbotAIConfig->log(nodeStore, " public:"); - sPlayerbotAIConfig->log(nodeStore, " static void loadNodes()"); - sPlayerbotAIConfig->log(nodeStore, " {"); - sPlayerbotAIConfig->log(nodeStore, " TravelNode** nodes = new TravelNode*[%zu];", anodes.size()); + sPlayerbotAIConfig.log(nodeStore, "#pragma once"); + sPlayerbotAIConfig.log(nodeStore, "#include \"TravelMgr.h\""); + sPlayerbotAIConfig.log(nodeStore, "class TravelNodeStore"); + sPlayerbotAIConfig.log(nodeStore, " {"); + sPlayerbotAIConfig.log(nodeStore, " public:"); + sPlayerbotAIConfig.log(nodeStore, " static void loadNodes()"); + sPlayerbotAIConfig.log(nodeStore, " {"); + sPlayerbotAIConfig.log(nodeStore, " TravelNode** nodes = new TravelNode*[%zu];", anodes.size()); for (uint32 i = 0; i < anodes.size(); i++) { @@ -2266,7 +2238,7 @@ void TravelNodeMap::printNodeStore() /* out << std::fixed << std::setprecision(2) << " nodes[" << i << "] = - sTravelNodeMap->addNode(&WorldPosition(" << node->getMapId() << "," << node->getX() << "f," << node->getY() + TravelNodeMap::instance().addNode(&WorldPosition(" << node->getMapId() << "," << node->getX() << "f," << node->getY() << "f," << node->getZ() << "f,"<< node->getO() <<"f), \"" << name << "\", " << (node->isImportant() ? "true" : "false") << ", true"; if (node->isTransport()) @@ -2274,7 +2246,7 @@ void TravelNodeMap::printNodeStore() out << ");"; */ - sPlayerbotAIConfig->log(nodeStore, out.str().c_str()); + sPlayerbotAIConfig.log(nodeStore, out.str().c_str()); saveNodes.insert(std::make_pair(node, i)); } @@ -2297,12 +2269,12 @@ void TravelNodeMap::printNodeStore() // out << std::fixed << std::setprecision(1) << " nodes[" << i << "]->setPathTo(nodes[" << // saveNodes.find(Link.first)->second << "],TravelNodePath("; out << Link.second->print() << "), true);"; - sPlayerbotAIConfig->log(nodeStore, out.str().c_str()); + sPlayerbotAIConfig.log(nodeStore, out.str().c_str()); } } - sPlayerbotAIConfig->log(nodeStore, " }"); - sPlayerbotAIConfig->log(nodeStore, "};"); + sPlayerbotAIConfig.log(nodeStore, " }"); + sPlayerbotAIConfig.log(nodeStore, "};"); printf("\r [Done] \r\x3D"); fflush(stdout); @@ -2322,7 +2294,7 @@ void TravelNodeMap::saveNodeStore() trans->Append(PlayerbotsDatabase.GetPreparedStatement(PLAYERBOTS_DEL_TRAVELNODE_PATH)); std::unordered_map saveNodes; - std::vector anodes = sTravelNodeMap->getNodes(); + std::vector anodes = TravelNodeMap::instance().getNodes(); for (uint32 i = 0; i < anodes.size(); i++) { diff --git a/src/Mgr/Travel/TravelNode.h b/src/Mgr/Travel/TravelNode.h index 3a86cbb169..41419f8a97 100644 --- a/src/Mgr/Travel/TravelNode.h +++ b/src/Mgr/Travel/TravelNode.h @@ -477,13 +477,11 @@ class TravelNodeStub class TravelNodeMap { public: - TravelNodeMap(){}; - TravelNodeMap(TravelNodeMap* baseMap); - - static TravelNodeMap* instance() + static TravelNodeMap& instance() { static TravelNodeMap instance; - return &instance; + + return instance; } TravelNode* addNode(WorldPosition pos, std::string const preferedName = "Travel Node", bool isImportant = false, @@ -586,6 +584,15 @@ class TravelNodeMap std::unordered_map> teleportNodes; private: + TravelNodeMap() = default; + ~TravelNodeMap() = default; + + TravelNodeMap(const TravelNodeMap&) = delete; + TravelNodeMap& operator=(const TravelNodeMap&) = delete; + + TravelNodeMap(TravelNodeMap&&) = delete; + TravelNodeMap& operator=(TravelNodeMap&&) = delete; + std::vector m_nodes; std::vector> mapOffsets; diff --git a/src/PlayerbotAIConfig.cpp b/src/PlayerbotAIConfig.cpp index b9ef257d95..f3201190c1 100644 --- a/src/PlayerbotAIConfig.cpp +++ b/src/PlayerbotAIConfig.cpp @@ -660,25 +660,25 @@ bool PlayerbotAIConfig::Initialize() } // Assign account types after accounts are created - sRandomPlayerbotMgr->AssignAccountTypes(); + sRandomPlayerbotMgr.AssignAccountTypes(); - if (sPlayerbotAIConfig->enabled) + if (sPlayerbotAIConfig.enabled) { - sRandomPlayerbotMgr->Init(); + sRandomPlayerbotMgr.Init(); } - sPlayerbotGuildMgr->Init(); - sRandomItemMgr->Init(); - sRandomItemMgr->InitAfterAhBot(); - sPlayerbotTextMgr->LoadBotTexts(); - sPlayerbotTextMgr->LoadBotTextChance(); + PlayerbotGuildMgr::instance().Init(); + sRandomItemMgr.Init(); + sRandomItemMgr.InitAfterAhBot(); + PlayerbotTextMgr::instance().LoadBotTexts(); + PlayerbotTextMgr::instance().LoadBotTextChance(); PlayerbotFactory::Init(); AiObjectContext::BuildAllSharedContexts(); - if (sPlayerbotAIConfig->randomBotSuggestDungeons) + if (sPlayerbotAIConfig.randomBotSuggestDungeons) { - sPlayerbotDungeonRepository->LoadDungeonSuggestions(); + PlayerbotDungeonRepository::instance().LoadDungeonSuggestions(); } excludedHunterPetFamilies.clear(); @@ -898,7 +898,7 @@ std::vector> PlayerbotAIConfig::ParseTempTalentsOrder(uint32 spells[talentTabInfo->tabpage].push_back(talentInfo); } - for (int tab = 0; tab < 3; tab++) + for (uint64_t tab = 0; tab < 3; tab++) { if (tab_links.size() <= tab) { @@ -907,7 +907,8 @@ std::vector> PlayerbotAIConfig::ParseTempTalentsOrder(uint32 std::sort(spells[tab].begin(), spells[tab].end(), [&](TalentEntry const* lhs, TalentEntry const* rhs) { return lhs->Row != rhs->Row ? lhs->Row < rhs->Row : lhs->Col < rhs->Col; }); - for (int i = 0; i < tab_links[tab].size(); i++) + + for (uint64_t i = 0; i < tab_links[tab].size(); ++i) { if (i >= spells[tab].size()) { @@ -956,7 +957,8 @@ std::vector> PlayerbotAIConfig::ParseTempPetTalentsOrder(uin std::sort(spells.begin(), spells.end(), [&](TalentEntry const* lhs, TalentEntry const* rhs) { return lhs->Row != rhs->Row ? lhs->Row < rhs->Row : lhs->Col < rhs->Col; }); - for (int i = 0; i < tab_link.size(); i++) + + for (uint64_t i = 0; i < tab_link.size(); ++i) { if (i >= spells.size()) { diff --git a/src/PlayerbotAIConfig.h b/src/PlayerbotAIConfig.h index fb112fc907..729fc5be16 100644 --- a/src/PlayerbotAIConfig.h +++ b/src/PlayerbotAIConfig.h @@ -8,11 +8,14 @@ #include #include +#include +#include +#include +#include +#include -#include "Common.h" #include "DBCEnums.h" #include "SharedDefines.h" -#include "Talentspec.h" enum class BotCheatMask : uint32 { @@ -62,11 +65,11 @@ enum NewRpgStatus : int class PlayerbotAIConfig { public: - PlayerbotAIConfig(){}; - static PlayerbotAIConfig* instance() + static PlayerbotAIConfig& instance() { static PlayerbotAIConfig instance; - return &instance; + + return instance; } bool Initialize(); @@ -449,6 +452,16 @@ class PlayerbotAIConfig bool IsRestrictedHealerDPSMap(uint32 mapId) const; std::vector excludedHunterPetFamilies; + +private: + PlayerbotAIConfig() = default; + ~PlayerbotAIConfig() = default; + + PlayerbotAIConfig(const PlayerbotAIConfig&) = delete; + PlayerbotAIConfig& operator=(const PlayerbotAIConfig&) = delete; + + PlayerbotAIConfig(PlayerbotAIConfig&&) = delete; + PlayerbotAIConfig& operator=(PlayerbotAIConfig&&) = delete; }; #define sPlayerbotAIConfig PlayerbotAIConfig::instance() diff --git a/src/Script/PlayerbotCommandScript.cpp b/src/Script/PlayerbotCommandScript.cpp index 4e3c5611f2..c12ed50afa 100644 --- a/src/Script/PlayerbotCommandScript.cpp +++ b/src/Script/PlayerbotCommandScript.cpp @@ -72,37 +72,37 @@ class playerbots_commandscript : public CommandScript return GuildTaskMgr::HandleConsoleCommand(handler, args); } - static bool HandlePerfMonCommand(ChatHandler* handler, char const* args) + static bool HandlePerfMonCommand(ChatHandler*, char const* args) { if (!strcmp(args, "reset")) { - sPerfMonitor->Reset(); + sPerfMonitor.Reset(); return true; } if (!strcmp(args, "tick")) { - sPerfMonitor->PrintStats(true, false); + sPerfMonitor.PrintStats(true, false); return true; } if (!strcmp(args, "stack")) { - sPerfMonitor->PrintStats(false, true); + sPerfMonitor.PrintStats(false, true); return true; } if (!strcmp(args, "toggle")) { - sPlayerbotAIConfig->perfMonEnabled = !sPlayerbotAIConfig->perfMonEnabled; - if (sPlayerbotAIConfig->perfMonEnabled) + sPlayerbotAIConfig.perfMonEnabled = !sPlayerbotAIConfig.perfMonEnabled; + if (sPlayerbotAIConfig.perfMonEnabled) LOG_INFO("playerbots", "Performance monitor enabled"); else LOG_INFO("playerbots", "Performance monitor disabled"); return true; } - sPerfMonitor->PrintStats(); + sPerfMonitor.PrintStats(); return true; } @@ -122,7 +122,7 @@ class playerbots_commandscript : public CommandScript Player* player = handler->GetSession()->GetPlayer(); std::string key = args; - PlayerbotMgr* mgr = sPlayerbotsMgr->GetPlayerbotMgr(player); + PlayerbotMgr* mgr = PlayerbotsMgr::instance().GetPlayerbotMgr(player); if (mgr) { mgr->HandleSetSecurityKeyCommand(player, key); @@ -151,7 +151,7 @@ class playerbots_commandscript : public CommandScript Player* player = handler->GetSession()->GetPlayer(); - PlayerbotMgr* mgr = sPlayerbotsMgr->GetPlayerbotMgr(player); + PlayerbotMgr* mgr = PlayerbotsMgr::instance().GetPlayerbotMgr(player); if (mgr) { mgr->HandleLinkAccountCommand(player, accountName, key); @@ -168,7 +168,7 @@ class playerbots_commandscript : public CommandScript { Player* player = handler->GetSession()->GetPlayer(); - PlayerbotMgr* mgr = sPlayerbotsMgr->GetPlayerbotMgr(player); + PlayerbotMgr* mgr = PlayerbotsMgr::instance().GetPlayerbotMgr(player); if (mgr) { mgr->HandleViewLinkedAccountsCommand(player); @@ -195,7 +195,7 @@ class playerbots_commandscript : public CommandScript Player* player = handler->GetSession()->GetPlayer(); - PlayerbotMgr* mgr = sPlayerbotsMgr->GetPlayerbotMgr(player); + PlayerbotMgr* mgr = PlayerbotsMgr::instance().GetPlayerbotMgr(player); if (mgr) { mgr->HandleUnlinkAccountCommand(player, accountName); diff --git a/src/Script/Playerbots.cpp b/src/Script/Playerbots.cpp index 8a8e1e0b73..438e1d6955 100644 --- a/src/Script/Playerbots.cpp +++ b/src/Script/Playerbots.cpp @@ -22,7 +22,6 @@ #include "DatabaseEnv.h" #include "DatabaseLoader.h" #include "GuildTaskMgr.h" -#include "Metric.h" #include "PlayerScript.h" #include "PlayerbotAIConfig.h" #include "PlayerbotGuildMgr.h" @@ -98,24 +97,24 @@ class PlayerbotsPlayerScript : public PlayerScript { if (!player->GetSession()->IsBot()) { - sPlayerbotsMgr->AddPlayerbotData(player, false); - sRandomPlayerbotMgr->OnPlayerLogin(player); + PlayerbotsMgr::instance().AddPlayerbotData(player, false); + sRandomPlayerbotMgr.OnPlayerLogin(player); // Before modifying the following messages, please make sure it does not violate the AGPLv3.0 license // especially if you are distributing a repack or hosting a public server // e.g. you can replace the URL with your own repository, // but it should be publicly accessible and include all modifications you've made - if (sPlayerbotAIConfig->enabled) + if (sPlayerbotAIConfig.enabled) { ChatHandler(player->GetSession()).SendSysMessage( "|cff00ff00This server runs with |cff00ccffmod-playerbots|r " "|cffcccccchttps://github.com/mod-playerbots/mod-playerbots|r"); } - if (sPlayerbotAIConfig->enabled || sPlayerbotAIConfig->randomBotAutologin) + if (sPlayerbotAIConfig.enabled || sPlayerbotAIConfig.randomBotAutologin) { std::string roundedTime = - std::to_string(std::ceil((sPlayerbotAIConfig->maxRandomBots * 0.11 / 60) * 10) / 10.0); + std::to_string(std::ceil((sPlayerbotAIConfig.maxRandomBots * 0.11 / 60) * 10) / 10.0); roundedTime = roundedTime.substr(0, roundedTime.find('.') + 2); ChatHandler(player->GetSession()).SendSysMessage( @@ -125,54 +124,11 @@ class PlayerbotsPlayerScript : public PlayerScript } } - bool OnPlayerBeforeTeleport(Player* /*player*/, uint32 /*mapid*/, float /*x*/, float /*y*/, float /*z*/, float /*orientation*/, uint32 /*options*/, Unit* /*target*/) override - { - /* for now commmented out until proven its actually required - * havent seen any proof CleanVisibilityReferences() is needed - - // If the player is not safe to touch, do nothing - if (!player) - return true; - - // If same map or not in world do nothing - if (!player->IsInWorld() || player->GetMapId() == mapid) - return true; - - // If real player do nothing - PlayerbotAI* ai = GET_PLAYERBOT_AI(player); - if (!ai || ai->IsRealPlayer()) - return true; - - // Cross-map bot teleport: defer visibility reference cleanup. - // CleanVisibilityReferences() erases this bot's GUID from other objects' visibility containers. - // This is intentionally done via the event queue (instead of directly here) because erasing - // from other players' visibility maps inside the teleport call stack can hit unsafe re-entrancy - // or iterator invalidation while visibility updates are in progress - ObjectGuid guid = player->GetGUID(); - player->m_Events.AddEventAtOffset( - [guid, mapid]() - { - // do nothing, if the player is not safe to touch - Player* p = ObjectAccessor::FindPlayer(guid); - if (!p || !p->IsInWorld() || p->IsDuringRemoveFromWorld()) - return; - - // do nothing if we are already on the target map - if (p->GetMapId() == mapid) - return; - - p->GetObjectVisibilityContainer().CleanVisibilityReferences(); - }, - Milliseconds(0)); - - */ - - return true; - } - void OnPlayerAfterUpdate(Player* player, uint32 diff) override { - if (PlayerbotAI* botAI = GET_PLAYERBOT_AI(player)) + PlayerbotAI* const botAI = PlayerbotsMgr::instance().GetPlayerbotAI(player); + + if (botAI != nullptr) { botAI->UpdateAI(diff); } @@ -185,19 +141,26 @@ class PlayerbotsPlayerScript : public PlayerScript bool OnPlayerCanUseChat(Player* player, uint32 type, uint32 /*lang*/, std::string& msg, Player* receiver) override { - if (type == CHAT_MSG_WHISPER) + if (type != CHAT_MSG_WHISPER) { - if (PlayerbotAI* botAI = GET_PLAYERBOT_AI(receiver)) - { - botAI->HandleCommand(type, msg, player); + return true; + } - // hotfix; otherwise the server will crash when whispering logout - // https://github.com/mod-playerbots/mod-playerbots/pull/1838 - // TODO: find the root cause and solve it. (does not happen in party chat) - if (msg == "logout") - return false; - } + PlayerbotAI* const botAI = PlayerbotsMgr::instance().GetPlayerbotAI(receiver); + + if (botAI == nullptr) + { + return true; } + + botAI->HandleCommand(type, msg, player); + + // hotfix; otherwise the server will crash when whispering logout + // https://github.com/mod-playerbots/mod-playerbots/pull/1838 + // TODO: find the root cause and solve it. (does not happen in party chat) + if (msg == "logout") + return false; + return true; } @@ -205,56 +168,77 @@ class PlayerbotsPlayerScript : public PlayerScript { for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { - if (Player* member = itr->GetSource()) + Player* const member = itr->GetSource(); + + if (member == nullptr) { - if (PlayerbotAI* botAI = GET_PLAYERBOT_AI(member)) - { - botAI->HandleCommand(type, msg, player); - } + continue; + } + + PlayerbotAI* const botAI = PlayerbotsMgr::instance().GetPlayerbotAI(member); + + if (botAI == nullptr) + { + continue; } + + botAI->HandleCommand(type, msg, player); } + return true; } - bool OnPlayerCanUseChat(Player* player, uint32 type, uint32 /*lang*/, std::string& msg, Guild* guild) override + bool OnPlayerCanUseChat(Player* player, uint32 type, uint32 /*lang*/, std::string& msg, Guild*) override { - if (type == CHAT_MSG_GUILD) + if (type != CHAT_MSG_GUILD) { - if (PlayerbotMgr* playerbotMgr = GET_PLAYERBOT_MGR(player)) + return true; + } + + PlayerbotMgr* playerbotMgr = PlayerbotsMgr::instance().GetPlayerbotMgr(player); + + if (playerbotMgr == nullptr) + { + return true; + } + + for (PlayerBotMap::const_iterator it = playerbotMgr->GetPlayerBotsBegin(); it != playerbotMgr->GetPlayerBotsEnd(); ++it) + { + Player* const bot = it->second; + + if (bot == nullptr) { - for (PlayerBotMap::const_iterator it = playerbotMgr->GetPlayerBotsBegin(); - it != playerbotMgr->GetPlayerBotsEnd(); ++it) - { - if (Player* const bot = it->second) - { - if (bot->GetGuildId() == player->GetGuildId()) - { - GET_PLAYERBOT_AI(bot)->HandleCommand(type, msg, player); - } - } - } + continue; } + + if (bot->GetGuildId() != player->GetGuildId()) + { + continue; + } + + PlayerbotsMgr::instance().GetPlayerbotAI(bot)->HandleCommand(type, msg, player); } + return true; } bool OnPlayerCanUseChat(Player* player, uint32 type, uint32 /*lang*/, std::string& msg, Channel* channel) override { - if (PlayerbotMgr* playerbotMgr = GET_PLAYERBOT_MGR(player)) + PlayerbotMgr* const playerbotMgr = PlayerbotsMgr::instance().GetPlayerbotMgr(player); + + if (playerbotMgr != nullptr && channel->GetFlags() & 0x18) { - if (channel->GetFlags() & 0x18) - { - playerbotMgr->HandleCommand(type, msg); - } + playerbotMgr->HandleCommand(type, msg); } - sRandomPlayerbotMgr->HandleCommand(type, msg, player); + sRandomPlayerbotMgr.HandleCommand(type, msg, player); + return true; } bool OnPlayerBeforeAchievementComplete(Player* player, AchievementEntry const* achievement) override { - if ((sRandomPlayerbotMgr->IsRandomBot(player) || sRandomPlayerbotMgr->IsAddclassBot(player)) && + if ((sRandomPlayerbotMgr.IsRandomBot(player) || sRandomPlayerbotMgr.IsAddclassBot(player)) && (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))) { return false; @@ -266,11 +250,11 @@ class PlayerbotsPlayerScript : public PlayerScript void OnPlayerGiveXP(Player* player, uint32& amount, Unit* /*victim*/, uint8 /*xpSource*/) override { // early return - if (sPlayerbotAIConfig->randomBotXPRate == 1.0 || !player) + if (sPlayerbotAIConfig.randomBotXPRate == 1.0 || !player) return; // no XP multiplier, when player is no bot. - if (!player->GetSession()->IsBot() || !sRandomPlayerbotMgr->IsRandomBot(player)) + if (!player->GetSession()->IsBot() || !sRandomPlayerbotMgr.IsRandomBot(player)) return; // no XP multiplier, when bot is in a group with a real player. @@ -292,7 +276,7 @@ class PlayerbotsPlayerScript : public PlayerScript } // otherwise apply bot XP multiplier. - amount = static_cast(std::round(static_cast(amount) * sPlayerbotAIConfig->randomBotXPRate)); + amount = static_cast(std::round(static_cast(amount) * sPlayerbotAIConfig.randomBotXPRate)); } }; @@ -303,7 +287,9 @@ class PlayerbotsMiscScript : public MiscScript void OnDestructPlayer(Player* player) override { - if (PlayerbotAI* botAI = GET_PLAYERBOT_AI(player)) + PlayerbotAI* botAI = PlayerbotsMgr::instance().GetPlayerbotAI(player); + + if (botAI != nullptr) { delete botAI; } @@ -360,20 +346,20 @@ class PlayerbotsWorldScript : public WorldScript LOG_INFO("server.loading", " "); LOG_INFO("server.loading", "Load Playerbots Config..."); - sPlayerbotAIConfig->Initialize(); + sPlayerbotAIConfig.Initialize(); LOG_INFO("server.loading", ">> Loaded playerbots config in {} ms", GetMSTimeDiffToNow(oldMSTime)); LOG_INFO("server.loading", " "); - sPlayerbotSpellRepository->Initialize(); + PlayerbotSpellRepository::Instance().Initialize(); LOG_INFO("server.loading", "Playerbots World Thread Processor initialized"); } void OnUpdate(uint32 diff) override { - sPlayerbotWorldProcessor->Update(diff); - sRandomPlayerbotMgr->UpdateAI(diff); // World thread only + PlayerbotWorldThreadProcessor::instance().Update(diff); + sRandomPlayerbotMgr.UpdateAI(diff); // World thread only } }; @@ -385,10 +371,12 @@ class PlayerbotsScript : public PlayerbotScript bool OnPlayerbotCheckLFGQueue(lfg::Lfg5Guids const& guidsList) override { bool nonBotFound = false; + for (ObjectGuid const& guid : guidsList.guids) { Player* player = ObjectAccessor::FindPlayer(guid); - if (guid.IsGroup() || (player && !GET_PLAYERBOT_AI(player))) + + if (guid.IsGroup() || (player && !PlayerbotsMgr::instance().GetPlayerbotAI(player))) { nonBotFound = true; break; @@ -401,41 +389,57 @@ class PlayerbotsScript : public PlayerbotScript void OnPlayerbotCheckKillTask(Player* player, Unit* victim) override { if (player) - sGuildTaskMgr->CheckKillTask(player, victim); + GuildTaskMgr::instance().CheckKillTask(player, victim); } void OnPlayerbotCheckPetitionAccount(Player* player, bool& found) override { - if (found && GET_PLAYERBOT_AI(player)) + if (!found) + { + return; + } + + if (PlayerbotsMgr::instance().GetPlayerbotAI(player) != nullptr) + { found = false; + } } bool OnPlayerbotCheckUpdatesToSend(Player* player) override { - if (PlayerbotAI* botAI = GET_PLAYERBOT_AI(player)) - return botAI->IsRealPlayer(); + PlayerbotAI* botAI = PlayerbotsMgr::instance().GetPlayerbotAI(player); - return true; + if (botAI == nullptr) + { + return true; + } + + return botAI->IsRealPlayer(); } void OnPlayerbotPacketSent(Player* player, WorldPacket const* packet) override { - if (!player) + if (player == nullptr) + { return; + } + + PlayerbotAI* botAI = PlayerbotsMgr::instance().GetPlayerbotAI(player); - if (PlayerbotAI* botAI = GET_PLAYERBOT_AI(player)) + if (botAI != nullptr) { botAI->HandleBotOutgoingPacket(*packet); } + if (PlayerbotMgr* playerbotMgr = GET_PLAYERBOT_MGR(player)) { playerbotMgr->HandleMasterOutgoingPacket(*packet); } } - void OnPlayerbotUpdate(uint32 diff) override + void OnPlayerbotUpdate(uint32) override { - sRandomPlayerbotMgr->UpdateSessions(); // Per-bot updates only + sRandomPlayerbotMgr.UpdateSessions(); // Per-bot updates only } void OnPlayerbotUpdateSessions(Player* player) override @@ -449,20 +453,21 @@ class PlayerbotsScript : public PlayerbotScript { if (PlayerbotMgr* playerbotMgr = GET_PLAYERBOT_MGR(player)) { - PlayerbotAI* botAI = GET_PLAYERBOT_AI(player); - if (!botAI || botAI->IsRealPlayer()) + PlayerbotAI* botAI = PlayerbotsMgr::instance().GetPlayerbotAI(player); + + if (botAI == nullptr || botAI->IsRealPlayer()) { playerbotMgr->LogoutAllBots(); } } - sRandomPlayerbotMgr->OnPlayerLogout(player); + sRandomPlayerbotMgr.OnPlayerLogout(player); } void OnPlayerbotLogoutBots() override { LOG_INFO("playerbots", "Logging out all bots..."); - sRandomPlayerbotMgr->LogoutAllBots(); + sRandomPlayerbotMgr.LogoutAllBots(); } }; diff --git a/src/Script/Playerbots.h b/src/Script/Playerbots.h index 72ea9e4f79..006f058f9d 100644 --- a/src/Script/Playerbots.h +++ b/src/Script/Playerbots.h @@ -27,8 +27,8 @@ int strcmpi(char const* s1, char const* s2); #define CAST_ANGLE_IN_FRONT (2.f * static_cast(M_PI) / 3.f) #define EMOTE_ANGLE_IN_FRONT (2.f * static_cast(M_PI) / 6.f) -#define GET_PLAYERBOT_AI(object) sPlayerbotsMgr->GetPlayerbotAI(object) -#define GET_PLAYERBOT_MGR(object) sPlayerbotsMgr->GetPlayerbotMgr(object) +#define GET_PLAYERBOT_AI(object) sPlayerbotsMgr.GetPlayerbotAI(object) +#define GET_PLAYERBOT_MGR(object) sPlayerbotsMgr.GetPlayerbotMgr(object) #define AI_VALUE(type, name) context->GetValue(name)->Get() #define AI_VALUE2(type, name, param) context->GetValue(name, param)->Get() @@ -43,10 +43,10 @@ int strcmpi(char const* s1, char const* s2); #define RESET_AI_VALUE(type, name) context->GetValue(name)->Reset() #define RESET_AI_VALUE2(type, name, param) context->GetValue(name, param)->Reset() -#define PAI_VALUE(type, name) sPlayerbotsMgr->GetPlayerbotAI(player)->GetAiObjectContext()->GetValue(name)->Get() +#define PAI_VALUE(type, name) sPlayerbotsMgr.GetPlayerbotAI(player)->GetAiObjectContext()->GetValue(name)->Get() #define PAI_VALUE2(type, name, param) \ - sPlayerbotsMgr->GetPlayerbotAI(player)->GetAiObjectContext()->GetValue(name, param)->Get() -#define GAI_VALUE(type, name) sSharedValueContext->getGlobalValue(name)->Get() -#define GAI_VALUE2(type, name, param) sSharedValueContext->getGlobalValue(name, param)->Get() + sPlayerbotsMgr.GetPlayerbotAI(player)->GetAiObjectContext()->GetValue(name, param)->Get() +#define GAI_VALUE(type, name) sSharedValueContext.getGlobalValue(name)->Get() +#define GAI_VALUE2(type, name, param) sSharedValueContext.getGlobalValue(name, param)->Get() #endif diff --git a/src/Script/PlayerbotsSecureLogin.cpp b/src/Script/PlayerbotsSecureLogin.cpp index aa5d103d58..fc54a82b7d 100644 --- a/src/Script/PlayerbotsSecureLogin.cpp +++ b/src/Script/PlayerbotsSecureLogin.cpp @@ -29,6 +29,7 @@ namespace return; PlayerbotAI* ai = GET_PLAYERBOT_AI(target); + if (!ai) return; @@ -41,11 +42,7 @@ namespace } } - if (sRandomPlayerbotMgr) - { - sRandomPlayerbotMgr->LogoutPlayerBot(target->GetGUID()); - return; - } + sRandomPlayerbotMgr.LogoutPlayerBot(target->GetGUID()); } } diff --git a/src/Script/WorldThr/PlayerbotOperations.h b/src/Script/WorldThr/PlayerbotOperations.h index cd8851902c..91940b6da7 100644 --- a/src/Script/WorldThr/PlayerbotOperations.h +++ b/src/Script/WorldThr/PlayerbotOperations.h @@ -355,7 +355,7 @@ class ArenaGroupFormationOperation : public PlayerbotOperation if (!member || !newGroup->IsMember(memberGuid)) continue; - PlayerbotAI* memberBotAI = sPlayerbotsMgr->GetPlayerbotAI(member); + PlayerbotAI* memberBotAI = PlayerbotsMgr::instance().GetPlayerbotAI(member); if (memberBotAI) memberBotAI->Reset(); @@ -412,13 +412,13 @@ class BotLogoutGroupCleanupOperation : public PlayerbotOperation if (!bot) return false; - PlayerbotAI* botAI = sPlayerbotsMgr->GetPlayerbotAI(bot); + PlayerbotAI* botAI = PlayerbotsMgr::instance().GetPlayerbotAI(bot); if (!botAI) return false; Group* group = bot->GetGroup(); if (group && !bot->InBattleground() && !bot->InBattlegroundQueue() && botAI->HasActivePlayerMaster()) - sPlayerbotRepository->Save(botAI); + PlayerbotRepository::instance().Save(botAI); return true; } @@ -448,7 +448,7 @@ class AddPlayerBotOperation : public PlayerbotOperation bool Execute() override { - sRandomPlayerbotMgr->AddPlayerBot(m_botGuid, m_masterAccountId); + sRandomPlayerbotMgr.AddPlayerBot(m_botGuid, m_masterAccountId); return true; } @@ -479,23 +479,35 @@ class OnBotLoginOperation : public PlayerbotOperation bool Execute() override { // find and verify bot still exists - Player* bot = ObjectAccessor::FindConnectedPlayer(m_botGuid); + Player* bot = ObjectAccessor::FindConnectedPlayer(this->m_botGuid); + if (!bot) + { return false; + } - PlayerbotHolder* holder = sRandomPlayerbotMgr; - if (m_masterAccountId) + if (this->m_masterAccountId) { - WorldSession* masterSession = sWorldSessionMgr->FindSession(m_masterAccountId); + WorldSession* masterSession = sWorldSessionMgr->FindSession(this->m_masterAccountId); Player* masterPlayer = masterSession ? masterSession->GetPlayer() : nullptr; - if (masterPlayer) - holder = GET_PLAYERBOT_MGR(masterPlayer); + + if (masterPlayer != nullptr) + { + PlayerbotMgr* manager = PlayerbotsMgr::instance().GetPlayerbotMgr(masterPlayer); + + if (manager == nullptr) + { + return false; + } + + manager->OnBotLogin(bot); + + return true; + } } - if (!holder) - return false; + sRandomPlayerbotMgr.OnBotLogin(bot); - holder->OnBotLogin(bot); return true; } diff --git a/src/Script/WorldThr/PlayerbotWorldThreadProcessor.cpp b/src/Script/WorldThr/PlayerbotWorldThreadProcessor.cpp index c776eb1207..f84bf62174 100644 --- a/src/Script/WorldThr/PlayerbotWorldThreadProcessor.cpp +++ b/src/Script/WorldThr/PlayerbotWorldThreadProcessor.cpp @@ -3,27 +3,13 @@ * and/or modify it under version 3 of the License, or (at your option), any later version. */ -#include "PlayerbotWorldThreadProcessor.h" - -#include "Log.h" -#include "PlayerbotAIConfig.h" - #include -PlayerbotWorldThreadProcessor::PlayerbotWorldThreadProcessor() - : m_enabled(true), m_maxQueueSize(10000), m_batchSize(100), m_queueWarningThreshold(80), - m_timeSinceLastUpdate(0), m_updateInterval(50) // Process at least every 50ms -{ - LOG_INFO("playerbots", "PlayerbotWorldThreadProcessor initialized"); -} +#include "PlayerbotWorldThreadProcessor.h" -PlayerbotWorldThreadProcessor::~PlayerbotWorldThreadProcessor() { ClearQueue(); } +#include "Timer.h" +#include "Log.h" -PlayerbotWorldThreadProcessor* PlayerbotWorldThreadProcessor::instance() -{ - static PlayerbotWorldThreadProcessor instance; - return &instance; -} void PlayerbotWorldThreadProcessor::Update(uint32 diff) { diff --git a/src/Script/WorldThr/PlayerbotWorldThreadProcessor.h b/src/Script/WorldThr/PlayerbotWorldThreadProcessor.h index e37d2b5ba5..94b91b97ba 100644 --- a/src/Script/WorldThr/PlayerbotWorldThreadProcessor.h +++ b/src/Script/WorldThr/PlayerbotWorldThreadProcessor.h @@ -6,13 +6,15 @@ #ifndef _PLAYERBOT_WORLD_THREAD_PROCESSOR_H #define _PLAYERBOT_WORLD_THREAD_PROCESSOR_H -#include "Common.h" -#include "PlayerbotOperation.h" - #include #include #include +#include "Log.h" + +#include "PlayerbotOperation.h" + + /** * @brief Processes thread-unsafe bot operations in the world thread * @@ -28,15 +30,17 @@ * * Usage: * auto op = std::make_unique(botGuid, params); - * sPlayerbotWorldProcessor->QueueOperation(std::move(op)); + * PlayerbotWorldThreadProcessor::instance().QueueOperation(std::move(op)); */ class PlayerbotWorldThreadProcessor { public: - PlayerbotWorldThreadProcessor(); - ~PlayerbotWorldThreadProcessor(); + static PlayerbotWorldThreadProcessor& instance() + { + static PlayerbotWorldThreadProcessor instance; - static PlayerbotWorldThreadProcessor* instance(); + return instance; + } /** * @brief Update and process queued operations (called from world thread) @@ -103,6 +107,21 @@ class PlayerbotWorldThreadProcessor bool IsEnabled() const { return m_enabled; } private: + PlayerbotWorldThreadProcessor() + : m_enabled(true), + m_maxQueueSize(10000), + m_batchSize(100), + m_queueWarningThreshold(80), + m_timeSinceLastUpdate(0), + m_updateInterval(50) // Process at least every 50ms + { + LOG_INFO("playerbots", "PlayerbotWorldThreadProcessor initialized"); + } + ~PlayerbotWorldThreadProcessor() + { + this->ClearQueue(); + } + /** * @brief Process a single batch of operations * @@ -137,6 +156,4 @@ class PlayerbotWorldThreadProcessor uint32 m_updateInterval; // Minimum ms between updates }; -#define sPlayerbotWorldProcessor PlayerbotWorldThreadProcessor::instance() - #endif diff --git a/src/Script/WorldThr/Queue.cpp b/src/Script/WorldThr/Queue.cpp index 136e1b4381..43b1597f88 100644 --- a/src/Script/WorldThr/Queue.cpp +++ b/src/Script/WorldThr/Queue.cpp @@ -50,7 +50,7 @@ uint32 Queue::Size() void Queue::RemoveExpired() { - if (!sPlayerbotAIConfig->expireActionTime) + if (!sPlayerbotAIConfig.expireActionTime) { return; } @@ -113,7 +113,7 @@ ActionNode* Queue::extractAndDeleteBasket(ActionBasket* basket) void Queue::collectExpiredBaskets(std::list& expiredBaskets) { - uint32 expiryTime = sPlayerbotAIConfig->expireActionTime; + uint32 expiryTime = sPlayerbotAIConfig.expireActionTime; for (ActionBasket* basket : actions) { if (basket->isExpired(expiryTime)) diff --git a/src/Script/WorldThr/Queue.h b/src/Script/WorldThr/Queue.h index b8a486dc85..439b61aa0e 100644 --- a/src/Script/WorldThr/Queue.h +++ b/src/Script/WorldThr/Queue.h @@ -56,7 +56,7 @@ class Queue /** * @brief Removes and deletes expired actions from the queue * - * Uses sPlayerbotAIConfig->expireActionTime to determine if actions have expired. + * Uses sPlayerbotAIConfig.expireActionTime to determine if actions have expired. * Both the ActionNode and ActionBasket are deleted for expired actions. */ void RemoveExpired(); diff --git a/src/Util/BroadcastHelper.cpp b/src/Util/BroadcastHelper.cpp index 19979d3d9f..246344bdaf 100644 --- a/src/Util/BroadcastHelper.cpp +++ b/src/Util/BroadcastHelper.cpp @@ -28,29 +28,29 @@ bool BroadcastHelper::BroadcastTest(PlayerbotAI* ai, Player* /* bot */) int32 rand = urand(0, 1); - if (rand == 1 && ai->SayToChannel(BOT_TEXT2("Posted to trade, %rand1, %rand2, %rand3", placeholders), ChatChannelId::TRADE)) + if (rand == 1 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to trade, %rand1, %rand2, %rand3", placeholders), ChatChannelId::TRADE)) return true; - else if (ai->SayToChannel(BOT_TEXT2("Posted to GuildRecruitment, %rand1, %rand2, %rand3", placeholders), ChatChannelId::GUILD_RECRUITMENT)) + else if (ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to GuildRecruitment, %rand1, %rand2, %rand3", placeholders), ChatChannelId::GUILD_RECRUITMENT)) return true; - return ai->SayToChannel(BOT_TEXT2("Posted to trade, %rand1, %rand2, %rand3", placeholders), ChatChannelId::TRADE); + return ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to trade, %rand1, %rand2, %rand3", placeholders), ChatChannelId::TRADE); //int32 rand = urand(1, 8); - if (rand == 1 && ai->SayToGuild(BOT_TEXT2("Posted to guild, %rand1, %rand2, %rand3", placeholders))) + if (rand == 1 && ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("Posted to guild, %rand1, %rand2, %rand3", placeholders))) return true; - else if (rand == 2 && ai->SayToWorld(BOT_TEXT2("Posted to world, %rand1, %rand2, %rand3", placeholders))) + else if (rand == 2 && ai->SayToWorld(PlayerbotTextMgr::instance().GetBotText("Posted to world, %rand1, %rand2, %rand3", placeholders))) return true; - else if (rand == 3 && ai->SayToChannel(BOT_TEXT2("Posted to general, %rand1, %rand2, %rand3", placeholders), ChatChannelId::GENERAL)) + else if (rand == 3 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to general, %rand1, %rand2, %rand3", placeholders), ChatChannelId::GENERAL)) return true; - else if (rand == 4 && ai->SayToChannel(BOT_TEXT2("Posted to trade, %rand1, %rand2, %rand3", placeholders), ChatChannelId::TRADE)) + else if (rand == 4 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to trade, %rand1, %rand2, %rand3", placeholders), ChatChannelId::TRADE)) return true; - else if (rand == 5 && ai->SayToChannel(BOT_TEXT2("Posted to LFG, %rand1, %rand2, %rand3", placeholders), ChatChannelId::LOOKING_FOR_GROUP)) + else if (rand == 5 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to LFG, %rand1, %rand2, %rand3", placeholders), ChatChannelId::LOOKING_FOR_GROUP)) return true; - else if (rand == 6 && ai->SayToChannel(BOT_TEXT2("Posted to LocalDefense, %rand1, %rand2, %rand3", placeholders), ChatChannelId::LOCAL_DEFENSE)) + else if (rand == 6 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to LocalDefense, %rand1, %rand2, %rand3", placeholders), ChatChannelId::LOCAL_DEFENSE)) return true; - else if (rand == 7 && ai->SayToChannel(BOT_TEXT2("Posted to WorldDefense, %rand1, %rand2, %rand3", placeholders), ChatChannelId::WORLD_DEFENSE)) + else if (rand == 7 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to WorldDefense, %rand1, %rand2, %rand3", placeholders), ChatChannelId::WORLD_DEFENSE)) return true; - else if (rand == 8 && ai->SayToChannel(BOT_TEXT2("Posted to GuildRecruitment, %rand1, %rand2, %rand3", placeholders), ChatChannelId::GUILD_RECRUITMENT)) + else if (rand == 8 && ai->SayToChannel(PlayerbotTextMgr::instance().GetBotText("Posted to GuildRecruitment, %rand1, %rand2, %rand3", placeholders), ChatChannelId::GUILD_RECRUITMENT)) return true; return false; @@ -63,7 +63,7 @@ bool BroadcastHelper::BroadcastTest(PlayerbotAI* ai, Player* /* bot */) */ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::string message, std::list> toChannels) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; if (message.empty()) { @@ -74,14 +74,14 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s { uint32 roll = urand(1, 100); uint32 chance = pair.second; - uint32 broadcastRoll = urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue); + uint32 broadcastRoll = urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue); switch (pair.first) { case TO_GUILD: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToGuildGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToGuildGlobalChance && ai->SayToGuild(message)) { return true; @@ -91,7 +91,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_WORLD: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToWorldGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToWorldGlobalChance && ai->SayToWorld(message)) { return true; @@ -101,7 +101,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_GENERAL: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToGeneralGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToGeneralGlobalChance && ai->SayToChannel(message, ChatChannelId::GENERAL)) { return true; @@ -111,7 +111,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_TRADE: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToTradeGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToTradeGlobalChance && ai->SayToChannel(message, ChatChannelId::TRADE)) { return true; @@ -121,7 +121,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_LOOKING_FOR_GROUP: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToLFGGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToLFGGlobalChance && ai->SayToChannel(message, ChatChannelId::LOOKING_FOR_GROUP)) { return true; @@ -131,7 +131,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_LOCAL_DEFENSE: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToLocalDefenseGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToLocalDefenseGlobalChance && ai->SayToChannel(message, ChatChannelId::LOCAL_DEFENSE)) { return true; @@ -141,7 +141,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_WORLD_DEFENSE: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToWorldDefenseGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToWorldDefenseGlobalChance && ai->SayToChannel(message, ChatChannelId::WORLD_DEFENSE)) { return true; @@ -151,7 +151,7 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s case TO_GUILD_RECRUITMENT: { if (roll <= chance - && broadcastRoll <= sPlayerbotAIConfig->broadcastToGuildRecruitmentGlobalChance + && broadcastRoll <= sPlayerbotAIConfig.broadcastToGuildRecruitmentGlobalChance && ai->SayToChannel(message, ChatChannelId::GUILD_RECRUITMENT)) { return true; @@ -168,14 +168,14 @@ bool BroadcastHelper::BroadcastToChannelWithGlobalChance(PlayerbotAI* ai, std::s bool BroadcastHelper::BroadcastLootingItem(PlayerbotAI* ai, Player* bot, ItemTemplate const* proto) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; std::map placeholders; placeholders["%item_link"] = ai->GetChatHelper()->FormatItem(proto); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); @@ -183,71 +183,71 @@ bool BroadcastHelper::BroadcastLootingItem(PlayerbotAI* ai, Player* bot, ItemTem switch (proto->Quality) { case ITEM_QUALITY_POOR: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemPoor) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemPoor) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_poor", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_poor", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case ITEM_QUALITY_NORMAL: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemNormal) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemNormal) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_normal", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_normal", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case ITEM_QUALITY_UNCOMMON: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemUncommon) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemUncommon) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_uncommon", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_uncommon", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case ITEM_QUALITY_RARE: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemRare) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemRare) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_rare", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_rare", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case ITEM_QUALITY_EPIC: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemEpic) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemEpic) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_epic", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_epic", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case ITEM_QUALITY_LEGENDARY: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemLegendary) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemLegendary) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_legendary", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_legendary", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case ITEM_QUALITY_ARTIFACT: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLootingItemArtifact) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLootingItemArtifact) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_looting_item_artifact", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_looting_item_artifact", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -261,23 +261,23 @@ bool BroadcastHelper::BroadcastLootingItem(PlayerbotAI* ai, Player* bot, ItemTem bool BroadcastHelper::BroadcastQuestAccepted(PlayerbotAI* ai, Player* bot, const Quest* quest) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestAccepted) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestAccepted) { std::map placeholders; placeholders["%quest_link"] = ai->GetChatHelper()->FormatQuest(quest); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_accepted_generic", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_accepted_generic", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -287,13 +287,13 @@ bool BroadcastHelper::BroadcastQuestAccepted(PlayerbotAI* ai, Player* bot, const bool BroadcastHelper::BroadcastQuestUpdateAddKill(PlayerbotAI* ai, Player* bot, Quest const* quest, uint32 availableCount, uint32 requiredCount, std::string obectiveName) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; std::map placeholders; AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%quest_link"] = ai->GetChatHelper()->FormatQuest(quest); placeholders["%quest_obj_name"] = obectiveName; placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); @@ -305,20 +305,20 @@ bool BroadcastHelper::BroadcastQuestUpdateAddKill(PlayerbotAI* ai, Player* bot, placeholders["%quest_obj_full_formatted"] = ai->GetChatHelper()->FormatQuestObjective(obectiveName, availableCount, requiredCount); if (availableCount < requiredCount - && urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestUpdateObjectiveProgress) + && urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestUpdateObjectiveProgress) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_update_add_kill_objective_progress", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_update_add_kill_objective_progress", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } else if (availableCount == requiredCount - && urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestUpdateObjectiveCompleted) + && urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestUpdateObjectiveCompleted) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_update_add_kill_objective_completed", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_update_add_kill_objective_completed", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -328,13 +328,13 @@ bool BroadcastHelper::BroadcastQuestUpdateAddKill(PlayerbotAI* ai, Player* bot, bool BroadcastHelper::BroadcastQuestUpdateAddItem(PlayerbotAI* ai, Player* bot, Quest const* quest, uint32 availableCount, uint32 requiredCount, const ItemTemplate* proto) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; std::map placeholders; AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%quest_link"] = ai->GetChatHelper()->FormatQuest(quest); std::string itemLinkFormatted = ai->GetChatHelper()->FormatItem(proto); placeholders["%item_link"] = itemLinkFormatted; @@ -347,20 +347,20 @@ bool BroadcastHelper::BroadcastQuestUpdateAddItem(PlayerbotAI* ai, Player* bot, placeholders["%quest_obj_full_formatted"] = ai->GetChatHelper()->FormatQuestObjective(itemLinkFormatted, availableCount, requiredCount); if (availableCount < requiredCount - && urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestUpdateObjectiveProgress) + && urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestUpdateObjectiveProgress) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_update_add_item_objective_progress", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_update_add_item_objective_progress", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } else if (availableCount == requiredCount - && urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestUpdateObjectiveCompleted) + && urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestUpdateObjectiveCompleted) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_update_add_item_objective_completed", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_update_add_item_objective_completed", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -370,23 +370,23 @@ bool BroadcastHelper::BroadcastQuestUpdateAddItem(PlayerbotAI* ai, Player* bot, bool BroadcastHelper::BroadcastQuestUpdateFailedTimer(PlayerbotAI* ai, Player* bot, Quest const* quest) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestUpdateFailedTimer) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestUpdateFailedTimer) { std::map placeholders; placeholders["%quest_link"] = ai->GetChatHelper()->FormatQuest(quest); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_update_failed_timer", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_update_failed_timer", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -396,23 +396,23 @@ bool BroadcastHelper::BroadcastQuestUpdateFailedTimer(PlayerbotAI* ai, Player* b bool BroadcastHelper::BroadcastQuestUpdateComplete(PlayerbotAI* ai, Player* bot, Quest const* quest) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestUpdateComplete) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestUpdateComplete) { std::map placeholders; placeholders["%quest_link"] = ai->GetChatHelper()->FormatQuest(quest); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_update_complete", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_update_complete", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -422,23 +422,23 @@ bool BroadcastHelper::BroadcastQuestUpdateComplete(PlayerbotAI* ai, Player* bot, bool BroadcastHelper::BroadcastQuestTurnedIn(PlayerbotAI* ai, Player* bot, Quest const* quest) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceQuestTurnedIn) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceQuestTurnedIn) { std::map placeholders; placeholders["%quest_link"] = ai->GetChatHelper()->FormatQuest(quest); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_quest_turned_in", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_quest_turned_in", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -448,14 +448,14 @@ bool BroadcastHelper::BroadcastQuestTurnedIn(PlayerbotAI* ai, Player* bot, Quest bool BroadcastHelper::BroadcastKill(PlayerbotAI* ai, Player* bot, Creature *creature) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; std::map placeholders; placeholders["%victim_name"] = creature->GetName(); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%victim_level"] = creature->GetLevel(); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); @@ -468,24 +468,24 @@ bool BroadcastHelper::BroadcastKill(PlayerbotAI* ai, Player* bot, Creature *crea if (creature->IsPet()) { - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillPet) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillPet) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_pet", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_pet", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } } else if (creature->IsPlayer()) { - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillPlayer) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillPlayer) { placeholders["%victim_class"] = ai->GetChatHelper()->FormatClass(creature->getClass()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_player", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_player", placeholders), { {TO_WORLD_DEFENSE, 50}, {TO_LOCAL_DEFENSE, 50}, {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -495,61 +495,61 @@ bool BroadcastHelper::BroadcastKill(PlayerbotAI* ai, Player* bot, Creature *crea switch (creature->GetCreatureTemplate()->rank) { case CREATURE_ELITE_NORMAL: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillNormal) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillNormal) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_normal", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_normal", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case CREATURE_ELITE_ELITE: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillElite) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillElite) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_elite", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_elite", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case CREATURE_ELITE_RAREELITE: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillRareelite) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillRareelite) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_rareelite", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_rareelite", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case CREATURE_ELITE_WORLDBOSS: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillWorldboss) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillWorldboss) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_worldboss", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_worldboss", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case CREATURE_ELITE_RARE: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillRare) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillRare) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_rare", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_rare", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } break; case CREATURE_UNKNOWN: - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceKillUnknown) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceKillUnknown) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_killed_unknown", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_killed_unknown", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -564,43 +564,43 @@ bool BroadcastHelper::BroadcastKill(PlayerbotAI* ai, Player* bot, Creature *crea bool BroadcastHelper::BroadcastLevelup(PlayerbotAI* ai, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; uint32 level = bot->GetLevel(); std::map placeholders; AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(level); - if (level == sPlayerbotAIConfig->randomBotMaxLevel - && urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLevelupMaxLevel) + if (level == sPlayerbotAIConfig.randomBotMaxLevel + && urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLevelupMaxLevel) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_levelup_max_level", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_levelup_max_level", placeholders), { {TO_GUILD, 30}, {TO_WORLD, 90}, {TO_GENERAL, 100} } ); } // It's divisible by 10 else if (level % 10 == 0 - && urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLevelupTenX) + && urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLevelupTenX) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_levelup_10x", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_levelup_10x", placeholders), { {TO_GUILD, 50}, {TO_WORLD, 90}, {TO_GENERAL, 100} } ); } - else if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceLevelupGeneric) + else if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceLevelupGeneric) { return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("broadcast_levelup_generic", placeholders), + PlayerbotTextMgr::instance().GetBotText("broadcast_levelup_generic", placeholders), { {TO_GUILD, 90}, {TO_WORLD, 90}, {TO_GENERAL, 100} } ); } @@ -610,9 +610,9 @@ bool BroadcastHelper::BroadcastLevelup(PlayerbotAI* ai, Player* bot) bool BroadcastHelper::BroadcastGuildMemberPromotion(PlayerbotAI* ai, Player* /* bot */, Player* player) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceGuildManagement) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceGuildManagement) { std::map placeholders; placeholders["%other_name"] = player->GetName(); @@ -620,7 +620,7 @@ bool BroadcastHelper::BroadcastGuildMemberPromotion(PlayerbotAI* ai, Player* /* placeholders["%other_race"] = ai->GetChatHelper()->FormatRace(player->getRace()); placeholders["%other_level"] = std::to_string(player->GetLevel()); - return ai->SayToGuild(BOT_TEXT2("broadcast_guild_promotion", placeholders)); + return ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("broadcast_guild_promotion", placeholders)); } return false; @@ -628,7 +628,7 @@ bool BroadcastHelper::BroadcastGuildMemberPromotion(PlayerbotAI* ai, Player* /* bool BroadcastHelper::BroadcastGuildMemberDemotion(PlayerbotAI* ai, Player* /* bot */, Player* player) { - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceGuildManagement) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceGuildManagement) { std::map placeholders; placeholders["%other_name"] = player->GetName(); @@ -636,7 +636,7 @@ bool BroadcastHelper::BroadcastGuildMemberDemotion(PlayerbotAI* ai, Player* /* b placeholders["%other_race"] = ai->GetChatHelper()->FormatRace(player->getRace()); placeholders["%other_level"] = std::to_string(player->GetLevel()); - return ai->SayToGuild(BOT_TEXT2("broadcast_guild_demotion", placeholders)); + return ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("broadcast_guild_demotion", placeholders)); } return false; @@ -644,25 +644,25 @@ bool BroadcastHelper::BroadcastGuildMemberDemotion(PlayerbotAI* ai, Player* /* b bool BroadcastHelper::BroadcastGuildGroupOrRaidInvite(PlayerbotAI* ai, Player* /* bot */, Player* player, Group* group) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; std::map placeholders; placeholders["%name"] = player->GetName(); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); //TODO move texts to sql! if (group && group->isRaidGroup()) { if (urand(0, 3)) { - return ai->SayToGuild(BOT_TEXT2("Hey anyone want to raid in %zone_name", placeholders)); + return ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("Hey anyone want to raid in %zone_name", placeholders)); } else { - return ai->SayToGuild(BOT_TEXT2("Hey %name I'm raiding in %zone_name do you wan to join me?", placeholders)); + return ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("Hey %name I'm raiding in %zone_name do you wan to join me?", placeholders)); } } else @@ -670,11 +670,11 @@ bool BroadcastHelper::BroadcastGuildGroupOrRaidInvite(PlayerbotAI* ai, Player* / //(bot->GetTeam() == ALLIANCE ? LANG_COMMON : LANG_ORCISH) if (urand(0, 3)) { - return ai->SayToGuild(BOT_TEXT2("Hey anyone wanna group up in %zone_name?", placeholders)); + return ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("Hey anyone wanna group up in %zone_name?", placeholders)); } else { - return ai->SayToGuild(BOT_TEXT2("Hey %name do you want join my group? I'm heading for %zone_name", placeholders)); + return ai->SayToGuild(PlayerbotTextMgr::instance().GetBotText("Hey %name do you want join my group? I'm heading for %zone_name", placeholders)); } } @@ -683,9 +683,9 @@ bool BroadcastHelper::BroadcastGuildGroupOrRaidInvite(PlayerbotAI* ai, Player* / bool BroadcastHelper::BroadcastSuggestInstance(PlayerbotAI* ai, std::vector& allowedInstances, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestInstance) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestInstance) { std::map placeholders; placeholders["%my_role"] = ChatHelper::FormatClass(bot, AiFactory::GetPlayerSpecTab(bot)); @@ -701,7 +701,7 @@ bool BroadcastHelper::BroadcastSuggestInstance(PlayerbotAI* ai, std::vector& quests, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestQuest) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestQuest) { int index = rand() % quests.size(); @@ -730,7 +730,7 @@ bool BroadcastHelper::BroadcastSuggestQuest(PlayerbotAI* ai, std::vector return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_quest", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_quest", placeholders), { {TO_LOOKING_FOR_GROUP, 50}, {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -740,9 +740,9 @@ bool BroadcastHelper::BroadcastSuggestQuest(PlayerbotAI* ai, std::vector bool BroadcastHelper::BroadcastSuggestGrindMaterials(PlayerbotAI* ai, std::string item, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestGrindMaterials) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestGrindMaterials) { std::map placeholders; @@ -755,7 +755,7 @@ bool BroadcastHelper::BroadcastSuggestGrindMaterials(PlayerbotAI* ai, std::strin return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_trade", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_trade", placeholders), { {TO_TRADE, 50}, {TO_LOOKING_FOR_GROUP, 50}, {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -765,9 +765,9 @@ bool BroadcastHelper::BroadcastSuggestGrindMaterials(PlayerbotAI* ai, std::strin bool BroadcastHelper::BroadcastSuggestGrindReputation(PlayerbotAI* ai, std::vector levels, std::vector allowedFactions, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestGrindReputation) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestGrindReputation) { std::map placeholders; @@ -787,7 +787,7 @@ bool BroadcastHelper::BroadcastSuggestGrindReputation(PlayerbotAI* ai, std::vect return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_faction", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_faction", placeholders), { {TO_LOOKING_FOR_GROUP, 50}, {TO_GUILD, 50}, {TO_WORLD, 50}, {TO_GENERAL, 100} } ); } @@ -797,9 +797,9 @@ bool BroadcastHelper::BroadcastSuggestGrindReputation(PlayerbotAI* ai, std::vect bool BroadcastHelper::BroadcastSuggestSell(PlayerbotAI* ai, const ItemTemplate* proto, uint32 count, uint32 price, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestSell) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestSell) { std::map placeholders; @@ -814,7 +814,7 @@ bool BroadcastHelper::BroadcastSuggestSell(PlayerbotAI* ai, const ItemTemplate* return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_sell", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_sell", placeholders), { {TO_TRADE, 90}, {TO_GENERAL, 100} } ); } @@ -824,24 +824,24 @@ bool BroadcastHelper::BroadcastSuggestSell(PlayerbotAI* ai, const ItemTemplate* bool BroadcastHelper::BroadcastSuggestSomething(PlayerbotAI* ai, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestSomething) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestSomething) { std::map placeholders; placeholders["%my_role"] = ChatHelper::FormatClass(bot, AiFactory::GetPlayerSpecTab(bot)); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_something", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_something", placeholders), { {TO_GUILD, 10}, {TO_WORLD, 70}, {TO_GENERAL, 100} } ); } @@ -851,29 +851,29 @@ bool BroadcastHelper::BroadcastSuggestSomething(PlayerbotAI* ai, Player* bot) bool BroadcastHelper::BroadcastSuggestSomethingToxic(PlayerbotAI* ai, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestSomethingToxic) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestSomethingToxic) { //items std::vector botItems = ai->GetInventoryAndEquippedItems(); std::map placeholders; - placeholders["%random_inventory_item_link"] = botItems.size() > 0 ? ai->GetChatHelper()->FormatItem(botItems[rand() % botItems.size()]->GetTemplate()) : BOT_TEXT1("string_empty_link"); + placeholders["%random_inventory_item_link"] = botItems.size() > 0 ? ai->GetChatHelper()->FormatItem(botItems[rand() % botItems.size()]->GetTemplate()) : PlayerbotTextMgr::instance().GetBotText("string_empty_link"); placeholders["%my_role"] = ChatHelper::FormatClass(bot, AiFactory::GetPlayerSpecTab(bot)); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_something_toxic", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_something_toxic", placeholders), { {TO_GUILD, 10}, {TO_WORLD, 70}, {TO_GENERAL, 100} } ); } @@ -883,9 +883,9 @@ bool BroadcastHelper::BroadcastSuggestSomethingToxic(PlayerbotAI* ai, Player* bo bool BroadcastHelper::BroadcastSuggestToxicLinks(PlayerbotAI* ai, Player* bot) { - if (!sPlayerbotAIConfig->enableBroadcasts) + if (!sPlayerbotAIConfig.enableBroadcasts) return false; - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestToxicLinks) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestToxicLinks) { //quests std::vector incompleteQuests; @@ -908,8 +908,8 @@ bool BroadcastHelper::BroadcastSuggestToxicLinks(PlayerbotAI* ai, Player* bot) std::map placeholders; - placeholders["%random_inventory_item_link"] = botItems.size() > 0 ? ai->GetChatHelper()->FormatItem(botItems[rand() % botItems.size()]->GetTemplate()) : BOT_TEXT1("string_empty_link"); - placeholders["%prefix"] = sPlayerbotAIConfig->toxicLinksPrefix; + placeholders["%random_inventory_item_link"] = botItems.size() > 0 ? ai->GetChatHelper()->FormatItem(botItems[rand() % botItems.size()]->GetTemplate()) : PlayerbotTextMgr::instance().GetBotText("string_empty_link"); + placeholders["%prefix"] = sPlayerbotAIConfig.toxicLinksPrefix; if (incompleteQuests.size() > 0) { @@ -924,15 +924,15 @@ bool BroadcastHelper::BroadcastSuggestToxicLinks(PlayerbotAI* ai, Player* bot) placeholders["%my_role"] = ChatHelper::FormatClass(bot, AiFactory::GetPlayerSpecTab(bot)); AreaTableEntry const* current_area = ai->GetCurrentArea(); AreaTableEntry const* current_zone = ai->GetCurrentZone(); - placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : BOT_TEXT1("string_unknown_area"); - placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : BOT_TEXT1("string_unknown_area"); + placeholders["%area_name"] = current_area ? ai->GetLocalizedAreaName(current_area) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); + placeholders["%zone_name"] = current_zone ? ai->GetLocalizedAreaName(current_zone) : PlayerbotTextMgr::instance().GetBotText("string_unknown_area"); placeholders["%my_class"] = ai->GetChatHelper()->FormatClass(bot->getClass()); placeholders["%my_race"] = ai->GetChatHelper()->FormatRace(bot->getRace()); placeholders["%my_level"] = std::to_string(bot->GetLevel()); return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("suggest_toxic_links", placeholders), + PlayerbotTextMgr::instance().GetBotText("suggest_toxic_links", placeholders), { {TO_GUILD, 10}, {TO_WORLD, 70}, {TO_GENERAL, 100} } ); } @@ -942,7 +942,7 @@ bool BroadcastHelper::BroadcastSuggestToxicLinks(PlayerbotAI* ai, Player* bot) bool BroadcastHelper::BroadcastSuggestThunderfury(PlayerbotAI* ai, Player* bot) { - if (urand(1, sPlayerbotAIConfig->broadcastChanceMaxValue) <= sPlayerbotAIConfig->broadcastChanceSuggestThunderfury) + if (urand(1, sPlayerbotAIConfig.broadcastChanceMaxValue) <= sPlayerbotAIConfig.broadcastChanceSuggestThunderfury) { std::map placeholders; ItemTemplate const* thunderfuryProto = sObjectMgr->GetItemTemplate(19019); @@ -950,7 +950,7 @@ bool BroadcastHelper::BroadcastSuggestThunderfury(PlayerbotAI* ai, Player* bot) return BroadcastToChannelWithGlobalChance( ai, - BOT_TEXT2("thunderfury_spam", placeholders), + PlayerbotTextMgr::instance().GetBotText("thunderfury_spam", placeholders), { {TO_WORLD, 70}, {TO_GENERAL, 100} } ); } diff --git a/src/Util/ServerFacade.cpp b/src/Util/ServerFacade.cpp index d69944c04f..8bd8ee60ef 100644 --- a/src/Util/ServerFacade.cpp +++ b/src/Util/ServerFacade.cpp @@ -4,8 +4,8 @@ */ #include "ServerFacade.h" +#include "Player.h" -#include "Playerbots.h" #include "TargetedMovementGenerator.h" float ServerFacade::GetDistance2d(Unit* unit, WorldObject* wo) @@ -25,13 +25,13 @@ float ServerFacade::GetDistance2d(Unit* unit, float x, float y) bool ServerFacade::IsDistanceLessThan(float dist1, float dist2) { - // return dist1 - dist2 < sPlayerbotAIConfig->targetPosRecalcDistance; + // return dist1 - dist2 < sPlayerbotAIConfig.targetPosRecalcDistance; return dist1 < dist2; } bool ServerFacade::IsDistanceGreaterThan(float dist1, float dist2) { - // return dist1 - dist2 > sPlayerbotAIConfig->targetPosRecalcDistance; + // return dist1 - dist2 > sPlayerbotAIConfig.targetPosRecalcDistance; return dist1 > dist2; } @@ -39,7 +39,7 @@ bool ServerFacade::IsDistanceGreaterOrEqualThan(float dist1, float dist2) { retu bool ServerFacade::IsDistanceLessOrEqualThan(float dist1, float dist2) { return !IsDistanceGreaterThan(dist1, dist2); } -void ServerFacade::SetFacingTo(Player* bot, WorldObject* wo, bool force) +void ServerFacade::SetFacingTo(Player* bot, WorldObject* wo, bool) { if (!bot) return; diff --git a/src/Util/ServerFacade.h b/src/Util/ServerFacade.h index 6668fa9562..978b8e7681 100644 --- a/src/Util/ServerFacade.h +++ b/src/Util/ServerFacade.h @@ -6,8 +6,6 @@ #ifndef _PLAYERBOT_SERVERFACADE_H #define _PLAYERBOT_SERVERFACADE_H -#include "Common.h" - class Player; class Unit; class WorldObject; @@ -29,12 +27,13 @@ class ServerFacade /** * @brief Get singleton instance. * - * @return ServerFacade* Pointer to the singleton instance. + * @return ServerFacade& Reference to the singleton instance. */ - static ServerFacade* instance() + static ServerFacade& instance() { static ServerFacade instance; - return &instance; + + return instance; } public: @@ -123,7 +122,4 @@ class ServerFacade void SendPacket(Player* player, WorldPacket* packet); }; -/** Global singleton accessor. */ -#define sServerFacade ServerFacade::instance() - #endif diff --git a/src/domain/core/inspector/abstract/AbstractInspector.h b/src/domain/core/inspector/abstract/AbstractInspector.h new file mode 100644 index 0000000000..7906180f65 --- /dev/null +++ b/src/domain/core/inspector/abstract/AbstractInspector.h @@ -0,0 +1,19 @@ +#pragma once + +class AbstractInspector +{ +protected: + AbstractInspector() = default; + ~AbstractInspector() = default; + + AbstractInspector(AbstractInspector const&) = default; + AbstractInspector& operator=(AbstractInspector const&) = default; + + AbstractInspector(AbstractInspector&&) = default; + AbstractInspector& operator=(AbstractInspector&&) = default; + + virtual bool isInspectable() const + { + return true; + } +}; diff --git a/src/domain/player/inspector/abstract/AbstractPlayerInspector.h b/src/domain/player/inspector/abstract/AbstractPlayerInspector.h new file mode 100644 index 0000000000..66e5874a08 --- /dev/null +++ b/src/domain/player/inspector/abstract/AbstractPlayerInspector.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include "ObjectGuid.h" +#include "ObjectAccessor.h" +#include "Player.h" + +#include "AbstractInspector.h" + +class AbstractPlayerInspector : public AbstractInspector +{ +public: + AbstractPlayerInspector( + uint64_t playerGUID + ) : + playerGUID(playerGUID) + {} + + AbstractPlayerInspector& operator=(AbstractPlayerInspector const&) = delete; + + Player* getCurrentPlayer() const + { + const ObjectGuid playerFullGUID = ObjectGuid::Create(this->playerGUID); + Player* const player = ObjectAccessor::FindPlayer(playerFullGUID); + + return player; + } + + bool isInspectable() const override + { + return true; + } + +protected: + const uint64_t playerGUID; +}; diff --git a/src/domain/player/inspector/global/GlobalPlayerInspector.h b/src/domain/player/inspector/global/GlobalPlayerInspector.h new file mode 100644 index 0000000000..7d397af66b --- /dev/null +++ b/src/domain/player/inspector/global/GlobalPlayerInspector.h @@ -0,0 +1,107 @@ +#pragma once + +#include + +#include "ObjectAccessor.h" +#include "SharedDefines.h" +#include "Player.h" +#include "GridNotifiers.h" + +#include "AiObjectContext.h" +#include "AiFactory.h" +#include "PlayerbotAI.h" +#include "AbstractPlayerInspector.h" +#include "PlayerbotMgr.h" + +class GlobalPlayerInspector : public AbstractPlayerInspector +{ +public: + GlobalPlayerInspector( + uint64_t playerGUID + ) : + AbstractPlayerInspector(playerGUID) + {} + + bool isDrinking() const + { + const Player* const player = this->getCurrentPlayer(); + + if (player == nullptr) + return false; + + if (!player->IsSitState()) + return false; + + return player->HasAuraType(SPELL_AURA_MOD_POWER_REGEN) || player->HasAuraType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); + } + + bool isEating() const + { + const Player* const player = this->getCurrentPlayer(); + + if (player == nullptr) + return false; + + if (!player->IsSitState()) + return false; + + return player->HasAuraType(SPELL_AURA_MOD_REGEN) || player->HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT); + } + + bool shouldBeDrinking(float manaThresholdPercent) const + { + Player* const player = this->getCurrentPlayer(); + + if (player == nullptr) + return false; + + if (!player->HasActivePowerType(POWER_MANA)) + return false; + + if (player->IsInCombat()) + return false; + + if (player->GetPowerPct(POWER_MANA) > manaThresholdPercent) + return false; + + if (player->IsUnderWater()) + return false; + + // Bots must not keep drinking if they have hostile entities close to them! + if (this->hasHostileUnitsInRange(15.0f)) + return false; + + PlayerbotAI* botAI = PlayerbotsMgr::instance().GetPlayerbotAI(player); + + if (botAI == nullptr) + return false; + + AiObjectContext* context = botAI->GetAiObjectContext(); + + if (context == nullptr) + return false; + + bool hasAvailableLoot = context->GetValue("loot target"); + + if (hasAvailableLoot) + return false; + + return true; + } + + bool hasHostileUnitsInRange(float range) const + { + const Player* const player = this->getCurrentPlayer(); + + if (player == nullptr) + return false; + + std::list targets; + + Acore::AnyUnfriendlyAttackableVisibleUnitInObjectRangeCheck u_check(player, range); + Acore::UnitListSearcher searcher(player, targets, u_check); + Cell::VisitObjects(player, searcher, PlayerbotAIConfig::instance().sightDistance); + + return !targets.empty(); + } +}; diff --git a/src/strategy/actions/non-combat/drink/DrinkAction.h b/src/strategy/actions/non-combat/drink/DrinkAction.h new file mode 100644 index 0000000000..f0f895cea2 --- /dev/null +++ b/src/strategy/actions/non-combat/drink/DrinkAction.h @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2016+ AzerothCore , released under GNU AGPL v3 license, you may redistribute it + * and/or modify it under version 3 of the License, or (at your option), any later version. + */ + +#ifndef _PLAYERBOT_DRINK_ACTION_H +#define _PLAYERBOT_DRINK_ACTION_H + +#include + +#include "Event.h" +#include "UseItemAction.h" +#include "GlobalPlayerInspector.h" +#include "DrinkAuraEnum.h" + + +class PlayerbotAI; + +class DrinkAction : public UseItemAction +{ +public: + DrinkAction(PlayerbotAI* botAI) : UseItemAction(botAI, "drink") {} + + bool isPossible() override + { + if (this->bot->IsInCombat()) + { + return false; + } + + if (this->bot->IsMounted()) + { + return false; + } + + if (this->botAI->HasAnyAuraOf(GetTarget(), "dire bear form", "bear form", "cat form", "travel form", "aquatic form","flight form", "swift flight form", nullptr)) + { + return false; + } + + if (this->bot->IsCrowdControlled()) + { + return false; + } + + return this->botAI->HasCheat(BotCheatMask::food) || UseItemAction::isPossible(); + } + + bool isUseful() override + { + const GlobalPlayerInspector playerInspector(this->bot->GetGUID().GetRawValue()); + + if (playerInspector.isDrinking()) + return false; + + return playerInspector.shouldBeDrinking(50.0f); + } + + bool Execute(Event event) override + { + std::string name = this->bot->GetName().c_str(); + + this->bot->ClearUnitState(UNIT_STATE_CHASE); + this->bot->ClearUnitState(UNIT_STATE_FOLLOW); + + this->botAI->InterruptSpell(); + + if (this->bot->isMoving()) + this->bot->StopMoving(); + + this->bot->SetStandState(UNIT_STAND_STATE_SIT); + + if (this->botAI->HasCheat(BotCheatMask::food)) + { + this->bot->AddAura(DRINK_AURA_GRACCU_MINCE_MEAT_FRUITCAKE, bot); + + this->botAI->SetNextCheckDelay(1000); + + return true; + } + + this->botAI->SetNextCheckDelay(1000); + + return UseItemAction::Execute(event); + } +}; + +#endif diff --git a/src/strategy/actions/non-combat/drink/definition/enum/DrinkAuraEnum.h b/src/strategy/actions/non-combat/drink/definition/enum/DrinkAuraEnum.h new file mode 100644 index 0000000000..94b5f14f67 --- /dev/null +++ b/src/strategy/actions/non-combat/drink/definition/enum/DrinkAuraEnum.h @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2016+ AzerothCore , released under GNU AGPL v3 license, you may redistribute it + * and/or modify it under version 3 of the License, or (at your option), any later version. + */ + +#ifndef _PLAYERBOT_DRINK_AURA_ENUM_H +#define _PLAYERBOT_DRINK_AURA_ENUM_H + +enum DrinkAuraEnum { + DRINK_AURA_GRACCU_MINCE_MEAT_FRUITCAKE = 25990, + DRINK_AURA_FISH_FEAST = 57426, + DRINK_AURA_GREAT_FEAST = 57301, + DRINK_AURA_DRAGONFIN_FILET = 57370, + DRINK_AURA_GIGANTIC_FEAST = 58465, + DRINK_AURA_BLACKENED_DRAGONFIN = 57366, + DRINK_AURA_BLACK_JELLY = 64354, + DRINK_AURA_FIRECRACKER_SALMON = 57341, + DRINK_AURA_PURIFIED_DRAENIC_WATER = 27089, + DRINK_AURA_DALARAN_CLAM_CHOWDER = 58067, + DRINK_AURA_HOT_BUTTERED_TROUT = 42309, + DRINK_AURA_KUNGALOOSH = 52911, + DRINK_AURA_CRANBERRY_CHUTNEY = 65420, + DRINK_AURA_BAKED_MANTA_RAY = 57101, + DRINK_AURA_SLOW_ROASTED_TURKEY = 65422, + DRINK_AURA_CONJURED_MANA_STRUDEL = 43523, + DRINK_AURA_CANDIED_SWEET_POTATO = 65418, + DRINK_AURA_SPICE_BREAD_STUFFING = 65419, + DRINK_AURA_SMALL_FEAST = 58474, + DRINK_AURA_SMOKED_SAGEFISH = 25690, + DRINK_AURA_YETI_MILK = 43183, + DRINK_AURA_SNAPPER_EXTREME = 57359, + DRINK_AURA_SMOKED_ROCKFIN = 57070, + DRINK_AURA_POACHED_NETTLEFISH = 57098, + DRINK_AURA_BLACK_COFFEE = 27089, + DRINK_AURA_MOUNTAIN_WATER = 27089, + DRINK_AURA_PUMPKIN_PIE = 65421, + DRINK_AURA_FILTERED_DRAENIC_WATER = 34291, + DRINK_AURA_BITTER_PLASMA = 43182, + DRINK_AURA_WORG_TARTARE = 57359, + DRINK_AURA_CLAMLETTE_MAGNIFIQUE = 64056, + DRINK_AURA_BOUNTIFUL_FEAST = 66476, + DRINK_AURA_GRILLED_SCULPIN = 57085, + DRINK_AURA_CONJURED_MANA_PIE = 61828, + DRINK_AURA_CUTTLESTEAK = 57364, + DRINK_AURA_PUNGENT_SEAL_WHEY = 43182, + DRINK_AURA_IMPERIAL_MANTA_STEAK = 57344, + DRINK_AURA_SWEET_NECTAR = 1133, + DRINK_AURA_BOTTLED_WINTERSPRING_WATER = 1135, + DRINK_AURA_CONJURED_MOUNTAIN_SPRING_WATER = 34291, + DRINK_AURA_HONEYMINT_TEA = 43183, + DRINK_AURA_SAUTEED_GOBY = 57070, + DRINK_AURA_REFRESHING_SPRING_WATER = 430, + DRINK_AURA_ENCHANTED_WATER = 1133, + DRINK_AURA_SMOKED_SALMON = 57096, + DRINK_AURA_GRIZZLEBERRY_JUICE = 27089, + DRINK_AURA_STAR_SORROW = 43183, + DRINK_AURA_PICKLED_FANGTOOTH = 57106, + DRINK_AURA_CONJURED_FRESH_WATER = 431, + DRINK_AURA_MORNING_GLORY_DEW = 1137, + DRINK_AURA_CONJURED_GLACIER_WATER = 27089, + DRINK_AURA_SKULLFISH_SOUP = 43706, + DRINK_AURA_SWEETENED_GOAT_MILK = 27089, + DRINK_AURA_BLACKROCK_FORTIFIED_WATER = 27089, + DRINK_AURA_FIZZY_FAIRE_DRINK = 432, + DRINK_AURA_ENRICHED_TEROCONE_JUICE = 41031, + DRINK_AURA_POACHED_NORTHERN_SCULPIN = 57335, + DRINK_AURA_CRUSADER_WATERSKIN = 43183, + DRINK_AURA_ALTERAC_MANNA_BISCUIT = 23692, + DRINK_AURA_HOT_APPLE_CIDER = 45020, + DRINK_AURA_SPICY_FRIED_HERRING = 57354, + DRINK_AURA_CONJURED_WATER = 430, + DRINK_AURA_CONJURED_MINERAL_WATER = 1135, + DRINK_AURA_CONJURED_CRYSTAL_WATER = 22734, + DRINK_AURA_BUBBLING_WATER = 432, + DRINK_AURA_GRILLED_BONESCALE = 57070, + DRINK_AURA_SPICY_BLUE_NETTLEFISH = 57343, + DRINK_AURA_FRESH_APPLE_JUICE = 43182, + DRINK_AURA_ICE_COLD_MILK = 431, + DRINK_AURA_UNDERSPORE_POD = 33772, + DRINK_AURA_FRESH_SQUEEZED_LIMEADE = 43182, + DRINK_AURA_JILLIAN_GOURMET_FISH_FEAST = 57426, + DRINK_AURA_MELON_JUICE = 432, + DRINK_AURA_GILNEAS_SPARKLING_WATER = 27089, + DRINK_AURA_STAR_LAMENT = 22734, + DRINK_AURA_CONJURED_SPRING_WATER = 1133, + DRINK_AURA_HYJAL_NECTAR = 22734, + DRINK_AURA_BLACKROCK_SPRING_WATER = 1137, + DRINK_AURA_BLACKROCK_MINERAL_WATER = 34291, + DRINK_AURA_ETHERMEAD = 27089, + DRINK_AURA_GOLDTHORN_TEA = 1133, + DRINK_AURA_ENRICHED_MANNA_BISCUIT = 18071, + DRINK_AURA_GREEN_TEA_LEAF = 833, + DRINK_AURA_CONJURED_PURIFIED_WATER = 432, + DRINK_AURA_CONJURED_SPARKLING_WATER = 1137, + DRINK_AURA_STAR_TEAR = 27089, + DRINK_AURA_NAARU_RATION = 44166, + DRINK_AURA_MOONBERRY_JUICE = 1135, + DRINK_AURA_SILVERWINE = 34291, + DRINK_AURA_FULL_MOONSHINE = 438, + DRINK_AURA_DOS_OGRIS = 27089, + DRINK_AURA_ESSENCE_MANGO = 24384, + DRINK_AURA_SENGGIN_ROOT = 2639, + DRINK_AURA_BLENDED_BEAN_BREW = 431, + DRINK_AURA_SAGEFISH_DELIGHT = 25691, + DRINK_AURA_SPARKLING_SOUTHSHORE_CIDER = 27089, + DRINK_AURA_CONJURED_MANA_BISCUIT = 44166, + DRINK_AURA_FROSTBERRY_JUICE = 27089 +}; + +#endif