From 283c68b6a9f6d0dd611ec38e2935d6020bcabe42 Mon Sep 17 00:00:00 2001 From: Antz Date: Mon, 14 Sep 2020 18:30:19 +0100 Subject: [PATCH] Style cleanup from the Mangos Futures Team --- src/game/AuctionHouseBot/AuctionHouseBot.cpp | 26 +- src/game/BattleGround/BattleGround.cpp | 50 +- src/game/BattleGround/BattleGroundAB.cpp | 6 + src/game/BattleGround/BattleGroundBE.cpp | 6 + src/game/BattleGround/BattleGroundEY.cpp | 48 + src/game/BattleGround/BattleGroundHandler.cpp | 32 +- src/game/BattleGround/BattleGroundIC.cpp | 2 + src/game/BattleGround/BattleGroundMgr.cpp | 82 +- src/game/BattleGround/BattleGroundNA.cpp | 4 + src/game/BattleGround/BattleGroundRB.cpp | 2 + src/game/BattleGround/BattleGroundRL.cpp | 4 + src/game/BattleGround/BattleGroundSA.cpp | 2 + src/game/BattleGround/BattleGroundWS.cpp | 14 + src/game/ChatCommands/Level0.cpp | 4 +- src/game/ChatCommands/Level1.cpp | 18 + src/game/ChatCommands/Level2.cpp | 136 +- src/game/ChatCommands/Level3.cpp | 124 +- src/game/ChatCommands/Level4.cpp | 4 + src/game/ChatCommands/debugcmds.cpp | 64 +- .../FleeingMovementGenerator.cpp | 2 + src/game/MotionGenerators/MotionMaster.cpp | 2 + src/game/MotionGenerators/PathFinder.cpp | 18 +- .../RandomMovementGenerator.cpp | 6 + .../WaypointMovementGenerator.cpp | 18 + src/game/Object/ArenaTeam.cpp | 62 + src/game/Object/ArenaTeam.h | 4 + src/game/Object/AuctionHouseMgr.cpp | 50 +- src/game/Object/Bag.cpp | 4 + src/game/Object/Calendar.cpp | 36 + src/game/Object/Creature.cpp | 38 + src/game/Object/Creature.h | 4 +- src/game/Object/CreatureAI.cpp | 4 + src/game/Object/CreatureEventAI.cpp | 34 +- src/game/Object/CreatureEventAIMgr.cpp | 18 +- src/game/Object/DynamicObject.cpp | 2 + src/game/Object/Formulas.h | 4 +- src/game/Object/GameObject.cpp | 74 +- src/game/Object/Guild.cpp | 144 +- src/game/Object/Item.cpp | 76 +- src/game/Object/ItemEnchantmentMgr.cpp | 4 + src/game/Object/LootMgr.cpp | 72 +- src/game/Object/Object.cpp | 100 +- src/game/Object/Object.h | 8 +- src/game/Object/ObjectGuid.h | 54 +- src/game/Object/ObjectMgr.cpp | 152 ++ src/game/Object/ObjectMgr.h | 4 + src/game/Object/ObjectPosSelector.cpp | 4 +- src/game/Object/Pet.cpp | 112 +- src/game/Object/Pet.h | 8 + src/game/Object/PetAI.cpp | 42 +- src/game/Object/Player.cpp | 2245 ++++++++++++++++- src/game/Object/Player.h | 14 + src/game/Object/ReactorAI.cpp | 2 + src/game/Object/ReputationMgr.cpp | 50 + src/game/Object/SocialMgr.cpp | 24 + src/game/Object/SpellMgr.cpp | 300 ++- src/game/Object/SpellMgr.h | 20 + src/game/Object/StatSystem.cpp | 44 + src/game/Object/TemporarySummon.cpp | 10 + src/game/Object/Totem.cpp | 20 + src/game/Object/TotemAI.cpp | 2 + src/game/Object/Unit.cpp | 1200 ++++++++- src/game/Object/Unit.h | 6 + src/game/Object/UnitEvents.h | 16 +- src/game/Object/UpdateMask.h | 2 + src/game/Object/Vehicle.cpp | 38 + src/game/OutdoorPvP/OutdoorPvP.cpp | 4 + src/game/OutdoorPvP/OutdoorPvPGH.cpp | 6 + src/game/OutdoorPvP/OutdoorPvPHP.cpp | 16 + src/game/OutdoorPvP/OutdoorPvPMgr.cpp | 4 + src/game/OutdoorPvP/OutdoorPvPNA.cpp | 22 + src/game/OutdoorPvP/OutdoorPvPTF.cpp | 14 +- src/game/OutdoorPvP/OutdoorPvPZM.cpp | 38 + src/game/References/ThreatManager.cpp | 32 +- src/game/Server/DB2Stores.cpp | 4 + src/game/Server/DBCStores.cpp | 72 +- src/game/Server/DBCStructure.cpp | 4 + src/game/Server/DBCStructure.h | 42 +- src/game/Server/WorldSession.cpp | 50 +- src/game/Server/WorldSocket.cpp | 17 +- src/game/Server/WorldSocketMgr.cpp | 8 +- src/game/Tools/CharacterDatabaseCleaner.cpp | 2 + src/game/Tools/PlayerDump.cpp | 78 +- src/game/Warden/Warden.cpp | 6 + src/game/Warden/WardenCheckMgr.cpp | 22 +- src/game/Warden/WardenMac.cpp | 6 + src/game/Warden/WardenWin.cpp | 20 + src/game/WorldHandlers/AccountMgr.cpp | 40 +- src/game/WorldHandlers/AchievementMgr.cpp | 328 ++- src/game/WorldHandlers/ArenaTeamHandler.cpp | 4 + .../WorldHandlers/AuctionHouseHandler.cpp | 26 + src/game/WorldHandlers/CalendarHandler.cpp | 60 + src/game/WorldHandlers/CellImpl.h | 14 + src/game/WorldHandlers/Channel.cpp | 36 + src/game/WorldHandlers/Channel.h | 30 +- src/game/WorldHandlers/ChannelHandler.cpp | 38 +- src/game/WorldHandlers/ChannelMgr.cpp | 2 + src/game/WorldHandlers/CharacterHandler.cpp | 73 +- src/game/WorldHandlers/Chat.cpp | 158 ++ src/game/WorldHandlers/ChatHandler.cpp | 96 +- src/game/WorldHandlers/CreatureLinkingMgr.cpp | 50 + src/game/WorldHandlers/DisableMgr.cpp | 16 + src/game/WorldHandlers/DuelHandler.cpp | 2 + src/game/WorldHandlers/GMTicketHandler.cpp | 16 + src/game/WorldHandlers/GameEventMgr.cpp | 30 + src/game/WorldHandlers/GossipDef.cpp | 120 + src/game/WorldHandlers/GridMap.cpp | 46 + src/game/WorldHandlers/GridNotifiers.cpp | 28 + src/game/WorldHandlers/GridNotifiers.h | 22 + src/game/WorldHandlers/GridNotifiersImpl.h | 86 + src/game/WorldHandlers/Group.cpp | 214 ++ src/game/WorldHandlers/Group.h | 18 + src/game/WorldHandlers/GroupHandler.cpp | 92 + src/game/WorldHandlers/GuildHandler.cpp | 22 + src/game/WorldHandlers/ItemHandler.cpp | 98 + src/game/WorldHandlers/LFGHandler.cpp | 40 + src/game/WorldHandlers/LFGMgr.cpp | 118 + src/game/WorldHandlers/LootHandler.cpp | 48 + src/game/WorldHandlers/Mail.cpp | 12 + src/game/WorldHandlers/MailHandler.cpp | 26 + src/game/WorldHandlers/Map.cpp | 46 +- src/game/WorldHandlers/MapManager.cpp | 14 +- src/game/WorldHandlers/MapManager.h | 6 + .../WorldHandlers/MapPersistentStateMgr.cpp | 68 + .../WorldHandlers/MapPersistentStateMgr.h | 8 + src/game/WorldHandlers/MassMailMgr.cpp | 6 + src/game/WorldHandlers/MiscHandler.cpp | 112 +- src/game/WorldHandlers/MoveMap.cpp | 2 + src/game/WorldHandlers/MoveMap.h | 2 + src/game/WorldHandlers/MovementHandler.cpp | 28 + src/game/WorldHandlers/NPCHandler.cpp | 48 + src/game/WorldHandlers/ObjectGridLoader.cpp | 12 + src/game/WorldHandlers/PetHandler.cpp | 48 + src/game/WorldHandlers/PetitionsHandler.cpp | 14 + src/game/WorldHandlers/PoolManager.cpp | 60 + src/game/WorldHandlers/PoolManager.h | 8 + src/game/WorldHandlers/QueryHandler.cpp | 32 + src/game/WorldHandlers/QuestDef.cpp | 32 + src/game/WorldHandlers/QuestHandler.cpp | 72 + src/game/WorldHandlers/ScriptMgr.cpp | 142 +- src/game/WorldHandlers/ScriptMgr.h | 2 + src/game/WorldHandlers/SkillDiscovery.cpp | 14 + src/game/WorldHandlers/SkillExtraItems.cpp | 6 + src/game/WorldHandlers/SkillHandler.cpp | 8 + src/game/WorldHandlers/Spell.cpp | 886 ++++++- src/game/WorldHandlers/Spell.h | 42 + src/game/WorldHandlers/SpellAuras.cpp | 745 +++++- src/game/WorldHandlers/SpellAuras.h | 14 + src/game/WorldHandlers/SpellEffects.cpp | 738 ++++++ src/game/WorldHandlers/SpellHandler.cpp | 32 + src/game/WorldHandlers/TaxiHandler.cpp | 10 + src/game/WorldHandlers/TradeHandler.cpp | 24 + src/game/WorldHandlers/TransportSystem.cpp | 8 + src/game/WorldHandlers/Transports.cpp | 32 + .../WorldHandlers/UnitAuraProcHandler.cpp | 128 + src/game/WorldHandlers/VehicleHandler.cpp | 8 + src/game/WorldHandlers/WaypointManager.cpp | 28 + src/game/WorldHandlers/WaypointManager.h | 4 + src/game/WorldHandlers/Weather.cpp | 14 + src/game/WorldHandlers/Weather.h | 4 + src/game/WorldHandlers/World.cpp | 74 +- src/game/movement/MoveSpline.cpp | 6 + src/game/movement/MoveSpline.h | 4 +- src/game/movement/MoveSplineInit.cpp | 10 + src/game/movement/packet_builder.cpp | 16 + src/game/movement/spline.h | 2 + src/game/movement/spline.impl.h | 8 +- src/game/vmap/BIH.h | 8 +- src/game/vmap/MapTree.cpp | 4 +- src/game/vmap/TileAssembler.cpp | 2 + src/game/vmap/VMapFactory.cpp | 4 +- src/mangosd/SOAP/SoapThread.cpp | 14 +- src/shared/Auth/AuthCrypt.cpp | 4 + src/shared/Auth/BigNumber.cpp | 4 + src/shared/Auth/WardenKeyGeneration.h | 2 + src/shared/Config/Config.cpp | 4 +- src/shared/DataStores/DB2FileLoader.cpp | 10 + src/shared/DataStores/DB2Store.h | 8 + src/shared/DataStores/DBCFileLoader.cpp | 2 + src/shared/DataStores/DBCStore.h | 2 + src/shared/Database/Field.h | 2 + src/shared/Linux/PosixDaemon.cpp | 6 + src/shared/Log/Log.cpp | 62 +- src/shared/Log/Log.h | 63 +- src/shared/Threading/DelayExecutor.cpp | 14 + src/shared/Utilities/ByteBuffer.h | 14 + src/shared/Utilities/Util.cpp | 4 + src/shared/Win/ServiceWin32.cpp | 8 +- src/shared/Win/WheatyExceptionReport.cpp | 20 +- .../Movemap-Generator/IntermediateValues.cpp | 39 +- .../Movemap-Generator/IntermediateValues.h | 2 +- .../Movemap-Generator/MMapCommon.h | 8 +- .../Movemap-Generator/TerrainBuilder.cpp | 6 +- .../Movemap-Generator/generator.cpp | 4 + .../map-extractor/System.cpp | 98 +- .../shared/ExtractorCommon.cpp | 4 + .../vmap-extractor/adtfile.cpp | 6 + .../vmap-extractor/dbcfile.cpp | 4 + .../vmap-extractor/gameobject_extract.cpp | 4 + .../vmap-extractor/mpqfile.cpp | 6 +- .../vmap-extractor/vmapexport.cpp | 60 + .../vmap-extractor/wdtfile.cpp | 2 + .../Extractor_projects/vmap-extractor/wmo.cpp | 4 +- 203 files changed, 12039 insertions(+), 353 deletions(-) diff --git a/src/game/AuctionHouseBot/AuctionHouseBot.cpp b/src/game/AuctionHouseBot/AuctionHouseBot.cpp index 428d00270..44c0be81d 100644 --- a/src/game/AuctionHouseBot/AuctionHouseBot.cpp +++ b/src/game/AuctionHouseBot/AuctionHouseBot.cpp @@ -1174,14 +1174,18 @@ bool AuctionBotSeller::Initialize() std::stringstream includeStream(sAuctionBotConfig.GetAHBotIncludes()); std::string temp; while (getline(includeStream, temp, ',')) - { includeItems.push_back(atoi(temp.c_str())); } + { + includeItems.push_back(atoi(temp.c_str())); + } } { std::stringstream excludeStream(sAuctionBotConfig.GetAHBotExcludes()); std::string temp; while (getline(excludeStream, temp, ',')) - { excludeItems.push_back(atoi(temp.c_str())); } + { + excludeItems.push_back(atoi(temp.c_str())); + } } sLog.outString("Forced Inclusion " SIZEFMTD " items", includeItems.size()); sLog.outString("Forced Exclusion " SIZEFMTD " items", excludeItems.size()); @@ -1492,16 +1496,24 @@ bool AuctionBotSeller::Initialize() { if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_MISC_MOUNT_MIN_REQ_LEVEL)) if (prototype->RequiredLevel < value) + { continue; + } if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_MISC_MOUNT_MAX_REQ_LEVEL)) if (prototype->RequiredLevel > value) + { continue; + } if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_MISC_MOUNT_MIN_SKILL_RANK)) if (prototype->RequiredSkillRank < value) + { continue; + } if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_MISC_MOUNT_MAX_SKILL_RANK)) if (prototype->RequiredSkillRank > value) + { continue; + } } if (prototype->Flags & ITEM_FLAG_LOOTABLE) @@ -1523,16 +1535,24 @@ bool AuctionBotSeller::Initialize() { if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_GLYPH_MIN_REQ_LEVEL)) if (prototype->RequiredLevel < value) + { continue; + } if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_GLYPH_MAX_REQ_LEVEL)) if (prototype->RequiredLevel > value) + { continue; + } if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_GLYPH_MIN_ITEM_LEVEL)) if (prototype->RequiredLevel < value) + { continue; + } if (uint32 value = sAuctionBotConfig.getConfig(CONFIG_UINT32_AHBOT_CLASS_GLYPH_MAX_ITEM_LEVEL)) if (prototype->RequiredLevel > value) + { continue; + } break; } case ITEM_CLASS_TRADE_GOODS: @@ -2177,7 +2197,9 @@ void AuctionHouseBot::Rebuild(bool all) AuctionEntry* entry = itr->second; if (entry->owner == sAuctionBotConfig.GetAHBotId()) // ahbot auction if (all || entry->bid == 0) // expire auction now if no bid or forced + { entry->expireTime = sWorld.GetGameTime(); + } } } } diff --git a/src/game/BattleGround/BattleGround.cpp b/src/game/BattleGround/BattleGround.cpp index 0eaf73cde..4bda35701 100644 --- a/src/game/BattleGround/BattleGround.cpp +++ b/src/game/BattleGround/BattleGround.cpp @@ -443,12 +443,16 @@ void BattleGround::Update(uint32 diff) for (BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr) if (Player* player = sObjectMgr.GetPlayer(itr->first)) + { player->GetSession()->SendPacket(&data); + } m_CountdownTimer = 0; } else + { m_CountdownTimer += diff; + } if (!(m_Events & BG_STARTING_EVENT_1)) { @@ -491,7 +495,9 @@ void BattleGround::Update(uint32 diff) for (BattleGroundPlayerMap::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { if (Player* player = sObjectMgr.GetPlayer(itr->first)) + { player->RemoveAurasDueToSpell(SPELL_ARENA_PREPARATION); + } } CheckArenaWinConditions(); @@ -502,7 +508,9 @@ void BattleGround::Update(uint32 diff) for (BattleGroundPlayerMap::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) if (Player* plr = sObjectMgr.GetPlayer(itr->first)) + { plr->RemoveAurasDueToSpell(SPELL_PREPARATION); + } // Announce BG starting if (sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_QUEUE_ANNOUNCER_START)) { @@ -922,9 +930,13 @@ void BattleGround::EndBattleGround(Team winner) if (isArena() && isRated() && winner_arena_team && loser_arena_team) { if (team == winner) + { winner_arena_team->OfflineMemberLost(itr->first, loser_rating); + } else + { loser_arena_team->OfflineMemberLost(itr->first, winner_rating); + } } continue; } @@ -965,7 +977,9 @@ void BattleGround::EndBattleGround(Team winner) // update achievement BEFORE personal rating update ArenaTeamMember* member = winner_arena_team->GetMember(plr->GetObjectGuid()); if (member) + { plr->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA, member->personal_rating); + } winner_arena_team->MemberWon(plr, loser_rating); plr->ModifyCurrencyCount(CURRENCY_CONQUEST_ARENA_META, sWorld.getConfig(CONFIG_UINT32_CURRENCY_ARENA_CONQUEST_POINTS_REWARD)); @@ -1344,7 +1358,9 @@ void BattleGround::RemovePlayerAtLeave(ObjectGuid guid, bool Transport, bool Sen ArenaTeam* winner_arena_team = sObjectMgr.GetArenaTeamById(GetArenaTeamIdForTeam(GetOtherTeam(team))); ArenaTeam* loser_arena_team = sObjectMgr.GetArenaTeamById(GetArenaTeamIdForTeam(team)); if (winner_arena_team && loser_arena_team) + { loser_arena_team->MemberLost(plr, winner_arena_team->GetRating()); + } } } if (SendPacket) @@ -1366,7 +1382,9 @@ void BattleGround::RemovePlayerAtLeave(ObjectGuid guid, bool Transport, bool Sen ArenaTeam* others_arena_team = sObjectMgr.GetArenaTeamById(GetArenaTeamIdForTeam(GetOtherTeam(team))); ArenaTeam* players_arena_team = sObjectMgr.GetArenaTeamById(GetArenaTeamIdForTeam(team)); if (others_arena_team && players_arena_team) + { players_arena_team->OfflineMemberLost(guid, others_arena_team->GetRating()); + } } } @@ -1476,7 +1494,9 @@ void BattleGround::StartTimedAchievement(AchievementCriteriaTypes type, uint32 e { for (BattleGroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr) if (Player* pPlayer = GetBgMap()->GetPlayer(itr->first)) + { pPlayer->GetAchievementMgr().StartTimedAchievementCriteria(type, entry); + } } void BattleGround::AddPlayer(Player* plr) @@ -1514,30 +1534,42 @@ void BattleGround::AddPlayer(Player* plr) if (team == ALLIANCE) // gold { if (plr->GetTeam() == HORDE) + { plr->CastSpell(plr, SPELL_HORDE_GOLD_FLAG, true); + } else + { plr->CastSpell(plr, SPELL_ALLIANCE_GOLD_FLAG, true); + } } else // green { if (plr->GetTeam() == HORDE) + { plr->CastSpell(plr, SPELL_HORDE_GREEN_FLAG, true); + } else + { plr->CastSpell(plr, SPELL_ALLIANCE_GREEN_FLAG, true); + } } plr->DestroyConjuredItems(true); plr->UnsummonPetTemporaryIfAny(); if (GetStatus() == STATUS_WAIT_JOIN) // not started yet + { plr->CastSpell(plr, SPELL_ARENA_PREPARATION, true); + } plr->CastSpell(plr, SPELL_ARENA_DAMPENING, true); } else { if (GetStatus() == STATUS_WAIT_JOIN) // not started yet + { plr->CastSpell(plr, SPELL_PREPARATION, true); // reduces all mana cost of spells. + } plr->CastSpell(plr, SPELL_BATTLEGROUND_DAMPENING, true); } @@ -1636,7 +1668,9 @@ void BattleGround::EventPlayerLoggedOut(Player* player) // 1 player is logging out, if it is the last, then end arena! if (isArena()) if (GetAlivePlayersCountByTeam(player->GetTeam()) <= 1 && GetPlayersCountByTeam(GetOtherTeam(player->GetTeam()))) + { EndBattleGround(GetOtherTeam(player->GetTeam())); + } } } @@ -1729,7 +1763,9 @@ void BattleGround::UpdatePlayerScore(Player* Source, uint32 type, uint32 value) { // reward honor instantly if (Source->RewardHonor(NULL, 1, (float)value)) + { itr->second->BonusHonor += value; + } } break; // used only in EY, but in MSG_PVP_LOG_DATA opcode @@ -1917,7 +1953,9 @@ void BattleGround::SpawnEvent(uint8 event1, uint8 event2, bool spawn) // or despawn something which was already despawned if (event2 == BG_EVENT_NONE || (spawn && m_ActiveEvents[event1] == event2) || (!spawn && m_ActiveEvents[event1] != event2)) - { return; } + { + return; + } if (spawn) { @@ -1926,7 +1964,9 @@ void BattleGround::SpawnEvent(uint8 event1, uint8 event2, bool spawn) m_ActiveEvents[event1] = event2; // set this event to active } else - { m_ActiveEvents[event1] = BG_EVENT_NONE; } // no event active if event2 gets despawned + { + m_ActiveEvents[event1] = BG_EVENT_NONE; // no event active if event2 gets despawned + } GuidVector::const_iterator itr = m_EventObjects[MAKE_PAIR32(event1, event2)].creatures.begin(); for (; itr != m_EventObjects[MAKE_PAIR32(event1, event2)].creatures.end(); ++itr) @@ -2149,7 +2189,9 @@ void BattleGround::HandleKillPlayer(Player* player, Player* killer) // to be able to remove insignia -- ONLY IN BattleGrounds if (!isArena()) + { player->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); + } } /// @@ -2231,9 +2273,13 @@ uint32 BattleGround::GetAlivePlayersCountByTeam(Team team) const void BattleGround::CheckArenaWinConditions() { if (!GetAlivePlayersCountByTeam(ALLIANCE) && GetPlayersCountByTeam(HORDE)) + { EndBattleGround(HORDE); + } else if (GetPlayersCountByTeam(ALLIANCE) && !GetAlivePlayersCountByTeam(HORDE)) + { EndBattleGround(ALLIANCE); + } } /// diff --git a/src/game/BattleGround/BattleGroundAB.cpp b/src/game/BattleGround/BattleGroundAB.cpp index 632d96c7f..087c847ba 100644 --- a/src/game/BattleGround/BattleGroundAB.cpp +++ b/src/game/BattleGround/BattleGroundAB.cpp @@ -175,7 +175,9 @@ void BattleGroundAB::Update(uint32 diff) // horde will be a bit disadvantaged, but we can assume that points aren't updated for both team in same Update() call uint8 otherTeam = (team + 1) % PVP_TEAM_COUNT; if (m_TeamScores[team] > m_TeamScores[otherTeam] + 500) + { m_TeamScores500Disadvantage[otherTeam] = true; + } } } @@ -596,9 +598,13 @@ void BattleGroundAB::EndBattleGround(Team winner) { // win reward if (winner == ALLIANCE) + { RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE); + } if (winner == HORDE) + { RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE); + } // complete map_end rewards (even if no team wins) RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE); RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE); diff --git a/src/game/BattleGround/BattleGroundBE.cpp b/src/game/BattleGround/BattleGroundBE.cpp index 2af90e760..8abb8687f 100644 --- a/src/game/BattleGround/BattleGroundBE.cpp +++ b/src/game/BattleGround/BattleGroundBE.cpp @@ -62,7 +62,9 @@ void BattleGroundBE::AddPlayer(Player* plr) void BattleGroundBE::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/) { if (GetStatus() == STATUS_WAIT_LEAVE) + { return; + } UpdateWorldState(0x9f1, GetAlivePlayersCountByTeam(ALLIANCE)); UpdateWorldState(0x9f0, GetAlivePlayersCountByTeam(HORDE)); @@ -73,7 +75,9 @@ void BattleGroundBE::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/) void BattleGroundBE::HandleKillPlayer(Player* player, Player* killer) { if (GetStatus() != STATUS_IN_PROGRESS) + { return; + } if (!killer) { @@ -106,7 +110,9 @@ void BattleGroundBE::UpdatePlayerScore(Player* source, uint32 type, uint32 value { BattleGroundScoreMap::iterator itr = m_PlayerScores.find(source->GetObjectGuid()); if (itr == m_PlayerScores.end()) // player not found... + { return; + } // there is nothing special in this score BattleGround::UpdatePlayerScore(source, type, value); diff --git a/src/game/BattleGround/BattleGroundEY.cpp b/src/game/BattleGround/BattleGroundEY.cpp index d9243507e..e36c4fdc3 100644 --- a/src/game/BattleGround/BattleGroundEY.cpp +++ b/src/game/BattleGround/BattleGroundEY.cpp @@ -56,7 +56,9 @@ void BattleGroundEY::Update(uint32 diff) m_resourceUpdateTimer = EY_RESOURCES_UPDATE_TIME; } else + { m_resourceUpdateTimer -= diff; + } // flag respawn if (m_flagState == EY_FLAG_STATE_WAIT_RESPAWN || m_flagState == EY_FLAG_STATE_ON_GROUND) @@ -65,12 +67,18 @@ void BattleGroundEY::Update(uint32 diff) { m_flagRespawnTimer = 0; if (m_flagState == EY_FLAG_STATE_WAIT_RESPAWN) + { RespawnFlag(); + } else + { RespawnDroppedFlag(); + } } else + { m_flagRespawnTimer -= diff; + } } // workaround for Fel Reaver Ruins flag capture needed on 3.3.5 only @@ -86,13 +94,17 @@ void BattleGroundEY::Update(uint32 diff) { // coords and range taken from DBC of areatrigger (4514) if (flagCarrier->GetDistance(2044.0f, 1729.729f, 1190.03f) <= 3.0f) + { EventPlayerCapturedFlag(flagCarrier, NODE_FEL_REAVER_RUINS); + } } } m_felReaverFlagTimer = EY_FEL_REAVER_FLAG_UPDATE_TIME; } else + { m_felReaverFlagTimer -= diff; + } } } @@ -142,18 +154,26 @@ void BattleGroundEY::UpdateTeamScore(Team team) } if (team == ALLIANCE) + { UpdateWorldState(WORLD_STATE_EY_RESOURCES_ALLIANCE, score); + } else + { UpdateWorldState(WORLD_STATE_EY_RESOURCES_HORDE, score); + } } void BattleGroundEY::EndBattleGround(Team winner) { // win reward if (winner == ALLIANCE) + { RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE); + } if (winner == HORDE) + { RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE); + } // complete map reward RewardHonorToTeam(GetBonusHonorFromKill(1), ALLIANCE); RewardHonorToTeam(GetBonusHonorFromKill(1), HORDE); @@ -161,7 +181,9 @@ void BattleGroundEY::EndBattleGround(Team winner) // disable capture points for (uint8 i = 0; i < EY_NODES_MAX; ++i) if (GameObject* go = GetBgMap()->GetGameObject(m_towers[i])) + { go->SetLootState(GO_JUST_DEACTIVATED); + } BattleGround::EndBattleGround(winner); } @@ -183,7 +205,9 @@ void BattleGroundEY::RemovePlayer(Player* plr, ObjectGuid guid) if (m_flagCarrier == guid) { if (plr) + { EventPlayerDroppedFlag(plr); + } else { ClearFlagCarrier(); @@ -314,19 +338,27 @@ bool BattleGroundEY::HandleAreaTrigger(Player* source, uint32 trigger) { case AREATRIGGER_BLOOD_ELF_TOWER_POINT: if (m_towerOwner[NODE_BLOOD_ELF_TOWER] == source->GetTeam()) + { EventPlayerCapturedFlag(source, NODE_BLOOD_ELF_TOWER); + } break; case AREATRIGGER_FEL_REAVER_RUINS_POINT: if (m_towerOwner[NODE_FEL_REAVER_RUINS] == source->GetTeam()) + { EventPlayerCapturedFlag(source, NODE_FEL_REAVER_RUINS); + } break; case AREATRIGGER_MAGE_TOWER_POINT: if (m_towerOwner[NODE_MAGE_TOWER] == source->GetTeam()) + { EventPlayerCapturedFlag(source, NODE_MAGE_TOWER); + } break; case AREATRIGGER_DRAENEI_RUINS_POINT: if (m_towerOwner[NODE_DRAENEI_RUINS] == source->GetTeam()) + { EventPlayerCapturedFlag(source, NODE_DRAENEI_RUINS); + } break; default: return false; @@ -390,9 +422,13 @@ void BattleGroundEY::RespawnDroppedFlag() GameObject* obj = GetBgMap()->GetGameObject(GetDroppedFlagGuid()); if (obj) + { obj->Delete(); + } else + { sLog.outError("BattleGroundEY: Unknown dropped flag: %s", GetDroppedFlagGuid().GetString().c_str()); + } ClearDroppedFlagGuid(); } @@ -454,7 +490,9 @@ void BattleGroundEY::EventPlayerClickedOnFlag(Player* source, GameObject* target } if (m_flagState == EY_FLAG_STATE_ON_BASE) + { UpdateWorldState(WORLD_STATE_EY_NETHERSTORM_FLAG_READY, WORLD_STATE_REMOVE); + } if (source->GetTeam() == ALLIANCE) { @@ -480,9 +518,13 @@ void BattleGroundEY::EventPlayerClickedOnFlag(Player* source, GameObject* target source->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); if (source->GetTeam() == ALLIANCE) + { PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, source->GetName()); + } else + { PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL, source->GetName()); + } } void BattleGroundEY::EventPlayerCapturedFlag(Player* source, EYNodes node) @@ -505,7 +547,9 @@ void BattleGroundEY::EventPlayerCapturedFlag(Player* source, EYNodes node) PlaySoundToAll(EY_SOUND_FLAG_CAPTURED_ALLIANCE); if (m_towersAlliance > 0) + { AddPoints(ALLIANCE, eyFlagPoints[m_towersAlliance - 1]); + } SendMessageToAll(LANG_BG_EY_CAPTURED_FLAG_A, CHAT_MSG_BG_SYSTEM_ALLIANCE, source); } @@ -514,7 +558,9 @@ void BattleGroundEY::EventPlayerCapturedFlag(Player* source, EYNodes node) PlaySoundToAll(EY_SOUND_FLAG_CAPTURED_HORDE); if (m_towersHorde > 0) + { AddPoints(HORDE, eyFlagPoints[m_towersHorde - 1]); + } SendMessageToAll(LANG_BG_EY_CAPTURED_FLAG_H, CHAT_MSG_BG_SYSTEM_HORDE, source); } @@ -615,7 +661,9 @@ WorldSafeLocsEntry const* BattleGroundEY::GetClosestGraveYard(Player* player) { entry = sWorldSafeLocsStore.LookupEntry(eyGraveyards[i]); if (!entry) + { sLog.outError("BattleGroundEY: Not found graveyard: %u", eyGraveyards[i]); + } else { distance = (entry->x - plr_x) * (entry->x - plr_x) + (entry->y - plr_y) * (entry->y - plr_y) + (entry->z - plr_z) * (entry->z - plr_z); diff --git a/src/game/BattleGround/BattleGroundHandler.cpp b/src/game/BattleGround/BattleGroundHandler.cpp index 947d71981..b6abc92a9 100644 --- a/src/game/BattleGround/BattleGroundHandler.cpp +++ b/src/game/BattleGround/BattleGroundHandler.cpp @@ -167,7 +167,9 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recv_data) // check if already in queue if (_player->GetBattleGroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is already in this queue - { return; } + { + return; + } // check if has free queue slots if (!_player->HasFreeBattleGroundQueueId()) { @@ -213,7 +215,9 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recv_data) { Player* member = itr->getSource(); if (!member) - { continue; } // this should never happen + { + continue; // this should never happen + } uint32 queueSlot = member->AddBattleGroundQueueId(bgQueueTypeId); // add to queue @@ -262,16 +266,22 @@ void WorldSession::HandleBattleGroundPlayerPositionsOpcode(WorldPacket & /*recv_ case BATTLEGROUND_WS: { if ((flagCarrierA = sObjectMgr.GetPlayer(((BattleGroundWS*)bg)->GetAllianceFlagCarrierGuid()))) + { ++flagCarrierCountH; + } if ((flagCarrierH = sObjectMgr.GetPlayer(((BattleGroundWS*)bg)->GetHordeFlagCarrierGuid()))) + { ++flagCarrierCountH; + } break; } case BATTLEGROUND_EY: { if ((flagCarrierH = sObjectMgr.GetPlayer(((BattleGroundEY*)bg)->GetFlagCarrierGuid()))) + { ++flagCarrierCountH; + } break; } case BATTLEGROUND_AB: @@ -287,9 +297,13 @@ void WorldSession::HandleBattleGroundPlayerPositionsOpcode(WorldPacket & /*recv_ data.WriteBits(flagCarrierCountA, 22); data.WriteBits(flagCarrierCountH, 22); if (flagCarrierA) + { data.WriteGuidMask<6, 5, 4, 7, 2, 1, 0, 3>(flagCarrierA->GetObjectGuid()); + } if (flagCarrierH) + { data.WriteGuidMask<6, 5, 4, 7, 2, 1, 0, 3>(flagCarrierH->GetObjectGuid()); + } if (flagCarrierA) { @@ -457,10 +471,14 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket& recv_data) { case 1: // port to battleground if (!_player->IsInvitedForBattleGroundQueueType(bgQueueTypeId)) - { return; } // cheating? + { + return; // cheating? + } if (!_player->InBattleGround()) + { _player->SetBattleGroundEntryPoint(); + } // resurrect the player if (!_player->IsAlive()) @@ -513,7 +531,9 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket& recv_data) bgQueue.RemovePlayer(_player->GetObjectGuid(), true); // player left queue, we should update it - do not update Arena Queue if (ginfo.arenaType == ARENA_TYPE_NONE) + { sBattleGroundMgr.ScheduleQueueUpdate(ginfo.ArenaTeamRating, ginfo.arenaType, bgQueueTypeId, bgTypeId, bracketEntry->GetBracketId()); + } SendPacket(&data); DEBUG_LOG("Battleground: player %s (%u) left queue for bgtype %u, queue type %u.", _player->GetName(), _player->GetGUIDLow(), bg->GetTypeID(), bgQueueTypeId); break; @@ -601,7 +621,9 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recv_data*/) // expected bracket entry PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bg->GetMapId(), _player->getLevel()); if (!bracketEntry) + { continue; + } uint32 avgTime = bgQueue.GetAverageQueueWaitTime(&ginfo, bracketEntry->GetBracketId()); // send status in BattleGround Queue @@ -746,7 +768,9 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recv_data) // if avg personal rating is more than 150 points below the teams rating, the team will be queued against an opponent matching or similar to the average personal rating if (avg_pers_rating + 150 < arenaRating) + { arenaRating = avg_pers_rating; + } BattleGroundQueue& bgQueue = sBattleGroundMgr.m_BattleGroundQueues[bgQueueTypeId]; uint32 avgTime = 0; @@ -766,7 +790,9 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recv_data) { Player* member = itr->getSource(); if (!member) + { continue; + } WorldPacket data; diff --git a/src/game/BattleGround/BattleGroundIC.cpp b/src/game/BattleGround/BattleGroundIC.cpp index 2f7de7361..291d1771a 100644 --- a/src/game/BattleGround/BattleGroundIC.cpp +++ b/src/game/BattleGround/BattleGroundIC.cpp @@ -50,7 +50,9 @@ void BattleGroundIC::UpdatePlayerScore(Player* source, uint32 type, uint32 value BattleGroundScoreMap::iterator itr = m_PlayerScores.find(source->GetObjectGuid()); if (itr == m_PlayerScores.end()) // player not found... + { return; + } BattleGround::UpdatePlayerScore(source, type, value); } diff --git a/src/game/BattleGround/BattleGroundMgr.cpp b/src/game/BattleGround/BattleGroundMgr.cpp index c67b6cae2..7d3850b56 100644 --- a/src/game/BattleGround/BattleGroundMgr.cpp +++ b/src/game/BattleGround/BattleGroundMgr.cpp @@ -189,10 +189,14 @@ GroupQueueInfo* BattleGroundQueue::AddGroup(Player* leader, Group* grp, BattleGr // compute index (if group is premade or joined a rated match) to queues uint32 index = 0; if (!isRated && !isPremade) - { index += PVP_TEAM_COUNT; } // BG_QUEUE_PREMADE_* -> BG_QUEUE_NORMAL_* + { + index += PVP_TEAM_COUNT; // BG_QUEUE_PREMADE_* -> BG_QUEUE_NORMAL_* + } if (ginfo->GroupTeam == HORDE) - { ++index; } // BG_QUEUE_*_ALLIANCE -> BG_QUEUE_*_HORDE + { + ++index; // BG_QUEUE_*_ALLIANCE -> BG_QUEUE_*_HORDE + } DEBUG_LOG("Adding Group to BattleGroundQueue bgTypeId : %u, bracket_id : %u, index : %u", BgTypeId, bracketId, index); @@ -213,7 +217,9 @@ GroupQueueInfo* BattleGroundQueue::AddGroup(Player* leader, Group* grp, BattleGr { Player* member = itr->getSource(); if (!member) - { continue; } // this should never happen + { + continue; // this should never happen + } PlayerQueueInfo& pl_info = m_QueuedPlayers[member->GetObjectGuid()]; pl_info.LastOnlineTime = lastOnlineTime; pl_info.GroupInfo = ginfo; @@ -282,7 +288,9 @@ void BattleGroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* g if (ginfo->arenaType == ARENA_TYPE_NONE) { if (ginfo->GroupTeam == HORDE) + { team_index = TEAM_INDEX_HORDE; + } } else { @@ -309,7 +317,9 @@ uint32 BattleGroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattleG if (ginfo->arenaType == ARENA_TYPE_NONE) { if (ginfo->GroupTeam == HORDE) + { team_index = TEAM_INDEX_HORDE; + } } else { @@ -323,7 +333,9 @@ uint32 BattleGroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattleG } else // if there aren't enough values return 0 - not available - { return 0; } + { + return 0; + } } // remove player from queue and from group info, if group info is empty then remove it too @@ -404,7 +416,9 @@ void BattleGroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount) // announce to world if arena team left queue for rated match, show only once if (group->arenaType != ARENA_TYPE_NONE && group->IsRated && group->Players.empty() && sWorld.getConfig(CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_EXIT)) + { sWorld.SendWorldText(LANG_ARENA_QUEUE_ANNOUNCE_WORLD_EXIT, group->arenaType, group->arenaType, group->ArenaTeamRating); + } // if player leaves queue and he is invited to rated arena match, then he have to loose if (group->IsInvitedToBGInstanceGUID && group->IsRated && decreaseInvitedCount) @@ -415,9 +429,13 @@ void BattleGroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount) DEBUG_LOG("UPDATING memberLost's personal arena rating for %s by opponents rating: %u", guid.GetString().c_str(), group->OpponentsTeamRating); Player* plr = sObjectMgr.GetPlayer(guid); if (plr) + { at->MemberLost(plr, group->OpponentsTeamRating); + } else + { at->OfflineMemberLost(guid, group->OpponentsTeamRating); + } at->SaveToDB(); } } @@ -492,7 +510,9 @@ bool BattleGroundQueue::InviteGroupToBG(GroupQueueInfo* ginfo, BattleGround* bg, // set ArenaTeamId for rated matches if (bg->isArena() && bg->isRated()) + { bg->SetArenaTeamIdForTeam(ginfo->GroupTeam, ginfo->ArenaTeamId); + } ginfo->RemoveInviteTime = WorldTimer::getMSTime() + INVITE_ACCEPT_WAIT_TIME; @@ -777,7 +797,9 @@ bool BattleGroundQueue::CheckSkirmishForSameFaction(BattleGroundBracketId bracke GroupsQueueType::iterator itr_team = m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].begin(); for (; itr_team != m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end(); ++itr_team) if (ginfo == *itr_team) + { break; + } if (itr_team == m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE + teamIdx].end()) { return false; @@ -789,7 +811,9 @@ bool BattleGroundQueue::CheckSkirmishForSameFaction(BattleGroundBracketId bracke { // if selection pool is full then break; if (!(*itr_team2)->IsInvitedToBGInstanceGUID && !m_SelectionPools[otherTeamIdx].AddGroup(*itr_team2, minPlayersPerTeam)) + { break; + } } if (m_SelectionPools[otherTeamIdx].GetPlayerCount() != minPlayersPerTeam) { @@ -831,7 +855,9 @@ void BattleGroundQueue::Update(BattleGroundTypeId bgTypeId, BattleGroundBracketI m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_HORDE].empty() && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_ALLIANCE].empty() && m_QueuedGroups[bracket_id][BG_QUEUE_NORMAL_HORDE].empty()) - { return; } + { + return; + } // battleground with free slot for player should be always in the beggining of the queue // maybe it would be better to create bgfreeslotqueue for each bracket_id @@ -1001,10 +1027,14 @@ void BattleGroundQueue::Update(BattleGroundTypeId bgTypeId, BattleGroundBracketI if (front1 && front2) { if (front1->JoinTime < front2->JoinTime) + { arenaRating = front1->ArenaTeamRating; + } } else if (!front1 && !front2) + { return; // queues are empty + } } // set rating range @@ -1171,7 +1201,9 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) Player* plr = sObjectMgr.GetPlayer(m_PlayerGuid); if (!plr) // player logged off (we should do nothing, he is correctly removed from queue in another procedure) - { return true; } + { + return true; + } BattleGround* bg = sBattleGroundMgr.GetBattleGround(m_BgInstanceGUID, m_BgTypeId); // battleground can be deleted already when we are removing queue info @@ -1190,7 +1222,9 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) bgQueue.RemovePlayer(m_PlayerGuid, true); // update queues if battleground isn't ended if (bg && bg->isBattleGround() && bg->GetStatus() != STATUS_WAIT_LEAVE) + { sBattleGroundMgr.ScheduleQueueUpdate(0, ARENA_TYPE_NONE, m_BgQueueTypeId, m_BgTypeId, bg->GetBracketId()); + } WorldPacket data; sBattleGroundMgr.BuildBattleGroundStatusPacket(&data, bg, plr, queueSlot, STATUS_NONE, 0, 0, ARENA_TYPE_NONE); @@ -1284,7 +1318,9 @@ void BattleGroundMgr::Update(uint32 diff) m_NextRatingDiscardUpdate = sWorld.getConfig(CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER); } else + { m_NextRatingDiscardUpdate -= diff; + } } } @@ -1292,7 +1328,9 @@ void BattleGroundMgr::BuildBattleGroundStatusPacket(WorldPacket* data, BattleGro { // we can be in 2 queues in same time... if (!bg) + { StatusID = STATUS_NONE; + } ObjectGuid playerGuid = player->GetObjectGuid(); ObjectGuid bgGuid = bg ? bg->GetObjectGuid() : ObjectGuid(); @@ -1520,9 +1558,13 @@ void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket* data, BattleGround* bg) for (int8 i = 0; i < PVP_TEAM_COUNT; ++i) { if (ArenaTeam* at = sObjectMgr.GetArenaTeamById(bg->m_ArenaTeamIds[i])) + { data->WriteBits(at->GetName().length(), 8); + } else + { data->WriteBits(0, 8); + } } } @@ -1543,7 +1585,9 @@ void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket* data, BattleGround* bg) data->WriteGuidMask<3, 0, 5, 1, 6>(memberGuid); Team team = bg->GetPlayerTeam(itr->first); if (!team && player) + { team = player->GetTeam(); + } data->WriteBit(team == ALLIANCE); // unk7 data->WriteGuidMask<7>(memberGuid); @@ -1566,9 +1610,13 @@ void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket* data, BattleGround* bg) buffer.WriteGuidBytes<1, 6>(memberGuid); // TODO: store this in player score if (player) + { buffer << uint32(player->GetPrimaryTalentTree(player->GetActiveSpec())); + } else + { buffer << uint32(0); + } switch (bg->GetTypeID()) // battleground specific things { @@ -1642,14 +1690,18 @@ void BattleGroundMgr::BuildPvpLogDataPacket(WorldPacket* data, BattleGround* bg) for (int8 i = 0; i < PVP_TEAM_COUNT; ++i) { if (ArenaTeam* at = sObjectMgr.GetArenaTeamById(bg->m_ArenaTeamIds[i])) + { data->append(at->GetName().data(), at->GetName().length()); + } } } *data << uint8(bg->GetPlayersCountByTeam(HORDE)); if (bg->GetStatus() == STATUS_WAIT_LEAVE) + { *data << uint8(bg->GetWinner() == ALLIANCE); // who win + } *data << uint8(bg->GetPlayersCountByTeam(ALLIANCE)); } @@ -1797,7 +1849,9 @@ BattleGround* BattleGroundMgr::GetBattleGroundTemplate(BattleGroundTypeId bgType uint32 BattleGroundMgr::CreateClientVisibleInstanceId(BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id) { if (IsArenaType(bgTypeId)) + { return 0; // arenas don't have client-instanceids + } // we create here an instanceid, which is just for // displaying this to the client and without any other use.. @@ -1992,7 +2046,9 @@ void BattleGroundMgr::CreateInitialBattleGrounds() } if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeID_)) + { continue; + } BattleGroundTypeId bgTypeID = BattleGroundTypeId(bgTypeID_); @@ -2126,7 +2182,9 @@ void BattleGroundMgr::DistributeArenaPoints() CharacterDatabase.PExecute("UPDATE `characters` SET `arenaPoints` = `arenaPoints` + '%u' WHERE `guid` = '%u'", plr_itr->second, plr_itr->first); // add points if player is online if (Player* pl = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, plr_itr->first))) + { pl->ModifyArenaPoints(plr_itr->second); + } } PlayerPoints.clear(); @@ -2200,7 +2258,9 @@ void BattleGroundMgr::BuildBattleGroundListPacket(WorldPacket* data, ObjectGuid data->WriteGuidBytes<6, 1, 7, 5>(guid); data->FlushBits(); if (count) + { data->append(buf); + } data->WriteGuidBytes<0, 2, 4, 3>(guid); } @@ -2348,9 +2408,13 @@ void BattleGroundMgr::ToggleArenaTesting() { m_ArenaTesting = !m_ArenaTesting; if (m_ArenaTesting) + { sWorld.SendWorldText(LANG_DEBUG_ARENA_ON); + } else + { sWorld.SendWorldText(LANG_DEBUG_ARENA_OFF); + } } void BattleGroundMgr::ScheduleQueueUpdate(uint32 arenaRating, ArenaType arenaType, BattleGroundQueueTypeId bgQueueTypeId, BattleGroundTypeId bgTypeId, BattleGroundBracketId bracket_id) @@ -2378,7 +2442,9 @@ uint32 BattleGroundMgr::GetMaxRatingDifference() const // this is for stupid people who can't use brain and set max rating difference to 0 uint32 diff = sWorld.getConfig(CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE); if (diff == 0) + { diff = 5000; + } return diff; } @@ -2533,7 +2599,9 @@ void BattleGroundMgr::LoadBattleEventIndexes() bar.step(); Field* fields = result->Fetch(); if (fields[2].GetUInt8() == BG_EVENT_NONE || fields[3].GetUInt8() == BG_EVENT_NONE) - { continue; } // we don't need to add those to the eventmap + { + continue; // we don't need to add those to the eventmap + } bool gameobject = (fields[0].GetUInt8() == 1); uint32 dbTableGuidLow = fields[1].GetUInt32(); diff --git a/src/game/BattleGround/BattleGroundNA.cpp b/src/game/BattleGround/BattleGroundNA.cpp index 9e1e5aaaa..261fadbb9 100644 --- a/src/game/BattleGround/BattleGroundNA.cpp +++ b/src/game/BattleGround/BattleGroundNA.cpp @@ -63,7 +63,9 @@ void BattleGroundNA::AddPlayer(Player* plr) void BattleGroundNA::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/) { if (GetStatus() == STATUS_WAIT_LEAVE) + { return; + } UpdateWorldState(0xa0f, GetAlivePlayersCountByTeam(ALLIANCE)); UpdateWorldState(0xa10, GetAlivePlayersCountByTeam(HORDE)); @@ -74,7 +76,9 @@ void BattleGroundNA::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/) void BattleGroundNA::HandleKillPlayer(Player* player, Player* killer) { if (GetStatus() != STATUS_IN_PROGRESS) + { return; + } if (!killer) { diff --git a/src/game/BattleGround/BattleGroundRB.cpp b/src/game/BattleGround/BattleGroundRB.cpp index 8474418aa..cc88cc0e6 100644 --- a/src/game/BattleGround/BattleGroundRB.cpp +++ b/src/game/BattleGround/BattleGroundRB.cpp @@ -50,7 +50,9 @@ void BattleGroundRB::UpdatePlayerScore(Player* source, uint32 type, uint32 value BattleGroundScoreMap::iterator itr = m_PlayerScores.find(source->GetObjectGuid()); if (itr == m_PlayerScores.end()) // player not found... + { return; + } BattleGround::UpdatePlayerScore(source, type, value); } diff --git a/src/game/BattleGround/BattleGroundRL.cpp b/src/game/BattleGround/BattleGroundRL.cpp index 54033637d..a158a11cf 100644 --- a/src/game/BattleGround/BattleGroundRL.cpp +++ b/src/game/BattleGround/BattleGroundRL.cpp @@ -62,7 +62,9 @@ void BattleGroundRL::AddPlayer(Player* plr) void BattleGroundRL::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/) { if (GetStatus() == STATUS_WAIT_LEAVE) + { return; + } UpdateWorldState(0xbb8, GetAlivePlayersCountByTeam(ALLIANCE)); UpdateWorldState(0xbb9, GetAlivePlayersCountByTeam(HORDE)); @@ -73,7 +75,9 @@ void BattleGroundRL::RemovePlayer(Player* /*plr*/, ObjectGuid /*guid*/) void BattleGroundRL::HandleKillPlayer(Player* player, Player* killer) { if (GetStatus() != STATUS_IN_PROGRESS) + { return; + } if (!killer) { diff --git a/src/game/BattleGround/BattleGroundSA.cpp b/src/game/BattleGround/BattleGroundSA.cpp index b57fbec23..fefd402cd 100644 --- a/src/game/BattleGround/BattleGroundSA.cpp +++ b/src/game/BattleGround/BattleGroundSA.cpp @@ -49,7 +49,9 @@ void BattleGroundSA::UpdatePlayerScore(Player* source, uint32 type, uint32 value { BattleGroundScoreMap::iterator itr = m_PlayerScores.find(source->GetObjectGuid()); if (itr == m_PlayerScores.end()) // player not found... + { return; + } BattleGround::UpdatePlayerScore(source, type, value); } diff --git a/src/game/BattleGround/BattleGroundWS.cpp b/src/game/BattleGround/BattleGroundWS.cpp index 35f29d3b4..6daeb4540 100644 --- a/src/game/BattleGround/BattleGroundWS.cpp +++ b/src/game/BattleGround/BattleGroundWS.cpp @@ -90,9 +90,13 @@ void BattleGroundWS::Update(uint32 diff) if (m_EndTimer <= diff) { if (m_TeamScores[TEAM_INDEX_ALLIANCE] > m_TeamScores[TEAM_INDEX_HORDE]) + { EndBattleGround(ALLIANCE); + } else if (m_TeamScores[TEAM_INDEX_ALLIANCE] < m_TeamScores[TEAM_INDEX_HORDE]) + { EndBattleGround(HORDE); + } else { // if 0 => tie @@ -106,7 +110,9 @@ void BattleGroundWS::Update(uint32 diff) uint32 minutesLeft = GetRemainingTimeInMinutes(); if (minutesLeft != minutesLeftPrev) + { UpdateWorldState(BG_WS_TIME_REMAINING, minutesLeft); + } } } } @@ -524,9 +530,13 @@ void BattleGroundWS::UpdateFlagState(Team team, uint32 value) void BattleGroundWS::UpdateTeamScore(Team team) { if (team == ALLIANCE) + { UpdateWorldState(BG_WS_FLAG_CAPTURES_ALLIANCE, m_TeamScores[TEAM_INDEX_ALLIANCE]); + } else + { UpdateWorldState(BG_WS_FLAG_CAPTURES_HORDE, m_TeamScores[TEAM_INDEX_HORDE]); + } } bool BattleGroundWS::HandleAreaTrigger(Player* source, uint32 trigger) @@ -592,9 +602,13 @@ void BattleGroundWS::EndBattleGround(Team winner) { // win reward if (winner == ALLIANCE) + { RewardHonorToTeam(GetBonusHonorFromKill(m_HonorWinKills), ALLIANCE); + } if (winner == HORDE) + { RewardHonorToTeam(GetBonusHonorFromKill(m_HonorWinKills), HORDE); + } // complete map_end rewards (even if no team wins) RewardHonorToTeam(GetBonusHonorFromKill(m_HonorEndKills), ALLIANCE); RewardHonorToTeam(GetBonusHonorFromKill(m_HonorEndKills), HORDE); diff --git a/src/game/ChatCommands/Level0.cpp b/src/game/ChatCommands/Level0.cpp index 036c06dc9..9914378c9 100644 --- a/src/game/ChatCommands/Level0.cpp +++ b/src/game/ChatCommands/Level0.cpp @@ -191,7 +191,9 @@ bool ChatHandler::HandleGMListIngameCommand(char* /*args*/) AccountTypes security = player->GetSession()->GetSecurity(); if ((player->isGameMaster() || (security > SEC_PLAYER && security <= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_GM_LEVEL_IN_GM_LIST))) && (!m_session || player->IsVisibleGloballyFor(m_session->GetPlayer()))) - { names.push_back(std::make_pair(GetNameLink(player), player->isAcceptWhispers())); } + { + names.push_back(std::make_pair(GetNameLink(player), player->isAcceptWhispers())); + } } } diff --git a/src/game/ChatCommands/Level1.cpp b/src/game/ChatCommands/Level1.cpp index eb93a2279..0a7dc0bcb 100644 --- a/src/game/ChatCommands/Level1.cpp +++ b/src/game/ChatCommands/Level1.cpp @@ -657,9 +657,13 @@ bool ChatHandler::HandleAppearCommand(char* args) } if (cMap->IsRaid()) + { _player->SetRaidDifficulty(target->GetRaidDifficulty()); + } else + { _player->SetDungeonDifficulty(target->GetDungeonDifficulty()); + } } PSendSysMessage(LANG_APPEARING_AT, chrNameLink.c_str()); @@ -778,7 +782,9 @@ bool ChatHandler::HandleModifyHolyPowerCommand(char* args) PSendSysMessage(LANG_YOU_CHANGE_HOLY_POWER, GetNameLink(chr).c_str(), power, maxPower); if (needReportToTarget(chr)) + { ChatHandler(chr).PSendSysMessage(LANG_YOURS_HOLY_POWER_CHANGED, GetNameLink().c_str(), power, maxPower); + } chr->SetPower(POWER_HOLY_POWER, power); @@ -991,7 +997,9 @@ bool ChatHandler::HandleModifyRunicPowerCommand(char* args) PSendSysMessage(LANG_YOU_CHANGE_RUNIC_POWER, GetNameLink(chr).c_str(), rune / 10, runem / 10); if (needReportToTarget(chr)) + { ChatHandler(chr).PSendSysMessage(LANG_YOURS_RUNIC_POWER_CHANGED, GetNameLink().c_str(), rune / 10, runem / 10); + } chr->SetMaxPower(POWER_RUNIC_POWER, runem); chr->SetPower(POWER_RUNIC_POWER, rune); @@ -1411,7 +1419,9 @@ bool ChatHandler::HandleModifyFlyCommand(char* args) PSendSysMessage(LANG_YOU_CHANGE_FLY_SPEED, modSpeed, GetNameLink(chr).c_str()); if (needReportToTarget(chr)) + { ChatHandler(chr).PSendSysMessage(LANG_YOURS_FLY_SPEED_CHANGED, GetNameLink().c_str(), modSpeed); + } chr->UpdateSpeed(MOVE_FLIGHT, true, modSpeed, true); @@ -1791,7 +1801,9 @@ bool ChatHandler::HandleModifyMoneyCommand(char* args) PSendSysMessage(LANG_YOU_TAKE_MONEY, MoneyToString(abs(addmoney)).c_str(), GetNameLink(chr).c_str()); if (needReportToTarget(chr)) + { ChatHandler(chr).PSendSysMessage(LANG_YOURS_MONEY_TAKEN, GetNameLink().c_str(), MoneyToString(abs(addmoney)).c_str()); + } chr->SetMoney(newmoney); } } @@ -1799,7 +1811,9 @@ bool ChatHandler::HandleModifyMoneyCommand(char* args) { PSendSysMessage(LANG_YOU_GIVE_MONEY, MoneyToString(addmoney).c_str(), GetNameLink(chr).c_str()); if (needReportToTarget(chr)) + { ChatHandler(chr).PSendSysMessage(LANG_YOURS_MONEY_GIVEN, GetNameLink().c_str(), MoneyToString(addmoney).c_str()); + } if (addmoney >= MAX_MONEY_AMOUNT) { @@ -2603,10 +2617,14 @@ bool ChatHandler::HandleModifyDrunkCommand(char* args) uint8 drunkValue = (uint8)atoi(args); if (drunkValue > 100) + { drunkValue = 100; + } if (Player* target = getSelectedPlayer()) + { target->SetDrunkValue(drunkValue); + } return true; } diff --git a/src/game/ChatCommands/Level2.cpp b/src/game/ChatCommands/Level2.cpp index 7f298e462..477569ee7 100644 --- a/src/game/ChatCommands/Level2.cpp +++ b/src/game/ChatCommands/Level2.cpp @@ -344,9 +344,13 @@ bool ChatHandler::HandleTriggerCommand(char* args) SendSysMessage(LANG_TRIGGER_REQ_KEYS_HEROIC); if (at->heroicKey) + { ShowItemListHelper(at->heroicKey, loc_idx, pl); + } if (at->heroicKey2) + { ShowItemListHelper(at->heroicKey2, loc_idx, pl); + } } if (at->requiredQuestHeroic) @@ -1311,7 +1315,9 @@ bool ChatHandler::HandleGameObjectPhaseCommand(char* args) // by DB guid if (GameObjectData const* go_data = sObjectMgr.GetGOData(lowguid)) + { obj = GetGameObjectWithGuid(lowguid, go_data->id); + } if (!obj) { @@ -1431,7 +1437,9 @@ void ChatHandler::ShowAchievementListHelper(AchievementEntry const* achEntry, Lo if (AchievementCriteriaEntryList const* criteriaList = sAchievementMgr.GetAchievementCriteriaByAchievement(achEntry->ID)) for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) if (mgr->IsCompletedCriteria(*itr, achEntry)) + { criteriaMask[((*itr)->showOrder - 1) / 32] |= (1 << (((*itr)->showOrder - 1) % 32)); + } for (int i = 0; i < 4; ++i) { @@ -1439,16 +1447,22 @@ void ChatHandler::ShowAchievementListHelper(AchievementEntry const* achEntry, Lo } } else + { ss << "0:0:0:0:"; + } } ss << "|h[" << name << " " << localeNames[loc] << "]|h|r"; } else + { ss << achEntry->ID << " - " << name << " " << localeNames[loc]; + } if (target && date) + { ss << " [" << TimeToTimestampStr(*date) << "]"; + } SendSysMessage(ss.str().c_str()); } @@ -1480,12 +1494,16 @@ bool ChatHandler::HandleLookupAchievementCommand(char* args) { AchievementEntry const* achEntry = sAchievementStore.LookupEntry(id); if (!achEntry) + { continue; + } int loc = GetSessionDbcLocale(); std::string name = achEntry->name[loc]; if (name.empty()) + { continue; + } if (!Utf8FitTo(name, wnamepart)) { @@ -1493,14 +1511,20 @@ bool ChatHandler::HandleLookupAchievementCommand(char* args) for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) + { continue; + } name = achEntry->name[loc]; if (name.empty()) + { continue; + } if (Utf8FitTo(name, wnamepart)) + { break; + } } } @@ -1513,7 +1537,9 @@ bool ChatHandler::HandleLookupAchievementCommand(char* args) } if (counter == 0) // if counter == 0 then we found nth + { SendSysMessage(LANG_COMMAND_ACHIEVEMENT_NOTFOUND); + } return true; } @@ -2607,7 +2633,9 @@ bool ChatHandler::HandleNpcSetPhaseCommand(char* args) pCreature->SetPhaseMask(phasemask, true); if (pCreature->HasStaticDBSpawnData()) + { pCreature->SaveToDB(); + } return true; } @@ -2700,7 +2728,9 @@ bool ChatHandler::HandleNpcSubNameCommand(char* /*args*/) /* Temp. disabled if (!*args) + { args = ""; + } if (strlen((char*)args)>75) { @@ -2884,7 +2914,9 @@ bool ChatHandler::HandleModifyPhaseCommand(char* args) Unit* target = getSelectedUnit(); if (!target) + { target = m_session->GetPlayer(); + } // check online security else if (target->GetTypeId() == TYPEID_PLAYER && HasLowerSecurity((Player*)target)) @@ -3128,7 +3160,9 @@ bool ChatHandler::HandleTicketCommand(char* args) ticket->SetResponseText(args); if (Player* pl = sObjectMgr.GetPlayer(ticket->GetPlayerGuid())) + { pl->GetSession()->SendGMResponse(ticket); + } return true; } @@ -3285,14 +3319,20 @@ inline void UnsummonVisualWaypoints(Player const* player, ObjectGuid ownerGuid) for (std::list::iterator itr = waypoints.begin(); itr != waypoints.end(); ++itr) { if ((*itr)->GetSubtype() != CREATURE_SUBTYPE_TEMPORARY_SUMMON) + { continue; + } TemporarySummonWaypoint* wpTarget = dynamic_cast(*itr); if (!wpTarget) + { continue; + } if (wpTarget->GetSummonerGuid() == ownerGuid) + { wpTarget->UnSummon(); + } } } @@ -3320,7 +3360,9 @@ bool ChatHandler::HandleWpAddCommand(char* args) CreatureInfo const* waypointInfo = ObjectMgr::GetCreatureTemplate(VISUAL_WAYPOINT); if (!waypointInfo || waypointInfo->GetHighGuid() != HIGHGUID_UNIT) + { return false; // must exist as normal creature in mangos.sql 'creature_template' + } Creature* targetCreature = getSelectedCreature(); WaypointPathOrigin wpDestination = PATH_NO_PATH; ///< into which storage @@ -3354,7 +3396,9 @@ bool ChatHandler::HandleWpAddCommand(char* args) wpPointId = wpTarget->GetWaypointId() + 1; // Insert as next waypoint } else // normal creature selected + { wpOwner = targetCreature; + } } else //!targetCreature - first argument must be dbGuid { @@ -3396,11 +3440,15 @@ bool ChatHandler::HandleWpAddCommand(char* args) { uint32 src = (uint32)PATH_NO_PATH; if (ExtractOptUInt32(&args, src, src)) + { wpDestination = (WaypointPathOrigin)src; + } else // pathId provided but no destination { if (wpPathId != 0) + { wpDestination = PATH_FROM_ENTRY; // Multiple Paths must only be assigned by entry + } } } @@ -3408,7 +3456,9 @@ bool ChatHandler::HandleWpAddCommand(char* args) { if (wpOwner->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) if (WaypointMovementGenerator const* wpMMGen = dynamic_cast const*>(wpOwner->GetMotionMaster()->GetCurrent())) + { wpMMGen->GetPathInformation(wpPathId, wpDestination); + } // Get information about default path if no current path. If no default path, prepare data dependendy on uniqueness if (wpDestination == PATH_NO_PATH && !sWaypointMgr.GetDefaultPath(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), &wpDestination)) @@ -3418,7 +3468,9 @@ bool ChatHandler::HandleWpAddCommand(char* args) { QueryResult* result = WorldDatabase.PQuery("SELECT COUNT(`id`) FROM `creature` WHERE `id` = %u", wpOwner->GetEntry()); if (result && result->Fetch()[0].GetUInt32() != 1) + { wpDestination = PATH_FROM_GUID; + } delete result; } } @@ -3501,7 +3553,9 @@ bool ChatHandler::HandleWpModifyCommand(char* args) CreatureInfo const* waypointInfo = ObjectMgr::GetCreatureTemplate(VISUAL_WAYPOINT); if (!waypointInfo || waypointInfo->GetHighGuid() != HIGHGUID_UNIT) - { return false; } // must exist as normal creature in mangos.sql 'creature_template' + { + return false; // must exist as normal creature in mangos.sql 'creature_template' + } // first arg: add del text emote spell waittime move char* subCmd_str = ExtractLiteralArg(&args); @@ -3598,10 +3652,14 @@ bool ChatHandler::HandleWpModifyCommand(char* args) { if (wpOwner->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) if (WaypointMovementGenerator const* wpMMGen = dynamic_cast const*>(wpOwner->GetMotionMaster()->GetCurrent())) + { wpMMGen->GetPathInformation(wpPathId, wpSource); + } if (wpSource == PATH_NO_PATH) + { sWaypointMgr.GetDefaultPath(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), &wpSource); + } } WaypointPath const* wpPath = sWaypointMgr.GetPathFromOrigin(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), wpPathId, wpSource); @@ -3637,7 +3695,9 @@ bool ChatHandler::HandleWpModifyCommand(char* args) sWaypointMgr.DeleteNode(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), wpId, wpPathId, wpSource); if (TemporarySummonWaypoint* wpCreature = dynamic_cast(targetCreature)) + { wpCreature->UnSummon(); + } if (wpPath->empty()) { @@ -3686,7 +3746,9 @@ bool ChatHandler::HandleWpModifyCommand(char* args) } if (!sWaypointMgr.SetNodeScriptId(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), wpId, wpPathId, wpSource, scriptId)) + { PSendSysMessage(LANG_WAYPOINT_INFO_UNK_SCRIPTID, scriptId); + } } else if (subCmd == "orientation") { @@ -3729,7 +3791,9 @@ bool ChatHandler::HandleWpShowCommand(char* args) CreatureInfo const* waypointInfo = ObjectMgr::GetCreatureTemplate(VISUAL_WAYPOINT); if (!waypointInfo || waypointInfo->GetHighGuid() != HIGHGUID_UNIT) - { return false; } // must exist as normal creature in mangos.sql 'creature_template' + { + return false; // must exist as normal creature in mangos.sql 'creature_template' + } // first arg: info, on, off, first, last @@ -3752,7 +3816,9 @@ bool ChatHandler::HandleWpShowCommand(char* args) { uint32 src; if (ExtractOptUInt32(&args, src, (uint32)PATH_NO_PATH)) + { wpOrigin = (WaypointPathOrigin)src; + } } } else // Guid must be provided @@ -3766,7 +3832,9 @@ bool ChatHandler::HandleWpShowCommand(char* args) { uint32 src = (uint32)PATH_NO_PATH; if (ExtractOptUInt32(&args, src, src)) + { wpOrigin = (WaypointPathOrigin)src; + } } // Params now parsed, check them @@ -3822,12 +3890,16 @@ bool ChatHandler::HandleWpShowCommand(char* args) wpPathId = wpTarget->GetPathId(); } else + { wpOwner = targetCreature; + } // Get the path WaypointPath* wpPath = NULL; if (wpOrigin != PATH_NO_PATH) // Might have been provided by param + { wpPath = sWaypointMgr.GetPathFromOrigin(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), wpPathId, wpOrigin); + } else { if (wpOwner->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) @@ -3838,7 +3910,9 @@ bool ChatHandler::HandleWpShowCommand(char* args) } if (wpOrigin == PATH_NO_PATH) + { wpPath = sWaypointMgr.GetDefaultPath(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), &wpOrigin); + } } if (!wpPath || wpPath->empty()) @@ -3865,7 +3939,9 @@ bool ChatHandler::HandleWpShowCommand(char* args) PSendSysMessage(LANG_WAYPOINT_INFO_ORI, point->second.orientation); PSendSysMessage(LANG_WAYPOINT_INFO_SCRIPTID, point->second.script_id); if (wpOrigin == PATH_FROM_EXTERNAL) + { PSendSysMessage(LANG_WAYPOINT_INFO_AISCRIPT, wpOwner->GetScriptName().c_str()); + } if (WaypointBehavior* behaviour = point->second.behavior) { PSendSysMessage(" ModelId1: %u", behaviour->model1); @@ -3971,7 +4047,9 @@ bool ChatHandler::HandleWpExportCommand(char* args) wpPathId = wpTarget->GetPathId(); } else // normal creature selected + { wpOwner = targetCreature; + } } else { @@ -4022,11 +4100,15 @@ bool ChatHandler::HandleWpExportCommand(char* args) { uint32 src = (uint32)PATH_NO_PATH; if (ExtractOptUInt32(&args, src, src)) + { wpOrigin = (WaypointPathOrigin)src; + } else // pathId provided but no destination { if (wpPathId != 0) + { wpOrigin = PATH_FROM_ENTRY; // Multiple Paths must only be assigned by entry + } } } @@ -4034,9 +4116,13 @@ bool ChatHandler::HandleWpExportCommand(char* args) { if (wpOwner->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE) if (WaypointMovementGenerator const* wpMMGen = dynamic_cast const*>(wpOwner->GetMotionMaster()->GetCurrent())) + { wpMMGen->GetPathInformation(wpPathId, wpOrigin); + } if (wpOrigin == PATH_NO_PATH) + { sWaypointMgr.GetDefaultPath(wpOwner->GetEntry(), wpOwner->GetGUIDLow(), &wpOrigin); + } } } @@ -4085,11 +4171,17 @@ bool ChatHandler::HandleWpExportCommand(char* args) outfile << itr->second.orientation << ","; outfile << itr->second.delay << ","; if (wpOrigin != PATH_FROM_EXTERNAL) // Only for normal waypoints + { outfile << itr->second.script_id << ")"; + } if (countDown > 1) + { outfile << ",\n"; + } else + { outfile << ";\n"; + } } PSendSysMessage(LANG_WAYPOINT_EXPORTED); @@ -4647,7 +4739,9 @@ bool ChatHandler::HandleLearnAllRecipesCommand(char* args) if ((skillInfo->categoryId != SKILL_CATEGORY_PROFESSION && skillInfo->categoryId != SKILL_CATEGORY_SECONDARY) || !skillInfo->canLink) // only prof with recipes have set - { continue; } + { + continue; + } int loc = GetSessionDbcLocale(); name = skillInfo->name[loc]; @@ -5315,9 +5409,13 @@ bool ChatHandler::HandleWaterwalkCommand(char* args) } if (value) - { player->SetWaterWalk(true); } // ON + { + player->SetWaterWalk(true); // ON + } else - { player->SetWaterWalk(false); } // OFF + { + player->SetWaterWalk(false); // OFF + } PSendSysMessage(LANG_YOU_SET_WATERWALK, args, GetNameLink(player).c_str()); if (needReportToTarget(player)) @@ -5362,7 +5460,9 @@ bool ChatHandler::HandleLookupTitleCommand(char* args) int loc = GetSessionDbcLocale(); std::string name = titleInfo->name[loc]; if (name.empty()) + { continue; + } if (!Utf8FitTo(name, wnamepart)) { @@ -5370,14 +5470,20 @@ bool ChatHandler::HandleLookupTitleCommand(char* args) for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) + { continue; + } name = titleInfo->name[loc]; if (name.empty()) + { continue; + } if (Utf8FitTo(name, wnamepart)) + { break; + } } } @@ -5394,16 +5500,22 @@ bool ChatHandler::HandleLookupTitleCommand(char* args) // send title in "id (idx:idx) - [namedlink locale]" format if (m_session) + { PSendSysMessage(LANG_TITLE_LIST_CHAT, id, titleInfo->bit_index, id, titleNameStr, localeNames[loc], knownStr, activeStr); + } else + { PSendSysMessage(LANG_TITLE_LIST_CONSOLE, id, titleInfo->bit_index, titleNameStr, localeNames[loc], knownStr, activeStr); + } ++counter; } } } if (counter == 0) // if counter == 0 then we found nth + { SendSysMessage(LANG_COMMAND_NOTITLEFOUND); + } return true; } @@ -5544,7 +5656,9 @@ bool ChatHandler::HandleTitlesSetMaskCommand(char* args) for (uint32 i = 1; i < sCharTitlesStore.GetNumRows(); ++i) if (CharTitlesEntry const* tEntry = sCharTitlesStore.LookupEntry(i)) + { titles2 &= ~(uint64(1) << tEntry->bit_index); + } titles &= ~titles2; // remove nonexistent titles @@ -5580,7 +5694,9 @@ bool ChatHandler::HandleCharacterTitlesCommand(char* args) { std::string name = titleInfo->name[loc]; if (name.empty()) + { continue; + } char const* activeStr = target && target->GetUInt32Value(PLAYER_CHOSEN_TITLE) == titleInfo->bit_index ? GetMangosString(LANG_ACTIVE) @@ -5591,9 +5707,13 @@ bool ChatHandler::HandleCharacterTitlesCommand(char* args) // send title in "id (idx:idx) - [namedlink locale]" format if (m_session) + { PSendSysMessage(LANG_TITLE_LIST_CHAT, id, titleInfo->bit_index, id, titleNameStr, localeNames[loc], knownStr, activeStr); + } else + { PSendSysMessage(LANG_TITLE_LIST_CONSOLE, id, titleInfo->bit_index, name.c_str(), localeNames[loc], knownStr, activeStr); + } } } return true; @@ -5678,12 +5798,18 @@ bool ChatHandler::HandleMmapPathCommand(char* args) followPath = true; para = strtok(NULL, " "); if (para && strcmp(para, "straight") == 0) + { useStraightPath = true; + } } else if (strcmp(para, "straight") == 0) + { useStraightPath = true; + } else if (strcmp(para, "to_me") == 0) + { unitToPlayer = true; + } else { PSendSysMessage("Use '.mmap path go' to move on target."); diff --git a/src/game/ChatCommands/Level3.cpp b/src/game/ChatCommands/Level3.cpp index f2bd05e3f..5644943be 100644 --- a/src/game/ChatCommands/Level3.cpp +++ b/src/game/ChatCommands/Level3.cpp @@ -937,7 +937,9 @@ bool ChatHandler::HandleReloadDBScriptsOnGossipCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_GOSSIP); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_GOSSIP]` reloaded."); + } return true; } @@ -959,7 +961,9 @@ bool ChatHandler::HandleReloadDBScriptsOnSpellCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_SPELL); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_SPELL]` reloaded."); + } return true; } @@ -981,7 +985,9 @@ bool ChatHandler::HandleReloadDBScriptsOnQuestStartCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_QUEST_START); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_QUEST_START]` reloaded."); + } return true; } @@ -1003,7 +1009,9 @@ bool ChatHandler::HandleReloadDBScriptsOnQuestEndCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_QUEST_END); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_QUEST_END]` reloaded."); + } return true; } @@ -1025,7 +1033,9 @@ bool ChatHandler::HandleReloadDBScriptsOnEventCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_EVENT); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_EVENT]` reloaded."); + } return true; } @@ -1048,7 +1058,9 @@ bool ChatHandler::HandleReloadDBScriptsOnGoUseCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_GOT_USE); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_GO[_TEMPLATE]_USE]` reloaded."); + } return true; } @@ -1070,7 +1082,9 @@ bool ChatHandler::HandleReloadDBScriptsOnCreatureDeathCommand(char* args) sScriptMgr.LoadDbScripts(DBS_ON_CREATURE_DEATH); if (*args != 'a') + { SendGlobalSysMessage("DB table `db_scripts [type = DBS_ON_CREATURE_DEATH]` reloaded."); + } return true; } @@ -1358,19 +1372,27 @@ void ChatHandler::ShowAchievementCriteriaListHelper(AchievementCriteriaEntry con ss << criEntry->ID << " - |cffffffff|Hachievement_criteria:" << criEntry->ID << "|h[" << criEntry->name[loc] << " " << localeNames[loc] << "]|h|r"; } else + { ss << criEntry->ID << " - " << criEntry->name[loc] << " " << localeNames[loc]; + } if (target) + { ss << " = " << target->GetAchievementMgr().GetCriteriaProgressCounter(criEntry); + } if (achEntry->flags & ACHIEVEMENT_FLAG_COUNTER) + { ss << GetMangosString(LANG_COUNTER); + } else { ss << " [" << AchievementMgr::GetCriteriaProgressMaxCounter(criEntry, achEntry) << "]"; if (target && target->GetAchievementMgr().IsCompletedCriteria(criEntry, achEntry)) + { ss << GetMangosString(LANG_COMPLETE); + } } SendSysMessage(ss.str().c_str()); @@ -1390,7 +1412,9 @@ bool ChatHandler::HandleAchievementCommand(char* args) } } else + { target = getSelectedPlayer(); + } uint32 achId; if (!ExtractUint32KeyFromLink(&args, "Hachievement", achId)) @@ -1455,7 +1479,9 @@ bool ChatHandler::HandleAchievementAddCommand(char* args) for (AchievementCriteriaEntryList::const_iterator itr = criteriaList->begin(); itr != criteriaList->end(); ++itr) { if (mgr.IsCompletedCriteria(*itr, achEntry)) + { continue; + } uint32 maxValue = AchievementMgr::GetCriteriaProgressMaxCounter(*itr, achEntry); if (maxValue == std::numeric_limits::max()) @@ -1528,7 +1554,9 @@ bool ChatHandler::HandleAchievementCriteriaAddCommand(char* args) } } else + { target = getSelectedPlayer(); + } AchievementCriteriaEntry const* criEntry = sAchievementCriteriaStore.LookupEntry(criId); if (!criEntry) @@ -1570,7 +1598,9 @@ bool ChatHandler::HandleAchievementCriteriaAddCommand(char* args) uint32 new_val; if (maxValue) + { new_val = progress < maxValue && maxValue - progress > val ? progress + val : maxValue; + } else { uint32 max_int = std::numeric_limits::max(); @@ -1603,7 +1633,9 @@ bool ChatHandler::HandleAchievementCriteriaRemoveCommand(char* args) } } else + { target = getSelectedPlayer(); + } AchievementCriteriaEntry const* criEntry = sAchievementCriteriaStore.LookupEntry(criId); if (!criEntry) @@ -1778,7 +1810,9 @@ bool ChatHandler::HandleUnLearnCommand(char* args) } if (GetTalentSpellCost(spell_id)) + { target->SendTalentsInfoData(false); + } return true; } @@ -2657,15 +2691,21 @@ bool ChatHandler::HandleLearnAllMyPetTalentsCommand(char* /*args*/) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) + { continue; + } TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) + { continue; + } // prevent learn talent for different family (cheating) if (((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask) == 0) + { continue; + } // search highest talent rank uint32 spellid = 0; @@ -2680,11 +2720,15 @@ bool ChatHandler::HandleLearnAllMyPetTalentsCommand(char* /*args*/) } if (!spellid) // ??? none spells in talent + { continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellid); if (!spellInfo || !SpellMgr::IsSpellValid(spellInfo, m_session->GetPlayer(), false)) + { continue; + } // learn highest rank of talent and learn all non-talent spell ranks (recursive by tree) pet->learnSpellHighRank(spellid); @@ -2765,7 +2809,9 @@ bool ChatHandler::HandleLearnCommand(char* args) SendSysMessage(LANG_YOU_KNOWN_SPELL); } else + { PSendSysMessage(LANG_TARGET_KNOWN_SPELL, GetNameLink(targetPlayer).c_str()); + } SetSentErrorMessage(true); return false; } @@ -2781,7 +2827,9 @@ bool ChatHandler::HandleLearnCommand(char* args) uint32 first_spell = sSpellMgr.GetFirstSpellInChain(spell); if (GetTalentSpellCost(first_spell)) + { targetPlayer->SendTalentsInfoData(false); + } return true; } @@ -3189,9 +3237,13 @@ bool ChatHandler::HandleListItemCommand(char* args) delete result; if (count > res_count) + { count -= res_count; + } else if (count) + { count = 0; + } } if (inv_count + mail_count + auc_count + guild_count == 0) @@ -3633,17 +3685,27 @@ void ChatHandler::ShowCurrencyListHelper(Player* target, CurrencyTypesEntry cons // send spell in "id - [name] (Amount: x)" format std::ostringstream ss; if (m_session) + { ss << id << " - |cff00aa00|Hcurrency:" << id << "|h[" << currency->name[loc]; + } else + { ss << id << " - " << currency->name[loc]; + } if (m_session) + { ss << " " << localeNames[loc] << "]|h|r"; + } else + { ss << " " << localeNames[loc]; + } if (target) + { ss << " (" << GetMangosString(LANG_CURRENCY_AMOUNT) << ": " << count << ")"; + } SendSysMessage(ss.str().c_str()); } @@ -3748,7 +3810,9 @@ bool ChatHandler::HandleLookupCurrencyCommand(char* args) int loc = GetSessionDbcLocale(); std::string name = currency->name[loc]; if (name.empty()) + { continue; + } if (!Utf8FitTo(name, wnamepart)) { @@ -3756,14 +3820,20 @@ bool ChatHandler::HandleLookupCurrencyCommand(char* args) for (; loc < MAX_LOCALE; ++loc) { if (loc == GetSessionDbcLocale()) + { continue; + } name = currency->name[loc]; if (name.empty()) + { continue; + } if (Utf8FitTo(name, wnamepart)) + { break; + } } } @@ -3775,7 +3845,9 @@ bool ChatHandler::HandleLookupCurrencyCommand(char* args) } } if (counter == 0) // if counter == 0 then we found nth + { SendSysMessage(LANG_COMMAND_NOCURRENCYFOUND); + } return true; } @@ -3842,7 +3914,9 @@ bool ChatHandler::HandleLookupSpellCommand(char* args) if (loc < MAX_LOCALE) { if (target) + { ShowSpellListHelper(target, spellInfo, LocaleConstant(loc)); + } ++counter; } @@ -4570,7 +4644,9 @@ bool ChatHandler::HandleReviveCommand(char* args) } else // will resurrected at login without corpse - { sObjectAccessor.ConvertCorpseForPlayer(target_guid); } + { + sObjectAccessor.ConvertCorpseForPlayer(target_guid); + } return true; } @@ -4608,7 +4684,9 @@ bool ChatHandler::HandleAuraCommand(char* args) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } uint8 eff = spellEffect->Effect; if (eff >= TOTAL_SPELL_EFFECTS) @@ -4887,14 +4965,18 @@ bool ChatHandler::HandleNpcInfoCommand(char* /*args*/) uint32 diff = 1; for (; diff < MAX_DIFFICULTY; ++diff) if (baseInfo->DifficultyEntry[diff - 1] == target->GetCreatureInfo()->Entry) + { break; + } if (diff < MAX_DIFFICULTY) PSendSysMessage(LANG_NPCINFO_CHAR_DIFFICULTY, target->GetGuidStr().c_str(), faction, npcflags, Entry, target->GetCreatureInfo()->Entry, diff, displayid, nativeid); else + { PSendSysMessage(LANG_NPCINFO_CHAR, target->GetGuidStr().c_str(), faction, npcflags, Entry, displayid, nativeid); + } PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel()); PSendSysMessage(LANG_NPCINFO_HEALTH, target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth()); @@ -4998,7 +5080,9 @@ bool ChatHandler::HandleNpcAddWeaponCommand(char* /*args*/) } if(added) + { PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT,ItemID,tmpItem->Name1,SlotID); + } } else { @@ -5130,7 +5214,9 @@ bool ChatHandler::HandleCharacterLevelCommand(char* args) } if (newlevel < 1) - { return false; } // invalid level + { + return false; // invalid level + } if (newlevel > STRONG_MAX_LEVEL) // hardcoded maximum level { @@ -5490,9 +5576,13 @@ bool ChatHandler::HandleChangeWeatherCommand(char* args) // clamp grade from 0 to 1 if (grade < 0.0f) + { grade = 0.0f; + } else if (grade > 1.0f) + { grade = 1.0f; + } Player* player = m_session->GetPlayer(); uint32 zoneId = player->GetZoneId(); @@ -5708,9 +5798,13 @@ bool ChatHandler::HandleResetAchievementsCommand(char* args) } if (target) + { target->GetAchievementMgr().Reset(); + } else + { AchievementMgr::DeleteFromDB(target_guid); + } return true; } @@ -5886,7 +5980,9 @@ bool ChatHandler::HandleResetSpecsCommand(char* args) Pet* pet = target->GetPet(); Pet::resetTalentsForAllPetsOf(target, pet); if (pet) + { target->SendTalentsInfoData(true); + } return true; } else if (target_guid) @@ -5921,7 +6017,9 @@ bool ChatHandler::HandleResetTalentsCommand(char* args) ChatHandler((Player*)owner).SendSysMessage(LANG_RESET_PET_TALENTS); if (!m_session || m_session->GetPlayer() != ((Player*)owner)) + { PSendSysMessage(LANG_RESET_PET_TALENTS_ONLINE, GetNameLink((Player*)owner).c_str()); + } } return true; } @@ -5937,12 +6035,16 @@ bool ChatHandler::HandleResetTalentsCommand(char* args) target->SendTalentsInfoData(false); ChatHandler(target).SendSysMessage(LANG_RESET_TALENTS); if (!m_session || m_session->GetPlayer() != target) + { PSendSysMessage(LANG_RESET_TALENTS_ONLINE, GetNameLink(target).c_str()); + } Pet* pet = target->GetPet(); Pet::resetTalentsForAllPetsOf(target, pet); if (pet) + { target->SendTalentsInfoData(true); + } return true; } @@ -6316,11 +6418,15 @@ bool ChatHandler::HandleQuestCompleteCommand(char* args) for (int i = 0; i < QUEST_REQUIRED_CURRENCY_COUNT; ++i) { if (pQuest->ReqCurrencyId[i]) + { player->ModifyCurrencyCount(pQuest->ReqCurrencyId[i], int32(pQuest->ReqCurrencyCount[i] * GetCurrencyPrecision(pQuest->ReqCurrencyId[i]))); + } } if (uint32 spell = pQuest->GetReqSpellLearned()) + { player->learnSpell(spell, false); + } player->CompleteQuest(entry, QUEST_STATUS_FORCE_COMPLETE); return true; @@ -7539,7 +7645,9 @@ bool ChatHandler::HandleInstanceUnbindCommand(char* args) ++counter; } else + { ++itr; + } } } PSendSysMessage("instances unbound: %d", counter); @@ -7721,7 +7829,9 @@ bool ChatHandler::HandleAccountSetAddonCommand(char* args) // or to self account if (GetAccountId() && GetAccountId() != account_id && HasLowerSecurityAccount(NULL, account_id, true)) - { return false; } + { + return false; + } uint32 lev; if (!ExtractUInt32(&args, lev)) @@ -8236,18 +8346,24 @@ bool ChatHandler::HandleMmapTestHeight(char* args) float radius = 0.0f; ExtractFloat(&args, radius); if (radius > 40.0f) + { radius = 40.0f; + } Unit* unit = getSelectedUnit(); Player* player = m_session->GetPlayer(); if (!unit) + { unit = player; + } if (unit->GetTypeId() == TYPEID_UNIT) { if (radius < 0.1f) + { radius = static_cast(unit)->GetRespawnRadius(); + } } else { @@ -8280,7 +8396,9 @@ bool ChatHandler::HandleMmapTestHeight(char* args) unit->SummonCreature(VISUAL_WAYPOINT, gx, gy, gz, 0, TEMPSUMMON_TIMED_DESPAWN, 15000); ++successes; if (successes >= 100) + { break; + } } } uint32 genTime = WorldTimer::getMSTimeDiff(startTime, WorldTimer::getMSTime()); diff --git a/src/game/ChatCommands/Level4.cpp b/src/game/ChatCommands/Level4.cpp index 983d3e2df..ac3ce3d51 100644 --- a/src/game/ChatCommands/Level4.cpp +++ b/src/game/ChatCommands/Level4.cpp @@ -512,9 +512,13 @@ bool ChatHandler::HandleAccountCreateCommand(char* args) AccountOpResult result; uint32 expansion = 0; if(ExtractUInt32(&args, expansion)) + { result = sAccountMgr.CreateAccount(account_name, password, expansion); + } else + { result = sAccountMgr.CreateAccount(account_name, password); + } switch (result) { case AOR_OK: diff --git a/src/game/ChatCommands/debugcmds.cpp b/src/game/ChatCommands/debugcmds.cpp index 940aaa381..8de7432f2 100644 --- a/src/game/ChatCommands/debugcmds.cpp +++ b/src/game/ChatCommands/debugcmds.cpp @@ -148,11 +148,15 @@ bool ChatHandler::HandleDebugRecvOpcodeCommand(char* /*args*/) { Unit* unit = getSelectedUnit(); if (!unit || (unit->GetTypeId() != TYPEID_PLAYER)) - { unit = m_session->GetPlayer(); } + { + unit = m_session->GetPlayer(); + } std::ifstream stream("ropcode.txt"); if (!stream.is_open()) - { return false; } + { + return false; + } uint32 opcode = 0; if (!(stream >> opcode)) @@ -167,7 +171,9 @@ bool ChatHandler::HandleDebugRecvOpcodeCommand(char* /*args*/) while (stream >> type) { if (type.empty()) - { break; } + { + break; + } if (type == "uint8") { @@ -206,17 +212,29 @@ bool ChatHandler::HandleDebugRecvOpcodeCommand(char* /*args*/) *data << value; } else if (type == "pguid") - { *data << unit->GetPackGUID(); } + { + *data << unit->GetPackGUID(); + } else if (type == "guid") - { *data << unit->GetObjectGuid(); } + { + *data << unit->GetObjectGuid(); + } else if (type == "mypguid") - { *data << m_session->GetPlayer()->GetPackGUID(); } + { + *data << m_session->GetPlayer()->GetPackGUID(); + } else if (type == "myguid") - { *data << m_session->GetPlayer()->GetObjectGuid(); } + { + *data << m_session->GetPlayer()->GetObjectGuid(); + } else if (type == "name") - { *data << unit->GetName(); } + { + *data << unit->GetName(); + } else if (type == "myname") - { *data << m_session->GetPlayerName(); } + { + *data << m_session->GetPlayerName(); + } else { DEBUG_LOG("Sending opcode: unknown type '%s'", type.c_str()); @@ -301,17 +319,29 @@ bool ChatHandler::HandleDebugSendOpcodeCommand(char* /*args*/) data << value; } else if (type == "pguid") - { data << unit->GetPackGUID(); } + { + data << unit->GetPackGUID(); + } else if (type == "guid") - { data << unit->GetObjectGuid(); } + { + data << unit->GetObjectGuid(); + } else if(type == "mypguid") - { data << m_session->GetPlayer()->GetPackGUID(); } + { + data << m_session->GetPlayer()->GetPackGUID(); + } else if (type == "myguid") - { data << m_session->GetPlayer()->GetObjectGuid(); } + { + data << m_session->GetPlayer()->GetObjectGuid(); + } else if (type == "name") - { data << unit->GetName(); } + { + data << unit->GetName(); + } else if (type == "myname") - { data << m_session->GetPlayerName(); } + { + data << m_session->GetPlayerName(); + } else { DEBUG_LOG("Sending opcode: unknown type '%s'", type.c_str()); @@ -1379,7 +1409,9 @@ bool ChatHandler::HandleDebugSpellCoefsCommand(char* args) { SpellEffectEntry const* spellEffect = spellEntry->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // Heals (Also count Mana Shield and Absorb effects as heals) if (spellEffect->Effect == SPELL_EFFECT_HEAL || spellEffect->Effect == SPELL_EFFECT_HEAL_MAX_HEALTH || (spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && (spellEffect->EffectApplyAuraName == SPELL_AURA_SCHOOL_ABSORB || spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_HEAL))) @@ -1394,7 +1426,9 @@ bool ChatHandler::HandleDebugSpellCoefsCommand(char* args) { SpellEffectEntry const* spellEffect = spellEntry->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // Periodic Heals if (spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_HEAL) { diff --git a/src/game/MotionGenerators/FleeingMovementGenerator.cpp b/src/game/MotionGenerators/FleeingMovementGenerator.cpp index 678a2c4dd..7d19bfbaa 100644 --- a/src/game/MotionGenerators/FleeingMovementGenerator.cpp +++ b/src/game/MotionGenerators/FleeingMovementGenerator.cpp @@ -146,7 +146,9 @@ void FleeingMovementGenerator::Initialize(T& owner) owner.StopMoving(); if (owner.GetTypeId() == TYPEID_UNIT) + { owner.SetTargetGuid(ObjectGuid()); + } _setTargetLocation(owner); } diff --git a/src/game/MotionGenerators/MotionMaster.cpp b/src/game/MotionGenerators/MotionMaster.cpp index c0423e4cf..39d4e92cb 100644 --- a/src/game/MotionGenerators/MotionMaster.cpp +++ b/src/game/MotionGenerators/MotionMaster.cpp @@ -62,7 +62,9 @@ void MotionMaster::Initialize() push(movement == NULL ? &si_idleMovement : movement); top()->Initialize(*m_owner); if (top()->GetMovementGeneratorType() == WAYPOINT_MOTION_TYPE) + { (static_cast*>(top()))->InitializeWaypointPath(*((Creature*)(m_owner)), 0, PATH_NO_PATH, 0, 0); + } } else { diff --git a/src/game/MotionGenerators/PathFinder.cpp b/src/game/MotionGenerators/PathFinder.cpp index 5c6d60c5f..adf580a88 100644 --- a/src/game/MotionGenerators/PathFinder.cpp +++ b/src/game/MotionGenerators/PathFinder.cpp @@ -101,7 +101,9 @@ dtPolyRef PathFinder::getPathPolyByPosition(const dtPolyRef* polyPath, uint32 po float closestPoint[VERTEX_SIZE]; dtStatus dtResult = m_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint, NULL); if (dtStatusFailed(dtResult)) + { continue; + } float d = dtVdist2DSqr(point, closestPoint); if (d < minDist2d) @@ -187,7 +189,9 @@ void PathFinder::BuildPolyPath(const Vector3& startPos, const Vector3& endPos) // Check for swimming or flying shortcut if ((startPoly == INVALID_POLYREF && m_sourceUnit->GetTerrain()->IsUnderWater(startPos.x, startPos.y, startPos.z)) || (endPoly == INVALID_POLYREF && m_sourceUnit->GetTerrain()->IsUnderWater(endPos.x, endPos.y, endPos.z))) - { m_type = ((Creature*)m_sourceUnit)->CanSwim() ? PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH) : PATHFIND_NOPATH; } + { + m_type = ((Creature*)m_sourceUnit)->CanSwim() ? PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH) : PATHFIND_NOPATH; + } else { m_type = ((Creature*)m_sourceUnit)->CanFly() ? PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH) : PATHFIND_NOPATH; @@ -517,11 +521,15 @@ void PathFinder::createFilter() { Creature* creature = (Creature*)m_sourceUnit; if (creature->CanWalk()) - { includeFlags |= NAV_GROUND; } // walk + { + includeFlags |= NAV_GROUND; // walk + } // creatures don't take environmental damage if (creature->CanSwim()) - { includeFlags |= (NAV_WATER | NAV_MAGMA | NAV_SLIME); } // swim + { + includeFlags |= (NAV_WATER | NAV_MAGMA | NAV_SLIME); // swim + } } else if (m_sourceUnit->GetTypeId() == TYPEID_PLAYER) { @@ -658,7 +666,9 @@ bool PathFinder::getSteerTarget(const float* startPos, const float* endPos, // Stop at Off-Mesh link or when point is further than slop away. if ((steerPathFlags[ns] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) || !inRangeYZX(&steerPath[ns * VERTEX_SIZE], startPos, minTargetDist, 1000.0f)) - { break; } + { + break; + } ++ns; } // Failed to find good point to steer to. diff --git a/src/game/MotionGenerators/RandomMovementGenerator.cpp b/src/game/MotionGenerators/RandomMovementGenerator.cpp index 2a2759812..f95ca5d01 100644 --- a/src/game/MotionGenerators/RandomMovementGenerator.cpp +++ b/src/game/MotionGenerators/RandomMovementGenerator.cpp @@ -61,12 +61,18 @@ void RandomMovementGenerator::_setRandomLocation(Creature& creature) init.SetWalk(true); init.Launch(); if (roll_chance_i(MOVEMENT_RANDOM_MMGEN_CHANCE_NO_BREAK)) + { i_nextMoveTime.Reset(50); + } else + { i_nextMoveTime.Reset(urand(3000, 10000)); // Keep a short wait time + } } else + { i_nextMoveTime.Reset(50); // Retry later + } return; } diff --git a/src/game/MotionGenerators/WaypointMovementGenerator.cpp b/src/game/MotionGenerators/WaypointMovementGenerator.cpp index c6508dba5..ee6b4757b 100644 --- a/src/game/MotionGenerators/WaypointMovementGenerator.cpp +++ b/src/game/MotionGenerators/WaypointMovementGenerator.cpp @@ -43,10 +43,14 @@ void WaypointMovementGenerator::LoadPath(Creature& creature, int32 pat DETAIL_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "LoadPath: loading waypoint path for %s", creature.GetGuidStr().c_str()); if (!overwriteEntry) + { overwriteEntry = creature.GetEntry(); + } if (wpOrigin == PATH_NO_PATH && pathId == 0) + { i_path = sWaypointMgr.GetDefaultPath(overwriteEntry, creature.GetGUIDLow(), &m_PathOrigin); + } else { m_PathOrigin = wpOrigin == PATH_NO_PATH ? PATH_FROM_ENTRY : wpOrigin; @@ -58,9 +62,13 @@ void WaypointMovementGenerator::LoadPath(Creature& creature, int32 pat if (!i_path) { if (m_PathOrigin == PATH_FROM_EXTERNAL) + { sLog.outErrorScriptLib("WaypointMovementGenerator::LoadPath: %s doesn't have waypoint path %i", creature.GetGuidStr().c_str(), pathId); + } else + { sLog.outErrorDb("WaypointMovementGenerator::LoadPath: %s doesn't have waypoint path %i", creature.GetGuidStr().c_str(), pathId); + } return; } @@ -186,7 +194,9 @@ void WaypointMovementGenerator::OnArrived(Creature& creature) { uint32 type = WAYPOINT_MOTION_TYPE; if (m_PathOrigin == PATH_FROM_EXTERNAL && m_pathId > 0) + { type = EXTERNAL_WAYPOINT_MOVE + m_pathId; + } creature.AI()->MovementInform(type, i_currentNode); } @@ -237,9 +247,13 @@ void WaypointMovementGenerator::StartMove(Creature& creature) if (creature.AI() && m_PathOrigin == PATH_FROM_EXTERNAL && m_pathId > 0) { if (!reachedLast) + { creature.AI()->MovementInform(EXTERNAL_WAYPOINT_MOVE_START + m_pathId, currPoint->first); + } else + { creature.AI()->MovementInform(EXTERNAL_WAYPOINT_FINISHED_LAST + m_pathId, currPoint->first); + } if (creature.IsDead() || !creature.IsInWorld()) // Might have happened with above calls { @@ -345,7 +359,9 @@ bool WaypointMovementGenerator::GetResetPosition(Creature&, float& x, z = curWP->z; if (curWP->orientation != 100) + { o = curWP->orientation; + } else // Calculate the resulting angle based on positions between previous and current waypoint { WaypointNode const* prevWP; @@ -355,7 +371,9 @@ bool WaypointMovementGenerator::GetResetPosition(Creature&, float& x, prevWP = &(lastPoint->second); } else // Take the last waypoint (crbegin()) as previous + { prevWP = &(i_path->rbegin()->second); + } float dx = x - prevWP->x; float dy = y - prevWP->y; diff --git a/src/game/Object/ArenaTeam.cpp b/src/game/Object/ArenaTeam.cpp index 77cb27f50..009965af8 100644 --- a/src/game/Object/ArenaTeam.cpp +++ b/src/game/Object/ArenaTeam.cpp @@ -32,11 +32,17 @@ void ArenaTeamMember::ModifyPersonalRating(Player* plr, int32 mod, uint32 slot) { if (int32(personal_rating) + mod < 0) + { personal_rating = 0; + } else + { personal_rating += mod; + } if (plr) + { plr->SetArenaTeamInfoField(slot, ARENA_TEAM_PERSONAL_RATING, personal_rating); + } } ArenaTeam::ArenaTeam() @@ -56,12 +62,18 @@ ArenaTeam::ArenaTeam() if (conf_value < 0) // -1 = select by season id { if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6) + { m_stats.rating = 0; + } else + { m_stats.rating = 1500; + } } else + { m_stats.rating = uint32(conf_value); + } m_stats.wins_week = 0; m_stats.wins_season = 0; @@ -171,9 +183,13 @@ bool ArenaTeam::AddMember(ObjectGuid playerGuid) if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6) { if (m_stats.rating < 1000) + { newmember.personal_rating = 0; + } else + { newmember.personal_rating = 1000; + } } else { @@ -181,7 +197,9 @@ bool ArenaTeam::AddMember(ObjectGuid playerGuid) } } else + { newmember.personal_rating = uint32(conf_value); + } m_members.push_back(newmember); @@ -195,7 +213,9 @@ bool ArenaTeam::AddMember(ObjectGuid playerGuid) // hide promote/remove buttons if (m_CaptainGuid != playerGuid) + { pl->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1); + } } return true; } @@ -249,7 +269,9 @@ bool ArenaTeam::LoadMembersFromDB(QueryResult* arenaTeamMembersResult) Field* fields = arenaTeamMembersResult->Fetch(); // prevent crash if db records are broken, when all members in result are already processed and current team hasn't got any members if (!fields) + { break; + } uint32 arenaTeamId = fields[0].GetUInt32(); if (arenaTeamId < m_TeamId) { @@ -288,7 +310,9 @@ bool ArenaTeam::LoadMembersFromDB(QueryResult* arenaTeamMembersResult) } if (newmember.guid == GetCaptainGuid()) + { captainPresentInTeam = true; + } m_members.push_back(newmember); } @@ -309,7 +333,9 @@ void ArenaTeam::SetCaptain(ObjectGuid guid) // disable remove/promote buttons Player* oldcaptain = sObjectMgr.GetPlayer(GetCaptainGuid()); if (oldcaptain) + { oldcaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1); + } // set new captain m_CaptainGuid = guid; @@ -319,7 +345,9 @@ void ArenaTeam::SetCaptain(ObjectGuid guid) // enable remove/promote buttons if (Player* newcaptain = sObjectMgr.GetPlayer(guid)) + { newcaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 0); + } } void ArenaTeam::DelMember(ObjectGuid guid) @@ -441,7 +469,9 @@ void ArenaTeam::NotifyStatsChanged() { Player* plr = sObjectMgr.GetPlayer(itr->guid); if (plr) + { Stats(plr->GetSession()); + } } } @@ -516,7 +546,9 @@ void ArenaTeam::BroadcastPacket(WorldPacket* packet) { Player* player = sObjectMgr.GetPlayer(itr->guid); if (player) + { player->GetSession()->SendPacket(packet); + } } } @@ -540,10 +572,14 @@ void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, ObjectGuid guid, char cons data << str2; } else if (str1) + { data << str1; + } if (guid) + { data << ObjectGuid(guid); + } BroadcastPacket(&data); @@ -589,18 +625,26 @@ uint32 ArenaTeam::GetPoints(uint32 MemberRating) { // As of Season 6 and later, all teams below 1500 rating will earn points as if they were a 1500 rated team if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6) + { rating = 1500; + } points = (float)rating * 0.22f + 14.0f; } else + { points = 1511.26f / (1.0f + 1639.28f * exp(-0.00412f * (float)rating)); + } // type penalties for <5v5 teams if (m_Type == ARENA_TYPE_2v2) + { points *= 0.76f; + } else if (m_Type == ARENA_TYPE_3v3) + { points *= 0.88f; + } return (uint32) points; } @@ -623,16 +667,22 @@ float ArenaTeam::GetChanceAgainst(uint32 own_rating, uint32 enemy_rating) if (sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID) >= 6) if (enemy_rating < 1000) + { enemy_rating = 1000; + } return 1.0f / (1.0f + exp(log(10.0f) * (float)((float)enemy_rating - (float)own_rating) / 400.0f)); } void ArenaTeam::FinishGame(int32 mod) { if (int32(m_stats.rating) + mod < 0) + { m_stats.rating = 0; + } else + { m_stats.rating += mod; + } m_stats.games_week += 1; m_stats.games_season += 1; @@ -642,7 +692,9 @@ void ArenaTeam::FinishGame(int32 mod) for (; i != sObjectMgr.GetArenaTeamMapEnd(); ++i) { if (i->second->GetType() == this->m_Type && i->second->GetStats().rating > m_stats.rating) + { ++m_stats.rank; + } } } @@ -715,9 +767,13 @@ void ArenaTeam::OfflineMemberLost(ObjectGuid guid, uint32 againstRating) // calculate the rating modification (ELO system with k=32 or k=48 if rating<1000) int32 mod = (int32)ceil(K * (0.0f - chance)); if (int32(itr->personal_rating) + mod < 0) + { itr->personal_rating = 0; + } else + { itr->personal_rating += mod; + } // update personal played stats itr->games_week += 1; itr->games_season += 1; @@ -768,7 +824,9 @@ void ArenaTeam::UpdateArenaPointsHelper(std::map& PlayerPoints) // the player participated in enough games, update his points uint32 points_to_add = 0; if (itr->games_week >= min_plays) + { points_to_add = GetPoints(itr->personal_rating); + } // OBSOLETE : CharacterDatabase.PExecute("UPDATE arena_team_member SET points_to_add = '%u' WHERE arenateamid = '%u' AND guid = '%u'", points_to_add, m_TeamId, itr->guid); std::map::iterator plr_itr = PlayerPoints.find(itr->guid.GetCounter()); @@ -776,10 +834,14 @@ void ArenaTeam::UpdateArenaPointsHelper(std::map& PlayerPoints) { // check if there is already more points if (plr_itr->second < points_to_add) + { PlayerPoints[itr->guid.GetCounter()] = points_to_add; + } } else + { PlayerPoints[itr->guid.GetCounter()] = points_to_add; + } } } diff --git a/src/game/Object/ArenaTeam.h b/src/game/Object/ArenaTeam.h index a29c66cf7..c2bbb29fc 100644 --- a/src/game/Object/ArenaTeam.h +++ b/src/game/Object/ArenaTeam.h @@ -165,7 +165,9 @@ class ArenaTeam { for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->guid == guid) + { return &(*itr); + } return NULL; } @@ -174,7 +176,9 @@ class ArenaTeam { for (MemberList::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->name == name) + { return &(*itr); + } return NULL; } diff --git a/src/game/Object/AuctionHouseMgr.cpp b/src/game/Object/AuctionHouseMgr.cpp index 3c8153b57..d339da31a 100644 --- a/src/game/Object/AuctionHouseMgr.cpp +++ b/src/game/Object/AuctionHouseMgr.cpp @@ -141,7 +141,9 @@ void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry* auction) { std::string owner_name; if (auction_owner) + { owner_name = auction_owner->GetName(); + } else if (ownerGuid && !sObjectMgr.GetPlayerNameByGUID(ownerGuid, owner_name)) { owner_name = sObjectMgr.GetMangosStringForDBCLocale(LANG_UNKNOWN); @@ -159,7 +161,9 @@ void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry* auction) } if (auction_owner) + { auction_owner->GetSession()->SendAuctionOwnerNotification(auction); + } // receiver exist if (bidder || bidder_accId) @@ -272,7 +276,9 @@ void AuctionHouseMgr::SendAuctionExpiredMail(AuctionEntry* auction) subject << auction->itemTemplate << ":" << auction->itemRandomPropertyId << ":" << AUCTION_EXPIRED << ":" << auction->Id << ":" << auction->itemCount; if (owner) + { owner->GetSession()->SendAuctionOwnerNotification(auction); + } RemoveAItem(auction->itemGuidLow); // we have to remove the item, before we delete it !! auction->itemGuidLow = 0; @@ -408,7 +414,9 @@ void AuctionHouseMgr::LoadAuctions() { std::string plName; if (!sObjectMgr.GetPlayerNameByGUID(ObjectGuid(HIGHGUID_PLAYER, auction->owner), plName)) + { plName = sObjectMgr.GetMangosStringForDBCLocale(LANG_UNKNOWN); + } Utf8toWStr(plName, plWName); } @@ -426,7 +434,9 @@ void AuctionHouseMgr::LoadAuctions() auction->auctionHouseEntry = NULL; // init later if (auction->moneyDeliveryTime) + { auction->itemGuidLow = 0; // must be 0 if auction delivery pending + } else { // check if sold item exists for guid @@ -567,13 +577,21 @@ AuctionHouseEntry const* AuctionHouseMgr::GetAuctionHouseEntry(Unit* unit) { FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId); if (!u_entry) - { houseid = 7; } // goblin auction house + { + houseid = 7; // goblin auction house + } else if (u_entry->ourMask & FACTION_MASK_ALLIANCE) - { houseid = 1; } // human auction house + { + houseid = 1; // human auction house + } else if (u_entry->ourMask & FACTION_MASK_HORDE) - { houseid = 6; } // orc auction house + { + houseid = 6; // orc auction house + } else - { houseid = 7; } // goblin auction house + { + houseid = 7; // goblin auction house + } break; } } @@ -625,7 +643,9 @@ void AuctionHouseObject::Update() { ///- perform the transaction if there was bidder if (itr->second->bid) + { itr->second->AuctionBidWinning(); + } ///- cancel the auction if there was no bidder and clear the auction else { @@ -649,7 +669,9 @@ void AuctionHouseObject::BuildListBidderItems(WorldPacket& data, Player* player, { AuctionEntry* Aentry = itr->second; if (Aentry->moneyDeliveryTime) // skip pending sell auctions + { continue; + } if (Aentry->bidder == player->GetGUIDLow()) { if (itr->second->BuildAuctionInfo(data)) @@ -667,7 +689,9 @@ void AuctionHouseObject::BuildListOwnerItems(WorldPacket& data, Player* player, { AuctionEntry* Aentry = itr->second; if (Aentry->moneyDeliveryTime) // skip pending sell auctions + { continue; + } if (Aentry->owner == player->GetGUIDLow()) { if (Aentry->BuildAuctionInfo(data)) @@ -879,7 +903,9 @@ bool AuctionSorter::operator()(const AuctionEntry* auc1, const AuctionEntry* auc int res = auc1->CompareAuctionEntry(m_sort[i] & ~AUCTION_SORT_REVERSED, auc2, m_viewPlayer); // "equal" by used column if (res == 0) + { continue; + } // less/greater and normal/reversed ordered return (res < 0) == ((m_sort[i] & AUCTION_SORT_REVERSED) == 0); } @@ -896,7 +922,9 @@ void WorldSession::BuildListAuctionItems(std::vector const& aucti { AuctionEntry* Aentry = *itr; if (Aentry->moneyDeliveryTime) + { continue; + } Item* item = sAuctionMgr.GetAItem(Aentry->itemGuidLow); if (!item) { @@ -940,7 +968,9 @@ void WorldSession::BuildListAuctionItems(std::vector const& aucti if (usable != 0x00) { if (_player->CanUseItem(item) != EQUIP_ERR_OK) + { continue; + } if (proto->Class == ITEM_CLASS_RECIPE) { @@ -948,10 +978,14 @@ void WorldSession::BuildListAuctionItems(std::vector const& aucti { SpellEffectEntry const* spellEff = spell->GetSpellEffect(EFFECT_INDEX_0); if (!spellEff) + { continue; + } if (_player->HasSpell(spellEff->EffectTriggerSpell)) + { continue; + } } } } @@ -981,7 +1015,9 @@ void AuctionHouseObject::BuildListPendingSales(WorldPacket& data, Player* player { AuctionEntry* Aentry = itr->second; if (!Aentry->moneyDeliveryTime) // skip not pending auctions + { continue; + } if (Aentry->owner == player->GetGUIDLow()) { std::ostringstream str1; @@ -1016,7 +1052,9 @@ AuctionEntry* AuctionHouseObject::AddAuction(AuctionHouseEntry const* auctionHou AH->owner = pl ? pl->GetGUIDLow() : 0; if (pl) + { Utf8toWStr(pl->GetName(), AH->ownerName); + } AH->startbid = bid; AH->bidder = 0; @@ -1142,7 +1180,9 @@ bool AuctionEntry::UpdateBid(uint64 newbid, Player* newbidder /*=NULL*/) else { if (newbidder) + { newbidder->ModifyMoney(-int64(newbid)); + } if (bidder) // return money to old bidder if present { @@ -1156,7 +1196,9 @@ bool AuctionEntry::UpdateBid(uint64 newbid, Player* newbidder /*=NULL*/) if ((newbid < buyout) || (buyout == 0)) // bid { if (auction_owner) + { auction_owner->GetSession()->SendAuctionOwnerNotification(this); + } // after this update we should save player's money ... CharacterDatabase.BeginTransaction(); diff --git a/src/game/Object/Bag.cpp b/src/game/Object/Bag.cpp index 750c3b2c8..1d79401dc 100644 --- a/src/game/Object/Bag.cpp +++ b/src/game/Object/Bag.cpp @@ -236,7 +236,9 @@ uint32 Bag::GetItemCount(uint32 item, Item* eItem) const for (uint32 i = 0; i < GetBagSize(); ++i) if (m_bagslot[i]) if (m_bagslot[i] != eItem && m_bagslot[i]->GetProto()->Socket[0].Color) + { count += m_bagslot[i]->GetGemCountWithID(item); + } return count; } @@ -248,7 +250,9 @@ uint32 Bag::GetItemCountWithLimitCategory(uint32 limitCategory, Item* eItem) con for (uint32 i = 0; i < GetBagSize(); ++i) if (m_bagslot[i]) if (m_bagslot[i] != eItem && m_bagslot[i]->GetProto()->ItemLimitCategory == limitCategory) + { count += m_bagslot[i]->GetCount(); + } return count; } diff --git a/src/game/Object/Calendar.cpp b/src/game/Object/Calendar.cpp index cf0a14980..948f26405 100644 --- a/src/game/Object/Calendar.cpp +++ b/src/game/Object/Calendar.cpp @@ -80,7 +80,9 @@ void CalendarEvent::RemoveInviteByItr(CalendarInviteMap::iterator inviteItr) MANGOS_ASSERT(inviteItr != m_Invitee.end()); // iterator must be valid if (!IsGuildEvent()) + { sCalendarMgr.SendCalendarEventInviteRemoveAlert(sObjectMgr.GetPlayer(inviteItr->second->InviteeGuid), this, CALENDAR_STATUS_REMOVED); + } sCalendarMgr.SendCalendarEventInviteRemove(inviteItr->second, Flags); @@ -97,9 +99,13 @@ void CalendarEvent::RemoveInviteByGuid(ObjectGuid const& playerGuid) while (itr != m_Invitee.end()) { if (itr->second->InviteeGuid == playerGuid) + { RemoveInviteByItr(itr++); + } else + { ++itr; + } } } @@ -175,7 +181,9 @@ void CalendarEvent::RemoveAllInvite(ObjectGuid const& removerGuid) while (itr != m_Invitee.end()) { if (removerGuid != itr->second->InviteeGuid) + { draft.SendMailTo(MailReceiver(itr->second->InviteeGuid), this, MAIL_CHECK_MASK_COPIED); + } RemoveInviteByItr(itr++); } } @@ -189,7 +197,9 @@ CalendarInvite::CalendarInvite(CalendarEvent* event, uint64 inviteId, ObjectGuid { // only for pre invite case if (!event) + { InviteId = 0; + } } ////////////////////////////////////////////////////////////////////////// @@ -202,9 +212,13 @@ void CalendarMgr::GetPlayerEventsList(ObjectGuid const& guid, CalendarEventsList uint32 guildId = 0; Player* player = sObjectMgr.GetPlayer(guid); if (player) + { guildId = player->GetGuildId(); + } else + { guildId = Player::GetGuildIdFromDB(guid); + } for (CalendarEventStore::iterator itr = m_EventStore.begin(); itr != m_EventStore.end(); ++itr) { @@ -219,7 +233,9 @@ void CalendarMgr::GetPlayerEventsList(ObjectGuid const& guid, CalendarEventsList // add all event where player is invited if (event->GetInviteByGuid(guid)) + { calEventList.push_back(event); + } } } @@ -231,7 +247,9 @@ void CalendarMgr::GetPlayerInvitesList(ObjectGuid const& guid, CalendarInvitesLi CalendarEvent* event = &itr->second; if (event->IsGuildAnnouncement()) + { continue; + } CalendarInviteMap const* cInvMap = event->GetInviteMap(); CalendarInviteMap::const_iterator ci_itr = cInvMap->begin(); @@ -391,10 +409,14 @@ CalendarInvite* CalendarMgr::AddInvite(CalendarEvent* event, ObjectGuid const& s CalendarInvite* invite = new CalendarInvite(event, GetNewInviteId(), senderGuid, inviteeGuid, statusTime, status, rank, text); if (!event->IsGuildAnnouncement()) + { SendCalendarEventInvite(invite); + } if (!event->IsGuildEvent() || invite->InviteeGuid == event->CreatorGuid) + { SendCalendarEventInviteAlert(invite); + } if (event->IsGuildAnnouncement()) { @@ -457,16 +479,22 @@ uint32 CalendarMgr::GetPlayerNumPending(ObjectGuid const& guid) { // pass all passed events if (event->EventTime < currTime) + { continue; + } // pass all locked events if (event->Flags & CALENDAR_FLAG_INVITES_LOCKED) + { continue; + } } // add only invite that require some action if ((*itr)->Status == CALENDAR_STATUS_INVITED || (*itr)->Status == CALENDAR_STATUS_TENTATIVE || (*itr)->Status == CALENDAR_STATUS_NOT_SIGNED_UP) + { ++pendingNum; + } } return pendingNum; @@ -492,7 +520,9 @@ void CalendarMgr::CopyEvent(uint64 eventId, time_t newTime, ObjectGuid const& gu } if (newEvent->IsGuildAnnouncement()) + { AddInvite(newEvent, guid, guid, CALENDAR_STATUS_CONFIRMED, CALENDAR_RANK_OWNER, "", time(NULL)); + } else { // copy all invitees, set new owner as the one who make the copy, set invitees status to invited @@ -511,7 +541,9 @@ void CalendarMgr::CopyEvent(uint64 eventId, time_t newTime, ObjectGuid const& gu CalendarModerationRank rank = CALENDAR_RANK_PLAYER; // copy moderator rank if (invite->Rank == CALENDAR_RANK_MODERATOR) + { rank = CALENDAR_RANK_MODERATOR; + } AddInvite(newEvent, guid, invite->InviteeGuid, CALENDAR_STATUS_INVITED, rank, "", time(NULL)); } @@ -641,7 +673,9 @@ void CalendarMgr::LoadCalendarsFromDB() sLog.outString(">> calendar_invites table is empty, cleared calendar_events table!"); } else + { sLog.outString(">> calendar_invite table is empty!"); + } } else { @@ -732,7 +766,9 @@ bool CalendarMgr::CanAddInviteTo(ObjectGuid const& guid) CalendarEvent* event = &itr->second; if (event->IsGuildAnnouncement()) + { continue; + } CalendarInviteMap const* cInvMap = event->GetInviteMap(); CalendarInviteMap::const_iterator ci_itr = cInvMap->begin(); diff --git a/src/game/Object/Creature.cpp b/src/game/Object/Creature.cpp index 48e16e5e3..d626c89aa 100644 --- a/src/game/Object/Creature.cpp +++ b/src/game/Object/Creature.cpp @@ -94,7 +94,9 @@ bool VendorItemData::RemoveItem(uint32 item_id, uint8 type) found = true; } else + { ++i; + } } return found; @@ -339,7 +341,9 @@ bool Creature::InitEntry(uint32 Entry, CreatureData const* data /*=NULL*/, GameE { cinfo = ObjectMgr::GetCreatureTemplate(normalInfo->DifficultyEntry[diff - 1]); if (cinfo) + { break; // template found + } // check and reported at startup, so just ignore (restore normalInfo) cinfo = normalInfo; @@ -410,7 +414,9 @@ bool Creature::InitEntry(uint32 Entry, CreatureData const* data /*=NULL*/, GameE LoadEquipment(normalInfo->EquipmentTemplateId); // use default from normal template if diff does not have any } else + { LoadEquipment(cinfo->EquipmentTemplateId); // else use from diff template + } } else if (data && data->equipmentId != -1) { @@ -458,7 +464,9 @@ bool Creature::UpdateEntry(uint32 Entry, Team team, const CreatureData* data /*= SetHealthPercent(healthPercent); } else + { SelectLevel(); + } if (team == HORDE) { @@ -685,7 +693,9 @@ void Creature::Update(uint32 update_diff, uint32 diff) break; } else + { m_corpseDecayTimer -= update_diff; + } if (m_groupLootId) // Loot is stopped already if corpse got removed. { @@ -720,7 +730,9 @@ void Creature::Update(uint32 update_diff, uint32 diff) break; } else + { m_corpseDecayTimer -= update_diff; + } } Unit::Update(update_diff, diff); @@ -1431,7 +1443,9 @@ void Creature::SelectLevel(uint32 forcedLevel /*= USE_DEFAULT_DATABASE_LEVEL*/) uint32 const maxlevel = cinfo->MaxLevel; if (level == USE_DEFAULT_DATABASE_LEVEL) + { level = minlevel == maxlevel ? minlevel : urand(minlevel, maxlevel); + } SetLevel(level); @@ -1480,7 +1494,9 @@ void Creature::SelectLevel(uint32 forcedLevel /*= USE_DEFAULT_DATABASE_LEVEL*/) health *= _GetHealthMod(rank); // Apply custom config settting if (health < 1) + { health = 1; + } ////////////////////////////////////////////////////////////////////////// // Set values @@ -1512,11 +1528,15 @@ void Creature::SelectLevel(uint32 forcedLevel /*= USE_DEFAULT_DATABASE_LEVEL*/) // For non regenerating powers set 0 if ((i == POWER_ENERGY || i == POWER_MANA) && !IsRegeneratingPower()) + { value = 0; + } // Mana requires an extra field to be set if (i == POWER_MANA) + { SetCreateMana(value); + } SetMaxPower(Powers(i), maxValue); SetPower(Powers(i), value); @@ -2160,9 +2180,13 @@ void Creature::SetLootStatus(CreatureLootStatus status) { case CREATURE_LOOT_STATUS_LOOTED: if (m_creatureInfo->SkinningLootId) + { SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); + } else + { RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); + } break; case CREATURE_LOOT_STATUS_SKINNED: m_corpseDecayTimer = 0; // remove corpse at next update @@ -2229,7 +2253,9 @@ SpellEntry const* Creature::ReachWithSpellAttack(Unit* pVictim) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if( (spellEffect->Effect == SPELL_EFFECT_SCHOOL_DAMAGE ) || (spellEffect->Effect == SPELL_EFFECT_INSTAKILL) || (spellEffect->Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) || @@ -2541,7 +2567,9 @@ void Creature::SaveRespawnTime() GetMap()->GetPersistentState()->SaveCreatureRespawnTime(GetGUIDLow(), m_respawnTime); } else if (m_corpseDecayTimer > 0) // dead (corpse) + { GetMap()->GetPersistentState()->SaveCreatureRespawnTime(GetGUIDLow(), time(NULL) + m_respawnDelay + m_corpseDecayTimer / IN_MILLISECONDS); + } } bool Creature::IsOutOfThreatArea(Unit* pVictim) const @@ -2655,7 +2683,9 @@ bool Creature::LoadCreatureAddon(bool reload) } if (cainfo->splineFlags & SPLINEFLAG_FLYING) + { SetLevitate(true); + } if (cainfo->auras) { @@ -2998,12 +3028,18 @@ void Creature::AllLootRemovedFromCorpse() // spawntimesecs=3min: corpse decay after 1min // spawntimesecs=4hour: corpse decay after 1hour 20min if (sWorld.getConfig(CONFIG_FLOAT_RATE_CORPSE_DECAY_LOOTED) > 0.0f) + { corpseLootedDelay = (uint32)((m_corpseDelay * IN_MILLISECONDS) * sWorld.getConfig(CONFIG_FLOAT_RATE_CORPSE_DECAY_LOOTED)); + } else + { corpseLootedDelay = (m_respawnDelay * IN_MILLISECONDS) / 3; + } } else // corpse was skinned, corpse will despawn next update + { corpseLootedDelay = 0; + } // if m_respawnTime is not expired already if (m_respawnTime >= time(NULL)) @@ -3017,7 +3053,9 @@ void Creature::AllLootRemovedFromCorpse() { // if m_respawnDelay is relatively short and corpseDecayTimer is larger than corpseLootedDelay if (m_corpseDecayTimer > corpseLootedDelay) + { m_corpseDecayTimer = corpseLootedDelay; + } } } else diff --git a/src/game/Object/Creature.h b/src/game/Object/Creature.h index 7845e97ef..1b1e68e02 100644 --- a/src/game/Object/Creature.h +++ b/src/game/Object/Creature.h @@ -178,7 +178,9 @@ struct CreatureInfo return SKILL_ENGINEERING; } else - { return SKILL_SKINNING; } // normal case + { + return SKILL_SKINNING; // normal case + } } bool IsExotic() const diff --git a/src/game/Object/CreatureAI.cpp b/src/game/Object/CreatureAI.cpp index 3417e8aba..207716d38 100644 --- a/src/game/Object/CreatureAI.cpp +++ b/src/game/Object/CreatureAI.cpp @@ -148,7 +148,9 @@ CanCastResult CreatureAI::DoCastSpellIfCan(Unit* pTarget, uint32 uiSpell, uint32 // Creature should always stop before it will cast a non-instant spell if (GetSpellCastTime(pSpell)) + { pCaster->StopMoving(); + } // Creature should interrupt any current melee spell pCaster->InterruptSpell(CURRENT_MELEE_SPELL); @@ -206,7 +208,9 @@ void CreatureAI::HandleMovementOnAttackStart(Unit* victim) { MotionMaster* creatureMotion = m_creature->GetMotionMaster(); if (m_isCombatMovement) + { creatureMotion->MoveChase(victim, m_attackDistance, m_attackAngle); + } // TODO - adapt this to only stop OOC-MMGens when MotionMaster rewrite is finished else if (creatureMotion->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE || creatureMotion->GetCurrentMovementGeneratorType() == RANDOM_MOTION_TYPE) { diff --git a/src/game/Object/CreatureEventAI.cpp b/src/game/Object/CreatureEventAI.cpp index 7842a6423..2b407fd0c 100644 --- a/src/game/Object/CreatureEventAI.cpp +++ b/src/game/Object/CreatureEventAI.cpp @@ -814,7 +814,9 @@ void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 { SpellRangeEntry const* spellRange = sSpellRangeStore.LookupEntry(spellInfo->GetRangeIndex()); if (spellRange) + { m_LastSpellMaxRange = spellRange->maxRange; + } } } break; @@ -1024,7 +1026,9 @@ void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 ThreatList const& threatList = m_creature->GetThreatManager().getThreatList(); for (ThreatList::const_iterator i = threatList.begin(); i != threatList.end(); ++i) if (Player* temp = m_creature->GetMap()->GetPlayer((*i)->getUnitGuid())) + { temp->GroupEventHappens(action.quest_event_all.questId, m_creature); + } } else if (pActionInvoker && pActionInvoker->GetTypeId() == TYPEID_PLAYER) { @@ -1280,7 +1284,9 @@ void CreatureEventAI::ProcessAction(CreatureEventAI_Action const& action, uint32 case ACTION_T_DYNAMIC_MOVEMENT: { if ((!!action.dynamicMovement.state) == m_DynamicMovement) + { break; + } m_DynamicMovement = !!action.dynamicMovement.state; SetCombatMovement(!m_DynamicMovement, true); @@ -1330,7 +1336,9 @@ void CreatureEventAI::Reset() case EVENT_T_TIMER_OOC: { if (i->UpdateRepeatTimer(m_creature, event.timer.initialMin, event.timer.initialMax)) + { i->Enabled = true; + } break; } default: @@ -1467,7 +1475,9 @@ void CreatureEventAI::ReceiveAIEvent(AIEventType eventType, Creature* pSender, U { if (itr->Event.event_type == EVENT_T_RECEIVE_AI_EVENT && itr->Event.receiveAIEvent.eventType == eventType && (!itr->Event.receiveAIEvent.senderEntry || itr->Event.receiveAIEvent.senderEntry == pSender->GetEntry())) - { ProcessEvent(*itr, pInvoker, pSender); } + { + ProcessEvent(*itr, pInvoker, pSender); + } } } @@ -1612,18 +1622,26 @@ void CreatureEventAI::UpdateAI(const uint32 diff) { // Do not decrement timers if event cannot trigger in this phase if (!(i->Event.event_inverse_phase_mask & (1 << m_Phase))) + { i->Time -= m_EventDiff; + } } else + { i->Time = 0; + } } // Skip processing of events that have time remaining or are disabled if (!(i->Enabled) || i->Time) + { continue; + } if (IsTimerBasedEvent(i->Event.event_type)) + { ProcessEvent(*i); + } } m_EventDiff = 0; @@ -1645,16 +1663,24 @@ void CreatureEventAI::UpdateAI(const uint32 diff) if (m_creature->IsWithinLOSInMap(victim)) { if (m_LastSpellMaxRange && m_creature->IsInRange(victim, 0, (m_LastSpellMaxRange / 1.5f))) + { SetCombatMovement(false, true); + } else + { SetCombatMovement(true, true); + } } else + { SetCombatMovement(true, true); + } } else if (m_MeleeEnabled && m_creature->CanReachWithMeleeAttack(victim) && !(m_creature->GetCreatureInfo()->ExtraFlags & CREATURE_EXTRA_FLAG_NO_MELEE)) - { DoMeleeAttackIfReady(); } + { + DoMeleeAttackIfReady(); + } } } @@ -1845,7 +1871,9 @@ void CreatureEventAI::DamageTaken(Unit* dealer, uint32& damage) AIEventType sendEvent[HEALTH_STEPS] = { AI_EVENT_LOST_SOME_HEALTH, AI_EVENT_LOST_HEALTH, AI_EVENT_CRITICAL_HEALTH }; if (newHealthPercent > healthSteps[step]) - { return; } // Not reached the next mark + { + return; // Not reached the next mark + } // search for highest reached mark (with actual event attached) for (uint32 i = HEALTH_STEPS - 1; i > step; --i) diff --git a/src/game/Object/CreatureEventAIMgr.cpp b/src/game/Object/CreatureEventAIMgr.cpp index 45eea8408..998066793 100644 --- a/src/game/Object/CreatureEventAIMgr.cpp +++ b/src/game/Object/CreatureEventAIMgr.cpp @@ -212,7 +212,9 @@ void CreatureEventAIMgr::LoadCreatureEventAI_Summons(bool check_entry_use) delete result; if (check_entry_use) + { CheckUnusedAISummons(); + } sLog.outString(); sLog.outString(">> Loaded %u CreatureEventAI summon definitions", Count); @@ -249,7 +251,9 @@ void CreatureEventAIMgr::CheckUnusedAISummons() case ACTION_T_SUMMON_ID: { if (action.summon_id.spawnId) + { idx_set.erase(action.summon_id.spawnId); + } break; } default: break; @@ -729,7 +733,9 @@ void CreatureEventAIMgr::LoadCreatureEventAI_Scripts() { // output as debug for now, also because there's no general rule all spells have RecoveryTime if (temp.event_param3 < spell->RecoveryTime) + { DEBUG_FILTER_LOG(LOG_FILTER_AI_AND_MOVEGENSS, "CreatureEventAI: Event %u Action %u uses SpellID %u but cooldown is longer(%u) than minumum defined in event param3(%u).", i, j+1,action.cast.spellId, spell->RecoveryTime, temp.event_param3); + } } } */ @@ -757,12 +763,16 @@ void CreatureEventAIMgr::LoadCreatureEventAI_Scripts() if (action.cast.target == TARGET_T_ACTION_INVOKER && (IsSpellHaveEffect(spell, SPELL_EFFECT_QUEST_COMPLETE) || IsSpellHaveEffect(spell, SPELL_EFFECT_CREATE_RANDOM_ITEM) || IsSpellHaveEffect(spell, SPELL_EFFECT_DUMMY) || IsSpellHaveEffect(spell, SPELL_EFFECT_KILL_CREDIT_PERSONAL) || IsSpellHaveEffect(spell, SPELL_EFFECT_KILL_CREDIT_GROUP))) - { sLog.outErrorEventAI("Event %u Action %u has TARGET_T_ACTION_INVOKER(%u) target type, but should have TARGET_T_ACTION_INVOKER_OWNER(%u).", i, j + 1, TARGET_T_ACTION_INVOKER, TARGET_T_ACTION_INVOKER_OWNER); } + { + sLog.outErrorEventAI("Event %u Action %u has TARGET_T_ACTION_INVOKER(%u) target type, but should have TARGET_T_ACTION_INVOKER_OWNER(%u).", i, j + 1, TARGET_T_ACTION_INVOKER, TARGET_T_ACTION_INVOKER_OWNER); + } // Spell that should only target players, but could get any if (spell->HasAttribute(SPELL_ATTR_EX3_TARGET_ONLY_PLAYER) && (action.cast.target == TARGET_T_ACTION_INVOKER || action.cast.target == TARGET_T_HOSTILE_RANDOM || action.cast.target == TARGET_T_HOSTILE_RANDOM_NOT_TOP)) - { sLog.outErrorEventAI("Event %u Action %u uses Target type %u for a spell (%u) that should only target players. This could be wrong.", i, j + 1, action.cast.target, action.cast.spellId); } + { + sLog.outErrorEventAI("Event %u Action %u uses Target type %u for a spell (%u) that should only target players. This could be wrong.", i, j + 1, action.cast.target, action.cast.spellId); + } } break; } @@ -920,7 +930,9 @@ void CreatureEventAIMgr::LoadCreatureEventAI_Scripts() break; case ACTION_T_SET_INST_DATA: if (!(temp.event_flags & EFLAG_DIFFICULTY_ALL)) + { sLog.outErrorEventAI("Event %u Action %u. Cannot set instance data without difficulty event flags.", i, j + 1); + } if (action.set_inst_data.value > 4/*SPECIAL*/) { sLog.outErrorEventAI("Event %u Action %u attempts to set instance data above encounter state 4. Custom case?", i, j + 1); @@ -928,7 +940,9 @@ void CreatureEventAIMgr::LoadCreatureEventAI_Scripts() break; case ACTION_T_SET_INST_DATA64: if (!(temp.event_flags & EFLAG_DIFFICULTY_ALL)) + { sLog.outErrorEventAI("Event %u Action %u. Cannot set instance data without difficulty event flags.", i, j + 1); + } IsValidTargetType(temp.event_type, action.type, action.set_inst_data64.target, i, j + 1); break; case ACTION_T_UPDATE_TEMPLATE: diff --git a/src/game/Object/DynamicObject.cpp b/src/game/Object/DynamicObject.cpp index bd9e9d566..4ab94b820 100644 --- a/src/game/Object/DynamicObject.cpp +++ b/src/game/Object/DynamicObject.cpp @@ -185,7 +185,9 @@ void DynamicObject::Delay(int32 delaytime) { SpellEffectEntry const* effect = holder->GetSpellProto()->GetSpellEffect(SpellEffectIndex(i)); if(!effect) + { continue; + } if ((effect->Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA || effect->Effect == SPELL_EFFECT_ADD_FARSIGHT) && holder->m_auras[i]) { foundAura = true; diff --git a/src/game/Object/Formulas.h b/src/game/Object/Formulas.h index f92f4a15e..f81b2d580 100644 --- a/src/game/Object/Formulas.h +++ b/src/game/Object/Formulas.h @@ -188,7 +188,9 @@ namespace MaNGOS if (u->GetTypeId() == TYPEID_UNIT && ( ((Creature*)u)->IsTotem() || ((Creature*)u)->IsPet() || (((Creature*)u)->GetCreatureInfo()->ExtraFlags & CREATURE_EXTRA_FLAG_NO_XP_AT_KILL))) - { return 0; } + { + return 0; + } uint32 xp_gain = BaseGain(pl->getLevel(), u->getLevel(), GetContentLevelsForMapAndZone(pl->GetMapId(), pl->GetZoneId())); if (xp_gain == 0) diff --git a/src/game/Object/GameObject.cpp b/src/game/Object/GameObject.cpp index 87e2d2104..001ad77a4 100644 --- a/src/game/Object/GameObject.cpp +++ b/src/game/Object/GameObject.cpp @@ -114,7 +114,9 @@ void GameObject::AddToWorld() #ifdef ENABLE_ELUNA if (!inWorld) + { sEluna->OnAddToWorld(this); + } #endif /* ENABLE_ELUNA */ } @@ -179,9 +181,13 @@ bool GameObject::Create(uint32 guidlow, uint32 name_id, Map* map, uint32 phaseMa } if (goinfo->type == GAMEOBJECT_TYPE_TRANSPORT) + { Object::_Create(guidlow, 0, HIGHGUID_MO_TRANSPORT); + } else + { Object::_Create(guidlow, goinfo->id, HIGHGUID_GAMEOBJECT); + } m_goInfo = goinfo; @@ -205,9 +211,13 @@ bool GameObject::Create(uint32 guidlow, uint32 name_id, Map* map, uint32 phaseMa SetWorldRotation(rotation.x, rotation.y, rotation.z, rotation.w); // For most of gameobjects is (0, 0, 0, 1) quaternion, only some transports has not standart rotation if (const GameObjectDataAddon* addon = sGameObjectDataAddonStorage.LookupEntry(guidlow)) + { SetTransportPathRotation(addon->path_rotation); + } else + { SetTransportPathRotation(QuaternionData(0, 0, 0, 1)); + } SetUInt32Value(GAMEOBJECT_FACTION, goinfo->faction); SetUInt32Value(GAMEOBJECT_FLAGS, goinfo->flags); @@ -238,7 +248,9 @@ bool GameObject::Create(uint32 guidlow, uint32 name_id, Map* map, uint32 phaseMa case GAMEOBJECT_TYPE_TRANSPORT: SetUInt32Value(GAMEOBJECT_LEVEL, WorldTimer::getMSTime()); if (goinfo->transport.startOpen) + { SetGoState(GO_STATE_ACTIVE); + } break; } @@ -450,9 +462,13 @@ void GameObject::Update(uint32 update_diff, uint32 p_time) if (m_groupLootId) { if (m_groupLootTimer <= update_diff) + { StopGroupLoot(); + } else + { m_groupLootTimer -= update_diff; + } } break; case GAMEOBJECT_TYPE_GOOBER: @@ -902,7 +918,9 @@ bool GameObject::isVisibleForInState(Player const* u, WorldObject const* viewPoi return true; } else + { trapNotVisible = true; + } } // only rogue have skill for traps detection @@ -975,7 +993,9 @@ bool GameObject::ActivateToQuest(Player* pTarget) const { if ((pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_INCOMPLETE || pTarget->GetQuestStatus(itr->second) == QUEST_STATUS_COMPLETE) && !pTarget->GetQuestRewardStatus(itr->second)) - { return true; } + { + return true; + } } break; @@ -1304,7 +1324,9 @@ void GameObject::Use(Unit* user) // FIXME: when GO casting will be implemented trap must cast spell to target if ((spellId = goInfo->trap.spellId)) + { caster->CastSpell(user, spellId, true, NULL, NULL, GetObjectGuid()); + } // use template cooldown if provided m_cooldownTime = time(NULL) + (goInfo->trap.cooldown ? goInfo->trap.cooldown : uint32(4)); @@ -1605,7 +1627,9 @@ void GameObject::Use(Unit* user) // just search fishhole for success case else // TODO: find reasonable value for fishing hole search - { fishingHole = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); } + { + fishingHole = LookupFishingHoleAround(20.0f + CONTACT_DISTANCE); + } if (success || sWorld.getConfig(CONFIG_BOOL_SKILL_FAIL_GAIN_FISHING)) { @@ -1735,7 +1759,9 @@ void GameObject::Use(Unit* user) spellId = info->summoningRitual.spellId; if (spellId == 62330) // GO store nonexistent spell, replace by expected + { spellId = 61993; + } // spell have reagent and mana cost but it not expected use its // it triggered spell in fact casted at currently channeled GO @@ -1829,9 +1855,13 @@ void GameObject::Use(Unit* user) } if (info->id == 194097) + { spellId = 61994; // Ritual of Summoning + } else + { spellId = 59782; // Summoning Stone Effect + } break; } @@ -1915,7 +1945,9 @@ void GameObject::Use(Unit* user) break; case 184142: // Netherstorm Flag if (bg->GetTypeID() == BATTLEGROUND_EY) + { bg->EventPlayerClickedOnFlag(player, this); + } break; } } @@ -2035,7 +2067,9 @@ void GameObject::SetWorldRotation(float qx, float qy, float qz, float qw) Quat rotation(qx, qy, qz, qw); // Temporary solution for gameobjects that has no rotation data in DB: if (qz == 0.f && qw == 0.f) + { rotation = Quat::fromAxisAngleRotation(G3D::Vector3::unitZ(), GetOrientation()); + } rotation.unitize(); m_packedRotation = QuaternionCompressed(rotation).m_raw; @@ -2698,12 +2732,18 @@ void GameObject::ForceGameObjectHealth(int32 diff, Unit* caster) DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DestructibleGO: %s taken damage %u dealt by %s", GetGuidStr().c_str(), uint32(-diff), caster->GetGuidStr().c_str()); #ifdef ENABLE_ELUNA if (caster && caster->ToPlayer()) + { sEluna->OnDamaged(this, caster->ToPlayer()); + } #endif if (m_useTimes > uint32(-diff)) + { m_useTimes += diff; + } else + { m_useTimes = 0; + } } else if (diff == 0 && GetMaxHealth()) // Rebuild - TODO: Rebuilding over time with special display-id? { @@ -2712,10 +2752,14 @@ void GameObject::ForceGameObjectHealth(int32 diff, Unit* caster) m_useTimes = GetMaxHealth(); // Start Event if exist if (caster && m_goInfo->destructibleBuilding.rebuildingEvent) + { StartEvents_Event(GetMap(), m_goInfo->destructibleBuilding.rebuildingEvent, this, caster->GetCharmerOrOwnerOrSelf(), true, caster->GetCharmerOrOwnerOrSelf()); + } } else // Set to value + { m_useTimes = uint32(diff); + } uint32 newDisplayId = 0xFFFFFFFF; // Set to invalid -1 to track if we switched to a change state DestructibleModelDataEntry const* destructibleInfo = sDestructibleModelDataStore.LookupEntry(m_goInfo->destructibleBuilding.destructibleData); @@ -2730,7 +2774,9 @@ void GameObject::ForceGameObjectHealth(int32 diff, Unit* caster) // Start Event if exist if (caster && m_goInfo->destructibleBuilding.intactEvent) + { StartEvents_Event(GetMap(), m_goInfo->destructibleBuilding.intactEvent, this, caster->GetCharmerOrOwnerOrSelf(), true, caster->GetCharmerOrOwnerOrSelf()); + } } else if (m_useTimes == 0) // Destroyed { @@ -2739,28 +2785,40 @@ void GameObject::ForceGameObjectHealth(int32 diff, Unit* caster) DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DestructibleGO: %s got destroyed", GetGuidStr().c_str()); #ifdef ENABLE_ELUNA if(caster && caster->ToPlayer()) + { sEluna->OnDestroyed(this, caster->ToPlayer()); + } #endif RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK_9 | GO_FLAG_UNK_10); SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK_11); // Get destroyed DisplayId if ((!m_goInfo->destructibleBuilding.destroyedDisplayId || m_goInfo->destructibleBuilding.destroyedDisplayId == 1) && destructibleInfo) + { newDisplayId = destructibleInfo->destroyedDisplayId; + } else + { newDisplayId = m_goInfo->destructibleBuilding.destroyedDisplayId; + } if (!newDisplayId) // No proper destroyed display ID exists, fetch damaged { if ((!m_goInfo->destructibleBuilding.damagedDisplayId || m_goInfo->destructibleBuilding.damagedDisplayId == 1) && destructibleInfo) + { newDisplayId = destructibleInfo->damagedDisplayId; + } else + { newDisplayId = m_goInfo->destructibleBuilding.damagedDisplayId; + } } // Start Event if exist if (caster && m_goInfo->destructibleBuilding.destroyedEvent) + { StartEvents_Event(GetMap(), m_goInfo->destructibleBuilding.destroyedEvent, this, caster->GetCharmerOrOwnerOrSelf(), true, caster->GetCharmerOrOwnerOrSelf()); + } } } else if (m_useTimes <= m_goInfo->destructibleBuilding.damagedNumHits) // Damaged @@ -2773,19 +2831,27 @@ void GameObject::ForceGameObjectHealth(int32 diff, Unit* caster) // Get damaged DisplayId if ((!m_goInfo->destructibleBuilding.damagedDisplayId || m_goInfo->destructibleBuilding.damagedDisplayId == 1) && destructibleInfo) + { newDisplayId = destructibleInfo->damagedDisplayId; + } else + { newDisplayId = m_goInfo->destructibleBuilding.damagedDisplayId; + } // Start Event if exist if (caster && m_goInfo->destructibleBuilding.damagedEvent) + { StartEvents_Event(GetMap(), m_goInfo->destructibleBuilding.damagedEvent, this, caster->GetCharmerOrOwnerOrSelf(), true, caster->GetCharmerOrOwnerOrSelf()); + } } } // Set display Id if (newDisplayId != 0xFFFFFFFF && newDisplayId != GetDisplayId() && newDisplayId) + { SetDisplayId(newDisplayId); + } // Set health SetGoAnimProgress(GetMaxHealth() ? m_useTimes * 255 / GetMaxHealth() : 255); @@ -2795,9 +2861,13 @@ void GameObject::SetInUse(bool use) { m_isInUse = use; if (use) + { SetGoState(GO_STATE_ACTIVE); + } else + { SetGoState(GO_STATE_READY); + } } uint32 GameObject::GetScriptId() diff --git a/src/game/Object/Guild.cpp b/src/game/Object/Guild.cpp index d197957c1..26bd9c4a7 100644 --- a/src/game/Object/Guild.cpp +++ b/src/game/Object/Guild.cpp @@ -223,7 +223,9 @@ bool Guild::AddMember(ObjectGuid plGuid, uint32 plRank) // 0 1 2 3 4 QueryResult* result = CharacterDatabase.PQuery("SELECT `name`,`level`,`class`,`zone`,`account` FROM `characters` WHERE `guid` = '%u'", lowguid); if (!result) - { return false; } // player doesn't exist + { + return false; // player doesn't exist + } Field* fields = result->Fetch(); newmember.Name = fields[0].GetCppString(); @@ -332,7 +334,9 @@ bool Guild::LoadGuildFromDB(QueryResult* guildDataResult) uint32 purchasedTabs = fields[12].GetUInt32(); if (purchasedTabs > GUILD_BANK_MAX_TABS) + { purchasedTabs = GUILD_BANK_MAX_TABS; + } m_TabListMap.resize(purchasedTabs); @@ -353,7 +357,9 @@ bool Guild::CheckGuildStructure() if (GM_rights == -1) { if (DelMember(m_LeaderGuid)) - { return false; } // guild will disbanded and deleted in caller + { + return false; // guild will disbanded and deleted in caller + } } else if (GM_rights != GR_GUILDMASTER) { @@ -485,7 +491,9 @@ bool Guild::LoadMembersFromDB(QueryResult* guildMembersResult) if (guildId > m_Id) // we loaded all members for this guild already, break cycle - { break; } + { + break; + } MemberSlot newmember; uint32 lowguid = fields[1].GetUInt32(); @@ -694,7 +702,9 @@ void Guild::BroadcastAddonToGuild(WorldSession* session, const std::string& msg, Player* pl = ObjectAccessor::FindPlayer(ObjectGuid(HIGHGUID_PLAYER, itr->first)); if (pl && pl->GetSession() && HasRankRight(pl->GetRank(), GR_RIGHT_GCHATLISTEN) && !pl->GetSocial()->HasIgnore(session->GetPlayer()->GetObjectGuid())) + { pl->GetSession()->SendPacket(&data); + } } } } @@ -720,7 +730,9 @@ void Guild::BroadcastToOfficers(WorldSession* session, const std::string& msg, u Player* pl = ObjectAccessor::FindPlayer(ObjectGuid(HIGHGUID_PLAYER, itr->first)); if (pl && pl->GetSession() && HasRankRight(pl->GetRank(), GR_RIGHT_OFFCHATLISTEN) && !pl->GetSocial()->HasIgnore(player->GetObjectGuid())) + { pl->GetSession()->SendPacket(&data); + } } } @@ -736,7 +748,9 @@ void Guild::BroadcastAddonToOfficers(WorldSession* session, const std::string& m Player* pl = ObjectAccessor::FindPlayer(ObjectGuid(HIGHGUID_PLAYER, itr->first)); if (pl && pl->GetSession() && HasRankRight(pl->GetRank(), GR_RIGHT_OFFCHATLISTEN) && !pl->GetSocial()->HasIgnore(session->GetPlayer()->GetObjectGuid())) + { pl->GetSession()->SendPacket(&data); + } } } } @@ -886,9 +900,13 @@ void Guild::SwitchRank(uint32 rankId, bool up) for (MemberList::iterator itr = members.begin(); itr != members.end(); ++itr) if (itr->second.RankId == rankId) + { itr->second.ChangeRank(otherRankId); + } else if (itr->second.RankId == otherRankId) + { itr->second.ChangeRank(rankId); + } CharacterDatabase.CommitTransaction(); } @@ -1005,9 +1023,13 @@ void Guild::Roster(WorldSession* session /*= NULL*/) { flags |= GUILDMEMBER_STATUS_ONLINE; if (player->isAFK()) + { flags |= GUILDMEMBER_STATUS_AFK; + } if (player->isDND()) + { flags |= GUILDMEMBER_STATUS_DND; + } } buffer << uint8(member.Class); @@ -1082,25 +1104,35 @@ void Guild::Query(WorldSession* session) data << m_Ranks[i].Name; } else - { data << uint8(0); } // null string + { + data << uint8(0); // null string + } } // Rank order of creation for (uint8 i = 0; i < GUILD_RANKS_MAX_COUNT; ++i) { if (i < m_Ranks.size()) + { data << uint32(i); + } else + { data << uint32(0); + } } // Rank order of "importance" (sorting by rights) for (uint8 i = 0; i < GUILD_RANKS_MAX_COUNT; ++i) { if (i < m_Ranks.size()) + { data << uint32(i); + } else + { data << uint32(0); + } } data << uint32(m_EmblemStyle); @@ -1293,17 +1325,23 @@ void Guild::DisplayGuildBankContent(WorldSession* session, uint8 TabId) uint32 itemCount = 0; for (int i = 0; i < GUILD_BANK_MAX_SLOTS; ++i) if (tab->Slots[i]) + { ++itemCount; + } data.WriteBits(itemCount, 20); data.WriteBits(0, 22); // Tell client that there's no tab info in this packet for (int i = 0; i < GUILD_BANK_MAX_SLOTS; ++i) if (tab->Slots[i]) + { AppendDisplayGuildBankSlot(data, buffer, tab, i); + } data << uint64(m_GuildBankMoney); if (!buffer.empty()) + { data.append(buffer); + } data << uint32(TabId); data << uint32(GetMemberSlotWithdrawRem(session->GetPlayer()->GetObjectGuid(), TabId)); @@ -1338,17 +1376,25 @@ void Guild::DisplayGuildBankContentUpdate(uint8 TabId, int32 slot1, int32 slot2) data.WriteBit(0); if (slot2 == -1) // single item in slot1 + { data.WriteBits(1, 20); // item count + } else // 2 items (in slot1 and slot2) + { data.WriteBits(2, 20); // item count + } data.WriteBits(0, 22); // Tell client that there's no tab info in this packet if (slot2 == -1) // single item in slot1 + { AppendDisplayGuildBankSlot(data, buffer, tab, slot1); + } else // 2 items (in slot1 and slot2) { if (slot1 > slot2) + { std::swap(slot1, slot2); + } AppendDisplayGuildBankSlot(data, buffer, tab, slot1); AppendDisplayGuildBankSlot(data, buffer, tab, slot2); @@ -1356,7 +1402,9 @@ void Guild::DisplayGuildBankContentUpdate(uint8 TabId, int32 slot1, int32 slot2) data << uint64(GetGuildBankMoney()); if (!buffer.empty()) + { data.append(buffer); + } data << uint32(TabId); size_t rempos = data.wpos(); @@ -1366,10 +1414,14 @@ void Guild::DisplayGuildBankContentUpdate(uint8 TabId, int32 slot1, int32 slot2) { Player* player = ObjectAccessor::FindPlayer(ObjectGuid(HIGHGUID_PLAYER, itr->first)); if (!player) + { continue; + } if (!IsMemberHaveRights(itr->first, TabId, GUILD_BANK_RIGHT_VIEW_TAB)) + { continue; + } data.put(rempos, uint32(GetMemberSlotWithdrawRem(player->GetGUIDLow(), TabId))); @@ -1396,7 +1448,9 @@ void Guild::DisplayGuildBankContentUpdate(uint8 TabId, GuildItemPosCountVec cons data << uint64(GetGuildBankMoney()); if (!buffer.empty()) + { data.append(buffer); + } data << uint32(TabId); @@ -1407,10 +1461,14 @@ void Guild::DisplayGuildBankContentUpdate(uint8 TabId, GuildItemPosCountVec cons { Player* player = ObjectAccessor::FindPlayer(ObjectGuid(HIGHGUID_PLAYER, itr->first)); if (!player) + { continue; + } if (!IsMemberHaveRights(itr->first, TabId, GUILD_BANK_RIGHT_VIEW_TAB)) + { continue; + } data.put(rempos, uint32(GetMemberSlotWithdrawRem(player->GetGUIDLow(), TabId))); @@ -1638,7 +1696,9 @@ bool Guild::MemberMoneyWithdraw(uint64 amount, uint32 LowGuid) void Guild::SetBankMoney(int64 money) { if (money < 0) // I don't know how this happens, it does!! + { money = 0; + } m_GuildBankMoney = money; CharacterDatabase.PExecute("UPDATE `guild` SET `BankMoney`='" UI64FMTD "' WHERE `guildid`='%u'", money, m_Id); @@ -1750,7 +1810,9 @@ void Guild::SetBankMoneyPerDay(uint32 rankId, uint32 money) } if (rankId == GR_GUILDMASTER) + { money = (uint32)WITHDRAW_MONEY_UNLIMITED; + } m_Ranks[rankId].BankMoneyPerDay = money; @@ -1758,7 +1820,9 @@ void Guild::SetBankMoneyPerDay(uint32 rankId, uint32 money) { MemberSlot& member = itr->second; if (member.RankId == rankId) + { member.BankResetTimeMoney = 0; + } } CharacterDatabase.PExecute("UPDATE `guild_rank` SET `BankMoneyPerDay`='%u' WHERE `rid`='%u' AND `guildid`='%u'", money, rankId, m_Id); @@ -1842,7 +1906,9 @@ bool Guild::LoadBankRightsFromDB(QueryResult* guildBankTabRightsResult) Field* fields = guildBankTabRightsResult->Fetch(); // prevent crash when all rights in result are already processed if (!fields) + { break; + } uint32 guildId = fields[0].GetUInt32(); if (guildId < m_Id) { @@ -1881,7 +1947,9 @@ void Guild::LoadGuildBankEventLogFromDB() // 0 1 2 3 4 5 6 QueryResult* result = CharacterDatabase.PQuery("SELECT `LogGuid`, `EventType`, `PlayerGuid`, `ItemOrMoney`, `ItemStackCount`, `DestTabId`, `TimeStamp` FROM `guild_bank_eventlog` WHERE `guildid`='%u' AND `TabId`='%u' ORDER BY `TimeStamp` DESC,`LogGuid` DESC LIMIT %u", m_Id, tabId, GUILD_BANK_MAX_LOGS); if (!result) + { continue; + } bool isNextLogGuidSet = false; do @@ -1998,7 +2066,9 @@ void Guild::DisplayGuildBankLogs(WorldSession* session, uint8 TabId) data << uint32(TabId); if (hasCashFlow) + { data << uint64(0); // cash flow contribution + } session->SendPacket(&data); @@ -2025,7 +2095,9 @@ void Guild::LogBankEvent(uint8 EventType, uint8 TabId, uint32 PlayerGuidLow, uin currentLogGuid = m_GuildBankEventLogNextGuid_Money; currentTabId = GUILD_BANK_MONEY_LOGS_TAB; if (m_GuildBankEventLog_Money.size() >= GUILD_BANK_MAX_LOGS) + { m_GuildBankEventLog_Money.pop_front(); + } m_GuildBankEventLog_Money.push_back(NewEvent); } @@ -2034,7 +2106,9 @@ void Guild::LogBankEvent(uint8 EventType, uint8 TabId, uint32 PlayerGuidLow, uin m_GuildBankEventLogNextGuid_Item[TabId] = ((m_GuildBankEventLogNextGuid_Item[TabId]) + 1) % sWorld.getConfig(CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT); currentLogGuid = m_GuildBankEventLogNextGuid_Item[TabId]; if (m_GuildBankEventLog_Item[TabId].size() >= GUILD_BANK_MAX_LOGS) + { m_GuildBankEventLog_Item[TabId].pop_front(); + } m_GuildBankEventLog_Item[TabId].push_back(NewEvent); } @@ -2135,9 +2209,13 @@ Item* Guild::_StoreItem(uint8 tab, uint8 slot, Item* pItem, uint32 count, bool c if (!pItem2) { if (clone) + { pItem = pItem->CloneItem(count); + } else + { pItem->SetCount(count); + } if (!pItem) { @@ -2184,7 +2262,9 @@ InventoryResult Guild::_CanStoreItem_InSpecificSlot(uint8 tab, uint8 slot, Guild // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) + { pItem2 = NULL; + } uint32 need_space; @@ -2213,7 +2293,9 @@ InventoryResult Guild::_CanStoreItem_InSpecificSlot(uint8 tab, uint8 slot, Guild } if (need_space > count) + { need_space = count; + } GuildItemPosCount newPosition = GuildItemPosCount(slot, need_space); if (!newPosition.isContainedIn(dest)) @@ -2231,17 +2313,23 @@ InventoryResult Guild::_CanStoreItem_InTab(uint8 tab, GuildItemPosCountVec& dest { // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (j == skip_slot) + { continue; + } Item* pItem2 = m_TabListMap[tab]->Slots[j]; // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) + { pItem2 = NULL; + } // if merge skip empty, if !merge skip non-empty if ((pItem2 != NULL) != merge) + { continue; + } if (pItem2) { @@ -2249,7 +2337,9 @@ InventoryResult Guild::_CanStoreItem_InTab(uint8 tab, GuildItemPosCountVec& dest { uint32 need_space = pSrcItem->GetMaxStackCount() - pItem2->GetCount(); if (need_space > count) + { need_space = count; + } GuildItemPosCount newPosition = GuildItemPosCount(j, need_space); if (!newPosition.isContainedIn(dest)) @@ -2268,7 +2358,9 @@ InventoryResult Guild::_CanStoreItem_InTab(uint8 tab, GuildItemPosCountVec& dest { uint32 need_space = pSrcItem->GetMaxStackCount(); if (need_space > count) + { need_space = count; + } GuildItemPosCount newPosition = GuildItemPosCount(j, need_space); if (!newPosition.isContainedIn(dest)) @@ -2385,9 +2477,13 @@ void Guild::SendGuildBankTabText(WorldSession* session, uint8 TabId) data.WriteStringData(tab->Text); if (session) + { session->SendPacket(&data); + } else + { BroadcastPacket(&data); + } } void Guild::SwapItems(Player* pl, uint8 BankTab, uint8 BankTabSlot, uint8 BankTabDst, uint8 BankTabSlotDst, uint32 SplitedAmount) @@ -2405,9 +2501,13 @@ void Guild::SwapItems(Player* pl, uint8 BankTab, uint8 BankTabSlot, uint8 BankTa } if (SplitedAmount > pItemSrc->GetCount()) + { return; // cheating? + } else if (SplitedAmount == pItemSrc->GetCount()) + { SplitedAmount = 0; // no split + } Item* pItemDst = GetItem(BankTabDst, BankTabSlotDst); @@ -2448,7 +2548,9 @@ void Guild::SwapItems(Player* pl, uint8 BankTab, uint8 BankTabSlot, uint8 BankTa CharacterDatabase.BeginTransaction(); if (BankTab != BankTabDst) + { LogBankEvent(GUILD_BANK_LOG_MOVE_ITEM, BankTab, pl->GetGUIDLow(), pItemSrc->GetEntry(), SplitedAmount, BankTabDst); + } pl->ItemRemovedQuestCheck(pItemSrc->GetEntry(), SplitedAmount); pItemSrc->SetCount(pItemSrc->GetCount() - SplitedAmount); @@ -2466,7 +2568,9 @@ void Guild::SwapItems(Player* pl, uint8 BankTab, uint8 BankTabSlot, uint8 BankTa CharacterDatabase.BeginTransaction(); if (BankTab != BankTabDst) + { LogBankEvent(GUILD_BANK_LOG_MOVE_ITEM, BankTab, pl->GetGUIDLow(), pItemSrc->GetEntry(), pItemSrc->GetCount(), BankTabDst); + } RemoveItem(BankTab, BankTabSlot); StoreItem(BankTabDst, gDest, pItemSrc); @@ -2523,7 +2627,9 @@ void Guild::SwapItems(Player* pl, uint8 BankTab, uint8 BankTabSlot, uint8 BankTa } DisplayGuildBankContentUpdate(BankTab, BankTabSlot, BankTab == BankTabDst ? BankTabSlotDst : -1); if (BankTab != BankTabDst) + { DisplayGuildBankContentUpdate(BankTabDst, BankTabSlotDst); + } } @@ -2538,9 +2644,13 @@ void Guild::MoveFromBankToChar(Player* pl, uint8 BankTab, uint8 BankTabSlot, uin } if (SplitedAmount > pItemBank->GetCount()) + { return; // cheating? + } else if (SplitedAmount == pItemBank->GetCount()) + { SplitedAmount = 0; // no split + } if (SplitedAmount) { @@ -2662,7 +2772,9 @@ void Guild::MoveFromBankToChar(Player* pl, uint8 BankTab, uint8 BankTabSlot, uin CharacterDatabase.BeginTransaction(); LogBankEvent(GUILD_BANK_LOG_WITHDRAW_ITEM, BankTab, pl->GetGUIDLow(), pItemBank->GetEntry(), pItemBank->GetCount()); if (pItemChar) + { LogBankEvent(GUILD_BANK_LOG_DEPOSIT_ITEM, BankTab, pl->GetGUIDLow(), pItemChar->GetEntry(), pItemChar->GetCount()); + } RemoveItem(BankTab, BankTabSlot); if (pItemChar) @@ -2706,9 +2818,13 @@ void Guild::MoveFromCharToBank(Player* pl, uint8 PlayerBag, uint8 PlayerSlot, ui } if (SplitedAmount > pItemChar->GetCount()) + { return; // cheating? + } else if (SplitedAmount == pItemChar->GetCount()) + { SplitedAmount = 0; // no split + } if (SplitedAmount) { @@ -2817,20 +2933,28 @@ void Guild::MoveFromCharToBank(Player* pl, uint8 PlayerBag, uint8 PlayerSlot, ui CharacterDatabase.BeginTransaction(); if (pItemBank) + { LogBankEvent(GUILD_BANK_LOG_WITHDRAW_ITEM, BankTab, pl->GetGUIDLow(), pItemBank->GetEntry(), pItemBank->GetCount()); + } LogBankEvent(GUILD_BANK_LOG_DEPOSIT_ITEM, BankTab, pl->GetGUIDLow(), pItemChar->GetEntry(), pItemChar->GetCount()); pl->MoveItemFromInventory(PlayerBag, PlayerSlot, true); pItemChar->DeleteFromInventoryDB(); if (pItemBank) + { RemoveItem(BankTab, BankTabSlot); + } StoreItem(BankTab, gDest, pItemChar); if (pItemBank) + { pl->MoveItemToInventory(iDest, pItemBank, true); + } pl->SaveInventoryAndGoldToDB(); if (pItemBank) + { MemberItemWithdraw(BankTab, pl->GetGUIDLow()); + } CharacterDatabase.CommitTransaction(); DisplayGuildBankContentUpdate(BankTab, gDest); @@ -2863,7 +2987,9 @@ void Guild::BroadcastEvent(GuildEvents event, ObjectGuid guid, char const* str1 } if (guid) + { data << ObjectGuid(guid); + } BroadcastPacket(&data); @@ -2881,7 +3007,9 @@ void Guild::DeleteGuildBankItems(bool alsoInDB /*= false*/) pItem->RemoveFromWorld(); if (alsoInDB) + { pItem->DeleteFromDB(); + } delete pItem; } @@ -2959,18 +3087,26 @@ void GuildBankEventLogEntry::WriteData(WorldPacket& data, ByteBuffer& buffer) buffer.WriteGuidBytes<6, 1, 5>(logGuid); if (hasStack) + { buffer << uint32(ItemStackCount); + } buffer << uint8(EventType); buffer.WriteGuidBytes<2, 4, 0, 7, 3>(logGuid); if (hasItem) + { buffer << uint32(ItemOrMoney); + } buffer << uint32(time(NULL) - TimeStamp); if (isMoneyEvent()) + { buffer << uint64(ItemOrMoney); + } if (itemMoved) + { buffer << uint8(DestTabId); // moved tab + } } diff --git a/src/game/Object/Item.cpp b/src/game/Object/Item.cpp index 9d4a44dc9..7c92cf2e0 100644 --- a/src/game/Object/Item.cpp +++ b/src/game/Object/Item.cpp @@ -322,9 +322,13 @@ uint32 ItemPrototype::GetArmor() const ArmorLocationEntry const* al = NULL; if (InventoryType == INVTYPE_ROBE) + { al = sArmorLocationStore.LookupEntry(INVTYPE_CHEST); + } else + { al = sArmorLocationStore.LookupEntry(InventoryType); + } if (!al) { @@ -377,15 +381,23 @@ float ItemPrototype::getDPS() const case INVTYPE_WEAPONMAINHAND: case INVTYPE_WEAPONOFFHAND: if (Flags2 & ITEM_FLAG2_CASTER_WEAPON) // caster weapon flag + { id = sItemDamageOneHandCasterStore.LookupEntry(ItemLevel); + } else + { id = sItemDamageOneHandStore.LookupEntry(ItemLevel); + } break; case INVTYPE_2HWEAPON: if (Flags2 & ITEM_FLAG2_CASTER_WEAPON) // caster weapon flag + { id = sItemDamageTwoHandCasterStore.LookupEntry(ItemLevel); + } else + { id = sItemDamageTwoHandStore.LookupEntry(ItemLevel); + } break; case INVTYPE_AMMO: id = sItemDamageAmmoStore.LookupEntry(ItemLevel); @@ -502,9 +514,13 @@ void Item::UpdateDuration(Player* owner, uint32 diff) #endif /* ENABLE_ELUNA */ if (uint32 newItemId = sObjectMgr.GetItemExpireConvert(GetEntry())) + { owner->ConvertItem(this, newItemId); + } else + { owner->DestroyItem(GetBagSlot(), GetSlot(), true); + } return; } @@ -690,7 +706,9 @@ bool Item::LoadFromDB(uint32 guidLow, Field* fields, ObjectGuid ownerGuid) if (GetItemRandomPropertyId() < 0) { if (UpdateItemSuffixFactor()) + { need_save = true; + } } // Remove bind flag for items vs NO_BIND set @@ -1134,7 +1152,9 @@ bool Item::IsBoundByEnchant() const } if (enchant_slot > PRISMATIC_ENCHANTMENT_SLOT && enchant_slot < PROP_ENCHANTMENT_SLOT_0) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) @@ -1181,12 +1201,16 @@ bool Item::IsFitToSpellRequirements(SpellEntry const* spellInfo) const if (equippedItems->EquippedItemClass != -1) // -1 == any item class { if (equippedItems->EquippedItemClass != int32(proto->Class)) - { return false; } // wrong item class + { + return false; // wrong item class + } if (equippedItems->EquippedItemSubClassMask != 0) // 0 == any subclass { if ((equippedItems->EquippedItemSubClassMask & (1 << proto->SubClass)) == 0) - { return false; } // subclass not present in mask + { + return false; // subclass not present in mask + } } } @@ -1196,7 +1220,9 @@ bool Item::IsFitToSpellRequirements(SpellEntry const* spellInfo) const if (equippedItems->EquippedItemInventoryTypeMask != 0 && (spellInfo->GetTargets() & TARGET_FLAG_ITEM)) // 0 == any inventory type { if ((equippedItems->EquippedItemInventoryTypeMask & (1 << proto->InventoryType)) == 0) - { return false; } // inventory type not present in mask + { + return false; // inventory type not present in mask + } } return true; @@ -1237,10 +1263,14 @@ void Item::SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint { Player* owner = GetOwner(); if (uint32 oldEnchant = GetEnchantmentId(slot)) + { owner->GetSession()->SendEnchantmentLog(GetOwnerGuid(), ObjectGuid(), GetEntry(), oldEnchant); + } if (id) + { owner->GetSession()->SendEnchantmentLog(GetOwnerGuid(), casterGuid, GetEntry(), id); + } } SetUInt32Value(ITEM_FIELD_ENCHANTMENT_1_1 + slot * MAX_ENCHANTMENT_OFFSET + ENCHANTMENT_ID_OFFSET, id); @@ -1308,14 +1338,18 @@ bool Item::GemsFitSockets() const if (!enchant_id) { if (SocketColor) fits &= false; - continue; + { + continue; + } } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) { if (SocketColor) fits &= false; - continue; + { + continue; + } } uint8 GemColor = 0; @@ -1328,7 +1362,9 @@ bool Item::GemsFitSockets() const { GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties); if (gemProperty) + { GemColor = gemProperty->color; + } } } @@ -1344,14 +1380,20 @@ uint8 Item::GetGemCountWithID(uint32 GemID) const { uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) + { continue; + } if (GemID == enchantEntry->GemID) + { ++count; + } } return count; } @@ -1363,18 +1405,26 @@ uint8 Item::GetGemCountWithLimitCategory(uint32 limitCategory) const { uint32 enchant_id = GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) + { continue; + } ItemPrototype const* gemProto = ObjectMgr::GetItemPrototype(enchantEntry->GemID); if (!gemProto) + { continue; + } if (gemProto->ItemLimitCategory == limitCategory) + { ++count; + } } return count; } @@ -1412,7 +1462,9 @@ void Item::SendTimeUpdate(Player* owner) Item* Item::CreateItem(uint32 item, uint32 count, Player const* player, uint32 randomPropertyId) { if (count < 1) - { return NULL; } // don't create item at zero count + { + return NULL; // don't create item at zero count + } if (ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(item)) { @@ -1656,7 +1708,9 @@ uint32 Item::GetSpecialPrice(ItemPrototype const* proto, uint32 minimumPrice /*= uint32 cost = 0; if (proto->Flags2 & ITEM_FLAG2_HAS_NORMAL_PRICE) + { cost = proto->SellPrice; + } else { bool normalPrice = true; @@ -1669,19 +1723,29 @@ uint32 Item::GetSpecialPrice(ItemPrototype const* proto, uint32 minimumPrice /*= { ItemClassEntry const* classEntry = sItemClassStore.LookupEntry(proto->Class); if (classEntry) + { cost *= classEntry->PriceFactor; + } else + { cost = 0; + } } else + { cost /= 4 * proto->BuyCount; + } } else + { cost = proto->SellPrice; + } } if (cost < minimumPrice) + { cost = minimumPrice; + } return cost; } diff --git a/src/game/Object/ItemEnchantmentMgr.cpp b/src/game/Object/ItemEnchantmentMgr.cpp index 41a51605a..44bd93313 100644 --- a/src/game/Object/ItemEnchantmentMgr.cpp +++ b/src/game/Object/ItemEnchantmentMgr.cpp @@ -76,9 +76,13 @@ void LoadRandomEnchantmentsTable() if (chance > 0.000001f && chance <= 100.0f) { if (entry > 0) + { RandomItemPropEnch[entry].push_back(EnchStoreItem(ench, chance)); + } else + { RandomItemSuffixEnch[-entry].push_back(EnchStoreItem(ench, chance)); + } } else { diff --git a/src/game/Object/LootMgr.cpp b/src/game/Object/LootMgr.cpp index 9fef6fac6..6fe25507f 100644 --- a/src/game/Object/LootMgr.cpp +++ b/src/game/Object/LootMgr.cpp @@ -437,7 +437,9 @@ LootItem::LootItem(uint32 itemid_, uint8 type_, uint32 count_, uint32 randomSuff needs_quest = false; if (currency) + { freeforall = false; + } else { ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemid); @@ -621,7 +623,9 @@ void Loot::FillNotNormalLootFor(Player* pl) QuestItemMap::const_iterator qmapitr = m_playerCurrencies.find(plguid); if (qmapitr == m_playerCurrencies.end()) + { FillCurrencyLoot(pl); + } qmapitr = m_playerQuestItems.find(plguid); if (qmapitr == m_playerQuestItems.end()) @@ -637,7 +641,9 @@ void Loot::FillNotNormalLootFor(Player* pl) qmapitr = m_playerNonQuestNonFFANonCurrencyConditionalItems.find(plguid); if (qmapitr == m_playerNonQuestNonFFANonCurrencyConditionalItems.end()) + { FillNonQuestNonFFANonCurrencyConditionalLoot(pl); + } } QuestItemList* Loot::FillCurrencyLoot(Player* player) @@ -889,7 +895,9 @@ LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, QuestItem** qite { QuestItem* currency2 = (QuestItem*) & (*iter); if (currency) + { *currency = currency2; + } is_looted = currency2->is_looted; break; } @@ -1259,7 +1267,9 @@ void LootTemplate::AddEntry(LootStoreItem& item) if (item.group > 0 && item.mincountOrRef > 0) // Group { if (item.group >= Groups.size()) - { Groups.resize(item.group); } // Adds new group the the loot template if needed + { + Groups.resize(item.group); // Adds new group the the loot template if needed + } Groups[item.group - 1].AddEntry(item); // Adds new entry to the group } else // Non-grouped entries and references are stored together @@ -1274,7 +1284,9 @@ void LootTemplate::Process(Loot& loot, LootStore const& store, bool rate, uint8 if (groupId) // Group reference uses own processing of the group { if (groupId > Groups.size()) - { return; } // Error message already printed at loading stage + { + return; // Error message already printed at loading stage + } Groups[groupId - 1].Process(loot); return; @@ -1284,14 +1296,18 @@ void LootTemplate::Process(Loot& loot, LootStore const& store, bool rate, uint8 for (LootStoreItemList::const_iterator i = Entries.begin() ; i != Entries.end() ; ++i) { if (!i->Roll(rate)) - { continue; } // Bad luck for the entry + { + continue; // Bad luck for the entry + } if (i->mincountOrRef < 0 && i->type == LOOT_ITEM_TYPE_ITEM) // References processing { LootTemplate const* Referenced = LootTemplates_Reference.GetLootFor(-i->mincountOrRef); if (!Referenced) - { continue; } // Error message already printed at loading stage + { + continue; // Error message already printed at loading stage + } // Check condition if (i->conditionId && !sObjectMgr.IsPlayerMeetToCondition(i->conditionId, NULL, NULL, loot.GetLootTarget(), CONDITION_FROM_REFERING_LOOT)) @@ -1305,7 +1321,9 @@ void LootTemplate::Process(Loot& loot, LootStore const& store, bool rate, uint8 } } else // Plain entries (not a reference, not grouped) - { loot.AddItem(*i); } // Chance is already checked, just add + { + loot.AddItem(*i); // Chance is already checked, just add + } } // Now processing groups @@ -1321,7 +1339,9 @@ bool LootTemplate::HasQuestDrop(LootTemplateMap const& store, uint8 groupId) con if (groupId) // Group reference { if (groupId > Groups.size()) - { return false; } // Error message [should be] already printed at loading stage + { + return false; // Error message [should be] already printed at loading stage + } return Groups[groupId - 1].HasQuestDrop(); } @@ -1331,14 +1351,18 @@ bool LootTemplate::HasQuestDrop(LootTemplateMap const& store, uint8 groupId) con { LootTemplateMap::const_iterator Referenced = store.find(-i->mincountOrRef); if (Referenced == store.end()) - { continue; } // Error message [should be] already printed at loading stage + { + continue; // Error message [should be] already printed at loading stage + } if (Referenced->second->HasQuestDrop(store, i->group)) { return true; } } else if (i->needs_quest) - { return true; } // quest drop found + { + return true; // quest drop found + } } // Now processing groups @@ -1357,7 +1381,9 @@ bool LootTemplate::HasQuestDropForPlayer(LootTemplateMap const& store, Player co if (groupId) // Group reference { if (groupId > Groups.size()) - { return false; } // Error message already printed at loading stage + { + return false; // Error message already printed at loading stage + } return Groups[groupId - 1].HasQuestDropForPlayer(player); } @@ -1368,14 +1394,18 @@ bool LootTemplate::HasQuestDropForPlayer(LootTemplateMap const& store, Player co { LootTemplateMap::const_iterator Referenced = store.find(-i->mincountOrRef); if (Referenced == store.end()) - { continue; } // Error message already printed at loading stage + { + continue; // Error message already printed at loading stage + } if (Referenced->second->HasQuestDropForPlayer(store, player, i->group)) { return true; } } else if (player->HasQuestForItem(i->itemid)) - { return true; } // active quest drop found + { + return true; // active quest drop found + } } // Now checking groups @@ -1582,15 +1612,23 @@ void LoadLootTemplates_Milling() { ItemPrototype const* proto = sItemStorage.LookupEntry(i); if (!proto) + { continue; + } if (!(proto->Flags & ITEM_FLAG_MILLABLE)) + { continue; + } if (ids_set.find(proto->ItemId) != ids_set.end()) + { ids_set.erase(proto->ItemId); + } else + { LootTemplates_Milling.ReportNotExistedId(proto->ItemId); + } } // output error for any still listed (not referenced from appropriate table) ids @@ -1639,13 +1677,19 @@ void LoadLootTemplates_Prospecting() { ItemPrototype const* proto = sItemStorage.LookupEntry(i); if (!proto) + { continue; + } if (!(proto->Flags & ITEM_FLAG_PROSPECTABLE)) + { continue; + } if (ids_set.find(proto->ItemId) != ids_set.end()) + { ids_set.erase(proto->ItemId); + } // else -- exist some cases that possible can be prospected but not expected have any result loot // LootTemplates_Prospecting.ReportNotExistedId(proto->ItemId); } @@ -1713,11 +1757,15 @@ void LoadLootTemplates_Spell() { SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) + { continue; + } // possible cases if (!IsLootCraftingSpell(spellInfo)) + { continue; + } if (ids_set.find(spell_id) == ids_set.end()) { @@ -1729,7 +1777,9 @@ void LoadLootTemplates_Spell() } } else + { ids_set.erase(spell_id); + } } // output error for any still listed (not referenced from appropriate table) ids diff --git a/src/game/Object/Object.cpp b/src/game/Object/Object.cpp index add1440d5..e27213d29 100644 --- a/src/game/Object/Object.cpp +++ b/src/game/Object/Object.cpp @@ -171,7 +171,9 @@ void Object::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) c if (isType(TYPEMASK_UNIT)) { if (((Unit*)this)->getVictim()) + { updateFlags |= UPDATEFLAG_HAS_ATTACKING_TARGET; + } } // DEBUG_LOG("BuildCreateUpdate: update-type: %u, object-type: %u got updateFlags: %X", updatetype, m_objectTypeId, updateFlags); @@ -299,7 +301,9 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const data->WriteGuidMask<7, 3, 2>(Guid); if (unit->m_movementInfo.GetMovementFlags()) + { data->WriteBits(unit->m_movementInfo.GetMovementFlags(), 30); + } data->WriteBit(false); data->WriteBit(!hasPitch); @@ -324,19 +328,25 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const data->WriteGuidMask<4>(Guid); if (isSplineEnabled) + { Movement::PacketBuilder::WriteCreateBits(*unit->movespline, *data); + } data->WriteGuidMask<6>(Guid); if (hasFallData) + { data->WriteBit(hasFallDirection); + } data->WriteGuidMask<0, 1>(Guid); data->WriteBit(false); // Unknown 4.3.3 data->WriteBit(!unit->m_movementInfo.GetMovementFlags2()); if (unit->m_movementInfo.GetMovementFlags2()) + { data->WriteBits(unit->m_movementInfo.GetMovementFlags2(), 12); + } } // used only with GO's, placeholder @@ -354,7 +364,9 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const { ObjectGuid guid; if (Unit* victim = ((Unit*)this)->getVictim()) + { guid = victim->GetObjectGuid(); + } data->WriteGuidMask<2, 7, 0, 4, 5, 6, 1, 3>(guid); } @@ -392,10 +404,14 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const *data << float(unit->GetSpeed(MOVE_SWIM_BACK)); if (hasElevation) + { *data << float(unit->m_movementInfo.GetSplineElevation()); + } if (isSplineEnabled) + { Movement::PacketBuilder::WriteCreateBytes(*unit->movespline, *data); + } *data << float(unit->GetPositionZ()); data->WriteGuidBytes<5>(Guid); @@ -409,7 +425,9 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const *data << float(NormalizeOrientation(unit->m_movementInfo.GetTransportPos()->o)); if (hasTransportTime2) + { *data << uint32(unit->m_movementInfo.GetTransportTime2()); + } *data << float(unit->m_movementInfo.GetTransportPos()->y); *data << float(unit->m_movementInfo.GetTransportPos()->x); @@ -418,7 +436,9 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const data->WriteGuidBytes<0>(tGuid); if (hasTransportTime3) + { *data << uint32(unit->m_movementInfo.GetFallTime()); + } *data << int8(unit->m_movementInfo.GetTransportSeat()); data->WriteGuidBytes<1, 6, 2, 4>(tGuid); @@ -439,12 +459,16 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const *data << float(unit->GetSpeed(MOVE_TURN_RATE)); if (hasOrientation) + { *data << float(NormalizeOrientation(unit->GetOrientation())); + } *data << float(unit->GetSpeed(MOVE_RUN)); if (hasPitch) + { *data << float(unit->m_movementInfo.GetPitch()); + } *data << float(unit->GetSpeed(MOVE_FLIGHT)); } @@ -462,7 +486,9 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const data->WriteGuidBytes<0, 5>(transGuid); if (hasTransportTime3) + { *data << uint32(0); + } data->WriteGuidBytes<3>(transGuid); *data << float(0.0f); // x offset @@ -475,11 +501,15 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const *data << float(0.0f); // o offset if (hasTransportTime2) + { *data << uint32(0); + } } if (updateFlags & UPDATEFLAG_ROTATION) + { *data << int64(((GameObject*)this)->GetPackedWorldRotation()); + } if (updateFlags & UPDATEFLAG_TRANSPORT_ARR) { @@ -514,13 +544,17 @@ void Object::BuildMovementUpdate(ByteBuffer* data, uint16 updateFlags) const { ObjectGuid guid; if (Unit* victim = ((Unit*)this)->getVictim()) + { guid = victim->GetObjectGuid(); + } data->WriteGuidBytes<4, 0, 3, 5, 7, 6, 2, 1>(guid); } if (updateFlags & UPDATEFLAG_TRANSPORT) + { *data << uint32(WorldTimer::getMSTime()); + } } void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* updateMask, Player* target) const @@ -532,7 +566,9 @@ void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* u uint32 valuesCount = m_valuesCount; if(GetTypeId() == TYPEID_PLAYER && target != this) + { valuesCount = PLAYER_END_NOT_SELF; + } bool IsActivateToQuest = false; bool IsPerCasterAuraState = false; @@ -598,12 +634,16 @@ void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* u if (GetTypeId() == TYPEID_UNIT) { if (!target->canSeeSpellClickOn((Creature*)this)) + { appendValue &= ~UNIT_NPC_FLAG_SPELLCLICK; + } if (appendValue & UNIT_NPC_FLAG_TRAINER) { if (!((Creature*)this)->IsTrainerOf(target, false)) + { appendValue &= ~(UNIT_NPC_FLAG_TRAINER | UNIT_NPC_FLAG_TRAINER_CLASS | UNIT_NPC_FLAG_TRAINER_PROFESSION); + } } if (appendValue & UNIT_NPC_FLAG_STABLEMASTER) @@ -623,12 +663,18 @@ void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* u { // IsPerCasterAuraState set if related pet caster aura state set already if (((Unit*)this)->HasAuraStateForCaster(AURA_STATE_CONFLAGRATE, target->GetObjectGuid())) + { *data << m_uint32Values[index]; + } else + { *data << (m_uint32Values[index] & ~(1 << (AURA_STATE_CONFLAGRATE - 1))); + } } else + { *data << m_uint32Values[index]; + } } // FIXME: Some values at server stored in float format but must be sent to client in uint32 format else if (index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME) @@ -740,12 +786,18 @@ void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* u else if (index == GAMEOBJECT_BYTES_1) { if (((GameObject*)this)->GetGOInfo()->type == GAMEOBJECT_TYPE_TRANSPORT) + { *data << uint32(m_uint32Values[index] | GO_STATE_TRANSPORT_SPEC); + } else + { *data << uint32(m_uint32Values[index]); + } } else - { *data << m_uint32Values[index]; } // other cases + { + *data << m_uint32Values[index]; // other cases + } } } } @@ -810,7 +862,9 @@ void Object::_SetUpdateBits(UpdateMask* updateMask, Player* target) const { uint32 valuesCount = m_valuesCount; if(GetTypeId() == TYPEID_PLAYER && target != this) + { valuesCount = PLAYER_END_NOT_SELF; + } for (uint16 index = 0; index < valuesCount; ++index ) if (m_changedValues[index]) @@ -823,7 +877,9 @@ void Object::_SetCreateBits(UpdateMask* updateMask, Player* target) const { uint32 valuesCount = m_valuesCount; if(GetTypeId() == TYPEID_PLAYER && target != this) + { valuesCount = PLAYER_END_NOT_SELF; + } for (uint16 index = 0; index < valuesCount; ++index) if (GetUInt32Value(index) != 0) @@ -1523,15 +1579,23 @@ void WorldObject::GetRandomPoint(float x, float y, float z, float distance, floa // angle to face `obj` to `this` float angle; if (!ori) + { angle = rand_norm_f() * 2 * M_PI_F; + } else + { angle = *ori; + } float new_dist; if (minDist == 0.0f) + { new_dist = rand_norm_f() * distance; + } else + { new_dist = minDist + rand_norm_f() * (distance - minDist); + } rand_x = x + new_dist * cos(angle); rand_y = y + new_dist * sin(angle); @@ -1546,7 +1610,9 @@ void WorldObject::UpdateGroundPositionZ(float x, float y, float& z) const { float new_z = GetMap()->GetHeight(GetPhaseMask(), x, y, z); if (new_z > INVALID_HEIGHT) - { z = new_z + 0.05f; } // just to be sure that we are not a few pixel under the surface + { + z = new_z + 0.05f; // just to be sure that we are not a few pixel under the surface + } } void WorldObject::UpdateAllowedPositionZ(float x, float y, float& z, Map* atMap /*=NULL*/) const @@ -1614,7 +1680,9 @@ void WorldObject::UpdateAllowedPositionZ(float x, float y, float& z, Map* atMap { float ground_z = atMap->GetHeight(GetPhaseMask(), x, y, z); if (z < ground_z) + { z = ground_z; + } } break; } @@ -1894,7 +1962,9 @@ Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, floa #ifdef ENABLE_ELUNA if (Unit* summoner = ToUnit()) + { sEluna->OnSummoned(pCreature, summoner); + } #endif /* ENABLE_ELUNA */ // Creature Linking, Initial load is handled like respawn @@ -2045,7 +2115,9 @@ void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, if (!sWorld.getConfig(CONFIG_BOOL_DETECT_POS_COLLISION)) { if (searcher) - { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available + { + searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); // update to LOS height if available + } else { UpdateGroundPositionZ(x, y, z); @@ -2075,7 +2147,9 @@ void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, if (selector.CheckOriginalAngle()) { if (searcher) - { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available + { + searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); // update to LOS height if available + } else { UpdateGroundPositionZ(x, y, z); @@ -2101,7 +2175,9 @@ void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, z = GetPositionZ(); if (searcher) - { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available + { + searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); // update to LOS height if available + } else { UpdateGroundPositionZ(x, y, z); @@ -2121,7 +2197,9 @@ void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, y = first_y; if (searcher) - { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available + { + searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); // update to LOS height if available + } else { UpdateGroundPositionZ(x, y, z); @@ -2139,7 +2217,9 @@ void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, z = GetPositionZ(); if (searcher) - { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available + { + searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); // update to LOS height if available + } else { UpdateGroundPositionZ(x, y, z); @@ -2156,7 +2236,9 @@ void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, y = first_y; if (searcher) - { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available + { + searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); // update to LOS height if available + } else { UpdateGroundPositionZ(x, y, z); @@ -2168,7 +2250,9 @@ void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update) m_phaseMask = newPhaseMask; if (update && IsInWorld()) + { UpdateVisibilityAndView(); + } } void WorldObject::PlayDistanceSound(uint32 sound_id, Player const* target /*= NULL*/) const diff --git a/src/game/Object/Object.h b/src/game/Object/Object.h index b24365f00..bdb76ecbe 100644 --- a/src/game/Object/Object.h +++ b/src/game/Object/Object.h @@ -539,9 +539,13 @@ class WorldObject : public Object float GetPositionY() const { return m_position.y; } float GetPositionZ() const { return m_position.z; } void GetPosition(float& x, float& y, float& z) const - { x = m_position.x; y = m_position.y; z = m_position.z; } + { + x = m_position.x; y = m_position.y; z = m_position.z; + } void GetPosition(WorldLocation& loc) const - { loc.mapid = m_mapId; GetPosition(loc.coord_x, loc.coord_y, loc.coord_z); loc.orientation = GetOrientation(); } + { + loc.mapid = m_mapId; GetPosition(loc.coord_x, loc.coord_y, loc.coord_z); loc.orientation = GetOrientation(); + } float GetOrientation() const { return m_position.o; } /// Gives a 2d-point in distance distance2d in direction absAngle around the current position (point-to-point) diff --git a/src/game/Object/ObjectGuid.h b/src/game/Object/ObjectGuid.h index 653e55980..49db1bde3 100644 --- a/src/game/Object/ObjectGuid.h +++ b/src/game/Object/ObjectGuid.h @@ -25,11 +25,11 @@ #ifndef MANGOS_OBJECT_GUID_H #define MANGOS_OBJECT_GUID_H -#include - #include "Common.h" #include "ByteBuffer.h" +#include + enum TypeID { TYPEID_OBJECT = 0, @@ -338,38 +338,46 @@ HASH_NAMESPACE_END #endif -#define DEFINE_READGUIDMASK(T1, T2) template \ - void ByteBuffer::ReadGuidMask(ObjectGuid& guid) \ - { \ - uint8 maskArr[] = { T2 }; \ +#define DEFINE_READGUIDMASK(T1, T2) template \ + void ByteBuffer::ReadGuidMask(ObjectGuid& guid) \ + { \ + uint8 maskArr[] = { T2 }; \ for (uint8 i = 0; i < countof(maskArr); ++i) \ - guid[maskArr[i]] = ReadBit(); \ + { \ + guid[maskArr[i]] = ReadBit(); \ + } \ } -#define DEFINE_WRITEGUIDMASK(T1, T2) template \ - void ByteBuffer::WriteGuidMask(ObjectGuid guid) \ - { \ - uint8 maskArr[] = { T2 }; \ +#define DEFINE_WRITEGUIDMASK(T1, T2) template \ + void ByteBuffer::WriteGuidMask(ObjectGuid guid) \ + { \ + uint8 maskArr[] = { T2 }; \ for (uint8 i = 0; i < countof(maskArr); ++i) \ - WriteBit(guid[maskArr[i]]); \ + { \ + WriteBit(guid[maskArr[i]]); \ + } \ } -#define DEFINE_READGUIDBYTES(T1, T2) template \ +#define DEFINE_READGUIDBYTES(T1, T2) template \ void ByteBuffer::ReadGuidBytes(ObjectGuid& guid) \ - { \ - uint8 maskArr[] = { T2 }; \ + { \ + uint8 maskArr[] = { T2 }; \ for (uint8 i = 0; i < countof(maskArr); ++i) \ - if (guid[maskArr[i]] != 0) \ - guid[maskArr[i]] ^= read(); \ + if (guid[maskArr[i]] != 0) \ + { \ + guid[maskArr[i]] ^= read(); \ + } \ } -#define DEFINE_WRITEGUIDBYTES(T1, T2) template \ - void ByteBuffer::WriteGuidBytes(ObjectGuid guid) \ - { \ - uint8 maskArr[] = { T2 }; \ - for (uint8 i = 0; i < countof(maskArr); ++i) \ - if (guid[maskArr[i]] != 0) \ +#define DEFINE_WRITEGUIDBYTES(T1, T2) template \ + void ByteBuffer::WriteGuidBytes(ObjectGuid guid) \ + { \ + uint8 maskArr[] = { T2 }; \ + for (uint8 i = 0; i < countof(maskArr); ++i) \ + if (guid[maskArr[i]] != 0) \ + { \ (*this) << uint8(guid[maskArr[i]] ^ 1); \ + } \ } DEFINE_READGUIDMASK(BITS_1, BIT_VALS_1) diff --git a/src/game/Object/ObjectMgr.cpp b/src/game/Object/ObjectMgr.cpp index fef9fa5fd..00e0a0914 100644 --- a/src/game/Object/ObjectMgr.cpp +++ b/src/game/Object/ObjectMgr.cpp @@ -541,7 +541,9 @@ void ObjectMgr::LoadCreatureTemplates() for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1 && ok; ++diff) { if (!cInfo->DifficultyEntry[diff]) + { continue; + } ok = false; // will be set to true at the end of this loop again CreatureInfo const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]); @@ -577,7 +579,9 @@ void ObjectMgr::LoadCreatureTemplates() ok2 = true; } if (!ok2) + { continue; + } if (cInfo->UnitClass != difficultyInfo->UnitClass) { @@ -635,7 +639,9 @@ void ObjectMgr::LoadCreatureTemplates() ok = true; } if (!ok) + { continue; + } FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->FactionAlliance); if (!factionTemplate) @@ -688,7 +694,9 @@ void ObjectMgr::LoadCreatureTemplates() } if (!displayScaleEntry) + { sLog.outErrorDb("Creature (Entry: %u) has nonexistent modelid in modelid_1/modelid_2/modelid_3/modelid_4", cInfo->Entry); + } if (!cInfo->MinLevel) { @@ -748,10 +756,14 @@ void ObjectMgr::LoadCreatureTemplates() } if (cInfo->MeleeAttackPower == 0) + { const_cast(cInfo)->MeleeAttackPower = BASE_ATTACK_TIME; + } if (cInfo->RangedAttackPower == 0) + { const_cast(cInfo)->RangedAttackPower = BASE_ATTACK_TIME; + } if (cInfo->NpcFlags & UNIT_NPC_FLAG_SPELLCLICK) { @@ -816,7 +828,9 @@ void ObjectMgr::LoadCreatureTemplates() if (cInfo->VendorTemplateId > 0) { if (!(cInfo->NpcFlags & UNIT_NPC_FLAG_VENDOR)) + { sLog.outErrorDb("Table `creature_template` have creature (Entry: %u) with VendorTemplateId %u but not have flag UNIT_NPC_FLAG_VENDOR (%u), vendor items will ignored.", cInfo->Entry, cInfo->VendorTemplateId, UNIT_NPC_FLAG_VENDOR); + } } /// if not set custom creature scale then load scale from CreatureDisplayInfo.dbc @@ -1170,7 +1184,9 @@ uint32 ObjectMgr::GetModelForRace(uint32 sourceModelId, uint32 racemask) for (CreatureModelRaceMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { if (!(itr->second.racemask & racemask)) + { continue; + } if (itr->second.creature_entry) { @@ -1468,7 +1484,9 @@ void ObjectMgr::LoadCreatures() if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry(i)) for (uint32 diff = 0; diff < MAX_DIFFICULTY - 1; ++diff) if (cInfo->DifficultyEntry[diff]) + { difficultyCreatures[diff].insert(cInfo->DifficultyEntry[diff]); + } // build single time for check spawnmask std::map spawnMasks; @@ -1476,7 +1494,9 @@ void ObjectMgr::LoadCreatures() if (sMapStore.LookupEntry(i)) for (int k = 0; k < MAX_DIFFICULTY; ++k) if (GetMapDifficultyData(i, Difficulty(k))) + { spawnMasks[i] |= (1 << k); + } // Map 0 was removed from dbc as of 4.x.x spawnMasks[0] = 1 << REGULAR_DIFFICULTY; @@ -1547,7 +1567,9 @@ void ObjectMgr::LoadCreatures() } } if (!ok) + { continue; + } if (data.modelid_override > 0 && !sCreatureDisplayInfoStore.LookupEntry(data.modelid_override)) { @@ -1623,7 +1645,9 @@ void ObjectMgr::LoadCreatures() AddCreatureToGrid(guid, &data); if (cInfo->ExtraFlags & CREATURE_EXTRA_FLAG_ACTIVE) + { m_activeCreatures.insert(ActiveCreatureGuidsOnMap::value_type(data.mapid, guid)); + } } ++count; @@ -1700,7 +1724,9 @@ void ObjectMgr::LoadGameObjects() if (sMapStore.LookupEntry(i)) for (int k = 0; k < MAX_DIFFICULTY; ++k) if (GetMapDifficultyData(i, Difficulty(k))) + { spawnMasks[i] |= (1 << k); + } // Map 0 was removed from dbc as of 4.x.x spawnMasks[0] = 1 << REGULAR_DIFFICULTY; @@ -1826,7 +1852,9 @@ void ObjectMgr::LoadGameObjects() } if (gameEvent == 0 && GuidPoolId == 0 && EntryPoolId == 0) // if not this is to be managed by GameEvent System or Pool system + { AddGameobjectToGrid(guid, &data); + } //uint32 zoneId, areaId; //sTerrainMgr.LoadTerrain(data.mapid)->GetZoneAndAreaId(zoneId, areaId, data.posX, data.posY, data.posZ); @@ -1853,7 +1881,9 @@ void ObjectMgr::LoadGameObjectAddon() { GameObjectDataAddon const* addon = sGameObjectDataAddonStorage.LookupEntry(i); if (!addon) + { continue; + } if (!GetGODataPair(addon->guid)) { @@ -2104,7 +2134,9 @@ void ObjectMgr::LoadItemPrototypes() { /* to many errors, and possible not all items really used in game if (dbcitem) + { sLog.outErrorDb("Item (Entry: %u) doesn't exists in DB, but must exist.",i); + } */ continue; } @@ -2297,7 +2329,9 @@ void ObjectMgr::LoadItemPrototypes() } } else if (proto->RequiredReputationRank > MIN_REPUTATION_RANK) + { sLog.outErrorDb("Item (Entry: %u) has RequiredReputationFaction ==0 but RequiredReputationRank > 0, rank setting is useless.", i); + } if (proto->MaxCount < -1) { @@ -2464,7 +2498,9 @@ void ObjectMgr::LoadItemPrototypes() else if (proto->Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_CHANCE_ON_HIT) { if (proto->Class != ITEM_CLASS_WEAPON) + { sLog.outErrorDb("Item (Entry: %u) isn't weapon (Class: %u) but has on hit spelltrigger_%d (%u), it will not triggered.", i, proto->Class, j + 1, proto->Spells[j].SpellTrigger); + } } if (proto->Spells[j].SpellId) @@ -2552,7 +2588,9 @@ void ObjectMgr::LoadItemPrototypes() { uint32 mask = 1 << j; if (!(proto->BagFamily & mask)) + { continue; + } ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j + 1); if (!bf) @@ -2575,7 +2613,9 @@ void ObjectMgr::LoadItemPrototypes() } if (proto->TotemCategory && !sTotemCategoryStore.LookupEntry(proto->TotemCategory)) + { sLog.outErrorDb("Item (Entry: %u) has wrong TotemCategory (%u)", i, proto->TotemCategory); + } for (int j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j) { @@ -2587,7 +2627,9 @@ void ObjectMgr::LoadItemPrototypes() } if (proto->GemProperties && !sGemPropertiesStore.LookupEntry(proto->GemProperties)) + { sLog.outErrorDb("Item (Entry: %u) has wrong GemProperties (%u)", i, proto->GemProperties); + } if (proto->RequiredDisenchantSkill < -1) { @@ -2633,7 +2675,9 @@ void ObjectMgr::LoadItemPrototypes() { // lot DB cases if (proto->RequiredDisenchantSkill >= 0) + { ERROR_DB_STRICT_LOG("Item (Entry: %u) marked as disenchantable by RequiredDisenchantSkill, but not have disenchanting loot id.", i); + } } if (proto->FoodType >= MAX_PET_DIET) @@ -2907,7 +2951,9 @@ void ObjectMgr::LoadItemRequiredTarget() { SpellEffectEntry const* spellEffect = pSpellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if (spellEffect->EffectImplicitTargetA == TARGET_CHAIN_DAMAGE || spellEffect->EffectImplicitTargetB == TARGET_CHAIN_DAMAGE || @@ -3480,19 +3526,27 @@ void ObjectMgr::LoadPlayerInfo() // skip expansion races if not playing with expansion if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < EXPANSION_TBC && (race == RACE_BLOODELF || race == RACE_DRAENEI)) + { continue; + } // skip expansion classes if not playing with expansion if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < EXPANSION_WOTLK && class_ == CLASS_DEATH_KNIGHT) + { continue; + } // skip expansion races if not playing with expansion if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < EXPANSION_CATA && (race == RACE_WORGEN || race == RACE_GOBLIN)) + { continue; + } // skip expansion classes / races if not playing with expansion if (sWorld.getConfig(CONFIG_UINT32_EXPANSION) < EXPANSION_MOP && (class_ == CLASS_MONK || race == RACE_PANDAREN_NEUTRAL || race == RACE_PANDAREN_ALLI || race == RACE_PANDAREN_HORDE)) + { continue; + } // fatal error if no level 1 data if (!pInfo->levelInfo || pInfo->levelInfo[0].stats[0] == 0) @@ -4076,7 +4130,9 @@ void ObjectMgr::LoadQuests() { // skip post-loading checks for disabled quests if (DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, iter->first)) + { continue; + } Quest* qinfo = iter->second; @@ -4374,7 +4430,9 @@ void ObjectMgr::LoadQuests() { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(k)); if(!spellEffect) + { continue; + } if ((spellEffect->Effect == SPELL_EFFECT_QUEST_COMPLETE && uint32(spellEffect->EffectMiscValue) == qinfo->QuestId) || spellEffect->Effect == SPELL_EFFECT_SEND_EVENT) @@ -4512,7 +4570,9 @@ void ObjectMgr::LoadQuests() if (qinfo->RewRepFaction[j]) { if (abs(qinfo->RewRepValueId[j]) > 9) + { sLog.outErrorDb("Quest %u has RewRepValueId%d = %i but value is not valid.", qinfo->GetQuestId(), j + 1, qinfo->RewRepValueId[j]); + } if (!sFactionStore.LookupEntry(qinfo->RewRepFaction[j])) { @@ -4806,7 +4866,9 @@ void ObjectMgr::LoadQuests() { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if (spellEffect->Effect != SPELL_EFFECT_QUEST_COMPLETE) { continue; @@ -4975,7 +5037,9 @@ void ObjectMgr::LoadQuestLocales() if (idx >= 0) { if ((int32)data.CompletedText.size() <= idx) + { data.CompletedText.resize(idx + 1); + } data.CompletedText[idx] = str; } @@ -5004,7 +5068,9 @@ void ObjectMgr::LoadQuestLocales() if (idx >= 0) { if ((int32)data.PortraitGiverName.size() <= idx) + { data.PortraitGiverName.resize(idx + 1); + } data.PortraitGiverName[idx] = str; } @@ -5016,7 +5082,9 @@ void ObjectMgr::LoadQuestLocales() if (idx >= 0) { if ((int32)data.PortraitGiverText.size() <= idx) + { data.PortraitGiverText.resize(idx + 1); + } data.PortraitGiverText[idx] = str; } @@ -5028,7 +5096,9 @@ void ObjectMgr::LoadQuestLocales() if (idx >= 0) { if ((int32)data.PortraitTurnInName.size() <= idx) + { data.PortraitTurnInName.resize(idx + 1); + } data.PortraitTurnInName[idx] = str; } @@ -5040,7 +5110,9 @@ void ObjectMgr::LoadQuestLocales() if (idx >= 0) { if ((int32)data.PortraitTurnInText.size() <= idx) + { data.PortraitTurnInText.resize(idx + 1); + } data.PortraitTurnInText[idx] = str; } @@ -5319,7 +5391,9 @@ void ObjectMgr::LoadWorldTemplate() { WorldTemplate const* temp = GetWorldTemplate(i); if (!temp) + { continue; + } MapEntry const* mapEntry = sMapStore.LookupEntry(temp->map); if (!mapEntry) @@ -6543,7 +6617,9 @@ void ObjectMgr::LoadGameObjectLocales() if (idx >= 0) { if ((int32)data.Name.size() <= idx) + { data.Name.resize(idx + 1); + } data.Name[idx] = str; } @@ -6559,7 +6635,9 @@ void ObjectMgr::LoadGameObjectLocales() if (idx >= 0) { if ((int32)data.CastBarCaption.size() <= idx) + { data.CastBarCaption.resize(idx + 1); + } data.CastBarCaption[idx] = str; } @@ -6746,7 +6824,9 @@ void ObjectMgr::LoadGameobjectInfo() } /* disable check for while, too many nonexistent spells if (goInfo->trap.spellId) // spell + { CheckGOSpellId(goInfo,goInfo->trap.spellId,3); + } */ break; } @@ -6785,7 +6865,9 @@ void ObjectMgr::LoadGameobjectInfo() } /* disable check for while, too many nonexistent spells if (goInfo->goober.spellId) // spell + { CheckGOSpellId(goInfo,goInfo->goober.spellId,10); + } */ CheckGONoDamageImmuneId(goInfo, goInfo->goober.noDamageImmune, 11); if (goInfo->goober.linkedTrapId) // linked trap @@ -7496,7 +7578,9 @@ void ObjectMgr::LoadQuestPOI() for (QuestPOIVector::iterator itr = vect.begin(); itr != vect.end(); ++itr) { if (itr->PoiId != poiId) + { continue; + } QuestPOIPoint point(x, y); itr->points.push_back(point); @@ -7829,9 +7913,13 @@ struct SQLSpellLoader : public SQLStorageLoaderBase(i); if (!spellEntry) + { continue; + } // insert serverside spell data if (sSpellStore.GetNumRows() <= i) @@ -7870,7 +7960,9 @@ void ObjectMgr::LoadSpellTemplate() continue; } else + { sSpellStore.InsertEntry(const_cast(spellEntry), i); + } } } @@ -8941,7 +9033,9 @@ bool PlayerCondition::Meets(Player const* player, Map const* map, WorldObject co case CONDITION_COMPLETED_ENCOUNTER: { if (!map) + { map = player ? player->GetMap() : source->GetMap(); + } if (!map->IsDungeon()) { sLog.outErrorDb("CONDITION_COMPLETED_ENCOUNTER (entry %u) is used outside of a dungeon (on Map %u) by %s", m_entry, player->GetMapId(), player->GetGuidStr().c_str()); @@ -8959,9 +9053,13 @@ bool PlayerCondition::Meets(Player const* player, Map const* map, WorldObject co } // Select matching difficulties if (map->GetDifficulty() != Difficulty(dbcEntry1->Difficulty)) + { dbcEntry1 = NULL; + } if (dbcEntry2 && map->GetDifficulty() != Difficulty(dbcEntry2->Difficulty)) + { dbcEntry2 = NULL; + } return completedEncounterMask & ((dbcEntry1 ? 1 << dbcEntry1->encounterIndex : 0) | (dbcEntry2 ? 1 << dbcEntry2->encounterIndex : 0)); } @@ -9493,7 +9591,9 @@ bool PlayerCondition::IsValid(uint16 entry, ConditionType condition, uint32 valu } if (value2) + { sLog.outErrorDb("XP user condition (entry %u, type %u) has useless data in value2 (%u)!", entry, condition, value2); + } break; } @@ -9921,7 +10021,9 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) { SpellEffectEntry const* spellEffect = spellinfo->GetSpellEffect(SpellEffectIndex(i)); if (!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_LEARN_SPELL && SpellMgr::IsProfessionOrRidingSpell(spellEffect->EffectTriggerSpell)) @@ -9931,7 +10033,9 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) { SpellEffectEntry const* spellEff = spellinfo->GetSpellEffect(SpellEffectIndex(j)); if (!spellEff) + { continue; + } if (spellEff->Effect == SPELL_EFFECT_LEARN_SPELL) { @@ -9958,7 +10062,9 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) sLog.outErrorDb("Table `%s` (Entry: %u) has wrong redundant reqlevel %u (<>prof reqlevel %u) for spell %u", tableName, entry, trainerSpell.reqLevel, minLevel, spell); } else + { trainerSpell.reqLevel = minLevel; + } } // for non-prof. spell use spellLevel if not provided any else @@ -9969,7 +10075,9 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) ERROR_DB_STRICT_LOG("Table `%s` (Entry: %u) has redundant reqlevel %u (=spell level) for spell %u", tableName, entry, trainerSpell.reqLevel, spell); } else + { trainerSpell.reqLevel = learnSpellinfo->GetSpellLevel(); + } } ++count; @@ -10134,12 +10242,18 @@ void ObjectMgr::LoadActiveEntities(Map* _map) { _map = sMapMgr.FindMap(continents[i]); if (!_map) + { _map = sMapMgr.CreateMap(continents[i], NULL); + } if (_map) + { LoadActiveEntities(_map); + } else + { sLog.outError("ObjectMgr::LoadActiveEntities - Unable to create Map %u", continents[i]); + } } return; @@ -10151,7 +10265,9 @@ void ObjectMgr::LoadActiveEntities(Map* _map) for (CreatureDataMap::const_iterator itr = mCreatureDataMap.begin(); itr != mCreatureDataMap.end(); ++itr) { if (itr->second.mapid == _map->GetId()) + { _map->ForceLoadGrid(itr->second.posX, itr->second.posY); + } } } else // Normal case - Load all npcs that are active @@ -10213,7 +10329,9 @@ void ObjectMgr::LoadGossipMenu(std::set& gossipScriptSet) { ScriptChainMap const* scm = sScriptMgr.GetScriptChainMap(DBS_ON_GOSSIP); if (!scm) + { continue; + } if (scm->find(gMenu.script_id) == scm->end()) { @@ -10416,7 +10534,9 @@ void ObjectMgr::LoadGossipMenuItems(std::set& gossipScriptSet) { ScriptChainMap const* scm = sScriptMgr.GetScriptChainMap(DBS_ON_GOSSIP); if (!scm) + { continue; + } if (scm->find(gMenuItem.action_script_id) == scm->end()) { @@ -10568,7 +10688,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost)) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST, ExtendedCost); + } else sLog.outErrorDb("Table `%s` contain item (Entry: %u) with wrong ExtendedCost (%u) for %s %u, ignoring", tableName, item_id, ExtendedCost, idStr, vendor_entry); @@ -10679,7 +10801,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (!cInfo) { if (pl) + { ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION); + } else sLog.outErrorDb("Table `%s` has data for nonexistent creature (Entry: %u), ignoring", tableName, vendor_entry); return false; @@ -10690,12 +10814,16 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (!skip_vendors || skip_vendors->count(vendor_entry) == 0) { if (pl) + { ChatHandler(pl).SendSysMessage(LANG_COMMAND_VENDORSELECTION); + } else sLog.outErrorDb("Table `%s` has data for creature (Entry: %u) without vendor flag, ignoring", tableName, vendor_entry); if (skip_vendors) + { skip_vendors->insert(vendor_entry); + } } return false; } @@ -10707,7 +10835,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (!GetItemPrototype(item_id)) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id); + } else sLog.outErrorDb("Table `%s` for %s %u contains nonexistent item (%u), ignoring", tableName, idStr, vendor_entry, item_id); @@ -10720,7 +10850,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (!currencyEntry) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_CURRENCY_NOT_FOUND, item_id); + } else sLog.outErrorDb("Table `%s` for %s %u contains nonexistent currency (%u), ignoring", tableName, idStr, vendor_entry, item_id); @@ -10731,7 +10863,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (currencyEntry->Category == CURRENCY_CATEGORY_META) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_VENDOR_META_CURRENCY_NOT_ALLOWED, item_id); + } else sLog.outErrorDb("Table `%s` for %s %u contains not allowed meta currency (%u), ignoring", tableName, idStr, vendor_entry, item_id); @@ -10742,7 +10876,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 else { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_VENDOR_WRONG_ITEM_TYPE, item_id, type); + } else sLog.outErrorDb("Table `%s` for %s %u contains nonexistent vendor item type %u (entry %u), ignoring", tableName, idStr, vendor_entry, type, item_id); @@ -10751,7 +10887,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (ExtendedCost && !sItemExtendedCostStore.LookupEntry(ExtendedCost)) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST, ExtendedCost); + } else sLog.outErrorDb("Table `%s` contains %s (Entry: %u) with wrong ExtendedCost (%u) for %s %u, ignoring", tableName, nameStr, item_id, ExtendedCost, idStr, vendor_entry); @@ -10763,7 +10901,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (maxcount > 0 && incrtime == 0) { if (pl) + { ChatHandler(pl).PSendSysMessage("MaxCount!=0 (%u) but IncrTime==0", maxcount); + } else sLog.outErrorDb("Table `%s` has `maxcount` (%u) for %s %u of %s %u but `incrtime`=0, ignoring", tableName, maxcount, nameStr, item_id, idStr, vendor_entry); @@ -10772,7 +10912,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 else if (maxcount == 0 && incrtime > 0) { if (pl) + { ChatHandler(pl).PSendSysMessage("MaxCount==0 but IncrTime<>=0"); + } else sLog.outErrorDb("Table `%s` has `maxcount`=0 for %s %u of %s %u but `incrtime`<>0, ignoring", tableName, nameStr, item_id, idStr, vendor_entry); @@ -10784,7 +10926,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (maxcount < uint32(currencyEntry->GetPrecision())) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_VENDOR_WRONG_CURRENCY_MAXCOUNT, item_id, uint32(currencyEntry->GetPrecision())); + } else sLog.outErrorDb("Table `%s` contains %s (Entry: %u) with too low maxcount. Maxcount for currencies is buycount, so it can't be 0 or less than that's currency precision (%u), ignoring", tableName, nameStr, item_id, uint32(currencyEntry->GetPrecision())); @@ -10807,7 +10951,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (vItems && vItems->FindItemCostPair(item_id, type, ExtendedCost)) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST, item_id, type == VENDOR_ITEM_TYPE_CURRENCY, ExtendedCost); + } else sLog.outErrorDb("Table `%s` has duplicate %s %u (with extended cost %u) for %s %u, ignoring", tableName, nameStr, item_id, ExtendedCost, idStr, vendor_entry); @@ -10819,7 +10965,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (tItems && tItems->FindItemCostPair(item_id, type, ExtendedCost)) { if (pl) + { ChatHandler(pl).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST, item_id, type == VENDOR_ITEM_TYPE_CURRENCY, ExtendedCost); + } else { if (!cInfo->VendorTemplateId) @@ -10839,7 +10987,9 @@ bool ObjectMgr::IsVendorItemValid(bool isTemplate, char const* tableName, uint32 if (countItems >= MAX_VENDOR_ITEMS) { if (pl) + { ChatHandler(pl).SendSysMessage(LANG_COMMAND_ADDVENDORITEMITEMS); + } else sLog.outErrorDb("Table `%s` has too many entries (%u >= %i) for %s %u, ignoring", tableName, countItems, MAX_VENDOR_ITEMS, idStr, vendor_entry); @@ -11146,7 +11296,9 @@ bool FindGOData::operator()(GameObjectDataPair const& dataPair) } if (!i_anyData) + { i_anyData = &dataPair; + } // without player we can't find more stricted cases, so use fouded if (!i_player) diff --git a/src/game/Object/ObjectMgr.h b/src/game/Object/ObjectMgr.h index d9f41951c..af200fe08 100644 --- a/src/game/Object/ObjectMgr.h +++ b/src/game/Object/ObjectMgr.h @@ -1271,7 +1271,9 @@ class ObjectMgr static inline void GetLocaleString(const StringVector& data, int loc_idx, std::string& value) { if (data.size() > size_t(loc_idx) && !data[loc_idx].empty()) + { value = data[loc_idx]; + } } int GetOrNewIndexForLocale(LocaleConstant loc); @@ -1371,7 +1373,9 @@ class ObjectMgr for (HotfixData::const_iterator itr = m_hotfixData.begin(); itr != m_hotfixData.end(); ++itr) if (itr->Entry == entry && itr->Type == type) if (itr->Timestamp > ret) + { ret = itr->Timestamp; + } return ret ? ret : uint32(time(NULL)); } diff --git a/src/game/Object/ObjectPosSelector.cpp b/src/game/Object/ObjectPosSelector.cpp index 9a10f98a3..f7c014f8b 100644 --- a/src/game/Object/ObjectPosSelector.cpp +++ b/src/game/Object/ObjectPosSelector.cpp @@ -239,7 +239,9 @@ bool ObjectPosSelector::NextUsedAngle(float& angle) { if (m_nextUsedAreaItr[USED_POS_PLUS] == m_UsedAreaLists[USED_POS_PLUS].end() && m_nextUsedAreaItr[USED_POS_MINUS] == m_UsedAreaLists[USED_POS_MINUS].end()) - { return false; } + { + return false; + } // ++ direction less updated if (m_nextUsedAreaItr[USED_POS_PLUS] != m_UsedAreaLists[USED_POS_PLUS].end() && diff --git a/src/game/Object/Pet.cpp b/src/game/Object/Pet.cpp index b398f16c3..55f7ad738 100644 --- a/src/game/Object/Pet.cpp +++ b/src/game/Object/Pet.cpp @@ -213,7 +213,9 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petentry, uint32 petnumber, bool c } if (owner->IsFFAPvP()) + { SetFFAPvP(true); + } SetCanModifyStats(true); InitStatsForLevel(petlevel); @@ -250,7 +252,9 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petentry, uint32 petnumber, bool c // load action bar, if data broken will fill later by default spells. if (!is_temporary_summoned) + { m_charmInfo->LoadPetActionBar(fields[12].GetCppString()); + } // since last save (in seconds) uint32 timediff = uint32(time(NULL) - fields[13].GetUInt64()); @@ -282,7 +286,9 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petentry, uint32 petnumber, bool c SetPower(powerType, savedpower > GetMaxPower(powerType) ? GetMaxPower(powerType) : savedpower); if (getPetType() == HUNTER_PET && savedhealth <= 0) + { SetDeathState(JUST_DIED); + } map->Add((Creature*)this); AIM_Initialize(); @@ -367,9 +373,13 @@ void Pet::SavePetToDB(PetSaveMode mode) { // Hunter Pets always save as current if dismissed or unsummoned due to range/etc. if (getPetType() == HUNTER_PET) + { mode = PET_SAVE_AS_CURRENT; + } else + { mode = PET_SAVE_NOT_IN_SLOT; + } } // not save pet as current if another pet temporary unsummoned else if (mode == PET_SAVE_AS_CURRENT && pOwner->GetTemporaryUnsummonedPetNumber() && @@ -682,7 +692,9 @@ void Pet::Unsummon(PetSaveMode mode, Unit* owner /*= NULL*/) // not save secondary permanent pet as current if (mode == PET_SAVE_AS_CURRENT && p_owner->GetTemporaryUnsummonedPetNumber() && p_owner->GetTemporaryUnsummonedPetNumber() != GetCharmInfo()->GetPetNumber()) - { mode = PET_SAVE_NOT_IN_SLOT; } + { + mode = PET_SAVE_NOT_IN_SLOT; + } if (mode == PET_SAVE_REAGENTS) { @@ -703,7 +715,9 @@ void Pet::Unsummon(PetSaveMode mode, Unit* owner /*= NULL*/) { Item* item = p_owner->StoreNewItem(dest, spellReagents->Reagent[i], true); if (p_owner->IsInWorld()) + { p_owner->SendNewItem(item, spellReagents->ReagentCount[i], true, false); + } } } } @@ -726,7 +740,9 @@ void Pet::Unsummon(PetSaveMode mode, Unit* owner /*= NULL*/) { case MINI_PET: if (p_owner) + { p_owner->SetMiniPet(NULL); + } break; case PROTECTOR_PET: case GUARDIAN_PET: @@ -918,11 +934,17 @@ void Pet::InitStatsForLevel(uint32 petlevel) { float scale; if (getLevel() >= cFamily->maxScaleLevel) + { scale = cFamily->maxScale; + } else if (getLevel() <= cFamily->minScaleLevel) + { scale = cFamily->minScale; + } else + { scale = cFamily->minScale + float(getLevel() - cFamily->minScaleLevel) / cFamily->maxScaleLevel * (cFamily->maxScale - cFamily->minScale); + } SetObjectScale(scale); UpdateModelData(); @@ -930,7 +952,9 @@ void Pet::InitStatsForLevel(uint32 petlevel) // Max level if (petlevel < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) + { SetUInt32Value(UNIT_FIELD_PETNEXTLEVELEXP, sObjectMgr.GetXPForPetLevel(petlevel)); + } else { SetUInt32Value(UNIT_FIELD_PETEXPERIENCE, 0); @@ -1142,7 +1166,9 @@ void Pet::InitStatsForLevel(uint32 petlevel) health *= cInfo->HealthMultiplier; if (mana > 0) + { mana *= cInfo->PowerMultiplier; + } armor *= cInfo->ArmorMultiplier; } @@ -1155,7 +1181,9 @@ void Pet::InitStatsForLevel(uint32 petlevel) // A pet cannot not have health if (health < 1) + { health = 1; + } // Set health SetCreateHealth(health); @@ -1223,7 +1251,9 @@ uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel) } // -15 or less else - { return 0; } // food too low level + { + return 0; // food too low level + } } void Pet::_LoadSpellCooldowns() @@ -1426,7 +1456,9 @@ void Pet::_LoadAuras(uint32 timediff) if (procCharges) { if (remaincharges <= 0 || remaincharges > procCharges) + { remaincharges = procCharges; + } } else { @@ -1439,7 +1471,9 @@ void Pet::_LoadAuras(uint32 timediff) stackcount = 1; } else if (defstackamount < stackcount) + { stackcount = defstackamount; + } else if (!stackcount) { stackcount = 1; @@ -1509,7 +1543,9 @@ void Pet::_SaveAuras() SpellEntry const* spellInfo = holder->GetSpellProto(); SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!effectEntry) + { continue; + } if (effectEntry->EffectApplyAuraName == SPELL_AURA_MOD_STEALTH || effectEntry->Effect == SPELL_EFFECT_APPLY_AREA_AURA_OWNER || @@ -1658,11 +1694,15 @@ bool Pet::addSpell(uint32 spell_id, ActiveStates active /*= ACT_DECIDE*/, PetSpe // skip learning spell and no rank spell case uint32 rankSpellId = talentInfo->RankID[i]; if (!rankSpellId || rankSpellId == spell_id) + { continue; + } // skip unknown ranks if (!HasSpell(rankSpellId)) + { continue; + } removeSpell(rankSpellId, false, false); } } @@ -1681,7 +1721,9 @@ bool Pet::addSpell(uint32 spell_id, ActiveStates active /*= ACT_DECIDE*/, PetSpe newspell.active = itr2->second.active; if (newspell.active == ACT_ENABLED) + { ToggleAutocast(itr2->first, false); + } oldspell_id = itr2->first; unlearnSpell(itr2->first, false, false); @@ -1738,7 +1780,9 @@ bool Pet::learnSpell(uint32 spell_id) data << uint32(spell_id); ((Player*)owner)->GetSession()->SendPacket(&data); - { ((Player*)owner)->PetSpellInitialize(); } + { + ((Player*)owner)->PetSpellInitialize(); + } } } return true; @@ -1755,10 +1799,14 @@ void Pet::InitLevelupSpellsForLevel() { // will called first if level down if (itr->first > level) + { unlearnSpell(itr->second, true); // will learn prev rank if any + } // will called if level up else + { learnSpell(itr->second); // will unlearn prev rank if any + } } } @@ -1771,14 +1819,20 @@ void Pet::InitLevelupSpellsForLevel() { SpellEntry const* spellEntry = sSpellStore.LookupEntry(defSpells->spellid[i]); if (!spellEntry) + { continue; + } // will called first if level down if(spellEntry->GetSpellLevel() > level) + { unlearnSpell(spellEntry->Id, true); + } // will called if level up else + { learnSpell(spellEntry->Id); + } } } } @@ -1799,7 +1853,9 @@ bool Pet::unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab) } } } - { return true; } + { + return true; + } } return false; } @@ -1832,9 +1888,13 @@ bool Pet::removeSpell(uint32 spell_id, bool learn_prev, bool clear_ab) if (talentCost > 0) { if (m_usedTalentCount > talentCost) + { m_usedTalentCount -= talentCost; + } else + { m_usedTalentCount = 0; + } UpdateFreeTalentPoints(false); } @@ -1899,7 +1959,9 @@ bool Pet::resetTalents(bool no_cost) // not need after this call if (((Player*)owner)->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS)) + { ((Player*)owner)->RemoveAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS, true); + } CreatureInfo const* ci = GetCreatureInfo(); if (!ci) @@ -1943,15 +2005,21 @@ bool Pet::resetTalents(bool no_cost) TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) + { continue; + } // unlearn only talents for pets family talent type if (!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask)) + { continue; + } for (int j = 0; j < MAX_TALENT_RANK; ++j) if (talentInfo->RankID[j]) + { removeSpell(talentInfo->RankID[j], !IsPassiveSpell(talentInfo->RankID[j]), false); + } } UpdateFreeTalentPoints(false); @@ -1971,11 +2039,15 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= NULL*/) { // not need after this call if (((Player*)owner)->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS)) + { ((Player*)owner)->RemoveAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS, true); + } // reset for online if (online_pet) + { online_pet->resetTalents(true); + } // now need only reset for offline pets (all pets except online case) uint32 except_petnumber = online_pet ? online_pet->GetCharmInfo()->GetPetNumber() : 0; @@ -2012,7 +2084,9 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= NULL*/) uint32 id = fields[0].GetUInt32(); if (need_comma) + { ss << ","; + } ss << id; @@ -2032,10 +2106,14 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= NULL*/) uint32 spell = fields[0].GetUInt32(); if (!GetTalentSpellCost(spell)) + { continue; + } if (need_execute) + { ss << ","; + } ss << spell; @@ -2067,15 +2145,23 @@ void Pet::UpdateFreeTalentPoints(bool resetIfNeed) { Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER || ((Player*)owner)->GetSession()->GetSecurity() < SEC_ADMINISTRATOR) + { resetTalents(true); + } else + { SetFreeTalentPoints(0); + } } else + { SetFreeTalentPoints(0); + } } else + { SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount); + } } void Pet::InitTalentForLevel() @@ -2089,7 +2175,9 @@ void Pet::InitTalentForLevel() } if (!m_loading) + { ((Player*)owner)->SendTalentsInfoData(true); + } } uint32 Pet::resetTalentsCost() const @@ -2123,7 +2211,9 @@ uint8 Pet::GetMaxTalentPointsForLevel(uint32 level) uint8 points = (level >= 20) ? ((level - 16) / 4) : 0; // Mod points from owner SPELL_AURA_MOD_PET_TALENT_POINTS if (Unit* owner = GetOwner()) + { points += owner->GetTotalAuraModifier(SPELL_AURA_MOD_PET_TALENT_POINTS); + } return points; } @@ -2142,7 +2232,9 @@ void Pet::ToggleAutocast(uint32 spellid, bool apply) if (apply) { for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; ++i) - { ; } // just search + { + ; // just search + } if (i == m_autospells.size()) { @@ -2162,7 +2254,9 @@ void Pet::ToggleAutocast(uint32 spellid, bool apply) { AutoSpellList::iterator itr2 = m_autospells.begin(); for (i = 0; i < m_autospells.size() && m_autospells[i] != spellid; ++i, ++itr2) - { ; } // just search + { + ; // just search + } if (i < m_autospells.size()) { @@ -2361,7 +2455,9 @@ void Pet::SynchronizeLevelWithOwner() GivePetLevel(owner->getLevel()); } else if (getLevel() + 5 < owner->getLevel()) + { GivePetLevel(owner->getLevel() - 5); + } break; default: break; @@ -2407,9 +2503,13 @@ void Pet::SetStayPosition(bool stay) void Pet::ApplyModeFlags(PetModeFlags mode, bool apply) { if (apply) + { m_petModeFlags = PetModeFlags(m_petModeFlags | mode); + } else + { m_petModeFlags = PetModeFlags(m_petModeFlags & ~mode); + } Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) diff --git a/src/game/Object/Pet.h b/src/game/Object/Pet.h index 7e8571205..973aa6e36 100644 --- a/src/game/Object/Pet.h +++ b/src/game/Object/Pet.h @@ -166,18 +166,26 @@ class Pet : public Creature uint32 GetPetAutoSpellOnPos(uint8 pos) const override { if (pos >= m_autospells.size()) + { return 0; + } else + { return m_autospells[pos]; + } } virtual bool CanSwim() const override { Unit const* owner = GetOwner(); if (owner) + { return owner->GetTypeId() == TYPEID_PLAYER ? true : ((Creature const*)owner)->CanSwim(); + } else + { return Creature::CanSwim(); + } } void RegenerateAll(uint32 update_diff) override; // overwrite Creature::RegenerateAll diff --git a/src/game/Object/PetAI.cpp b/src/game/Object/PetAI.cpp index a439aedac..c92f64cf2 100644 --- a/src/game/Object/PetAI.cpp +++ b/src/game/Object/PetAI.cpp @@ -71,7 +71,9 @@ void PetAI::MoveInLineOfSight(Unit* pWho) AttackStart(pWho); if (Unit* owner = m_creature->GetOwner()) + { owner->SetInCombatState(true, pWho); + } } } } @@ -90,7 +92,9 @@ void PetAI::AttackStart(Unit* u) // hope it doesn't start to leak memory without this :-/ // i_pet->Clear(); if (!m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE)) + { HandleMovementOnAttackStart(u); + } inCombat = true; } @@ -145,7 +149,9 @@ void PetAI::UpdateAI(const uint32 diff) Unit* victim = NULL; if (!((Pet*)m_creature)->isControlled()) + { m_creature->SelectHostileTarget(); + } // Creature pets and guardians will always look in threat list for victim if (!(m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE) @@ -154,7 +160,9 @@ void PetAI::UpdateAI(const uint32 diff) if (m_updateAlliesTimer <= diff) // UpdateAllies self set update timer - { UpdateAllies(); } + { + UpdateAllies(); + } else { m_updateAlliesTimer -= diff; @@ -171,12 +179,16 @@ void PetAI::UpdateAI(const uint32 diff) if (!owner->IsWithinDistInMap(m_creature, (PET_FOLLOW_DIST * 2))) { if (!m_creature->hasUnitState(UNIT_STAT_FOLLOW)) + { m_creature->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); + } return; } else - ((Pet*)m_creature)->SetIsRetreating(); + { + ((Pet*)m_creature)->SetIsRetreating(); + } } else if (((Pet*)m_creature)->GetSpellOpener() != 0) // have opener stored { @@ -195,10 +207,14 @@ void PetAI::UpdateAI(const uint32 diff) m_creature->SetInFront(victim); if (victim->GetTypeId() == TYPEID_PLAYER) + { m_creature->SendCreateUpdateToPlayer((Player*)victim); + } if (owner->GetTypeId() == TYPEID_PLAYER) + { m_creature->SendCreateUpdateToPlayer((Player*)owner); + } uint32 spell_id = ((Pet*)m_creature)->GetSpellOpener(); SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); @@ -213,7 +229,9 @@ void PetAI::UpdateAI(const uint32 diff) spell->SpellStart(&(spell->m_targets)); } else + { delete spell; + } ((Pet*)m_creature)->SetSpellOpener(); } @@ -280,7 +298,9 @@ void PetAI::UpdateAI(const uint32 diff) } // just ignore non-combat spells else if (IsNonCombatSpell(spellInfo)) + { continue; + } Spell* spell = new Spell(m_creature, spellInfo, false); @@ -357,7 +377,9 @@ void PetAI::UpdateAI(const uint32 diff) // Guardians will always look in threat list for victim if (!((Pet*)m_creature)->isControlled()) + { m_creature->SelectHostileTarget(); + } if (!(m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE) || (m_creature->IsPet() && ((Pet*)m_creature)->GetModeFlags() & PET_MODE_DISABLE_ACTIONS))) @@ -390,14 +412,20 @@ void PetAI::UpdateAI(const uint32 diff) { m_creature->SetInFront(victim); if (victim->GetTypeId() == TYPEID_PLAYER) + { m_creature->SendCreateUpdateToPlayer((Player*)victim); + } if (owner && owner->GetTypeId() == TYPEID_PLAYER) + { m_creature->SendCreateUpdateToPlayer((Player*)owner); + } } if (DoMeleeAttackIfReady()) + { victim->AddThreat(m_creature); + } } else if (!(m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE) || m_creature->hasUnitState(UNIT_STAT_MOVING))) @@ -418,7 +446,9 @@ void PetAI::UpdateAI(const uint32 diff) { //if stay command is set but we dont have stay pos set then we need to establish current pos as stay position if (!pet->IsStayPosSet()) + { pet->SetStayPosition(true); + } float stayPosX = pet->GetStayPosX(); float stayPosY = pet->GetStayPosY(); @@ -436,10 +466,14 @@ void PetAI::UpdateAI(const uint32 diff) m_creature->GetMotionMaster()->MoveIdle(); } else if (m_creature->GetOrientation() != StayPosO) + { m_creature->SetOrientation(StayPosO); + } } else + { pet->GetMotionMaster()->MovePoint(0, stayPosX, stayPosY, stayPosZ, false); + } } } else if (m_creature->hasUnitState(UNIT_STAT_FOLLOW)) @@ -522,5 +556,7 @@ void PetAI::AttackedBy(Unit* attacker) if (!(m_creature->getVictim() || ((Pet*)m_creature)->GetIsRetreating() == true) && !(m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE) || (m_creature->GetCharmInfo() && m_creature->GetCharmInfo()->HasReactState(REACT_PASSIVE)))) - { AttackStart(attacker); } + { + AttackStart(attacker); + } } diff --git a/src/game/Object/Player.cpp b/src/game/Object/Player.cpp index e29067914..24ac6d71f 100644 --- a/src/game/Object/Player.cpp +++ b/src/game/Object/Player.cpp @@ -181,7 +181,9 @@ void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 leve } // level dependent taxi hubs if (level >= 68) + { SetTaximaskNode(213); // Shattered Sun Staging Area + } } void PlayerTaxi::LoadTaxiMask(const char* data) @@ -190,8 +192,7 @@ void PlayerTaxi::LoadTaxiMask(const char* data) int index; Tokens::iterator iter; - for (iter = tokens.begin(), index = 0; - (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index) + for (iter = tokens.begin(), index = 0; (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index) { // load and set bits only for existing taxi nodes m_taximask[index] = sTaxiNodesMask[index] & uint8(std::stoul((*iter).c_str())); @@ -204,12 +205,16 @@ void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) if (all) { for (uint8 i = 0; i < TaxiMaskSize; ++i) + { data << uint8(sTaxiNodesMask[i]); // all existing nodes + } } else { for (uint8 i = 0; i < TaxiMaskSize; ++i) + { data << uint8(m_taximask[i]); // known nodes + } } } @@ -291,7 +296,9 @@ uint32 PlayerTaxi::GetCurrentTaxiPath() const std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi) { for (int i = 0; i < TaxiMaskSize; ++i) + { ss << uint32(taxi.m_taximask[i]) << " "; // cast to prevent conversion to char + } return ss; } //== TradeData ================================================= @@ -391,9 +398,13 @@ void TradeData::SetMoney(uint64 money) void TradeData::Update(bool for_trader /*= true*/) { if (for_trader) - { m_trader->GetSession()->SendUpdateTrade(true); } // player state for trader + { + m_trader->GetSession()->SendUpdateTrade(true); // player state for trader + } else - { m_player->GetSession()->SendUpdateTrade(false); } // player state for player + { + m_player->GetSession()->SendUpdateTrade(false); // player state for player + } } void TradeData::SetAccepted(bool state, bool crosssend /*= false*/) @@ -640,7 +651,9 @@ Player::~Player() } for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter) - { delete iter->second; } // if item is duplicated... then server may crash ... but that item should be deallocated + { + delete iter->second; // if item is duplicated... then server may crash ... but that item should be deallocated + } delete PlayerTalkClass; @@ -757,7 +770,9 @@ bool Player::Create(uint32 guidlow, const std::string& name, uint8 race, uint8 c SetUInt32Value(PLAYER_GUILD_TIMESTAMP, 0); for (int i = 0; i < KNOWN_TITLES_SIZE; ++i) + { SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES + i, 0); // 0=disabled + } SetUInt32Value(PLAYER_CHOSEN_TITLE, 0); SetUInt32Value(PLAYER_FIELD_KILLS, 0); @@ -772,7 +787,9 @@ bool Player::Create(uint32 guidlow, const std::string& name, uint8 race, uint8 c { uint32 gm_level = sWorld.getConfig(CONFIG_UINT32_START_GM_LEVEL); if (gm_level > start_level) + { start_level = gm_level; + } } SetUInt32Value(UNIT_FIELD_LEVEL, start_level); @@ -870,7 +887,9 @@ bool Player::Create(uint32 guidlow, const std::string& name, uint8 race, uint8 c break; } if (iProto->Stackable < count) + { count = iProto->Stackable; + } } StoreNewItemInBestSlots(item_id, count); @@ -920,7 +939,9 @@ bool Player::Create(uint32 guidlow, const std::string& name, uint8 race, uint8 c // all item positions resolved if (info->phaseMap != 0) + { CharacterDatabase.PExecute("REPLACE INTO `character_phase_data` (`guid`, `map`) VALUES (%u, %u)", guidlow, info->phaseMap); + } return true; } @@ -945,7 +966,9 @@ bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) } if (titem_amount == 0) - { return true; } // equipped + { + return true; // equipped + } // attempt store ItemPosCountVec sDest; @@ -1041,7 +1064,9 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) DamageEffectType damageType = SELF_DAMAGE; if (type == DAMAGE_FALL && getClass() == CLASS_ROGUE) + { damageType = SELF_DAMAGE_ROGUE_FALL; + } uint32 final_damage = DealDamage(this, damage, NULL, damageType, SPELL_SCHOOL_MASK_NORMAL, NULL, false); @@ -1076,7 +1101,9 @@ int32 Player::getMaxTimer(MirrorTimerType timer) { if (!IsAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL)) - { return DISABLED_MIRROR_TIMER; } + { + return DISABLED_MIRROR_TIMER; + } int32 UnderWaterTime = sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX) * IN_MILLISECONDS; AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING); for (AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i) @@ -1277,10 +1304,14 @@ DrunkenState Player::GetDrunkenstateByValue(uint8 value) void Player::SetDrunkValue(uint8 newDrunkValue, uint32 itemId /*= 0*/) { if (newDrunkValue > 100) + { newDrunkValue = 100; + } if (newDrunkValue < GetDrunkValue()) + { m_drunkTimer = 0; // reset sobering timer + } uint32 oldDrunkenState = Player::GetDrunkenstateByValue(GetDrunkValue()); @@ -1290,9 +1321,13 @@ void Player::SetDrunkValue(uint8 newDrunkValue, uint32 itemId /*= 0*/) // special drunk invisibility detection if (newDrunkenState >= DRUNKEN_DRUNK) + { m_detectInvisibilityMask |= (1 << 6); + } else + { m_detectInvisibilityMask &= ~(1 << 6); + } if (newDrunkenState == oldDrunkenState) { @@ -1334,7 +1369,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) // Update player only attacks if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK)) + { setAttackTimer(RANGED_ATTACK, (update_diff >= ranged_att ? 0 : ranged_att - update_diff)); + } time_t now = time(NULL); @@ -1350,7 +1387,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) // Update items that have just a limited lifetime if (now > m_Last_tick) + { UpdateItemDuration(uint32(now - m_Last_tick)); + } if (!m_timedquests.empty()) { @@ -1368,7 +1407,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) { q_status.m_timer -= update_diff; if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED; - ++iter; + { + ++iter; + } } } } @@ -1405,25 +1446,37 @@ void Player::Update(uint32 update_diff, uint32 p_time) if (m_regenTimer) { if (update_diff >= m_regenTimer) + { m_regenTimer = 0; + } else + { m_regenTimer -= update_diff; + } } if (m_positionStatusUpdateTimer) { if (update_diff >= m_positionStatusUpdateTimer) + { m_positionStatusUpdateTimer = 0; + } else + { m_positionStatusUpdateTimer -= update_diff; + } } if (m_weaponChangeTimer > 0) { if (update_diff >= m_weaponChangeTimer) + { m_weaponChangeTimer = 0; + } else + { m_weaponChangeTimer -= update_diff; + } } if (m_zoneUpdateTimer > 0) @@ -1434,40 +1487,56 @@ void Player::Update(uint32 update_diff, uint32 p_time) GetZoneAndAreaId(newzone, newarea); if (m_zoneUpdateId != newzone) + { UpdateZone(newzone, newarea); // Also update area + } else { // Use area updates as well // Needed for free for all arenas for example if (m_areaUpdateId != newarea) + { UpdateArea(newarea); + } m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL; } } else + { m_zoneUpdateTimer -= update_diff; + } } if (m_timeSyncTimer > 0) { if (update_diff >= m_timeSyncTimer) + { SendTimeSync(); + } else + { m_timeSyncTimer -= update_diff; + } } if (IsAlive()) { if (!HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN)) + { SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER); + } if (!m_regenTimer) + { RegenerateAll(); + } } if (m_deathState == JUST_DIED) + { KillPlayer(); + } if (m_nextSave > 0) { @@ -1478,7 +1547,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) DETAIL_LOG("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow()); } else + { m_nextSave -= update_diff; + } } // Handle Water/drowning @@ -1493,7 +1564,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) m_DetectInvTimer = 3000; } else + { m_DetectInvTimer -= update_diff; + } } // Played time @@ -1510,7 +1583,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) m_drunkTimer += update_diff; if (m_drunkTimer > 9 * IN_MILLISECONDS) + { HandleSobering(); + } } // Not auto-free ghost from body in instances; also check for resurrection prevention @@ -1523,7 +1598,9 @@ void Player::Update(uint32 update_diff, uint32 p_time) RepopAtGraveyard(); } else + { m_deathTimer -= p_time; + } } UpdateEnchantTime(update_diff); @@ -1534,10 +1611,14 @@ void Player::Update(uint32 update_diff, uint32 p_time) Pet* pet = GetPet(); if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGuid() && (pet->GetObjectGuid() != GetCharmGuid()))) + { pet->Unsummon(PET_SAVE_REAGENTS, this); + } if (IsHasDelayedTeleport()) + { TeleportTo(m_teleport_dest, m_teleport_options); + } } void Player::SetDeathState(DeathState s) @@ -1566,21 +1647,27 @@ void Player::SetDeathState(DeathState s) // passive spell if (!ressSpellId) + { ressSpellId = GetResurrectionSpellId(); + } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1); if (InstanceData* mapInstance = GetInstanceData()) + { mapInstance->OnPlayerDeath(this); + } } Unit::SetDeathState(s); // restore resurrection spell id for player after aura remove if (s == JUST_DIED && cur && ressSpellId) + { SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); + } if (IsAlive() && !cur) { @@ -1589,7 +1676,9 @@ void Player::SetDeathState(DeathState s) // restore default warrior stance if (getClass() == CLASS_WARRIOR) + { CastSpell(this, SPELL_ID_PASSIVE_BATTLE_STANCE, true); + } } } @@ -1642,20 +1731,32 @@ bool Player::BuildEnumData(QueryResult* result, ByteBuffer* data, ByteBuffer* bu } if(playerFlags & PLAYER_FLAGS_HIDE_HELM) + { char_flags |= CHARACTER_FLAG_HIDE_HELM; + } if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK) + { char_flags |= CHARACTER_FLAG_HIDE_CLOAK; + } if(playerFlags & PLAYER_FLAGS_GHOST) + { char_flags |= CHARACTER_FLAG_GHOST; + } if(atLoginFlags & AT_LOGIN_RENAME) + { char_flags |= CHARACTER_FLAG_RENAME; + } if(sWorld.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED)) { if(!fields[21].GetCppString().empty()) + { char_flags |= CHARACTER_FLAG_DECLINED; + } } else + { char_flags |= CHARACTER_FLAG_DECLINED; + } data->WriteBit(guildGuid[4]); data->WriteBit(guid[0]); @@ -1722,10 +1823,14 @@ bool Player::BuildEnumData(QueryResult* result, ByteBuffer* data, ByteBuffer* bu // values stored in 2 uint16 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16); if(!enchantId) + { continue; + } if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))) + { break; + } } *buffer << uint32(enchant ? enchant->aura_id : 0); @@ -1792,7 +1897,9 @@ void Player::ToggleAFK() // afk player not allowed in battleground if (isAFK() && InBattleGround() && !InArena()) + { LeaveBattleground(); + } } void Player::ToggleDND() @@ -1805,15 +1912,25 @@ ChatTagFlags Player::GetChatTag() const ChatTagFlags tag = CHAT_TAG_NONE; if (isAFK()) + { tag |= CHAT_TAG_AFK; + } if (isDND()) + { tag |= CHAT_TAG_DND; + } if (isGMChat()) + { tag |= CHAT_TAG_GM; + } if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_COMMENTATOR)) + { tag |= CHAT_TAG_COM; + } if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DEVELOPER)) + { tag |= CHAT_TAG_DEV; + } return tag; } @@ -1829,12 +1946,16 @@ void Player::SendTeleportPacket(float oldX, float oldY, float oldZ, float oldO) data.WriteBit(!transportGuid.IsEmpty()); data.WriteGuidMask<1>(guid); if (transportGuid) + { data.WriteGuidMask<1, 3, 2, 5, 0, 7, 6, 4>(transportGuid); + } data.WriteGuidMask<4, 7, 5>(guid); if (transportGuid) + { data.WriteGuidBytes<5, 6, 1, 7, 0, 2, 4, 3>(transportGuid); + } data << uint32(0); // counter data.WriteGuidBytes<1, 2, 3, 5>(guid); @@ -1899,7 +2020,9 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // then he will repop near BootyBay instead of normally continuing his journey // This code is probably added to catch passengers on ships to northrend who shouldn't go there if (lockStatus == AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION && !assignedAreaTrigger && GetTransport()) + { RepopAtGraveyard(); // Teleport to near graveyard if on transport, looks blizz like :) + } SendTransferAbortedByLockStatus(mEntry, lockStatus, miscRequirement); return false; @@ -1907,7 +2030,9 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati } if (Group* grp = GetGroup()) // TODO: Verify that this is correct place + { grp->SetPlayerMap(GetObjectGuid(), mapid); + } // if we were on a transport, leave if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport) @@ -1922,7 +2047,9 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // ObjectAccessor won't find the flag. if (duel && GetMapId() != mapid) if (GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER))) + { DuelComplete(DUEL_FLED); + } // reset movement flags at teleport, because player will continue move with these flags after teleport m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); @@ -1948,11 +2075,15 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati { // same map, only remove pet if out of range for new position if (pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance())) + { UnsummonPetTemporaryIfAny(); + } } if (!(options & TELE_TO_NOT_LEAVE_COMBAT)) + { CombatStop(); + } // this will be used instead of the current location in SaveToDB m_teleport_dest = WorldLocation(mapid, x, y, z, orientation); @@ -2010,16 +2141,22 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // and we already will found "current" battleground // just need check that this is targeted map or leave if (bg->GetMapId() != mapid) + { LeaveBattleground(false); // don't teleport to entry point + } } // remove pet on map change if (pet) + { UnsummonPetTemporaryIfAny(); + } // remove vehicle accessories on map change if (IsVehicle()) + { GetVehicleInfo()->RemoveAccessoriesFromMap(); + } // remove all dyn objects RemoveAllDynObjects(); @@ -2028,7 +2165,9 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // not attempt interrupt teleportation spell at caster teleport if (!(options & TELE_TO_SPELL)) if (IsNonMeleeSpellCasted(true)) + { InterruptNonMeleeSpells(true); + } // remove auras before removing from map... RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING); @@ -2045,7 +2184,9 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati data << uint32(m_transport->GetEntry()); } else + { data.WriteBit(0); // has transport + } data << uint32(mapid); GetSession()->SendPacket(&data); @@ -2053,7 +2194,9 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati // remove from old map now if (oldmap) + { oldmap->Remove(this, false); + } // new final coordinates float final_x = x; @@ -2098,9 +2241,13 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati data << uint32(mapid); if (m_transport) + { data << float(m_movementInfo.GetTransportPos()->z); + } else + { data << float(final_z); + } GetSession()->SendPacket(&data); SendSavedInstances(); @@ -2133,14 +2280,22 @@ void Player::ProcessDelayedOperations() ResurrectPlayer(0.0f, false); if (GetMaxHealth() > m_resurrectHealth) + { SetHealth(m_resurrectHealth); + } else + { SetHealth(GetMaxHealth()); + } if (GetMaxPower(POWER_MANA) > m_resurrectMana) + { SetPower(POWER_MANA, m_resurrectMana); + } else + { SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); + } SetPower(POWER_RAGE, 0); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY)); @@ -2193,7 +2348,9 @@ void Player::AddToWorld() for (int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i) { if (m_items[i]) + { m_items[i]->AddToWorld(); + } } } @@ -2202,14 +2359,18 @@ void Player::RemoveFromWorld() for (int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i) { if (m_items[i]) + { m_items[i]->RemoveFromWorld(); + } } ///- Do not add/remove the player from the object storage ///- It will crash when updating the ObjectAccessor ///- The player should only be removed when logging out if (IsInWorld()) + { GetCamera().ResetView(); + } Unit::RemoveFromWorld(); } @@ -2233,7 +2394,9 @@ void Player::RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacke // Berserker Rage effect if (HasAura(18499, EFFECT_INDEX_0)) + { addRage *= 1.3f; + } } addRage *= sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME); @@ -2252,7 +2415,9 @@ void Player::RegenerateAll(uint32 diff) { Regenerate(POWER_RAGE, diff); if (getClass() == CLASS_DEATH_KNIGHT) + { Regenerate(POWER_RUNIC_POWER, diff); + } } } @@ -2261,22 +2426,34 @@ void Player::RegenerateAll(uint32 diff) Regenerate(POWER_MANA, diff); if (getClass() == CLASS_DEATH_KNIGHT) + { Regenerate(POWER_RUNE, diff); + } if (getClass() == CLASS_MONK) + { Regenerate(POWER_CHI, diff); + } if (getClass() == CLASS_HUNTER) + { Regenerate(POWER_FOCUS, diff); + } if (getClass() == CLASS_PALADIN) { if (IsInCombat()) + { ResetHolyPowerRegenTimer(); + } else if (m_holyPowerRegenTimer <= diff) + { m_holyPowerRegenTimer = 0; + } else + { m_holyPowerRegenTimer -= diff; + } if (!m_holyPowerRegenTimer) { @@ -2312,7 +2489,9 @@ void Player::Regenerate(Powers power, uint32 diff) case POWER_MANA: { if (HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN)) + { break; + } float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA); if (IsInCombat()) @@ -2337,7 +2516,9 @@ void Player::Regenerate(Powers power, uint32 diff) break; case POWER_HOLY_POWER: if (!m_holyPowerRegenTimer) + { addvalue = 1; + } else { return; @@ -2358,7 +2539,9 @@ void Player::Regenerate(Powers power, uint32 diff) case POWER_RUNE: { if (getClass() != CLASS_DEATH_KNIGHT) + { break; + } for (uint8 rune = 0; rune < MAX_RUNES; rune += 2) { @@ -2374,7 +2557,9 @@ void Player::Regenerate(Powers power, uint32 diff) } if (cd) + { SetRuneCooldown(rune, (cd < cd_diff) ? 0 : cd - cd_diff); + } } break; } @@ -2389,7 +2574,9 @@ void Player::Regenerate(Powers power, uint32 diff) AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for (AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) if ((*i)->GetModifier()->m_miscvalue == int32(power)) + { addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f; + } } // addvalue computed on a 2sec basis. => update to diff time @@ -2399,14 +2586,20 @@ void Player::Regenerate(Powers power, uint32 diff) { curValue += uint32(addvalue); if (curValue > maxValue) + { curValue = maxValue; + } } else { if (curValue <= uint32(addvalue)) + { curValue = 0; + } else + { curValue -= uint32(addvalue); + } } SetPower(power, curValue); } @@ -2426,7 +2619,9 @@ void Player::RegenerateHealth(uint32 diff) // polymorphed case if (IsPolymorphed()) + { addvalue = (float)GetMaxHealth() / 3; + } // normal regen case (maybe partly in combat case) else if (!IsInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT)) { @@ -2434,9 +2629,13 @@ void Player::RegenerateHealth(uint32 diff) if (!IsInCombat()) { if (getLevel() < 15) + { addvalue = 0.20f * GetMaxHealth() * addvalue / getLevel(); + } else + { addvalue = 0.015f * GetMaxHealth() * addvalue; + } AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT); for (AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i) @@ -2447,10 +2646,14 @@ void Player::RegenerateHealth(uint32 diff) addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 2.0f / 5.0f; } else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT)) + { addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f; + } if (!IsStandState()) + { addvalue *= 1.33f; + } } // always regeneration bonus (including combat) @@ -2459,7 +2662,9 @@ void Player::RegenerateHealth(uint32 diff) addvalue += m_baseHealthRegen / 2.5f; if (addvalue < 0) + { addvalue = 0; + } addvalue *= (float)diff / REGEN_TIME_FULL; @@ -2646,17 +2851,25 @@ void Player::SetGameMaster(bool on) AuraList const& phases2 = GetAurasByType(SPELL_AURA_PHASE_2); if (!phases.empty()) + { SetPhaseMask(phases.front()->GetMiscValue(), false); + } else if (!phases2.empty()) + { SetPhaseMask(phases2.front()->GetMiscValue(), false); + } else + { SetPhaseMask(PHASEMASK_NORMAL, false); + } CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); // restore FFA PvP Server state if (sWorld.IsFFAPvPRealm()) + { SetFFAPvP(true); + } // restore FFA PvP area state, remove not allowed for GM mounts UpdateArea(m_areaUpdateId); @@ -2677,11 +2890,17 @@ void Player::SetGMVisible(bool on) // Reapply stealth/invisibility if active or show if not any if (HasAuraType(SPELL_AURA_MOD_STEALTH)) + { SetVisibility(VISIBILITY_GROUP_STEALTH); + } else if (HasAuraType(SPELL_AURA_MOD_INVISIBILITY)) + { SetVisibility(VISIBILITY_GROUP_INVISIBILITY); + } else + { SetVisibility(VISIBILITY_ON); + } } else { @@ -2730,7 +2949,9 @@ void Player::UninviteFromGroup() sObjectMgr.RemoveGroup(group); } else + { group->RemoveAllInvites(); + } delete group; } @@ -2828,7 +3049,9 @@ void Player::GiveXP(uint32 xp, Unit* victim) newXP -= nextLvlXP; if (level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) + { GiveLevel(level + 1); + } level = getLevel(); nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP); @@ -2898,21 +3121,29 @@ void Player::GiveLevel(uint32 level) // set current level health and mana/energy to maximum after applying all mods. if (IsAlive()) + { SetHealth(GetMaxHealth()); + } SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY)); if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE)) + { SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE)); + } SetPower(POWER_FOCUS, 0); _ApplyAllLevelScaleItemMods(true); // update level to hunter/summon pet if (Pet* pet = GetPet()) + { pet->SynchronizeLevelWithOwner(); + } if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level, getRaceMask())) + { MailDraft(mailReward->mailTemplateId).SendMailTo(this, MailSender(MAIL_CREATURE, mailReward->senderEntry)); + } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL); @@ -2935,7 +3166,9 @@ void Player::UpdateFreeTalentPoints(bool resetIfNeed) if (m_usedTalentCount > 0) // Free any used talents { if (resetIfNeed) + { resetTalents(true); + } SetFreeTalentPoints(0); } } @@ -2953,13 +3186,19 @@ void Player::UpdateFreeTalentPoints(bool resetIfNeed) if (m_usedTalentCount > talentPointsForLevel) { if (resetIfNeed && GetSession()->GetSecurity() < SEC_ADMINISTRATOR) + { resetTalents(true); + } else + { SetFreeTalentPoints(0); + } } // else update amount of free points else + { SetFreeTalentPoints(talentPointsForLevel - m_usedTalentCount); + } } } @@ -2968,13 +3207,17 @@ void Player::InitTalentForLevel() UpdateFreeTalentPoints(); if (!GetSession()->PlayerLoading()) + { SendTalentsInfoData(false); // update at client + } } void Player::InitStatsForLevel(bool reapplyMods) { if (reapplyMods) // reapply stats values only on .reset stats (level) command + { _RemoveAllStatBonuses(); + } uint32 basehp = 0, basemana = 0; sObjectMgr.GetPlayerClassLevelInfo(getClass(), getLevel(), basehp, basemana); @@ -3131,20 +3374,26 @@ void Player::InitStatsForLevel(bool reapplyMods) //SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default if (reapplyMods) // reapply stats values only on .reset stats (level) command + { _ApplyAllStatBonuses(); + } // set current level health and mana/energy to maximum after applying all mods. SetHealth(GetMaxHealth()); SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY)); if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE)) + { SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE)); + } SetPower(POWER_FOCUS, 0); SetPower(POWER_RUNIC_POWER, 0); // update level to hunter/summon pet if (Pet* pet = GetPet()) + { pet->SynchronizeLevelWithOwner(); + } } void Player::SendInitialSpells() @@ -3163,10 +3412,14 @@ void Player::SendInitialSpells() for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) + { continue; + } if (!itr->second.active || itr->second.disabled) + { continue; + } data << uint32(itr->first); data << uint16(0); // it's not slot id @@ -3182,7 +3435,9 @@ void Player::SendInitialSpells() { SpellEntry const* sEntry = sSpellStore.LookupEntry(itr->first); if (!sEntry) + { continue; + } data << uint32(itr->first); @@ -3236,7 +3491,9 @@ void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResp data << (uint32) mailAction; data << (uint32) mailError; if (mailError == MAIL_ERR_EQUIP_ERROR) + { data << (uint32) equipError; + } else if (mailAction == MAIL_ITEM_TAKEN) { data << (uint32) item_guid; // item guid low? @@ -3265,10 +3522,14 @@ void Player::UpdateNextMailTimeAndUnreads() if ((*itr)->deliver_time > cTime) { if (!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time) + { m_nextMailDelivereTime = (*itr)->deliver_time; + } } else if (((*itr)->checked & MAIL_CHECK_MASK_READ) == 0) + { ++unReadMails; + } } } @@ -3282,7 +3543,9 @@ void Player::AddNewMailDeliverTime(time_t deliver_time) else // not ready and no have ready mails { if (!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time) + { m_nextMailDelivereTime = deliver_time; + } } } @@ -3298,7 +3561,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen CharacterDatabase.PExecute("DELETE FROM `character_spell` WHERE `spell` = '%u'", spell_id); } else + { sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request.", spell_id); + } return false; } @@ -3312,7 +3577,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen CharacterDatabase.PExecute("DELETE FROM `character_spell` WHERE `spell` = '%u'", spell_id); } else + { sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.", spell_id); + } return false; } @@ -3349,7 +3616,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen itr->second.dependent == dependent && itr->second.disabled == disabled) { if (!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly + { itr->second.state = PLAYERSPELL_UNCHANGED; + } return false; } @@ -3359,7 +3628,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen { itr->second.dependent = dependent; if (itr->second.state != PLAYERSPELL_NEW) + { itr->second.state = PLAYERSPELL_CHANGED; + } dependent_set = true; } @@ -3369,14 +3640,20 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen itr->second.active = active; if (!IsInWorld() && !learning && !dependent_set)// explicitly load from DB and then exist in it already and set correctly + { itr->second.state = PLAYERSPELL_UNCHANGED; + } else if (itr->second.state != PLAYERSPELL_NEW) + { itr->second.state = PLAYERSPELL_CHANGED; + } if (active) { if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo)) + { CastSpell(this, spell_id, true); + } } else if (IsInWorld()) { @@ -3402,7 +3679,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen if (itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED) { if (itr->second.state != PLAYERSPELL_NEW) + { itr->second.state = PLAYERSPELL_CHANGED; + } itr->second.disabled = disabled; if (disabled) @@ -3426,7 +3705,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen { // can be in case spell loading but learned at some previous spell loading if (!IsInWorld() && !learning && !dependent_set) + { itr->second.state = PLAYERSPELL_UNCHANGED; + } return false; } @@ -3447,7 +3728,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen // skip learning spell and no rank spell case uint32 rankSpellId = talentInfo->RankID[i]; if (!rankSpellId || rankSpellId == spell_id) + { continue; + } removeSpell(rankSpellId, false, false); } @@ -3457,9 +3740,13 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen else if (uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id)) { if (!IsInWorld() || disabled) // at spells loading, no output, but allow save + { addSpell(prev_spell, active, true, true, disabled); + } else // at normal learning + { learnSpell(prev_spell, true); + } } PlayerSpell newspell; @@ -3473,9 +3760,16 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen { for (PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2) { - if (itr2->second.state == PLAYERSPELL_REMOVED) continue; + if (itr2->second.state == PLAYERSPELL_REMOVED) + { + continue; + } SpellEntry const* i_spellInfo = sSpellStore.LookupEntry(itr2->first); - if (!i_spellInfo) continue; + + if (!i_spellInfo) + { + continue; + } if (sSpellMgr.IsRankSpellDueToSpell(spellInfo, itr2->first)) { @@ -3494,7 +3788,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new) itr2->second.active = false; if (itr2->second.state != PLAYERSPELL_NEW) + { itr2->second.state = PLAYERSPELL_CHANGED; + } superceded_old = true; // new spell replace old in action bars and spell book. } else if (sSpellMgr.IsHighRankOfSpell(itr2->first, spell_id)) @@ -3510,7 +3806,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen // mark new spell as disable (not learned yet for client and will not learned) newspell.active = false; if (newspell.state != PLAYERSPELL_NEW) + { newspell.state = PLAYERSPELL_CHANGED; + } } } } @@ -3538,7 +3836,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen (*iter).second.currentRank = talentPos->rank; if ((*iter).second.state != PLAYERSPELL_NEW) + { (*iter).second.state = PLAYERSPELL_CHANGED; + } } } else @@ -3559,7 +3859,9 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen if (uint32 freeProfs = GetFreePrimaryProfessionPoints()) { if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id)) + { SetFreePrimaryProfessions(freeProfs - 1); + } } // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned) @@ -3593,12 +3895,16 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill); if (skill_value < spellLearnSkill->value) + { skill_value = spellLearnSkill->value; + } uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue; if (skill_max_value < new_skill_max_value) + { skill_max_value = new_skill_max_value; + } SetSkill(spellLearnSkill->skill, skill_value, skill_max_value, spellLearnSkill->step); } @@ -3609,10 +3915,14 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen { SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId); if (!pSkill) + { continue; + } if (HasSkill(pSkill->id)) + { continue; + } if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL || // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL @@ -3644,9 +3954,13 @@ bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependen if (!itr2->second.autoLearned) { if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save + { addSpell(itr2->second.spell, itr2->second.active, true, true, false); + } else // at normal learning + { learnSpell(itr2->second.spell, true); + } } } @@ -3671,7 +3985,9 @@ bool Player::IsNeedCastPassiveLikeSpellAtLearn(SpellEntry const* spellInfo) cons ShapeshiftForm form = GetShapeshiftForm(); if (IsNeedCastSpellAtFormApply(spellInfo, form)) // SPELL_ATTR_PASSIVE | SPELL_ATTR_UNK7 spells + { return true; // all stance req. cases, not have auarastate cases + } if (!spellInfo->HasAttribute(SPELL_ATTR_PASSIVE)) { @@ -3714,12 +4030,16 @@ void Player::learnSpell(uint32 spell_id, bool dependent) { PlayerSpellMap::iterator iter = m_spells.find(i->second); if (iter != m_spells.end() && iter->second.disabled) + { learnSpell(i->second, false); + } } } if (IsInWorld()) + { SpellAddedQuestCheck(spell_id); + } } void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate) @@ -3739,12 +4059,16 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext(); for (SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2) if (HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second)) + { removeSpell(itr2->second, disabled, false); + } // re-search, it can be corrupted in prev loop itr = m_spells.find(spell_id); if (itr == m_spells.end() || itr->second.state == PLAYERSPELL_REMOVED) + { return; // already unleared + } bool cur_active = itr->second.active; bool cur_dependent = itr->second.dependent; @@ -3753,14 +4077,20 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo { itr->second.disabled = disabled; if (itr->second.state != PLAYERSPELL_NEW) + { itr->second.state = PLAYERSPELL_CHANGED; + } } else { if (itr->second.state == PLAYERSPELL_NEW) + { m_spells.erase(itr); + } else + { itr->second.state = PLAYERSPELL_REMOVED; + } } RemoveAurasDueToSpell(spell_id); @@ -3768,7 +4098,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo // remove pet auras for (int i = 0; i < MAX_EFFECT_INDEX; ++i) if (PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i))) + { RemovePetAura(petSpell); + } TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id); if (talentPos) @@ -3778,20 +4110,30 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo if (iter != m_talents[m_activeSpec].end()) { if ((*iter).second.state != PLAYERSPELL_NEW) + { (*iter).second.state = PLAYERSPELL_REMOVED; + } else + { m_talents[m_activeSpec].erase(iter); + } } else + { sLog.outError("removeSpell: Player (GUID: %u) has talent spell (id: %u) but doesn't have talent", GetGUIDLow(), spell_id); + } // free talent points uint32 talentCosts = GetTalentSpellCost(talentPos); if (talentCosts < m_usedTalentCount) + { m_usedTalentCount -= talentCosts; + } else + { m_usedTalentCount = 0; + } UpdateFreeTalentPoints(false); } @@ -3802,7 +4144,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo uint32 freeProfs = GetFreePrimaryProfessionPoints() + 1; uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT)) ? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10; if (freeProfs <= maxProfs) + { SetFreePrimaryProfessions(freeProfs); + } } // remove dependent skill @@ -3811,7 +4155,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo { uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id); if (!prev_spell) // first rank, remove skill + { SetSkill(spellLearnSkill->skill, 0, 0); + } else { // search prev. skill setting by spell ranks chain @@ -3823,19 +4169,25 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo } if (!prevSkill) // not found prev skill setting, remove skill + { SetSkill(spellLearnSkill->skill, 0, 0); + } else // set to prev. skill setting values { uint32 skill_value = GetPureSkillValue(prevSkill->skill); uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill); if (skill_value > prevSkill->value) + { skill_value = prevSkill->value; + } uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue; if (skill_max_value > new_skill_max_value) + { skill_max_value = new_skill_max_value; + } SetSkill(prevSkill->skill, skill_value, skill_max_value, prevSkill->step); } @@ -3850,7 +4202,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo { SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId); if (!pSkill) + { continue; + } if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL && pSkill->categoryId != SKILL_CATEGORY_CLASS) ||// not unlearn class skills (spellbook/talent pages) @@ -3886,7 +4240,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo if (talentPos) { if (learn_low_rank) + { learnSpell(prev_id, false); + } } // if ranked non-stackable spell: need activate lesser rank and update dependence state else if (cur_active && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo)) @@ -3900,7 +4256,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo { spell.dependent = cur_dependent; if (spell.state != PLAYERSPELL_NEW) + { spell.state = PLAYERSPELL_CHANGED; + } } // now re-learn if need re-activate @@ -3926,7 +4284,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (CanDualWield() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_DUAL_WIELD)) + { SetCanDualWield(false); + } if (CanTitanGrip() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_TITAN_GRIP)) { @@ -3938,7 +4298,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo // for talents and normal spell unlearn that allow offhand use for some weapons if (sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET)) + { AutoUnequipOffhandIfNeed(); + } // remove from spell book if not replaced by lesser rank if (!prev_activate && sendUpdate) @@ -3949,7 +4311,9 @@ void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bo } if (IsInWorld()) + { SpellRemovedQuestCheck(spell_id); + } } void Player::RemoveSpellCooldown(uint32 spell_id, bool update /* = false */) @@ -3957,7 +4321,9 @@ void Player::RemoveSpellCooldown(uint32 spell_id, bool update /* = false */) m_spellCooldowns.erase(spell_id); if (update) + { SendClearCooldown(spell_id, this); + } } void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) @@ -3972,9 +4338,13 @@ void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();) { if (ct_set.find(i->first) != ct_set.end()) + { RemoveSpellCooldown((i++)->first, update); + } else + { ++i; + } } } @@ -4051,7 +4421,9 @@ void Player::_LoadSpellCooldowns(QueryResult* result) // skip outdated cooldown if (db_time <= curTime) + { continue; + } AddSpellCooldown(spell_id, item_id, db_time); @@ -4078,7 +4450,9 @@ void Player::_SaveSpellCooldowns() for (SpellCooldowns::iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end();) { if (itr->second.end <= curTime) + { m_spellCooldowns.erase(itr++); + } else if (itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload { stmt = CharacterDatabase.CreateStatement(insertSpellCooldown, "INSERT INTO `character_spell_cooldown` (`guid`,`spell`,`item`,`time`) VALUES( ?, ?, ?, ?)"); @@ -4086,7 +4460,9 @@ void Player::_SaveSpellCooldowns() ++itr; } else + { ++itr; + } } } @@ -4123,7 +4499,9 @@ uint32 Player::resetTalentsCost() const int32 new_cost = m_resetTalentsCost + 5 * GOLD; // until it hits a cap of 50 gold. if (new_cost > 50 * GOLD) + { new_cost = 50 * GOLD; + } return new_cost; } } @@ -4138,7 +4516,9 @@ bool Player::resetTalents(bool no_cost, bool all_specs) // not need after this call if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS) && all_specs) + { RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS, true); + } if (m_usedTalentCount == 0 && !all_specs) { @@ -4193,7 +4573,9 @@ bool Player::resetTalents(bool no_cost, bool all_specs) for (int j = 0; j < MAX_TALENT_RANK; ++j) if (talentInfo->RankID[j]) + { removeSpell(talentInfo->RankID[j], !IsPassiveSpell(talentInfo->RankID[j]), false); + } iter = m_talents[m_activeSpec].begin(); } @@ -4217,7 +4599,9 @@ bool Player::resetTalents(bool no_cost, bool all_specs) for (uint8 spec = 0; spec < MAX_TALENT_SPEC_COUNT; ++spec) { if (!all_specs && spec != m_activeSpec) + { continue; + } m_talentsPrimaryTree[spec] = 0; } @@ -4228,7 +4612,9 @@ bool Player::resetTalents(bool no_cost, bool all_specs) for (uint8 spec = 0; spec < MAX_TALENT_SPEC_COUNT; ++spec) { if (spec == m_activeSpec) + { continue; + } for (PlayerTalentMap::iterator iter = m_talents[spec].begin(); iter != m_talents[spec].end();) { @@ -4272,7 +4658,9 @@ bool Player::resetTalents(bool no_cost, bool all_specs) if(Pet* pet = GetPet()) { if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets())) + { pet->Unsummon(PET_SAVE_REAGENTS, this); + } } */ return true; @@ -4301,7 +4689,9 @@ void Player::_SetCreateBits(UpdateMask* updateMask, Player* target) const for (uint16 index = 0; index < m_valuesCount; ++index) { if (GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index)) + { updateMask->SetBit(index); + } } } } @@ -4419,14 +4809,18 @@ void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) c for (int i = 0; i < EQUIPMENT_SLOT_END; ++i) { if (m_items[i] == NULL) + { continue; + } m_items[i]->BuildCreateUpdateBlockForPlayer(data, target); } for (int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { if (m_items[i] == NULL) + { continue; + } m_items[i]->BuildCreateUpdateBlockForPlayer(data, target); } @@ -4442,7 +4836,9 @@ void Player::DestroyForPlayer(Player* target, bool anim) const for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i) { if (m_items[i] == NULL) + { continue; + } m_items[i]->DestroyForPlayer(target); } @@ -4452,7 +4848,9 @@ void Player::DestroyForPlayer(Player* target, bool anim) const for (int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { if (m_items[i] == NULL) + { continue; + } m_items[i]->DestroyForPlayer(target); } @@ -4571,14 +4969,18 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe { // for nonexistent account avoid update realm if (accountId == 0) + { updateRealmChars = false; + } uint32 charDelete_method = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_METHOD); uint32 charDelete_minLvl = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_MIN_LEVEL); // if we want to finally delete the character or the character does not meet the level requirement, we set it to mode 0 if (deleteFinally || Player::GetLevelFromDB(playerguid) < charDelete_minLvl) + { charDelete_method = 0; + } uint32 lowguid = playerguid.GetCounter(); @@ -4609,7 +5011,9 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe uint32 groupId = (*resultGroup)[0].GetUInt32(); delete resultGroup; if (Group* group = sObjectMgr.GetGroupById(groupId)) + { RemoveFromGroup(group, playerguid); + } } // remove signs from petitions (also remove petitions if owner); @@ -4653,9 +5057,13 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe MailDraft draft; if (mailTemplateId) + { draft.SetMailTemplate(mailTemplateId, false);// items already included + } else + { draft.SetSubjectAndBody(subject, body); + } if (has_items) { @@ -4791,7 +5199,9 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe } if (updateRealmChars) + { sWorld.UpdateRealmCharCount(accountId); + } } /* @@ -4872,7 +5282,9 @@ void Player::SetFeatherFall(bool enable) // start fall from current height if (!enable) + { SetFallInformation(0, GetPositionZ()); + } } void Player::SetHover(bool enable) @@ -4893,7 +5305,9 @@ void Player::BuildPlayerRepop() GetSession()->SendPacket(&data); if (getRace() == RACE_NIGHTELF) + { CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form) + } CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?) // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK @@ -4921,7 +5335,9 @@ void Player::BuildPlayerRepop() SetWaterWalk(true); if (!GetSession()->isLogingOut()) + { SetRoot(false); + } // BG - remove insignia related RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); @@ -4951,7 +5367,9 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) // remove death flag + set aura SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00); if (getRace() == RACE_NIGHTELF) + { RemoveAurasDueToSpell(20584); // speed bonuses + } RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST SetDeathState(ALIVE); @@ -5068,11 +5486,17 @@ Corpse* Player::CreateCorpse() uint32 flags = CORPSE_FLAG_UNK2; if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM)) + { flags |= CORPSE_FLAG_HIDE_HELM; + } if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK)) + { flags |= CORPSE_FLAG_HIDE_CLOAK; + } if (InBattleGround() && !InArena()) + { flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia + } corpse->SetUInt32Value(CORPSE_FIELD_FLAGS, flags); corpse->SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId()); @@ -5094,7 +5518,9 @@ Corpse* Player::CreateCorpse() // we not need saved corpses for BG/arenas if (!GetMap()->IsBattleGroundOrArena()) + { corpse->SaveToDB(); + } // register for player, but not show sObjectAccessor.AddCorpse(corpse); @@ -5105,7 +5531,9 @@ void Player::SpawnCorpseBones() { if (sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid())) if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player + { SaveToDB(); // prevent loading as ghost without corpse + } } Corpse* Player::GetCorpse() const @@ -5117,7 +5545,9 @@ void Player::DurabilityLossAll(double percent, bool inventory) { for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { DurabilityLoss(pItem, percent); + } if (inventory) { @@ -5126,13 +5556,17 @@ void Player::DurabilityLossAll(double percent, bool inventory) for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { DurabilityLoss(pItem, percent); + } for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = GetItemByPos(i, j)) + { DurabilityLoss(pItem, percent); + } } } @@ -5153,7 +5587,9 @@ void Player::DurabilityLoss(Item* item, double percent) uint32 pDurabilityLoss = uint32(pMaxDurability * percent); if (pDurabilityLoss < 1) + { pDurabilityLoss = 1; + } DurabilityPointsLoss(item, pDurabilityLoss); } @@ -5162,7 +5598,9 @@ void Player::DurabilityPointsLossAll(int32 points, bool inventory) { for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { DurabilityPointsLoss(pItem, points); + } if (inventory) { @@ -5171,13 +5609,17 @@ void Player::DurabilityPointsLossAll(int32 points, bool inventory) for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { DurabilityPointsLoss(pItem, points); + } for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = GetItemByPos(i, j)) + { DurabilityPointsLoss(pItem, points); + } } } @@ -5188,21 +5630,29 @@ void Player::DurabilityPointsLoss(Item* item, int32 points) int32 pNewDurability = pOldDurability - points; if (pNewDurability < 0) + { pNewDurability = 0; + } else if (pNewDurability > pMaxDurability) + { pNewDurability = pMaxDurability; + } if (pOldDurability != pNewDurability) { // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check if (pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped()) + { _ApplyItemMods(item, item->GetSlot(), false); + } item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability); // modify item stats _after_ restore durability to pass _ApplyItemMods internal check if (pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped()) + { _ApplyItemMods(item, item->GetSlot(), true); + } item->SetState(ITEM_CHANGED, this); } @@ -5211,7 +5661,9 @@ void Player::DurabilityPointsLoss(Item* item, int32 points) void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot) { if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) + { DurabilityPointsLoss(pItem, 1); + } } uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank) @@ -5280,7 +5732,9 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g costs = uint32(costs * discountMod); if (costs == 0) // fix for ITEM_QUALITY_ARTIFACT + { costs = 1; + } if (guildBank) { @@ -5323,7 +5777,9 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g return TotalCost; } else + { ModifyMoney(-int64(costs)); + } } } @@ -5332,7 +5788,9 @@ uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool g // reapply mods for total broken and repaired item if equipped if (IsEquipmentPos(pos) && !curDurability) + { _ApplyItemMods(item, pos & 255, true); + } return TotalCost; } @@ -5354,9 +5812,13 @@ void Player::RepopAtGraveyard() // Special handle for battleground maps if (BattleGround* bg = GetBattleGround()) + { ClosestGrave = bg->GetClosestGraveYard(this); + } else + { ClosestGrave = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()); + } // stop countdown until repop m_deathTimer = 0; @@ -5377,7 +5839,9 @@ void Player::RepopAtGraveyard() GetSession()->SendPacket(&data); } if (updateVisibility && IsInWorld()) + { UpdateVisibilityAndView(); + } } } @@ -5399,7 +5863,9 @@ void Player::CleanupChannels() m_channels.erase(m_channels.begin()); // remove from player's channel list ch->Leave(this, false); // not send to client, not remove from player's channel list if (ChannelMgr* cMgr = channelMgr(GetTeam())) + { cMgr->LeftChannel(ch->GetName()); // deleted channel if empty + } } DEBUG_LOG("Player: channels cleaned up!"); } @@ -5431,14 +5897,20 @@ void Player::UpdateLocalChannels(uint32 newZone) // skip non built-in channels if (!(*i)->IsConstant()) + { continue; + } ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId()); if (!ch) + { continue; + } if ((ch->flags & 4) == 4) // global channel without zone name in pattern + { continue; + } // new channel char new_channel_name_buf[100]; @@ -5488,7 +5960,9 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa break; case PCT_MOD: if (amount <= -100.0f) + { amount = -200.0f; + } val = (100.0f + amount) / 100.0f; m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f / val); @@ -5673,7 +6147,9 @@ float Player::GetRatingMultiplier(CombatRating cr) const // gtOCTClassCombatRatingScalarStore.dbc starts with 1, CombatRating with zero, so cr+1 GtOCTClassCombatRatingScalarEntry const* classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((getClass() - 1) * GT_MAX_RATING + cr + 1); if (!Rating || !classRating) + { return 1.0f; // By default use minimum coefficient (not must be called) + } return classRating->ratio / Rating->ratio; } @@ -5765,9 +6241,13 @@ void Player::UpdateRating(CombatRating cr) AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT); for (AuraList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i) if ((*i)->GetMiscValue() & (1 << cr)) + { amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f); + } if (amount < 0) + { amount = 0; + } SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount)); bool affectStats = CanModifyStats(); @@ -5804,11 +6284,15 @@ void Player::UpdateRating(CombatRating cr) break; case CR_CRIT_RANGED: if (affectStats) + { UpdateCritPercentage(RANGED_ATTACK); + } break; case CR_CRIT_SPELL: if (affectStats) + { UpdateAllSpellCritChances(); + } break; case CR_RESILIENCE_DAMAGE_TAKEN: break; @@ -5825,7 +6309,9 @@ void Player::UpdateRating(CombatRating cr) break; case CR_ARMOR_PENETRATION: if (affectStats) + { UpdateArmorPenetration(); + } break; case CR_MASTERY: UpdateMasteryAuras(); @@ -5860,9 +6346,13 @@ void Player::SetRegularAttackTime() { ItemPrototype const* proto = tmpitem->GetProto(); if (proto->Delay) + { SetAttackTime(WeaponAttackType(i), proto->Delay); + } else + { SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME); + } } } } @@ -5876,7 +6366,9 @@ bool Player::UpdateSkill(uint32 skill_id, uint32 step) } if (skill_id == SKILL_FIST_WEAPONS) + { skill_id = SKILL_UNARMED; + } SkillStatusMap::iterator itr = mSkillStatus.find(skill_id); if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED) @@ -5903,11 +6395,15 @@ bool Player::UpdateSkill(uint32 skill_id, uint32 step) uint32 new_value = value + step; if (new_value > max) + { new_value = max; + } SetUInt16Value(PLAYER_SKILL_RANK_0 + field, offset, new_value); if (itr->second.uState != SKILL_NEW) + { itr->second.uState = SKILL_CHANGED; + } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, skill_id); return true; @@ -5947,14 +6443,20 @@ bool Player::UpdateCraftSkill(uint32 spellid) if (spellEntry && spellEntry->GetMechanic() == MECHANIC_DISCOVERY) { if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this)) + { learnSpell(discoveredSpell, false); + } } uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING); if (!_spell_idx->second->characterPoints) + { sLog.outError("Player::UpdateCraftSkill spell %u has characterPoints == 0!", spellid); + } else + { craft_skill_gain += _spell_idx->second->characterPoints - 1; + } return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue, _spell_idx->second->max_value, @@ -6056,11 +6558,15 @@ bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step) { uint16 new_value = SkillValue + step; if (new_value > MaxValue) + { new_value = MaxValue; + } SetUInt16Value(PLAYER_SKILL_RANK_0 + field, offset, new_value); if (itr->second.uState != SKILL_NEW) + { itr->second.uState = SKILL_CHANGED; + } for (uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl) { if (SkillValue < *bsl && new_value >= *bsl) @@ -6101,16 +6607,22 @@ void Player::UpdateSkillsForLevel() for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr) { if (itr->second.uState == SKILL_DELETED) + { continue; + } uint32 pskill = itr->first; SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(pskill); if (!pSkill) + { continue; + } if (GetSkillRangeType(pSkill, false) != SKILL_RANGE_LEVEL) + { continue; + } // only weapons skills curently have SKILL_RANGE_LEVEL uint16 field = itr->second.pos / 2; @@ -6123,7 +6635,9 @@ void Player::UpdateSkillsForLevel() { SetUInt16Value(PLAYER_SKILL_MAX_RANK_0 + field, offset, maxSkill); if (itr->second.uState != SKILL_NEW) + { itr->second.uState = SKILL_CHANGED; + } } } } @@ -6133,11 +6647,15 @@ void Player::UpdateSkillsToMaxSkillsForLevel() for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr) { if (itr->second.uState == SKILL_DELETED) + { continue; + } uint32 pskill = itr->first; if (IsProfessionOrRidingSkill(pskill)) + { continue; + } uint16 field = itr->second.pos / 2; uint8 offset = itr->second.pos & 1; // itr->second.pos % 2 @@ -6147,7 +6665,9 @@ void Player::UpdateSkillsToMaxSkillsForLevel() { SetUInt16Value(PLAYER_SKILL_RANK_0 + field, offset, max); if (itr->second.uState != SKILL_NEW) + { itr->second.uState = SKILL_CHANGED; + } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill); } } @@ -6178,7 +6698,9 @@ void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0 SetUInt16Value(PLAYER_SKILL_RANK_0 + field, offset, currVal); SetUInt16Value(PLAYER_SKILL_MAX_RANK_0 + field, offset, maxVal); if (itr->second.uState != SKILL_NEW) + { itr->second.uState = SKILL_CHANGED; + } learnSkillRewardedSpells(id, oldVal); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id); @@ -6195,15 +6717,21 @@ void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0 // mark as deleted or simply remove from map if not saved yet if (itr->second.uState != SKILL_NEW) + { itr->second.uState = SKILL_DELETED; + } else + { mSkillStatus.erase(itr); + } // remove all spells that related to this skill for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) if (SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j)) if (pAbility->skillId == id) + { removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId)); + } } } else if (currVal) // add @@ -6236,7 +6764,9 @@ void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0 itr->second.uState = SKILL_CHANGED; } else + { mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW))); + } // apply skill bonuses SetUInt16Value(PLAYER_SKILL_MODIFIER_0 + field, offset, 0); @@ -6246,13 +6776,17 @@ void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL); for (AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j) if ((*j)->GetModifier()->m_miscvalue == int32(id)) + { (*j)->ApplyModifier(true); + } // permanent bonuses AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT); for (AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j) if ((*j)->GetModifier()->m_miscvalue == int32(id)) + { (*j)->ApplyModifier(true); + } // Learn all spells for skill learnSkillRewardedSpells(id, currVal); @@ -6440,9 +6974,13 @@ void Player::SendInitialActionButtons() const { ActionButtonList::const_iterator itr = currentActionButtonList.find(button); if (itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED) + { data << uint32(itr->second.packedData); + } else + { data << uint32(0); + } } data << uint8(1); // talent spec amount (in packet) GetSession()->SendPacket(&data); @@ -6468,7 +7006,9 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Pl if (player) sLog.outError("Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS); else + { sLog.outError("Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS); + } } return false; } @@ -6480,7 +7020,9 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Pl if (player) sLog.outError("Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE); else + { sLog.outError("Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE); + } } return false; } @@ -6497,7 +7039,9 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Pl if (player) sLog.outError("Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName()); else + { sLog.outError("Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button); + } } return false; } @@ -6536,7 +7080,9 @@ bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Pl if (player) sLog.outError("Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName()); else + { sLog.outError("Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button); + } } return false; } @@ -6577,9 +7123,13 @@ void Player::removeActionButton(uint8 spec, uint8 button) } if (buttonItr->second.uState == ACTIONBUTTON_NEW) + { currentActionButtonList.erase(buttonItr); // new and not saved + } else + { buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save + } DETAIL_LOG("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec); } @@ -6615,9 +7165,13 @@ bool Player::SetPosition(float x, float y, float z, float orientation, bool tele if (teleport || old_x != x || old_y != y || old_z != z || old_r != orientation) { if (teleport || old_x != x || old_y != y || old_z != z) + { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING); + } else + { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING); + } RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); @@ -6632,7 +7186,9 @@ bool Player::SetPosition(float x, float y, float z, float orientation, bool tele // group update if (GetGroup() && (old_x != x || old_y != y)) + { SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION); + } } if (m_positionStatusUpdateTimer) // Update position's state only on interval @@ -6662,30 +7218,42 @@ void Player::SaveRecallPosition() void Player::SendMessageToSet(WorldPacket* data, bool self) const { if (IsInWorld()) + { GetMap()->MessageBroadcast(this, data, false); + } // if player is not in world and map in not created/already destroyed // no need to create one, just send packet for itself! if (self) + { GetSession()->SendPacket(data); + } } void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self) const { if (IsInWorld()) + { GetMap()->MessageDistBroadcast(this, data, dist, false); + } if (self) + { GetSession()->SendPacket(data); + } } void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool own_team_only) const { if (IsInWorld()) + { GetMap()->MessageDistBroadcast(this, data, dist, false, own_team_only); + } if (self) + { GetSession()->SendPacket(data); + } } void Player::SendDirectMessage(WorldPacket* data) const @@ -6738,20 +7306,28 @@ void Player::CheckAreaExploreAndOutdoor() for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) + { continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (!spellInfo || !IsNeedCastSpellAtOutdoor(spellInfo) || HasAura(itr->first)) + { continue; + } SpellShapeshiftEntry const* shapeShift = spellInfo->GetSpellShapeshift(); if (!shapeShift || (shapeShift->Stances || shapeShift->StancesNot) && !IsNeedCastSpellAtFormApply(spellInfo, GetShapeshiftForm())) + { continue; + } CastSpell(this, itr->first, true, NULL); } } else if (sWorld.getConfig(CONFIG_BOOL_VMAP_INDOOR_CHECK) && !isGameMaster()) + { RemoveAurasWithAttribute(SPELL_ATTR_OUTDOORS_ONLY); + } if (areaFlag == 0xffff) { @@ -6798,9 +7374,13 @@ void Player::CheckAreaExploreAndOutdoor() { int32 exploration_percent = (100 - ((diff - 5) * 5)); if (exploration_percent > 100) + { exploration_percent = 100; + } else if (exploration_percent < 0) + { exploration_percent = 0; + } XP = uint32(sObjectMgr.GetBaseXP(p->area_level) * exploration_percent / 100 * sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE)); } @@ -6869,7 +7449,9 @@ int32 Player::CalculateReputationGain(ReputationSource source, int32 rep, int32 // faction specific auras only seem to apply to kills if (source == REPUTATION_SOURCE_KILL) + { repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction); + } percent += rep > 0 ? repMod : -repMod; @@ -6889,7 +7471,9 @@ int32 Player::CalculateReputationGain(ReputationSource source, int32 rep, int32 } if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel())) + { percent *= rate; + } if (percent <= 0.0f) { @@ -6975,14 +7559,18 @@ void Player::RewardReputation(Unit* pVictim, float rate) FactionEntry const* factionEntry1 = sFactionStore.LookupEntry(repFaction1); uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1); if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1) + { GetReputationMgr().ModifyReputation(factionEntry1, donerep1); + } // Wiki: Team factions value divided by 2 if (factionEntry1 && Rep->is_teamaward1) { FactionEntry const* team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team); if (team1_factionEntry) + { GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2); + } } } @@ -6993,14 +7581,18 @@ void Player::RewardReputation(Unit* pVictim, float rate) FactionEntry const* factionEntry2 = sFactionStore.LookupEntry(repFaction2); uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2); if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2) + { GetReputationMgr().ModifyReputation(factionEntry2, donerep2); + } // Wiki: Team factions value divided by 2 if (factionEntry2 && Rep->is_teamaward2) { FactionEntry const* team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team); if (team2_factionEntry) + { GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2); + } } } } @@ -7012,7 +7604,9 @@ void Player::RewardReputation(Quest const* pQuest) for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) { if (!pQuest->RewRepFaction[i]) + { continue; + } // No diplomacy mod are applied to the final value (flat). Note the formula (finalValue = DBvalue/100) if (pQuest->RewRepValue[i]) @@ -7020,7 +7614,9 @@ void Player::RewardReputation(Quest const* pQuest) int32 rep = CalculateReputationGain(REPUTATION_SOURCE_QUEST, pQuest->RewRepValue[i] / 100, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest), true); if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i])) + { GetReputationMgr().ModifyReputation(factionEntry, rep); + } } else { @@ -7032,12 +7628,16 @@ void Player::RewardReputation(Quest const* pQuest) int32 repPoints = pRow->rewardValue[field]; if (!repPoints) + { continue; + } repPoints = CalculateReputationGain(REPUTATION_SOURCE_QUEST, repPoints, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest)); if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i])) + { GetReputationMgr().ModifyReputation(factionEntry, repPoints); + } } } } @@ -7144,13 +7744,21 @@ bool Player::RewardHonor(Unit* uVictim, uint32 groupsize, float honor) // title[15..28] -> rank[5..18] // title[other] -> 0 if (victim_title == 0) + { victim_guid.Clear(); // Don't show HK: message, only log. + } else if (victim_title < 15) + { victim_rank = victim_title + 4; + } else if (victim_title < 29) + { victim_rank = victim_title - 14 + 4; + } else + { victim_guid.Clear(); // Don't show HK: message, only log. + } } k_grey = MaNGOS::XP::GetGrayLevel(k_level); @@ -7195,7 +7803,9 @@ bool Player::RewardHonor(Unit* uVictim, uint32 groupsize, float honor) honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f) / 100.0f; if (groupsize > 1) + { honor /= groupsize; + } honor *= (((float)urand(8, 12)) / 10); // approx honor: 80% - 120% of real honor } @@ -7220,9 +7830,13 @@ bool Player::RewardHonor(Unit* uVictim, uint32 groupsize, float honor) void Player::SetInGuild(uint32 GuildId) { if (GuildId) + { SetGuidValue(OBJECT_FIELD_DATA, ObjectGuid(HIGHGUID_GUILD, 0, GuildId)); + } else + { SetGuidValue(OBJECT_FIELD_DATA, ObjectGuid()); + } ApplyModFlag(PLAYER_FLAGS, PLAYER_FLAGS_GUILD_LEVELING_ENABLED, GuildId != 0 && sWorld.getConfig(CONFIG_BOOL_GUILD_LEVELING_ENABLED)); SetUInt16Value(OBJECT_FIELD_TYPE, 1, GuildId != 0); @@ -7378,14 +7992,18 @@ void Player::UpdateArea(uint32 newArea) if (area && (area->flags & AREA_FLAG_ARENA)) { if (!isGameMaster()) + { SetFFAPvP(true); + } } else { // remove ffa flag only if not ffapvp realm // removal in sanctuaries and capitals is handled in zone update if (IsFFAPvP() && !sWorld.IsFFAPvPRealm()) + { SetFFAPvP(false); + } } UpdateAreaDependentAuras(); @@ -7458,19 +8076,25 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) if (pvpInfo.inHostileArea) // in hostile area { if (!IsPvP() || pvpInfo.endTimer != 0) + { UpdatePvP(true, true); + } } else // in friendly area { if (IsPvP() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0) + { pvpInfo.endTimer = time(0); // start toggle-off + } } if (zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary { SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY); if (sWorld.IsFFAPvPRealm()) + { SetFFAPvP(false); + } } else { @@ -7478,15 +8102,21 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) } if (zone->flags & AREA_FLAG_CAPITAL) // in capital city + { SetRestType(REST_TYPE_IN_CITY); + } else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() != REST_TYPE_IN_TAVERN) + { // resting and not in tavern (leave city then); tavern leave handled in CheckAreaExploreAndOutdoor + } SetRestType(REST_TYPE_NO); // remove items with area/map limitations (delete only for alive player to allow back in ghost mode) // if player resurrected at teleport this will be applied in resurrect code if (IsAlive()) + { DestroyZoneLimitedItem(true, newZone); + } // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example) AutoUnequipOffhandIfNeed(); @@ -7496,7 +8126,9 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) // group update if (GetGroup()) + { SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE); + } UpdateZoneDependentAuras(); UpdateZoneDependentPets(); @@ -7570,7 +8202,9 @@ void Player::DuelComplete(DuelCompleteType type) { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1); if (duel->opponent) + { duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1); + } } // Used by Eluna @@ -7580,7 +8214,9 @@ void Player::DuelComplete(DuelCompleteType type) // Remove Duel Flag object if (GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER))) + { duel->initiator->RemoveGameObject(obj, true); + } /* remove auras */ std::vector auras2remove; @@ -7588,7 +8224,9 @@ void Player::DuelComplete(DuelCompleteType type) for (SpellAuraHolderMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i) { if (!i->second->IsPositive() && i->second->GetCasterGuid() == GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime) + { auras2remove.push_back(i->second->GetId()); + } } for (size_t i = 0; i < auras2remove.size(); ++i) @@ -7601,7 +8239,9 @@ void Player::DuelComplete(DuelCompleteType type) for (SpellAuraHolderMap::const_iterator i = auras.begin(); i != auras.end(); ++i) { if (!i->second->IsPositive() && i->second->GetCasterGuid() == duel->opponent->GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime) + { auras2remove.push_back(i->second->GetId()); + } } for (size_t i = 0; i < auras2remove.size(); ++i) { @@ -7610,14 +8250,22 @@ void Player::DuelComplete(DuelCompleteType type) // cleanup combo points if (GetComboTargetGuid() == duel->opponent->GetObjectGuid()) + { ClearComboPoints(); + } else if (GetComboTargetGuid() == duel->opponent->GetPetGuid()) + { ClearComboPoints(); + } if (duel->opponent->GetComboTargetGuid() == GetObjectGuid()) + { duel->opponent->ClearComboPoints(); + } else if (duel->opponent->GetComboTargetGuid() == GetPetGuid()) + { duel->opponent->ClearComboPoints(); + } // cleanups SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid()); @@ -7657,18 +8305,24 @@ void Player::_ApplyItemMods(Item* item, uint8 slot, bool apply) uint32 attacktype = Player::GetAttackBySlot(slot); if (attacktype < MAX_ATTACK) + { _ApplyWeaponDependentAuraMods(item, WeaponAttackType(attacktype), apply); + } _ApplyItemBonuses(proto, slot, apply); if (slot == EQUIPMENT_SLOT_RANGED) + { _ApplyAmmoBonuses(); + } ApplyItemEquipSpell(item, apply); ApplyEnchantment(item, apply); if (proto->Socket[0].Color) // only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items + { CorrectMetaGemEnchants(slot, apply); + } DEBUG_LOG("_ApplyItemMods complete."); } @@ -7689,7 +8343,9 @@ void Player::_ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool appl // req. check at equip, but allow use for extended range if range limit max level, set proper level uint32 ssd_level = getLevel(); if (ssd && ssd_level > ssd->MaxLevel) + { ssd_level = ssd->MaxLevel; + } ScalingStatValuesEntry const* ssv = proto->StatScalingFactor ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL; if (only_level_Scale && !ssv) @@ -7705,7 +8361,9 @@ void Player::_ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool appl if (ssd && ssv) { if (ssd->StatMod[i] < 0) + { continue; + } statType = ssd->StatMod[i]; val = (ssv->getssdMultiplier(proto->StatScalingFactor) * ssd->Modifier[i]) / 10000; } @@ -7716,7 +8374,9 @@ void Player::_ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool appl } if (val == 0) + { continue; + } switch (statType) { @@ -7827,7 +8487,9 @@ void Player::_ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool appl if (ssv) { if (int32 spellbonus = ssv->getSpellBonus(proto->StatScalingFactor)) + { ApplySpellPowerBonus(spellbonus, apply); + } } // If set ScalingStatValue armor get it or use item armor @@ -7835,11 +8497,15 @@ void Player::_ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool appl if (ssv) { if (uint32 ssvarmor = ssv->getArmorMod(proto->StatScalingFactor)) + { armor = ssvarmor; + } } // Add armor bonus from ArmorDamageModifier if > 0 if (proto->ArmorDamageModifier > 0) + { armor += uint32(proto->ArmorDamageModifier); + } if (armor) { @@ -7905,15 +8571,23 @@ void Player::_ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool appl if (proto->Delay) { if (slot == EQUIPMENT_SLOT_RANGED) + { SetAttackTime(RANGED_ATTACK, apply ? proto->Delay : BASE_ATTACK_TIME); + } else if (slot == EQUIPMENT_SLOT_MAINHAND) + { SetAttackTime(BASE_ATTACK, apply ? proto->Delay : BASE_ATTACK_TIME); + } else if (slot == EQUIPMENT_SLOT_OFFHAND) + { SetAttackTime(OFF_ATTACK, apply ? proto->Delay : BASE_ATTACK_TIME); + } } if (CanModifyStats() && (damage || proto->Delay)) + { UpdateDamagePhysical(attType); + } } void Player::_ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply) @@ -8017,13 +8691,17 @@ void Player::ApplyItemEquipSpell(Item* item, bool apply, bool form_change) // no spell if (!spellData.SpellId) + { continue; + } if (apply) { // apply only at-equip spells if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP) + { continue; + } } else { @@ -8031,13 +8709,17 @@ void Player::ApplyItemEquipSpell(Item* item, bool apply, bool form_change) // except on form change and with at-use with negative charges, so allow consuming item spells (including with extra flag that prevent consume really) // applied to player after item remove from equip slot if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_USE && (form_change || spellData.SpellCharges < 0)) + { continue; + } } // check if it is valid spell SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId); if (!spellproto) + { continue; + } ApplyEquipSpell(spellproto, item, apply, form_change); } @@ -8059,7 +8741,9 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply for (SpellAuraHolderMap::const_iterator iter = spair.first; iter != spair.second; ++iter) { if (!item || iter->second->GetCastItemGuid() == item->GetObjectGuid()) + { return; // and skip re-cast already active aura at form change + } } } @@ -8073,13 +8757,19 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply { // Cannot be used in this stance/form if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) == SPELL_CAST_OK) + { return; // and remove only not compatible at form change + } } if (item) + { RemoveAurasDueToItemSpell(item, spellInfo->Id); // un-apply all spells , not only at-equipped + } else + { RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case) + } } } @@ -8099,13 +8789,17 @@ void Player::UpdateEquipSpellsAtFormChange() { ItemSetEffect* eff = ItemSetEff[setindex]; if (!eff) + { continue; + } for (uint32 y = 0; y < 8; ++y) { SpellEntry const* spellInfo = eff->spells[y]; if (!spellInfo) + { continue; + } ApplyEquipSpell(spellInfo, NULL, false, true); // remove spells that not fit to form ApplyEquipSpell(spellInfo, NULL, true, true); // add spells that fit form but not active @@ -8145,20 +8839,28 @@ void Player::ApplyItemOnStoreSpell(Item* item, bool apply) // no spell if (!spellData.SpellId) + { continue; + } // apply/unapply only at-store spells if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE) + { continue; + } if (apply) { // can be attempt re-applied at move in inventory slots if (!HasAura(spellData.SpellId)) + { CastSpell(this, spellData.SpellId, true, item); + } } else + { RemoveAurasDueToItemSpell(item, spellData.SpellId); + } } } @@ -8180,11 +8882,15 @@ void Player::DestroyItemWithOnStoreSpell(Item* item, uint32 spellId) _Spell const& spellData = proto->Spells[i]; if (spellData.SpellId != spellId) + { continue; + } // apply/unapply only at-store spells if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE) + { continue; + } DestroyItem(item->GetBagSlot(), item->GetSlot(), true); break; @@ -8228,11 +8934,15 @@ void Player::_HandleDeadlyPoison(Unit* Target, WeaponAttackType attType, SpellEn for (int s = 0; s < 3; ++s) { if (pSecondEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) + { continue; + } if (SpellEntry const* combatEntry = sSpellStore.LookupEntry(pSecondEnchant->spellid[s])) if (combatEntry->GetDispel() == DISPEL_POISON) + { CastSpell(Target, combatEntry, true, otherWeapon); + } } } } @@ -8262,11 +8972,15 @@ void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType) // no spell if (!spellData.SpellId) + { continue; + } // wrong triggering type if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT) + { continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellData.SpellId); if (!spellInfo) @@ -8294,14 +9008,18 @@ void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType) } if (roll_chance_f(chance)) + { CastSpell(Target, spellInfo->Id, true, item); + } } // item combat enchantments for (int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot) { if (e_slot > PRISMATIC_ENCHANTMENT_SLOT && e_slot < PROP_ENCHANTMENT_SLOT_0) + { continue; + } uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot)); SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); @@ -8309,7 +9027,9 @@ void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType) for (int s = 0; s < 3; ++s) { if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) + { continue; + } uint32 proc_spell_id = pEnchant->spellid[s]; SpellEntry const* spellInfo = sSpellStore.LookupEntry(proc_spell_id); @@ -8332,12 +9052,16 @@ void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType) if (roll_chance_f(chance)) { if (IsPositiveSpell(spellInfo->Id)) + { CastSpell(this, spellInfo->Id, true, item); + } else { // Deadly Poison, unique effect needs to be handled before casting triggered spell if (spellInfo->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000000010000))) + { _HandleDeadlyPoison(Target, attType, spellInfo); + } CastSpell(Target, spellInfo->Id, true, item); } @@ -8381,11 +9105,15 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 // no spell if (!spellData.SpellId) + { continue; + } // wrong triggering type if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) + { continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellData.SpellId); if (!spellInfo) @@ -8407,17 +9135,23 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 for (int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot) { if (e_slot > PRISMATIC_ENCHANTMENT_SLOT && e_slot < PROP_ENCHANTMENT_SLOT_0) + { continue; + } uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot)); SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) + { continue; + } for (int s = 0; s < 3; ++s) { if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_USE_SPELL) + { continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]); if (!spellInfo) @@ -8447,14 +9181,20 @@ void Player::_RemoveAllItemMods() { ItemPrototype const* proto = m_items[i]->GetProto(); if (!proto) + { continue; + } // item set bonuses not dependent from item broken state if (proto->ItemSet) + { RemoveItemsSetItem(this, proto); + } if (m_items[i]->IsBroken()) + { continue; + } ApplyItemEquipSpell(m_items[i], false); ApplyEnchantment(m_items[i], false); @@ -8466,19 +9206,27 @@ void Player::_RemoveAllItemMods() if (m_items[i]) { if (m_items[i]->IsBroken()) + { continue; + } ItemPrototype const* proto = m_items[i]->GetProto(); if (!proto) + { continue; + } uint32 attacktype = Player::GetAttackBySlot(i); if (attacktype < MAX_ATTACK) + { _ApplyWeaponDependentAuraMods(m_items[i], WeaponAttackType(attacktype), false); + } _ApplyItemBonuses(proto, i, false); if (i == EQUIPMENT_SLOT_RANGED) + { _ApplyAmmoBonuses(); + } } } @@ -8494,20 +9242,28 @@ void Player::_ApplyAllItemMods() if (m_items[i]) { if (m_items[i]->IsBroken()) + { continue; + } ItemPrototype const* proto = m_items[i]->GetProto(); if (!proto) + { continue; + } uint32 attacktype = Player::GetAttackBySlot(i); if (attacktype < MAX_ATTACK) + { _ApplyWeaponDependentAuraMods(m_items[i], WeaponAttackType(attacktype), true); + } _ApplyItemBonuses(proto, i, true); if (i == EQUIPMENT_SLOT_RANGED) + { _ApplyAmmoBonuses(); + } } } @@ -8517,14 +9273,20 @@ void Player::_ApplyAllItemMods() { ItemPrototype const* proto = m_items[i]->GetProto(); if (!proto) + { continue; + } // item set bonuses not dependent from item broken state if (proto->ItemSet) + { AddItemsSetItem(this, m_items[i]); + } if (m_items[i]->IsBroken()) + { continue; + } ApplyItemEquipSpell(m_items[i], true); ApplyEnchantment(m_items[i], true); @@ -8541,11 +9303,15 @@ void Player::_ApplyAllLevelScaleItemMods(bool apply) if (m_items[i]) { if (m_items[i]->IsBroken()) + { continue; + } ItemPrototype const* proto = m_items[i]->GetProto(); if (!proto) + { continue; + } _ApplyItemBonuses(proto, i, apply, true); } @@ -8671,7 +9437,9 @@ void Player::SendLootRelease(ObjectGuid guid) void Player::SendLoot(ObjectGuid guid, LootType loot_type) { if (ObjectGuid lootGuid = GetLootGuid()) + { m_session->DoLootRelease(lootGuid); + } Loot* loot = NULL; PermissionTypes permission = ALL_PERMISSION; @@ -8734,7 +9502,9 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) break; default: if (!Lootid) + { break; + } DEBUG_LOG(" send normal GO loot"); loot->FillLoot(Lootid, LootTemplates_Gameobject, this, false); @@ -8778,24 +9548,38 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) if (group == GetGroup()) { if (group->GetLootMethod() == FREE_FOR_ALL) + { permission = ALL_PERMISSION; + } else if (group->GetLooterGuid() == GetObjectGuid()) { if (group->GetLootMethod() == MASTER_LOOT) + { permission = MASTER_PERMISSION; + } else + { permission = ALL_PERMISSION; + } } else + { permission = GROUP_PERMISSION; + } } else + { permission = NONE_PERMISSION; + } } else if (recipient == this) + { permission = ALL_PERMISSION; + } else + { permission = NONE_PERMISSION; + } } break; } @@ -8858,16 +9642,22 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) uint32 pLevel = bones->loot.gold; bones->loot.clear(); if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV) + { loot->FillLoot(0, LootTemplates_Creature, this, false); + } // It may need a better formula // Now it works like this: lvl10: ~6copper, lvl70: ~9silver bones->loot.gold = (uint32)(urand(50, 150) * 0.016f * pow(((float)pLevel) / 5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)); } if (bones->lootRecipient != this) + { permission = NONE_PERMISSION; + } else + { permission = OWNER_PERMISSION; + } break; } case HIGHGUID_UNIT: @@ -8898,7 +9688,9 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) loot->clear(); if (uint32 Lootid = creature->GetCreatureInfo()->PickpocketLootId) + { loot->FillLoot(Lootid, LootTemplates_Pickpocketing, this, false); + } // Generate extra money for pick pocket loot const uint32 a = urand(0, creature->getLevel() / 2); @@ -8929,7 +9721,9 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) loot->clear(); if (uint32 Lootid = creature->GetCreatureInfo()->LootId) + { loot->FillLoot(Lootid, LootTemplates_Creature, recipient, false); + } loot->generateMoneyLoot(creature->GetCreatureInfo()->MinLootGold, creature->GetCreatureInfo()->MaxLootGold); @@ -8966,7 +9760,9 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) // let reopen skinning loot if will closed. if (!loot->empty()) + { creature->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); + } permission = OWNER_PERMISSION; } @@ -8984,24 +9780,38 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) if (group == GetGroup()) { if (group->GetLootMethod() == FREE_FOR_ALL) + { permission = ALL_PERMISSION; + } else if (group->GetLooterGuid() == GetObjectGuid()) { if (group->GetLootMethod() == MASTER_LOOT) + { permission = MASTER_PERMISSION; + } else + { permission = ALL_PERMISSION; + } } else + { permission = GROUP_PERMISSION; + } } else + { permission = NONE_PERMISSION; + } } else if (recipient == this) + { permission = OWNER_PERMISSION; + } else + { permission = NONE_PERMISSION; + } } } break; @@ -9035,10 +9845,14 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) // add 'this' player as one of the players that are looting 'loot' if (permission != NONE_PERMISSION) + { loot->AddLooter(GetObjectGuid()); + } if (loot_type == LOOT_CORPSE && !guid.IsItem()) + { SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING); + } } void Player::SendNotifyLootMoneyRemoved() @@ -9098,35 +9912,51 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) case 3519: // Terokkar Forest case 3521: // Zangarmarsh if (OutdoorPvP* outdoorPvP = sOutdoorPvPMgr.GetScript(zoneid)) + { outdoorPvP->FillInitialWorldStates(data, count); + } break; case 2597: // AV if (bg && bg->GetTypeID() == BATTLEGROUND_AV) + { bg->FillInitialWorldStates(data, count); + } break; case 3277: // WS if (bg && bg->GetTypeID() == BATTLEGROUND_WS) + { bg->FillInitialWorldStates(data, count); + } break; case 3358: // AB if (bg && bg->GetTypeID() == BATTLEGROUND_AB) + { bg->FillInitialWorldStates(data, count); + } break; case 3820: // EY if (bg && bg->GetTypeID() == BATTLEGROUND_EY) + { bg->FillInitialWorldStates(data, count); + } break; case 3698: // Nagrand Arena if (bg && bg->GetTypeID() == BATTLEGROUND_NA) + { bg->FillInitialWorldStates(data, count); + } break; case 3702: // Blade's Edge Arena if (bg && bg->GetTypeID() == BATTLEGROUND_BE) + { bg->FillInitialWorldStates(data, count); + } break; case 3968: // Ruins of Lordaeron if (bg && bg->GetTypeID() == BATTLEGROUND_RL) + { bg->FillInitialWorldStates(data, count); + } break; } @@ -9145,9 +9975,13 @@ void Player::FillBGWeekendWorldStates(WorldPacket& data, uint32& count) if (bl && bl->HolidayWorldStateId) { if (BattleGroundMgr::IsBGWeekend(BattleGroundTypeId(bl->id))) + { FillInitialWorldState(data, count, bl->HolidayWorldStateId, 1); + } else + { FillInitialWorldState(data, count, bl->HolidayWorldStateId, 0); + } } } } @@ -9157,7 +9991,9 @@ uint32 Player::GetXPRestBonus(uint32 xp) uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus if (rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp + { rested_bonus = xp; + } SetRestBonus(GetRestBonus() - rested_bonus); @@ -9212,7 +10048,9 @@ void Player::SetVirtualItemSlot(uint8 i, Item* item) return; } if (charges > 1) + { item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT, charges - 1); + } else if (charges <= 1) { ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false); @@ -9311,7 +10149,9 @@ bool Player::GetSlotsForInventoryType(uint8 invType, uint8* slots, uint32 subCla // suggest offhand slot only if know dual wielding // (this will be replace mainhand weapon at auto equip instead unwanted "you don't known dual wielding" ... if (CanDualWield()) + { slots[1] = EQUIPMENT_SLOT_OFFHAND; + } break; } case INVTYPE_SHIELD: @@ -9323,7 +10163,9 @@ bool Player::GetSlotsForInventoryType(uint8 invType, uint8* slots, uint32 subCla case INVTYPE_2HWEAPON: slots[0] = EQUIPMENT_SLOT_MAINHAND; if (CanDualWield() && CanTitanGrip()) + { slots[1] = EQUIPMENT_SLOT_OFFHAND; + } break; case INVTYPE_TABARD: slots[0] = EQUIPMENT_SLOT_TABARD; @@ -9436,7 +10278,9 @@ InventoryResult Player::CanUnequipItems(uint32 item, uint32 count) const } } else + { res = ires; + } } } for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) @@ -9483,13 +10327,17 @@ uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const { Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem && pItem != skipItem && pItem->GetEntry() == item) + { count += pItem->GetCount(); + } } for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pBag) + { count += pBag->GetItemCount(item, skipItem); + } } if (skipItem && skipItem->GetProto()->GemProperties) @@ -9498,7 +10346,9 @@ uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const { Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color) + { count += pItem->GetGemCountWithID(item); + } } } @@ -9508,13 +10358,17 @@ uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const { Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem && pItem != skipItem && pItem->GetEntry() == item) + { count += pItem->GetCount(); + } } for (int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) { Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pBag) + { count += pBag->GetItemCount(item, skipItem); + } } if (skipItem && skipItem->GetProto()->GemProperties) @@ -9523,7 +10377,9 @@ uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const { Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color) + { count += pItem->GetGemCountWithID(item); + } } } } @@ -9537,20 +10393,28 @@ uint32 Player::GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipIte for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem) + { count += pItem->GetCount(); + } for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem); + } for (int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem) + { count += pItem->GetCount(); + } for (int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem); + } return count; } @@ -9957,7 +10821,9 @@ bool Player::HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_ for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i == int(except_slot)) + { continue; + } Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem && pItem->GetEntry() == item) @@ -9976,7 +10842,9 @@ bool Player::HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_ for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i == int(except_slot)) + { continue; + } Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem && pItem->GetProto()->Socket[0].Color) @@ -9999,15 +10867,21 @@ bool Player::HasItemOrGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i == int(except_slot)) + { continue; + } Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (!pItem) + { continue; + } ItemPrototype const* pProto = pItem->GetProto(); if (!pProto) + { continue; + } if (pProto->ItemLimitCategory == limitCategory) { @@ -10037,7 +10911,9 @@ InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Ite if (!pProto) { if (no_space_count) + { *no_space_count = count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } @@ -10049,7 +10925,9 @@ InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Ite if (curcount + count > uint32(pProto->MaxCount)) { if (no_space_count) + { *no_space_count = count + curcount - pProto->MaxCount; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10061,7 +10939,9 @@ InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Ite if (!limitEntry) { if (no_space_count) + { *no_space_count = count; + } return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED; } @@ -10072,7 +10952,9 @@ InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Ite if (curcount + count > uint32(limitEntry->maxCount)) { if (no_space_count) + { *no_space_count = count + curcount - limitEntry->maxCount; + } return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS; } } @@ -10087,7 +10969,9 @@ InventoryResult Player::_CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, Item // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) + { pItem2 = NULL; + } uint32 need_space; @@ -10145,7 +11029,9 @@ InventoryResult Player::_CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, Item } if (need_space > count) + { need_space = count; + } ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space); if (!newPosition.isContainedIn(dest)) @@ -10192,17 +11078,23 @@ InventoryResult Player::_CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, It { // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (j == skip_slot) + { continue; + } Item* pItem2 = GetItemByPos(bag, j); // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) + { pItem2 = NULL; + } // if merge skip empty, if !merge skip non-empty if ((pItem2 != NULL) != merge) + { continue; + } uint32 need_space = pProto->GetMaxStackSize(); @@ -10211,14 +11103,18 @@ InventoryResult Player::_CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, It // can be merged at least partly uint8 res = pItem2->CanBeMergedPartlyWith(pProto); if (res != EQUIP_ERR_OK) + { continue; + } // decrease at current stacksize need_space -= pItem2->GetCount(); } if (need_space > count) + { need_space = count; + } ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) @@ -10241,17 +11137,23 @@ InventoryResult Player::_CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 s { // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot if (INVENTORY_SLOT_BAG_0 == skip_bag && j == skip_slot) + { continue; + } Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, j); // ignore move item (this slot will be empty at move) if (pItem2 == pSrcItem) + { pItem2 = NULL; + } // if merge skip empty, if !merge skip non-empty if ((pItem2 != NULL) != merge) + { continue; + } uint32 need_space = pProto->GetMaxStackSize(); @@ -10260,14 +11162,18 @@ InventoryResult Player::_CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 s // can be merged at least partly uint8 res = pItem2->CanBeMergedPartlyWith(pProto); if (res != EQUIP_ERR_OK) + { continue; + } // descrease at current stacksize need_space -= pItem2->GetCount(); } if (need_space > count) + { need_space = count; + } ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space); if (!newPosition.isContainedIn(dest)) @@ -10292,7 +11198,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (!pProto) { if (no_space_count) + { *no_space_count = count; + } return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND; } @@ -10302,14 +11210,18 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (pItem->HasTemporaryLoot()) { if (no_space_count) + { *no_space_count = count; + } return EQUIP_ERR_ALREADY_LOOTED; } if (pItem->IsBindedNotWith(this)) { if (no_space_count) + { *no_space_count = count; + } return EQUIP_ERR_DONT_OWN_THAT_ITEM; } } @@ -10322,7 +11234,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (count == no_similar_count) { if (no_space_count) + { *no_space_count = no_similar_count; + } return res; } count -= no_similar_count; @@ -10335,7 +11249,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10347,7 +11263,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10366,7 +11284,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10378,7 +11298,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10387,12 +11309,16 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag res = _CanStoreItem_InBag(bag, dest, pProto, count, true, false, pItem, NULL_BAG, slot); if (res != EQUIP_ERR_OK) + { res = _CanStoreItem_InBag(bag, dest, pProto, count, true, true, pItem, NULL_BAG, slot); + } if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10404,7 +11330,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10417,7 +11345,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10429,7 +11359,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10437,12 +11369,16 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de { res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot); if (res != EQUIP_ERR_OK) + { res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot); + } if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10454,7 +11390,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10469,7 +11407,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10481,7 +11421,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } @@ -10491,7 +11433,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de { res = _CanStoreItem_InBag(i, dest, pProto, count, true, false, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -10501,7 +11445,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10511,7 +11457,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de { res = _CanStoreItem_InBag(i, dest, pProto, count, true, true, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -10521,7 +11469,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10534,7 +11484,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de { res = _CanStoreItem_InBag(i, dest, pProto, count, false, false, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -10544,7 +11496,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } @@ -10561,7 +11515,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de if (res != EQUIP_ERR_OK) { if (no_space_count) + { *no_space_count = count + no_similar_count; + } return res; } @@ -10573,7 +11529,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } @@ -10581,7 +11539,9 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de { res = _CanStoreItem_InBag(i, dest, pProto, count, false, true, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -10591,13 +11551,17 @@ InventoryResult Player::_CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& de } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS; } } if (no_space_count) + { *no_space_count = count + no_similar_count; + } return EQUIP_ERR_INVENTORY_FULL; } @@ -10769,7 +11733,9 @@ InventoryResult Player::CanStoreItems(Item** pItems, int count) const // special bag already checked if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER)) + { continue; + } for (uint32 j = 0; j < pBag->GetBagSize(); ++j) { @@ -10869,7 +11835,9 @@ InventoryResult Player::CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool } if (IsInCombat() && pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0) + { return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err + } if (IsNonMeleeSpellCasted(false)) { @@ -11149,7 +12117,9 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest { res = _CanStoreItem_InBag(bag, dest, pProto, count, true, false, pItem, NULL_BAG, slot); if (res != EQUIP_ERR_OK) + { res = _CanStoreItem_InBag(bag, dest, pProto, count, true, true, pItem, NULL_BAG, slot); + } if (res != EQUIP_ERR_OK) { @@ -11181,7 +12151,9 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest { res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot); if (res != EQUIP_ERR_OK) + { res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot); + } if (res != EQUIP_ERR_OK) { @@ -11219,7 +12191,9 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest { res = _CanStoreItem_InBag(i, dest, pProto, count, true, false, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -11232,7 +12206,9 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest { res = _CanStoreItem_InBag(i, dest, pProto, count, true, true, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -11248,7 +12224,9 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest { res = _CanStoreItem_InBag(i, dest, pProto, count, false, false, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -11273,7 +12251,9 @@ InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest { res = _CanStoreItem_InBag(i, dest, pProto, count, false, true, pItem, bag, slot); if (res != EQUIP_ERR_OK) + { continue; + } if (count == 0) { @@ -11332,17 +12312,25 @@ InventoryResult Player::CanUseItem(Item* pItem, bool direct_action) const { SkillLineAbilityEntry const* skillInfo = sSkillLineAbilityStore.LookupEntry(i); if (!skillInfo) + { continue; + } if (skillInfo->skillId != item_use_skill) + { continue; + } // can't learn if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0) + { continue; + } if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0) + { continue; + } allowScaleSkill = true; break; @@ -11562,9 +12550,13 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool if (!pItem2) { if (clone) + { pItem = pItem->CloneItem(count, this); + } else + { pItem->SetCount(count); + } if (!pItem) { @@ -11623,7 +12615,9 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool pItem2->SetCount(pItem2->GetCount() + count); if (IsInWorld() && update) + { pItem2->SendCreateUpdateToPlayer(this); + } if (!clone) { @@ -11681,7 +12675,9 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto && pProto->ItemSet) + { AddItemsSetItem(this, pItem); + } _ApplyItemMods(pItem, slot, true); @@ -11693,12 +12689,16 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s; if (getClass() == CLASS_ROGUE) + { cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s; + } SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell); if (!spellProto) + { sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell); + } else { m_weaponChangeTimer = spellProto->GetStartRecoveryTime(); @@ -11738,7 +12738,9 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) { pItem2->SetCount(pItem2->GetCount() + pItem->GetCount()); if (IsInWorld() && update) + { pItem2->SendCreateUpdateToPlayer(this); + } // delete item (it not in any slot currently) // pItem->DeleteFromDB(); @@ -11766,7 +12768,9 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) } // Apply Titan's Grip damage penalty if necessary if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152)) + { CastSpell(this, 49152, true); + } // only for full equip instead adding to stack GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry()); @@ -11797,7 +12801,9 @@ void Player::QuickEquipItem(uint16 pos, Item* pItem) } // Apply Titan's Grip damage penalty if necessary if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152)) + { CastSpell(this, 49152, true); + } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry()); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot + 1); @@ -11830,7 +12836,9 @@ void Player::VisualizeItem(uint8 slot, Item* pItem) // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory) if (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM) + { pItem->SetBinding(true); + } DEBUG_LOG("STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry()); @@ -11842,7 +12850,9 @@ void Player::VisualizeItem(uint8 slot, Item* pItem) pItem->SetContainer(NULL); if (slot < EQUIPMENT_SLOT_END) + { SetVisibleItemSlot(slot, pItem); + } pItem->SetState(ITEM_CHANGED, this); } @@ -11869,7 +12879,9 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto && pProto->ItemSet) + { RemoveItemsSetItem(this, pProto); + } _ApplyItemMods(pItem, slot, false); @@ -11911,7 +12923,9 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) SetVisibleItemSlot(slot, NULL); // Remove Titan's Grip damage penalty if necessary if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && !HasTwoHandWeaponInOneHand()) + { RemoveAurasDueToSpell(49152); + } } UpdateArmorSpecializations(); @@ -11920,7 +12934,9 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) { Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, bag); if (pBag) + { pBag->RemoveItem(slot, update); + } } pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid()); // pItem->SetGuidValue(ITEM_FIELD_OWNER, ObjectGuid()); not clear owner at remove (it will be set at store). This used in mail and auction code @@ -11929,7 +12945,9 @@ void Player::RemoveItem(uint8 bag, uint8 slot, bool update) // ApplyItemOnStoreSpell, for avoid re-apply will remove at _adding_ to not appropriate slot if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } } } @@ -11943,7 +12961,9 @@ void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) // item atStore spell not removed in RemoveItem (for avoid reappaly in slots changes), so do it directly if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot)) + { ApplyItemOnStoreSpell(it, false); + } it->RemoveFromUpdateQueueOf(this); if (it->IsInWorld()) @@ -11969,7 +12989,9 @@ void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool { // update owner for last item (this can be original item with wrong owner if (pLastItem->GetOwnerGuid() != GetObjectGuid()) + { pLastItem->SetOwnerGuid(GetObjectGuid()); + } // if this original item then it need create record in inventory // in case trade we already have item in other player inventory @@ -12005,7 +13027,9 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) RemoveItemDurations(pItem); if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot)) + { ApplyItemOnStoreSpell(pItem, false); + } ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount()); #ifdef ENABLE_ELUNA @@ -12023,7 +13047,9 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto && pProto->ItemSet) + { RemoveItemsSetItem(this, pProto); + } _ApplyItemMods(pItem, slot, false); } @@ -12052,7 +13078,9 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) m_items[slot] = NULL; } else if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, bag)) + { pBag->RemoveItem(slot, update); + } if (IsInWorld() && update) { @@ -12095,7 +13123,9 @@ void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequ ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount); pItem->SetCount(pItem->GetCount() - count + remcount); if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } pItem->SetState(ITEM_CHANGED, this); return; } @@ -12130,7 +13160,9 @@ void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequ ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount); pItem->SetCount(pItem->GetCount() - count + remcount); if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } pItem->SetState(ITEM_CHANGED, this); return; } @@ -12165,7 +13197,9 @@ void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequ ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount); pItem->SetCount(pItem->GetCount() - count + remcount); if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } pItem->SetState(ITEM_CHANGED, this); return; } @@ -12195,7 +13229,9 @@ void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequ ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount); pItem->SetCount(pItem->GetCount() - count + remcount); if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } pItem->SetState(ITEM_CHANGED, this); return; } @@ -12226,7 +13262,9 @@ void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequ ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount); pItem->SetCount(pItem->GetCount() - count + remcount); if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } pItem->SetState(ITEM_CHANGED, this); return; } @@ -12245,7 +13283,9 @@ void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone) for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) + { DestroyItem(INVENTORY_SLOT_BAG_0, i, update); + } // in inventory bags for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) @@ -12253,13 +13293,17 @@ void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) + { DestroyItem(i, j, update); + } // in equipment and bag list for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone)) + { DestroyItem(INVENTORY_SLOT_BAG_0, i, update); + } } void Player::DestroyConjuredItems(bool update) @@ -12272,7 +13316,9 @@ void Player::DestroyConjuredItems(bool update) for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->IsConjuredConsumable()) + { DestroyItem(INVENTORY_SLOT_BAG_0, i, update); + } // in inventory bags for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) @@ -12280,13 +13326,17 @@ void Player::DestroyConjuredItems(bool update) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->IsConjuredConsumable()) + { DestroyItem(i, j, update); + } // in equipment and bag list for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->IsConjuredConsumable()) + { DestroyItem(INVENTORY_SLOT_BAG_0, i, update); + } } void Player::DestroyItemCount(Item* pItem, uint32& count, bool update) @@ -12310,7 +13360,9 @@ void Player::DestroyItemCount(Item* pItem, uint32& count, bool update) pItem->SetCount(pItem->GetCount() - count); count = 0; if (IsInWorld() && update) + { pItem->SendCreateUpdateToPlayer(this); + } pItem->SetState(ITEM_CHANGED, this); } } @@ -12375,7 +13427,9 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) } if (IsInWorld()) + { pSrcItem->SendCreateUpdateToPlayer(this); + } pSrcItem->SetState(ITEM_CHANGED, this); StoreItem(dest, pNewItem, true); } @@ -12395,7 +13449,9 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) } if (IsInWorld()) + { pSrcItem->SendCreateUpdateToPlayer(this); + } pSrcItem->SetState(ITEM_CHANGED, this); BankItem(dest, pNewItem, true); } @@ -12415,7 +13471,9 @@ void Player::SplitItem(uint16 src, uint16 dst, uint32 count) } if (IsInWorld()) + { pSrcItem->SendCreateUpdateToPlayer(this); + } pSrcItem->SetState(ITEM_CHANGED, this); EquipItem(dest, pNewItem, true); AutoUnequipOffhandIfNeed(); @@ -12548,11 +13606,17 @@ void Player::SwapItem(uint16 src, uint16 dst) ItemPosCountVec sDest; uint16 eDest; if (IsInventoryPos(dst)) + { msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, false); + } else if (IsBankPos(dst)) + { msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, false); + } else if (IsEquipmentPos(dst)) + { msg = CanEquipItem(dstslot, eDest, pSrcItem, false); + } else { return; @@ -12566,9 +13630,13 @@ void Player::SwapItem(uint16 src, uint16 dst) RemoveItem(srcbag, srcslot, true); if (IsInventoryPos(dst)) + { StoreItem(sDest, pSrcItem, true); + } else if (IsBankPos(dst)) + { BankItem(sDest, pSrcItem, true); + } else if (IsEquipmentPos(dst)) { EquipItem(eDest, pSrcItem, true); @@ -12598,14 +13666,20 @@ void Player::SwapItem(uint16 src, uint16 dst) ItemPosCountVec sDest; uint16 eDest = 0; if (IsInventoryPos(dst)) + { msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, true); + } else if (IsBankPos(dst)) + { msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, true); + } else if (IsEquipmentPos(dst)) { msg = CanEquipItem(dstslot, eDest, pSrcItem, true); if (msg == EQUIP_ERR_OK) + { msg = CanUnequipItem(eDest, true); + } } if (msg != EQUIP_ERR_OK) @@ -12618,14 +13692,20 @@ void Player::SwapItem(uint16 src, uint16 dst) ItemPosCountVec sDest2; uint16 eDest2 = 0; if (IsInventoryPos(src)) + { msg = CanStoreItem(srcbag, srcslot, sDest2, pDstItem, true); + } else if (IsBankPos(src)) + { msg = CanBankItem(srcbag, srcslot, sDest2, pDstItem, true); + } else if (IsEquipmentPos(src)) { msg = CanEquipItem(srcslot, eDest2, pDstItem, true); if (msg == EQUIP_ERR_OK) + { msg = CanUnequipItem(eDest2, true); + } } if (msg != EQUIP_ERR_OK) @@ -12661,7 +13741,9 @@ void Player::SwapItem(uint16 src, uint16 dst) { Item* bagItem = fullBag->GetItemByPos(i); if (!bagItem) + { continue; + } ItemPrototype const* bagItemProto = bagItem->GetProto(); if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto)) @@ -12687,7 +13769,9 @@ void Player::SwapItem(uint16 src, uint16 dst) { Item* bagItem = fullBag->GetItemByPos(i); if (!bagItem) + { continue; + } fullBag->RemoveItem(i, true); emptyBag->StoreItem(count, bagItem, true); @@ -12704,19 +13788,31 @@ void Player::SwapItem(uint16 src, uint16 dst) // add to dest if (IsInventoryPos(dst)) + { StoreItem(sDest, pSrcItem, true); + } else if (IsBankPos(dst)) + { BankItem(sDest, pSrcItem, true); + } else if (IsEquipmentPos(dst)) + { EquipItem(eDest, pSrcItem, true); + } // add to src if (IsInventoryPos(src)) + { StoreItem(sDest2, pDstItem, true); + } else if (IsBankPos(src)) + { BankItem(sDest2, pDstItem, true); + } else if (IsEquipmentPos(src)) + { EquipItem(eDest2, pDstItem, true); + } AutoUnequipOffhandIfNeed(); } @@ -12764,14 +13860,20 @@ void Player::AddItemToBuyBackSlot(Item* pItem) SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetObjectGuid()); if (ItemPrototype const* pProto = pItem->GetProto()) + { SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount()); + } else + { SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0); + } SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime); // move to next (for non filled list is move most optimized choice) if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1) + { ++m_currentBuybackSlot; + } } } @@ -12806,7 +13908,9 @@ void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del) // if current backslot is filled set to now free slot if (m_items[m_currentBuybackSlot]) + { m_currentBuybackSlot = slot; + } } } @@ -12860,7 +13964,9 @@ void Player::SendBuyError(BuyResult msg, Creature* pCreature, uint32 item, uint3 data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid()); data << uint32(item); if (param > 0) + { data << uint32(param); + } data << uint8(msg); GetSession()->SendPacket(&data); } @@ -12872,7 +13978,9 @@ void Player::SendSellError(SellResult msg, Creature* pCreature, ObjectGuid itemG data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid()); data << ObjectGuid(itemGuid); if (param > 0) + { data << uint32(param); + } data << uint8(msg); GetSession()->SendPacket(&data); } @@ -12885,7 +13993,9 @@ void Player::TradeCancel(bool sendback) // send yellow "Trade canceled" message to both traders if (sendback) + { GetSession()->SendCancelTrade(); + } trader->GetSession()->SendCancelTrade(); @@ -12912,7 +14022,9 @@ void Player::UpdateItemDuration(uint32 time, bool realtimeonly) ++itr; // current element can be erased in UpdateDuration if ((realtimeonly && (item->GetProto()->ExtraFlags & ITEM_EXTRA_REAL_TIME_DURATION)) || !realtimeonly) + { item->UpdateDuration(this, time); + } } } @@ -12945,14 +14057,20 @@ void Player::AddEnchantmentDurations(Item* item) for (int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x) { if (x > PRISMATIC_ENCHANTMENT_SLOT && x < PROP_ENCHANTMENT_SLOT_0) + { continue; + } if (!item->GetEnchantmentId(EnchantmentSlot(x))) + { continue; + } uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x)); if (duration > 0) + { AddEnchantmentDuration(item, EnchantmentSlot(x), duration); + } } } @@ -12967,7 +14085,9 @@ void Player::RemoveEnchantmentDurations(Item* item) itr = m_enchantDuration.erase(itr); } else + { ++itr; + } } } @@ -12990,7 +14110,9 @@ void Player::RemoveAllEnchantments(EnchantmentSlot slot) next = m_enchantDuration.erase(itr); } else + { ++next; + } } // remove enchants from inventory items @@ -12999,7 +14121,9 @@ void Player::RemoveAllEnchantments(EnchantmentSlot slot) for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) if (pItem->GetEnchantmentId(slot)) + { pItem->ClearEnchantment(slot); + } // in inventory bags for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) @@ -13007,7 +14131,9 @@ void Player::RemoveAllEnchantments(EnchantmentSlot slot) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) if (Item* pItem = pBag->GetItemByPos(j)) if (pItem->GetEnchantmentId(slot)) + { pItem->ClearEnchantment(slot); + } } // duration == 0 will remove item enchant @@ -13109,11 +14235,17 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool break; case ITEM_ENCHANTMENT_TYPE_DAMAGE: if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND) + { HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply); + } else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND) + { HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply); + } else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED) + { HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply); + } break; case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL: { @@ -13141,12 +14273,18 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool } // Cast custom spell vs all equal basepoints got from enchant_amount if (basepoints) + { CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item); + } else + { CastSpell(this, enchant_spell_id, true, item); + } } else + { RemoveAurasDueToItemSpell(item, enchant_spell_id); + } } break; } @@ -13350,10 +14488,14 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool // visualize enchantment at player and equipped items if (slot == PERM_ENCHANTMENT_SLOT) + { SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0); + } if (slot == TEMP_ENCHANTMENT_SLOT) + { SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0); + } if (apply_dur) { @@ -13362,7 +14504,9 @@ void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool // set duration uint32 duration = item->GetEnchantmentDuration(slot); if (duration > 0) + { AddEnchantmentDuration(item, slot, duration); + } } else { @@ -13649,9 +14793,13 @@ void Player::SendNewItem(Item* item, uint32 count, bool received, bool created, data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory if (broadcast && GetGroup()) + { GetGroup()->BroadcastPacket(&data, true); + } else + { GetSession()->SendPacket(&data); + } } /*********************************************************/ @@ -13672,7 +14820,9 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) // if canSeeQuests (the default, top level menu) and no menu options exist for this, use options from default options if (pMenuItemBounds.first == pMenuItemBounds.second && canSeeQuests) + { pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0); + } for (GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr) { @@ -13682,11 +14832,15 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) if (itr->second.conditionId && !sObjectMgr.IsPlayerMeetToCondition(itr->second.conditionId, this, GetMap(), pSource, CONDITION_FROM_GOSSIP_OPTION)) { if (isGameMaster()) // Let GM always see menu items regardless of conditions + { isGMSkipConditionCheck = true; + } else { if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER) + { canSeeQuests = false; + } continue; // Skip this option } } @@ -13698,7 +14852,9 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) uint32 NpcFlagss = pCreature->GetUInt32Value(UNIT_NPC_FLAGS); if (!(itr->second.npc_option_NpcFlags & NpcFlagss)) + { continue; + } switch (itr->second.option_id) { @@ -13712,7 +14868,9 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) break; case GOSSIP_OPTION_SPIRITHEALER: if (!IsDead()) + { hasMenuItem = false; + } break; case GOSSIP_OPTION_VENDOR: { @@ -13729,25 +14887,37 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) // pet trainers not have spells in fact now /* FIXME: gossip menu with single unlearn pet talents option not show by some reason if (pCreature->GetCreatureInfo()->TrainerType == TRAINER_TYPE_PETS) + { hasMenuItem = false; + } else */ if (!pCreature->IsTrainerOf(this, false)) + { hasMenuItem = false; + } break; case GOSSIP_OPTION_UNLEARNTALENTS: if (!pCreature->CanTrainAndResetTalentsOf(this)) + { hasMenuItem = false; + } break; case GOSSIP_OPTION_UNLEARNPETSKILLS: if (pCreature->GetCreatureInfo()->TrainerType != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->TrainerClass != CLASS_HUNTER) + { hasMenuItem = false; + } else if (Pet* pet = GetPet()) { if (pet->getPetType() != HUNTER_PET || pet->m_spells.size() <= 1) + { hasMenuItem = false; + } } else + { hasMenuItem = false; + } break; case GOSSIP_OPTION_TAXIVENDOR: if (GetSession()->SendLearnNewTaxiNode(pCreature)) @@ -13757,11 +14927,15 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) break; case GOSSIP_OPTION_BATTLEFIELD: if (!pCreature->CanInteractWithBattleMaster(this, false)) + { hasMenuItem = false; + } break; case GOSSIP_OPTION_STABLEPET: if (getClass() != CLASS_HUNTER) + { hasMenuItem = false; + } break; case GOSSIP_OPTION_SPIRITGUIDE: case GOSSIP_OPTION_INNKEEPER: @@ -13788,7 +14962,9 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) break; case GOSSIP_OPTION_GOSSIP: if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER) + { hasMenuItem = false; + } break; default: hasMenuItem = false; @@ -13810,10 +14986,14 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) if (GossipMenuItemsLocale const* no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry)) { if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty()) + { strOptionText = no->OptionText[loc_idx]; + } if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty()) + { strBoxText = no->BoxText[loc_idx]; + } } } @@ -13830,7 +15010,9 @@ void Player::PrepareGossipMenu(WorldObject* pSource, uint32 menuId) } if (canSeeQuests) + { PrepareQuestMenu(pSource->GetObjectGuid()); + } // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-) /*if (pMenu->Empty()) @@ -13881,7 +15063,9 @@ void Player::SendPreparedGossip(WorldObject* pSource) uint32 textId = GetGossipTextId(pSource); if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId()) + { textId = GetGossipTextId(menuId, pSource); + } PlayerTalkClass->SendGossipMenu(textId, pSource->GetObjectGuid()); } @@ -13911,9 +15095,13 @@ void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 me if (moneyTake > 0) { if (GetMoney() >= moneyTake) + { ModifyMoney(-int64(moneyTake)); + } else + { return; // cheating + } } if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) @@ -13932,7 +15120,9 @@ void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 me case GOSSIP_OPTION_GOSSIP: { if (pMenuData.m_gAction_poi) + { PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi); + } // send new menu || close gossip || stay at current menu if (pMenuData.m_gAction_menu > 0) @@ -13950,7 +15140,9 @@ void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 me } case GOSSIP_OPTION_SPIRITHEALER: if (IsDead()) + { ((Creature*)pSource)->CastSpell(((Creature*)pSource), 17251, true, NULL, NULL, GetObjectGuid()); + } break; case GOSSIP_OPTION_QUESTGIVER: PrepareQuestMenu(guid); @@ -14138,16 +15330,24 @@ void Player::PrepareQuestMenu(ObjectGuid guid) Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) + { continue; + } QuestStatus status = GetQuestStatus(quest_id); if (status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(quest_id)) + { qm.AddMenuItem(quest_id, 4); + } else if (status == QUEST_STATUS_INCOMPLETE) + { qm.AddMenuItem(quest_id, 4); + } else if (status == QUEST_STATUS_AVAILABLE) + { qm.AddMenuItem(quest_id, 2); + } } for (QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr) @@ -14157,14 +15357,20 @@ void Player::PrepareQuestMenu(ObjectGuid guid) Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) + { continue; + } QuestStatus status = GetQuestStatus(quest_id); if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false)) + { qm.AddMenuItem(quest_id, 4); + } else if (status == QUEST_STATUS_NONE && CanTakeQuest(pQuest, false)) + { qm.AddMenuItem(quest_id, 2); + } } } @@ -14191,15 +15397,23 @@ void Player::SendPreparedQuest(ObjectGuid guid) if (pQuest) { if (icon == 4 && !GetQuestRewardStatus(quest_id)) + { PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true); + } else if (icon == 4) + { PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true); + } // Send completable on repeatable and autoCompletable quest if player don't have quest // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not) else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDailyOrWeekly()) + { PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true); + } else + { PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true); + } } } // multiply entries @@ -14367,7 +15581,9 @@ bool Player::CanCompleteQuest(uint32 quest_id) const QuestStatus status = q_itr != mQuestStatus.end() ? q_itr->second.m_status : QUEST_STATUS_NONE; if (status == QUEST_STATUS_COMPLETE) + { return false; // not allow re-complete quest + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id); @@ -14425,7 +15641,9 @@ bool Player::CanCompleteQuest(uint32 quest_id) const for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) { if (qInfo->ReqCreatureOrGOId[i] == 0) + { continue; + } if (qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i]) { @@ -14531,7 +15749,9 @@ bool Player::CanRewardQuest(Quest const* pQuest, bool msg) const GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i]) { if (msg) + { SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]); + } return false; } @@ -14544,7 +15764,9 @@ bool Player::CanRewardQuest(Quest const* pQuest, bool msg) const !HasCurrencyCount(pQuest->ReqCurrencyId[i], int32(pQuest->ReqCurrencyCount[i] * GetCurrencyPrecision(pQuest->ReqCurrencyId[i])))) { if (msg) + { SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL); + } return false; } @@ -14647,7 +15869,9 @@ void Player::AddQuest(Quest const* pQuest, Object* questGiver) if (pQuest->GetRepObjectiveFaction()) if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction())) + { GetReputationMgr().SetVisible(factionEntry); + } uint32 qtime = 0; if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) @@ -14656,19 +15880,25 @@ void Player::AddQuest(Quest const* pQuest, Object* questGiver) // shared timed quest if (questGiver && questGiver->GetTypeId() == TYPEID_PLAYER) + { limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILLISECONDS; + } AddTimedQuest(quest_id); questStatusData.m_timer = limittime * IN_MILLISECONDS; qtime = static_cast(time(NULL)) + limittime; } else + { questStatusData.m_timer = 0; + } SetQuestSlot(log_slot, quest_id, qtime); if (questStatusData.uState != QUEST_NEW) + { questStatusData.uState = QUEST_CHANGED; + } // quest accept scripts if (questGiver) @@ -14709,10 +15939,14 @@ void Player::AddQuest(Quest const* pQuest, Object* questGiver) } if (pQuest->GetSrcItemId() == questGiver->GetEntry()) + { notRequiredItem = false; + } if (notRequiredItem) + { DestroyItem(((Item*)questGiver)->GetBagSlot(), ((Item*)questGiver)->GetSlot(), true); + } } GiveQuestSourceItemIfNeed(pQuest); @@ -14752,12 +15986,16 @@ void Player::CompleteQuest(uint32 quest_id, QuestStatus status) uint16 log_slot = FindQuestSlot(quest_id); if (log_slot < MAX_QUEST_LOG_SIZE) + { SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE); + } if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id)) { if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED)) + { RewardQuest(qInfo, 0, this, false); + } } } } @@ -14780,7 +16018,9 @@ void Player::RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, { ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(pQuest->ReqSourceId[i]); if (iProto && iProto->Bonding == BIND_QUEST_ITEM) + { DestroyItemCount(pQuest->ReqSourceId[i], pQuest->ReqSourceCount[i], true, false, true); + } } } @@ -14852,7 +16092,9 @@ void Player::RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, // reward money used if > xp replacement money if (pQuest->GetRewOrReqMoney() > int32(money)) + { money = pQuest->GetRewOrReqMoney(); + } ModifyMoney(money); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money); @@ -14860,17 +16102,23 @@ void Player::RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, // req money case if (pQuest->GetRewOrReqMoney() < 0) + { ModifyMoney(pQuest->GetRewOrReqMoney()); + } // honor reward if (uint32 honor = pQuest->CalculateRewardHonor(getLevel())) + { RewardHonor(NULL, 0, honor); + } // title reward if (pQuest->GetCharTitleId()) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId())) + { SetTitle(titleEntry); + } } if (pQuest->GetBonusTalents()) @@ -14881,7 +16129,9 @@ void Player::RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, // Send reward mail if (uint32 mail_template_id = pQuest->GetRewMailTemplateId()) + { MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_HAS_BODY, pQuest->GetRewMailDelaySecs()); + } if (pQuest->IsDaily()) { @@ -14890,22 +16140,34 @@ void Player::RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, } if (pQuest->IsWeekly()) + { SetWeeklyQuestStatus(quest_id); + } if (pQuest->IsMonthly()) + { SetMonthlyQuestStatus(quest_id); + } if (!pQuest->IsRepeatable()) + { SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE); + } else + { SetQuestStatus(quest_id, QUEST_STATUS_NONE); + } q_status.m_rewarded = true; if (q_status.uState != QUEST_NEW) + { q_status.uState = QUEST_CHANGED; + } if (announce) + { SendQuestReward(pQuest, xp); + } bool handled = false; @@ -14926,12 +16188,18 @@ void Player::RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data) if (pQuest->GetRewSpellCast() > 0) + { CastSpell(this, pQuest->GetRewSpellCast(), true); + } else if (pQuest->GetRewSpell() > 0) + { CastSpell(this, pQuest->GetRewSpell(), true); + } if (pQuest->GetZoneOrSort() > 0) + { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort()); + } GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT); GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId()); @@ -14971,7 +16239,9 @@ void Player::IncompleteQuest(uint32 quest_id) uint16 log_slot = FindQuestSlot(quest_id); if (log_slot < MAX_QUEST_LOG_SIZE) + { RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE); + } } } @@ -14999,7 +16269,9 @@ void Player::FailQuest(uint32 questId) SendQuestTimerFailed(questId); } else + { SendQuestFailed(questId); + } } } @@ -15017,7 +16289,9 @@ bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const if (GetSkillValue(skill) < qInfo->GetRequiredSkillValue()) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15039,7 +16313,9 @@ bool Player::SatisfyQuestSpell(Quest const* qInfo, bool msg) const if (!HasSpell(spell)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_SPELL); + } return false; } @@ -15052,7 +16328,9 @@ bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) const if (getLevel() < qInfo->GetMinLevel()) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15121,7 +16399,9 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const // skip checked quest id, only state of other quests in group is interesting if (exclude_Id == prevId) + { continue; + } QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id); @@ -15129,7 +16409,9 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const if (i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15164,13 +16446,17 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const // skip checked quest id, only state of other quests in group is interesting if (exclude_Id == prevId) + { continue; + } // alternative quest from group also must be active if (!IsCurrentQuest(exclude_Id)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15183,7 +16469,9 @@ bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const // Has only positive prev. quests in non-rewarded state // and negative prev. quests in non-active state if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15200,7 +16488,9 @@ bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const if ((reqClass & getClassMask()) == 0) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15220,7 +16510,9 @@ bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) const if ((reqraces & getRaceMask()) == 0) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE); + } return false; } @@ -15234,7 +16526,9 @@ bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) const if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue()) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15243,7 +16537,9 @@ bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) const if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue()) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15258,7 +16554,9 @@ bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) const if (itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON); + } return false; } @@ -15271,7 +16569,9 @@ bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) const if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED); + } return false; } @@ -15297,14 +16597,18 @@ bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const // skip checked quest id, only state of other quests in group is interesting if (exclude_Id == qInfo->GetQuestId()) + { continue; + } // not allow have daily quest if daily quest from exclusive group already recently completed Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id); if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15316,7 +16620,9 @@ bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15338,7 +16644,9 @@ bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) const (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15365,7 +16673,9 @@ bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const if (IsCurrentQuest(prevId)) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); + } return false; } @@ -15401,7 +16711,9 @@ bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const if (!have_slot) { if (msg) + { SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_TOO_MANY_DAILY_QUESTS); + } return false; } @@ -15453,14 +16765,18 @@ bool Player::CanGiveQuestSourceItemIfNeed(Quest const* pQuest, ItemPosCountVec* msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, destTemp, srcitem, count); } else + { msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, *dest, srcitem, count); + } if (msg == EQUIP_ERR_OK) { return true; } else + { SendEquipError(msg, NULL, NULL, srcitem); + } return false; } @@ -15493,7 +16809,9 @@ bool Player::TakeQuestSourceItem(uint32 quest_id, bool msg) { uint32 count = qInfo->GetSrcItemCount(); if (count <= 0) + { count = 1; + } // exist one case when destroy source quest item not possible: // non un-equippable item (equipped non-empty bag, for example) @@ -15501,7 +16819,9 @@ bool Player::TakeQuestSourceItem(uint32 quest_id, bool msg) if (res != EQUIP_ERR_OK) { if (msg) + { SendEquipError(res, NULL, NULL, srcitem); + } return false; } @@ -15564,7 +16884,9 @@ void Player::SetQuestStatus(uint32 quest_id, QuestStatus status) q_status.m_status = status; if (q_status.uState != QUEST_NEW) + { q_status.uState = QUEST_CHANGED; + } } UpdateForQuestWorldObjects(); @@ -15633,11 +16955,15 @@ void Player::AreaExploredOrEventHappens(uint32 questId) q_status.m_explored = true; if (q_status.uState != QUEST_NEW) + { q_status.uState = QUEST_CHANGED; + } } } if (CanCompleteQuest(questId)) + { CompleteQuest(questId); + } } } @@ -15652,11 +16978,15 @@ void Player::GroupEventHappens(uint32 questId, WorldObject const* pEventObject) // for any leave or dead (with not released body) group member at appropriate distance if (pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) + { pGroupGuy->AreaExploredOrEventHappens(questId); + } } } else + { AreaExploredOrEventHappens(questId); + } } void Player::CurrencyAddedQuestCheck(uint32 entry) @@ -15665,16 +16995,22 @@ void Player::CurrencyAddedQuestCheck(uint32 entry) { uint32 questid = GetQuestSlotQuestId(i); if (questid == 0) + { continue; + } QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status != QUEST_STATUS_INCOMPLETE) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) + { continue; + } for (int j = 0; j < QUEST_REQUIRED_CURRENCY_COUNT; ++j) { @@ -15682,7 +17018,9 @@ void Player::CurrencyAddedQuestCheck(uint32 entry) if (reqcurrency == entry) { if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } } } } @@ -15696,10 +17034,14 @@ void Player::CurrencyRemovedQuestCheck(uint32 entry) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) + { continue; + } for (int j = 0; j < QUEST_REQUIRED_CURRENCY_COUNT; ++j) { @@ -15707,7 +17049,9 @@ void Player::CurrencyRemovedQuestCheck(uint32 entry) if (reqcurrency == entry) { if (!HasCurrencyCount(entry, int32(qInfo->ReqCurrencyCount[j] * GetCurrencyPrecision(entry)))) + { IncompleteQuest(questid); + } } } } @@ -15721,16 +17065,22 @@ void Player::ItemAddedQuestCheck(uint32 entry, uint32 count) { uint32 questid = GetQuestSlotQuestId(i); if (questid == 0) + { continue; + } QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status != QUEST_STATUS_INCOMPLETE) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) + { continue; + } for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j) { @@ -15744,10 +17094,14 @@ void Player::ItemAddedQuestCheck(uint32 entry, uint32 count) uint32 additemcount = (curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount); q_status.m_itemcount[j] += additemcount; if (q_status.uState != QUEST_NEW) + { q_status.uState = QUEST_CHANGED; + } } if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } return; } } @@ -15761,12 +17115,18 @@ void Player::ItemRemovedQuestCheck(uint32 entry, uint32 count) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) + { continue; + } if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER)) + { continue; + } for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j) { @@ -15778,9 +17138,13 @@ void Player::ItemRemovedQuestCheck(uint32 entry, uint32 count) uint32 reqitemcount = qInfo->ReqItemCount[j]; uint32 curitemcount; if (q_status.m_status != QUEST_STATUS_COMPLETE) + { curitemcount = q_status.m_itemcount[j]; + } else + { curitemcount = GetItemCount(entry, true); + } if (curitemcount < reqitemcount + count) { uint32 remitemcount = (curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount); @@ -15802,25 +17166,35 @@ void Player::SpellAddedQuestCheck(uint32 entry) { uint32 questid = GetQuestSlotQuestId(i); if (questid == 0) + { continue; + } QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status != QUEST_STATUS_INCOMPLETE) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) + { continue; + } uint32 reqspelllearned = qInfo->GetReqSpellLearned(); if (!reqspelllearned) + { continue; + } if (reqspelllearned == entry) { if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } } } @@ -15833,19 +17207,27 @@ void Player::SpellRemovedQuestCheck(uint32 entry) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) + { continue; + } uint32 reqspelllearned = qInfo->GetReqSpellLearned(); if (!reqspelllearned) + { continue; + } if (reqspelllearned == entry) { if (!HasSpell(entry)) + { IncompleteQuest(questid); + } } } @@ -15855,11 +17237,15 @@ void Player::SpellRemovedQuestCheck(uint32 entry) void Player::KilledMonster(CreatureInfo const* cInfo, ObjectGuid guid) { if (cInfo->Entry) + { KilledMonsterCredit(cInfo->Entry, guid); + } for (int i = 0; i < MAX_KILL_CREDIT; ++i) if (cInfo->KillCredit[i]) + { KilledMonsterCredit(cInfo->KillCredit[i], guid); + } } void Player::KilledMonsterCredit(uint32 entry, ObjectGuid guid) @@ -15871,11 +17257,15 @@ void Player::KilledMonsterCredit(uint32 entry, ObjectGuid guid) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) + { continue; + } // just if !ingroup || !noraidgroup || raidgroup QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid())) @@ -15886,11 +17276,15 @@ void Player::KilledMonsterCredit(uint32 entry, ObjectGuid guid) { // skip GO activate objective or none if (qInfo->ReqCreatureOrGOId[j] <= 0) + { continue; + } // skip Cast at creature objective if (qInfo->ReqSpell[j] != 0) + { continue; + } uint32 reqkill = qInfo->ReqCreatureOrGOId[j]; @@ -15902,13 +17296,17 @@ void Player::KilledMonsterCredit(uint32 entry, ObjectGuid guid) { q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount; if (q_status.uState != QUEST_NEW) + { q_status.uState = QUEST_CHANGED; + } SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, q_status.m_creatureOrGOcount[j]); } if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). continue; @@ -15928,28 +17326,40 @@ void Player::CastedCreatureOrGO(uint32 entry, ObjectGuid guid, uint32 spell_id, { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) + { continue; + } if (!original_caster && !qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE)) + { continue; + } if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST)) + { continue; + } QuestStatusData& q_status = mQuestStatus[questid]; if (q_status.m_status != QUEST_STATUS_INCOMPLETE) + { continue; + } for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { // skip kill creature objective (0) or wrong spell casts if (qInfo->ReqSpell[j] != spell_id) + { continue; + } uint32 reqTarget = 0; @@ -15970,7 +17380,9 @@ void Player::CastedCreatureOrGO(uint32 entry, ObjectGuid guid, uint32 spell_id, // other not this creature/GO related objectives if (reqTarget != entry) + { continue; + } uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j]; uint32 curCastCount = q_status.m_creatureOrGOcount[j]; @@ -15978,13 +17390,17 @@ void Player::CastedCreatureOrGO(uint32 entry, ObjectGuid guid, uint32 spell_id, { q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount; if (q_status.uState != QUEST_NEW) + { q_status.uState = QUEST_CHANGED; + } SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, q_status.m_creatureOrGOcount[j]); } if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). break; @@ -15999,11 +17415,15 @@ void Player::TalkedToCreature(uint32 entry, ObjectGuid guid) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (!qInfo) + { continue; + } QuestStatusData& q_status = mQuestStatus[questid]; @@ -16015,7 +17435,9 @@ void Player::TalkedToCreature(uint32 entry, ObjectGuid guid) { // skip spell casts and Gameobject objectives if (qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0) + { continue; + } uint32 reqTarget = 0; @@ -16023,7 +17445,9 @@ void Player::TalkedToCreature(uint32 entry, ObjectGuid guid) // checked at quest_template loading reqTarget = qInfo->ReqCreatureOrGOId[j]; else + { continue; + } if (reqTarget == entry) { @@ -16037,7 +17461,9 @@ void Player::TalkedToCreature(uint32 entry, ObjectGuid guid) SendQuestUpdateAddCreatureOrGo(qInfo, guid, j, q_status.m_creatureOrGOcount[j]); } if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization). continue; @@ -16054,7 +17480,9 @@ void Player::MoneyChanged(uint32 count) { uint32 questid = GetQuestSlotQuestId(i); if (!questid) + { continue; + } Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid); if (qInfo && qInfo->GetRewOrReqMoney() < 0) @@ -16066,13 +17494,17 @@ void Player::MoneyChanged(uint32 count) if (int32(count) >= -qInfo->GetRewOrReqMoney()) { if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } } } else if (q_status.m_status == QUEST_STATUS_COMPLETE) { if (int32(count) < -qInfo->GetRewOrReqMoney()) + { IncompleteQuest(questid); + } } } } @@ -16093,12 +17525,16 @@ void Player::ReputationChanged(FactionEntry const* factionEntry) { if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue()) if (CanCompleteQuest(questid)) + { CompleteQuest(questid); + } } else if (q_status.m_status == QUEST_STATUS_COMPLETE) { if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue()) + { IncompleteQuest(questid); + } } } } @@ -16112,11 +17548,15 @@ bool Player::HasQuestForItem(uint32 itemid) const { uint32 questid = GetQuestSlotQuestId(i); if (questid == 0) + { continue; + } QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid); if (qs_itr == mQuestStatus.end()) + { continue; + } QuestStatusData const& q_status = qs_itr->second; @@ -16124,11 +17564,15 @@ bool Player::HasQuestForItem(uint32 itemid) const { Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid); if (!qinfo) + { continue; + } // hide quest if player is in raid-group and quest is no raid quest if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid() && !InBattleGround()) + { continue; + } // There should be no mixed ReqItem/ReqSource drop // This part for ReqItem drop @@ -16320,7 +17764,9 @@ void Player::SendQuestUpdateAddCreatureOrGo(Quest const* pQuest, ObjectGuid guid uint16 log_slot = FindQuestSlot(pQuest->GetQuestId()); if (log_slot < MAX_QUEST_LOG_SIZE) + { SetQuestSlotCounter(log_slot, creatureOrGO_idx, count); + } } void Player::SendQuestGiverStatusMultiple() @@ -16338,15 +17784,21 @@ void Player::SendQuestGiverStatusMultiple() Creature* questgiver = GetMap()->GetAnyTypeCreature(*itr); if (!questgiver || questgiver->IsHostileTo(this)) + { continue; + } if (!questgiver->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER)) + { continue; + } uint8 dialogStatus = sScriptMgr.GetDialogStatus(this, questgiver); if (dialogStatus == DIALOG_STATUS_REWARD_REP) + { dialogStatus = GetSession()->getDialogStatus(this, questgiver, DIALOG_STATUS_NONE); + } data << questgiver->GetObjectGuid(); data << uint8(dialogStatus); @@ -16357,15 +17809,21 @@ void Player::SendQuestGiverStatusMultiple() GameObject* questgiver = GetMap()->GetGameObject(*itr); if (!questgiver) + { continue; + } if (questgiver->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER) + { continue; + } uint8 dialogStatus = sScriptMgr.GetDialogStatus(this, questgiver); if (dialogStatus == DIALOG_STATUS_REWARD_REP) + { dialogStatus = GetSession()->getDialogStatus(this, questgiver, DIALOG_STATUS_NONE); + } data << questgiver->GetObjectGuid(); data << uint8(dialogStatus); @@ -16471,7 +17929,9 @@ void Player::_LoadEquipmentSets(QueryResult* result) ++count; if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit + { break; + } } while (result->NextRow()); delete result; @@ -16618,7 +18078,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) uint64 money = fields[8].GetUInt64(); if (money > MAX_MONEY_AMOUNT) + { money = MAX_MONEY_AMOUNT; + } SetMoney(money); SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32()); @@ -16669,7 +18131,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) uint32 difficulty = fields[39].GetUInt32(); if (difficulty >= MAX_DUNGEON_DIFFICULTY || getLevel() < LEVELREQUIREMENT_HEROIC) + { difficulty = DUNGEON_DIFFICULTY_NORMAL; + } SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP)); @@ -16681,11 +18145,15 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) { uint32 arena_team_id = GetArenaTeamId(arena_slot); if (!arena_team_id) + { continue; + } if (ArenaTeam* at = sObjectMgr.GetArenaTeamById(arena_team_id)) if (at->HaveMember(GetObjectGuid())) + { continue; + } // arena team not exist or not member, cleanup fields for (int j = 0; j < ARENA_TEAM_END; ++j) @@ -16736,7 +18204,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) { // leave bg if (player_at_bg) + { currentBg->RemovePlayerAtLeave(GetObjectGuid(), false, true); + } // move to bg enter point const WorldLocation& _loc = GetBattleGroundEntryPoint(); @@ -16844,9 +18314,13 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) { AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId()); if (at) + { Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation); + } else + { sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId()); + } } SaveRecallPosition(); @@ -16861,7 +18335,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) // calculate sobering. after 15 minutes logged out, the player will be sober again uint8 newDrunkValue = 0; if (time_diff < uint32(GetDrunkValue()) * 9) + { newDrunkValue = GetDrunkValue() - time_diff / 9; + } SetDrunkValue(newDrunkValue); @@ -16876,7 +18352,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & (PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM); if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM)) + { SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags); + } m_taxi.LoadTaxiMask(fields[17].GetString()); // must be before InitTaxiNodesForLevel @@ -16897,7 +18375,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) m_deathExpireTime = (time_t)fields[37].GetUInt64(); if (m_deathExpireTime > now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP) + { m_deathExpireTime = now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP - 1; + } std::string taxi_nodes = fields[38].GetCppString(); @@ -16936,13 +18416,19 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) for (uint8 i = 0; i < MAX_TALENT_SPEC_COUNT; ++i) { if (i >= talentTrees.size()) + { break; + } uint32 talentTree = atol(talentTrees[i].c_str()); if (!talentTree || sTalentTabStore.LookupEntry(talentTree)) + { m_talentsPrimaryTree[i] = talentTree; + } else if (i == m_activeSpec) + { SetAtLoginFlag(AT_LOGIN_RESET_TALENTS); // invalid tree, reset talents + } } // reset stats before loading any modifiers @@ -16955,7 +18441,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) m_rest_bonus = fields[21].GetFloat(); if (time_diff > 0) + { SetRestBonus(GetRestBonus() + ComputeRest(time_diff, true, (fields[23].GetInt32() > 0))); + } // load skills after InitStatsForLevel because it triggering aura apply also _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS)); @@ -16974,7 +18462,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura) if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) + { m_deathState = DEAD; + } _LoadCurrencies(holder->GetResult(PLAYER_LOGIN_QUERY_LOADCURRENCIES)); _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS)); @@ -17008,7 +18498,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded uint32 curTitle = fields[43].GetUInt32(); if (curTitle && !HasTitle(curTitle)) + { curTitle = 0; + } SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle); @@ -17026,7 +18518,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) // problems with taxi path loading TaxiNodesEntry const* nodeEntry = NULL; if (uint32 node_id = m_taxi.GetTaxiSource()) + { nodeEntry = sTaxiNodesStore.LookupEntry(node_id); + } if (!nodeEntry) // don't know taxi start node, to homebind { @@ -17069,7 +18563,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) // Spell code allow apply any auras to dead character in load time in aura/spell/item loading // Do now before stats re-calculation cleanup for ghost state unexpected auras if (!IsAlive()) + { RemoveAllAurasOnDeath(); + } // apply all stat bonuses from items and auras SetCanModifyStats(true); @@ -17113,7 +18609,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) case 1: break; // visible case 2: // save state if (extraflags & PLAYER_EXTRA_GM_INVISIBLE) + { SetGMVisible(false); + } break; } @@ -17124,7 +18622,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) case 1: SetAcceptTicket(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS) + { SetAcceptTicket(true); + } break; } @@ -17135,7 +18635,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) case 1: SetGMChat(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_GM_CHAT) + { SetGMChat(true); + } break; } @@ -17146,7 +18648,9 @@ bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder) case 1: SetAcceptWhispers(true); break; // enable case 2: // save state if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS) + { SetAcceptWhispers(true); + } break; } } @@ -17179,10 +18683,14 @@ bool Player::IsTappedByMeOrMyGroup(Creature* creature) { /* Check groups are the same */ if (plr_group != my_group) - { return false; } // Cheater, deny loot + { + return false; // Cheater, deny loot + } } else - { return false; } // We're not in a group, probably cheater + { + return false; // We're not in a group, probably cheater + } /* We're in the looters group, so mob is tapped by us */ return true; @@ -17196,7 +18704,9 @@ bool Player::IsTappedByMeOrMyGroup(Creature* creature) else /* Don't know what happened to the recipient, probably disconnected * Either way, it isn't us, so mark as tapped */ - { return false; } + { + return false; + } return false; } @@ -17254,7 +18764,9 @@ void Player::_LoadActions(QueryResult* result) uint8 type = fields[3].GetUInt8(); if (ActionButton* ab = addActionButton(spec, button, action, type)) + { ab->uState = ACTIONBUTTON_UNCHANGED; + } else { sLog.outError(" ...at loading, and will deleted in DB also"); @@ -17308,7 +18820,9 @@ void Player::_LoadAuras(QueryResult* result, uint32 timediff) if (remaintime != -1 && !IsPositiveSpell(spellproto)) { if (remaintime / IN_MILLISECONDS <= int32(timediff)) + { continue; + } remaintime -= timediff * IN_MILLISECONDS; } @@ -17317,18 +18831,28 @@ void Player::_LoadAuras(QueryResult* result, uint32 timediff) if (uint32 procCharges = spellproto->GetProcCharges()) { if (remaincharges <= 0 || remaincharges > procCharges) + { remaincharges = procCharges; + } } else + { remaincharges = 0; + } uint32 defstackamount = spellproto->GetStackAmount(); if (!defstackamount) + { stackcount = 1; + } else if (defstackamount < stackcount) + { stackcount = defstackamount; + } else if (!stackcount) + { stackcount = 1; + } SpellAuraHolder* holder = CreateSpellAuraHolder(spellproto, this, NULL); holder->SetLoadedState(caster_guid, ObjectGuid(HIGHGUID_ITEM, item_lowguid), stackcount, remaincharges, maxduration, remaintime); @@ -17336,11 +18860,15 @@ void Player::_LoadAuras(QueryResult* result, uint32 timediff) for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if ((effIndexMask & (1 << i)) == 0) + { continue; + } Aura* aura = CreateAura(spellproto, SpellEffectIndex(i), NULL, holder, this); if (!damage[i]) + { damage[i] = aura->GetModifier()->m_amount; + } aura->SetLoadedState(damage[i], periodicTime[i]); holder->AddAura(aura, SpellEffectIndex(i)); @@ -17350,20 +18878,26 @@ void Player::_LoadAuras(QueryResult* result, uint32 timediff) { // reset stolen single target auras if (caster_guid != GetObjectGuid() && holder->GetTrackedAuraType() == TRACK_AURA_TYPE_SINGLE_TARGET) + { holder->SetTrackedAuraType(TRACK_AURA_TYPE_NOT_TRACKED); + } AddSpellAuraHolder(holder); DETAIL_LOG("Added auras from spellid %u", spellproto->Id); } else + { delete holder; + } } while (result->NextRow()); delete result; } if (getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) + { CastSpell(this, SPELL_ID_PASSIVE_BATTLE_STANCE, true); + } } void Player::_LoadGlyphs(QueryResult* result) @@ -17509,32 +19043,46 @@ void Player::_LoadInventory(QueryResult* result, uint32 timediff) { ItemPosCountVec dest; if (CanStoreItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false) == EQUIP_ERR_OK) + { item = StoreItem(dest, item, true); + } else + { success = false; + } } else if (IsEquipmentPos(INVENTORY_SLOT_BAG_0, slot)) { uint16 dest; if (CanEquipItem(slot, dest, item, false, false) == EQUIP_ERR_OK) + { QuickEquipItem(dest, item); + } else + { success = false; + } } else if (IsBankPos(INVENTORY_SLOT_BAG_0, slot)) { ItemPosCountVec dest; if (CanBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false, false) == EQUIP_ERR_OK) + { item = BankItem(dest, item, true); + } else + { success = false; + } } if (success) { // store bags that may contain items in them if (item->IsBag() && IsBagPos(item->GetPos())) + { bagMap[item_lowguid] = (Bag*)item; + } } } // the item/bag in a bag @@ -17547,12 +19095,18 @@ void Player::_LoadInventory(QueryResult* result, uint32 timediff) { ItemPosCountVec dest; if (CanStoreItem(itr->second->GetSlot(), slot, dest, item, false) == EQUIP_ERR_OK) + { item = StoreItem(dest, item, true); + } else + { success = false; + } } else + { success = false; + } } // item's state may have changed after stored @@ -17562,11 +19116,15 @@ void Player::_LoadInventory(QueryResult* result, uint32 timediff) // restore container unchanged state also if (item->GetContainer()) + { item->GetContainer()->SetState(ITEM_UNCHANGED, this); + } // recharged mana gem if (timediff > 15 * MINUTE && proto->ItemLimitCategory == ITEM_LIMIT_CATEGORY_MANA_GEM) + { item->RestoreCharges(); + } } else { @@ -17652,7 +19210,9 @@ void Player::_LoadMailedItems(QueryResult* result) Mail* mail = GetMail(mail_id); if (!mail) + { continue; + } mail->AddItem(item_guid_low, item_template); ItemPrototype const* proto = ObjectMgr::GetItemPrototype(item_template); @@ -17723,7 +19283,9 @@ void Player::_LoadMails(QueryResult* result) m_mail.push_back(m); if (m->mailTemplateId && !m->has_items) + { m->prepareTemplateItems(this); + } } while (result->NextRow()); delete result; @@ -17737,7 +19299,9 @@ void Player::LoadPet() { Pet* pet = new Pet; if (!pet->LoadPetFromDB(this, 0, 0, true)) + { delete pet; + } } } @@ -17766,7 +19330,9 @@ void Player::_LoadQuestStatus(QueryResult* result) uint32 qstatus = fields[1].GetUInt32(); if (qstatus < MAX_QUEST_STATUS) + { questStatusData.m_status = QuestStatus(qstatus); + } else { questStatusData.m_status = QUEST_STATUS_NONE; @@ -17783,12 +19349,18 @@ void Player::_LoadQuestStatus(QueryResult* result) AddTimedQuest(quest_id); if (quest_time <= sWorld.GetGameTime()) + { questStatusData.m_timer = 1; + } else + { questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILLISECONDS; + } } else + { quest_time = 0; + } questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32(); questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32(); @@ -17813,17 +19385,25 @@ void Player::_LoadQuestStatus(QueryResult* result) SetQuestSlot(slot, quest_id, uint32(quest_time)); if (questStatusData.m_explored) + { SetQuestSlotState(slot, QUEST_STATE_COMPLETE); + } if (questStatusData.m_status == QUEST_STATUS_COMPLETE) + { SetQuestSlotState(slot, QUEST_STATE_COMPLETE); + } if (questStatusData.m_status == QUEST_STATUS_FAILED) + { SetQuestSlotState(slot, QUEST_STATE_FAIL); + } for (uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx) if (questStatusData.m_creatureOrGOcount[idx]) + { SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]); + } ++slot; } @@ -17837,11 +19417,15 @@ void Player::_LoadQuestStatus(QueryResult* result) if (pQuest->GetCharTitleId()) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId())) + { SetTitle(titleEntry); + } } if (pQuest->GetBonusTalents()) + { m_questRewardTalentCount += pQuest->GetBonusTalents(); + } } DEBUG_LOG("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow()); @@ -17886,7 +19470,9 @@ void Player::_LoadDailyQuestStatus(QueryResult* result) Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest) + { continue; + } //SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1 + quest_daily_idx, quest_id); ++quest_daily_idx; @@ -17917,7 +19503,9 @@ void Player::_LoadWeeklyQuestStatus(QueryResult* result) Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest) + { continue; + } m_weeklyquests.insert(quest_id); @@ -17946,7 +19534,9 @@ void Player::_LoadMonthlyQuestStatus(QueryResult* result) Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest) + { continue; + } m_monthlyquests.insert(quest_id); @@ -18051,7 +19641,9 @@ void Player::_LoadTalents(QueryResult* result) } if (m_activeSpec == spec) + { addSpell(talentInfo->RankID[currentRank], true, false, false, false); + } else { PlayerTalent talent; @@ -18219,12 +19811,16 @@ InstancePlayerBind* Player::BindToInstance(DungeonPersistentState* state, bool p if (bind.state != state) { if (bind.state) + { bind.state->RemovePlayer(this); + } state->AddPlayer(this); } if (permanent) + { state->SetCanReset(false); + } bind.state = state; bind.perm = permanent; @@ -18264,7 +19860,9 @@ DungeonPersistentState* Player::GetBoundInstanceSaveForSelfOrGroup(uint32 mapid) // use the player's difficulty setting (it may not be the same as the group's) if (Group* group = GetGroup()) if ((groupBind = group->GetBoundInstance(mapid, this))) + { state = groupBind->state; + } } return state; @@ -18357,7 +19955,9 @@ void Player::ConvertInstancesToGroup(Player* player, Group* group, ObjectGuid pl { player_guid = player->GetObjectGuid(); if (!group) + { group = player->GetGroup(); + } } MANGOS_ASSERT(player_guid); @@ -18374,7 +19974,9 @@ void Player::ConvertInstancesToGroup(Player* player, Group* group, ObjectGuid pl has_binds = true; if (group) + { group->BindToInstance(itr->second.state, itr->second.perm, true); + } // permanent binds are not removed if (!itr->second.perm) @@ -18384,7 +19986,9 @@ void Player::ConvertInstancesToGroup(Player* player, Group* group, ObjectGuid pl has_solo = true; } else + { ++itr; + } } } } @@ -18485,7 +20089,9 @@ void Player::SaveToDB() #ifdef ENABLE_ELUNA // Hack to check that this is not on create save if (!HasAtLoginFlag(AT_LOGIN_FIRST)) + { sEluna->OnSave(this); + } #endif /* ENABLE_ELUNA */ static SqlStatementID delChar ; @@ -18575,9 +20181,13 @@ void Player::SaveToDB() uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->z)); uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->o)); if (m_transport) + { uberInsert.addUInt32(m_transport->GetGUIDLow()); + } else + { uberInsert.addUInt32(0); + } uberInsert.addUInt32(m_ExtraFlags); @@ -18640,7 +20250,9 @@ void Player::SaveToDB() uberInsert.Execute(); if (m_mailsUpdated) // save mails only when needed + { _SaveMail(); + } _SaveBGData(); _SaveInventory(); @@ -18666,11 +20278,15 @@ void Player::SaveToDB() // check if stats should only be saved on logout // save stats can be out of transaction if (m_session->isLogingOut() || !sWorld.getConfig(CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT)) + { _SaveStats(); + } // save pet (hunter pet level and experience and all type pets health/mana). if (Pet* pet = GetPet()) + { pet->SavePetToDB(PET_SAVE_AS_CURRENT); + } } // fast save function for item/money cheating preventing - save only inventory and money state @@ -18786,7 +20402,9 @@ void Player::_SaveAuras() { // don't save not own area auras if (aur->IsAreaAura() && holder->GetCasterGuid() != GetObjectGuid()) + { continue; + } damage[i] = aur->GetModifier()->m_amount; periodicTime[i] = aur->GetModifier()->periodictime; @@ -18795,7 +20413,9 @@ void Player::_SaveAuras() } if (!effIndexMask) + { continue; + } stmt.addUInt32(GetGUIDLow()); stmt.addUInt64(holder->GetCasterGuid().GetRawValue()); @@ -18895,7 +20515,10 @@ void Player::_SaveInventory() for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i) { Item* item = m_itemUpdateQueue[i]; - if (!item || item->GetState() == ITEM_REMOVED) continue; + if (!item || item->GetState() == ITEM_REMOVED) + { + continue; + } Item* test = GetItemByPos(item->GetBagSlot(), item->GetSlot()); if (test == NULL) @@ -19035,7 +20658,9 @@ void Player::_SaveMail() itr = m_mail.begin(); } else + { ++itr; + } } m_mailsUpdated = false; @@ -19245,15 +20870,21 @@ void Player::_SaveSpells() if (!talentCosts) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED) + { stmtDel.PExecute(GetGUIDLow(), itr->first); + } // add only changed/new not dependent spells if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED)) + { stmtIns.PExecute(GetGUIDLow(), itr->first, uint8(itr->second.active ? 1 : 0), uint8(itr->second.disabled ? 1 : 0)); + } } if (itr->second.state == PLAYERSPELL_REMOVED) + { m_spells.erase(itr++); + } else { itr->second.state = PLAYERSPELL_UNCHANGED; @@ -19275,14 +20906,20 @@ void Player::_SaveTalents() for (PlayerTalentMap::iterator itr = m_talents[i].begin(); itr != m_talents[i].end();) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED) + { stmtDel.PExecute(GetGUIDLow(), itr->first, i); + } // add only changed/new talents if (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED) + { stmtIns.PExecute(GetGUIDLow(), itr->first, itr->second.currentRank, i); + } if (itr->second.state == PLAYERSPELL_REMOVED) + { m_talents[i].erase(itr++); + } else { itr->second.state = PLAYERSPELL_UNCHANGED; @@ -19390,13 +21027,17 @@ void Player::UpdateSpeakTime() // prevent overwrite mute time, if message send just before mutes set, for example. time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME); if (GetSession()->m_muteTime < new_mute) + { GetSession()->m_muteTime = new_mute; + } m_speakCount = 0; } } else + { m_speakCount = 0; + } m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY); } @@ -19557,11 +21198,15 @@ void Player::ResetInstances(InstanceResetMethod method, bool isRaid) // if the map is loaded, reset it if (Map* map = sMapMgr.FindMap(state->GetMapId(), state->GetInstanceId())) if (map->IsDungeon()) + { ((DungeonMap*)map)->Reset(method); + } // since this is a solo instance there should not be any players inside if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY) + { SendResetInstanceSuccess(state->GetMapId()); + } state->DeleteFromDB(); m_boundInstances[diff].erase(itr++); @@ -19612,7 +21257,9 @@ void Player::UpdateContestedPvP(uint32 diff) ResetContestedPvP(); } else + { m_contestedPvPTimer -= diff; + } } void Player::UpdatePvPFlag(time_t currTime) @@ -19653,7 +21300,9 @@ void Player::UpdateDuelFlag(time_t currTime) void Player::RemovePet(PetSaveMode mode) { if (Pet* pet = GetPet()) + { pet->Unsummon(mode, this); + } } void Player::Say(const std::string& text, const uint32 language) @@ -19745,7 +21394,9 @@ void Player::PetSpellInitialize() for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr) { if (itr->second.state == PETSPELL_REMOVED) + { continue; + } data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first, itr->second.active)); ++addlist; @@ -19854,7 +21505,9 @@ void Player::CharmSpellInitialize() for (uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i) { if (charmInfo->GetCharmSpell(i)->GetAction()) + { ++addlist; + } } } } @@ -19865,9 +21518,13 @@ void Player::CharmSpellInitialize() data << uint32(0); if (charm->GetTypeId() != TYPEID_PLAYER) + { data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0); + } else + { data << uint8(0) << uint8(0) << uint16(0); + } charmInfo->BuildActionBar(&data); @@ -19879,7 +21536,9 @@ void Player::CharmSpellInitialize() { CharmSpellEntry* cspell = charmInfo->GetCharmSpell(i); if (cspell->GetAction()) + { data << uint32(cspell->packedData); + } } } @@ -19912,9 +21571,13 @@ void Player::AddSpellMod(Aura* aura, bool apply) uint32 _mask2 = 0; if (eff < 64) + { _mask = uint64(1) << (eff - 0); + } else + { _mask2 = uint32(1) << (eff - 64); + } if (aura->GetAuraSpellClassMask().IsFitToFamilyMask(_mask, _mask2)) { @@ -19922,7 +21585,9 @@ void Player::AddSpellMod(Aura* aura, bool apply) for (AuraList::const_iterator itr = m_spellMods[mod->m_miscvalue].begin(); itr != m_spellMods[mod->m_miscvalue].end(); ++itr) { if ((*itr)->GetModifier()->m_auraname == mod->m_auraname && ((*itr)->GetAuraSpellClassMask().IsFitToFamilyMask(_mask, _mask2))) + { val += (*itr)->GetModifier()->m_amount; + } } val += apply ? mod->m_amount : -(mod->m_amount); data << uint8(eff); @@ -19934,9 +21599,13 @@ void Player::AddSpellMod(Aura* aura, bool apply) SendDirectMessage(&data); if (apply) + { m_spellMods[mod->m_miscvalue].push_back(aura); + } else + { m_spellMods[mod->m_miscvalue].remove(aura); + } } template T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell const* /*spell*/) @@ -19956,15 +21625,21 @@ template T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& bas Modifier const* mod = aura->GetModifier(); if (!aura->isAffectedOnSpell(spellInfo)) + { continue; + } if (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER) + { totalflat += mod->m_amount; + } else { // skip percent mods for null basevalue (most important for spell mods with charges ) if (basevalue == T(0)) + { continue; + } // special case (skip >10sec spell casts for instant cast setting) if (mod->m_miscvalue == SPELLMOD_CASTING_TIME @@ -20010,7 +21685,9 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid) // send update if charter owner in game Player* owner = sObjectMgr.GetPlayer(ownerguid); if (owner) + { owner->GetSession()->SendPetitionQueryOpcode(petitionguid); + } } while (result->NextRow()); @@ -20039,7 +21716,9 @@ void Player::LeaveAllArenaTeams(ObjectGuid guid) Field* fields = result->Fetch(); if (uint32 at_id = fields[0].GetUInt32()) if (ArenaTeam* at = sObjectMgr.GetArenaTeamById(at_id)) + { at->DelMember(guid); + } } while (result->NextRow()); @@ -20050,23 +21729,35 @@ void Player::SetRestBonus(float rest_bonus_new) { // Prevent resting on max level if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) + { rest_bonus_new = 0; + } if (rest_bonus_new < 0) + { rest_bonus_new = 0; + } float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP) * 1.5f / 2.0f; if (rest_bonus_new > rest_bonus_max) + { m_rest_bonus = rest_bonus_max; + } else + { m_rest_bonus = rest_bonus_new; + } // update data for client if (m_rest_bonus > 10) + { SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_RESTED); + } else if (m_rest_bonus <= 1) + { SetByteValue(PLAYER_BYTES_2, 3, REST_STATE_NORMAL); + } // RestTickUpdate SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus)); @@ -20085,7 +21776,9 @@ void Player::HandleStealthedUnitsDetection() for (std::list::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i) { if ((*i) == this) + { continue; + } bool hasAtClient = HaveAtClient((*i)); bool hasDetected = (*i)->IsVisibleForOrDetect(this, viewPoint, true); @@ -20103,7 +21796,9 @@ void Player::HandleStealthedUnitsDetection() // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) if ((*i) != this && (*i)->isType(TYPEMASK_UNIT)) + { SendAurasForTarget(*i); + } } } else @@ -20165,17 +21860,23 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc RemoveSpellsCausingAura(SPELL_AURA_MOUNTED); if (IsInDisallowedMountForm()) + { RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT); + } if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) if (spell->m_spellInfo->Id != spellid) + { InterruptSpell(CURRENT_GENERIC_SPELL, false); + } InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false); if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL)) if (spell->m_spellInfo->Id != spellid) + { InterruptSpell(CURRENT_CHANNELED_SPELL, true); + } } uint32 sourcenode = nodes[0]; @@ -20245,7 +21946,9 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc totalcost += cost; if (prevnode == sourcenode) + { sourcepath = path; + } m_taxi.AddTaxiDestination(lastnode); @@ -20267,7 +21970,9 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc uint64 money = GetMoney(); if (npc) + { totalcost = (uint32)ceil(totalcost * GetReputationPriceDiscount(npc)); + } if (money < totalcost) { @@ -20339,7 +22044,9 @@ void Player::ContinueTaxiFlight() // skip nodes at another map if (node.mapid != GetMapId()) + { continue; + } distPrev = distNext; @@ -20373,14 +22080,18 @@ void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) + { continue; + } uint32 unSpellId = itr->first; SpellEntry const* spellInfo = sSpellStore.LookupEntry(unSpellId); MANGOS_ASSERT(spellInfo); // Not send cooldown for this spells if (spellInfo->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE)) + { continue; + } if ((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs) { @@ -20404,34 +22115,44 @@ void Player::InitDataForForm(bool reapplyMods) SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME); } else + { SetRegularAttackTime(); + } switch (form) { case FORM_CAT: { if (GetPowerType() != POWER_ENERGY) + { SetPowerType(POWER_ENERGY); + } break; } case FORM_BEAR: { if (GetPowerType() != POWER_RAGE) + { SetPowerType(POWER_RAGE); + } break; } default: // 0, for example { ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass()); if (cEntry && cEntry->powerType < MAX_POWERS && uint32(GetPowerType()) != cEntry->powerType) + { SetPowerType(Powers(cEntry->powerType)); + } break; } } // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change. if (!reapplyMods) + { UpdateEquipSpellsAtFormChange(); + } UpdateAttackPowerAndDamage(); UpdateAttackPowerAndDamage(true); @@ -20473,20 +22194,28 @@ void Player::TakeExtendedCost(uint32 extendedCostId) for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i) { if (extendedCost->reqitem[i]) + { DestroyItemCount(extendedCost->reqitem[i], extendedCost->reqitemcount[i], true); + } } for (int i = 0; i < MAX_EXTENDED_COST_CURRENCIES; ++i) { if (extendedCost->reqcur[i] == CURRENCY_NONE) + { continue; + } if (extendedCost->IsSeasonCurrencyRequirement(i)) + { continue; + } CurrencyTypesEntry const * entry = sCurrencyTypesStore.LookupEntry(extendedCost->reqcur[i]); if (!entry) + { continue; + } int32 cost = int32(extendedCost->reqcurrcount[i]); ModifyCurrencyCount(entry->ID, -cost); @@ -20607,7 +22336,9 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uin for (uint8 i = 0; i < MAX_EXTENDED_COST_CURRENCIES; ++i) { if (iece->reqcur[i] == CURRENCY_NONE) + { continue; + } CurrencyTypesEntry const * costCurrency = sCurrencyTypesStore.LookupEntry(iece->reqcur[i]); if (!costCurrency) @@ -20643,11 +22374,15 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uin uint64 price = (crItem->ExtendedCost == 0 || pProto->Flags2 & ITEM_FLAG2_EXT_COST_REQUIRES_GOLD) ? pProto->BuyPrice * count : 0; if (pProto->BuyCount > 1) + { price = uint64(price / float(pProto->BuyCount) + 0.5f); + } // reputation discount if (price) + { price = uint64(floor(price * GetReputationPriceDiscount(pCreature))); + } if (GetMoney() < price) { @@ -20670,7 +22405,9 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uin ModifyMoney(-int64(price)); if (crItem->ExtendedCost) + { TakeExtendedCost(crItem->ExtendedCost); + } pItem = StoreNewItem(dest, item, true); } @@ -20693,12 +22430,16 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uin ModifyMoney(-int64(price)); if (crItem->ExtendedCost) + { TakeExtendedCost(crItem->ExtendedCost); + } pItem = EquipNewItem(dest, item, true); if (pItem) + { AutoUnequipOffhandIfNeed(); + } } else { @@ -20815,7 +22556,9 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, for (uint8 i = 0; i < MAX_EXTENDED_COST_CURRENCIES; ++i) { if (iece->reqcur[i] == CURRENCY_NONE) + { continue; + } CurrencyTypesEntry const * costCurrency = sCurrencyTypesStore.LookupEntry(iece->reqcur[i]); if (!costCurrency) @@ -20867,7 +22610,9 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, } if (crItem->ExtendedCost) + { TakeExtendedCost(crItem->ExtendedCost); + } ModifyCurrencyCount(currencyId, crItem->maxcount, true, false, true); @@ -20892,7 +22637,9 @@ uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) uint32 t_rating = at->GetRating(); p_rating = p_rating < t_rating ? p_rating : t_rating; if (max_personal_rating < p_rating) + { max_personal_rating = p_rating; + } } } return max_personal_rating; @@ -20922,7 +22669,9 @@ void Player::UpdateHomebindTime(uint32 time) RepopAtGraveyard(); } else + { m_HomebindTimer -= time; + } } else { @@ -20947,9 +22696,13 @@ void Player::UpdatePvP(bool state, bool ovrride) else { if (pvpInfo.endTimer != 0) + { pvpInfo.endTimer = time(NULL); + } else + { SetPvP(state); + } } } @@ -21006,18 +22759,26 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK) // prevent 0 cooldowns set by another way if (rec <= 0 && catrec <= 0 && (cat == 76 || (IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))) + { rec = GetAttackTime(RANGED_ATTACK); + } // Now we have cooldown data (if found any), time to apply mods if (rec > 0) + { ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell); + } if (catrec > 0) + { ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell); + } // replace negative cooldowns by 0 if (rec < 0) rec = 0; - if (catrec < 0) catrec = 0; + { + if (catrec < 0) catrec = 0; + } // no cooldown after applying spell mods if (rec == 0 && catrec == 0) @@ -21031,7 +22792,9 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it // self spell cooldown if (recTime > 0) + { AddSpellCooldown(spellInfo->Id, itemId, recTime); + } // category spells if (cat && catrec > 0) @@ -21042,7 +22805,9 @@ void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 it for (SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset) { if (*i_scset == spellInfo->Id) // skip main spell, already handled above + { continue; + } AddSpellCooldown(*i_scset, itemId, catrecTime); } @@ -21086,11 +22851,15 @@ void Player::UpdatePotionCooldown(Spell* spell) for (int idx = 0; idx < 5; ++idx) if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE) if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId)) + { SendCooldownEvent(spellInfo, m_lastPotionId); + } } // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown) else + { SendCooldownEvent(spell->m_spellInfo, m_lastPotionId, spell); + } m_lastPotionId = 0; } @@ -21116,7 +22885,9 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (i == slot) + { continue; + } Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color) { @@ -21124,30 +22895,42 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) { uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) + { continue; + } uint32 gemid = enchantEntry->GemID; if (!gemid) + { continue; + } ItemPrototype const* gemProto = sItemStorage.LookupEntry(gemid); if (!gemProto) + { continue; + } GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties); if (!gemProperty) + { continue; + } uint8 GemColor = gemProperty->color; for (uint8 b = 0, tmpcolormask = 1; b < 4; ++b, tmpcolormask <<= 1) { if (tmpcolormask & GemColor) + { ++curcount[b]; + } } } } @@ -21158,7 +22941,9 @@ bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) for (int i = 0; i < 5; ++i) { if (!Condition->Color[i]) + { continue; + } uint32 _cur_gem = curcount[Condition->Color[i] - 1]; @@ -21191,22 +22976,30 @@ void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply) { // enchants for the slot being socketed are handled by Player::ApplyItemMods if (slot == exceptslot) + { continue; + } Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!pItem || !pItem->GetProto()->Socket[0].Color) + { continue; + } for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + 3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) + { continue; + } uint32 condition = enchantEntry->EnchantmentCondition; if (condition) @@ -21233,28 +23026,38 @@ void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply) { // enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data) if (slot == exceptslot) + { continue; + } Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot); if (!pItem || !pItem->GetProto()->Socket[0].Color) // if item has no sockets or no item is equipped go to next item + { continue; + } // cycle all (gem)enchants for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + 3; ++enchant_slot) { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) // if no enchant go to next enchant(slot) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) + { continue; + } // only metagems to be (de)activated, so only enchants with condition uint32 condition = enchantEntry->EnchantmentCondition; if (condition) + { ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), apply); + } } } } @@ -21282,10 +23085,14 @@ void Player::SetBattleGroundEntryPoint() { AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED); if (!auras.empty()) + { m_bgData.mountSpell = (*auras.begin())->GetId(); + } } else + { m_bgData.mountSpell = 0; + } // If map is dungeon find linked graveyard if (GetMap()->IsDungeon()) @@ -21297,7 +23104,9 @@ void Player::SetBattleGroundEntryPoint() return; } else + { sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId()); + } } // If new entry point is not BG or arena set it else if (!GetMap()->IsBattleGroundOrArena()) @@ -21469,7 +23278,9 @@ template<> inline void BeforeVisibilityDestroy(Creature* t, Player* p) { if (p->GetPetGuid() == t->GetObjectGuid() && ((Creature*)t)->IsPet()) + { ((Pet*)t)->Unsummon(PET_SAVE_REAGENTS); + } } void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target) @@ -21488,7 +23299,9 @@ void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* targe target->DestroyForPlayer(this, !target->IsInWorld() && ((Creature*)target)->IsDead()); } else + { target->DestroyForPlayer(this); + } m_clientGUIDs.erase(t_guid); @@ -21501,14 +23314,18 @@ void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* targe { target->SendCreateUpdateToPlayer(this); if (target->GetTypeId() != TYPEID_GAMEOBJECT || !((GameObject*)target)->IsTransport()) + { m_clientGUIDs.insert(target->GetObjectGuid()); + } DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "UpdateVisibilityOf: %s is visible now for player %u. Distance = %f", target->GetGuidStr().c_str(), GetGUIDLow(), GetDistance(target)); // target aura duration for caster show only if target exist at caster client // send data at target visibility change (adding to client) if (target != this && target->isType(TYPEMASK_UNIT)) + { SendAurasForTarget((Unit*)target); + } } } } @@ -21523,7 +23340,9 @@ template<> inline void UpdateVisibilityOf_helper(GuidSet& s64, GameObject* target) { if (!target->IsTransport()) + { s64.insert(target->GetObjectGuid()); + } } template @@ -21606,7 +23425,9 @@ void Player::AddComboPoints(Unit* target, int8 count) { if (m_comboTargetGuid) if (Unit* target2 = ObjectAccessor::GetUnit(*this, m_comboTargetGuid)) + { target2->RemoveComboPointHolder(GetGUIDLow()); + } m_comboTargetGuid = target->GetObjectGuid(); m_comboPoints = count; @@ -21615,7 +23436,9 @@ void Player::AddComboPoints(Unit* target, int8 count) } if (m_comboPoints > 5) m_comboPoints = 5; - if (m_comboPoints < 0) m_comboPoints = 0; + { + if (m_comboPoints < 0) m_comboPoints = 0; + } SendComboPoints(); } @@ -21635,7 +23458,9 @@ void Player::ClearComboPoints() SendComboPoints(); if (Unit* target = ObjectAccessor::GetUnit(*this, m_comboTargetGuid)) + { target->RemoveComboPointHolder(GetGUIDLow()); + } m_comboTargetGuid.Clear(); } @@ -21643,7 +23468,9 @@ void Player::ClearComboPoints() void Player::SetGroup(Group* group, int8 subgroup) { if (group == NULL) + { m_group.unlink(); + } else { // never use SetGroup without a subgroup unless you specify NULL for group @@ -21762,7 +23589,9 @@ void Player::SendInitialPacketsBeforeAddToMap() m_reputationMgr.SendInitialReputations(); if (!IsAlive()) + { SendCorpseReclaimDelay(true); + } SendInitWorldStates(GetZoneId(), GetAreaId()); @@ -21789,7 +23618,9 @@ void Player::SendInitialPacketsBeforeAddToMap() // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment if (IsFreeFlying() || IsTaxiFlying()) + { m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING); + } SendCurrencies(); @@ -21821,11 +23652,15 @@ void Player::SendInitialPacketsAfterAddToMap() { Unit::AuraList const& auraList = GetAurasByType(*itr); if (!auraList.empty()) + { auraList.front()->ApplyModifier(true, true); + } } if (HasAuraType(SPELL_AURA_MOD_STUN) || HasAuraType(SPELL_AURA_MOD_ROOT)) + { SetRoot(true); + } SendAurasForTarget(this); SendEnchantmentDurations(); // must be after add to map @@ -21843,12 +23678,16 @@ void Player::SendUpdateToOutOfRangeGroupMembers() return; } if (Group* group = GetGroup()) + { group->UpdatePlayerOutOfRange(this); + } m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE; m_auraUpdateMask = 0; if (Pet* pet = GetPet()) + { pet->ResetAuraUpdateMask(); + } } void Player::SendTransferAbortedByLockStatus(MapEntry const* mapEntry, AreaLockStatus lockStatus, uint32 miscRequirement) @@ -21916,13 +23755,21 @@ void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint3 // type of warning, based on the time remaining until reset uint32 type; if (time > 3600) + { type = RAID_INSTANCE_WELCOME; + } else if (time > 900 && time <= 3600) + { type = RAID_INSTANCE_WARNING_HOURS; + } else if (time > 300 && time <= 900) + { type = RAID_INSTANCE_WARNING_MIN; + } else + { type = RAID_INSTANCE_WARNING_MIN_SOON; + } WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4 + 4 + 4 + 4); data << uint32(type); @@ -21950,11 +23797,15 @@ void Player::ApplyEquipCooldown(Item* pItem) // no spell if (!spellData.SpellId) + { continue; + } // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown) if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) + { continue; + } AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30); @@ -21969,14 +23820,18 @@ void Player::resetSpells() { // not need after this call if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS)) + { RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS, true); + } // make full copy of map (spells removed and marked as deleted at another spell remove // and we can't use original map for safe iterative with visit each spell at loop end PlayerSpellMap smap = GetSpellMap(); for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) + { removeSpell(iter->first, false, false); // only iter->first can be accessed, object by iter->second can be deleted already + } learnDefaultSpells(); learnQuestRewardedSpells(); @@ -21991,9 +23846,13 @@ void Player::learnDefaultSpells() uint32 tspell = *itr; DEBUG_LOG("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u", uint32(getClass()), uint32(getRace()), tspell); if (!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add + { addSpell(tspell, true, true, true, false); + } else // but send in normal spell in game learn case + { learnSpell(tspell, true); + } } } @@ -22061,7 +23920,9 @@ void Player::learnQuestRewardedSpells(Quest const* quest) for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED || itr->first == learned_0) + { continue; + } SpellEntry const* itrInfo = sSpellStore.LookupEntry(itr->first); if (!itrInfo) @@ -22073,11 +23934,15 @@ void Player::learnQuestRewardedSpells(Quest const* quest) SpellEffectEntry const* itrSpellEffect0 = learnedInfo->GetSpellEffect(EFFECT_INDEX_0); SpellEffectEntry const* itrSpellEffect1 = learnedInfo->GetSpellEffect(EFFECT_INDEX_1); if ((itrSpellEffect0 && itrSpellEffect0->Effect != SPELL_EFFECT_TRADE_SKILL) || (itrSpellEffect1 && itrSpellEffect1->Effect != 0)) + { continue; + } // compare same chain spells if (sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell) + { continue; + } // now we have 2 specialization, learn possible only if found is lesser specialization rank if (!sSpellMgr.IsHighRankOfSpell(learned_0, itr->first)) @@ -22098,11 +23963,15 @@ void Player::learnQuestRewardedSpells() { // skip no rewarded quests if (!itr->second.m_rewarded) + { continue; + } Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first); if (!quest) + { continue; + } learnQuestRewardedSpells(quest); } @@ -22116,24 +23985,36 @@ void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value) { SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j); if (!pAbility || pAbility->skillId != skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL) + { continue; + } // Check race if set if (pAbility->racemask && !(pAbility->racemask & raceMask)) + { continue; + } // Check class if set if (pAbility->classmask && !(pAbility->classmask & classMask)) + { continue; + } if (sSpellStore.LookupEntry(pAbility->spellId)) { // need unlearn spell if (skill_value < pAbility->req_skill_value) + { removeSpell(pAbility->spellId); + } // need learn else if (!IsInWorld()) + { addSpell(pAbility->spellId, true, true, true, false); + } else + { learnSpell(pAbility->spellId, true); + } } } } @@ -22250,7 +24131,9 @@ bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const // limit check leel to dbc compatible level range uint32 level = getLevel(); if (level > DEFAULT_MAX_LEVEL) + { level = DEFAULT_MAX_LEVEL; + } if (level < bg->GetMinLevel() || level > bg->GetMaxLevel()) { @@ -22302,11 +24185,15 @@ bool Player::IsSpellFitByClassAndRace(uint32 spell_id, uint32* pReqlevel /*= NUL SkillLineAbilityEntry const* abilityEntry = _spell_idx->second; // skip wrong race skills if (abilityEntry->racemask && (abilityEntry->racemask & racemask) == 0) + { continue; + } // skip wrong class skills if (abilityEntry->classmask && (abilityEntry->classmask & classmask) == 0) + { continue; + } SkillRaceClassInfoMapBounds raceBounds = sSpellMgr.GetSkillRaceClassInfoMapBounds(abilityEntry->skillId); for (SkillRaceClassInfoMap::const_iterator itr = raceBounds.first; itr != raceBounds.second; ++itr) @@ -22349,11 +24236,15 @@ bool Player::HasQuestForGO(int32 GOId) const { uint32 questid = GetQuestSlotQuestId(i); if (questid == 0) + { continue; + } QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid); if (qs_itr == mQuestStatus.end()) + { continue; + } QuestStatusData const& qs = qs_itr->second; @@ -22361,15 +24252,21 @@ bool Player::HasQuestForGO(int32 GOId) const { Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid); if (!qinfo) + { continue; + } if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid()) + { continue; + } for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j) { if (qinfo->ReqCreatureOrGOId[j] >= 0) // skip non GO case + { continue; + } if ((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j]) { @@ -22395,17 +24292,23 @@ void Player::UpdateForQuestWorldObjects() if (itr->IsGameObject()) { if (GameObject* obj = GetMap()->GetGameObject(*itr)) + { obj->BuildValuesUpdateBlockForPlayer(&udata, this); + } } else if (itr->IsCreatureOrVehicle()) { Creature* obj = GetMap()->GetAnyTypeCreature(*itr); if (!obj) + { continue; + } // check if this unit requires quest specific flags if (!obj->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK)) + { continue; + } SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry()); for (SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr) @@ -22446,7 +24349,9 @@ void Player::SummonIfPossible(bool agree) // drop flag at summon // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag if (BattleGround* bg = GetBattleGround()) + { bg->EventPlayerDroppedFlag(this); + } m_summon_expire = 0; @@ -22615,7 +24520,9 @@ void Player::RemoveItemDependentAurasAndCasts(Item* pItem) for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) if (spell->getState() != SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo, pItem)) + { InterruptSpell(CurrentSpellTypes(i)); + } } uint32 Player::GetResurrectionSpellId() @@ -22656,7 +24563,9 @@ uint32 Player::GetResurrectionSpellId() // Reincarnation (passive spell) // prio: 1 // Glyph of Renewed Life remove reagent requiremnnt if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030, 1) || HasAura(58059, EFFECT_INDEX_0))) + { spell_id = 21169; + } return spell_id; } @@ -22698,12 +24607,16 @@ void Player::RewardSinglePlayerAtKill(Unit* pVictim) GiveXP(xp, pVictim); if (Pet* pet = GetPet()) + { pet->GivePetXP(xp); + } // normal creature (not pet/etc) can be only in !PvP case if (pVictim->GetTypeId() == TYPEID_UNIT) if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry())) + { KilledMonster(normalInfo, pVictim->GetObjectGuid()); + } } } @@ -22720,18 +24633,26 @@ void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewar { Player* pGroupGuy = itr->getSource(); if (!pGroupGuy) + { continue; + } if (!pGroupGuy->IsAtGroupRewardDistance(pRewardSource)) + { continue; // member (alive or dead) or his corpse at req. distance + } // quest objectives updated only for alive group member or dead but with not released body if (pGroupGuy->IsAlive() || !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) + { pGroupGuy->KilledMonsterCredit(creature_id, creature_guid); + } } } else // if (!pGroup) + { KilledMonsterCredit(creature_id, creature_guid); + } } void Player::RewardPlayerAndGroupAtCast(WorldObject* pRewardSource, uint32 spellid) @@ -22743,18 +24664,26 @@ void Player::RewardPlayerAndGroupAtCast(WorldObject* pRewardSource, uint32 spell { Player* pGroupGuy = itr->getSource(); if (!pGroupGuy) + { continue; + } if (!pGroupGuy->IsAtGroupRewardDistance(pRewardSource)) + { continue; // member (alive or dead) or his corpse at req. distance + } // quest objectives updated only for alive group member or dead but with not released body if (pGroupGuy->IsAlive() || !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) + { pGroupGuy->CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid, pGroupGuy == this); + } } } else // if (!pGroup) + { CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid); + } } bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const @@ -22782,7 +24711,9 @@ void Player::ResurectUsingRequestData() { /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse if (m_resurrectGuid.IsPlayer()) + { TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation()); + } // we cannot resurrect player when we triggered far teleport // player will be resurrected upon teleportation @@ -22795,14 +24726,22 @@ void Player::ResurectUsingRequestData() ResurrectPlayer(0.0f, false); if (GetMaxHealth() > m_resurrectHealth) + { SetHealth(m_resurrectHealth); + } else + { SetHealth(GetMaxHealth()); + } if (GetMaxPower(POWER_MANA) > m_resurrectMana) + { SetPower(POWER_MANA, m_resurrectMana); + } else + { SetPower(POWER_MANA, GetMaxPower(POWER_MANA)); + } SetPower(POWER_RAGE, 0); @@ -22859,7 +24798,9 @@ void Player::UpdateAreaDependentAuras() iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } // some auras applied at subzone enter @@ -22879,7 +24820,9 @@ struct UpdateZoneDependentPetsHelper if (uint32 spell_id = unit->GetUInt32Value(UNIT_CREATED_BY_SPELL)) if (SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell_id)) if (sSpellMgr.GetSpellAllowedInLocationError(spellEntry, owner->GetMapId(), zone_id, area_id, owner) != SPELL_CAST_OK) + { ((Pet*)unit)->Unsummon(PET_SAVE_AS_DELETED, owner); + } } Player* owner; uint32 zone_id; @@ -22920,12 +24863,18 @@ void Player::UpdateCorpseReclaimDelay() // full and partly periods 1..3 uint32 count = uint32((m_deathExpireTime - now) / DEATH_EXPIRE_STEP + 1); if (count < MAX_DEATH_COUNT) + { m_deathExpireTime = now + (count + 1) * DEATH_EXPIRE_STEP; + } else + { m_deathExpireTime = now + MAX_DEATH_COUNT * DEATH_EXPIRE_STEP; + } } else + { m_deathExpireTime = now + DEATH_EXPIRE_STEP; + } } void Player::SendCorpseReclaimDelay(bool load) @@ -22952,10 +24901,14 @@ void Player::SendCorpseReclaimDelay(bool load) { count = uint32(m_deathExpireTime - corpse->GetGhostTime()) / DEATH_EXPIRE_STEP; if (count >= MAX_DEATH_COUNT) + { count = MAX_DEATH_COUNT - 1; + } } else + { count = 0; + } time_t expected_time = corpse->GetGhostTime() + corpseReclaimDelay[count]; @@ -22968,7 +24921,9 @@ void Player::SendCorpseReclaimDelay(bool load) delay = uint32(expected_time - now); } else + { delay = GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP); + } //! corpse reclaim delay 30 * 1000ms or longer at often deaths WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4); @@ -23009,7 +24964,9 @@ uint32 Player::GetNextResetTalentsCost() const int32 new_cost = GetTalentResetCost() + 5 * GOLD; // until it hits a cap of 50 gold. if (new_cost > 50 * GOLD) + { new_cost = 50 * GOLD; + } return new_cost; } } @@ -23072,10 +25029,14 @@ void Player::UpdateGroupLeaderFlag(const bool remove /*= false*/) if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GROUP_LEADER)) { if (remove || !group || group->GetLeaderGuid() != GetObjectGuid()) + { RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GROUP_LEADER); + } } else if (!remove && group && group->GetLeaderGuid() == GetObjectGuid()) + { SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GROUP_LEADER); + } } void Player::SetBattleGroundRaid(Group* group, int8 subgroup) @@ -23103,7 +25064,9 @@ void Player::RemoveFromBattleGroundRaid() void Player::SetOriginalGroup(Group* group, int8 subgroup) { if (group == NULL) + { m_originalGroup.unlink(); + } else { // never use SetOriginalGroup without a subgroup unless you specify NULL for group @@ -23121,7 +25084,9 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) { m_MirrorTimerFlags &= ~(UNDERWATER_INWATER | UNDERWATER_INLAVA | UNDERWATER_INSLIME | UNDERWATER_INDARKWATER); if (m_lastLiquid && m_lastLiquid->SpellId) + { RemoveAurasDueToSpell(m_lastLiquid->SpellId == 37025 ? 37284 : m_lastLiquid->SpellId); + } m_lastLiquid = NULL; return; } @@ -23130,7 +25095,9 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) { LiquidTypeEntry const* liquid = sLiquidTypeStore.LookupEntry(liqEntry); if (m_lastLiquid && m_lastLiquid->SpellId && m_lastLiquid->Id != liqEntry) + { RemoveAurasDueToSpell(m_lastLiquid->SpellId); + } if (liquid && liquid->SpellId) { @@ -23149,7 +25116,9 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) if (pInst->CheckConditionCriteriaMeet(this, INSTANCE_CONDITION_ID_LURKER, NULL, CONDITION_FROM_HARDCODED)) { if (pInst->CheckConditionCriteriaMeet(this, INSTANCE_CONDITION_ID_SCALDING_WATER, NULL, CONDITION_FROM_HARDCODED)) + { CastSpell(this, liquidSpellId, true); + } else { SummonCreature(21508, 0, 0, 0, 0, TEMPSUMMON_TIMED_OOC_DESPAWN, 2000); @@ -23160,11 +25129,15 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) } } else + { CastSpell(this, liquidSpellId, true); + } } } else + { RemoveAurasDueToSpell(liquidSpellId); + } } m_lastLiquid = liquid; @@ -23179,32 +25152,48 @@ void Player::UpdateUnderwaterState(Map* m, float x, float y, float z) if (liquid_status.CreatureTypeFlags & (MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN | MAP_LIQUID_TYPE_MAGMA | MAP_LIQUID_TYPE_SLIME)) { if (res & LIQUID_MAP_UNDER_WATER) + { m_MirrorTimerFlags |= UNDERWATER_INWATER; + } else + { m_MirrorTimerFlags &= ~UNDERWATER_INWATER; + } } // Allow travel in dark water on taxi or transport if ((liquid_status.CreatureTypeFlags & MAP_LIQUID_TYPE_DARK_WATER) && !IsTaxiFlying() && !GetTransport()) + { m_MirrorTimerFlags |= UNDERWATER_INDARKWATER; + } else + { m_MirrorTimerFlags &= ~UNDERWATER_INDARKWATER; + } // in lava check, anywhere in lava level if (liquid_status.CreatureTypeFlags & MAP_LIQUID_TYPE_MAGMA) { if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK)) + { m_MirrorTimerFlags |= UNDERWATER_INLAVA; + } else + { m_MirrorTimerFlags &= ~UNDERWATER_INLAVA; + } } // in slime check, anywhere in slime level if (liquid_status.CreatureTypeFlags & MAP_LIQUID_TYPE_SLIME) { if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK)) + { m_MirrorTimerFlags |= UNDERWATER_INSLIME; + } else + { m_MirrorTimerFlags &= ~UNDERWATER_INSLIME; + } } } @@ -23260,7 +25249,9 @@ uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 n uint32 level = getLevel(); if (level > GT_MAX_LEVEL) + { level = GT_MAX_LEVEL; // max level in this dbc + } uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2); uint8 haircolor = GetByteValue(PLAYER_BYTES, 3); @@ -23281,16 +25272,24 @@ uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 n float cost = 0; if (hairstyle != newhairstyle) + { cost += bsc->cost; // full price + } if (haircolor != newhaircolor && hairstyle == newhairstyle) + { cost += bsc->cost * 0.5f; // +1/2 of price + } if (facialhair != newfacialhair) + { cost += bsc->cost * 0.75f; // +3/4 of price + } if (skintone != newskintone && newskintone != -1) + { cost += bsc->cost * 0.5f; // +1/2 of price + } return uint32(cost); } @@ -23300,18 +25299,26 @@ void Player::InitGlyphsForLevel() uint32 slot = 0; for (uint32 i = 0; i < sGlyphSlotStore.GetNumRows() && slot < MAX_GLYPH_SLOT_INDEX; ++i) if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(i)) + { SetGlyphSlot(slot++, gs->Id); + } uint32 level = getLevel(); uint32 value = 0; // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level if (level >= 25) + { value |= 0x01 | 0x02 | 0x40; + } if (level >= 50) + { value |= 0x04 | 0x08 | 0x80; + } if (level >= 75) + { value |= 0x10 | 0x20 | 0x100; + } SetUInt32Value(PLAYER_GLYPHS_ENABLED, value); } @@ -23414,12 +25421,16 @@ void Player::UpdateRuneRegen(RuneType rune) for (uint8 i = 0; i < MAX_RUNES; i += 2) { if (GetBaseRune(i) != rune) + { continue; + } uint32 cd = GetRuneCooldown(i); uint32 secondRuneCd = GetRuneCooldown(i + 1); if (!cd && !secondRuneCd) + { actualRune = GetCurrentRune(i); + } else if (secondRuneCd && (cd > secondRuneCd || !cd)) { cooldown = GetBaseRuneCooldown(i + 1); @@ -23438,19 +25449,27 @@ void Player::UpdateRuneRegen(RuneType rune) Unit::AuraList const& regenAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for (Unit::AuraList::const_iterator i = regenAuras.begin(); i != regenAuras.end(); ++i) if ((*i)->GetMiscValue() == POWER_RUNE && (*i)->GetSpellEffect()->EffectMiscValueB == rune) + { auraMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + } // Unholy Presence if (Aura* aura = GetAura(48265, EFFECT_INDEX_0)) + { auraMod *= (100.0f + aura->GetModifier()->m_amount) / 100.0f; + } // Runic Corruption if (Aura* aura = GetAura(51460, EFFECT_INDEX_0)) + { auraMod *= (100.0f + aura->GetModifier()->m_amount) / 100.0f; + } float hastePct = (100.0f - GetRatingBonusValue(CR_HASTE_MELEE)) / 100.0f; if (hastePct < 0) + { hastePct = 1.0f; + } cooldown *= hastePct / auraMod; @@ -23485,7 +25504,9 @@ void Player::AddRuneByAuraEffect(uint8 index, RuneType newType, Aura const* aura { // Item - Death Knight T11 DPS 4P Bonus if (newType == RUNE_DEATH && HasAura(90459)) + { CastSpell(this, 90507, true); // Death Eater + } SetRuneConvertAura(index, aura); ConvertRune(index, newType); } @@ -23532,7 +25553,9 @@ void Player::RestoreBaseRune(uint8 index) } if (Unit* target = aura->GetTarget()) + { target->RemoveSpellAuraHolder(const_cast(aura)->GetHolder()); + } } void Player::ConvertRune(uint8 index, RuneType newType) @@ -23634,9 +25657,13 @@ void Player::AutoStoreLoot(Loot& loot, bool broadcast, uint8 bag, uint8 slot) ItemPosCountVec dest; InventoryResult msg = CanStoreNewItem(bag, slot, dest, lootItem->itemid, lootItem->count); if (msg != EQUIP_ERR_OK && slot != NULL_SLOT) + { msg = CanStoreNewItem(bag, NULL_SLOT, dest, lootItem->itemid, lootItem->count); + } if (msg != EQUIP_ERR_OK && bag != NULL_BAG) + { msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, lootItem->itemid, lootItem->count); + } if (msg != EQUIP_ERR_OK) { SendEquipError(msg, NULL, NULL, lootItem->itemid); @@ -23747,7 +25774,9 @@ uint32 Player::CalculateTalentsPoints() const talentPointsForLevel += float(m_questRewardTalentCount); if (talentPointsForLevel > baseForLevel) + { talentPointsForLevel = baseForLevel; + } return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT)); } @@ -23846,14 +25875,18 @@ void Player::_LoadSkills(QueryResult* result) uint16 step = 0; if (pSkill->categoryId == SKILL_CATEGORY_SECONDARY) + { step = max / 75; + } if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION) { step = max / 75; if (professionCount < 2) + { SetUInt32Value(PLAYER_PROFESSION_SKILL_LINE_1 + professionCount++, skill); + } } SetUInt16Value(PLAYER_SKILL_STEP_0 + field, offset, step); @@ -23896,27 +25929,47 @@ void Player::_LoadSkills(QueryResult* result) { uint32 base_level = std::min(getLevel(), sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL)); if (base_level < 1) + { base_level = 1; + } uint32 base_skill = (base_level - 1) * 5; // 270 at starting level 55 if (base_skill < 1) + { base_skill = 1; // skill mast be known and then > 0 in any case + } if (GetPureSkillValue(SKILL_FIRST_AID) < base_skill) + { SetSkill(SKILL_FIRST_AID, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_AXES) < base_skill) + { SetSkill(SKILL_AXES, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_DEFENSE) < base_skill) + { SetSkill(SKILL_DEFENSE, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_POLEARMS) < base_skill) + { SetSkill(SKILL_POLEARMS, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_SWORDS) < base_skill) + { SetSkill(SKILL_SWORDS, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_2H_AXES) < base_skill) + { SetSkill(SKILL_2H_AXES, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_2H_SWORDS) < base_skill) + { SetSkill(SKILL_2H_SWORDS, base_skill, base_skill); + } if (GetPureSkillValue(SKILL_UNARMED) < base_skill) + { SetSkill(SKILL_UNARMED, base_skill, base_skill); + } } } @@ -23924,12 +25977,16 @@ uint32 Player::GetPhaseMaskForSpawn() const { uint32 phase = PHASEMASK_NORMAL; if (!isGameMaster()) + { phase = GetPhaseMask(); + } else { AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE); if (!phases.empty()) + { phase = phases.front()->GetMiscValue(); + } } // some aura phases include 1 normal map in addition to phase itself @@ -23956,14 +26013,20 @@ InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limi { uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot)); if (!enchant_id) + { continue; + } SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!enchantEntry) + { continue; + } ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID); if (!pGem) + { continue; + } // include for check equip another gems with same limit category for not equipped item (and then not counted) uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory @@ -24044,18 +26107,24 @@ void Player::HandleFall(MovementInfo const& movementInfo) { // Prevent fall damage from being more than the player maximum health if (damage > GetMaxHealth()) + { damage = GetMaxHealth(); + } // Gust of Wind if (GetDummyAura(43621)) + { damage = GetMaxHealth() / 2; + } uint32 original_health = GetHealth(); uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage); // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case if (IsAlive() && final_damage < original_health) + { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff * 100)); + } } // Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction @@ -24136,7 +26205,9 @@ bool Player::LearnTalent(uint32 talentId, uint32 talentRank) // find current max talent rank uint32 curtalent_maxrank = 0; if (PlayerTalent const* talent = GetKnownTalentById(talentId)) + { curtalent_maxrank = talent->currentRank + 1; + } // we already have same or higher talent rank learned if (curtalent_maxrank >= (talentRank + 1)) @@ -24161,7 +26232,9 @@ bool Player::LearnTalent(uint32 talentId, uint32 talentRank) { PlayerTalent depTalent = (*dependsOnTalent).second; if (depTalent.currentRank >= talentInfo->DependsOnRank) + { hasEnoughRank = true; + } } if (!hasEnoughRank) @@ -24191,9 +26264,13 @@ bool Player::LearnTalent(uint32 talentId, uint32 talentRank) if (HasSpell(tmpTalent->RankID[rank])) { if (tmpTalent->TalentTab == tTab) + { spentPoints += (rank + 1); + } if (tmpTalent->TalentTab == m_talentsPrimaryTree[m_activeSpec]) + { primaryTreeTalents += (rank + 1); + } } } } @@ -24352,7 +26429,9 @@ void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRa { if (depTalentInfo->RankID[i] != 0) if (pet->HasSpell(depTalentInfo->RankID[i])) + { hasEnoughRank = true; + } } if (!hasEnoughRank) { @@ -24422,7 +26501,9 @@ void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRa void Player::UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode) { if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND) + { SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z); + } } void Player::UnsummonPetTemporaryIfAny() @@ -24434,7 +26515,9 @@ void Player::UnsummonPetTemporaryIfAny() } if (!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned()) + { m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber(); + } pet->Unsummon(PET_SAVE_AS_CURRENT, this); } @@ -24470,7 +26553,9 @@ void Player::ResummonPetTemporaryUnSummonedIfAny() Pet* NewPet = new Pet; if (!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true)) + { delete NewPet; + } m_temporaryUnsummonedPetNumber = 0; } @@ -24501,7 +26586,9 @@ void Player::BuildPlayerTalentsInfoData(WorldPacket* data) if (m_specsCount) { if (m_specsCount > MAX_TALENT_SPEC_COUNT) + { m_specsCount = MAX_TALENT_SPEC_COUNT; + } // loop through all specs (only 1 for now) for (uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx) @@ -24522,11 +26609,15 @@ void Player::BuildPlayerTalentsInfoData(WorldPacket* data) PlayerTalent talent = (*iter).second; if (talent.state == PLAYERSPELL_REMOVED) + { continue; + } // skip another tab talents if (talent.talentEntry->TalentTab != talentTabId) + { continue; + } *data << uint32(talent.talentEntry->TalentID); // Talent.dbc *data << uint8(talent.currentRank); // talentMaxRank (0-4) @@ -24584,20 +26675,28 @@ void Player::BuildPetTalentsInfoData(WorldPacket* data) { TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentTabId); if (!talentTabInfo) + { continue; + } if (!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask)) + { continue; + } for (uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId) { TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId); if (!talentInfo) + { continue; + } // skip another tab talents if (talentInfo->TalentTab != talentTabId) + { continue; + } // find max talent rank int32 curtalent_maxrank = -1; @@ -24612,7 +26711,9 @@ void Player::BuildPetTalentsInfoData(WorldPacket* data) // not learned talent if (curtalent_maxrank < 0) + { continue; + } *data << uint32(talentInfo->TalentID); // Talent.dbc *data << uint8(curtalent_maxrank); // talentMaxRank (0-4) @@ -24631,9 +26732,13 @@ void Player::SendTalentsInfoData(bool pet) WorldPacket data(SMSG_TALENT_UPDATE, 50); data << uint8(pet ? 1 : 0); if (pet) + { BuildPetTalentsInfoData(&data); + } else + { BuildPlayerTalentsInfoData(&data); + } GetSession()->SendPacket(&data); } @@ -24648,7 +26753,9 @@ void Player::BuildEnchantmentsInfoData(WorldPacket* data) Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (!item) + { continue; + } slotUsedMask |= (1 << i); @@ -24663,7 +26770,9 @@ void Player::BuildEnchantmentsInfoData(WorldPacket* data) uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j)); if (!enchId) + { continue; + } enchantmentMask |= (1 << j); @@ -24689,7 +26798,9 @@ void Player::SendEquipmentSetList() for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) { if (itr->second.state == EQUIPMENT_SET_DELETED) + { continue; + } data.appendPackGUID(itr->second.Guid); data << uint32(itr->first); data << itr->second.Name; @@ -24698,9 +26809,13 @@ void Player::SendEquipmentSetList() { // ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HIGHGUID_ITEM if (itr->second.IgnoreMask & (1 << i)) + { data << ObjectGuid(uint64(1)).WriteAsPacked(); + } else + { data << ObjectGuid(HIGHGUID_ITEM, itr->second.Items[i]).WriteAsPacked(); + } } ++count; // client have limit but it checked at loading and set @@ -24866,9 +26981,13 @@ void Player::DeleteEquipmentSet(uint64 setGuid) if (itr->second.Guid == setGuid) { if (itr->second.state == EQUIPMENT_SET_NEW) + { m_EquipmentSets.erase(itr); + } else + { itr->second.state = EQUIPMENT_SET_DELETED; + } break; } } @@ -24937,12 +27056,16 @@ void Player::ActivateSpec(uint8 specNum) for (int r = 0; r < MAX_TALENT_RANK; ++r) if (talentInfo->RankID[r]) + { removeSpell(talentInfo->RankID[r], !IsPassiveSpell(talentInfo->RankID[r]), false); + } specIter = m_talents[m_activeSpec].begin(); } else + { ++specIter; + } } // now new spec data have only talents (maybe different rank) as in temp spec data, sync ranks then. @@ -24965,15 +27088,21 @@ void Player::ActivateSpec(uint8 specNum) if (PlayerTalent const* cur_talent = GetKnownTalentById(tempIter->first)) { if (cur_talent->currentRank != talent.currentRank) + { learnSpell(talentSpellId, false); + } } else + { learnSpell(talentSpellId, false); + } // sync states - original state is changed in addSpell that learnSpell calls PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].find(tempIter->first); if (specIter != m_talents[m_activeSpec].end()) + { specIter->second.state = talent.state; + } else { sLog.outError("ActivateSpec: Talent spell %u expected to learned at spec switch but not listed in talents at final check!", talentSpellId); @@ -25027,12 +27156,16 @@ void Player::ActivateSpec(uint8 specNum) Powers pw = GetPowerType(); if (pw != POWER_MANA) + { SetPower(POWER_MANA, 0); + } SetPower(pw, 0); if (m_talentsPrimaryTree[m_activeSpec] && !sTalentTabStore.LookupEntry(m_talentsPrimaryTree[m_activeSpec])) + { resetTalents(true); + } // Update talent tree role-dependent mana regen UpdateManaRegen(); @@ -25050,7 +27183,9 @@ void Player::UpdateSpecCount(uint8 count) // maybe current spec data must be copied to 0 spec? if (m_activeSpec >= count) + { ActivateSpec(0); + } // copy spec data from new specs if (count > curCount) @@ -25249,7 +27384,9 @@ void Player::SetRestType(RestType n_r_type, uint32 areaTriggerId /*= 0*/) // Set player to FFA PVP when not in rested environment. if (sWorld.IsFFAPvPRealm()) + { SetFFAPvP(true); + } } else { @@ -25259,7 +27396,9 @@ void Player::SetRestType(RestType n_r_type, uint32 areaTriggerId /*= 0*/) time_inn_enter = time(NULL); if (sWorld.IsFFAPvPRealm()) + { SetFFAPvP(false); + } } } @@ -25276,7 +27415,9 @@ uint32 Player::GetEquipGearScore(bool withBags, bool withBank) for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { _fillGearScoreData(item, &gearScore, twoHandScore); + } } if (withBags) @@ -25285,7 +27426,9 @@ uint32 Player::GetEquipGearScore(bool withBags, bool withBank) for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { _fillGearScoreData(item, &gearScore, twoHandScore); + } } // check bags @@ -25296,7 +27439,9 @@ uint32 Player::GetEquipGearScore(bool withBags, bool withBank) for (uint32 j = 0; j < pBag->GetBagSize(); ++j) { if (Item* item2 = pBag->GetItemByPos(j)) + { _fillGearScoreData(item2, &gearScore, twoHandScore); + } } } } @@ -25307,7 +27452,9 @@ uint32 Player::GetEquipGearScore(bool withBags, bool withBank) for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i) { if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i)) + { _fillGearScoreData(item, &gearScore, twoHandScore); + } } for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i) @@ -25320,7 +27467,9 @@ uint32 Player::GetEquipGearScore(bool withBags, bool withBank) for (uint8 j = 0; j < bag->GetBagSize(); ++j) { if (Item* item2 = bag->GetItemByPos(j)) + { _fillGearScoreData(item2, &gearScore, twoHandScore); + } } } } @@ -25349,7 +27498,9 @@ uint32 Player::GetEquipGearScore(bool withBags, bool withBank) DEBUG_LOG("Player: calculating gear score for %u. Result is %u", GetObjectGuid().GetCounter(), res); if (withBags && withBank) + { m_cachedGS = res; + } return res; } @@ -25434,7 +27585,9 @@ void Player::_fillGearScoreData(Item* item, GearScoreVec* gearScore, uint32& two (*gearScore)[EQUIPMENT_SLOT_FINGER1] = level; } else if ((*gearScore)[EQUIPMENT_SLOT_FINGER2] < level) + { (*gearScore)[EQUIPMENT_SLOT_FINGER2] = level; + } break; } case INVTYPE_TRINKET: @@ -25445,7 +27598,9 @@ void Player::_fillGearScoreData(Item* item, GearScoreVec* gearScore, uint32& two (*gearScore)[EQUIPMENT_SLOT_TRINKET1] = level; } else if ((*gearScore)[EQUIPMENT_SLOT_TRINKET2] < level) + { (*gearScore)[EQUIPMENT_SLOT_TRINKET2] = level; + } break; } case INVTYPE_CLOAK: @@ -25476,12 +27631,18 @@ void Player::SendCurrencies() const uint32 weekCap = GetCurrencyWeekCap(itr->second.currencyEntry); if (weekCap) + { data << uint32(floor(weekCap / itr->second.currencyEntry->GetPrecision())); + } if (itr->second.currencyEntry->HasSeasonCount()) + { data << uint32(floor(itr->second.seasonCount / itr->second.currencyEntry->GetPrecision())); + } data << uint32(itr->first); if (weekCap && itr->second.weekCount) + { data << uint32(floor(itr->second.weekCount / itr->second.currencyEntry->GetPrecision())); + } } GetSession()->SendPacket(&data); @@ -25557,7 +27718,9 @@ void Player::ModifyCurrencyCount(uint32 id, int32 count, bool modifyWeek, bool m } if (!ignoreMultipliers && count > 0) + { count *= GetTotalAuraMultiplierByMiscValue(SPELL_AURA_MOD_CURRENCY_GAIN, id); + } CurrencyTypesEntry const * currency = NULL; @@ -25591,11 +27754,15 @@ void Player::ModifyCurrencyCount(uint32 id, int32 count, bool modifyWeek, bool m int32 newTotalCount = oldTotalCount + count; if (newTotalCount < 0) + { newTotalCount = 0; + } int32 newWeekCount = oldWeekCount + (modifyWeek && count > 0 ? count : 0); if (newWeekCount < 0) + { newWeekCount = 0; + } int32 totalCap = GetCurrencyTotalCap(currency); if (totalCap && totalCap < newTotalCount) @@ -25617,20 +27784,26 @@ void Player::ModifyCurrencyCount(uint32 id, int32 count, bool modifyWeek, bool m if (newTotalCount != oldTotalCount) { if (itr->second.state != PLAYERCURRENCY_NEW) + { itr->second.state = PLAYERCURRENCY_CHANGED; + } itr->second.totalCount = newTotalCount; itr->second.weekCount = newWeekCount; int32 diff = newTotalCount - oldTotalCount; if (diff > 0 && modifySeason) + { itr->second.seasonCount += diff; + } // probably excessive checks if (IsInWorld() && !GetSession()->PlayerLoading()) { if (diff > 0) + { UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CURRENCY_EARNED, id, newTotalCount); + } WorldPacket packet(SMSG_SET_CURRENCY, 13); bool bit0 = modifyWeek && weekCap && diff > 0; @@ -25641,25 +27814,37 @@ void Player::ModifyCurrencyCount(uint32 id, int32 count, bool modifyWeek, bool m packet.WriteBit(bit2); if (bit1) + { packet << uint32(floor(itr->second.seasonCount / currency->GetPrecision())); + } packet << uint32(floor(newTotalCount / currency->GetPrecision())); packet << uint32(id); if (bit0) + { packet << uint32(floor(newWeekCount / currency->GetPrecision())); + } GetSession()->SendPacket(&packet); // init currency week limit for new currencies if (initWeek) + { SendCurrencyWeekCap(currency); + } if (diff > 0) + { CurrencyAddedQuestCheck(id); + } else + { CurrencyRemovedQuestCheck(id); + } } if (itr->first == CURRENCY_CONQUEST_ARENA_META || itr->first == CURRENCY_CONQUEST_BG_META) + { ModifyCurrencyCount(CURRENCY_CONQUEST_POINTS, diff, modifyWeek, modifySeason, ignoreMultipliers); + } } } @@ -25701,14 +27886,22 @@ void Player::_LoadCurrencies(QueryResult* result) cur.state = PLAYERCURRENCY_UNCHANGED; if (totalCap && totalCount > totalCap) + { cur.totalCount = totalCap; + } else + { cur.totalCount = totalCount; + } if (weekCap && weekCount > weekCap) + { cur.weekCount = weekCap; + } else + { cur.weekCount = weekCount; + } cur.seasonCount = seasonCount; @@ -25726,12 +27919,18 @@ void Player::_SaveCurrencies() for (PlayerCurrenciesMap::iterator itr = m_currencies.begin(); itr != m_currencies.end();) { if (itr->second.state == PLAYERCURRENCY_CHANGED) + { CharacterDatabase.PExecute("UPDATE `character_currencies` SET `totalCount` = '%u', `weekCount` = '%u', `seasonCount` = '%u', `flags` = '%u' WHERE `guid` = '%u' AND `id` = '%u'", itr->second.totalCount, itr->second.weekCount, itr->second.seasonCount, itr->second.flags, GetGUIDLow(), itr->first); + } else if (itr->second.state == PLAYERCURRENCY_NEW) + { CharacterDatabase.PExecute("INSERT INTO `character_currencies` (`guid`, `id`, `totalCount`, `weekCount`, `seasonCount`, `flags`) VALUES ('%u', '%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second.totalCount, itr->second.weekCount, itr->second.seasonCount, itr->second.flags); + } if (itr->second.state == PLAYERCURRENCY_REMOVED) + { m_currencies.erase(itr++); + } else { itr->second.state = PLAYERCURRENCY_UNCHANGED; @@ -25983,7 +28182,9 @@ void Player::UpdateArmorSpecializations() for (int i = 0; i < MAX_ARMOR_SPECIALIZATION_SPELLS; ++i) { if (armorSpecToTab[i].Class != getClass()) + { continue; + } SpellEntry const * spellProto = sSpellStore.LookupEntry(armorSpecToTab[i].spellId); if (!spellProto || !spellProto->HasAttribute(SPELL_ATTR_EX8_ARMOR_SPECIALIZATION)) @@ -26010,7 +28211,9 @@ void Player::UpdateArmorSpecializations() Aura* aura = holder->GetAuraByEffectIndex(EFFECT_INDEX_0); if (!aura) + { continue; + } // recalculate modifier depending on current tree aura->ApplyModifier(false, false); @@ -26061,10 +28264,14 @@ bool Player::FitArmorSpecializationRules(SpellEntry const * spellProto) const if (inventoryTypeMask & (1 << i)) { if (!GetSlotsForInventoryType(i, slots)) + { continue; + } for (int j = 0; j < 4; ++j) if (slots[j] != NULL_SLOT) + { slotMask |= 1 << slots[j]; + } } } @@ -26105,13 +28312,19 @@ float Player::ComputeRest(time_t timePassed, bool offline /*= false*/, bool inRe // So final formula (TotalXP/1152000) float bonus = timePassed * (GetUInt32Value(PLAYER_NEXT_LEVEL_XP) / 1152000.0f); // Get the gained rest xp for given second if (!offline) + { bonus *= sWorld.getConfig(CONFIG_FLOAT_RATE_REST_INGAME); // Apply the custom setting + } else { if (inRestPlace) + { bonus *= sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY); + } else + { bonus *= sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS) / 4.0f; // bonus is reduced by 4 when not in rest place + } } return bonus; } diff --git a/src/game/Object/Player.h b/src/game/Object/Player.h index 9578cca95..b25bc4290 100644 --- a/src/game/Object/Player.h +++ b/src/game/Object/Player.h @@ -257,9 +257,13 @@ struct Glyph else if (newId == 0) { if (uState == GLYPH_NEW) // delete before add new -> no change + { uState = GLYPH_UNCHANGED; + } else // delete existing data + { uState = GLYPH_DELETED; + } } else if (uState != GLYPH_NEW) // if not new data, change current data { @@ -404,9 +408,13 @@ struct Runes void SetRuneState(uint8 index, bool set = true) { if (set) + { runeState |= (1 << index); // usable + } else + { runeState &= ~(1 << index); // on cooldown + } } }; @@ -1661,13 +1669,19 @@ class Player : public Unit void ModifyMoney(int64 d) { if (d < 0) + { SetMoney(GetMoney() > uint64(-d) ? GetMoney() + d : 0); + } else + { SetMoney(GetMoney() < uint64(MAX_MONEY_AMOUNT - d) ? GetMoney() + d : MAX_MONEY_AMOUNT); + } // "At Gold Limit" if (GetMoney() >= MAX_MONEY_AMOUNT) + { SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, NULL, NULL); + } } void SetMoney(uint64 value) { diff --git a/src/game/Object/ReactorAI.cpp b/src/game/Object/ReactorAI.cpp index f6271f0ab..a8df4c0f7 100644 --- a/src/game/Object/ReactorAI.cpp +++ b/src/game/Object/ReactorAI.cpp @@ -129,5 +129,7 @@ ReactorAI::EnterEvadeMode() // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) + { m_creature->GetMotionMaster()->MoveTargetedHome(); + } } diff --git a/src/game/Object/ReputationMgr.cpp b/src/game/Object/ReputationMgr.cpp index ae73f1209..6bcbe994b 100644 --- a/src/game/Object/ReputationMgr.cpp +++ b/src/game/Object/ReputationMgr.cpp @@ -106,9 +106,13 @@ ReputationRank ReputationMgr::GetBaseRank(FactionEntry const* factionEntry) cons void ReputationMgr::ApplyForceReaction(uint32 faction_id, ReputationRank rank, bool apply) { if (apply) + { m_forcedReactions[faction_id] = rank; + } else + { m_forcedReactions.erase(faction_id); + } } uint32 ReputationMgr::GetDefaultStateFlags(FactionEntry const* factionEntry) const @@ -244,7 +248,9 @@ void ReputationMgr::Initialize() newFaction.needSave = true; if (newFaction.Flags & FACTION_FLAG_VISIBLE) + { ++m_visibleFactionCount; + } UpdateRankCounters(REP_HOSTILE, GetBaseRank(factionEntry)); @@ -274,7 +280,9 @@ void ReputationMgr::SetReputation(FactionEntry const* factionEntry, int32 standi // bonuses are already given, so just modify standing by rate int32 spilloverRep = standing * repTemplate->faction_rate[i]; if (SetOneFactionReputation(sFactionStore.LookupEntry(repTemplate->faction[i]), spilloverRep, incremental)) + { anyRankIncreased = true; + } } } } @@ -295,7 +303,9 @@ void ReputationMgr::SetReputation(FactionEntry const* factionEntry, int32 standi if (parentState != m_factions.end() && (parentState->second.Flags & FACTION_FLAG_TEAM_REPUTATION)) { if (SetOneFactionReputation(parent, int32(spillOverRepOut), incremental)) + { anyRankIncreased = true; + } } else // spill to "sister" factions { @@ -311,12 +321,16 @@ void ReputationMgr::SetReputation(FactionEntry const* factionEntry, int32 standi if (FactionEntry const* factionEntryCalc = sFactionStore.LookupEntry(*itr)) { if (factionEntryCalc == factionEntry || GetRank(factionEntryCalc) > ReputationRank(factionEntryCalc->spilloverMaxRankIn)) + { continue; + } int32 spilloverRep = int32(spillOverRepOut * factionEntryCalc->spilloverRateIn); if (spilloverRep != 0 || !incremental) if (SetOneFactionReputation(factionEntryCalc, spilloverRep, incremental)) + { anyRankIncreased = true; + } } } } @@ -326,7 +340,9 @@ void ReputationMgr::SetReputation(FactionEntry const* factionEntry, int32 standi if (faction != m_factions.end()) { if (SetOneFactionReputation(factionEntry, standing, incremental)) + { anyRankIncreased = true; + } // only this faction gets reported to client, even if it has no own visible standing SendState(&faction->second, anyRankIncreased); @@ -342,12 +358,18 @@ bool ReputationMgr::SetOneFactionReputation(FactionEntry const* factionEntry, in int32 BaseRep = GetBaseReputation(factionEntry); if (incremental) + { standing += faction.Standing + BaseRep; + } if (standing > Reputation_Cap) + { standing = Reputation_Cap; + } else if (standing < Reputation_Bottom) + { standing = Reputation_Bottom; + } ReputationRank old_rank = ReputationToRank(faction.Standing + BaseRep); ReputationRank new_rank = ReputationToRank(standing); @@ -359,7 +381,9 @@ bool ReputationMgr::SetOneFactionReputation(FactionEntry const* factionEntry, in SetVisible(&faction); if (new_rank <= REP_HOSTILE) + { SetAtWar(&faction, true); + } UpdateRankCounters(old_rank, new_rank); @@ -388,7 +412,9 @@ void ReputationMgr::SetVisible(FactionTemplateEntry const* factionTemplateEntry) } if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction)) + { SetVisible(factionEntry); + } } void ReputationMgr::SetVisible(FactionEntry const* factionEntry) @@ -462,9 +488,13 @@ void ReputationMgr::SetAtWar(FactionState* faction, bool atWar) } if (atWar) + { faction->Flags |= FACTION_FLAG_AT_WAR; + } else + { faction->Flags &= ~FACTION_FLAG_AT_WAR; + } faction->needSend = true; faction->needSave = true; @@ -496,9 +526,13 @@ void ReputationMgr::SetInactive(FactionState* faction, bool inactive) } if (inactive) + { faction->Flags |= FACTION_FLAG_INACTIVE; + } else + { faction->Flags &= ~FACTION_FLAG_INACTIVE; + } faction->needSend = true; faction->needSave = true; @@ -553,10 +587,14 @@ void ReputationMgr::LoadFromDB(QueryResult* result) if (forceItr != m_forcedReactions.end()) { if (forceItr->second <= REP_HOSTILE) + { SetAtWar(faction, true); + } } else if (GetRank(factionEntry) <= REP_HOSTILE) + { SetAtWar(faction, true); + } // reset changed flag if values similar to saved in DB if (faction->Flags == dbFactionFlags) @@ -595,16 +633,28 @@ void ReputationMgr::SaveToDB() void ReputationMgr::UpdateRankCounters(ReputationRank old_rank, ReputationRank new_rank) { if (old_rank >= REP_EXALTED) + { --m_exaltedFactionCount; + } if (old_rank >= REP_REVERED) + { --m_reveredFactionCount; + } if (old_rank >= REP_HONORED) + { --m_honoredFactionCount; + } if (new_rank >= REP_EXALTED) + { ++m_exaltedFactionCount; + } if (new_rank >= REP_REVERED) + { ++m_reveredFactionCount; + } if (new_rank >= REP_HONORED) + { ++m_honoredFactionCount; + } } diff --git a/src/game/Object/SocialMgr.cpp b/src/game/Object/SocialMgr.cpp index c50001df8..f522159f7 100644 --- a/src/game/Object/SocialMgr.cpp +++ b/src/game/Object/SocialMgr.cpp @@ -49,7 +49,9 @@ uint32 PlayerSocial::GetNumberOfSocialsWithFlag(SocialFlag flag) for (PlayerSocialMap::const_iterator itr = m_playerSocialMap.begin(); itr != m_playerSocialMap.end(); ++itr) { if (itr->second.Flags & flag) + { ++counter; + } } return counter; } @@ -74,7 +76,9 @@ bool PlayerSocial::AddToSocialList(ObjectGuid friend_guid, bool ignore) uint32 flag = SOCIAL_FLAG_FRIEND; if (ignore) + { flag = SOCIAL_FLAG_IGNORED; + } PlayerSocialMap::const_iterator itr = m_playerSocialMap.find(friend_guid.GetCounter()); if (itr != m_playerSocialMap.end()) @@ -102,7 +106,9 @@ void PlayerSocial::RemoveFromSocialList(ObjectGuid friend_guid, bool ignore) uint32 flag = SOCIAL_FLAG_FRIEND; if (ignore) + { flag = SOCIAL_FLAG_IGNORED; + } itr->second.Flags &= ~flag; if (itr->second.Flags == 0) @@ -214,7 +220,9 @@ void SocialMgr::GetFriendInfo(Player* player, uint32 friend_lowguid, FriendInfo& PlayerSocialMap::iterator itr = player->GetSocial()->m_playerSocialMap.find(friend_lowguid); if (itr != player->GetSocial()->m_playerSocialMap.end()) + { friendInfo.Note = itr->second.Note; + } // PLAYER see his team only and PLAYER can't see MODERATOR, GAME MASTER, ADMINISTRATOR characters // MODERATOR, GAME MASTER, ADMINISTRATOR can see all @@ -225,9 +233,13 @@ void SocialMgr::GetFriendInfo(Player* player, uint32 friend_lowguid, FriendInfo& { friendInfo.Status = FRIEND_STATUS_ONLINE; if (pFriend->isAFK()) + { friendInfo.Status = FRIEND_STATUS_AFK; + } if (pFriend->isDND()) + { friendInfo.Status = FRIEND_STATUS_DND; + } friendInfo.Area = pFriend->GetZoneId(); friendInfo.Level = pFriend->getLevel(); friendInfo.Class = pFriend->getClass(); @@ -281,9 +293,13 @@ void SocialMgr::SendFriendStatus(Player* player, FriendsResult result, ObjectGui } if (broadcast) + { BroadcastToFriendListers(player, &data); + } else + { player->GetSession()->SendPacket(&data); + } } void SocialMgr::BroadcastToFriendListers(Player* player, WorldPacket* packet) @@ -345,16 +361,24 @@ PlayerSocial* SocialMgr::LoadFromDB(QueryResult* result, ObjectGuid guid) note = fields[2].GetCppString(); if ((flags & SOCIAL_FLAG_IGNORED) && ignoreCounter >= SOCIALMGR_IGNORE_LIMIT) + { continue; + } if ((flags & SOCIAL_FLAG_FRIEND) && friendCounter >= SOCIALMGR_FRIEND_LIMIT) + { continue; + } social->m_playerSocialMap[friend_guid] = FriendInfo(flags, note); if (flags & SOCIAL_FLAG_IGNORED) + { ++ignoreCounter; + } else + { ++friendCounter; + } } while (result->NextRow()); delete result; diff --git a/src/game/Object/SpellMgr.cpp b/src/game/Object/SpellMgr.cpp index 05c4e69d5..17380753a 100644 --- a/src/game/Object/SpellMgr.cpp +++ b/src/game/Object/SpellMgr.cpp @@ -103,14 +103,18 @@ int32 CalculateSpellDuration(SpellEntry const* spellInfo, Unit const* caster) int32 maxduration = GetSpellMaxDuration(spellInfo); if (duration != maxduration && caster->GetTypeId() == TYPEID_PLAYER) + { duration += int32((maxduration - duration) * ((Player*)caster)->GetComboPoints() / 5); + } if (Player* modOwner = caster->GetSpellModOwner()) { modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_DURATION, duration); if (duration < 0) + { duration = 0; + } } } @@ -143,12 +147,16 @@ uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell) { uint32 level = spell->GetCaster()->getLevel(); if (level == 1) + { castTime = uint32(spellScalingEntry->castTimeMin); + } else if (level < uint32(spellScalingEntry->castScalingMaxLevel)) castTime = uint32(spellScalingEntry->castTimeMin + float(level - 1) * (spellScalingEntry->castTimeMax - spellScalingEntry->castTimeMin) / (spellScalingEntry->castScalingMaxLevel - 1)); else + { castTime = uint32(spellScalingEntry->castTimeMax); + } } else if (SpellCastTimesEntry const* spellCastTimeEntry = sSpellCastTimesStore.LookupEntry(spellInfo->GetCastingTimeIndex())) { @@ -158,7 +166,9 @@ uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell) if (SpellLevelsEntry const* levelsEntry = spellInfo->GetSpellLevels()) { if (levelsEntry->maxLevel) + { level = std::min(level, levelsEntry->maxLevel); + } level = std::max(level, levelsEntry->baseLevel) - levelsEntry->baseLevel; } @@ -166,10 +176,14 @@ uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell) castTime = uint32(spellCastTimeEntry->CastTime + spellCastTimeEntry->CastTimePerLevel * level); } else + { castTime = uint32(spellCastTimeEntry->CastTime); + } if (castTime < uint32(spellCastTimeEntry->MinCastTime)) + { castTime = uint32(spellCastTimeEntry->MinCastTime); + } } else // not all spells have cast time index and this is all is pasiive abilities @@ -178,19 +192,27 @@ uint32 GetSpellCastTime(SpellEntry const* spellInfo, Spell const* spell) if (spell) { if (Player* modOwner = spell->GetCaster()->GetSpellModOwner()) + { modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell); + } if (!spellInfo->HasAttribute(SPELL_ATTR_UNK4) && !spellInfo->HasAttribute(SPELL_ATTR_TRADESPELL)) + { castTime = uint32(castTime * spell->GetCaster()->GetFloatValue(UNIT_MOD_CAST_SPEED)); + } else { if (spell->IsRangedSpell() && !spell->IsAutoRepeat()) + { castTime = uint32(castTime * spell->GetCaster()->m_modAttackSpeedPct[RANGED_ATTACK]); + } } } if (spellInfo->HasAttribute(SPELL_ATTR_RANGED) && (!spell || !spell->IsAutoRepeat())) + { castTime += 500; + } return (castTime > 0) ? castTime : 0; } @@ -200,10 +222,14 @@ uint32 GetSpellCastTimeForBonus(SpellEntry const* spellProto, DamageEffectType d uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto); if (CastingTime > 7000) CastingTime = 7000; - if (CastingTime < 1500) CastingTime = 1500; + { + if (CastingTime < 1500) CastingTime = 1500; + } if (damagetype == DOT && !IsChanneledSpell(spellProto)) + { CastingTime = 3500; + } int32 overTime = 0; uint8 effects = 0; @@ -214,16 +240,22 @@ uint32 GetSpellCastTimeForBonus(SpellEntry const* spellProto, DamageEffectType d { SpellEffectEntry const* spellEffect = spellProto->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (IsAreaEffectTarget(Targets(spellEffect->EffectImplicitTargetA)) || IsAreaEffectTarget(Targets(spellEffect->EffectImplicitTargetB))) + { AreaEffect = true; + } } for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) { SpellEffectEntry const* spellEffect = spellProto->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } switch (spellEffect->Effect) { case SPELL_EFFECT_SCHOOL_DAMAGE: @@ -241,7 +273,9 @@ uint32 GetSpellCastTimeForBonus(SpellEntry const* spellProto, DamageEffectType d case SPELL_AURA_PERIODIC_HEAL: case SPELL_AURA_PERIODIC_LEECH: if (GetSpellDuration(spellProto)) + { overTime = GetSpellDuration(spellProto); + } break; // Penalty for additional effects case SPELL_AURA_DUMMY: @@ -271,28 +305,40 @@ uint32 GetSpellCastTimeForBonus(SpellEntry const* spellProto, DamageEffectType d // mainly for DoTs which are 3500 here otherwise uint32 OriginalCastTime = GetSpellCastTime(spellProto); if (OriginalCastTime > 7000) OriginalCastTime = 7000; - if (OriginalCastTime < 1500) OriginalCastTime = 1500; + { + if (OriginalCastTime < 1500) OriginalCastTime = 1500; + } // Portion to Over Time float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f)); if (damagetype == DOT) + { CastingTime = uint32(CastingTime * PtOT); + } else if (PtOT < 1.0f) + { CastingTime = uint32(CastingTime * (1 - PtOT)); + } else + { CastingTime = 0; + } } // Area Effect Spells receive only half of bonus if (AreaEffect) + { CastingTime /= 2; + } // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing for (int j = 0; j < MAX_EFFECT_INDEX; ++j) { SpellEffectEntry const* spellEffect = spellProto->GetSpellEffect(SpellEffectIndex(j)); if (!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_HEALTH_LEECH || spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_LEECH) { @@ -320,13 +366,17 @@ uint16 GetSpellAuraMaxTicks(SpellEntry const* spellInfo) // 200% limit if (DotDuration > 30000) + { DotDuration = 30000; + } for (int j = 0; j < MAX_EFFECT_INDEX; ++j) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && ( spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE || spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_HEAL || @@ -362,10 +412,14 @@ float CalculateDefaultCoefficient(SpellEntry const* spellProto, DamageEffectType if (damagetype == DOT) { if (!IsChanneledSpell(spellProto)) + { DotFactor = GetSpellDuration(spellProto) / 15000.0f; + } if (uint16 DotTicks = GetSpellAuraMaxTicks(spellProto)) + { DotFactor /= DotTicks; + } } // Distribute Damage over multiple effects, reduce by AoE @@ -430,7 +484,9 @@ bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 spellId_2) SpellEntry const* spellInfo_1 = sSpellStore.LookupEntry(spellId_1); SpellEntry const* spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if (!spellInfo_1 || !spellInfo_2) return false; - if (spellInfo_1->Id == spellId_2) return false; + { + if (spellInfo_1->Id == spellId_2) return false; + } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { @@ -440,7 +496,9 @@ bool IsNoStackAuraDueToAura(uint32 spellId_1, uint32 spellId_2) { SpellEffectEntry const* effect_2 = spellInfo_2->GetSpellEffect(SpellEffectIndex(j)); if(!effect_1 || !effect_2) + { continue; + } if (effect_1->Effect == effect_2->Effect && effect_1->EffectApplyAuraName == effect_2->EffectApplyAuraName && effect_1->EffectMiscValue == effect_2->EffectMiscValue @@ -459,14 +517,18 @@ int32 CompareAuraRanks(uint32 spellId_1, uint32 spellId_2) SpellEntry const* spellInfo_1 = sSpellStore.LookupEntry(spellId_1); SpellEntry const* spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if (!spellInfo_1 || !spellInfo_2) return 0; - if (spellId_1 == spellId_2) return 0; + { + if (spellId_1 == spellId_2) return 0; + } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { SpellEffectEntry const* spellEffect_1 = spellInfo_1->GetSpellEffect(SpellEffectIndex(i)); SpellEffectEntry const* spellEffect_2 = spellInfo_2->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect_1 || !spellEffect_2) + { continue; + } if (spellEffect_1->Effect != 0 && spellEffect_2->Effect != 0 && spellEffect_1->Effect == spellEffect_2->Effect) { @@ -505,7 +567,9 @@ SpellSpecific GetSpellSpecific(uint32 spellId) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } switch(spellEffect->EffectApplyAuraName) { @@ -940,7 +1004,9 @@ bool IsPositiveEffect(SpellEntry const* spellproto, SpellEffectIndex effIndex) case SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT: case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: if (spellEffect->CalculateSimpleValue() > 0) + { return true; // some expected positive spells have SPELL_ATTR_NEGATIVE or unclear target modes + } break; case SPELL_AURA_ADD_TARGET_TRIGGER: return true; @@ -957,7 +1023,9 @@ bool IsPositiveEffect(SpellEntry const* spellproto, SpellEffectIndex effIndex) { SpellEffectEntry const* triggerSpellEffect = spellTriggeredProto->GetSpellEffect(SpellEffectIndex(i)); if (!triggerSpellEffect) + { continue; + } // if non-positive trigger cast targeted to positive target this main cast is non-positive // this will place this spell auras as debuffs if (triggerSpellEffect->Effect && @@ -973,7 +1041,9 @@ bool IsPositiveEffect(SpellEntry const* spellproto, SpellEffectIndex effIndex) break; case SPELL_AURA_MOD_STUN: //have positive and negative spells, we can't sort its correctly at this moment. if (effIndex == EFFECT_INDEX_0 && spellproto->GetSpellEffectIdByIndex(EFFECT_INDEX_1) == 0 && spellproto->GetSpellEffectIdByIndex(EFFECT_INDEX_2) == 0) + { return false; // but all single stun aura spells is negative + } // Petrification if (spellproto->Id == 17624) @@ -1321,7 +1391,9 @@ void SpellMgr::LoadSpellTargetPositions() { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (spellEffect->EffectImplicitTargetA==TARGET_TABLE_X_Y_Z_COORDINATES || spellEffect->EffectImplicitTargetB==TARGET_TABLE_X_Y_Z_COORDINATES) { found = true; @@ -1393,7 +1465,9 @@ struct SpellRankHelper for (std::set::const_iterator itr = firstRankSpells.begin(); itr != firstRankSpells.end(); ++itr) { if (worker.SetStateToEntry(*itr)) + { mgr.doForHighRanks(*itr, worker); + } } } std::set firstRankSpells; @@ -1413,16 +1487,22 @@ struct DoSpellProcEvent // add ranks only for not filled data (some ranks have ppm data different for ranks for example) SpellProcEventMap::const_iterator spellItr = spe_map.find(spell_id); if (spellItr == spe_map.end()) + { spe_map[spell_id] = spe; + } // if custom rank data added then it must be same except ppm else { SpellProcEventEntry const& r_spe = spellItr->second; if (spe.schoolMask != r_spe.schoolMask) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different schoolMask from first rank in chain", spell_id); + } if (spe.spellFamilyName != r_spe.spellFamilyName) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different spellFamilyName from first rank in chain", spell_id); + } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { @@ -1434,18 +1514,26 @@ struct DoSpellProcEvent } if (spe.procFlags != r_spe.procFlags) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different procFlags from first rank in chain", spell_id); + } if (spe.procEx != r_spe.procEx) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different procEx from first rank in chain", spell_id); + } // only ppm allowed has been different from first rank if (spe.customChance != r_spe.customChance) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different customChance from first rank in chain", spell_id); + } if (spe.cooldown != r_spe.cooldown) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` as custom rank have different cooldown from first rank in chain", spell_id); + } } } @@ -1470,29 +1558,41 @@ struct DoSpellProcEvent if (spe.procFlags == 0) { if (spell->GetProcFlags()==0) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell (no proc flags)", spell->Id); + } } else { if (spell->GetProcFlags()==spe.procFlags) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` has exactly same proc flags as in spell.dbc, field value redundant", spell->Id); + } else + { isCustom = true; + } } if (spe.customChance == 0) { /* enable for re-check cases, 0 chance ok for some cases because in some cases it set by another spell/talent spellmod) if (spell->procChance==0 && !spe.ppmRate) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` probally not triggered spell (no chance or ppm)", spell->Id); + } */ } else { if (spell->GetProcChance()==spe.customChance) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` has exactly same custom chance as in spell.dbc, field value redundant", spell->Id); + } else + { isCustom = true; + } } // totally redundant record @@ -1507,17 +1607,25 @@ struct DoSpellProcEvent empty = false; ClassFamilyMask const& mask = spell->GetEffectSpellClassMask(SpellEffectIndex(i)); if (mask == spe.spellFamilyMask[i]) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` has same class mask as in Spell.dbc (EffectIndex %u) and doesn't have any other data", spell->Id, i); + } } } if (empty) + { sLog.outErrorDb("Spell %u listed in `spell_proc_event` doesn't have any useful data", spell->Id); + } } if (isCustom) + { ++customProc; + } else + { ++count; + } } bool HasEntry(uint32 spellId) { return spe_map.find(spellId) != spe_map.end(); } @@ -1806,7 +1914,9 @@ void SpellMgr::LoadSpellBonuses() { SpellEffectEntry const* spellEffect = spell->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (!spellEffect->Effect) { ++x; @@ -1834,7 +1944,9 @@ void SpellMgr::LoadSpellBonuses() // TODO: maybe add explicit list possible direct damage spell effects... if (x < MAX_EFFECT_INDEX) + { need_direct = true; + } // Check if direct_bonus is needed in `spell_bonus_data` float direct_calc = 0.0f; @@ -1846,7 +1958,9 @@ void SpellMgr::LoadSpellBonuses() { SpellEffectEntry const* spellEffect = spell->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // Heals (Also count Mana Shield and Absorb effects as heals) if (spellEffect->Effect == SPELL_EFFECT_HEAL || spellEffect->Effect == SPELL_EFFECT_HEAL_MAX_HEALTH || (spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && (spellEffect->EffectApplyAuraName == SPELL_AURA_SCHOOL_ABSORB || spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_HEAL)) ) @@ -1869,7 +1983,9 @@ void SpellMgr::LoadSpellBonuses() { SpellEffectEntry const* spellEffect = spell->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // Periodic Heals if (spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_HEAL) { @@ -2060,14 +2176,18 @@ struct DoSpellThreat // add ranks only for not filled data (spells adding flat threat are usually different for ranks) SpellThreatMap::const_iterator spellItr = threatMap.find(spell_id); if (spellItr == threatMap.end()) + { threatMap[spell_id] = ste; + } // just assert that entry is not redundant else { SpellThreatEntry const& r_ste = spellItr->second; if (ste.threat == r_ste.threat && ste.multiplier == r_ste.multiplier && ste.ap_bonus == r_ste.ap_bonus) + { sLog.outErrorDb("Spell %u listed in `spell_threat` as custom rank has same data as Rank 1, so redundant", spell_id); + } } } const char* TableName() { return "spell_threat"; } @@ -2154,7 +2274,9 @@ bool SpellMgr::IsRankSpellDueToSpell(SpellEntry const* spellInfo_1, uint32 spell { SpellEntry const* spellInfo_2 = sSpellStore.LookupEntry(spellId_2); if (!spellInfo_1 || !spellInfo_2) return false; - if (spellInfo_1->Id == spellId_2) return false; + { + if (spellInfo_1->Id == spellId_2) return false; + } return GetFirstSpellInChain(spellInfo_1->Id) == GetFirstSpellInChain(spellId_2); } @@ -2184,7 +2306,9 @@ bool SpellMgr::canStackSpellRanksInSpellBook(SpellEntry const* spellInfo) const { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } switch(spellInfo->GetSpellFamilyName()) { case SPELLFAMILY_PALADIN: @@ -2623,7 +2747,9 @@ bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) cons if ((spellIconID_1 == 313 && spellIconID_2 == 1932) || (spellIconID_2 == 313 && spellIconID_1 == 1932)) if (spellVisual_1 != 0 && spellVisual_2 != 0) + { return true; // can't be stacked + } // Corruption and Unstable Affliction if ((spellIconID_1 == 313 && spellIconID_2 == 2039) || @@ -2995,7 +3121,9 @@ bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) cons SpellEffectEntry const* spellEffect1 = spellInfo_1->GetSpellEffect(SpellEffectIndex(i)); SpellEffectEntry const* spellEffect2 = spellInfo_2->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect1 || !spellEffect2) + { continue; + } if (spellEffect1->EffectApplyAuraName == SPELL_AURA_ADD_FLAT_MODIFIER || spellEffect1->EffectApplyAuraName == SPELL_AURA_ADD_PCT_MODIFIER || spellEffect2->EffectApplyAuraName == SPELL_AURA_ADD_FLAT_MODIFIER || @@ -3031,7 +3159,9 @@ bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) cons SpellEffectEntry const* spellEffect2 = spellInfo_2->GetSpellEffect(SpellEffectIndex(i)); if (!spellEffect1 && !spellEffect2) + { continue; + } if (!spellEffect1 || !spellEffect2) { @@ -3046,7 +3176,9 @@ bool SpellMgr::IsNoStackSpellDueToSpell(uint32 spellId_1, uint32 spellId_2) cons // ignore dummy only spells if (spellEffect1->Effect && spellEffect1->Effect != SPELL_EFFECT_DUMMY && spellEffect1->EffectApplyAuraName != SPELL_AURA_DUMMY) + { dummy_only = false; + } } if (dummy_only) @@ -3177,7 +3309,9 @@ bool SpellMgr::IsSkillBonusSpell(uint32 spellId) const { SkillLineAbilityEntry const* pAbility = _spell_idx->second; if (!pAbility || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL) + { continue; + } if (pAbility->req_skill_value > 0) { @@ -3207,7 +3341,9 @@ SpellEntry const* SpellMgr::SelectAuraRankForLevel(SpellEntry const* spellInfo, { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // for simple aura in check apply to any non caster based targets, in rank search mode to any explicit targets if (((spellEffect->Effect == SPELL_EFFECT_APPLY_AURA && (IsExplicitPositiveTarget(spellEffect->EffectImplicitTargetA) || @@ -3231,7 +3367,9 @@ SpellEntry const* SpellMgr::SelectAuraRankForLevel(SpellEntry const* spellInfo, { SpellEntry const* nextSpellInfo = sSpellStore.LookupEntry(nextSpellId); if (!nextSpellInfo) + { break; + } // if found appropriate level if (level + 10 >= nextSpellInfo->GetSpellLevel()) @@ -3325,17 +3463,23 @@ void SpellMgr::LoadSpellChains() { TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); if (!talentInfo) + { continue; + } // not add ranks for 1 ranks talents (if exist non ranks spells then it will included in table data) if (!talentInfo->RankID[1]) + { continue; + } for (int j = 0; j < MAX_TALENT_RANK; ++j) { uint32 spell_id = talentInfo->RankID[j]; if (!spell_id) + { continue; + } if (!sSpellStore.LookupEntry(spell_id)) { @@ -3363,27 +3507,37 @@ void SpellMgr::LoadSpellChains() // skip GM/test/internal spells.begin Its not have ranks anyway if (ab_itr->second->skillId == SKILL_INTERNAL) + { continue; + } // some forward spells not exist and can be ignored (some outdated data) SpellEntry const* spell_entry = sSpellStore.LookupEntry(spell_id); if (!spell_entry) // no cases + { continue; + } // ignore spell without forwards (non ranked or missing info in skill abilities) uint32 forward_id = ab_itr->second->forward_spellid; if (!forward_id) + { continue; + } // some forward spells not exist and can be ignored (some outdated data) SpellEntry const* forward_entry = sSpellStore.LookupEntry(forward_id); if (!forward_entry) + { continue; + } // some forward spells still exist but excluded from real use as ranks and not listed in skill abilities now SkillLineAbilityMapBounds bounds = mSkillLineAbilityMap.equal_range(forward_id); if (bounds.first == bounds.second) + { continue; + } // spell already listed in chains store SpellChainMap::const_iterator chain_itr = mSpellChains.find(forward_id); @@ -3594,7 +3748,9 @@ void SpellMgr::LoadSpellChains() } if (skip) + { continue; + } } mSpellChains[spell_id] = node; @@ -3660,10 +3816,14 @@ void SpellMgr::LoadSpellChains() SpellChainNode const& node = i->second; if (node.prev) + { mSpellChainsNext.insert(SpellChainMapNext::value_type(node.prev, spell_id)); + } if (node.req) + { mSpellChainsNext.insert(SpellChainMapNext::value_type(node.req, spell_id)); + } } // check single rank redundant cases (single rank talents/spell abilities not added by default so this can be only custom cases) @@ -3671,7 +3831,9 @@ void SpellMgr::LoadSpellChains() { // skip non-first ranks, and spells with additional reqs if (i->second.rank > 1 || i->second.req) + { continue; + } if (mSpellChainsNext.find(i->first) == mSpellChainsNext.end()) { @@ -3697,22 +3859,30 @@ void SpellMgr::LoadSpellLearnSkills() SpellEntry const* entry = sSpellStore.LookupEntry(spell); if (!entry) + { continue; + } for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { SpellEffectEntry const* spellEffect = entry->GetSpellEffect(SpellEffectIndex(i)); if (!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_SKILL) { SpellLearnSkillNode dbc_node; dbc_node.skill = spellEffect->EffectMiscValue; dbc_node.step = entry->CalculateSimpleValue(SpellEffectIndex(i)); if (dbc_node.skill != SKILL_RIDING) + { dbc_node.value = 1; + } else + { dbc_node.value = dbc_node.step * 75; + } dbc_node.maxvalue = dbc_node.step * 75; mSpellLearnSkills[spell] = dbc_node; @@ -3791,13 +3961,17 @@ void SpellMgr::LoadSpellLearnSpells() SpellEntry const* entry = sSpellStore.LookupEntry(spell); if (!entry) + { continue; + } for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { SpellEffectEntry const* spellEffect = entry->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if(spellEffect->Effect == SPELL_EFFECT_LEARN_SPELL) { SpellLearnSpellNode dbc_node; @@ -3806,7 +3980,9 @@ void SpellMgr::LoadSpellLearnSpells() // ignore learning nonexistent spells (broken/outdated/or generic learning spell 483 if (!sSpellStore.LookupEntry(dbc_node.spell)) + { continue; + } // talent or passive spells or skill-step spells auto-casted and not need dependent learning, // pet teaching spells don't must be dependent learning (casted) @@ -3860,7 +4036,9 @@ void SpellMgr::LoadSpellScriptTarget() { SpellEffectEntry const* spellEffect = spellProto->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if( spellEffect->EffectImplicitTargetA == TARGET_SCRIPT || spellEffect->EffectImplicitTargetB == TARGET_SCRIPT || @@ -3905,7 +4083,9 @@ void SpellMgr::LoadSpellScriptTarget() case SPELL_TARGET_TYPE_GAMEOBJECT: { if (!itr->targetEntry) + { break; + } if (!sGOStorage.LookupEntry(itr->targetEntry)) { @@ -3948,13 +4128,17 @@ void SpellMgr::LoadSpellScriptTarget() { SpellEntry const* spellInfo = sSpellStore.LookupEntry(i); if (!spellInfo) + { continue; + } for (int j = 0; j < MAX_EFFECT_INDEX; ++j) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(j)); if (!spellEffect) + { continue; + } if (spellEffect->EffectImplicitTargetA == TARGET_SCRIPT || spellEffect->EffectImplicitTargetA != TARGET_SELF && spellEffect->EffectImplicitTargetB == TARGET_SCRIPT) @@ -4063,28 +4247,38 @@ void SpellMgr::LoadPetLevelupSpellMap() { CreatureFamilyEntry const* creatureFamily = sCreatureFamilyStore.LookupEntry(i); if (!creatureFamily) // not exist + { continue; + } for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) { SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j); if (!skillLine) + { continue; + } if (skillLine->skillId != creatureFamily->skillLine[0] && (!creatureFamily->skillLine[1] || skillLine->skillId != creatureFamily->skillLine[1])) continue; if (skillLine->learnOnGetSkill != ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL) + { continue; + } SpellEntry const* spell = sSpellStore.LookupEntry(skillLine->spellId); if (!spell) // not exist + { continue; + } PetLevelupSpellSet& spellSet = mPetLevelupSpellMap[creatureFamily->ID]; if (spellSet.empty()) + { ++family_count; + } spellSet.insert(PetLevelupSpellSet::value_type(spell->GetSpellLevel(),spell->Id)); count++; @@ -4118,7 +4312,9 @@ bool SpellMgr::LoadPetDefaultSpells_helper(CreatureInfo const* cInfo, PetDefault for (int j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) { if (!petDefSpells.spellid[j]) + { continue; + } for (PetLevelupSpellSet::const_iterator itr = levelupSpells->begin(); itr != levelupSpells->end(); ++itr) { @@ -4158,15 +4354,21 @@ void SpellMgr::LoadPetDefaultSpells() { CreatureInfo const* cInfo = sCreatureStorage.LookupEntry(i); if (!cInfo) + { continue; + } if (!cInfo->PetSpellDataId) + { continue; + } // for creature with PetSpellDataId get default pet spells from dbc CreatureSpellDataEntry const* spellDataEntry = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId); if (!spellDataEntry) + { continue; + } int32 petSpellsId = -(int32)cInfo->PetSpellDataId; PetDefaultSpellsEntry petDefSpells; @@ -4187,29 +4389,39 @@ void SpellMgr::LoadPetDefaultSpells() { SpellEntry const* spellEntry = sSpellStore.LookupEntry(i); if (!spellEntry) + { continue; + } for (int k = 0; k < MAX_EFFECT_INDEX; ++k) { SpellEffectEntry const* spellEffect = spellEntry->GetSpellEffect(SpellEffectIndex(k)); if(!spellEffect) + { continue; + } if(spellEffect->Effect==SPELL_EFFECT_SUMMON || spellEffect->Effect==SPELL_EFFECT_SUMMON_PET) { uint32 creature_id = spellEffect->EffectMiscValue; CreatureInfo const* cInfo = sCreatureStorage.LookupEntry(creature_id); if (!cInfo) + { continue; + } // already loaded if (cInfo->PetSpellDataId) + { continue; + } // for creature without PetSpellDataId get default pet spells from creature_template int32 petSpellsId = cInfo->Entry; if (mPetDefaultSpellsMap.find(cInfo->Entry) != mPetDefaultSpellsMap.end()) + { continue; + } PetDefaultSpellsEntry petDefSpells; if (CreatureTemplateSpells const* templateSpells = sCreatureTemplateSpellsStorage.LookupEntry(cInfo->Entry)) @@ -4247,7 +4459,9 @@ bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } switch(spellEffect->Effect) { @@ -4266,9 +4480,13 @@ bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg) if (msg) { if (pl) + { ChatHandler(pl).PSendSysMessage("Craft spell %u not have create item entry.", spellInfo->Id); + } else + { sLog.outErrorDb("Craft spell %u not have create item entry.", spellInfo->Id); + } } return false; } @@ -4279,9 +4497,13 @@ bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg) if (msg) { if(pl) + { ChatHandler(pl).PSendSysMessage("Craft spell %u create item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellEffect->EffectItemType); + } else + { sLog.outErrorDb("Craft spell %u create item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellEffect->EffectItemType); + } } return false; } @@ -4297,9 +4519,13 @@ bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg) if (msg) { if(pl) + { ChatHandler(pl).PSendSysMessage("Spell %u learn to broken spell %u, and then...",spellInfo->Id,spellEffect->EffectTriggerSpell); + } else + { sLog.outErrorDb("Spell %u learn to invalid spell %u, and then...",spellInfo->Id,spellEffect->EffectTriggerSpell); + } } return false; } @@ -4320,9 +4546,13 @@ bool SpellMgr::IsSpellValid(SpellEntry const* spellInfo, Player* pl, bool msg) if(msg) { if(pl) + { ChatHandler(pl).PSendSysMessage("Craft spell %u requires reagent item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellReagents->Reagent[j]); + } else + { sLog.outErrorDb("Craft spell %u requires reagent item (Entry: %u) but item does not exist in item_template.",spellInfo->Id,spellReagents->Reagent[j]); + } } return false; } @@ -4387,17 +4617,29 @@ void SpellMgr::LoadSpellAreas() for (SpellAreaMap::const_iterator itr = sa_bounds.first; itr != sa_bounds.second; ++itr) { if (spellArea.spellId != itr->second.spellId) + { continue; + } if (spellArea.areaId != itr->second.areaId) + { continue; + } if (spellArea.questStart != itr->second.questStart) + { continue; + } if (spellArea.auraSpell != itr->second.auraSpell) + { continue; + } if ((spellArea.raceMask & itr->second.raceMask) == 0) + { continue; + } if (spellArea.gender != itr->second.gender) + { continue; + } // duplicate by requirements ok = false; @@ -4469,7 +4711,9 @@ void SpellMgr::LoadSpellAreas() SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(EFFECT_INDEX_0); if (!spellEffect) + { continue; + } switch (spellEffect->EffectApplyAuraName) { @@ -4531,11 +4775,15 @@ void SpellMgr::LoadSpellAreas() // for search by current zone/subzone at zone/subzone change if (spellArea.areaId) + { mSpellAreaForAreaMap.insert(SpellAreaForAreaMap::value_type(spellArea.areaId, sa)); + } // for search at aura apply if (spellArea.auraSpell) + { mSpellAreaForAuraMap.insert(SpellAreaForAuraMap::value_type(abs(spellArea.auraSpell), sa)); + } ++count; } @@ -4559,9 +4807,13 @@ SpellCastResult SpellMgr::GetSpellAllowedInLocationError(SpellEntry const* spell { for (uint32 i = 0; i < 6; ++i) if (groupEntry->AreaId[i] == zone_id || groupEntry->AreaId[i] == area_id) + { found = true; + } if (found || !groupEntry->nextGroup) + { break; + } // Try search in next group groupEntry = sAreaGroupStore.LookupEntry(groupEntry->nextGroup); } @@ -4723,7 +4975,9 @@ void SpellMgr::LoadSkillLineAbilityMap() bar.step(); SkillLineAbilityEntry const* SkillInfo = sSkillLineAbilityStore.LookupEntry(i); if (!SkillInfo) + { continue; + } mSkillLineAbilityMap.insert(SkillLineAbilityMap::value_type(SkillInfo->spellId, SkillInfo)); ++count; @@ -4745,11 +4999,15 @@ void SpellMgr::LoadSkillRaceClassInfoMap() bar.step(); SkillRaceClassInfoEntry const* skillRCInfo = sSkillRaceClassInfoStore.LookupEntry(i); if (!skillRCInfo) + { continue; + } // not all skills really listed in ability skills list if (!sSkillLineStore.LookupEntry(skillRCInfo->skillId)) + { continue; + } mSkillRaceClassInfoMap.insert(SkillRaceClassInfoMap::value_type(skillRCInfo->skillId, skillRCInfo)); @@ -4947,53 +5205,75 @@ void SpellMgr::CheckUsedSpells(char const* table) { SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellId); if (!spellEntry) + { continue; + } SpellClassOptionsEntry const* classOptions = spellEntry->GetSpellClassOptions(); if(family >=0 && classOptions && classOptions->SpellFamilyName != uint32(family)) + { continue; + } if (familyMaskA != UI64LIT(0xFFFFFFFFFFFFFFFF) || familyMaskB != 0xFFFFFFFF) { if (familyMaskA == UI64LIT(0x0000000000000000) && familyMaskB == 0x00000000) { if (classOptions && classOptions->SpellFamilyFlags) + { continue; + } } else { if (!spellEntry->IsFitToFamilyMask(familyMaskA, familyMaskB)) + { continue; + } } } if (spellIcon >= 0 && spellEntry->GetSpellIconID() != uint32(spellIcon)) + { continue; + } if (spellVisual >= 0 && spellEntry->GetSpellVisual() != uint32(spellVisual)) + { continue; + } if(category >= 0 && spellEntry->GetCategory() != uint32(category)) + { continue; + } if (effectIdx >= 0) { SpellEffectEntry const* spellEffect = spellEntry->GetSpellEffect(SpellEffectIndex(effectIdx)); if(effectType >=0 && spellEffect && spellEffect->Effect != uint32(effectType)) + { continue; + } if(auraType >=0 && spellEffect && spellEffect->EffectApplyAuraName != uint32(auraType)) + { continue; + } } else { if (effectType >= 0 && !IsSpellHaveEffect(spellEntry, SpellEffects(effectType))) + { continue; + } if (auraType >= 0 && !IsSpellHaveAura(spellEntry, AuraType(auraType))) + { continue; + } } found = true; @@ -5361,10 +5641,14 @@ void SpellArea::ApplyOrRemoveSpellIfCan(Player* player, uint32 newZone, uint32 n if (IsFitToRequirements(player, newZone, newArea)) { if (autocast && !player->HasAura(spellId)) + { player->CastSpell(player, spellId, true); + } } else if (!onlyApply && player->HasAura(spellId)) + { player->RemoveAurasDueToSpell(spellId); + } } SpellEntry const* GetSpellEntryByDifficulty(uint32 id, Difficulty difficulty, bool isRaid) @@ -5400,16 +5684,22 @@ int32 GetMasteryCoefficient(SpellEntry const * spellProto) { SpellEffectEntry const * effectEntry = spellProto->GetSpellEffect(SpellEffectIndex(j)); if (!effectEntry) + { continue; + } // mastery scaling coef is stored in dummy aura, except 77215 (Potent Afflictions, zero effect) // and 76808 (Executioner, not stored at all) int32 bp = effectEntry->CalculateSimpleValue(); if (spellProto->Id == 76808) + { bp = 250; + } if (!bp) + { continue; + } coef = bp; break; diff --git a/src/game/Object/SpellMgr.h b/src/game/Object/SpellMgr.h index 9f287687a..66021d24b 100644 --- a/src/game/Object/SpellMgr.h +++ b/src/game/Object/SpellMgr.h @@ -371,7 +371,9 @@ inline bool IsSpellWithCasterSourceTargetsOnly(SpellEntry const* spellInfo) { SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!effectEntry) + { continue; + } uint32 targetA = effectEntry->EffectImplicitTargetA; if(targetA && !IsCasterSourceTarget(targetA)) @@ -504,7 +506,9 @@ inline bool HasAreaAuraEffect(SpellEntry const* spellInfo) { SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!effectEntry) + { continue; + } if (IsAreaAuraEffect(effectEntry->Effect)) { return true; @@ -519,7 +523,9 @@ inline bool HasAuraWithTriggerEffect(SpellEntry const* spellInfo) { SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!effectEntry) + { continue; + } switch(effectEntry->Effect) { @@ -539,7 +545,9 @@ inline bool IsOnlySelfTargeting(SpellEntry const* spellInfo) { SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!effectEntry) + { continue; + } switch (effectEntry->EffectImplicitTargetA) { @@ -626,19 +634,27 @@ inline uint32 GetSpellMechanicMask(SpellEntry const* spellInfo, uint32 effectMas uint32 mask = 0; if (uint32 mech = spellInfo->GetMechanic()) + { mask |= 1 << (mech - 1); + } for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (!(effectMask & (1 << i))) + { continue; + } SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if (!effectEntry) + { continue; + } if (effectEntry->EffectMechanic) + { mask |= 1 << (effectEntry->EffectMechanic - 1); + } } return mask; @@ -649,13 +665,17 @@ inline uint32 GetAllSpellMechanicMask(SpellEntry const* spellInfo) SpellCategoriesEntry const* spellCategory = spellInfo->GetSpellCategories(); uint32 mask = 0; if (spellCategory && spellCategory->Mechanic) + { mask |= 1 << (spellCategory->Mechanic - 1); + } for (int i=0; i< MAX_EFFECT_INDEX; ++i) { SpellEffectEntry const* effectEntry = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if (effectEntry && effectEntry->EffectMechanic) + { mask |= 1 << (effectEntry->EffectMechanic-1); + } } return mask; diff --git a/src/game/Object/StatSystem.cpp b/src/game/Object/StatSystem.cpp index dcf42a4b8..871fc3ffd 100644 --- a/src/game/Object/StatSystem.cpp +++ b/src/game/Object/StatSystem.cpp @@ -53,7 +53,9 @@ bool Player::UpdateStats(Stats stat) { Pet* pet = GetPet(); if (pet) + { pet->UpdateStats(stat); + } } switch (stat) @@ -90,12 +92,16 @@ bool Player::UpdateStats(Stats stat) AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT); for (AuraList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i) if (Stats((*i)->GetMiscBValue()) == stat) + { mask |= (*i)->GetMiscValue(); + } if (mask) { for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating) if (mask & (1 << rating)) + { ApplyRatingMod(CombatRating(rating), 0, true); + } } return true; } @@ -174,7 +180,9 @@ void Player::UpdateResistances(uint32 school) Pet* pet = GetPet(); if (pet) + { pet->UpdateResistances(school); + } } else { @@ -197,7 +205,9 @@ void Player::UpdateArmor() { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) + { value += int32(GetStat(Stats((*i)->GetMiscBValue())) * mod->m_amount / 100.0f); + } } value *= GetModifierValue(unitMod, TOTAL_PCT); @@ -206,7 +216,9 @@ void Player::UpdateArmor() Pet* pet = GetPet(); if (pet) + { pet->UpdateArmor(); + } UpdateAttackPowerAndDamage(); // armor dependent auras update for SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR } @@ -220,7 +232,9 @@ float Player::GetHealthBonusFromStamina() float baseStam = stamina < 20 ? stamina : 20; float moreStam = stamina - baseStam; if (moreStam < 0.0f) + { moreStam = 0.0f; + } return baseStam + moreStam * hpBase->ratio; } @@ -321,7 +335,9 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) { if (SpellShapeshiftFormEntry const * entry = sSpellShapeshiftFormStore.LookupEntry(uint32(GetShapeshiftForm()))) if (entry->flags1 & 0x20) + { val2 += std::max(GetStat(STAT_AGILITY) - 10.0f, 0.0f) * chrEntry->apPerStr; + } } } @@ -352,7 +368,9 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) Pet* pet = GetPet(); // update pet's AP if (pet) + { pet->UpdateAttackPowerAndDamage(); + } } else { @@ -673,14 +691,20 @@ void Player::UpdateExpertise(WeaponAttackType attack) { // item neutral spell if((*itr)->GetSpellProto()->GetEquippedItemClass() == -1) + { expertise += (*itr)->GetModifier()->m_amount; + } // item dependent spell else if (weapon && weapon->IsFitToSpellRequirements((*itr)->GetSpellProto())) + { expertise += (*itr)->GetModifier()->m_amount; + } } if (expertise < 0) + { expertise = 0; + } switch (attack) { @@ -758,24 +782,32 @@ void Player::UpdateMasteryAuras() { SpellAuraHolder* holder = GetSpellAuraHolder(masterySpells->at(i)); if (!holder) + { continue; + } SpellEntry const* spellEntry = holder->GetSpellProto(); // calculate mastery scaling coef int32 masteryCoef = GetMasteryCoefficient(spellEntry); if (!masteryCoef) + { continue; + } // update aura modifiers for (uint32 j = 0; j < MAX_EFFECT_INDEX; ++j) { Aura* aura = holder->GetAuraByEffectIndex(SpellEffectIndex(j)); if (!aura) + { continue; + } if (spellEntry->CalculateSimpleValue(SpellEffectIndex(j))) + { continue; + } aura->ApplyModifier(false, false); aura->GetModifier()->m_amount = int32(masteryValue * masteryCoef / 100.0f); @@ -952,13 +984,17 @@ bool Pet::UpdateStats(Stats stat) if (stat == STAT_STAMINA) { if (owner) + { value += float(owner->GetStat(stat)) * 0.3f; + } } // warlock's and mage's pets gain 30% of owner's intellect else if (stat == STAT_INTELLECT && getPetType() == SUMMON_PET) { if (owner && (owner->getClass() == CLASS_WARLOCK || owner->getClass() == CLASS_MAGE)) + { value += float(owner->GetStat(stat)) * 0.3f; + } } SetStat(stat, int32(value)); @@ -1006,7 +1042,9 @@ void Pet::UpdateResistances(uint32 school) Unit* owner = GetOwner(); // hunter and warlock pets gain 40% of owner's resistance if (owner && (getPetType() == HUNTER_PET || (getPetType() == SUMMON_PET && owner->getClass() == CLASS_WARLOCK))) + { value += float(owner->GetResistance(SpellSchools(school))) * 0.4f; + } SetResistance(SpellSchools(school), int32(value)); } @@ -1025,7 +1063,9 @@ void Pet::UpdateArmor() Unit* owner = GetOwner(); // hunter and warlock pets gain 35% of owner's armor value if (owner && (getPetType() == HUNTER_PET || (getPetType() == SUMMON_PET && owner->getClass() == CLASS_WARLOCK))) + { bonus_armor = 0.35f * float(owner->GetArmor()); + } value = GetModifierValue(unitMod, BASE_VALUE); value *= GetModifierValue(unitMod, BASE_PCT); @@ -1100,7 +1140,9 @@ void Pet::UpdateAttackPowerAndDamage(bool ranged) int32 shadow = int32(owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_SHADOW)) - owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_SHADOW); int32 maximum = (fire > shadow) ? fire : shadow; if (maximum < 0) + { maximum = 0; + } SetBonusDamage(int32(maximum * 0.15f)); bonusAP = maximum * 0.57f; } @@ -1109,7 +1151,9 @@ void Pet::UpdateAttackPowerAndDamage(bool ranged) { int32 frost = int32(owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + SPELL_SCHOOL_FROST)) - owner->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + SPELL_SCHOOL_FROST); if (frost < 0) + { frost = 0; + } SetBonusDamage(int32(frost * 0.4f)); } } diff --git a/src/game/Object/TemporarySummon.cpp b/src/game/Object/TemporarySummon.cpp index 03d3340b9..6cb7329f8 100644 --- a/src/game/Object/TemporarySummon.cpp +++ b/src/game/Object/TemporarySummon.cpp @@ -208,7 +208,9 @@ void TemporarySummon::Update(uint32 update_diff, uint32 diff) Unit* owner = GetCharmerOrOwner(); uint32 const& spellId = GetUInt32Value(UNIT_CREATED_BY_SPELL); if (!owner || !spellId || !owner->HasAura(spellId)) + { UnSummon(); + } } break; @@ -248,21 +250,29 @@ void TemporarySummon::UnSummon() CombatStop(); if (m_linkedToOwnerAura & TEMPSUMMON_LINKED_AURA_REMOVE_OWNER) + { RemoveAuraFromOwner(); + } if (GetSummonerGuid().IsCreatureOrVehicle()) { if (Creature* sum = GetMap()->GetCreature(GetSummonerGuid())) if (sum->AI()) + { sum->AI()->SummonedCreatureDespawn(this); + } } else if (GetSummonerGuid().IsPlayer()) // if player that summoned this creature was MCing it, uncharm if (Player* player = GetMap()->GetPlayer(GetSummonerGuid())) if (player->GetMover() == this) + { player->Uncharm(); + } if (AI()) + { AI()->SummonedCreatureDespawn(this); + } AddObjectToRemoveList(); } diff --git a/src/game/Object/Totem.cpp b/src/game/Object/Totem.cpp index 32bbdacac..77d31e58e 100644 --- a/src/game/Object/Totem.cpp +++ b/src/game/Object/Totem.cpp @@ -57,14 +57,18 @@ bool Totem::Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const* if (owner->GetTypeId() == TYPEID_PLAYER) { if (uint32 modelid_race = sObjectMgr.GetModelForRace(GetNativeDisplayId(), owner->getRaceMask())) + { SetDisplayId(modelid_race); + } } cPos.SelectFinalPoint(this); // totem must be at same Z in case swimming caster and etc. if (fabs(cPos.m_pos.z - owner->GetPositionZ()) > 5.0f) + { cPos.m_pos.z = owner->GetPositionZ(); + } if (!cPos.Relocate(this)) { @@ -75,7 +79,9 @@ bool Totem::Create(uint32 guidlow, CreatureCreatePos& cPos, CreatureInfo const* // Only works if you create the object in it, not if it is moves to that map. // Normally non-players do not teleport to other maps. if (InstanceData* iData = GetMap()->GetInstanceData()) + { iData->OnCreatureCreate(this); + } LoadCreatureAddon(false); @@ -97,7 +103,9 @@ void Totem::Update(uint32 update_diff, uint32 time) return; } else + { m_duration -= update_diff; + } Creature::Update(update_diff, time); } @@ -108,7 +116,9 @@ void Totem::Summon(Unit* owner) owner->GetMap()->Add((Creature*)this); if (owner->GetTypeId() == TYPEID_UNIT && ((Creature*)owner)->AI()) + { ((Creature*)owner)->AI()->JustSummoned((Creature*)this); + } #ifdef ENABLE_ELUNA sEluna->OnSummoned(this, owner); #endif /* ENABLE_ELUNA */ @@ -153,18 +163,24 @@ void Totem::UnSummon() { Player* Target = itr->getSource(); if (Target && pGroup->SameSubGroup((Player*)owner, Target)) + { Target->RemoveAurasDueToSpell(GetSpell()); + } } } } if (owner->GetTypeId() == TYPEID_UNIT && ((Creature*)owner)->AI()) + { ((Creature*)owner)->AI()->SummonedCreatureDespawn((Creature*)this); + } } // any totem unsummon look like as totem kill, req. for proper animation if (IsAlive()) + { SetDeathState(DEAD); + } AddObjectToRemoveList(); } @@ -195,10 +211,14 @@ void Totem::SetTypeBySummonSpell(SpellEntry const* spellProto) { // If spell have cast time -> so its active totem if (GetSpellCastTime(totemSpell)) + { m_type = TOTEM_ACTIVE; + } } if (spellProto->Id == 2056) + { m_type = TOTEM_STATUE; // Jewelery statue + } } bool Totem::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index, bool castOnSelf) const diff --git a/src/game/Object/TotemAI.cpp b/src/game/Object/TotemAI.cpp index 9e53f322d..34000488c 100644 --- a/src/game/Object/TotemAI.cpp +++ b/src/game/Object/TotemAI.cpp @@ -109,7 +109,9 @@ TotemAI::UpdateAI(const uint32 /*diff*/) m_creature->CastSpell(victim, getTotem().GetSpell(), false); } else + { i_victimGuid.Clear(); + } } bool diff --git a/src/game/Object/Unit.cpp b/src/game/Object/Unit.cpp index 472e0dc79..e905aad07 100644 --- a/src/game/Object/Unit.cpp +++ b/src/game/Object/Unit.cpp @@ -99,7 +99,9 @@ void MovementInfo::Read(ByteBuffer& data, uint16 opcode) { MovementStatusElements element = sequence[i]; if (element == MSEEnd) + { break; + } if (element >= MSEGuidBit0 && element <= MSEGuidBit7) { @@ -116,21 +118,27 @@ void MovementInfo::Read(ByteBuffer& data, uint16 opcode) if (element >= MSETransportGuidBit0 && element <= MSETransportGuidBit7) { if (hasTransportData) + { t_guid[element - MSETransportGuidBit0] = data.ReadBit(); + } continue; } if (element >= MSEGuidByte0 && element <= MSEGuidByte7) { if (guid[element - MSEGuidByte0]) + { guid[element - MSEGuidByte0] ^= data.ReadUInt8(); + } continue; } if (element >= MSETransportGuidByte0 && element <= MSETransportGuidByte7) { if (hasTransportData && t_guid[element - MSETransportGuidByte0]) + { t_guid[element - MSETransportGuidByte0] ^= data.ReadUInt8(); + } continue; } @@ -138,11 +146,15 @@ void MovementInfo::Read(ByteBuffer& data, uint16 opcode) { case MSEFlags: if (hasMovementFlags) + { moveFlags = data.ReadBits(30); + } break; case MSEFlags2: if (hasMovementFlags2) + { moveFlags2 = data.ReadBits(13); + } break; case MSEUnknownBit: data.ReadBit(); @@ -155,7 +167,9 @@ void MovementInfo::Read(ByteBuffer& data, uint16 opcode) // break; case MSETimestamp: if (si.hasTimeStamp) + { data >> time; + } break; case MSEHasTimestamp: si.hasTimeStamp = !data.ReadBit(); @@ -177,18 +191,24 @@ void MovementInfo::Read(ByteBuffer& data, uint16 opcode) break; case MSEHasFallDirection: if (si.hasFallData) + { si.hasFallDirection = data.ReadBit(); + } break; case MSEHasTransportData: hasTransportData = data.ReadBit(); break; case MSEHasTransportTime2: if (hasTransportData) + { si.hasTransportTime2 = data.ReadBit(); + } break; case MSEHasTransportTime3: if (hasTransportData) + { si.hasTransportTime3 = data.ReadBit(); + } break; case MSEHasSpline: si.hasSpline = data.ReadBit(); @@ -207,67 +227,99 @@ void MovementInfo::Read(ByteBuffer& data, uint16 opcode) break; case MSEPositionO: if (si.hasOrientation) + { data >> pos.o; + } break; case MSEPitch: if (si.hasPitch) + { data >> s_pitch; + } break;; case MSEFallTime: if (si.hasFallData) + { data >> fallTime; + } break; case MSESplineElevation: if (si.hasSplineElevation) + { data >> splineElevation; + } break; case MSEFallHorizontalSpeed: if (si.hasFallData && si.hasFallDirection) + { data >> jump.xyspeed; + } break; case MSEFallVerticalSpeed: if (si.hasFallData) + { data >> jump.velocity; + } break; case MSEFallCosAngle: if (si.hasFallData && si.hasFallDirection) + { data >> jump.cosAngle; + } break; case MSEFallSinAngle: if (si.hasFallData && si.hasFallDirection) + { data >> jump.sinAngle; + } break; case MSETransportSeat: if (hasTransportData) + { data >> t_seat; + } break; case MSETransportPositionO: if (hasTransportData) + { data >> t_pos.o; + } break; case MSETransportPositionX: if (hasTransportData) + { data >> t_pos.x; + } break; case MSETransportPositionY: if (hasTransportData) + { data >> t_pos.y; + } break; case MSETransportPositionZ: if (hasTransportData) + { data >> t_pos.z; + } break; case MSETransportTime: if (hasTransportData) + { data >> t_time; + } break; case MSETransportTime2: if (hasTransportData && si.hasTransportTime2) + { data >> t_time2; + } break; case MSETransportTime3: if (hasTransportData && si.hasTransportTime3) + { data >> fallTime; + } break; case MSEMovementCounter: //for (int i = 0; i < counterCount; i++) @@ -307,7 +359,9 @@ void MovementInfo::Write(ByteBuffer& data, uint16 opcode) const MovementStatusElements element = sequence[i]; if (element == MSEEnd) + { break; + } if (element >= MSEGuidBit0 && element <= MSEGuidBit7) { @@ -318,21 +372,27 @@ void MovementInfo::Write(ByteBuffer& data, uint16 opcode) const if (element >= MSETransportGuidBit0 && element <= MSETransportGuidBit7) { if (hasTransportData) + { data.WriteBit(t_guid[element - MSETransportGuidBit0]); + } continue; } if (element >= MSEGuidByte0 && element <= MSEGuidByte7) { if (guid[element - MSEGuidByte0]) + { data << uint8((guid[element - MSEGuidByte0] ^ 1)); + } continue; } if (element >= MSETransportGuidByte0 && element <= MSETransportGuidByte7) { if (hasTransportData && t_guid[element - MSETransportGuidByte0]) + { data << uint8((t_guid[element - MSETransportGuidByte0] ^ 1)); + } continue; } @@ -346,15 +406,21 @@ void MovementInfo::Write(ByteBuffer& data, uint16 opcode) const break; case MSEFlags: if (moveFlags) + { data.WriteBits(moveFlags, 30); + } break; case MSEFlags2: if (moveFlags2) + { data.WriteBits(moveFlags2, 13); + } break; case MSETimestamp: if (si.hasTimeStamp) + { data << uint32(time); + } break; case MSEHasPitch: data.WriteBit(!si.hasPitch); @@ -376,18 +442,24 @@ void MovementInfo::Write(ByteBuffer& data, uint16 opcode) const break; case MSEHasFallDirection: if (si.hasFallData) + { data.WriteBit(si.hasFallDirection); + } break; case MSEHasTransportData: data.WriteBit(hasTransportData); break; case MSEHasTransportTime2: if (hasTransportData) + { data.WriteBit(si.hasTransportTime2); + } break; case MSEHasTransportTime3: if (hasTransportData) + { data.WriteBit(si.hasTransportTime3); + } break; case MSEHasSpline: data.WriteBit(si.hasSpline); @@ -406,70 +478,102 @@ void MovementInfo::Write(ByteBuffer& data, uint16 opcode) const break; case MSEPositionO: if (si.hasOrientation) + { data << float(NormalizeOrientation(pos.o)); + } break; case MSEPitch: if (si.hasPitch) + { data << float(s_pitch); + } break; case MSEHasOrientation: data.WriteBit(!si.hasOrientation); break; case MSEFallTime: if (si.hasFallData) + { data << uint32(fallTime); + } break; case MSESplineElevation: if (si.hasSplineElevation) + { data << float(splineElevation); + } break; case MSEFallHorizontalSpeed: if (si.hasFallData && si.hasFallDirection) + { data << float(jump.xyspeed); + } break; case MSEFallVerticalSpeed: if (si.hasFallData) + { data << float(jump.velocity); + } break; case MSEFallCosAngle: if (si.hasFallData && si.hasFallDirection) + { data << float(jump.cosAngle); + } break; case MSEFallSinAngle: if (si.hasFallData && si.hasFallDirection) + { data << float(jump.sinAngle); + } break; case MSETransportSeat: if (hasTransportData) + { data << int8(t_seat); + } break; case MSETransportPositionO: if (hasTransportData) + { data << float(NormalizeOrientation(t_pos.o)); + } break; case MSETransportPositionX: if (hasTransportData) + { data << float(t_pos.x); + } break; case MSETransportPositionY: if (hasTransportData) + { data << float(t_pos.y); + } break; case MSETransportPositionZ: if (hasTransportData) + { data << float(t_pos.z); + } break; case MSETransportTime: if (hasTransportData) + { data << uint32(t_time); + } break; case MSETransportTime2: if (hasTransportData && si.hasTransportTime2) + { data << uint32(t_time2); + } break; case MSETransportTime3: if (hasTransportData && si.hasTransportTime3) + { data << uint32(fallTime); + } break; case MSEMovementCounter: data << uint32(0); @@ -479,7 +583,9 @@ void MovementInfo::Write(ByteBuffer& data, uint16 opcode) const break;*/ case MSEUnknownArray: for (std::list::const_iterator itr = unkArray.begin(); itr != unkArray.end(); ++itr) + { data << uint32(*itr); + } break; //case MSEUnkInt32: // if (si.hasUnkInt32) @@ -669,7 +775,9 @@ void Unit::Update(uint32 update_diff, uint32 p_time) if (CanHaveThreatList()) + { GetThreatManager().UpdateForClient(update_diff); + } // update combat timer only for players and pets if (IsInCombat() && GetCharmerOrOwnerPlayerOrPlayerItself()) @@ -705,11 +813,15 @@ void Unit::Update(uint32 update_diff, uint32 p_time) { // Initialize vehicle if not done if (IsAlive() && !m_vehicleInfo->IsInitialized()) + { m_vehicleInfo->Initialize(); + } // Update passenger positions if we are the first vehicle if (!IsBoarded()) + { m_vehicleInfo->Update(update_diff); + } } // update abilities available only for fraction of time @@ -816,7 +928,9 @@ bool Unit::haveOffhandWeapon() const /*ItemEntry const* itemInfo = sItemStore.LookupEntry(ItemId); if (itemInfo && itemInfo->Class == ITEM_CLASS_WEAPON) - return true;*/ + { + return true; + }*/ return false; } @@ -934,7 +1048,9 @@ void Unit::DealDamageMods(Unit* pVictim, uint32& damage, uint32* absorb) if (!IsAllowedDamageInArea(pVictim)) { if (absorb) + { *absorb += damage; + } damage = 0; } @@ -963,18 +1079,24 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa if (damagetype != DOT) { if (damagetype != SELF_DAMAGE_ROGUE_FALL) + { RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); + } RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED)) + { pVictim->SetStandState(UNIT_STAND_STATE_STAND); + } } if (!damage) { // Rage from physical damage received . if (cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->GetPowerType() == POWER_RAGE)) + { ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false); + } return 0; } @@ -994,9 +1116,13 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa case BASE_ATTACK: { if (cleanDamage->hitOutCome == MELEE_HIT_CRIT) + { weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType) / 1000.0f * 7); + } else + { weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType) / 1000.0f * 3.5f); + } ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true); @@ -1005,9 +1131,13 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa case OFF_ATTACK: { if (cleanDamage->hitOutCome == MELEE_HIT_CRIT) + { weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType) / 1000.0f * 3.5f); + } else + { weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType) / 1000.0f * 1.75f); + } ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true); @@ -1040,7 +1170,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa for (AuraList::const_iterator itr = vShareDamageAuras.begin(); itr != vShareDamageAuras.end(); ++itr) { if (!spellProto) + { break; + } SpellEffectEntry const* spellEffect = spellProto->GetSpellEffect(EFFECT_INDEX_0); @@ -1067,7 +1199,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa { // prevent kill only if killed in duel and killed by opponent or opponent controlled creature if (((Player*)pVictim)->duel->opponent == this || ((Player*)pVictim)->duel->opponent->GetObjectGuid() == GetOwnerGuid()) + { damage = health - 1; + } duel_hasEnded = true; } @@ -1079,7 +1213,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa pVictim->SetInCombatWith(this); if (Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself()) + { SetContestedPvP(attackedPlayer); + } } if (GetTypeId() == TYPEID_PLAYER && this != pVictim) @@ -1101,7 +1237,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa } if (pVictim->GetTypeId() == TYPEID_PLAYER) + { ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage); + } if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->IsPet() && !((Creature*)pVictim)->HasLootRecipient()) { @@ -1176,7 +1314,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa player_tap->SendDirectMessage(&data); } else if (GetTypeId() == TYPEID_UNIT && this != pVictim) + { ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0); + } // Reward player, his pets, and group/raid members if (player_tap != pVictim) @@ -1235,7 +1375,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa // Used by Eluna #ifdef ENABLE_ELUNA if (Player* killed = pVictim->ToPlayer()) + { sEluna->OnPlayerKilledByCreature(killer, killed); + } #endif /* ENABLE_ELUNA */ } @@ -1259,11 +1401,17 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa // achievement stuff playerVictim->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health); if (player_tap) + { player_tap->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL, 1, 0, pVictim); + } if (GetTypeId() == TYPEID_UNIT) + { playerVictim->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry()); + } else if (GetTypeId() == TYPEID_PLAYER && pVictim != this) + { playerVictim->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, playerVictim->GetTeam()); + } // 10% durability loss on death // only if not player and not controlled by player pet. And not at BG @@ -1323,7 +1471,9 @@ uint32 Unit::DealDamage(Unit* pVictim, uint32 damage, CleanDamage const* cleanDa DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageAlive"); if (pVictim->GetTypeId() == TYPEID_PLAYER) + { ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage); + } pVictim->ModifyHealth(- (int32)damage); @@ -1532,7 +1682,9 @@ void Unit::JustKilledCreature(Creature* victim, Player* responsiblePlayer) if (responsiblePlayer) // killedby Player, inform BG if (BattleGround* bg = responsiblePlayer->GetBattleGround()) + { bg->HandleKillUnit(victim, responsiblePlayer); + } // Used by Eluna #ifdef ENABLE_ELUNA @@ -1592,7 +1744,9 @@ void Unit::JustKilledCreature(Creature* victim, Player* responsiblePlayer) victim->SetDeathState(JUST_DIED); // if !spiritOfRedemtionTalentReady always true for unit if (isPet) - { return; } // Pets might have been unsummoned at this place, do not handle them further! + { + return; // Pets might have been unsummoned at this place, do not handle them further! + } /* ******************************** Prepare loot if can ************************************ */ victim->DeleteThreatList(); @@ -1687,7 +1841,9 @@ void Unit::CastSpell(Unit* Victim, SpellEntry const* spellInfo, bool triggered, } if (spellInfo->GetTargets() & TARGET_FLAG_SOURCE_LOCATION) if (WorldObject* caster = spell->GetCastingObject()) + { targets.setSource(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ()); + } spell->m_CastItem = castItem; spell->SpellStart(&targets, triggeredByAura); @@ -1700,7 +1856,9 @@ void Unit::CastCustomSpell(Unit* Victim, uint32 spellId, int32 const* bp0, int32 if (!spellInfo) { if (triggeredByAura) + { sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + } else { sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); @@ -1716,9 +1874,13 @@ void Unit::CastCustomSpell(Unit* Victim, SpellEntry const* spellInfo, int32 cons if (!spellInfo) { if (triggeredByAura) + { sLog.outError("CastCustomSpell: unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + } else + { sLog.outError("CastCustomSpell: unknown spell by caster: %s", GetGuidStr().c_str()); + } return; } @@ -1779,9 +1941,13 @@ void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, if (!spellInfo) { if (triggeredByAura) + { sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + } else + { sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); + } return; } @@ -1794,9 +1960,13 @@ void Unit::CastSpell(float x, float y, float z, SpellEntry const* spellInfo, boo if (!spellInfo) { if (triggeredByAura) + { sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + } else + { sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s", GetGuidStr().c_str()); + } return; } @@ -2058,7 +2228,9 @@ void Unit::CalculateMeleeDamage(Unit* pVictim, CalcDamageInfo* damageInfo, Weapo if (damageInfo->attackType == RANGED_ATTACK) { if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL; - if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS; + { + if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS; + } } switch (damageInfo->hitOutCome) @@ -2103,12 +2275,18 @@ void Unit::CalculateMeleeDamage(Unit* pVictim, CalcDamageInfo* damageInfo, Weapo int32 mod = 0; // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE if (damageInfo->attackType == RANGED_ATTACK) + { mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); + } else + { mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); + } if (mod != 0) + { damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod) / 100.0f)); + } // Resilience - reduce crit damage uint32 reduction_affected_damage = CalcNotIgnoreDamageReduction(damageInfo->damage, damageInfo->damageSchoolMask); @@ -2140,7 +2318,9 @@ void Unit::CalculateMeleeDamage(Unit* pVictim, CalcDamageInfo* damageInfo, Weapo // Target has a chance to double the blocked amount if it has SPELL_AURA_MOD_BLOCK_CRIT_CHANCE if (roll_chance_i(pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE))) + { damageInfo->blocked_amount *= 2; + } if (damageInfo->blocked_amount >= damageInfo->damage) { @@ -2149,7 +2329,9 @@ void Unit::CalculateMeleeDamage(Unit* pVictim, CalcDamageInfo* damageInfo, Weapo damageInfo->procEx |= PROC_EX_FULL_BLOCK; } else - { damageInfo->procEx |= PROC_EX_NORMAL_HIT; } // Partial blocks can still cause attacker procs + { + damageInfo->procEx |= PROC_EX_NORMAL_HIT; // Partial blocks can still cause attacker procs + } damageInfo->damage -= damageInfo->blocked_amount; damageInfo->cleanDamage += damageInfo->blocked_amount; @@ -2468,14 +2650,18 @@ uint32 Unit::CalcNotIgnoreAbsorbDamage(uint32 damage, SpellSchoolMask damageScho Unit::AuraList const& ignoreAbsorbSchool = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL); for (Unit::AuraList::const_iterator i = ignoreAbsorbSchool.begin(); i != ignoreAbsorbSchool.end(); ++i) if ((*i)->GetMiscValue() & damageSchoolMask) + { absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount) / 100.0f; + } if (spellInfo) { Unit::AuraList const& ignoreAbsorbForSpell = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL); for (Unit::AuraList::const_iterator citr = ignoreAbsorbForSpell.begin(); citr != ignoreAbsorbForSpell.end(); ++citr) if ((*citr)->isAffectedOnSpell(spellInfo)) + { absorb_affected_rate *= (100.0f - (*citr)->GetModifier()->m_amount) / 100.0f; + } } return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage); @@ -2487,7 +2673,9 @@ uint32 Unit::CalcNotIgnoreDamageReduction(uint32 damage, SpellSchoolMask damageS Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL); for (Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i) if ((*i)->GetMiscValue() & damageSchoolMask) + { absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount) / 100.0f; + } return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage); } @@ -2505,7 +2693,9 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage) { float maxArmorPen = 400 + 85 * pVictim->getLevel(); if (getLevel() > 59) + { maxArmorPen += 4.5f * 85 * (pVictim->getLevel() - 59); + } // Cap ignored armor to this value maxArmorPen = std::min(((armor + maxArmorPen) / 3), armor); // Also, armor penetration is limited to 100% since 3.1.2, before greater values did @@ -2521,7 +2711,9 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage) float levelModifier = (float)getLevel(); if (levelModifier > 59) + { levelModifier = levelModifier + (4.5f * (levelModifier - 59)); + } float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40); tmpvalue = tmpvalue / (1.0f + tmpvalue); @@ -2556,7 +2748,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM tmpvalue2 += (float)pCaster->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask); if (pCaster->GetTypeId() == TYPEID_PLAYER) + { tmpvalue2 -= (float)((Player*)pCaster)->GetSpellPenetrationItemMod(); + } tmpvalue2 *= (float)(0.15f / getLevel()); if (tmpvalue2 < 0.0f) @@ -2620,7 +2814,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM // only work with proper school mask damage Modifier* i_mod = (*i)->GetModifier(); if (!(i_mod->m_miscvalue & schoolMask)) + { continue; + } SpellEntry const* i_spellProto = (*i)->GetSpellProto(); SpellClassOptionsEntry const* adsClassOptions = i_spellProto->GetSpellClassOptions(); @@ -2664,7 +2860,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { Modifier* mod = (*i)->GetModifier(); if (!(mod->m_miscvalue & schoolMask)) + { continue; + } SpellEntry const* spellProto = (*i)->GetSpellProto(); @@ -2691,7 +2889,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { // reduces all damage taken while stun, fear or silence if (unitflag & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED)) + { RemainingDamage -= RemainingDamage * currentAbsorb / 100; + } continue; } // Nerves of Steel @@ -2699,7 +2899,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { // while affected by Stun and Fear if (unitflag & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING)) + { RemainingDamage -= RemainingDamage * currentAbsorb / 100; + } continue; } // Spell Deflection @@ -2715,9 +2917,13 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM if (spellProto->Id == 41475 && canReflect) { if (RemainingDamage < currentAbsorb) + { reflectDamage = RemainingDamage / 2; + } else + { reflectDamage = currentAbsorb / 2; + } reflectSpell = 33619; reflectTriggeredBy = *i; reflectTriggeredBy->SetInUse(true); // lock aura from final deletion until processing @@ -2729,7 +2935,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM // Max absorb stored in 1 dummy effect int32 max_absorb = spellProto->CalculateSimpleValue(EFFECT_INDEX_1); if (max_absorb < currentAbsorb) + { currentAbsorb = max_absorb; + } break; } break; @@ -2741,7 +2949,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { // reduces all damage taken while Stunned and in Cat Form if (GetShapeshiftForm() == FORM_CAT && (unitflag & UNIT_FLAG_STUNNED)) + { RemainingDamage -= RemainingDamage * currentAbsorb / 100; + } continue; } // Moonkin Form passive @@ -2749,7 +2959,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { // reduces all damage taken while Stunned if (unitflag & UNIT_FLAG_STUNNED) + { RemainingDamage -= RemainingDamage * currentAbsorb / 100; + } continue; } break; @@ -2786,10 +2998,14 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000001)) && canReflect) { if (pCaster == this) + { break; + } Unit* caster = (*i)->GetCaster(); if (!caster) + { break; + } AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY); for (AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k) { @@ -2799,9 +3015,13 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM case 5064: // Rank 2 { if (RemainingDamage >= currentAbsorb) + { reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb / 100; + } else + { reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage / 100; + } reflectSpell = 33619; reflectTriggeredBy = *i; reflectTriggeredBy->SetInUse(true);// lock aura from final deletion until processing @@ -2820,7 +3040,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { // reduces all damage taken while stun, fear or silence if (unitflag & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED)) + { RemainingDamage -= RemainingDamage * currentAbsorb / 100; + } continue; } break; @@ -2855,11 +3077,15 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM { Unit* caster = (*i)->GetCaster(); if (!caster) + { continue; + } int32 absorbed = RemainingDamage * currentAbsorb / 100; int32 canabsorb = caster->GetHealth(); if (canabsorb < absorbed) + { absorbed = canabsorb; + } RemainingDamage -= absorbed; @@ -2886,7 +3112,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM // Fire Ward or Frost Ward or Ice Barrier (or Mana Shield) // for Incanter's Absorption converting to spell power if (spellProto->IsFitToFamily(SPELLFAMILY_MAGE, UI64LIT(0x0000000000000000), 0x00000008)) + { incanterAbsorption += currentAbsorb; + } // Reduce shield amount mod->m_amount -= currentAbsorb; @@ -2969,7 +3197,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM // Mana Shield (or Fire Ward or Frost Ward or Ice Barrier) // for Incanter's Absorption converting to spell power if ((*i)->GetSpellProto()->IsFitToFamily(SPELLFAMILY_MAGE, UI64LIT(0x0000000000000000), 0x000008)) + { incanterAbsorption += currentAbsorb; + } (*i)->GetModifier()->m_amount -= currentAbsorb; if ((*i)->GetModifier()->m_amount <= 0) @@ -2998,7 +3228,9 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM // apply normalized part of already accumulated amount in aura if (Aura* spdAura = GetAura(44413, EFFECT_INDEX_0)) + { amount += spdAura->GetModifier()->m_amount * spdAura->GetAuraDuration() / spdAura->GetAuraMaxDuration(); + } // Incanter's Absorption (triggered absorb based spell power, will replace existing if any) CastCustomSpell(this, 44413, &amount, NULL, NULL, true); @@ -3017,12 +3249,16 @@ void Unit::CalculateDamageAbsorbAndResist(Unit* pCaster, SpellSchoolMask schoolM // check damage school mask if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) + { continue; + } // Damage can be splitted only if aura has an alive caster Unit* caster = (*i)->GetCaster(); if (!caster || caster == this || !caster->IsInWorld() || !caster->IsAlive()) + { continue; + } uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f); @@ -3095,7 +3331,9 @@ void Unit::CalculateAbsorbResistBlock(Unit* pCaster, SpellNonMeleeDamage* damage { damageInfo->blocked = uint32(damageInfo->damage * GetShieldBlockDamageValue() / 100.0f); if (damageInfo->damage < damageInfo->blocked) + { damageInfo->blocked = damageInfo->damage; + } damageInfo->damage -= damageInfo->blocked; } @@ -3135,17 +3373,23 @@ void Unit::CalculateHealAbsorb(const uint32 heal, uint32* absorb) // currentAbsorb - heal can be absorbed // If need absorb less heal if (RemainingHeal < currentAbsorb) + { currentAbsorb = RemainingHeal; + } RemainingHeal -= currentAbsorb; // Reduce aura amount mod->m_amount -= currentAbsorb; if ((*i)->GetHolder()->DropAuraCharge()) + { mod->m_amount = 0; + } // Need remove it later if (mod->m_amount <= 0) + { existExpired = true; + } } // Remove all expired absorb auras @@ -3159,7 +3403,9 @@ void Unit::CalculateHealAbsorb(const uint32 heal, uint32* absorb) i = vHealAbsorb.begin(); } else + { ++i; + } } } @@ -3184,7 +3430,9 @@ void Unit::AttackerStateUpdate(Unit* pVictim, WeaponAttackType attType, bool ext } if (attType == RANGED_ATTACK) + { return; // ignore ranged case + } uint32 extraAttacks = m_extraAttacks; @@ -3200,7 +3448,9 @@ void Unit::AttackerStateUpdate(Unit* pVictim, WeaponAttackType attType, bool ext { AttackerStateUpdate(pVictim, BASE_ATTACK, true); if (m_extraAttacks > 0) + { --m_extraAttacks; + } } } return; @@ -3252,7 +3502,9 @@ void Unit::AttackerStateUpdate(Unit* pVictim, WeaponAttackType attType, bool ext { AttackerStateUpdate(pVictim, BASE_ATTACK, true); if (m_extraAttacks > 0) + { --m_extraAttacks; + } } } } @@ -3324,9 +3576,13 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* pVictim, WeaponAttackT { // Reduce dodge chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) + { dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100); + } else + { dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; + } // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE dodge_chance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100; @@ -3347,9 +3603,13 @@ MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit* pVictim, WeaponAttackT { // Reduce parry chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) + { parry_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100); + } else + { parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; + } if (parry_chance > 0 && (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->ExtraFlags & CREATURE_EXTRA_FLAG_NO_PARRY))) { @@ -3437,7 +3697,9 @@ uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized) float min_damage, max_damage; if (normalized && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->CalculateMinMaxDamage(attType, normalized, min_damage, max_damage); + } else { switch (attType) @@ -3468,7 +3730,9 @@ uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized) } if (max_damage == 0.0f) + { max_damage = 5.0f; + } return urand((uint32)min_damage, (uint32)max_damage); } @@ -3484,10 +3748,14 @@ float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const float LvlPenalty = 0.0f; if (spellLevel < 20) + { LvlPenalty = 20.0f - spellLevel * 3.75f; + } float LvlFactor = (float(spellLevel) + 6.0f) / float(getLevel()); if (LvlFactor > 1.0f) + { LvlFactor = 1.0f; + } return (100.0f - LvlPenalty) * LvlFactor / 100.0f; } @@ -3542,7 +3810,9 @@ bool Unit::IsSpellBlocked(Unit* pCaster, SpellEntry const* spellEntry, WeaponAtt for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i) { if (!(*i)->isAffectedOnSpell(spellProto)) + { continue; + } if ((*i)->GetModifier()->m_miscvalue == ???) { return false; @@ -3564,7 +3834,9 @@ bool Unit::IsSpellBlocked(Unit* pCaster, SpellEntry const* spellEntry, WeaponAtt // the block chance is modified by 0.5% if the target is a mob and 0.2% if the target is a player. blockChance += (getLevel() - pCaster->GetLevelForTarget(this)) * (pCaster->GetTypeId() == TYPEID_PLAYER ? 0.2f : 0.5f); if (blockChance < 0.0f) + { blockChance = 0.0f; + } return roll_chance_f(blockChance); } @@ -3580,30 +3852,46 @@ float Unit::MeleeSpellMissChance(Unit* pVictim, WeaponAttackType attType, int32 // TODO: implement diminishing returns for defense from player's defense rating // pure skill diff is not sufficient since 3.x anymore, but exact formulas hard to research if (pVictim->GetTypeId() == TYPEID_PLAYER) + { hitChance = 95.0f + skillDiff * 0.04f; + } else if (skillDiff < -10) + { hitChance = 94.0f + (skillDiff + 10) * 0.4f; + } else + { hitChance = 95.0f + skillDiff * 0.1f; + } // Hit chance depends from victim auras if (attType == RANGED_ATTACK) + { hitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); + } else + { hitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); + } // Spellmod from SPELLMOD_RESIST_MISS_CHANCE if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, hitChance); + } // Miss = 100 - hit float missChance = 100.0f - hitChance; // Bonuses from attacker aura and ratings if (attType == RANGED_ATTACK) + { missChance -= m_modRangedHitChance; + } else + { missChance -= m_modMeleeHitChance; + } // Limit miss chance from 0 to 60% if (missChance < 0.0f) @@ -3623,7 +3911,9 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* pVictim, SpellEntry const* spell) WeaponAttackType attType = BASE_ATTACK; if (spell->GetDmgClass() == SPELL_DAMAGE_CLASS_RANGED) + { attType = RANGED_ATTACK; + } // bonus from skills is 0.04% per skill Diff int32 attackerWeaponSkill = GetMaxSkillValueForLevel(); @@ -3649,7 +3939,9 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* pVictim, SpellEntry const* spell) { int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); if (resist_mech < temp * 100) + { resist_mech = temp * 100; + } } } // Roll chance @@ -3695,24 +3987,32 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* pVictim, SpellEntry const* spell) { // Can`t dodge from behind in PvP (but its possible in PvE) if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER) + { canDodge = false; + } // Can`t parry without special ability if (!pVictim->HasAuraType(SPELL_AURA_MOD_PARRY_FROM_BEHIND_PERCENT)) + { canParry = false; + } } // Check creatures ExtraFlags for disable parry if (pVictim->GetTypeId() == TYPEID_UNIT) { uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->ExtraFlags; if (flagEx & CREATURE_EXTRA_FLAG_NO_PARRY) + { canParry = false; + } } // Ignore combat result aura AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT); for (AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i) { if (!(*i)->isAffectedOnSpell(spell)) + { continue; + } switch ((*i)->GetModifier()->m_miscvalue) { case MELEE_HIT_DODGE: canDodge = false; break; @@ -3732,11 +4032,17 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* pVictim, SpellEntry const* spell) dodgeChance += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE) * 100; // Reduce dodge chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) + { dodgeChance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f); + } else + { dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; + } if (dodgeChance < 0) + { dodgeChance = 0; + } tmp += dodgeChance; if (roll < tmp) @@ -3751,11 +4057,17 @@ SpellMissInfo Unit::MeleeSpellHitResult(Unit* pVictim, SpellEntry const* spell) int32 parryChance = int32(pVictim->GetUnitParryChance() * 100.0f) - skillDiff * 4; // Reduce parry chance by attacker expertise rating if (GetTypeId() == TYPEID_PLAYER) + { parryChance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f); + } else + { parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE) * 25; + } if (parryChance < 0) + { parryChance = 0; + } // if (from_behind) -- only 100% currently and not 100% sure way value apply // parryChance = int32(parryChance * (pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_PARRY_FROM_BEHIND_PERCENT) - 1)); @@ -3787,18 +4099,26 @@ SpellMissInfo Unit::MagicSpellHitResult(Unit* pVictim, SpellEntry const* spell) // Base hit chance from attacker and victim levels int32 modHitChance; if (leveldif < 3) + { modHitChance = 96 - leveldif; + } else + { modHitChance = 94 - (leveldif - 2) * lchance; + } // Spellmod from SPELLMOD_RESIST_MISS_CHANCE if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance); + } // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras modHitChance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask); // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST if (IsDispelSpell(spell)) + { modHitChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST); + } // Chance resist mechanic (select max value from every mechanic spell effect) int32 resist_mech = 0; // Get effects mechanic and chance @@ -3809,7 +4129,9 @@ SpellMissInfo Unit::MagicSpellHitResult(Unit* pVictim, SpellEntry const* spell) { int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); if (resist_mech < temp) + { resist_mech = temp; + } } } // Apply mod @@ -3821,7 +4143,9 @@ SpellMissInfo Unit::MagicSpellHitResult(Unit* pVictim, SpellEntry const* spell) if (HitChance < 100) HitChance = 100; - if (HitChance > 10000) HitChance = 10000; + { + if (HitChance > 10000) HitChance = 10000; + } int32 tmp = spell->HasAttribute(SPELL_ATTR_EX3_CANT_MISS) ? 0 : (10000 - HitChance); @@ -3894,7 +4218,9 @@ SpellMissInfo Unit::SpellHitResult(Unit* pVictim, SpellEntry const* spell, bool Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL); for (Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i) if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell)) + { reflectchance += (*i)->GetModifier()->m_amount; + } if (reflectchance > 0 && roll_chance_i(reflectchance)) { // Start triggers for remove charges if need (trigger only for victim, and mark as active spell) @@ -3939,7 +4265,9 @@ float Unit::MeleeMissChanceCalc(const Unit* pVictim, WeaponAttackType attType) c } } if (!isNormal && !m_currentSpells[CURRENT_MELEE_SPELL]) + { missChance += 19.0f; + } } int32 skillDiff = int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetMaxSkillValueForLevel(this)); @@ -3948,23 +4276,37 @@ float Unit::MeleeMissChanceCalc(const Unit* pVictim, WeaponAttackType attType) c // TODO: implement diminishing returns for defense from player's defense rating // pure skill diff is not sufficient since 3.x anymore, but exact formulas hard to research if (pVictim->GetTypeId() == TYPEID_PLAYER) + { missChance -= skillDiff * 0.04f; + } else if (skillDiff < -10) + { missChance -= (skillDiff + 10) * 0.4f - 1.0f; + } else + { missChance -= skillDiff * 0.1f; + } // Hit chance bonus from attacker based on ratings and auras if (attType == RANGED_ATTACK) + { missChance -= m_modRangedHitChance; + } else + { missChance -= m_modMeleeHitChance; + } // Modify miss chance by victim auras if (attType == RANGED_ATTACK) + { missChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); + } else + { missChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); + } // Limit miss chance from 0 to 60% if (missChance < 0.0f) @@ -4020,10 +4362,14 @@ float Unit::GetUnitParryChance() const { Item* tmpitem = player->GetWeaponForAttack(BASE_ATTACK, true, true); if (!tmpitem) + { tmpitem = player->GetWeaponForAttack(OFF_ATTACK, true, true); + } if (tmpitem) + { chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE); + } } } else if (GetTypeId() == TYPEID_UNIT) @@ -4105,21 +4451,29 @@ float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit* pVict // flat aura mods if (attackType == RANGED_ATTACK) + { crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE); + } else + { crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); + } crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE); if (crit < 0.0f) + { crit = 0.0f; + } return crit; } void Unit::_UpdateSpells(uint32 time) { if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) + { _UpdateAutoRepeatSpell(); + } // remove finished spells from current pointers for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) @@ -4151,7 +4505,9 @@ void Unit::_UpdateSpells(uint32 time) iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } if (!m_gameObj.empty()) @@ -4169,7 +4525,9 @@ void Unit::_UpdateSpells(uint32 time) dnext1 = m_gameObj.erase(ite1); } else + { ++dnext1; + } } } } @@ -4184,7 +4542,9 @@ void Unit::_UpdateAutoRepeatSpell() { // cancel wand shoot if (!isAutoShot) + { InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + } // auto shot just waits return; } @@ -4248,7 +4608,9 @@ void Unit::SetCurrentCastedSpell(Spell* pSpell) { // break autorepeat if not Auto Shot if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT) + { InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + } } } break; @@ -4274,7 +4636,9 @@ void Unit::SetCurrentCastedSpell(Spell* pSpell) InterruptSpell(CURRENT_CHANNELED_SPELL, false); // special action: first cast delay if (getAttackTimer(RANGED_ATTACK) < 500) + { setAttackTimer(RANGED_ATTACK, 500); + } } } break; @@ -4286,7 +4650,9 @@ void Unit::SetCurrentCastedSpell(Spell* pSpell) // current spell (if it is still here) may be safely deleted now if (m_currentSpells[CSpellType]) + { m_currentSpells[CSpellType]->SetReferencedFromCurrent(false); + } // set new current spell m_currentSpells[CSpellType] = pSpell; @@ -4308,11 +4674,15 @@ void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool se if (spellType == CURRENT_AUTOREPEAT_SPELL && sendAutoRepeatCancelToClient) { if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SendAutoRepeatCancel(this); + } } if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED) + { m_currentSpells[spellType]->cancel(); + } // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt) if (m_currentSpells[spellType]) @@ -4332,7 +4702,9 @@ void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/) } if (spellType == CURRENT_CHANNELED_SPELL) + { spell->SendChannelUpdate(0); + } spell->finish(ok); } @@ -4366,15 +4738,21 @@ void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id) { // generic spells are interrupted if they are not finished or delayed if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id == spell_id)) + { InterruptSpell(CURRENT_GENERIC_SPELL, withDelayed); + } // autorepeat spells are interrupted if they are not finished or delayed if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == spell_id)) + { InterruptSpell(CURRENT_AUTOREPEAT_SPELL, withDelayed); + } // channeled spells are interrupted if they are not finished, even if they are delayed if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id == spell_id)) + { InterruptSpell(CURRENT_CHANNELED_SPELL, true); + } } Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const @@ -4471,7 +4849,9 @@ int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const AuraList const& mTotalAuraList = GetAurasByType(auratype); for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if ((*i)->GetModifier()->m_amount > modifier) + { modifier = (*i)->GetModifier()->m_amount; + } return modifier; } @@ -4483,7 +4863,9 @@ int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const AuraList const& mTotalAuraList = GetAurasByType(auratype); for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) if ((*i)->GetModifier()->m_amount < modifier) + { modifier = (*i)->GetModifier()->m_amount; + } return modifier; } @@ -4502,7 +4884,9 @@ int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue & misc_mask) + { modifier += mod->m_amount; + } } return modifier; } @@ -4521,7 +4905,9 @@ float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue & misc_mask) + { multiplier *= (100.0f + mod->m_amount) / 100.0f; + } } return multiplier; } @@ -4540,7 +4926,9 @@ int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_ { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier) + { modifier = mod->m_amount; + } } return modifier; @@ -4560,7 +4948,9 @@ int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_ { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier) + { modifier = mod->m_amount; + } } return modifier; @@ -4575,7 +4965,9 @@ int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue == misc_value) + { modifier += mod->m_amount; + } } return modifier; } @@ -4589,7 +4981,9 @@ float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_valu { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue == misc_value) + { multiplier *= (100.0f + mod->m_amount) / 100.0f; + } } return multiplier; } @@ -4603,7 +4997,9 @@ int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_ { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue == misc_value && mod->m_amount > modifier) + { modifier = mod->m_amount; + } } return modifier; @@ -4618,7 +5014,9 @@ int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_ { Modifier* mod = (*i)->GetModifier(); if (mod->m_miscvalue == misc_value && mod->m_amount < modifier) + { modifier = mod->m_amount; + } } return modifier; @@ -4638,7 +5036,9 @@ float Unit::GetTotalAuraMultiplierByMiscValueForMask(AuraType auratype, uint32 m { Modifier* mod = (*i)->GetModifier(); if (mask & (1 << (mod->m_miscvalue - 1))) + { multiplier *= (100.0f + mod->m_amount) / 100.0f; + } } return multiplier; } @@ -4687,7 +5087,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) // Check for coexisting Weapon-proced Auras if (holder->IsWeaponBuffCoexistableWith(foundHolder)) + { continue; + } // Carry over removed Aura's remaining damage if Aura still has ticks remaining if (foundHolder->GetSpellProto()->HasAttribute(SPELL_ATTR_EX4_STACK_DOT_MODIFIER)) @@ -4710,7 +5112,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) aur->GetModifier()->m_amount += int32(remainingDamage / aur->GetAuraMaxTicks()); } else + { DEBUG_LOG("Holder (spell %u) on target (lowguid: %u) doesn't have aura on effect index %u. skipping.", aurSpellInfo->Id, holder->GetTarget()->GetGUIDLow(), i); + } } } } @@ -4727,7 +5131,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) { // no need to check non stacking auras that weren't/won't be applied on this target if (!foundHolder->m_auras[i] || !holder->m_auras[i]) + { continue; + } // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original SpellEffectEntry const* spellEffect = aurSpellInfo->GetSpellEffect(SpellEffectIndex(i)); @@ -4759,7 +5165,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) } if (stop) + { break; + } } } @@ -4802,9 +5210,13 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) removed = true; // remove from target if target found if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) + { itr_target->RemoveAurasDueToSpell(itr_spellEntry->Id); // TODO AURA_REMOVE_BY_TRACKING (might require additional work elsewhere) + } else // Normally the tracking will be removed by the AuraRemoval + { scTargets.erase(itr); + } } break; case TRACK_AURA_TYPE_CONTROL_VEHICLE: @@ -4813,7 +5225,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) uint8 i = EFFECT_INDEX_0; for (; i < MAX_EFFECT_INDEX; ++i) if (IsAuraApplyEffect(aurSpellInfo, SpellEffectIndex(i))) + { break; + } // Remove auras when first holder is applied if ((1 << i) & holder->GetAuraFlags()) @@ -4822,9 +5236,13 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) // remove from target if target found if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) + { itr_target->RemoveAurasByCasterSpell(itr_spellEntry->Id, caster->GetObjectGuid(), AURA_REMOVE_BY_TRACKING); + } else // Normally the tracking will be removed by the AuraRemoval + { scTargets.erase(itr); + } } break; } @@ -4847,7 +5265,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) { case TRACK_AURA_TYPE_CONTROL_VEHICLE: // Only track the controlled vehicle, no secondary effects if (!IsSpellHaveAura(aurSpellInfo, SPELL_AURA_CONTROL_VEHICLE, holder->GetAuraFlags())) + { break; + } // no break here, track other controlled case TRACK_AURA_TYPE_SINGLE_TARGET: // Register spell holder single target scTargets[aurSpellInfo] = GetObjectGuid(); @@ -4862,7 +5282,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i))) + { AddAuraToModList(aur); + } holder->ApplyAuraModifiers(true, true); // This is the place where auras are actually applied onto the target DEBUG_LOG("Holder of spell %u now is in use", holder->GetId()); @@ -4882,7 +5304,9 @@ bool Unit::AddSpellAuraHolder(SpellAuraHolder* holder) void Unit::AddAuraToModList(Aura* aura) { if (aura->GetModifier()->m_auraname < TOTAL_AURAS) + { m_modAuras[aura->GetModifier()->m_auraname].push_back(aura); + } } void Unit::RemoveRankAurasDueToSpell(uint32 spellId) @@ -4905,9 +5329,13 @@ void Unit::RemoveRankAurasDueToSpell(uint32 spellId) RemoveAurasDueToSpell(i_spellId); if (m_spellAuraHolders.empty()) + { break; + } else + { next = m_spellAuraHolders.begin(); + } } } } @@ -4946,7 +5374,9 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) SpellEntry const* i_spellProto = (*i).second->GetSpellProto(); if (!i_spellProto) + { continue; + } uint32 i_spellId = i_spellProto->Id; @@ -4955,11 +5385,15 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) { // passive non-stackable spells not stackable only for same caster if (holder->GetCasterGuid() != i->second->GetCasterGuid()) + { continue; + } // passive non-stackable spells not stackable only with another rank of same spell if (!sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) + { continue; + } } // prevent triggering aura of removing aura that triggered it @@ -4990,9 +5424,13 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) RemoveAurasDueToSpell(i_spellId); if (m_spellAuraHolders.empty()) + { break; + } else + { next = m_spellAuraHolders.begin(); + } continue; } @@ -5017,9 +5455,13 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) RemoveAurasDueToSpell(i_spellId); if (m_spellAuraHolders.empty()) + { break; + } else + { next = m_spellAuraHolders.begin(); + } continue; } @@ -5029,7 +5471,9 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) { SpellEntry const* triggeredBy = holder->GetTriggeredBy(); if (triggeredBy && sSpellMgr.IsSpellCanAffectSpell(triggeredBy, i_spellProto)) // check if this spell can be triggered by any talent aura + { continue; + } if (sSpellMgr.IsNoStackSpellDueToSpell(spellProto->Id, i_spellProto->Id)) { @@ -5042,9 +5486,13 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) RemoveAurasDueToSpell(i_spellId); if (m_spellAuraHolders.empty()) + { break; + } else + { next = m_spellAuraHolders.begin(); + } } continue; } @@ -5055,7 +5503,9 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) if (IsNoStackAuraDueToAura(spellId, i_spellId)) { if (CompareAuraRanks(spellId, i_spellId) < 0) + { return false; // cannot remove higher rank + } // Its a parent aura (create this aura in ApplyModifier) if ((*i).second->IsInUse()) @@ -5066,9 +5516,13 @@ bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder* holder) RemoveAurasDueToSpell(i_spellId); if (m_spellAuraHolders.empty()) + { break; + } else + { next = m_spellAuraHolders.begin(); + } } } } @@ -5089,7 +5543,9 @@ void Unit::RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except) iter = spair.first; } else + { ++iter; + } } } void Unit::RemoveAurasByCasterSpell(uint32 spellId, ObjectGuid casterGuid, AuraRemoveMode mode /*=AURA_REMOVE_BY_DEFAULT*/) @@ -5104,7 +5560,9 @@ void Unit::RemoveAurasByCasterSpell(uint32 spellId, ObjectGuid casterGuid, AuraR iter = spair.first; } else + { ++iter; + } } } @@ -5121,7 +5579,9 @@ void Unit::RemoveSingleAuraFromSpellAuraHolder(uint32 spellId, SpellEffectIndex iter = spair.first; } else + { ++iter; + } } } @@ -5170,7 +5630,9 @@ void Unit::RemoveAuraHolderDueToSpellByDispel(uint32 spellId, uint32 stackAmount uint32 triggeredSpell = 0; if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x10000000), 0x00000000, casterGuid)) + { caster = dotAura->GetCaster(); + } if (caster && !caster->IsDead()) { @@ -5193,7 +5655,9 @@ void Unit::RemoveAuraHolderDueToSpellByDispel(uint32 spellId, uint32 stackAmount // Haste if (triggeredSpell) + { caster->CastSpell(caster, triggeredSpell, true); + } return; } // Vampiric touch (first dummy aura) @@ -5238,7 +5702,9 @@ void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGuid, U Aura* aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); if (!aur) + { continue; + } int32 basePoints = aur->GetBasePoints(); // construct the new aura for the attacker - will never return NULL, it's just a wrapper for @@ -5290,7 +5756,9 @@ void Unit::RemoveAurasWithDispelType(DispelType type, ObjectGuid casterGuid) itr = auras.begin(); } else + { ++itr; + } } } @@ -5328,7 +5796,9 @@ void Unit::RemoveAurasDueToSpell(uint32 spellId, SpellAuraHolder* except, AuraRe iter = bounds.first; } else + { ++iter; + } } } @@ -5344,7 +5814,9 @@ void Unit::RemoveAurasDueToItemSpell(Item* castItem, uint32 spellId) iter = bounds.first; } else + { ++iter; + } } } @@ -5358,7 +5830,9 @@ void Unit::RemoveAurasWithInterruptFlags(uint32 flags) iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } } @@ -5372,7 +5846,9 @@ void Unit::RemoveAurasWithAttribute(uint32 flags) iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } } @@ -5403,7 +5879,9 @@ void Unit::RemoveAurasOnCast(SpellEntry const* castedSpellEntry) removeThisHolder = !foundStealth; } else + { removeThisHolder = true; + } } if (removeThisHolder) @@ -5412,7 +5890,9 @@ void Unit::RemoveAurasOnCast(SpellEntry const* castedSpellEntry) iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } } @@ -5468,7 +5948,9 @@ void Unit::RemoveNotOwnTrackedTargetAuras(uint32 newPhase) // remove from target if target found if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) + { itr_target->RemoveAurasByCasterSpell(itr_spellEntry->Id, GetObjectGuid()); + } itr = scTargets.begin(); // list can be changed at remove aura continue; @@ -5482,7 +5964,9 @@ void Unit::RemoveNotOwnTrackedTargetAuras(uint32 newPhase) // remove from target if target found if (itr_target) + { itr_target->RemoveAurasByCasterSpell(itr_spellEntry->Id, GetObjectGuid()); + } itr = scTargets.begin(); // list can be changed at remove aura continue; @@ -5503,10 +5987,14 @@ void Unit::RemoveSpellAuraHolder(SpellAuraHolder* holder, AuraRemoveMode mode) Unit* caster = holder->GetCaster(); if (IsChanneledSpell(AurSpellInfo) && caster) if (caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem() && ((Totem*)caster)->GetTotemType() == TOTEM_STATUE) + { statue = ((Totem*)caster); + } if (m_spellAuraHoldersUpdateIterator != m_spellAuraHolders.end() && m_spellAuraHoldersUpdateIterator->second == holder) + { ++m_spellAuraHoldersUpdateIterator; + } SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(holder->GetId()); for (SpellAuraHolderMap::iterator itr = bounds.first; itr != bounds.second; ++itr) @@ -5524,16 +6012,22 @@ void Unit::RemoveSpellAuraHolder(SpellAuraHolder* holder, AuraRemoveMode mode) for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { if (Aura* aura = holder->m_auras[i]) + { RemoveAura(aura, mode); + } } holder->_RemoveSpellAuraHolder(); if (mode != AURA_REMOVE_BY_DELETE) + { holder->HandleSpellSpecificBoosts(false); + } if (statue) + { statue->UnSummon(); + } // If holder in use (removed from code that plan access to it data after return) // store it in holder list with delayed deletion @@ -5543,7 +6037,9 @@ void Unit::RemoveSpellAuraHolder(SpellAuraHolder* holder, AuraRemoveMode mode) m_deletedHolders.push_back(holder); } else + { delete holder; + } if (mode != AURA_REMOVE_BY_EXPIRE && IsChanneledSpell(AurSpellInfo) && !IsAreaOfEffectSpell(AurSpellInfo) && caster && caster->GetObjectGuid() != GetObjectGuid()) @@ -5561,9 +6057,13 @@ void Unit::RemoveSingleAuraFromSpellAuraHolder(SpellAuraHolder* holder, SpellEff } if (aura->IsLastAuraOnHolder()) + { RemoveSpellAuraHolder(holder, mode); + } else + { RemoveAura(aura, mode); + } } void Unit::RemoveAura(Aura* Aur, AuraRemoveMode mode) @@ -5603,14 +6103,20 @@ void Unit::RemoveAura(Aura* Aur, AuraRemoveMode mode) } } else + { Aur->ApplyModifier(false, true); + } // If aura in use (removed from code that plan access to it data after return) // store it in aura list with delayed deletion if (Aur->IsInUse()) + { m_deletedAuras.push_back(Aur); + } else + { delete Aur; + } } void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) @@ -5640,7 +6146,9 @@ void Unit::RemoveArenaAuras(bool onleave) iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } } @@ -5656,7 +6164,9 @@ void Unit::RemoveAllAurasOnDeath() iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } } @@ -5673,7 +6183,9 @@ void Unit::RemoveAllAurasOnEvade() iter = m_spellAuraHolders.begin(); } else + { ++iter; + } } } @@ -5685,12 +6197,18 @@ void Unit::DelaySpellAuraHolder(uint32 spellId, int32 delaytime, ObjectGuid cast SpellAuraHolder* holder = iter->second; if (casterGuid != holder->GetCasterGuid()) + { continue; + } if (holder->GetAuraDuration() < delaytime) + { holder->SetAuraDuration(0); + } else + { holder->SetAuraDuration(holder->GetAuraDuration() - delaytime); + } holder->SendAuraUpdate(false); @@ -5764,11 +6282,15 @@ Aura* Unit::GetTriggeredByClientAura(uint32 spellId) const { SpellAuraHolder const* holder = (*itr)->GetHolder(); if (!holder || holder->IsDeleted()) + { continue; + } SpellEffectEntry const* spellEffect = holder->GetSpellProto()->GetSpellEffect(SpellEffectIndex((*itr)->GetEffIndex())); if(!spellEffect) + { continue; + } // NOTE for further development: If there are more spells of this aura type, it might be required to check that this is the effect that applies SPELL_AURA_PERIODIC_TRIGGER_BY_CLIENT if (holder->GetCasterGuid() == GetObjectGuid() && spellEffect->EffectTriggerSpell == spellId) @@ -5827,7 +6349,9 @@ void Unit::RemoveDynObject(uint32 spellid) i = m_dynObjGUIDs.erase(i); } else + { ++i; + } } } @@ -5836,7 +6360,9 @@ void Unit::RemoveAllDynObjects() while (!m_dynObjGUIDs.empty()) { if (DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin())) + { dynObj->Delete(); + } m_dynObjGUIDs.erase(m_dynObjGUIDs.begin()); } } @@ -5891,7 +6417,9 @@ GameObject* Unit::GetGameObject(uint32 spellId) const WildGameObjectMap::const_iterator find = m_wildGameObjs.find(spellId); if (find != m_wildGameObjs.end()) + { return GetMap()->GetGameObject(find->second); // Can be NULL + } return NULL; } @@ -5924,9 +6452,13 @@ void Unit::AddWildGameObject(GameObject* gameObj) { GameObject* pGo = GetMap()->GetGameObject(itr->second); if (pGo) + { ++itr; + } else + { m_wildGameObjs.erase(itr++); + } } } @@ -5983,7 +6515,9 @@ void Unit::RemoveGameObject(uint32 spellid, bool del) next = m_gameObj.erase(i); } else + { ++next; + } } } @@ -6034,7 +6568,9 @@ void Unit::SendSpellNonMeleeDamageLog(Unit* target, uint32 SpellID, uint32 Damag log.blocked = Blocked; log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6; if (CriticalHit) + { log.HitInfo |= SPELL_HIT_TYPE_CRIT; + } SendSpellNonMeleeDamageLog(&log); } @@ -6089,11 +6625,15 @@ void Unit::ProcDamageAndSpell(Unit* pVictim, uint32 procAttacker, uint32 procVic { // Not much to do if no flags are set. if (procAttacker) + { ProcDamageAndSpellFor(false, pVictim, procAttacker, procExtra, attType, procSpell, amount); + } // Now go on with a victim's events'n'auras // Not much to do if no flags are set or there is no victim if (pVictim && pVictim->IsAlive() && procVictim) + { pVictim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount); + } } void Unit::SendSpellMiss(Unit* target, uint32 spellID, SpellMissInfo missInfo) @@ -6136,13 +6676,17 @@ void Unit::SendAttackStateUpdate(CalcDamageInfo* damageInfo) if (damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2)) { for (uint32 i = 0; i < count; ++i) + { data << uint32(damageInfo->absorb); // Absorb + } } if (damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2)) { for (uint32 i = 0; i < count; ++i) + { data << uint32(damageInfo->resist); // Resist + } } data << uint8(damageInfo->TargetState); @@ -6151,10 +6695,14 @@ void Unit::SendAttackStateUpdate(CalcDamageInfo* damageInfo) // HITINFO_NOACTION normally set if spell if (damageInfo->HitInfo & HITINFO_BLOCK) + { data << uint32(damageInfo->blocked_amount); + } if (damageInfo->HitInfo & HITINFO_UNK22) + { data << uint32(0); // count of some sort? + } if (damageInfo->HitInfo & HITINFO_UNK0) { @@ -6217,7 +6765,9 @@ void Unit::SetPowerType(Powers new_powertype) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE); + } } else if (((Creature*)this)->IsPet()) { @@ -6226,7 +6776,9 @@ void Unit::SetPowerType(Powers new_powertype) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE); + } } } @@ -6277,9 +6829,13 @@ FactionTemplateEntry const* Unit::getFactionTemplateEntry() const guid = GetObjectGuid(); if (guid.GetHigh() == HIGHGUID_PET) + { sLog.outError("%s (base creature entry %u) have invalid faction template id %u, owner %s", GetGuidStr().c_str(), GetEntry(), getFaction(), ((Pet*)this)->GetOwnerGuid().GetString().c_str()); + } else + { sLog.outError("%s have invalid faction template id %u", GetGuidStr().c_str(), getFaction()); + } } } return entry; @@ -6652,7 +7208,9 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack) if (HasAuraType(SPELL_AURA_MOD_UNATTACKABLE)) + { RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE); + } // in fighting already if (m_attacking) @@ -6680,14 +7238,18 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) { // set position before any AI calls/assistance if (GetTypeId() == TYPEID_UNIT) + { ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ()); + } } // Set our target SetTargetGuid(victim->GetObjectGuid()); if (meleeAttack) + { addUnitState(UNIT_STAT_MELEE_ATTACKING); + } m_attacking = victim; m_attacking->_addAttacker(this); @@ -6700,10 +7262,14 @@ bool Unit::Attack(Unit* victim, bool meleeAttack) // delay offhand weapon attack to next attack time if (haveOffhandWeapon()) + { resetAttackTimer(OFF_ATTACK); + } if (meleeAttack) + { SendMeleeAttackStart(victim); + } return true; } @@ -6712,7 +7278,9 @@ void Unit::AttackedBy(Unit* attacker) { // trigger AI reaction if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI()) + { ((Creature*)this)->AI()->AttackedBy(attacker); + } // do not pet reaction for self inflicted damage (like environmental) if (attacker == this) @@ -6722,7 +7290,9 @@ void Unit::AttackedBy(Unit* attacker) // trigger pet AI reaction if (Pet* pet = GetPet()) + { pet->AttackedBy(attacker); + } } bool Unit::AttackStop(bool targetSwitch /*=false*/) @@ -6764,17 +7334,23 @@ bool Unit::AttackStop(bool targetSwitch /*=false*/) void Unit::CombatStop(bool includingCast) { if (includingCast && IsNonMeleeSpellCasted(false)) + { InterruptNonMeleeSpells(false); + } AttackStop(); RemoveAllAttackers(); if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel + } else if (GetTypeId() == TYPEID_UNIT) { if (((Creature*)this)->GetTemporaryFactionFlags() & TEMPFACTION_RESTORE_COMBAT_STOP) + { ((Creature*)this)->ClearTemporaryFaction(); + } } ClearInCombat(); @@ -6885,11 +7461,19 @@ void Unit::ModifyAuraState(AuraState flag, bool apply) const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { - if (itr->second.state == PLAYERSPELL_REMOVED) continue; + if (itr->second.state == PLAYERSPELL_REMOVED) + { + continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); - if (!spellInfo || !IsPassiveSpell(spellInfo)) continue; + if (!spellInfo || !IsPassiveSpell(spellInfo)) + { + continue; + } if (AuraState(spellInfo->GetCasterAuraState()) == flag) + { CastSpell(this, itr->first, true, NULL); + } } } } @@ -6912,7 +7496,9 @@ void Unit::ModifyAuraState(AuraState flag, bool apply) itr = tAuras.begin(); } else + { ++itr; + } } } } @@ -6993,9 +7579,13 @@ Pet* Unit::_GetPet(ObjectGuid guid) const void Unit::RemoveMiniPet() { if (Pet* pet = GetMiniPet()) + { pet->Unsummon(PET_SAVE_AS_DELETED, this); + } else + { SetCritterGuid(ObjectGuid()); + } } Pet* Unit::GetMiniPet() const @@ -7037,7 +7627,9 @@ void Unit::Uncharm() { uint32 createdBySpellId = charm->GetUInt32Value(UNIT_CREATED_BY_SPELL); if (static_cast(charm)->IsTemporarySummon() && createdBySpellId) + { RemoveAurasDueToSpell(createdBySpellId); + } } } } @@ -7047,7 +7639,9 @@ void Unit::SetPet(Pet* pet) SetPetGuid(pet ? pet->GetObjectGuid() : ObjectGuid()); if (pet && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SendPetGUIDs(); + } } void Unit::SetCharm(Unit* pet) @@ -7072,7 +7666,9 @@ void Unit::RemoveGuardians() ObjectGuid guid = *m_guardianPets.begin(); if (Pet* pet = GetMap()->GetPet(guid)) + { pet->Unsummon(PET_SAVE_AS_DELETED, this); // can remove pet guid from m_guardianPets + } m_guardianPets.erase(guid); } @@ -7149,7 +7745,9 @@ void Unit::UnsummonAllTotems() { for (int i = 0; i < MAX_TOTEM_SLOT; ++i) if (Totem* totem = GetTotem(TotemSlot(i))) + { totem->UnSummon(); + } } int32 Unit::DealHeal(Unit* pVictim, uint32 addhealth, SpellEntry const* spellProto, bool critical, uint32 absorb) @@ -7159,7 +7757,9 @@ int32 Unit::DealHeal(Unit* pVictim, uint32 addhealth, SpellEntry const* spellPro Unit* unit = this; if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) + { unit = GetOwner(); + } // overheal = addhealth - gain unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical, absorb); @@ -7167,11 +7767,15 @@ int32 Unit::DealHeal(Unit* pVictim, uint32 addhealth, SpellEntry const* spellPro if (unit->GetTypeId() == TYPEID_PLAYER) { if (BattleGround* bg = ((Player*)unit)->GetBattleGround()) + { bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain); + } // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria) if (gain) + { ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim); + } ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth); } @@ -7184,7 +7788,9 @@ int32 Unit::DealHeal(Unit* pVictim, uint32 addhealth, SpellEntry const* spellPro // Script Event HealedBy if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->AI()) + { ((Creature*)pVictim)->AI()->HealedBy(this, addhealth); + } return gain; } @@ -7284,7 +7890,9 @@ int32 Unit::SpellBonusWithCoeffs(SpellEntry const* spellProto, int32 total, int3 // Not apply this to creature casted spells if (GetTypeId() == TYPEID_UNIT && !((Creature*)this)->IsPet()) + { coeff = 1.0f; + } // Check for table values else if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id)) { @@ -7299,7 +7907,9 @@ int32 Unit::SpellBonusWithCoeffs(SpellEntry const* spellProto, int32 total, int3 if (GetTypeId() == TYPEID_PLAYER && spellProto->GetSpellFamilyName() == SPELLFAMILY_DEATHKNIGHT) { if (SpellEntry const* spell = ((Player*)this)->GetKnownTalentRankById(2005)) + { ap_bonus += ((spell->CalculateSimpleValue(EFFECT_INDEX_0) * ap_bonus) / 100.0f); + } } total += int32(ap_bonus * (GetTotalAttackPowerValue(IsSpellRequiresRangedAP(spellProto) ? RANGED_ATTACK : BASE_ATTACK) + ap_benefit)); @@ -7307,7 +7917,9 @@ int32 Unit::SpellBonusWithCoeffs(SpellEntry const* spellProto, int32 total, int3 } // Default calculation else if (benefit) + { coeff = CalculateDefaultCoefficient(spellProto, damagetype) * defCoeffMod; + } if (benefit) { @@ -7353,7 +7965,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u // Creature damage if (GetTypeId() == TYPEID_UNIT && !((Creature*)this)->IsPet()) + { DoneTotalMod *= ((Creature*)this)->_GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->Rank); + } AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); for (AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) @@ -7387,7 +8001,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u for (Unit::AuraList::const_iterator itr = doneFromManaPctAuras.begin(); itr != doneFromManaPctAuras.end(); ++itr) { if (GetSpellSchoolMask(spellProto) & (*itr)->GetModifier()->m_miscvalue) + { DoneTotalMod *= (100.0f + (*itr)->GetModifier()->m_amount * powerPct) / 100.0f; + } } } } @@ -7395,13 +8011,17 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u // done scripted mod (take it from owner) Unit* owner = GetOwner(); if (!owner) + { owner = this; + } AuraList const& mOverrideClassScript = owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->isAffectedOnSpell(spellProto)) + { continue; + } switch ((*i)->GetModifier()->m_miscvalue) { // Molten Fury @@ -7412,7 +8032,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u case 6928: { if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT)) + { DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + } break; } // Soul Siphon @@ -7431,7 +8053,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u SpellEntry const* m_spell = itr->second->GetSpellProto(); SpellClassOptionsEntry const* itrClassOptions = m_spell->GetSpellClassOptions(); if (itrClassOptions && (itrClassOptions->SpellFamilyName != SPELLFAMILY_WARLOCK || !(itrClassOptions->SpellFamilyFlags & UI64LIT(0x0004071B8044C402)))) + { continue; + } modPercent += stepPercent * itr->second->GetStackAmount(); if (modPercent >= maxPercent) { @@ -7446,12 +8070,16 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u case 6925: case 6927: if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT)) + { DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + } break; case 5481: // Starfire Bonus { if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x0000000000200002))) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } case 4418: // Increased Shock Damage @@ -7474,13 +8102,17 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u if ((*i)->GetSpellProto()->GetSpellIconID() == 2656) { if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT)) + { DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + } } else // Tundra Stalker { // Frost Fever (target debuff) if (pVictim->GetAura(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002)) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } break; @@ -7488,14 +8120,18 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u case 7293: // Rage of Rivendare { if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000))) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } // Twisted Faith case 7377: { if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000000000008000), 0, GetObjectGuid())) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } // Marked for Death @@ -7506,7 +8142,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u case 7602: { if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400))) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } } @@ -7530,7 +8168,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u if (pVictim->getLevel() > getLevel()) // Glyph of Ice Lance if (Aura* glyph = GetDummyAura(56377)) + { multiplier = glyph->GetModifier()->m_amount; + } DoneTotalMod *= multiplier; } @@ -7558,7 +8198,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000004000)) { if (pVictim->GetHealth() * 100 / pVictim->GetMaxHealth() <= 25) + { DoneTotalMod *= 4; + } } break; } @@ -7571,7 +8213,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x00100000))) // Glyph of Smite if (Aura* aur = GetAura(55692, EFFECT_INDEX_0)) + { DoneTotalMod *= (aur->GetModifier()->m_amount + 100.0f) / 100.0f; + } } // Shadow word: Death else if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000200000000))) @@ -7582,7 +8226,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u Aura const* hpPct = glyph->GetAuraByEffectIndex(EFFECT_INDEX_0); Aura const* dmPct = glyph->GetAuraByEffectIndex(EFFECT_INDEX_1); if (hpPct && dmPct && pVictim->GetHealth() * 100 <= pVictim->GetMaxHealth() * hpPct->GetModifier()->m_amount) + { DoneTotalMod *= (dmPct->GetModifier()->m_amount + 100.0f) / 100.0f; + } } } break; @@ -7625,7 +8271,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u } } if (!found) + { break; + } // search for Glacier Rot dummy aura Unit::AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY); @@ -7642,7 +8290,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x00002000)) { if (Aura* sigil = GetDummyAura(64962)) + { DoneTotal += sigil->GetModifier()->m_amount; + } } break; } @@ -7656,7 +8306,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u // Pets just add their bonus damage to their spell damage // note that their spell damage is just gain of their own auras if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + { DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage(); + } // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true); @@ -7664,7 +8316,9 @@ uint32 Unit::SpellDamageBonusDone(Unit* pVictim, SpellEntry const* spellProto, u float tmpDamage = (int32(pdamage) + DoneTotal * int32(stack)) * DoneTotalMod; // apply spellmod to Done damage (flat and pct) if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage); + } return tmpDamage > 0 ? uint32(tmpDamage) : 0; } @@ -7699,7 +8353,9 @@ uint32 Unit::SpellDamageBonusTaken(Unit* pCaster, SpellEntry const* spellProto, if ((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) { if (GetTypeId() != TYPEID_PLAYER) + { continue; + } TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; } @@ -7713,7 +8369,9 @@ uint32 Unit::SpellDamageBonusTaken(Unit* pCaster, SpellEntry const* spellProto, case 47582: // Pain and Suffering (Rank 3) // Shadow Word: Death if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000200000000))) + { TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } } @@ -7723,7 +8381,9 @@ uint32 Unit::SpellDamageBonusTaken(Unit* pCaster, SpellEntry const* spellProto, for (AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i) { if ((*i)->GetCasterGuid() == pCaster->GetObjectGuid() && (*i)->isAffectedOnSpell(spellProto)) + { TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } } // Mod damage from spell mechanic @@ -7734,7 +8394,9 @@ uint32 Unit::SpellDamageBonusTaken(Unit* pCaster, SpellEntry const* spellProto, { TakenTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, schoolMask); if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + { TakenTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_PET_AOE_DAMAGE_AVOIDANCE, schoolMask); + } } // Taken fixed damage bonus auras @@ -7757,7 +8419,9 @@ int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) { for (Unit::AuraList::const_iterator itr = mOverrideSpellPowerAuras.begin(); itr != mOverrideSpellPowerAuras.end(); ++itr) if (schoolMask & (*itr)->GetModifier()->m_miscvalue) + { DoneAdvertisedBenefit += (*itr)->GetModifier()->m_amount; + } return int32(GetTotalAttackPowerValue(BASE_ATTACK) * (100.0f + DoneAdvertisedBenefit) / 100.0f); } @@ -7779,7 +8443,9 @@ int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) DoneAdvertisedBenefit += ((Player*)this)->GetBaseSpellPowerBonus(); if (GetPowerIndex(POWER_MANA) != INVALID_POWER_INDEX) + { DoneAdvertisedBenefit += std::max(0, int32(GetStat(STAT_INTELLECT)) - 10); // spellpower from intellect + } // Damage bonus from stats AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT); @@ -7797,7 +8463,9 @@ int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) for (AuraList::const_iterator i = mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i) { if ((*i)->GetModifier()->m_miscvalue & schoolMask) + { DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f); + } } } @@ -7806,7 +8474,9 @@ int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) for (Unit::AuraList::const_iterator itr = mSpellPowerPctAuras.begin(); itr != mSpellPowerPctAuras.end(); ++itr) { if (!(*itr)->GetModifier()->m_miscvalue || (*itr)->GetModifier()->m_miscvalue & schoolMask) + { DoneAdvertisedBenefit = int32(DoneAdvertisedBenefit * (100.0f + (*itr)->GetModifier()->m_amount) / 100.0f); + } } return DoneAdvertisedBenefit; @@ -7821,7 +8491,9 @@ int32 Unit::SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask) for (AuraList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) { if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0) + { TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount; + } } return TakenAdvertisedBenefit; @@ -7853,10 +8525,14 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM case SPELL_DAMAGE_CLASS_MAGIC: { if (schoolMask & SPELL_SCHOOL_MASK_NORMAL) + { crit_chance = 0.0f; + } // For other schools else if (GetTypeId() == TYPEID_PLAYER) + { crit_chance = GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask)); + } else { crit_chance = float(m_baseSpellCritChance); @@ -7879,29 +8555,41 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!((*i)->isAffectedOnSpell(spellProto))) + { continue; + } switch ((*i)->GetModifier()->m_miscvalue) { case 849: // Shatter Rank 1 if (pVictim->IsFrozen() || IsIgnoreUnitState(spellProto, IGNORE_UNIT_TARGET_NON_FROZEN)) + { crit_chance += 17.0f; + } break; case 910: // Shatter Rank 2 if (pVictim->IsFrozen() || IsIgnoreUnitState(spellProto, IGNORE_UNIT_TARGET_NON_FROZEN)) + { crit_chance += 34.0f; + } break; case 911: // Shatter Rank 3 if (pVictim->IsFrozen() || IsIgnoreUnitState(spellProto, IGNORE_UNIT_TARGET_NON_FROZEN)) + { crit_chance += 50.0f; + } break; case 7917: // Glyph of Shadowburn if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT)) + { crit_chance += (*i)->GetModifier()->m_amount; + } break; case 7997: // Renewed Hope case 7998: if (pVictim->HasAura(6788)) + { crit_chance += (*i)->GetModifier()->m_amount; + } break; default: break; @@ -7920,7 +8608,9 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM // Glyph of Fire Blast if (pVictim->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED) || pVictim->IsInRoots()) if (Aura* aura = GetAura(56369, EFFECT_INDEX_0)) + { crit_chance += aura->GetModifier()->m_amount; + } } break; } @@ -7929,7 +8619,9 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000800))) { if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 2) + { break; + } AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY); for (AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) { @@ -7968,7 +8660,9 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM { Aura* aura = pVictim->GetDummyAura(58597); if (aura && aura->GetCasterGuid() == GetObjectGuid()) + { crit_chance += aura->GetModifier()->m_amount; + } } // Exorcism else if (spellProto->GetCategory() == 19) @@ -7998,7 +8692,9 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM case SPELL_DAMAGE_CLASS_RANGED: { if (pVictim) + { crit_chance = GetUnitCriticalChance(attackType, pVictim); + } crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); break; @@ -8009,7 +8705,9 @@ bool Unit::IsSpellCrit(Unit* pVictim, SpellEntry const* spellProto, SpellSchoolM // percent done // only players use intelligence for critical chance computations if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance); + } crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f; if (roll_chance_f(crit_chance)) @@ -8040,7 +8738,9 @@ uint32 Unit::SpellCriticalDamageBonus(SpellEntry const* spellProto, uint32 damag // adds additional damage to crit_bonus (from talents) if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); + } if (!pVictim) { @@ -8051,18 +8751,28 @@ uint32 Unit::SpellCriticalDamageBonus(SpellEntry const* spellProto, uint32 damag if(spellProto->GetDmgClass() >= SPELL_DAMAGE_CLASS_MELEE) { if (GetWeaponAttackType(spellProto) == RANGED_ATTACK) + { critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE); + } else + { critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE); + } } else + { critPctDamageMod += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE, GetSpellSchoolMask(spellProto)); + } if (critPctDamageMod != 0) + { crit_bonus = int32(crit_bonus * float((100.0f + critPctDamageMod) / 100.0f)); + } if (crit_bonus > 0) + { damage += crit_bonus; + } return damage; } @@ -8073,7 +8783,9 @@ uint32 Unit::SpellCriticalHealingBonus(SpellEntry const* spellProto, uint32 dama int32 crit_bonus = damage; if (crit_bonus > 0) + { damage += crit_bonus; + } damage = int32(damage * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT)); @@ -8117,17 +8829,25 @@ uint32 Unit::SpellHealingBonusDone(Unit* pVictim, SpellEntry const* spellProto, float healthPct = std::max(0.0f, 1.0f - float(pVictim->GetHealth()) / pVictim->GetMaxHealth()); for (AuraList::const_iterator i = mHealingFromHealthPct.begin();i != mHealingFromHealthPct.end(); ++i) if ((*i)->isAffectedOnSpell(spellProto)) + { DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount * healthPct) / 100.0f; + } } // done scripted mod (take it from owner) Unit* owner = GetOwner(); - if (!owner) owner = this; + if (!owner) + { + owner = this; + } AuraList const& mOverrideClassScript = owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->isAffectedOnSpell(spellProto)) + { continue; + } switch ((*i)->GetModifier()->m_miscvalue) { case 4415: // Increased Rejuvenation Healing @@ -8138,18 +8858,24 @@ uint32 Unit::SpellHealingBonusDone(Unit* pVictim, SpellEntry const* spellProto, case 7997: // Renewed Hope case 7998: if (pVictim->HasAura(6788)) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; case 21: // Test of Faith case 6935: case 6918: if (pVictim->GetHealth() < pVictim->GetMaxHealth() / 2) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; case 7798: // Glyph of Regrowth { if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, UI64LIT(0x0000000000000040))) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } case 8477: // Nourish Heal Boost @@ -8165,13 +8891,17 @@ uint32 Unit::SpellHealingBonusDone(Unit* pVictim, SpellEntry const* spellProto, ++ownHotCount; if (ownHotCount) + { DoneTotalMod *= (stepPercent * ownHotCount + 100.0f) / 100.0f; + } break; } case 7871: // Glyph of Lesser Healing Wave { if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, UI64LIT(0x0000040000000000), 0, GetObjectGuid())) + { DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } default: @@ -8195,7 +8925,9 @@ uint32 Unit::SpellHealingBonusDone(Unit* pVictim, SpellEntry const* spellProto, DoneTotalMod *= 1.2f; // base bonus at HoTs if (Aura* glyph = GetAura(62971, EFFECT_INDEX_0))// Glyph of Nourish + { DoneTotalMod *= (glyph->GetModifier()->m_amount * ownHotCount + 100.0f) / 100.0f; + } } // Lifebloom else if (spellProto->IsFitToFamilyMask(UI64LIT(0x0000001000000000))) @@ -8224,7 +8956,9 @@ uint32 Unit::SpellHealingBonusDone(Unit* pVictim, SpellEntry const* spellProto, float heal = (healamount + DoneTotal * int32(stack)) * DoneTotalMod; // apply spellmod to Done amount if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal); + } return heal < 0 ? 0 : uint32(heal); } @@ -8240,12 +8974,16 @@ uint32 Unit::SpellHealingBonusTaken(Unit* pCaster, SpellEntry const* spellProto, // Healing taken percent float minval = float(GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT)); if (minval) + { TakenTotalMod *= (100.0f + minval) / 100.0f; + } float maxval = float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT)); // no SPELL_AURA_MOD_PERIODIC_HEAL positive cases if (maxval) + { TakenTotalMod *= (100.0f + maxval) / 100.0f; + } // No heal amount for this class spells if (spellProto->GetDmgClass() == SPELL_DAMAGE_CLASS_NONE) @@ -8267,7 +9005,9 @@ uint32 Unit::SpellHealingBonusTaken(Unit* pCaster, SpellEntry const* spellProto, AuraList const& mHealingGet = GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED); for (AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i) if ((*i)->isAffectedOnSpell(spellProto)) + { TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } // use float as more appropriate for negative values and percent applying float heal = (healamount + TakenTotal * int32(stack)) * TakenTotalMod; @@ -8284,7 +9024,9 @@ int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) { for (Unit::AuraList::const_iterator itr = mOverrideSpellPowerAuras.begin(); itr != mOverrideSpellPowerAuras.end(); ++itr) if (schoolMask & (*itr)->GetModifier()->m_miscvalue) + { AdvertisedBenefit += (*itr)->GetModifier()->m_amount; + } return int32(GetTotalAttackPowerValue(BASE_ATTACK) * (100.0f + AdvertisedBenefit) / 100.0f); } @@ -8292,7 +9034,9 @@ int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE); for (AuraList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i) if (!(*i)->GetModifier()->m_miscvalue || ((*i)->GetModifier()->m_miscvalue & schoolMask) != 0) + { AdvertisedBenefit += (*i)->GetModifier()->m_amount; + } // Healing bonus of spirit, intellect and strength if (GetTypeId() == TYPEID_PLAYER) @@ -8301,7 +9045,9 @@ int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) AdvertisedBenefit += ((Player*)this)->GetBaseSpellPowerBonus(); if (GetPowerIndex(POWER_MANA) != INVALID_POWER_INDEX) + { AdvertisedBenefit += std::max(0, int32(GetStat(STAT_INTELLECT)) - 10); // spellpower from intellect + } // Healing bonus from stats AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT); @@ -8316,7 +9062,9 @@ int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER); for (AuraList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i) if ((*i)->GetModifier()->m_miscvalue & schoolMask) + { AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f); + } } // pct spell power modifier @@ -8324,7 +9072,9 @@ int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) for (Unit::AuraList::const_iterator itr = mSpellPowerPctAuras.begin(); itr != mSpellPowerPctAuras.end(); ++itr) { if (!(*itr)->GetModifier()->m_miscvalue || (*itr)->GetModifier()->m_miscvalue & schoolMask) + { AdvertisedBenefit = int32(AdvertisedBenefit * (100.0f + (*itr)->GetModifier()->m_amount) / 100.0f); + } } return AdvertisedBenefit; @@ -8336,7 +9086,9 @@ int32 Unit::SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask) AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_HEALING); for (AuraList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) if ((*i)->GetModifier()->m_miscvalue & schoolMask) + { AdvertisedBenefit += (*i)->GetModifier()->m_amount; + } return AdvertisedBenefit; } @@ -8509,7 +9261,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp // Pets just add their bonus damage to their melee damage if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + { DoneFlat += ((Pet*)this)->GetBonusDamage(); + } } // ..done flat (by creature type mask) @@ -8547,7 +9301,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp } if (attType == OFF_ATTACK) + { DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required + } } if (!spellProto) @@ -8571,7 +9327,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp // ============================================= Unit* owner = GetOwner(); if (!owner) + { owner = this; + } // ..done (class scripts) if (spellProto) @@ -8580,7 +9338,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { if (!(*i)->isAffectedOnSpell(spellProto)) + { continue; + } switch ((*i)->GetModifier()->m_miscvalue) { @@ -8592,13 +9352,17 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp if ((*i)->GetSpellProto()->GetSpellIconID() == 2656) { if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT)) + { DonePercent *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + } } else // Tundra Stalker { // Frost Fever (target debuff) if (pVictim->GetAura(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002)) + { DonePercent *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } break; @@ -8606,7 +9370,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp case 7293: // Rage of Rivendare { if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000))) + { DonePercent *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } // Marked for Death @@ -8617,7 +9383,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp case 7602: { if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400))) + { DonePercent *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } break; } } @@ -8689,7 +9457,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp if (Aura* aur = GetDummyAura(56826)) // check for Serpent Sting at target if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000004000))) + { DonePercent *= (aur->GetModifier()->m_amount + 100.0f) / 100.0f; + } } } @@ -8733,7 +9503,9 @@ uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackTyp if (spellProto) { if (Player* modOwner = GetSpellModOwner()) + { modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage); + } } // bonus result can be negative @@ -8764,7 +9536,9 @@ uint32 Unit::MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage, WeaponAttackTy // Shred also have bonus as MECHANIC_BLEED damages SpellClassOptionsEntry const* classOptions = spellProto ? spellProto->GetSpellClassOptions() : NULL; if (classOptions && classOptions->SpellFamilyName==SPELLFAMILY_DRUID && classOptions->SpellFamilyFlags & UI64LIT(0x00008000)) + { mechanicMask |= (1 << (MECHANIC_BLEED-1)); + } // FLAT damage bonus auras // ======================= @@ -8772,9 +9546,13 @@ uint32 Unit::MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage, WeaponAttackTy // ..taken flat (base at attack power for marked target and base at attack power for creature type) if (attType == RANGED_ATTACK) + { TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN); + } else + { TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN); + } // ..taken flat (by school mask) TakenFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask); @@ -8791,16 +9569,22 @@ uint32 Unit::MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage, WeaponAttackTy // ..taken pct (melee/ranged) if (attType == RANGED_ATTACK) + { TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT); + } else + { TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT); + } // ..taken pct (aoe avoidance) if (spellProto && IsAreaOfEffectSpell(spellProto)) { TakenPercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, schoolMask); if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + { TakenPercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_PET_AOE_DAMAGE_AVOIDANCE, schoolMask); + } } // special dummys/class scripts and other effects @@ -8816,7 +9600,9 @@ uint32 Unit::MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage, WeaponAttackTy if ((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL) { if (GetTypeId() != TYPEID_PLAYER) + { continue; + } TakenPercent *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; } @@ -8880,7 +9666,9 @@ void Unit::ApplySpellDispelImmunity(const SpellEntry* spellProto, DispelType typ ApplySpellImmune(spellProto->Id, IMMUNITY_DISPEL, type, apply); if (apply && spellProto->HasAttribute(SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) + { RemoveAurasWithDispelType(type); + } } float Unit::GetWeaponProcChance() const @@ -8926,13 +9714,17 @@ void Unit::Mount(uint32 mount, uint32 spellId) { // Called by Taxi system / GM command if (!spellId) + { ((Player*)this)->UnsummonPetTemporaryIfAny(); + } // Called by mount aura else if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId)) { // Flying case (Unsummon any pet) if (IsSpellHaveAura(spellInfo, SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED)) + { ((Player*)this)->UnsummonPetTemporaryIfAny(); + } // Normal case (Unsummon only permanent pet) else if (Pet* pet = GetPet()) { @@ -8940,13 +9732,17 @@ void Unit::Mount(uint32 mount, uint32 spellId) || sWorld.getConfig(CONFIG_BOOL_PET_UNSUMMON_AT_MOUNT))) ((Player*)this)->UnsummonPetTemporaryIfAny(); else + { pet->SetModeFlags(PET_MODE_DISABLE_ACTIONS); + } } } float height = ((Player*)this)->GetCollisionHeight(true); if (height) + { SendCollisionHeightUpdate(height); + } } } @@ -8979,14 +9775,20 @@ void Unit::Unmount(bool from_aura) { // Get reaction state and display appropriately if (CharmInfo* charmInfo = pet->GetCharmInfo()) + { pet->SetModeFlags(PetModeFlags(charmInfo->GetReactState() | charmInfo->GetCommandState() * 0x100)); + } } else + { ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny(); + } float height = ((Player*)this)->GetCollisionHeight(false); if (height) + { SendCollisionHeightUpdate(height); + } } } @@ -9005,25 +9807,37 @@ bool Unit::IsNearWaypoint(float currentPositionX, float currentPositionY, float if (distanceX > 0) { if (currentPositionX > destinationPostionX) + { xDifference = currentPositionX - destinationPostionX; + } else + { xDifference = destinationPostionX - currentPositionX; + } } // distanceY == 0, means do not test the distance between the creature's current Y ordinate and the destination Y ordinate if (distanceY > 0) { if (currentPositionY > destinationPostionY) + { yDifference = currentPositionY - destinationPostionY; + } else + { yDifference = destinationPostionY - currentPositionY; + } } // distanceZ == 0, means do not test the distance between the creature's current Z ordinate and the destination Z ordinate if (distanceZ > 0) { if (currentPositionZ > destinationPostionZ) + { zDifference = currentPositionZ - destinationPostionZ; + } else + { zDifference = destinationPostionZ - currentPositionZ; + } } // check based on which ordinates to test the current distance from (distance along the X, and/or Y, and/or Z ordinates) @@ -9066,38 +9880,56 @@ MountCapabilityEntry const* Unit::GetMountCapability(uint32 mountType) const { MountCapabilityEntry const* mountCapability = sMountCapabilityStore.LookupEntry(mountTypeEntry->MountCapability[i - 1]); if (!mountCapability) + { continue; + } if (ridingSkill < mountCapability->RequiredRidingSkill) + { continue; + } if (m_movementInfo.HasMovementFlag2(MOVEFLAG2_FULLSPEEDPITCHING)) { if (!(mountCapability->Flags & MOUNT_FLAG_CAN_PITCH)) + { continue; + } } else if (m_movementInfo.HasMovementFlag(MOVEFLAG_SWIMMING)) { if (!(mountCapability->Flags & MOUNT_FLAG_CAN_SWIM)) + { continue; + } } else if (!(mountCapability->Flags & 0x1)) // unknown flags, checked in 4.2.2 14545 client { if (!(mountCapability->Flags & 0x2)) + { continue; + } } if (mountCapability->RequiredMap != -1 && int32(GetMapId()) != mountCapability->RequiredMap) + { continue; + } if (mountCapability->RequiredArea && (mountCapability->RequiredArea != zoneId && mountCapability->RequiredArea != areaId)) + { continue; + } if (mountCapability->RequiredAura && !HasAura(mountCapability->RequiredAura)) + { continue; + } if (mountCapability->RequiredSpell && (GetTypeId() != TYPEID_PLAYER || !(Player*)(this)->HasSpell(mountCapability->RequiredSpell))) + { continue; + } return mountCapability; } @@ -9169,7 +10001,9 @@ void Unit::SetInCombatState(bool PvP, Unit* enemy) } if (getRace() == RACE_WORGEN && !IsInWorgenForm(true) && HasWorgenForm()) + { CastSpell(this, 97709, true); // cast Altered Form + } if (creatureNotInCombat) { @@ -9178,7 +10012,9 @@ void Unit::SetInCombatState(bool PvP, Unit* enemy) // client does not handle this state on it's own (reset to default at LoadCreatureAddon) if (getStandState() == UNIT_STAND_STATE_CUSTOM) + { SetStandState(UNIT_STAND_STATE_STAND); + } Creature* pCreature = (Creature*)this; @@ -9207,7 +10043,9 @@ void Unit::SetInCombatState(bool PvP, Unit* enemy) // Used by Eluna #ifdef ENABLE_ELUNA if (GetTypeId() == TYPEID_PLAYER) + { sEluna->OnPlayerEnterCombat(ToPlayer(), enemy); + } #endif /* ENABLE_ELUNA */ } @@ -9224,7 +10062,9 @@ void Unit::ClearInCombat() // Used by Eluna #ifdef ENABLE_ELUNA if (GetTypeId() == TYPEID_PLAYER) + { sEluna->OnPlayerLeaveCombat(ToPlayer()); + } #endif /* ENABLE_ELUNA */ // Player's state will be cleared in Player::UpdateContestedPvP @@ -9232,12 +10072,16 @@ void Unit::ClearInCombat() { Creature* cThis = static_cast(this); if (cThis->GetCreatureInfo()->UnitFlags & UNIT_FLAG_OOC_NOT_ATTACKABLE && !(cThis->GetTemporaryFactionFlags() & TEMPFACTION_TOGGLE_OOC_NOT_ATTACK)) + { SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); + } clearUnitState(UNIT_STAT_ATTACK_PLAYER); } else + { ((Player*)this)->UpdatePotionCooldown(); + } } bool Unit::IsTargetableForAttack(bool inverseAlive /*=false*/) const @@ -9380,7 +10224,9 @@ bool Unit::IsVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, boo // if player is dead then he can't detect anyone in any cases if (!u->IsAlive()) + { detect = false; + } } else { @@ -9569,7 +10415,9 @@ bool Unit::IsVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, boo // This allows to check talent tree and will add addition stealth dependent on used points) int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL); if (stealthMod < 0) + { stealthMod = 0; + } //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia) // based on wowwiki every 5 mod we have 1 more level diff in calculation @@ -9597,7 +10445,9 @@ void Unit::UpdateVisibilityAndView() { AuraList& alist = m_modAuras[*type]; if (alist.empty()) + { continue; + } for (AuraList::iterator it = alist.begin(); it != alist.end();) { @@ -9611,7 +10461,9 @@ void Unit::UpdateVisibilityAndView() it = alist.begin(); } else + { ++it; + } } } @@ -9626,7 +10478,9 @@ void Unit::SetVisibility(UnitVisibility x) m_Visibility = x; if (IsInWorld()) + { UpdateVisibilityAndView(); + } } bool Unit::canDetectInvisibilityOf(Unit const* u) const @@ -9636,24 +10490,32 @@ bool Unit::canDetectInvisibilityOf(Unit const* u) const for (int32 i = 0; i < 32; ++i) { if (((1 << i) & mask) == 0) + { continue; + } // find invisibility level int32 invLevel = 0; Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY); for (Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr) if ((*itr)->GetModifier()->m_miscvalue == i && invLevel < (*itr)->GetModifier()->m_amount) + { invLevel = (*itr)->GetModifier()->m_amount; + } // find invisibility detect level int32 detectLevel = 0; Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION); for (Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr) if ((*itr)->GetModifier()->m_miscvalue == i && detectLevel < (*itr)->GetModifier()->m_amount) + { detectLevel = (*itr)->GetModifier()->m_amount; + } if (i == 6 && GetTypeId() == TYPEID_PLAYER) // special drunk detection case + { detectLevel = ((Player*)this)->GetDrunkValue(); + } if (invLevel <= detectLevel) { @@ -9759,7 +10621,9 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced, float ratio, bool ignore // Use speed from aura float max_speed = normalization / baseMoveSpeed[mtype]; if (speed > max_speed) + { speed = max_speed; + } } break; } @@ -9771,13 +10635,17 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced, float ratio, bool ignore if (GetTypeId() == TYPEID_UNIT) { if (((Creature*)this)->HasSearchedAssistance()) + { speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk". + } } // for player case, we look for some custom rates else { if (getDeathState() == CORPSE) + { speed *= sWorld.getConfig(((Player*)this)->InBattleGround() ? CONFIG_FLOAT_GHOST_RUN_SPEED_BG : CONFIG_FLOAT_GHOST_RUN_SPEED_WORLD); + } } // Apply strongest slow aura mod to speed @@ -9787,7 +10655,9 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced, float ratio, bool ignore speed *= (100.0f + slow) / 100.0f; float min_speed = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED) / 100.0f; if (speed < min_speed) + { speed = min_speed; + } } if (GetTypeId() == TYPEID_UNIT) @@ -9824,7 +10694,9 @@ struct SetSpeedRateHelper void Unit::SetSpeedRate(UnitMoveType mtype, float rate, bool forced, bool ignoreChange) { if (rate < 0) + { rate = 0.0f; + } // Update speed only on change if (m_speed_rate[mtype] != rate || ignoreChange) @@ -10051,7 +10923,9 @@ void Unit::SetDeathState(DeathState s) ClearComboPointHolders(); // any combo points pointed to unit lost at it death if (IsNonMeleeSpellCasted(false)) + { InterruptNonMeleeSpells(false); + } } if (s == JUST_DIED) @@ -10067,11 +10941,15 @@ void Unit::SetDeathState(DeathState s) // Unsummon vehicle accessories if (IsVehicle()) + { m_vehicleInfo->RemoveAccessoriesFromMap(); + } // Unboard from transport if (GetTransportInfo() && ((Unit*)GetTransportInfo()->GetTransport())->IsVehicle()) + { ((Unit*)GetTransportInfo()->GetTransport())->RemoveSpellsCausingAura(SPELL_AURA_CONTROL_VEHICLE, GetObjectGuid()); + } ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false); ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false); @@ -10159,7 +11037,9 @@ void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false { // Only mobs can manage threat lists if (CanHaveThreatList()) + { m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell); + } } //====================================================================== @@ -10167,7 +11047,9 @@ void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false void Unit::DeleteThreatList() { if (CanHaveThreatList(true) && !m_ThreatManager.isThreatListEmpty()) + { SendThreatClear(); + } m_ThreatManager.clearReferences(); } @@ -10199,10 +11081,14 @@ void Unit::TauntApply(Unit* taunter) if (!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_DIED) && !IsSecondChoiceTarget(taunter, true)) { if (GetTargetGuid() || !target) + { SetInFront(taunter); + } if (((Creature*)this)->AI()) + { ((Creature*)this)->AI()->AttackStart(taunter); + } } m_ThreatManager.tauntApply(taunter); @@ -10236,13 +11122,19 @@ void Unit::TauntFadeOut(Unit* taunter) m_fixateTargetGuid.Clear(); if (((Creature*)this)->AI()) + { ((Creature*)this)->AI()->EnterEvadeMode(); + } if (InstanceData* mapInstance = GetInstanceData()) + { mapInstance->OnCreatureEvade((Creature*)this); + } if (m_isCreatureLinkingTrigger) + { GetMap()->GetCreatureLinkingHolder()->DoCreatureLinkingEvent(LINKING_EVENT_EVADE, (Creature*)this); + } return; } @@ -10253,10 +11145,14 @@ void Unit::TauntFadeOut(Unit* taunter) if (target && target != taunter) { if (GetTargetGuid()) + { SetInFront(target); + } if (((Creature*)this)->AI()) + { ((Creature*)this)->AI()->AttackStart(target); + } } } @@ -10265,9 +11161,13 @@ void Unit::TauntFadeOut(Unit* taunter) void Unit::FixateTarget(Unit* pVictim) { if (!pVictim) // Remove Fixation + { m_fixateTargetGuid.Clear(); + } else if (pVictim->IsTargetableForAttack()) // Apply Fixation + { m_fixateTargetGuid = pVictim->GetObjectGuid(); + } // Start attacking the fixated target or the next proper one SelectHostileTarget(); @@ -10313,12 +11213,16 @@ bool Unit::SelectHostileTarget() if (m_fixateTargetGuid) { if (oldTarget && oldTarget->GetObjectGuid() == m_fixateTargetGuid) + { target = oldTarget; + } else { Unit* pFixateTarget = GetMap()->GetUnit(m_fixateTargetGuid); if (pFixateTarget && pFixateTarget->IsAlive() && !IsSecondChoiceTarget(pFixateTarget, true)) + { target = pFixateTarget; + } } } // then checking if we have some taunt on us @@ -10343,7 +11247,9 @@ bool Unit::SelectHostileTarget() // No valid fixate target, taunt aura or taunt aura caster is dead, standard target selection if (!target && !m_ThreatManager.isThreatListEmpty()) + { target = m_ThreatManager.getHostileTarget(); + } if (target) { @@ -10351,7 +11257,9 @@ bool Unit::SelectHostileTarget() { SetInFront(target); if (oldTarget != target) + { ((Creature*)this)->AI()->AttackStart(target); + } // check if currently selected target is reachable // NOTE: path alrteady generated from AttackStart() @@ -10409,10 +11317,14 @@ bool Unit::SelectHostileTarget() ((Creature*)this)->AI()->EnterEvadeMode(); if (InstanceData* mapInstance = GetInstanceData()) + { mapInstance->OnCreatureEvade((Creature*)this); + } if (m_isCreatureLinkingTrigger) + { GetMap()->GetCreatureLinkingHolder()->DoCreatureLinkingEvent(LINKING_EVENT_EVADE, (Creature*)this); + } return false; } @@ -10489,7 +11401,9 @@ int32 Unit::CalculateSpellDamage(Unit const* target, SpellEntry const* spellProt { float Scale = gtScalingEntry->value; if (uint32(scalingEntry->castTimeMax) > 0 && uint32(scalingEntry->castScalingMaxLevel) > level) + { Scale *= float(scalingEntry->castTimeMin + float(level - 1) * (scalingEntry->castTimeMax - scalingEntry->castTimeMin) / (scalingEntry->castScalingMaxLevel - 1)) / float(scalingEntry->castTimeMax); + } //if (uint32(scalingEntry->coefLevelBase) > level) // Scale *= (1.0f - scalingEntry->coefBase) * (level - 1) / (scalingEntry->coefLevelBase - 1) + scalingEntry->coefBase; @@ -10505,7 +11419,9 @@ int32 Unit::CalculateSpellDamage(Unit const* target, SpellEntry const* spellProt uint32 baseLevel = spellProto->GetBaseLevel(); if (maxLevel) + { level = std::min(level, maxLevel); + } level = std::max(level, baseLevel); level = std::max(level, spellLevel) - spellLevel; @@ -10579,7 +11495,9 @@ int32 Unit::CalculateAuraDuration(SpellEntry const* spellProto, uint32 effectMas for (int32 mechanic = FIRST_MECHANIC; mechanic < MAX_MECHANIC; ++mechanic) { if (!(mechanicMask & (1 << (mechanic - 1)))) + { continue; + } int32 stackingMod = GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic); int32 nonStackingMod = GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic); @@ -10603,7 +11521,9 @@ int32 Unit::CalculateAuraDuration(SpellEntry const* spellProto, uint32 effectMas duration = int32(int64(duration) * (100 + durationMod) / 100); if (duration < 0) + { duration = 0; + } } if (caster == this) @@ -10616,7 +11536,9 @@ int32 Unit::CalculateAuraDuration(SpellEntry const* spellProto, uint32 effectMas { // Glyph of Thorns if (Aura* aur = GetAura(57862, EFFECT_INDEX_0)) + { duration += aur->GetModifier()->m_amount * MINUTE * IN_MILLISECONDS; + } } break; case SPELLFAMILY_PALADIN: @@ -10625,20 +11547,26 @@ int32 Unit::CalculateAuraDuration(SpellEntry const* spellProto, uint32 effectMas { // Glyph of Blessing of Might if (Aura* aur = GetAura(57958, EFFECT_INDEX_0)) + { duration += aur->GetModifier()->m_amount * MINUTE * IN_MILLISECONDS; + } } // Blessing of Wisdom else if (spellProto->GetSpellIconID() == 306 && spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000010000))) { // Glyph of Blessing of Wisdom if (Aura* aur = GetAura(57979, EFFECT_INDEX_0)) + { duration += aur->GetModifier()->m_amount * MINUTE * IN_MILLISECONDS; + } } // Inquisition else if (spellProto->Id == 84963) { if (spell && GetPowerIndex(POWER_HOLY_POWER) != INVALID_POWER_INDEX) + { duration *= spell->GetUsedHolyPower(); + } } break; default: @@ -10654,7 +11582,9 @@ DiminishingLevels Unit::GetDiminishing(DiminishingGroup group) for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) { if (i->DRGroup != group) + { continue; + } if (!i->hitCount) { @@ -10687,9 +11617,13 @@ void Unit::IncrDiminishing(DiminishingGroup group) for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) { if (i->DRGroup != group) + { continue; + } if (i->hitCount < DIMINISHING_LEVEL_IMMUNE) + { i->hitCount += 1; + } return; } m_Diminishing.push_back(DiminishingReturn(group, WorldTimer::getMSTime(), DIMINISHING_LEVEL_2)); @@ -10713,7 +11647,9 @@ void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32& duration, U Unit const* source = casterOwner ? casterOwner : caster; if (target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER) + { duration = limitduration; + } } float mod = 1.0f; @@ -10741,16 +11677,22 @@ void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) { if (i->DRGroup != group) + { continue; + } if (apply) + { i->stack += 1; + } else if (i->stack) { i->stack -= 1; // Remember time after last aura from group removed if (i->stack == 0) + { i->hitTime = WorldTimer::getMSTime(); + } } break; } @@ -10817,7 +11759,9 @@ bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, f case BASE_PCT: case TOTAL_PCT: if (amount <= -100.0f) // small hack-fix for -100% modifiers + { amount = -200.0f; + } val = (100.0f + amount) / 100.0f; m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f / val); @@ -11017,14 +11961,18 @@ void Unit::SetLevel(uint32 lvl) // group update if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL); + } } void Unit::SetHealth(uint32 val) { uint32 maxHealth = GetMaxHealth(); if (maxHealth < val) + { val = maxHealth; + } SetUInt32Value(UNIT_FIELD_HEALTH, val); @@ -11032,7 +11980,9 @@ void Unit::SetHealth(uint32 val) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP); + } } else if (((Creature*)this)->IsPet()) { @@ -11041,7 +11991,9 @@ void Unit::SetHealth(uint32 val) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP); + } } } } @@ -11055,7 +12007,9 @@ void Unit::SetMaxHealth(uint32 val) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP); + } } else if (((Creature*)this)->IsPet()) { @@ -11064,12 +12018,16 @@ void Unit::SetMaxHealth(uint32 val) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP); + } } } if (val < health) + { SetHealth(val); + } } void Unit::SetHealthPercent(float percent) @@ -11160,10 +12118,14 @@ void Unit::SetPowerByIndex(uint32 powerIndex, int32 val) { int32 maxPower = GetMaxPowerByIndex(powerIndex); if (val > maxPower) + { val = maxPower; + } if (val < 0) + { val = 0; + } if (GetPowerByIndex(powerIndex) == val) { @@ -11191,7 +12153,9 @@ void Unit::SetPowerByIndex(uint32 powerIndex, int32 val) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); + } } else if (((Creature*)this)->IsPet()) { @@ -11200,13 +12164,17 @@ void Unit::SetPowerByIndex(uint32 powerIndex, int32 val) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER); + } } } // modifying holy power resets it's fade timer if (power == POWER_HOLY_POWER) + { ResetHolyPowerRegenTimer(); + } } void Unit::SetMaxPower(Powers power, int32 val) @@ -11235,7 +12203,9 @@ void Unit::SetMaxPowerByIndex(uint32 powerIndex, int32 val) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); + } } else if (((Creature*)this)->IsPet()) { @@ -11244,12 +12214,16 @@ void Unit::SetMaxPowerByIndex(uint32 powerIndex, int32 val) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER); + } } } if (val < cur_power) + { SetPowerByIndex(powerIndex, val); + } } void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply) @@ -11260,7 +12234,9 @@ void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); + } } else if (((Creature*)this)->IsPet()) { @@ -11269,7 +12245,9 @@ void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER); + } } } } @@ -11282,7 +12260,9 @@ void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply) if (GetTypeId() == TYPEID_PLAYER) { if (((Player*)this)->GetGroup()) + { ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); + } } else if (((Creature*)this)->IsPet()) { @@ -11291,7 +12271,9 @@ void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply) { Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER); + } } } } @@ -11300,9 +12282,13 @@ void Unit::ApplyAuraProcTriggerDamage(Aura* aura, bool apply) { AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE]; if (apply) + { tAuraProcTriggerDamage.push_back(aura); + } else + { tAuraProcTriggerDamage.remove(aura); + } } uint32 Unit::GetCreatePowers(Powers power) const @@ -11379,9 +12365,13 @@ void Unit::CleanupsBeforeDelete() ClearComboPointHolders(); DeleteThreatList(); if (GetTypeId() == TYPEID_PLAYER) + { GetHostileRefManager().setOnlineOfflineState(false); + } else + { GetHostileRefManager().deleteReferences(); + } RemoveAllAuras(AURA_REMOVE_BY_DELETE); } WorldObject::CleanupsBeforeDelete(); @@ -11390,7 +12380,9 @@ void Unit::CleanupsBeforeDelete() CharmInfo* Unit::InitCharmInfo(Unit* charm) { if (!m_charmInfo) + { m_charmInfo = new CharmInfo(charm); + } return m_charmInfo; } @@ -11444,9 +12436,13 @@ void CharmInfo::InitVehicleCreateSpells() for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) { if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x])) + { m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true); + } else + { AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ActiveStates(0x8 + x)); + } } } @@ -11464,9 +12460,13 @@ void CharmInfo::InitPossessCreateSpells() for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) { if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x])) + { m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true); + } else + { AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE); + } } } @@ -11507,15 +12507,23 @@ void CharmInfo::InitCharmCreateSpells() { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if(spellEffect->EffectImplicitTargetA != TARGET_SELF && spellEffect->EffectImplicitTargetA != 0) + { onlyselfcast = false; + } } if (onlyselfcast || !IsPositiveSpell(spellId)) // only self cast and spells versus enemies are autocastable + { newstate = ACT_DISABLED; + } else + { newstate = ACT_PASSIVE; + } AddSpellToActionBar(spellId, newstate); } @@ -11579,16 +12587,22 @@ void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply) for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) if (spellid == m_charmspells[x].GetAction()) + { m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED); + } } void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow) { m_petnumber = petnumber; if (statwindow) + { m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber); + } else + { m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0); + } } void CharmInfo::LoadPetActionBar(const std::string& data) @@ -11598,7 +12612,9 @@ void CharmInfo::LoadPetActionBar(const std::string& data) Tokens tokens = StrSplit(data, " "); if (tokens.size() != (ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_START) * 2) + { return; // non critical, will reset to default + } int index; Tokens::iterator iter; @@ -11613,7 +12629,9 @@ void CharmInfo::LoadPetActionBar(const std::string& data) // check correctness if (PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].GetAction())) + { SetActionBar(index, 0, ACT_DISABLED); + } } } @@ -11679,15 +12697,23 @@ uint32 createProcExtendMask(SpellNonMeleeDamage* damageInfo, SpellMissInfo missC { // On block if (damageInfo->blocked) + { procEx |= PROC_EX_BLOCK; + } // On absorb if (damageInfo->absorb) + { procEx |= PROC_EX_ABSORB; + } // On crit if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT) + { procEx |= PROC_EX_CRITICAL_HIT; + } else + { procEx |= PROC_EX_NORMAL_HIT; + } } return procEx; } @@ -11754,7 +12780,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, { // skip deleted auras (possible at recursive triggered call if (itr->second->GetState() != SPELLAURAHOLDER_STATE_READY || itr->second->IsDeleted()) + { continue; + } SpellProcEventEntry const* spellProcEvent = NULL; // check if that aura is triggered by proc event (then it will be managed by proc handler) @@ -11764,7 +12792,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, // only process damage case on victim if (!isVictim || !(procFlag & PROC_FLAG_TAKEN_ANY_DAMAGE)) + { continue; + } const SpellEntry* se = itr->second->GetSpellProto(); @@ -11789,7 +12819,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, // Some auras can be deleted in function called in this loop (except first, ofc) SpellAuraHolder* triggeredByHolder = itr->triggeredByHolder; if (triggeredByHolder->IsDeleted()) + { continue; + } SpellProcEventEntry const* spellProcEvent = itr->spellProcEvent; bool useCharges = triggeredByHolder->GetAuraCharges() > 0; @@ -11799,17 +12831,23 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, // For players set spell cooldown if need uint32 cooldown = 0; if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown) + { cooldown = spellProcEvent->cooldown; + } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { Aura* triggeredByAura = triggeredByHolder->GetAuraByEffectIndex(SpellEffectIndex(i)); if (!triggeredByAura) + { continue; + } SpellEffectEntry const* spellEffect = triggeredByHolder->GetSpellProto()->GetSpellEffect(SpellEffectIndex(i)); if (!spellEffect) + { continue; + } if (procSpell) { @@ -11818,24 +12856,34 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, if (spellProcEvent->spellFamilyMask[i]) { if (!procSpell->IsFitToFamilyMask(spellProcEvent->spellFamilyMask[i])) + { continue; + } // don't allow proc from cast end for non modifier spells // unless they have proc ex defined for that if (IsCastEndProcModifierAura(triggeredByHolder->GetSpellProto(), SpellEffectIndex(i), procSpell)) { if (useCharges && procExtra != PROC_EX_CAST_END && spellProcEvent->procEx == PROC_EX_NONE) + { continue; + } } else if (spellProcEvent->procEx == PROC_EX_NONE && procExtra == PROC_EX_CAST_END) + { continue; + } } // don't check dbc FamilyFlags if schoolMask exists else if (!triggeredByAura->CanProcFrom(procSpell, procFlag, spellProcEvent->procEx, procExtra, damage != 0, !spellProcEvent->schoolMask)) + { continue; + } } else if (!triggeredByAura->CanProcFrom(procSpell, procFlag, PROC_EX_NONE, procExtra, damage != 0, true)) + { continue; + } } SpellAuraProcResult procResult = (*this.*AuraProcHandler[spellEffect->EffectApplyAuraName])(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown); @@ -11858,7 +12906,9 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, { // If last charge dropped add spell to remove list if (triggeredByHolder->DropAuraCharge()) + { removedSpells.push_back(triggeredByHolder->GetId()); + } } triggeredByHolder->SetInUse(false); @@ -12007,18 +13057,26 @@ void Unit::SetFeared(bool apply, ObjectGuid casterGuid, uint32 spellID, uint32 t Creature* c = ((Creature*)this); // restore appropriate movement generator if (getVictim()) + { GetMotionMaster()->MoveChase(getVictim()); + } else + { GetMotionMaster()->Initialize(); + } // attack caster if can if (Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : NULL) + { c->AttackedBy(caster); + } } } if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SetClientControl(this, !apply); + } } void Unit::SetConfused(bool apply, ObjectGuid casterGuid, uint32 spellID) @@ -12041,14 +13099,20 @@ void Unit::SetConfused(bool apply, ObjectGuid casterGuid, uint32 spellID) { // restore appropriate movement generator if (getVictim()) + { GetMotionMaster()->MoveChase(getVictim()); + } else + { GetMotionMaster()->Initialize(); + } } } if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SetClientControl(this, !apply); + } } void Unit::SetFeignDeath(bool apply, ObjectGuid casterGuid, uint32 /*spellID*/) @@ -12063,9 +13127,13 @@ void Unit::SetFeignDeath(bool apply, ObjectGuid casterGuid, uint32 /*spellID*/) */ if (GetTypeId() != TYPEID_PLAYER) + { StopMoving(); + } else + { ((Player*)this)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE); + } // blizz like 2.0.x SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); @@ -12080,7 +13148,9 @@ void Unit::SetFeignDeath(bool apply, ObjectGuid casterGuid, uint32 /*spellID*/) // prevent interrupt message if (casterGuid == GetObjectGuid()) + { FinishSpell(CURRENT_GENERIC_SPELL, false); + } InterruptNonMeleeSpells(true); GetHostileRefManager().deleteReferences(); } @@ -12105,9 +13175,13 @@ void Unit::SetFeignDeath(bool apply, ObjectGuid casterGuid, uint32 /*spellID*/) { // restore appropriate movement generator if (getVictim()) + { GetMotionMaster()->MoveChase(getVictim()); + } else + { GetMotionMaster()->Initialize(); + } } } } @@ -12132,7 +13206,9 @@ void Unit::SetStandState(uint8 state) SetByteValue(UNIT_FIELD_BYTES_1, 0, state); if (IsStandState()) + { RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED); + } if (GetTypeId() == TYPEID_PLAYER) { @@ -12162,7 +13238,9 @@ void Unit::SetDisplayId(uint32 modelId) } Unit* owner = GetOwner(); if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID); + } } } @@ -12175,9 +13253,13 @@ void Unit::UpdateModelData() // never actually update combat_reach for player, it's always the same. Below player case is for initialization if (GetTypeId() == TYPEID_PLAYER) + { SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); + } else + { SetFloatValue(UNIT_FIELD_COMBATREACH, GetObjectScale() * modelInfo->combat_reach); + } } } @@ -12189,9 +13271,13 @@ void Unit::ClearComboPointHolders() Player* plr = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, lowguid)); if (plr && plr->GetComboTargetGuid() == GetObjectGuid())// recheck for safe + { plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders; + } else + { m_ComboPointHolders.erase(lowguid); // or remove manually + } } } @@ -12203,12 +13289,18 @@ void Unit::ClearAllReactives() } if (HasAuraState(AURA_STATE_DEFENSE)) + { ModifyAuraState(AURA_STATE_DEFENSE, false); + } if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) + { ModifyAuraState(AURA_STATE_HUNTER_PARRY, false); + } if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->ClearComboPoints(); + } } void Unit::UpdateReactives(uint32 p_time) @@ -12218,7 +13310,9 @@ void Unit::UpdateReactives(uint32 p_time) ReactiveType reactive = ReactiveType(i); if (!m_reactiveTimer[reactive]) + { continue; + } if (m_reactiveTimer[reactive] <= p_time) { @@ -12228,15 +13322,21 @@ void Unit::UpdateReactives(uint32 p_time) { case REACTIVE_DEFENSE: if (HasAuraState(AURA_STATE_DEFENSE)) + { ModifyAuraState(AURA_STATE_DEFENSE, false); + } break; case REACTIVE_HUNTER_PARRY: if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) + { ModifyAuraState(AURA_STATE_HUNTER_PARRY, false); + } break; case REACTIVE_OVERPOWER: if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->ClearComboPoints(); + } break; default: break; @@ -12259,7 +13359,9 @@ Unit* Unit::SelectRandomUnfriendlyTarget(Unit* except /*= NULL*/, float radius / // remove current target if (except) + { targets.remove(except); + } // remove not LoS targets for (std::list::iterator tIter = targets.begin(); tIter != targets.end();) @@ -12271,7 +13373,9 @@ Unit* Unit::SelectRandomUnfriendlyTarget(Unit* except /*= NULL*/, float radius / targets.erase(tIter2); } else + { ++tIter; + } } // no appropriate targets @@ -12302,7 +13406,9 @@ Unit* Unit::SelectRandomFriendlyTarget(Unit* except /*= NULL*/, float radius /*= // remove current target if (except) + { targets.remove(except); + } // remove not LoS targets for (std::list::iterator tIter = targets.begin(); tIter != targets.end();) @@ -12314,7 +13420,9 @@ Unit* Unit::SelectRandomFriendlyTarget(Unit* except /*= NULL*/, float radius /*= targets.erase(tIter2); } else + { ++tIter; + } } // no appropriate targets @@ -12363,9 +13471,13 @@ void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply void Unit::ApplyCastTimePercentMod(float val, bool apply) { if (val > 0) + { ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, val, !apply); + } else + { ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, -val, apply); + } } void Unit::UpdateAuraForGroup(uint8 slot) @@ -12403,7 +13515,9 @@ float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized) Item* Weapon = ((Player*)this)->GetWeaponForAttack(attType, true, false); if (!Weapon) + { return 2.4f; // fist attack + } switch (Weapon->GetProto()->InventoryType) { @@ -12464,14 +13578,18 @@ void Unit::AddPetAura(PetAura const* petSpell) { m_petAuras.insert(petSpell); if (Pet* pet = GetPet()) + { pet->CastPetAura(petSpell); + } } void Unit::RemovePetAura(PetAura const* petSpell) { m_petAuras.erase(petSpell); if (Pet* pet = GetPet()) + { pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry())); + } } void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/) @@ -12481,22 +13599,34 @@ void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, { SpellEntry const* spell = iter->second->GetSpellProto(); if (spell->Id == exceptSpellId) + { ++iter; + } else if (non_positive && iter->second->IsPositive()) + { ++iter; + } else if (spell->HasAttribute(SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)) + { ++iter; + } else if (iter->second->HasMechanicMask(mechMask)) { RemoveAurasDueToSpell(spell->Id); if (auras.empty()) + { break; + } else + { iter = auras.begin(); + } } else + { ++iter; + } } } @@ -12533,14 +13663,18 @@ void Unit::NearTeleportTo(float x, float y, float z, float orientation, bool cas DisableSpline(); if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->TeleportTo(GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0)); + } else { Creature* c = (Creature*)this; // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly if (!c->GetMotionMaster()->empty()) if (MovementGenerator* movgen = c->GetMotionMaster()->top()) + { movgen->Interrupt(*c); + } GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation); @@ -12550,7 +13684,9 @@ void Unit::NearTeleportTo(float x, float y, float z, float orientation, bool cas // but apply Reset expected to be safe in any case if (!c->GetMotionMaster()->empty()) if (MovementGenerator* movgen = c->GetMotionMaster()->top()) + { movgen->Reset(*c); + } } } @@ -12572,9 +13708,13 @@ struct SetPvPHelper void Unit::SetPvP(bool state) { if (state) + { SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); + } else + { RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); + } CallForAllControlledUnits(SetPvPHelper(state), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); } @@ -12589,9 +13729,13 @@ struct SetFFAPvPHelper void Unit::SetFFAPvP(bool state) { if (state) + { SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); + } else + { RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP); + } CallForAllControlledUnits(SetFFAPvPHelper(state), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); } @@ -12599,7 +13743,9 @@ void Unit::SetFFAPvP(bool state) void Unit::RestoreOriginalFaction() { if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->setFactionForRace(getRace()); + } else { Creature* creature = (Creature*)this; @@ -12607,10 +13753,14 @@ void Unit::RestoreOriginalFaction() if (creature->IsPet() || creature->IsTotem()) { if (Unit* owner = GetOwner()) + { setFaction(owner->getFaction()); + } } else + { setFaction(creature->GetCreatureInfo()->FactionAlliance); + } } } @@ -12668,7 +13818,9 @@ uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float c { float percent = GetCombatRatingReduction(cr) * rate; if (percent > cap) + { percent = cap; + } return uint32(percent * damage / 100.0f); } @@ -12741,11 +13893,15 @@ void Unit::StopAttackFaction(uint32 faction_id) { AttackStop(); if (IsNonMeleeSpellCasted(false)) + { InterruptNonMeleeSpells(false); + } // melee and ranged forced attack cancel if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SendAttackSwingCancelAttack(); + } } } @@ -12758,7 +13914,9 @@ void Unit::StopAttackFaction(uint32 faction_id) itr = attackers.begin(); } else + { ++itr; + } } GetHostileRefManager().deleteReferencesForFaction(faction_id); @@ -12917,7 +14075,9 @@ class RelocationNotifyEvent : public BasicEvent void Unit::ScheduleAINotify(uint32 delay) { if (!IsAINotifyScheduled()) + { m_Events.AddEvent(new RelocationNotifyEvent(*this), m_Events.CalculateTime(delay)); + } } void Unit::OnRelocated() @@ -12986,7 +14146,9 @@ void Unit::UpdateSplineMovement(uint32 t_diff) bool arrived = movespline->Finalized(); if (arrived) + { DisableSpline(); + } m_movesplineTimer.Update(t_diff); if (m_movesplineTimer.Passed() || arrived) @@ -12995,11 +14157,17 @@ void Unit::UpdateSplineMovement(uint32 t_diff) Movement::Location loc = movespline->ComputePosition(); if (IsBoarded()) + { GetTransportInfo()->SetLocalPosition(loc.x, loc.y, loc.z, loc.orientation); + } else if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->SetPosition(loc.x, loc.y, loc.z, loc.orientation); + } else + { GetMap()->CreatureRelocation((Creature*)this, loc.x, loc.y, loc.z, loc.orientation); + } } } @@ -13200,7 +14368,9 @@ Unit* Unit::TakePossessOf(SpellEntry const* spellEntry, SummonPropertiesEntry co CreatureCreatePos pos(GetMap(), x, y, z, ang, GetPhaseMask()); if (x == 0.0f && y == 0.0f && z == 0.0f) + { pos = CreatureCreatePos(this, GetOrientation(), CONTACT_DISTANCE, ang); + } if (!pCreature->Create(GetMap()->GenerateLocalLowGuid(cinfo->GetHighGuid()), pos, cinfo)) { @@ -13242,19 +14412,25 @@ Unit* Unit::TakePossessOf(SpellEntry const* spellEntry, SummonPropertiesEntry co { // Initialize pet bar if (CharmInfo* charmInfo = pCreature->InitCharmInfo(pCreature)) + { charmInfo->InitPossessCreateSpells(); + } player->PossessSpellInitialize(); } else { // fire just summoned hook if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI()) + { ((Creature*)this)->AI()->JustSummoned(pCreature); + } } // Creature Linking, Initial load is handled like respawn if (pCreature->IsLinkingEventTrigger()) + { GetMap()->GetCreatureLinkingHolder()->DoCreatureLinkingEvent(LINKING_EVENT_RESPAWN, pCreature); + } // return the creature therewith the summoner has access to it return pCreature; @@ -13264,7 +14440,9 @@ bool Unit::TakePossessOf(Unit* possessed) { Player* player = NULL; if (GetTypeId() == TYPEID_PLAYER) + { player = static_cast(this); + } possessed->addUnitState(UNIT_STAT_CONTROLLED); possessed->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); @@ -13275,7 +14453,9 @@ bool Unit::TakePossessOf(Unit* possessed) Creature* possessedCreature = NULL; if (possessed->GetTypeId() == TYPEID_UNIT) + { possessedCreature = static_cast(possessed); + } if (player) { @@ -13319,7 +14499,9 @@ void Unit::ResetControlState(bool attackCharmer /*= true*/) { Player* player = NULL; if (GetTypeId() == TYPEID_PLAYER) + { player = static_cast(this); + } Unit* possessed = GetCharm(); @@ -13362,7 +14544,9 @@ void Unit::ResetControlState(bool attackCharmer /*= true*/) return; } else + { player->RemovePetActionBar(); + } } possessed->CombatStop(true); diff --git a/src/game/Object/Unit.h b/src/game/Object/Unit.h index 50d17e638..d20fd6e1e 100644 --- a/src/game/Object/Unit.h +++ b/src/game/Object/Unit.h @@ -1445,7 +1445,9 @@ class Unit : public WorldObject { AttackerSet::const_iterator itr = m_attackers.find(pAttacker); if (itr == m_attackers.end()) + { m_attackers.insert(pAttacker); + } } /** * Internal function, must only be called from Unit::AttackStop() @@ -3317,9 +3319,13 @@ class Unit : public WorldObject void SetVisibleAura(uint8 slot, SpellAuraHolder* holder) { if (!holder) + { m_visibleAuras.erase(slot); + } else + { m_visibleAuras[slot] = holder; + } } VisibleAuraMap const& GetVisibleAuras() const { return m_visibleAuras; } uint8 GetVisibleAurasCount() const { return m_visibleAuras.size(); } diff --git a/src/game/Object/UnitEvents.h b/src/game/Object/UnitEvents.h index bf1e3f801..f80958385 100644 --- a/src/game/Object/UnitEvents.h +++ b/src/game/Object/UnitEvents.h @@ -94,16 +94,24 @@ class ThreatRefStatusChangeEvent : public UnitBaseEvent ThreatManager* iThreatManager; public: ThreatRefStatusChangeEvent(uint32 pType) : UnitBaseEvent(pType), iThreatManager(NULL) - { iHostileReference = NULL; } + { + iHostileReference = NULL; + } ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference) : UnitBaseEvent(pType), iThreatManager(NULL) - { iHostileReference = pHostileReference; } + { + iHostileReference = pHostileReference; + } ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference, float pValue) : UnitBaseEvent(pType), iThreatManager(NULL) - { iHostileReference = pHostileReference; iFValue = pValue; } + { + iHostileReference = pHostileReference; iFValue = pValue; + } ThreatRefStatusChangeEvent(uint32 pType, HostileReference* pHostileReference, bool pValue) : UnitBaseEvent(pType), iThreatManager(NULL) - { iHostileReference = pHostileReference; iBValue = pValue; } + { + iHostileReference = pHostileReference; iBValue = pValue; + } int32 getIValue() const { return iIValue; } diff --git a/src/game/Object/UpdateMask.h b/src/game/Object/UpdateMask.h index a37a2f984..759b38b72 100644 --- a/src/game/Object/UpdateMask.h +++ b/src/game/Object/UpdateMask.h @@ -73,7 +73,9 @@ class UpdateMask void Clear() { if (mUpdateMask) + { memset(mUpdateMask, 0, mBlocks << 2); + } } UpdateMask& operator = (const UpdateMask& mask) diff --git a/src/game/Object/Vehicle.cpp b/src/game/Object/Vehicle.cpp index 5bf3593c3..9e6b5806f 100644 --- a/src/game/Object/Vehicle.cpp +++ b/src/game/Object/Vehicle.cpp @@ -113,10 +113,14 @@ VehicleInfo::VehicleInfo(Unit* owner, VehicleEntry const* vehicleEntry, uint32 o m_vehicleSeats.insert(VehicleSeatMap::value_type(i, seatEntry)); if (IsUsableSeatForCreature(seatEntry->m_flags)) + { m_creatureSeats |= 1 << i; + } if (IsUsableSeatForPlayer(seatEntry->m_flags, seatEntry->m_flagsB)) + { m_playerSeats |= 1 << i; + } } } } @@ -132,7 +136,9 @@ VehicleInfo::~VehicleInfo() void VehicleInfo::Initialize() { if (!m_overwriteNpcEntry) + { m_overwriteNpcEntry = m_owner->GetEntry(); + } // Loading passengers (rough version only!) SQLMultiStorage::SQLMSIteratorBounds bounds = sVehicleAccessoryStorage.getBounds(m_overwriteNpcEntry); @@ -152,18 +158,30 @@ void VehicleInfo::Initialize() Unit* pVehicle = (Unit*)m_owner; if (vehicleFlags & VEHICLE_FLAG_NO_STRAFE) + { pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_NO_STRAFE); + } if (vehicleFlags & VEHICLE_FLAG_NO_JUMPING) + { pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_NO_JUMPING); + } if (vehicleFlags & VEHICLE_FLAG_FULLSPEEDTURNING) + { pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_FULLSPEEDTURNING); + } if (vehicleFlags & VEHICLE_FLAG_ALLOW_PITCHING) + { pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_ALLOW_PITCHING); + } if (vehicleFlags & VEHICLE_FLAG_FULLSPEEDPITCHING) + { pVehicle->m_movementInfo.AddMovementFlags2(MOVEFLAG2_FULLSPEEDPITCHING); + } if (vehicleFlags & VEHICLE_FLAG_FIXED_POSITION) + { pVehicle->SetRoot(true); + } // // Initialize power type based on DBC values (creatures only) // if (pVehicle->GetTypeId() == TYPEID_UNIT) @@ -237,7 +255,9 @@ void VehicleInfo::Board(Unit* passenger, uint8 seat) } if (!passenger->IsRooted()) + { passenger->SetRoot(true); + } Movement::MoveSplineInit init(*passenger); init.MoveTo(0.0f, 0.0f, 0.0f); // ToDo: Set correct local coords @@ -351,7 +371,9 @@ void VehicleInfo::UnBoard(Unit* passenger, bool changeVehicle) } if (passenger->IsRooted()) + { passenger->SetRoot(false); + } Movement::MoveSplineInit init(*passenger); // ToDo: Set proper unboard coordinates @@ -378,7 +400,9 @@ void VehicleInfo::UnBoard(Unit* passenger, bool changeVehicle) !(m_vehicleEntry->m_flags & (VEHICLE_FLAG_UNK4 | VEHICLE_FLAG_UNK20))) { if (((Creature*)m_owner)->IsTemporarySummon()) + { ((Creature*)m_owner)->ForcedDespawn(1000); + } } } } @@ -549,7 +573,9 @@ void VehicleInfo::ApplySeatMods(Unit* passenger, uint32 seatFlags) Unit* pVehicle = (Unit*)m_owner; // Vehicles are alawys Unit if (seatFlags & SEAT_FLAG_NOT_SELECTABLE) + { passenger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + } if (passenger->GetTypeId() == TYPEID_PLAYER) { @@ -557,7 +583,9 @@ void VehicleInfo::ApplySeatMods(Unit* passenger, uint32 seatFlags) // group update if (pPlayer->GetGroup()) + { pPlayer->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_VEHICLE_SEAT); + } if (seatFlags & SEAT_FLAG_CAN_CONTROL) { @@ -619,7 +647,9 @@ void VehicleInfo::RemoveSeatMods(Unit* passenger, uint32 seatFlags) Unit* pVehicle = (Unit*)m_owner; if (seatFlags & SEAT_FLAG_NOT_SELECTABLE) + { passenger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + } if (passenger->GetTypeId() == TYPEID_PLAYER) { @@ -627,7 +657,9 @@ void VehicleInfo::RemoveSeatMods(Unit* passenger, uint32 seatFlags) // group update if (pPlayer->GetGroup()) + { pPlayer->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_VEHICLE_SEAT); + } if (seatFlags & SEAT_FLAG_CAN_CONTROL) { @@ -645,11 +677,15 @@ void VehicleInfo::RemoveSeatMods(Unit* passenger, uint32 seatFlags) // reset vehicle faction if (pVehicle->GetTypeId() == TYPEID_UNIT) + { ((Creature*)pVehicle)->ClearTemporaryFaction(); + } } if (seatFlags & SEAT_FLAG_CAN_CAST) + { pPlayer->RemovePetActionBar(); + } } else if (passenger->GetTypeId() == TYPEID_UNIT) { @@ -662,7 +698,9 @@ void VehicleInfo::RemoveSeatMods(Unit* passenger, uint32 seatFlags) // Reinitialize movement ((Creature*)passenger)->AI()->SetCombatMovement(true, true); if (!passenger->getVictim()) + { passenger->GetMotionMaster()->Initialize(); + } } } diff --git a/src/game/OutdoorPvP/OutdoorPvP.cpp b/src/game/OutdoorPvP/OutdoorPvP.cpp index affae5e39..935e4d3cb 100644 --- a/src/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/game/OutdoorPvP/OutdoorPvP.cpp @@ -92,9 +92,13 @@ void OutdoorPvP::HandleGameObjectCreate(GameObject* go) CapturePointSliderMap const* capturePoints = sOutdoorPvPMgr.GetCapturePointSliderMap(); CapturePointSliderMap::const_iterator itr = capturePoints->find(go->GetEntry()); if (itr != capturePoints->end()) + { go->SetCapturePointSlider(itr->second.Value, itr->second.IsLocked); + } else + { go->SetCapturePointSlider(CAPTURE_SLIDER_MIDDLE, false); + } } } diff --git a/src/game/OutdoorPvP/OutdoorPvPGH.cpp b/src/game/OutdoorPvP/OutdoorPvPGH.cpp index c65c8e034..71982943c 100644 --- a/src/game/OutdoorPvP/OutdoorPvPGH.cpp +++ b/src/game/OutdoorPvP/OutdoorPvPGH.cpp @@ -140,7 +140,9 @@ void OutdoorPvPGH::DespawnVendors(const WorldObject* objRef) for (GuidList::const_iterator itr = m_teamVendors.begin(); itr != m_teamVendors.end(); ++itr) { if (Creature* vendor = objRef->GetMap()->GetCreature(*itr)) + { vendor->ForcedDespawn(); + } } m_teamVendors.clear(); } @@ -149,7 +151,9 @@ void OutdoorPvPGH::DespawnVendors(const WorldObject* objRef) void OutdoorPvPGH::LockLighthouse(const WorldObject* objRef) { if (GameObject* go = objRef->GetMap()->GetGameObject(m_capturePoint)) + { go->SetLootState(GO_JUST_DEACTIVATED); + } else { // if grid is unloaded, changing the saved slider value is enough @@ -162,7 +166,9 @@ void OutdoorPvPGH::LockLighthouse(const WorldObject* objRef) void OutdoorPvPGH::UnlockLighthouse(const WorldObject* objRef) { if (GameObject* go = objRef->GetMap()->GetGameObject(m_capturePoint)) + { go->SetLootState(GO_ACTIVATED); + } else { // if grid is unloaded, changing the saved slider value is enough diff --git a/src/game/OutdoorPvP/OutdoorPvPHP.cpp b/src/game/OutdoorPvP/OutdoorPvPHP.cpp index b50244678..8d3500988 100644 --- a/src/game/OutdoorPvP/OutdoorPvPHP.cpp +++ b/src/game/OutdoorPvP/OutdoorPvPHP.cpp @@ -77,9 +77,13 @@ void OutdoorPvPHP::HandlePlayerEnterZone(Player* player, bool isMainZone) // buff the player if same team is controlling all capture points if (m_towersAlliance == MAX_HP_TOWERS && player->GetTeam() == ALLIANCE) + { player->CastSpell(player, SPELL_HELLFIRE_SUPERIORITY_ALLIANCE, true); + } else if (m_towersHorde == MAX_HP_TOWERS && player->GetTeam() == HORDE) + { player->CastSpell(player, SPELL_HELLFIRE_SUPERIORITY_HORDE, true); + } } void OutdoorPvPHP::HandlePlayerLeaveZone(Player* player, bool isMainZone) @@ -168,7 +172,9 @@ void OutdoorPvPHP::HandlePlayerKillInsideArea(Player* player) { // check capture point team if (player->GetTeam() == m_towerOwner[i]) + { player->CastSpell(player, player->GetTeam() == ALLIANCE ? SPELL_HELLFIRE_TOWER_TOKEN_ALLIANCE : SPELL_HELLFIRE_TOWER_TOKEN_HORDE, true); + } return; } @@ -191,7 +197,9 @@ bool OutdoorPvPHP::HandleEvent(uint32 eventId, GameObject* go) if (hellfireTowerEvents[i][j].team != m_towerOwner[i]) { if (hellfireTowerEvents[i][j].defenseMessage) + { sWorld.SendDefenseMessage(ZONE_ID_HELLFIRE_PENINSULA, hellfireTowerEvents[i][j].defenseMessage); + } return ProcessCaptureEvent(go, i, hellfireTowerEvents[i][j].team, hellfireTowerEvents[i][j].worldState, hellfireTowerEvents[i][j].towerArtKit, hellfireTowerEvents[i][j].towerAnim); } @@ -219,7 +227,9 @@ bool OutdoorPvPHP::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team SendUpdateWorldState(WORLD_STATE_HP_TOWER_COUNT_ALLIANCE, m_towersAlliance); if (m_towersAlliance == MAX_HP_TOWERS) + { BuffTeam(ALLIANCE, SPELL_HELLFIRE_SUPERIORITY_ALLIANCE); + } } else if (team == HORDE) { @@ -230,7 +240,9 @@ bool OutdoorPvPHP::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team SendUpdateWorldState(WORLD_STATE_HP_TOWER_COUNT_HORDE, m_towersHorde); if (m_towersHorde == MAX_HP_TOWERS) + { BuffTeam(HORDE, SPELL_HELLFIRE_SUPERIORITY_HORDE); + } } else { @@ -239,7 +251,9 @@ bool OutdoorPvPHP::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team if (m_towerOwner[towerId] == ALLIANCE) { if (m_towersAlliance == MAX_HP_TOWERS) + { BuffTeam(ALLIANCE, SPELL_HELLFIRE_SUPERIORITY_ALLIANCE, true); + } // update counter --m_towersAlliance; @@ -248,7 +262,9 @@ bool OutdoorPvPHP::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team else { if (m_towersHorde == MAX_HP_TOWERS) + { BuffTeam(HORDE, SPELL_HELLFIRE_SUPERIORITY_HORDE, true); + } // update counter --m_towersHorde; diff --git a/src/game/OutdoorPvP/OutdoorPvPMgr.cpp b/src/game/OutdoorPvP/OutdoorPvPMgr.cpp index 56e3b50d3..40806106e 100644 --- a/src/game/OutdoorPvP/OutdoorPvPMgr.cpp +++ b/src/game/OutdoorPvP/OutdoorPvPMgr.cpp @@ -145,7 +145,9 @@ void OutdoorPvPMgr::HandlePlayerEnterZone(Player* player, uint32 zoneId) script->HandlePlayerEnterZone(player, true); } else if (OutdoorPvP* affectedScript = GetScriptOfAffectedZone(zoneId)) + { affectedScript->HandlePlayerEnterZone(player, false); + } } /** @@ -162,7 +164,9 @@ void OutdoorPvPMgr::HandlePlayerLeaveZone(Player* player, uint32 zoneId) script->HandlePlayerLeaveZone(player, true); } else if (OutdoorPvP* affectedScript = GetScriptOfAffectedZone(zoneId)) + { affectedScript->HandlePlayerLeaveZone(player, false); + } } void OutdoorPvPMgr::Update(uint32 diff) diff --git a/src/game/OutdoorPvP/OutdoorPvPNA.cpp b/src/game/OutdoorPvP/OutdoorPvPNA.cpp index 85e7ccd6f..4a808d934 100644 --- a/src/game/OutdoorPvP/OutdoorPvPNA.cpp +++ b/src/game/OutdoorPvP/OutdoorPvPNA.cpp @@ -81,7 +81,9 @@ void OutdoorPvPNA::HandlePlayerEnterZone(Player* player, bool isMainZone) // buff the player if same team is controlling the zone if (player->GetTeam() == m_zoneOwner) + { player->CastSpell(player, SPELL_STRENGTH_HALAANI, true); + } } void OutdoorPvPNA::HandlePlayerLeaveZone(Player* player, bool isMainZone) @@ -99,7 +101,9 @@ void OutdoorPvPNA::HandleObjectiveComplete(uint32 eventId, const std::list::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if ((*itr) && (*itr)->GetTeam() == team) + { (*itr)->KilledMonsterCredit(NPC_HALAA_COMBATANT); + } } } } @@ -115,7 +119,9 @@ void OutdoorPvPNA::HandlePlayerKillInsideArea(Player* player) { // check capture point team if (player->GetTeam() == m_zoneOwner) + { player->CastSpell(player, player->GetTeam() == ALLIANCE ? SPELL_NAGRAND_TOKEN_ALLIANCE : SPELL_NAGRAND_TOKEN_HORDE, true); + } return; } @@ -177,7 +183,9 @@ void OutdoorPvPNA::HandleCreatureDeath(Creature* creature) // set the respawn timer after the last guard died - 5 min for the first time, or 1 hour if the city is under siege if (!m_soldiersRespawnTimer) + { m_soldiersRespawnTimer = m_isUnderSiege ? HOUR * IN_MILLISECONDS : 5 * MINUTE * IN_MILLISECONDS; + } // decrease the counter --m_guardsLeft; @@ -418,7 +426,9 @@ void OutdoorPvPNA::DespawnVendors(const WorldObject* objRef) for (GuidList::const_iterator itr = m_teamVendors.begin(); itr != m_teamVendors.end(); ++itr) { if (Creature* soldier = objRef->GetMap()->GetCreature(*itr)) + { soldier->ForcedDespawn(); + } } m_teamVendors.clear(); } @@ -531,12 +541,18 @@ void OutdoorPvPNA::Update(uint32 diff) // if all the guards are respawned, stop the timer, else resume the timer depending on the siege state if (m_guardsLeft == MAX_NA_GUARDS) + { m_soldiersRespawnTimer = 0; + } else + { m_soldiersRespawnTimer = m_isUnderSiege ? HOUR * IN_MILLISECONDS : 5 * MINUTE * IN_MILLISECONDS; + } } else + { m_soldiersRespawnTimer -= diff; + } } } @@ -547,7 +563,9 @@ void OutdoorPvPNA::RespawnSoldier() { // Find player who is in main zone (Nagrand) to get correct map reference if (!itr->second) + { continue; + } if (Player* player = sObjectMgr.GetPlayer(itr->first)) { @@ -564,7 +582,9 @@ void OutdoorPvPNA::RespawnSoldier() void OutdoorPvPNA::LockHalaa(const WorldObject* objRef) { if (GameObject* go = objRef->GetMap()->GetGameObject(m_capturePoint)) + { go->SetLootState(GO_JUST_DEACTIVATED); + } else { // if grid is unloaded, changing the saved slider value is enough @@ -577,7 +597,9 @@ void OutdoorPvPNA::LockHalaa(const WorldObject* objRef) void OutdoorPvPNA::UnlockHalaa(const WorldObject* objRef) { if (GameObject* go = objRef->GetMap()->GetGameObject(m_capturePoint)) + { go->SetLootState(GO_ACTIVATED); + } else { // if grid is unloaded, changing the saved slider value is enough diff --git a/src/game/OutdoorPvP/OutdoorPvPTF.cpp b/src/game/OutdoorPvP/OutdoorPvPTF.cpp index fe1b12ad1..30999214c 100644 --- a/src/game/OutdoorPvP/OutdoorPvPTF.cpp +++ b/src/game/OutdoorPvP/OutdoorPvPTF.cpp @@ -65,7 +65,9 @@ void OutdoorPvPTF::FillInitialWorldStates(WorldPacket& data, uint32& count) } } else + { UpdateTimerWorldState(); + } } void OutdoorPvPTF::SendRemoveWorldStates(Player* player) @@ -87,7 +89,9 @@ void OutdoorPvPTF::HandlePlayerEnterZone(Player* player, bool isMainZone) // Handle the buffs if (player->GetTeam() == m_zoneOwner) + { player->CastSpell(player, SPELL_AUCHINDOUN_BLESSING, true); + } } void OutdoorPvPTF::HandlePlayerLeaveZone(Player* player, bool isMainZone) @@ -138,7 +142,9 @@ void OutdoorPvPTF::HandleObjectiveComplete(uint32 eventId, const std::list::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if ((*itr) && (*itr)->GetTeam() == team) + { (*itr)->AreaExploredOrEventHappens(team == ALLIANCE ? QUEST_SPIRITS_OF_AUCHINDOUM_ALLIANCE : QUEST_SPIRITS_OF_AUCHINDOUM_HORDE); + } } return; } @@ -305,7 +311,9 @@ void OutdoorPvPTF::UnlockZone() { // Find player who is in main zone (Terokkar Forest) to get correct map reference if (!itr->second) + { continue; + } if (Player* player = sObjectMgr.GetPlayer(itr->first)) { @@ -336,7 +344,9 @@ void OutdoorPvPTF::Update(uint32 diff) m_zoneUpdateTimer = TIMER_TF_UPDATE_TIME; } else - m_zoneUpdateTimer -= diff;*/ + { + m_zoneUpdateTimer -= diff; + }*/ m_zoneLockTimer -= diff; } @@ -362,7 +372,9 @@ void OutdoorPvPTF::LockTowers(const WorldObject* objRef) for (uint8 i = 0; i < MAX_TF_TOWERS; ++i) { if (GameObject* go = objRef->GetMap()->GetGameObject(m_towerBanners[i])) + { go->SetLootState(GO_JUST_DEACTIVATED); + } else { // if grid is unloaded, changing the saved slider value is enough diff --git a/src/game/OutdoorPvP/OutdoorPvPZM.cpp b/src/game/OutdoorPvP/OutdoorPvPZM.cpp index 656f4a683..290e1d610 100644 --- a/src/game/OutdoorPvP/OutdoorPvPZM.cpp +++ b/src/game/OutdoorPvP/OutdoorPvPZM.cpp @@ -89,7 +89,9 @@ void OutdoorPvPZM::HandlePlayerEnterZone(Player* player, bool isMainZone) // cast buff the the player which enters the zone if (player->GetTeam() == m_graveyardOwner) + { player->CastSpell(player, SPELL_TWIN_SPIRE_BLESSING, true); + } } void OutdoorPvPZM::HandlePlayerLeaveZone(Player* player, bool isMainZone) @@ -106,19 +108,31 @@ void OutdoorPvPZM::HandleCreatureCreate(Creature* creature) { case NPC_PVP_BEAM_RED: if (creature->GetPositionY() < 7000.0f) // East Beam + { m_beamTowerRed[0] = creature->GetObjectGuid(); + } else if (creature->GetPositionY() < 7300.0f) // Center Beam + { m_beamGraveyardRed = creature->GetObjectGuid(); + } else // West Beam + { m_beamTowerRed[1] = creature->GetObjectGuid(); + } break; case NPC_PVP_BEAM_BLUE: if (creature->GetPositionY() < 7000.0f) // East Beam + { m_beamTowerBlue[0] = creature->GetObjectGuid(); + } else if (creature->GetPositionY() < 7300.0f) // Center Beam + { m_beamGraveyardBlue = creature->GetObjectGuid(); + } else // West Beam + { m_beamTowerBlue[1] = creature->GetObjectGuid(); + } break; } } @@ -160,7 +174,9 @@ void OutdoorPvPZM::HandlePlayerKillInsideArea(Player* player) { // check capture point team if (player->GetTeam() == m_towerOwner[i]) + { player->CastSpell(player, player->GetTeam() == ALLIANCE ? SPELL_ZANGA_TOWER_TOKEN_ALLIANCE : SPELL_ZANGA_TOWER_TOKEN_HORDE, true); + } return; } @@ -183,7 +199,9 @@ bool OutdoorPvPZM::HandleEvent(uint32 eventId, GameObject* go) if (zangarmarshTowerEvents[i][j].team != m_towerOwner[i]) { if (zangarmarshTowerEvents[i][j].defenseMessage) + { sWorld.SendDefenseMessage(ZONE_ID_ZANGARMARSH, zangarmarshTowerEvents[i][j].defenseMessage); + } return ProcessCaptureEvent(go, i, zangarmarshTowerEvents[i][j].team, zangarmarshTowerEvents[i][j].worldState, zangarmarshTowerEvents[i][j].mapState); } @@ -214,7 +232,9 @@ bool OutdoorPvPZM::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team // only add flag to scouts if team does not have captured graveyard already if (m_graveyardOwner != ALLIANCE) + { UpdateScoutState(ALLIANCE, true); + } } } else if (team == HORDE) @@ -230,7 +250,9 @@ bool OutdoorPvPZM::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team // only add flag to scouts if team does not already have captured graveyard if (m_graveyardOwner != HORDE) + { UpdateScoutState(HORDE, true); + } } } else @@ -241,7 +263,9 @@ bool OutdoorPvPZM::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team // only remove flag from scouts if team does not already have captured graveyard if (m_towersAlliance == MAX_ZM_TOWERS && m_graveyardOwner != ALLIANCE) + { UpdateScoutState(ALLIANCE, false); + } // update counter --m_towersAlliance; @@ -252,7 +276,9 @@ bool OutdoorPvPZM::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team // only remove flag from scouts if team does not already have captured graveyard if (m_towersHorde == MAX_ZM_TOWERS && m_graveyardOwner != HORDE) + { UpdateScoutState(HORDE, false); + } // update counter --m_towersHorde; @@ -285,7 +311,9 @@ void OutdoorPvPZM::UpdateScoutState(Team team, bool spawned) SendUpdateWorldState(m_scoutWorldStateAlliance, WORLD_STATE_ADD); if (spawned) + { sWorld.SendDefenseMessage(ZONE_ID_ZANGARMARSH, LANG_OPVP_ZM_SPAWN_FIELD_SCOUT_A); + } } else { @@ -294,7 +322,9 @@ void OutdoorPvPZM::UpdateScoutState(Team team, bool spawned) SendUpdateWorldState(m_scoutWorldStateHorde, WORLD_STATE_ADD); if (spawned) + { sWorld.SendDefenseMessage(ZONE_ID_ZANGARMARSH, LANG_OPVP_ZM_SPAWN_FIELD_SCOUT_H); + } } } @@ -335,7 +365,9 @@ bool OutdoorPvPZM::HandleGameObjectUse(Player* player, GameObject* go) SetBeaconArtKit(go, m_beamGraveyardRed, 0); } else + { RespawnGO(go, m_graveyardBannerNeutral, false); + } if (team == ALLIANCE) { @@ -377,7 +409,9 @@ bool OutdoorPvPZM::HandleGameObjectUse(Player* player, GameObject* go) // apply zone buff if (m_graveyardOwner != TEAM_NONE) + { BuffTeam(m_graveyardOwner, SPELL_TWIN_SPIRE_BLESSING, true); + } BuffTeam(team, SPELL_TWIN_SPIRE_BLESSING); // reset scout so that team cannot take flag @@ -410,8 +444,12 @@ void OutdoorPvPZM::SetBeaconArtKit(const WorldObject* objRef, ObjectGuid creatur if (Creature* beam = objRef->GetMap()->GetCreature(creatureGuid)) { if (auraId) + { beam->CastSpell(beam, auraId, true); + } else + { beam->RemoveAllAuras(); + } } } diff --git a/src/game/References/ThreatManager.cpp b/src/game/References/ThreatManager.cpp index 8487ef487..609928db2 100644 --- a/src/game/References/ThreatManager.cpp +++ b/src/game/References/ThreatManager.cpp @@ -118,7 +118,9 @@ void HostileReference::fireStatusChanged(ThreatRefStatusChangeEvent& pThreatRefS void HostileReference::addThreat(float pMod) { if (pMod + iThreat < 0) + { pMod = -iThreat; + } iThreat += pMod; // the threat is changed. Source and target unit have to be availabe @@ -137,7 +139,9 @@ void HostileReference::addThreat(float pMod) { Unit* victim_owner = getTarget()->GetOwner(); if (victim_owner && victim_owner->IsAlive()) - { getSource()->addThreat(victim_owner, 0.0f); } // create a threat to the owner of a pet, if the pet attacks + { + getSource()->addThreat(victim_owner, 0.0f); // create a threat to the owner of a pet, if the pet attacks + } } } @@ -169,7 +173,9 @@ void HostileReference::updateOnlineStatus() if (!online) { if (creature->AI()->canReachByRangeAttack(getTarget())) - { online = true; } // not accessable but stays online + { + online = true; // not accessable but stays online + } } else { @@ -189,7 +195,9 @@ void HostileReference::setOnlineOfflineState(bool pIsOnline) { iOnline = pIsOnline; if (!iOnline) - { setAccessibleState(false); } // if not online that not accessable as well + { + setAccessibleState(false); // if not online that not accessable as well + } ThreatRefStatusChangeEvent event(UEV_THREAT_REF_ONLINE_STATUS, this); fireStatusChanged(event); @@ -491,10 +499,14 @@ void ThreatManager::addThreatDirectly(Unit* pVictim, float threat) HostileReference* ref = iThreatContainer.addThreat(pVictim, threat); // Ref is online if (ref) + { iUpdateNeed = true; + } // Ref is not in the online refs, search the offline refs next else + { ref = iThreatOfflineContainer.addThreat(pVictim, threat); + } if (!ref) // there was no ref => create a new one { @@ -504,7 +516,9 @@ void ThreatManager::addThreatDirectly(Unit* pVictim, float threat) hostileReference->addThreat(threat); // now we add the real threat iUpdateNeed = true; if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster()) - { hostileReference->setOnlineOfflineState(false); } // GM is always offline + { + hostileReference->setOnlineOfflineState(false); // GM is always offline + } } } @@ -538,9 +552,13 @@ float ThreatManager::getThreat(Unit* pVictim, bool pAlsoSearchOfflineList) float threat = 0.0f; if (HostileReference* ref = iThreatContainer.getReferenceByTarget(pVictim)) + { threat = ref->getThreat(); + } else if (pAlsoSearchOfflineList) + { threat = iThreatOfflineContainer.getReferenceByTarget(pVictim)->getThreat(); + } return threat; } @@ -585,7 +603,9 @@ void ThreatManager::setCurrentVictim(HostileReference* pHostileReference) } if (pHostileReference) + { iOwner->SendHighestThreatUpdate(pHostileReference); + } iCurrentVictim = pHostileReference; iUpdateNeed = true; @@ -606,7 +626,9 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat case UEV_THREAT_REF_THREAT_CHANGE: if ((getCurrentVictim() == hostileReference && threatRefStatusChangeEvent->getFValue() < 0.0f) || (getCurrentVictim() != hostileReference && threatRefStatusChangeEvent->getFValue() > 0.0f)) - { setDirty(true); } // the order in the threat list might have changed + { + setDirty(true); // the order in the threat list might have changed + } break; case UEV_THREAT_REF_ONLINE_STATUS: if (!hostileReference->isOnline()) diff --git a/src/game/Server/DB2Stores.cpp b/src/game/Server/DB2Stores.cpp index 79197cb4d..722891b83 100644 --- a/src/game/Server/DB2Stores.cpp +++ b/src/game/Server/DB2Stores.cpp @@ -75,7 +75,9 @@ inline void LoadDB2(LocalDB2Data& localeData, StoreProblemList1& errors, DB2Stor for(uint8 i = 0; fullLocaleNameList[i].name; ++i) { if (!(localeData.availableDb2Locales & (1 << i))) + { continue; + } LocaleNameStr const* localStr = &fullLocaleNameList[i]; @@ -97,7 +99,9 @@ inline void LoadDB2(LocalDB2Data& localeData, StoreProblemList1& errors, DB2Stor fclose(f); } else + { errors.push_back(db2Filename); + } } } diff --git a/src/game/Server/DBCStores.cpp b/src/game/Server/DBCStores.cpp index 39b654d26..ba9ed4e1a 100644 --- a/src/game/Server/DBCStores.cpp +++ b/src/game/Server/DBCStores.cpp @@ -332,7 +332,9 @@ static uint32 ReadDBCBuild(const std::string& dbc_path, LocaleNameStr const*&loc } } else + { ReadDBCBuildFileText(dbc_path, localeNameStr->name, text); + } if (text.empty()) { @@ -392,7 +394,9 @@ inline void LoadDBC(LocalData& localeData, BarGoLink& bar, StoreProblemList& err for (uint8 i = 0; fullLocaleNameList[i].name; ++i) { if (!(localeData.availableDbcLocales & (1 << i))) + { continue; + } LocaleNameStr const* localStr = &fullLocaleNameList[i]; @@ -437,7 +441,9 @@ inline void LoadDBC(LocalData& localeData, BarGoLink& bar, StoreProblemList& err fclose(f); } else + { errlist.push_back(dbc_filename); + } } } @@ -454,7 +460,9 @@ void LoadDBCStores(const std::string& dataPath) if (build) sLog.outError("Found DBC files for build %u but mangosd expected DBC for one from builds: %s Please extract correct DBC files.", build, AcceptableClientBuildsListStr().c_str()); else + { sLog.outError("Incorrect DataDir value in mangosd.conf or not found build info (outdated DBC files). Required one from builds: %s Please extract correct DBC files.", AcceptableClientBuildsListStr().c_str()); + } Log::WaitBeforeContinueIfNeed(); exit(1); } @@ -479,7 +487,9 @@ void LoadDBCStores(const std::string& dataPath) // fill MapId->DBC records ( skip sub zones and continents ) if (area->zone == 0 && area->mapid != 0 && area->mapid != 1 && area->mapid != 530 && area->mapid != 571 && area->mapid != 860 && area->mapid != 870) + { sAreaFlagByMapID.insert(AreaFlagByMapID::value_type(area->mapid, area->exploreFlag)); + } } } @@ -499,7 +509,9 @@ void LoadDBCStores(const std::string& dataPath) LoadDBC(availableDbcLocales,bar,bad_dbc_files,sChrPowerTypesStore, dbcPath,"ChrClassesXPowerTypes.dbc"); for (uint32 i = 0; i < MAX_CLASSES; ++i) for (uint32 j = 0; j < MAX_POWERS; ++j) + { PowersByClass[i][j] = MAX_POWERS; + } for (uint32 i = 0; i < sChrPowerTypesStore.GetNumRows(); ++i) { @@ -508,7 +520,9 @@ void LoadDBCStores(const std::string& dataPath) uint32 index = 0; for (uint32 j = 0; j < MAX_POWERS; ++j) if (PowersByClass[power->classId][j] != MAX_POWERS) + { ++index; + } PowersByClass[power->classId][power->power] = index; } @@ -592,7 +606,9 @@ void LoadDBCStores(const std::string& dataPath) // fill data for (uint32 i = 1; i < sMapDifficultyStore.GetNumRows(); ++i) if (MapDifficultyEntry const* entry = sMapDifficultyStore.LookupEntry(i)) + { sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = entry; + } LoadDBC(availableDbcLocales, bar, bad_dbc_files, sMovieStore, dbcPath, "Movie.dbc"); LoadDBC(availableDbcLocales,bar,bad_dbc_files, sMountCapabilityStore, dbcPath,"MountCapability.dbc"); @@ -607,7 +623,9 @@ void LoadDBCStores(const std::string& dataPath) for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) + { MANGOS_ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); + } LoadDBC(availableDbcLocales, bar, bad_dbc_files, sRandomPropertiesPointsStore, dbcPath, "RandPropPoints.dbc"); LoadDBC(availableDbcLocales, bar, bad_dbc_files, sScalingStatDistributionStore, dbcPath, "ScalingStatDistribution.dbc"); @@ -632,7 +650,9 @@ void LoadDBCStores(const std::string& dataPath) { if(SpellCategoriesEntry const* category = spell->GetSpellCategories()) if(uint32 cat = category->Category) + { sSpellCategoryStore[cat].insert(i); + } // DBC not support uint64 fields but SpellEntry have SpellFamilyFlags mapped at 2 uint32 fields // uint32 field already converted to bigendian if need, but must be swapped for correct uint64 bigendian view @@ -658,7 +678,9 @@ void LoadDBCStores(const std::string& dataPath) } if (spellEffect->EffectSpellId < MAX_EFFECT_INDEX && spellEffect->Difficulty == 0) - sSpellEffectMap[spellEffect->EffectSpellId].effects[spellEffect->EffectIndex] = spellEffect; + { + sSpellEffectMap[spellEffect->EffectSpellId].effects[spellEffect->EffectIndex] = spellEffect; + } } } @@ -677,7 +699,9 @@ void LoadDBCStores(const std::string& dataPath) SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j); if (!skillLine) + { continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId); if (spellInfo && (spellInfo->GetAttributes() & (SPELL_ATTR_UNK4 | SPELL_ATTR_PASSIVE | SPELL_ATTR_UNK7 | SPELL_ATTR_UNK8)) == (SPELL_ATTR_UNK4 | SPELL_ATTR_PASSIVE | SPELL_ATTR_UNK7 | SPELL_ATTR_UNK8)) @@ -686,10 +710,14 @@ void LoadDBCStores(const std::string& dataPath) { CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(i); if (!cFamily) + { continue; + } if (skillLine->skillId != cFamily->skillLine[0] && skillLine->skillId != cFamily->skillLine[1]) + { continue; + } sPetFamilySpellsStore[i].insert(spellInfo->Id); } @@ -718,7 +746,9 @@ void LoadDBCStores(const std::string& dataPath) if (!talentInfo) continue; for (int j = 0; j < MAX_TALENT_RANK; j++) if (talentInfo->RankID[j]) + { sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(i, j); + } } //LoadDBC(availableDbcLocales, bar, bad_dbc_files, sTalentTabStore, dbcPath, "TalentTab.dbc"); @@ -730,21 +760,29 @@ void LoadDBCStores(const std::string& dataPath) { TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentTabId); if (!talentTabInfo) + { continue; + } for (uint32 i = 0; i < MAX_MASTERY_SPELLS; ++i) if (uint32 spellid = talentTabInfo->masterySpells[i]) if (sSpellStore.LookupEntry(spellid)) + { sTalentTreeMasterySpellsMap[talentTabId].push_back(spellid); + } // prevent memory corruption; otherwise cls will become 12 below if ((talentTabInfo->ClassMask & CLASSMASK_ALL_PLAYABLE) == 0) + { continue; + } // store class talent tab pages for (uint32 cls = 1; cls < MAX_CLASSES; ++cls) if (talentTabInfo->ClassMask & (1 << (cls - 1))) + { sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabId; + } sTalentTreeRolesMap[talentTabId] = talentTabInfo->rolesMask; } @@ -754,7 +792,9 @@ void LoadDBCStores(const std::string& dataPath) for (uint32 i = 0; i < sTalentTreePrimarySpellsStore.GetNumRows(); ++i) if (TalentTreePrimarySpellsEntry const* talentSpell = sTalentTreePrimarySpellsStore.LookupEntry(i)) if (sSpellStore.LookupEntry(talentSpell->SpellId)) + { sTalentTreePrimarySpellsMap[talentSpell->TalentTree].push_back(talentSpell->SpellId); + } sTalentTreePrimarySpellsStore.Clear(); LoadDBC(availableDbcLocales, bar, bad_dbc_files, sTaxiNodesStore, dbcPath, "TaxiNodes.dbc"); @@ -762,7 +802,9 @@ void LoadDBCStores(const std::string& dataPath) LoadDBC(availableDbcLocales, bar, bad_dbc_files, sTaxiPathStore, dbcPath, "TaxiPath.dbc"); for (uint32 i = 1; i < sTaxiPathStore.GetNumRows(); ++i) if (TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(i)) + { sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID, entry->price); + } uint32 pathCount = sTaxiPathStore.GetNumRows(); //## TaxiPathNode.dbc ## Loaded only for initialization different structures @@ -774,7 +816,9 @@ void LoadDBCStores(const std::string& dataPath) if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) { if (pathLength[entry->path] < entry->index + 1) + { pathLength[entry->path] = entry->index + 1; + } } // Set path length sTaxiPathNodesByPath.resize(pathCount); // 0 and some other indexes not used @@ -785,7 +829,9 @@ void LoadDBCStores(const std::string& dataPath) // fill data (pointers to sTaxiPathNodeStore elements for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) + { sTaxiPathNodesByPath[entry->path].set(entry->index, entry); + } // Initialize global taxinodes mask // include existing nodes that have at least single not spell base (scripted) path @@ -796,7 +842,9 @@ void LoadDBCStores(const std::string& dataPath) for (int j = 0; j < MAX_EFFECT_INDEX; ++j) if(SpellEffectEntry const* effect = sInfo->GetSpellEffect(SpellEffectIndex(j))) if(effect->Effect==123 /*SPELL_EFFECT_SEND_TAXI*/) + { spellPaths.insert(effect->EffectMiscValue); + } memset(sTaxiNodesMask, 0, sizeof(sTaxiNodesMask)); memset(sOldContinentsNodesMask, 0, sizeof(sTaxiNodesMask)); @@ -807,7 +855,9 @@ void LoadDBCStores(const std::string& dataPath) { TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i); if (!node) + { continue; + } TaxiPathSetBySource::const_iterator src_i = sTaxiPathSetBySource.find(i); if (src_i != sTaxiPathSetBySource.end() && !src_i->second.empty()) @@ -824,7 +874,9 @@ void LoadDBCStores(const std::string& dataPath) } if (!ok) + { continue; + } } // valid taxi network node @@ -833,19 +885,29 @@ void LoadDBCStores(const std::string& dataPath) sTaxiNodesMask[field] |= submask; if (node->MountCreatureID[0] && node->MountCreatureID[0] != 32981) + { sHordeTaxiNodesMask[field] |= submask; + } if (node->MountCreatureID[1] && node->MountCreatureID[1] != 32981) + { sAllianceTaxiNodesMask[field] |= submask; + } if (node->MountCreatureID[0] == 32981 || node->MountCreatureID[1] == 32981) + { sDeathKnightTaxiNodesMask[field] |= submask; + } // old continent node (+ nodes virtually at old continents, check explicitly to avoid loading map files for zone info) if (node->map_id < 2 || i == 82 || i == 83 || i == 93 || i == 94) + { sOldContinentsNodesMask[field] |= submask; + } // fix DK node at Ebon Hold if (i == 315) + { (const_cast(node))->MountCreatureID[1] = node->MountCreatureID[0]; + } } } @@ -854,7 +916,9 @@ void LoadDBCStores(const std::string& dataPath) LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTransportAnimationStore, dbcPath,"TransportAnimation.dbc"); for (uint32 i = 0; i < sTransportAnimationStore.GetNumRows(); ++i) if (TransportAnimationEntry const* entry = sTransportAnimationStore.LookupEntry(i)) + { sTransportAnimationsByEntry[entry->transportEntry][entry->timeFrame] = entry; + } LoadDBC(availableDbcLocales, bar, bad_dbc_files, sVehicleStore, dbcPath, "Vehicle.dbc"); LoadDBC(availableDbcLocales, bar, bad_dbc_files, sVehicleSeatStore, dbcPath, "VehicleSeat.dbc"); @@ -1186,7 +1250,9 @@ ContentLevels GetContentLevelsForMapAndZone(uint32 mapId, uint32 zoneId) } if (mapEntry->rootPhaseMap != -1) + { mapId = mapEntry->rootPhaseMap; + } switch (mapId) { @@ -1233,7 +1299,9 @@ PvPDifficultyEntry const* GetBattlegroundBracketByLevel(uint32 mapid, uint32 lev { // skip unrelated and too-high brackets if (entry->mapId != mapid || entry->minLevel > level) + { continue; + } // exactly fit if (entry->maxLevel >= level) @@ -1243,7 +1311,9 @@ PvPDifficultyEntry const* GetBattlegroundBracketByLevel(uint32 mapid, uint32 lev // remember for possible out-of-range case (search higher from existed) if (!maxEntry || maxEntry->maxLevel < entry->maxLevel) + { maxEntry = entry; + } } } diff --git a/src/game/Server/DBCStructure.cpp b/src/game/Server/DBCStructure.cpp index 7675c9519..7e15a6321 100644 --- a/src/game/Server/DBCStructure.cpp +++ b/src/game/Server/DBCStructure.cpp @@ -31,14 +31,18 @@ int32 SpellEntry::CalculateSimpleValue(SpellEffectIndex eff) const { if(SpellEffectEntry const* effectEntry = GetSpellEffectEntry(Id, eff)) + { return effectEntry->CalculateSimpleValue(); + } return 0; } ClassFamilyMask const& SpellEntry::GetEffectSpellClassMask(SpellEffectIndex eff) const { if (SpellEffectEntry const* effectEntry = GetSpellEffectEntry(Id, eff)) + { return effectEntry->EffectSpellClassMask; + } static ClassFamilyMask const emptyCFM; diff --git a/src/game/Server/DBCStructure.h b/src/game/Server/DBCStructure.h index 44b53a09b..0cb172390 100644 --- a/src/game/Server/DBCStructure.h +++ b/src/game/Server/DBCStructure.h @@ -1464,7 +1464,9 @@ struct MapEntry bool IsTransport() const { if (IsContinent()) + { return false; + } return map_type == MAP_COMMON && mapFlags == MAP_FLAG_INSTANCEABLE; } }; @@ -1634,11 +1636,17 @@ struct ScalingStatValuesEntry if (mask & 0x4001F) { if(mask & 0x00000001) return ssdMultiplier[1]; - if(mask & 0x00000002) return ssdMultiplier[2]; // 0 and 1 were duplicated + { + if(mask & 0x00000002) return ssdMultiplier[2]; // 0 and 1 were duplicated + } if(mask & 0x00000004) return ssdMultiplier[3]; - if(mask & 0x00000008) return ssdMultiplier[0]; + { + if(mask & 0x00000008) return ssdMultiplier[0]; + } if(mask & 0x00000010) return ssdMultiplier[4]; - if(mask & 0x00040000) return ssdMultiplier[2]; // 4.0.0 + { + if(mask & 0x00040000) return ssdMultiplier[2]; // 4.0.0 + } } return 0; } @@ -1648,14 +1656,22 @@ struct ScalingStatValuesEntry if (mask & 0x00F001E0) { if (mask & 0x00000020) return armorMod[0]; - if (mask & 0x00000040) return armorMod[1]; + { + if (mask & 0x00000040) return armorMod[1]; + } if (mask & 0x00000080) return armorMod[2]; - if (mask & 0x00000100) return armorMod[3]; + { + if (mask & 0x00000100) return armorMod[3]; + } if (mask & 0x00100000) return armorMod2[0]; // cloth - if (mask & 0x00200000) return armorMod2[1]; // leather + { + if (mask & 0x00200000) return armorMod2[1]; // leather + } if (mask & 0x00400000) return armorMod2[2]; // mail - if (mask & 0x00800000) return armorMod2[3]; // plate + { + if (mask & 0x00800000) return armorMod2[3]; // plate + } } return 0; } @@ -1665,11 +1681,17 @@ struct ScalingStatValuesEntry if (mask & 0x7E00) { if (mask & 0x00000200) return dpsMod[0]; - if (mask & 0x00000400) return dpsMod[1]; + { + if (mask & 0x00000400) return dpsMod[1]; + } if (mask & 0x00000800) return dpsMod[2]; - if (mask & 0x00001000) return dpsMod[3]; + { + if (mask & 0x00001000) return dpsMod[3]; + } if (mask & 0x00002000) return dpsMod[4]; - if (mask & 0x00004000) return dpsMod[5]; // not used? + { + if (mask & 0x00004000) return dpsMod[5]; // not used? + } } return 0; } diff --git a/src/game/Server/WorldSession.cpp b/src/game/Server/WorldSession.cpp index a5cb31231..bd7e28be2 100644 --- a/src/game/Server/WorldSession.cpp +++ b/src/game/Server/WorldSession.cpp @@ -147,7 +147,9 @@ WorldSession::~WorldSession() ///- empty incoming packet queue WorldPacket* packet = NULL; while (_recvQueue.next(packet)) - { delete packet; } + { + delete packet; + } } void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const @@ -168,9 +170,13 @@ void WorldSession::SendPacket(WorldPacket const* packet) #ifdef ENABLE_PLAYERBOTS if (GetPlayer()) { if (GetPlayer()->GetPlayerbotAI()) + { GetPlayer()->GetPlayerbotAI()->HandleBotOutgoingPacket(*packet); + } else if (GetPlayer()->GetPlayerbotMgr()) + { GetPlayer()->GetPlayerbotMgr()->HandleMasterOutgoingPacket(*packet); + } } #endif @@ -290,7 +296,9 @@ bool WorldSession::Update(PacketFilter& updater) #ifdef ENABLE_PLAYERBOTS if (_player && _player->GetPlayerbotMgr()) + { _player->GetPlayerbotMgr()->HandleMasterIncomingPacket(*packet); + } #endif break; case STATUS_LOGGEDIN_OR_RECENTLY_LOGGEDOUT: @@ -300,7 +308,9 @@ bool WorldSession::Update(PacketFilter& updater) } else // not expected _player or must checked in packet hanlder - { ExecuteOpcode(opHandle, packet); } + { + ExecuteOpcode(opHandle, packet); + } break; case STATUS_TRANSFER: if (!_player) @@ -327,7 +337,9 @@ bool WorldSession::Update(PacketFilter& updater) // single from authed time opcodes send in to after logout time // and before other STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes. if (packet->GetOpcode() != CMSG_SET_ACTIVE_VOICE_CHANNEL) + { m_playerRecentlyLogout = false; + } ExecuteOpcode(opHandle, packet); break; @@ -372,7 +384,9 @@ bool WorldSession::Update(PacketFilter& updater) #ifdef ENABLE_PLAYERBOTS if (GetPlayer() && GetPlayer()->GetPlayerbotMgr()) + { GetPlayer()->GetPlayerbotMgr()->UpdateSessions(0); + } #endif ///- Cleanup socket pointer if need @@ -401,7 +415,9 @@ bool WorldSession::Update(PacketFilter& updater) // _warden->Update(); if (!m_Socket) - { return false; } // Will remove this session from the world session map + { + return false; // Will remove this session from the world session map + } } return true; @@ -425,7 +441,9 @@ void WorldSession::LogoutPlayer(bool Save) { // finish pending transfers before starting the logout while (_player && _player->IsBeingTeleportedFar()) - { HandleMoveWorldportAckOpcode(); } + { + HandleMoveWorldportAckOpcode(); + } m_playerLogout = true; m_playerSave = Save; @@ -434,7 +452,9 @@ void WorldSession::LogoutPlayer(bool Save) { #ifdef ENABLE_PLAYERBOTS if (GetPlayer()->GetPlayerbotMgr()) + { GetPlayer()->GetPlayerbotMgr()->LogoutAllBots(); + } #endif sLog.outChar("Account: %d (IP: %s) Logout Character:[%s] (guid: %u)", GetAccountId(), GetRemoteAddress().c_str(), _player->GetName() , _player->GetGUIDLow()); @@ -446,7 +466,9 @@ void WorldSession::LogoutPlayer(bool Save) #ifdef ENABLE_PLAYERBOTS if (_player->GetPlayerbotMgr()) + { _player->GetPlayerbotMgr()->LogoutAllBots(); + } sRandomPlayerbotMgr.OnPlayerLogout(_player); #endif @@ -527,7 +549,9 @@ void WorldSession::LogoutPlayer(bool Save) // FG: finish pending transfers after starting the logout // this should fix players beeing able to logout and login back with full hp at death position while (_player->IsBeingTeleportedFar()) - { HandleMoveWorldportAckOpcode(); } + { + HandleMoveWorldportAckOpcode(); + } for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) { @@ -752,13 +776,17 @@ void WorldSession::SendSetPhaseShift(uint32 phaseMask, uint16 mapId) data << uint32(phaseMask ? 2 : 0); // WRONG: number of Phase.dbc ids * 2 if (phaseMask) + { data << uint16(phaseMask); + } data.WriteGuidBytes<3, 0>(guid); data << uint32(mapId ? 2 : 0); // number of terrains swaps * 2 if (mapId) + { data << uint16(mapId); + } data.WriteGuidBytes<5>(guid); SendPacket(&data); @@ -912,7 +940,9 @@ void WorldSession::SendAuthResponse(uint8 code, bool queued, uint32 queuePos) packet << uint8(code); packet.WriteBit(queued); // IsInQueue if (queued) + { packet.WriteBit(1); // unk + } packet.WriteBit(hasAccountData); @@ -950,7 +980,9 @@ void WorldSession::SendAuthResponse(uint8 code, bool queued, uint32 queuePos) } if (queued) + { packet << uint32(queuePos); + } SendPacket(&packet); } @@ -967,7 +999,9 @@ void WorldSession::LoadAccountData(QueryResult* result, uint32 mask) { for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i) if (mask & (1 << i)) + { m_accountData[i] = AccountData(); + } if (!result) { @@ -1053,7 +1087,9 @@ void WorldSession::SendAccountDataTimes(uint32 mask) data.WriteBit(1); for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i) + { data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time + } data << uint32(mask); // type mask data << uint32(time(NULL)); // unix time of something @@ -1222,7 +1258,9 @@ void WorldSession::ReadAddonsInfo(ByteBuffer &data) } } else + { sLog.outError("Addon packet uncompress error!"); + } } void WorldSession::SendAddonsInfo() @@ -1261,7 +1299,9 @@ void WorldSession::SendAddonsInfo() uint8 unk2 = (itr->CRC != 0x4c1c776d); // If addon is Standard addon CRC data << uint8(unk2); // if 1, than add addon public signature if (unk2) // if CRC is wrong, add public key (client need it) + { data.append(tdata, sizeof(tdata)); + } data << uint32(0); } diff --git a/src/game/Server/WorldSocket.cpp b/src/game/Server/WorldSocket.cpp index 304cdfaeb..43fc10431 100644 --- a/src/game/Server/WorldSocket.cpp +++ b/src/game/Server/WorldSocket.cpp @@ -193,11 +193,15 @@ int WorldSocket::SendPacket(const WorldPacket& pct) { // Put the packet on the buffer. if (m_OutBuffer->copy((char*) header.header, header.getHeaderLength()) == -1) + { MANGOS_ASSERT(false); + } if (!pct.empty()) if (m_OutBuffer->copy((char*) pct.contents(), pct.size()) == -1) + { MANGOS_ASSERT(false); + } } else { @@ -209,7 +213,9 @@ int WorldSocket::SendPacket(const WorldPacket& pct) mb->copy((char*) header.header, header.getHeaderLength()); if (!pct.empty()) + { mb->copy((const char*)pct.contents(), pct.size()); + } if (msg_queue()->enqueue_tail(mb, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1) { @@ -326,7 +332,9 @@ int WorldSocket::SendAuthChallenge() packet << uint16(0); for (int i = 0; i < 8; i++) + { packet << uint32(0); + } packet << uint8(1); packet << uint32(m_Seed); @@ -1050,8 +1058,7 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket) std::string address = GetRemoteAddress(); DEBUG_LOG("WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.", - accountName.c_str (), - address.c_str()); + account.c_str (), address.c_str()); // Update the last_ip in the database // No SQL injection, username escaped. @@ -1074,7 +1081,9 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket) // Warden: Initialize Warden system only if it is enabled by config if (wardenActive) + { m_Session->InitWarden(uint16(BuiltNumberClient), &K, os); + } sWorld.AddSession(m_Session); @@ -1091,7 +1100,9 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket) recvPacket >> latency; if (m_LastPingTime == ACE_Time_Value::zero) - { m_LastPingTime = ACE_OS::gettimeofday(); } // for 1st ping + { + m_LastPingTime = ACE_OS::gettimeofday(); // for 1st ping + } else { ACE_Time_Value cur_time = ACE_OS::gettimeofday(); diff --git a/src/game/Server/WorldSocketMgr.cpp b/src/game/Server/WorldSocketMgr.cpp index 2131144a8..b94837af4 100644 --- a/src/game/Server/WorldSocketMgr.cpp +++ b/src/game/Server/WorldSocketMgr.cpp @@ -53,7 +53,9 @@ WorldSocketMgr::WorldSocketMgr() WorldSocketMgr::~WorldSocketMgr() { if (reactor_) delete reactor_; - if (acceptor_) delete acceptor_; + { + if (acceptor_) delete acceptor_; + } } @@ -140,7 +142,9 @@ int WorldSocketMgr::StartNetwork(ACE_INET_Addr& addr) void WorldSocketMgr::StopNetwork() { if (acceptor_) acceptor_->close(); - if (reactor_) reactor_->end_reactor_event_loop(); + { + if (reactor_) reactor_->end_reactor_event_loop(); + } wait(); } diff --git a/src/game/Tools/CharacterDatabaseCleaner.cpp b/src/game/Tools/CharacterDatabaseCleaner.cpp index 828d78541..f7247d949 100644 --- a/src/game/Tools/CharacterDatabaseCleaner.cpp +++ b/src/game/Tools/CharacterDatabaseCleaner.cpp @@ -50,7 +50,9 @@ void CharacterDatabaseCleaner::CleanDatabase() // clean up if (flags & CLEANING_FLAG_ACHIEVEMENT_PROGRESS) + { CleanCharacterAchievementProgress(); + } if (flags & CLEANING_FLAG_SKILLS) { CleanCharacterSkills(); diff --git a/src/game/Tools/PlayerDump.cpp b/src/game/Tools/PlayerDump.cpp index 6e3b0b4e7..ebf5828f0 100644 --- a/src/game/Tools/PlayerDump.cpp +++ b/src/game/Tools/PlayerDump.cpp @@ -158,7 +158,9 @@ bool changenth(std::string& str, int n, const char* with, bool insert = false, b } if (nonzero && str.substr(s, e - s) == "0") - { return true; } // not an error + { + return true; // not an error + } if (!insert) { str.replace(s, e - s, with); @@ -190,7 +192,9 @@ bool changetoknth(std::string& str, int n, const char* with, bool insert = false return false; } if (nonzero && str.substr(s, e - s) == "0") - { return true; } // not an error + { + return true; // not an error + } if (!insert) { str.replace(s, e - s, with); @@ -221,7 +225,9 @@ bool changeGuid(std::string& str, int n, std::map& guidMap, uint char chritem[20]; uint32 oldGuid = atoi(getnth(str, n).c_str()); if (nonzero && oldGuid == 0) - { return true; } // not an error + { + return true; // not an error + } uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid); snprintf(chritem, 20, "%u", newGuid); @@ -234,7 +240,9 @@ bool changetokGuid(std::string& str, int n, std::map& guidMap, u char chritem[20]; uint32 oldGuid = atoi(gettoknth(str, n).c_str()); if (nonzero && oldGuid == 0) - { return true; } // not an error + { + return true; // not an error + } uint32 newGuid = registerNewGuid(oldGuid, guidMap, hiGuid); snprintf(chritem, 20, "%u", newGuid); @@ -348,7 +356,9 @@ void PlayerDumpWriter::DumpTableContent(std::string& dump, uint32 guid, char con // for guid set stop if set is empty if (guids && guids->empty()) - { return; } // nothing to do + { + return; // nothing to do + } // setup for guids case start position GUIDs::const_iterator guids_itr; @@ -522,7 +532,9 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s // normalize the name if specified and check if it exists if (!normalizePlayerName(name)) + { name = ""; + } if (ObjectMgr::CheckPlayerName(name, true) == CHAR_NAME_SUCCESS) { @@ -535,7 +547,9 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s } } else + { name = ""; + } // name encoded or empty @@ -655,7 +669,9 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s } if (!changenth(line, 1, newguid)) // character_*.guid update + { ROLLBACK(DUMP_FILE_BROKEN); + } break; case DTT_CHARACTER: @@ -709,25 +725,35 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s } if (!changeGuid(line, 2, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed(), true)) - { ROLLBACK(DUMP_FILE_BROKEN); } // character_inventory.bag update + { + ROLLBACK(DUMP_FILE_BROKEN); // character_inventory.bag update + } if (!changeGuid(line, 4, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // character_inventory.item update + { + ROLLBACK(DUMP_FILE_BROKEN); // character_inventory.item update + } break; } case DTT_ITEM: { // item, owner, data field:item, owner guid if (!changeGuid(line, 1, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // item_instance.guid update + { + ROLLBACK(DUMP_FILE_BROKEN); // item_instance.guid update + } if (!changenth(line, 2, newguid)) // item_instance.owner_guid update { ROLLBACK(DUMP_FILE_BROKEN); } std::string vals = getnth(line, 3); // item_instance.data get if (!changetokGuid(vals, OBJECT_FIELD_GUID + 1, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // item_instance.data.OBJECT_FIELD_GUID update + { + ROLLBACK(DUMP_FILE_BROKEN); // item_instance.data.OBJECT_FIELD_GUID update + } if (!changetoknth(vals, ITEM_FIELD_OWNER + 1, newguid)) - { ROLLBACK(DUMP_FILE_BROKEN); } // item_instance.data.ITEM_FIELD_OWNER update + { + ROLLBACK(DUMP_FILE_BROKEN); // item_instance.data.ITEM_FIELD_OWNER update + } if (!changenth(line, 3, vals.c_str())) // item_instance.data update { ROLLBACK(DUMP_FILE_BROKEN); @@ -741,14 +767,18 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s ROLLBACK(DUMP_FILE_BROKEN); } if (!changeGuid(line, 2, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // character_gifts.item_guid update + { + ROLLBACK(DUMP_FILE_BROKEN); // character_gifts.item_guid update + } break; } case DTT_ITEM_LOOT: { // item, owner if (!changeGuid(line, 1, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // item_loot.guid update + { + ROLLBACK(DUMP_FILE_BROKEN); // item_loot.guid update + } if (!changenth(line, 2, newguid)) // item_Loot.owner_guid update { ROLLBACK(DUMP_FILE_BROKEN); @@ -815,22 +845,30 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s // lookup currpetid and match to new inserted pet id std::map :: const_iterator petids_iter = petids.find(atoi(currpetid)); if (petids_iter == petids.end()) // couldn't find new inserted id + { ROLLBACK(DUMP_FILE_BROKEN); + } snprintf(newpetid, 20, "%d", petids_iter->second); if (!changenth(line, 1, newpetid)) // character_pet_declinedname.id + { ROLLBACK(DUMP_FILE_BROKEN); + } if (!changenth(line, 2, newguid)) // character_pet_declinedname.owner update + { ROLLBACK(DUMP_FILE_BROKEN); + } break; } case DTT_MAIL: // mail { if (!changeGuid(line, 1, mails, sObjectMgr.m_MailIds.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // mail.id update + { + ROLLBACK(DUMP_FILE_BROKEN); // mail.id update + } if (!changenth(line, 6, newguid)) // mail.receiver update { ROLLBACK(DUMP_FILE_BROKEN); @@ -840,9 +878,13 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s case DTT_MAIL_ITEM: // mail_items { if (!changeGuid(line, 1, mails, sObjectMgr.m_MailIds.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // mail_items.id + { + ROLLBACK(DUMP_FILE_BROKEN); // mail_items.id + } if (!changeGuid(line, 2, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) - { ROLLBACK(DUMP_FILE_BROKEN); } // mail_items.item_guid + { + ROLLBACK(DUMP_FILE_BROKEN); // mail_items.item_guid + } if (!changenth(line, 4, newguid)) // mail_items.receiver { ROLLBACK(DUMP_FILE_BROKEN); @@ -852,12 +894,18 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s case DTT_EQSET_TABLE: { if (!changenth(line, 1, newguid)) // character_equipmentsets.guid update + { ROLLBACK(DUMP_FILE_BROKEN); + } if (!changeGuid(line, 2, eqsets, sObjectMgr.m_EquipmentSetIds.GetNextAfterMaxUsed())) + { ROLLBACK(DUMP_FILE_BROKEN); // character_equipmentsets.setguid + } for (int i = 0; i < 19; ++i) // character_equipmentsets.item0..item18 if (!changeGuid(line, 6 + i, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed())) + { ROLLBACK(DUMP_FILE_BROKEN); + } break; } default: diff --git a/src/game/Warden/Warden.cpp b/src/game/Warden/Warden.cpp index 97dded50e..d6b736ce2 100644 --- a/src/game/Warden/Warden.cpp +++ b/src/game/Warden/Warden.cpp @@ -259,9 +259,13 @@ std::string Warden::Penalty(WardenCheck* check /*= NULL*/) WardenActions action; if (check) + { action = check->Action; + } else + { action = WardenActions(sWorld.getConfig(CONFIG_UINT32_WARDEN_CLIENT_FAIL_ACTION)); + } switch (action) { @@ -281,7 +285,9 @@ std::string Warden::Penalty(WardenCheck* check /*= NULL*/) banReason << "Warden Anticheat Violation"; // Check can be NULL, for example if the client sent a wrong signature in the warden packet (CHECKSUM FAIL) if (check) + { banReason << ": " << (check->Comment.empty() ? std::string("Undocumented Check") : check->Comment) << " (CheckId: " << check->CheckId << ")"; + } sWorld.BanAccount(BAN_ACCOUNT, accountName, sWorld.getConfig(CONFIG_UINT32_WARDEN_CLIENT_BAN_DURATION), banReason.str(), "Warden"); diff --git a/src/game/Warden/WardenCheckMgr.cpp b/src/game/Warden/WardenCheckMgr.cpp index 963c45ae2..4d7b3021d 100644 --- a/src/game/Warden/WardenCheckMgr.cpp +++ b/src/game/Warden/WardenCheckMgr.cpp @@ -37,10 +37,14 @@ WardenCheckMgr::WardenCheckMgr() : m_lock(0), CheckStore(), CheckResultStore() { WardenCheckMgr::~WardenCheckMgr() { for (CheckMap::iterator it = CheckStore.begin(); it != CheckStore.end(); ++it) + { delete it->second; + } for (CheckResultMap::iterator it = CheckResultStore.begin(); it != CheckResultStore.end(); ++it) + { delete it->second; + } CheckStore.clear(); CheckResultStore.clear(); @@ -110,7 +114,9 @@ void WardenCheckMgr::LoadWardenChecks() // PROC_CHECK support missing if (checkType == MEM_CHECK || checkType == MPQ_CHECK || checkType == LUA_STR_CHECK || checkType == DRIVER_CHECK || checkType == MODULE_CHECK) + { wardenCheck->Str = str; + } CheckStore.insert(std::pair(build, wardenCheck)); @@ -133,9 +139,13 @@ void WardenCheckMgr::LoadWardenChecks() } if (comment.empty()) + { wardenCheck->Comment = ""; + } else + { wardenCheck->Comment = comment; + } ++count; } while (result->NextRow()); @@ -176,7 +186,9 @@ void WardenCheckMgr::LoadWardenOverrides() // Check if action value is in range (0-2, see WardenActions enum) if (action > WARDEN_ACTION_BAN) + { sLog.outWarden("Warden check override action out of range (ID: %u, action: %u)", checkId, action); + } else { bool found = false; @@ -206,7 +218,9 @@ WardenCheck* WardenCheckMgr::GetWardenDataById(uint16 build, uint16 id) for (CheckMap::iterator it = CheckStore.lower_bound(build); it != CheckStore.upper_bound(build); ++it) { if (it->second->CheckId == id) + { result = it->second; + } } return result; @@ -220,7 +234,9 @@ WardenCheckResult* WardenCheckMgr::GetWardenResultById(uint16 build, uint16 id) for (CheckResultMap::iterator it = CheckResultStore.lower_bound(build); it != CheckResultStore.upper_bound(build); ++it) { if (it->second->Id == id) + { result = it->second; + } } return result; @@ -236,9 +252,13 @@ void WardenCheckMgr::GetWardenCheckIds(bool isMemCheck, uint16 build, std::list< if (isMemCheck) { if ((it->second->Type == MEM_CHECK) || (it->second->Type == MODULE_CHECK)) + { idl.push_back(it->second->CheckId); + } } else + { idl.push_back(it->second->CheckId); + } } -} \ No newline at end of file +} diff --git a/src/game/Warden/WardenMac.cpp b/src/game/Warden/WardenMac.cpp index 6e0564cf0..49ded8210 100644 --- a/src/game/Warden/WardenMac.cpp +++ b/src/game/Warden/WardenMac.cpp @@ -156,7 +156,9 @@ void WardenMac::HandleHashResult(ByteBuffer &buff) { sLog.outWarden("%s failed hash reply. Action: %s", _session->GetPlayerName(), Penalty().c_str()); if (sWorld.getConfig(CONFIG_UINT32_WARDEN_CLIENT_FAIL_ACTION) > uint32(WARDEN_ACTION_LOG)) + { _session->KickPlayer(); + } return; } @@ -254,9 +256,13 @@ void WardenMac::HandleData(ByteBuffer &buff) } if (found && sWorld.getConfig(CONFIG_UINT32_WARDEN_CLIENT_FAIL_ACTION) > uint32(WARDEN_ACTION_LOG)) + { _session->KickPlayer(); + } else + { sLog.outWarden("SHA1 and MD5 hash verified. Handle data passed."); + } Warden::HandleData(buff); } diff --git a/src/game/Warden/WardenWin.cpp b/src/game/Warden/WardenWin.cpp index 836eef4ba..f07a3ff9c 100644 --- a/src/game/Warden/WardenWin.cpp +++ b/src/game/Warden/WardenWin.cpp @@ -170,10 +170,14 @@ void WardenWin::RequestData() // If all checks were done, fill the todo list again if (_memChecksTodo.empty()) + { sWardenCheckMgr->GetWardenCheckIds(true, build, _memChecksTodo); + } if (_otherChecksTodo.empty()) + { sWardenCheckMgr->GetWardenCheckIds(false, build, _otherChecksTodo); + } _serverTicks = WorldTimer::getMSTime(); @@ -184,7 +188,9 @@ void WardenWin::RequestData() { // If todo list is done break loop (will be filled on next Update() run) if (_memChecksTodo.empty()) + { break; + } // Get check id from the end and remove it from todo id = _memChecksTodo.back(); @@ -201,7 +207,9 @@ void WardenWin::RequestData() { // If todo list is done break loop (will be filled on next Update() run) if (_otherChecksTodo.empty()) + { break; + } // Get check id from the end and remove it from todo id = _otherChecksTodo.back(); @@ -400,11 +408,17 @@ void WardenWin::HandleData(ByteBuffer &buff) if (memcmp(buff.contents() + buff.rpos(), &byte, sizeof(uint8)) != 0) { if (type == PAGE_CHECK_A || type == PAGE_CHECK_B) + { sLog.outWarden("RESULT PAGE_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + } if (type == MODULE_CHECK) + { sLog.outWarden("RESULT MODULE_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + } if (type == DRIVER_CHECK) + { sLog.outWarden("RESULT DRIVER_CHECK fail, CheckId %u account Id %u", *itr, _session->GetAccountId()); + } checkFailed = *itr; buff.rpos(buff.rpos() + 1); continue; @@ -412,11 +426,17 @@ void WardenWin::HandleData(ByteBuffer &buff) buff.rpos(buff.rpos() + 1); if (type == PAGE_CHECK_A || type == PAGE_CHECK_B) + { sLog.outWarden("RESULT PAGE_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); + } else if (type == MODULE_CHECK) + { sLog.outWarden("RESULT MODULE_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); + } else if (type == DRIVER_CHECK) + { sLog.outWarden("RESULT DRIVER_CHECK passed CheckId %u account Id %u", *itr, _session->GetAccountId()); + } break; } case LUA_STR_CHECK: diff --git a/src/game/WorldHandlers/AccountMgr.cpp b/src/game/WorldHandlers/AccountMgr.cpp index 92bfd2f19..e64f91f0c 100644 --- a/src/game/WorldHandlers/AccountMgr.cpp +++ b/src/game/WorldHandlers/AccountMgr.cpp @@ -44,18 +44,24 @@ AccountMgr::~AccountMgr() AccountOpResult AccountMgr::CreateAccount(std::string username, std::string password) { if (utf8length(username) > MAX_ACCOUNT_STR) - { return AOR_NAME_TOO_LONG; } // username's too long + { + return AOR_NAME_TOO_LONG; // username's too long + } normalizeString(username); normalizeString(password); if (GetId(username)) { - { return AOR_NAME_ALREADY_EXIST; } // username does already exist + { + return AOR_NAME_ALREADY_EXIST; // username does already exist + } } if (!LoginDatabase.PExecute("INSERT INTO `account` (`username`,`sha_pass_hash`,`joindate`) VALUES ('%s','%s',NOW())", username.c_str(), CalculateShaPassHash(username, password).c_str())) - { return AOR_DB_INTERNAL_ERROR; } // unexpected error + { + return AOR_DB_INTERNAL_ERROR; // unexpected error + } LoginDatabase.Execute("INSERT INTO `realmcharacters` (`realmid`, `acctid`, `numchars`) SELECT `realmlist`.`id`, `account`.`id`, 0 FROM `realmlist`,`account` LEFT JOIN `realmcharacters` ON `acctid`=`account`.`id` WHERE `acctid` IS NULL"); return AOR_OK; // everything's fine @@ -64,7 +70,9 @@ AccountOpResult AccountMgr::CreateAccount(std::string username, std::string pass AccountOpResult AccountMgr::CreateAccount(std::string username, std::string password, uint32 expansion) { if (utf8length(username) > MAX_ACCOUNT_STR) + { return AOR_NAME_TOO_LONG; // username's too long + } normalizeString(username); normalizeString(password); @@ -75,7 +83,9 @@ AccountOpResult AccountMgr::CreateAccount(std::string username, std::string pass } if (!LoginDatabase.PExecute("INSERT INTO `account`(`username`,`sha_pass_hash`,`joindate`,`expansion`) VALUES('%s','%s',NOW(),'%u')", username.c_str(), CalculateShaPassHash(username, password).c_str(), expansion)) + { return AOR_DB_INTERNAL_ERROR; // unexpected error + } LoginDatabase.Execute("INSERT INTO `realmcharacters` (`realmid`, `acctid`, `numchars`) SELECT `realmlist`.`id`, `account`.`id`, 0 FROM `realmlist`,`account` LEFT JOIN `realmcharacters` ON `acctid`=`account`.`id` WHERE `acctid` IS NULL"); return AOR_OK; // everything's fine @@ -85,7 +95,9 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accid) { QueryResult* result = LoginDatabase.PQuery("SELECT 1 FROM `account` WHERE `id`='%u'", accid); if (!result) - { return AOR_NAME_NOT_EXIST; } // account doesn't exist + { + return AOR_NAME_NOT_EXIST; // account doesn't exist + } delete result; // existing characters list @@ -119,7 +131,9 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accid) LoginDatabase.CommitTransaction(); if (!res) - { return AOR_DB_INTERNAL_ERROR; } // unexpected error; + { + return AOR_DB_INTERNAL_ERROR; // unexpected error; + } return AOR_OK; } @@ -128,7 +142,9 @@ AccountOpResult AccountMgr::ChangeUsername(uint32 accid, std::string new_uname, { QueryResult* result = LoginDatabase.PQuery("SELECT 1 FROM `account` WHERE `id`='%u'", accid); if (!result) - { return AOR_NAME_NOT_EXIST; } // account doesn't exist + { + return AOR_NAME_NOT_EXIST; // account doesn't exist + } delete result; if (utf8length(new_uname) > MAX_ACCOUNT_STR) @@ -149,7 +165,9 @@ AccountOpResult AccountMgr::ChangeUsername(uint32 accid, std::string new_uname, if (!LoginDatabase.PExecute("UPDATE `account` SET `v`='0',`s`='0',`username`='%s',`sha_pass_hash`='%s' WHERE `id`='%u'", safe_new_uname.c_str(), CalculateShaPassHash(new_uname, new_passwd).c_str(), accid)) - { return AOR_DB_INTERNAL_ERROR; } // unexpected error + { + return AOR_DB_INTERNAL_ERROR; // unexpected error + } return AOR_OK; } @@ -159,7 +177,9 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accid, std::string new_passwd) std::string username; if (!GetName(accid, username)) - { return AOR_NAME_NOT_EXIST; } // account doesn't exist + { + return AOR_NAME_NOT_EXIST; // account doesn't exist + } if (utf8length(new_passwd) > MAX_ACCOUNT_STR) { @@ -171,7 +191,9 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accid, std::string new_passwd) // also reset s and v to force update at next realmd login if (!LoginDatabase.PExecute("UPDATE `account` SET `v`='0', `s`='0', `sha_pass_hash`='%s' WHERE `id`='%u'", CalculateShaPassHash(username, new_passwd).c_str(), accid)) - { return AOR_DB_INTERNAL_ERROR; } // unexpected error + { + return AOR_DB_INTERNAL_ERROR; // unexpected error + } return AOR_OK; } diff --git a/src/game/WorldHandlers/AchievementMgr.cpp b/src/game/WorldHandlers/AchievementMgr.cpp index 1e1a2305e..9f9e2cf26 100644 --- a/src/game/WorldHandlers/AchievementMgr.cpp +++ b/src/game/WorldHandlers/AchievementMgr.cpp @@ -472,7 +472,9 @@ void AchievementMgr::ResetAchievementCriteria(AchievementCriteriaTypes type, uin // don't update already completed criteria if (IsCompletedCriteria(achievementCriteria, achievement)) + { continue; + } switch (type) { @@ -485,7 +487,9 @@ void AchievementMgr::ResetAchievementCriteria(AchievementCriteriaTypes type, uin case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: // have total statistic also not expected to be reset // reset only the criteria having the miscvalue1 condition if (achievementCriteria->win_rated_arena.flag == miscvalue1) + { SetCriteriaProgress(achievementCriteria, achievement, 0, PROGRESS_SET); + } break; default: // reset all cases break; @@ -515,7 +519,9 @@ void AchievementMgr::SaveToDB() for (CompletedAchievementMap::iterator iter = m_completedAchievements.begin(); iter != m_completedAchievements.end(); ++iter) { if (!iter->second.changed) + { continue; + } /// mark as saved in db iter->second.changed = false; @@ -534,7 +540,9 @@ void AchievementMgr::SaveToDB() for (CriteriaProgressMap::iterator iter = m_criteriaProgress.begin(); iter != m_criteriaProgress.end(); ++iter) { if (!iter->second.changed) + { continue; + } /// mark as updated in db iter->second.changed = false; @@ -574,7 +582,9 @@ void AchievementMgr::LoadFromDB(QueryResult* achievementResult, QueryResult* cri // don't must happen: cleanup at server startup in sAchievementMgr.LoadCompletedAchievements() if (!sAchievementStore.LookupEntry(achievement_id)) + { continue; + } CompletedAchievementData& ca = m_completedAchievements[achievement_id]; ca.date = time_t(fields[1].GetUInt64()); @@ -631,7 +641,9 @@ void AchievementMgr::LoadFromDB(QueryResult* achievementResult, QueryResult* cri m_criteriaFailTimes[criteria->ID] = failTime; // A failed Achievement - will be removed by DoFailedTimedAchievementCriterias on next tick for player if (failTime <= time(NULL)) + { progress.timedCriteriaFailed = true; + } } } @@ -661,7 +673,9 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) // Not broadcast a hidden achievement if(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN) + { return; + } if (Guild* guild = sGuildMgr.GetGuildById(GetPlayer()->GetGuildId())) { @@ -763,10 +777,14 @@ void AchievementMgr::StartTimedAchievementCriteria(AchievementCriteriaTypes type // only apply to specific timedRequirementId related criteria if (achievementCriteria->timedCriteriaMiscId != timedRequirementId) + { continue; + } if (!achievementCriteria->IsExplicitlyStartedTimedCriteria()) + { continue; + } AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementCriteria->referredAchievement); // Checked in LoadAchievementCriteriaList @@ -777,23 +795,33 @@ void AchievementMgr::StartTimedAchievementCriteria(AchievementCriteriaTypes type // don't update already completed criteria if (IsCompletedCriteria(achievementCriteria, achievement)) + { continue; + } // Only the Quest-Complete Timed Achievements need the groupcheck, so this check is only needed here if (achievementCriteria->requiredType == ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST && GetPlayer()->GetGroup()) + { continue; + } // do not start already failed timers if (startTime && time_t(startTime + achievementCriteria->timeLimit) < time(NULL)) + { continue; + } CriteriaProgress* progress = NULL; CriteriaProgressMap::iterator iter = m_criteriaProgress.find(achievementCriteria->ID); if (iter == m_criteriaProgress.end()) + { progress = &m_criteriaProgress[achievementCriteria->ID]; + } else + { progress = &iter->second; + } progress->changed = true; progress->counter = 0; @@ -881,7 +909,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui // don't update already completed criteria if (IsCompletedCriteria(achievementCriteria, achievement)) + { continue; + } // init values, real set in switch uint32 change = 0; @@ -902,7 +932,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; @@ -919,7 +951,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } change = miscvalue1; progressType = PROGRESS_ACCUMULATE; break; @@ -932,7 +966,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } change = miscvalue1; progressType = PROGRESS_HIGHEST; break; @@ -943,39 +979,53 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (achievementCriteria->win_bg.bgMapID != GetPlayer()->GetMapId()) + { continue; + } if (achievementCriteria->win_bg.additionalRequirement1_type || achievementCriteria->win_bg.additionalRequirement2_type) { // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit)) + { continue; + } } // some hardcoded requirements else { BattleGround* bg = GetPlayer()->GetBattleGround(); if (!bg) + { continue; + } switch (achievementCriteria->referredAchievement) { case 161: // AB, Overcome a 500 resource disadvantage { if (bg->GetTypeID() != BATTLEGROUND_AB) + { continue; + } if (!((BattleGroundAB*)bg)->IsTeamScores500Disadvantage(GetPlayer()->GetTeam())) + { continue; + } break; } case 156: // AB, win while controlling all 5 flags (all nodes) case 784: // EY, win while holding 4 bases (all nodes) { if (!bg->IsAllNodesControlledByTeam(GetPlayer()->GetTeam())) + { continue; + } break; } case 1762: // SA, win without losing any siege vehicles @@ -992,14 +1042,20 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (achievementCriteria->kill_creature.creatureID != miscvalue1) + { continue; + } // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit)) + { continue; + } change = miscvalue2; progressType = PROGRESS_ACCUMULATE; @@ -1020,7 +1076,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } if (!ok) + { continue; + } // skip wrong race achievements for (uint8 i = 1; i < MAX_RACES; ++i) @@ -1033,7 +1091,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } if (!ok) + { continue; + } change = GetPlayer()->getLevel(); progressType = PROGRESS_HIGHEST; @@ -1043,7 +1103,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // update at loading or specific skill update if (miscvalue1 && miscvalue1 != achievementCriteria->reach_skill_level.skillID) + { continue; + } change = GetPlayer()->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID); progressType = PROGRESS_HIGHEST; break; @@ -1052,7 +1114,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // update at loading or specific skill update if (miscvalue1 && miscvalue1 != achievementCriteria->learn_skill_level.skillID) + { continue; + } change = GetPlayer()->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID); progressType = PROGRESS_HIGHEST; break; @@ -1060,7 +1124,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: { if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) == m_completedAchievements.end()) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; @@ -1071,7 +1137,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui uint32 counter = 0; for (QuestStatusMap::const_iterator questItr = GetPlayer()->getQuestStatusMap().begin(); questItr != GetPlayer()->getQuestStatusMap().end(); ++questItr) if (questItr->second.m_rewarded) + { ++counter; + } change = counter; progressType = PROGRESS_HIGHEST; break; @@ -1080,14 +1148,18 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // speedup for non-login case if (miscvalue1 && miscvalue1 != achievementCriteria->complete_quests_in_zone.zoneID) + { continue; + } uint32 counter = 0; for (QuestStatusMap::const_iterator questItr = GetPlayer()->getQuestStatusMap().begin(); questItr != GetPlayer()->getQuestStatusMap().end(); ++questItr) { Quest const* quest = sObjectMgr.GetQuestTemplate(questItr->first); if (questItr->second.m_rewarded && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID) + { ++counter; + } } change = counter; progressType = PROGRESS_HIGHEST; @@ -1107,18 +1179,26 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (GetPlayer()->GetMapId() != achievementCriteria->complete_battleground.mapID) + { continue; + } change = miscvalue1; progressType = PROGRESS_ACCUMULATE; break; case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (GetPlayer()->GetMapId() != achievementCriteria->death_at_map.mapID) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; @@ -1126,7 +1206,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } // skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter bool notfit = false; for (int j = 0; j < MAX_ARENA_SLOT; ++j) @@ -1135,13 +1217,17 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { BattleGround* bg = GetPlayer()->GetBattleGround(); if (!bg || !bg->isArena() || ArenaTeam::GetSlotByType(bg->GetArenaType()) != j) + { notfit = true; + } break; } } if (notfit) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1151,11 +1237,15 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } Map const* map = GetPlayer()->IsInWorld() ? GetPlayer()->GetMap() : sMapMgr.FindMap(GetPlayer()->GetMapId(), GetPlayer()->GetInstanceId()); if (!map || !map->IsDungeon()) + { continue; + } // search case bool found = false; @@ -1167,19 +1257,25 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // if raid accepted (ignore difficulty) if (!achievIdForDungeon[j][2]) + { break; // for + } } else if (GetPlayer()->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL) { // dungeon in normal mode accepted if (!achievIdForDungeon[j][1]) + { break; // for + } } else { // dungeon in heroic mode accepted if (!achievIdForDungeon[j][3]) + { break; // for + } } found = true; @@ -1187,11 +1283,15 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } } if (!found) + { continue; + } // FIXME: work only for instances where max==min for players if (map->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1200,20 +1300,28 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (miscvalue1 != achievementCriteria->killed_by_creature.creatureEntry) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } // if team check required: must kill by opposition faction if (achievement->ID == 318 && miscvalue2 == uint32(GetPlayer()->GetTeam())) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1222,12 +1330,16 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit)) + { continue; + } // miscvalue1 is the ingame fallheight*100 as stored in dbc change = miscvalue1; @@ -1237,9 +1349,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (miscvalue2 != achievementCriteria->death_from.type) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; @@ -1249,13 +1365,17 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui if (miscvalue1) { if (miscvalue1 != achievementCriteria->complete_quest.questID) + { continue; + } } else { // login case. if (!GetPlayer()->GetQuestRewardStatus(achievementCriteria->complete_quest.questID)) + { continue; + } } // exist many achievements with this criteria, use at this moment hardcoded check to skip simple case @@ -1271,7 +1391,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit)) + { continue; + } break; } default: @@ -1280,7 +1402,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui // As the groupFlag had wrong meaning, only the Quest-Complete Timed Achievements need the groupcheck, so this check is only needed here if (achievementCriteria->timeLimit > 0 && GetPlayer()->GetGroup()) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; @@ -1290,15 +1414,21 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: { if (!miscvalue1 || miscvalue1 != achievementCriteria->be_spell_target.spellID) + { continue; + } // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data) + { continue; + } if (!data->Meets(GetPlayer(), unit)) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1308,15 +1438,21 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: { if (!miscvalue1 || miscvalue1 != achievementCriteria->cast_spell.spellID) + { continue; + } // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data) + { continue; + } if (!data->Meets(GetPlayer(), unit)) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1324,10 +1460,14 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: if (miscvalue1 && miscvalue1 != achievementCriteria->learn_spell.spellID) + { continue; + } if (!GetPlayer()->HasSpell(achievementCriteria->learn_spell.spellID)) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; @@ -1337,9 +1477,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui // miscvalue1=loot_type (note: 0 = LOOT_CORPSE and then it ignored) // miscvalue2=count of item loot if (!miscvalue1 || !miscvalue2) + { continue; + } if (miscvalue1 != achievementCriteria->loot_type.lootType) + { continue; + } // zone specific if (achievementCriteria->loot_type.lootTypeCount == 1) @@ -1347,7 +1491,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit)) + { continue; + } } change = miscvalue2; @@ -1357,14 +1503,18 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: // speedup for non-login case if (miscvalue1 && achievementCriteria->own_item.itemID != miscvalue1) + { continue; + } change = GetPlayer()->GetItemCount(achievementCriteria->own_item.itemID, true); progressType = PROGRESS_HIGHEST; break; case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: // miscvalue1 contains the personal rating if (!miscvalue1) // no update at login + { continue; + } // additional requirements if (achievementCriteria->win_rated_arena.flag == ACHIEVEMENT_CRITERIA_CONDITION_NO_LOOSE) @@ -1386,13 +1536,19 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (achievementCriteria->use_item.itemID != miscvalue1) + { continue; + } // possible additional requirements AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (data && !data->Meets(GetPlayer(), unit, miscvalue1)) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; @@ -1400,9 +1556,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: // You _have_ to loot that item, just owning it when logging in does _not_ count! if (!miscvalue1) + { continue; + } if (miscvalue1 != achievementCriteria->own_item.itemID) + { continue; + } change = miscvalue2; progressType = PROGRESS_ACCUMULATE; break; @@ -1410,18 +1570,24 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference); if (!worldOverlayEntry) + { break; + } bool matchFound = false; for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) { uint32 area_id = worldOverlayEntry->areatableID[j]; if (!area_id) // array have 0 only in empty tail + { break; + } int32 exploreFlag = GetAreaFlagByAreaID(area_id); if (exploreFlag < 0) + { continue; + } uint32 playerIndexOffset = uint32(exploreFlag) / 32; uint32 mask = 1 << (uint32(exploreFlag) % 32); @@ -1434,7 +1600,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } if (!matchFound) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; @@ -1448,11 +1616,15 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // skip faction check only at loading if (miscvalue1 && miscvalue1 != achievementCriteria->gain_reputation.factionID) + { continue; + } int32 reputation = GetPlayer()->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID); if (reputation <= 0) + { continue; + } change = reputation; progressType = PROGRESS_HIGHEST; @@ -1468,7 +1640,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // skip for login case if (!miscvalue1) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; break; @@ -1477,14 +1651,20 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // miscvalue1 = equip_slot+1 (for avoid use 0) if (!miscvalue1) + { continue; + } uint32 item_slot = miscvalue1 - 1; if (item_slot != achievementCriteria->equip_epic_item.itemSlot) + { continue; + } // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit, item_slot)) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; break; @@ -1495,17 +1675,25 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui // miscvalue1 = itemid // miscvalue2 = diced value if (!miscvalue1) + { continue; + } if (miscvalue2 != achievementCriteria->roll_greed_on_loot.rollValue) + { continue; + } ItemPrototype const* pProto = ObjectMgr::GetItemPrototype(miscvalue1); uint32 requiredItemLevel = 0; if (achievementCriteria->ID == 2412 || achievementCriteria->ID == 2358) + { requiredItemLevel = 185; + } if (!pProto || pProto->ItemLevel < requiredItemLevel) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; @@ -1514,15 +1702,21 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // miscvalue1 = emote if (!miscvalue1) + { continue; + } if (miscvalue1 != achievementCriteria->do_emote.emoteID) + { continue; + } if (achievementCriteria->do_emote.count) { // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), unit)) + { continue; + } } change = 1; @@ -1533,16 +1727,22 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: { if (!miscvalue1) + { continue; + } if (achievementCriteria->healing_done.flag == ACHIEVEMENT_CRITERIA_CONDITION_MAP) { if (GetPlayer()->GetMapId() != achievementCriteria->healing_done.mapid) + { continue; + } // map specific case (BG in fact) expected player targeted damage/heal if (!unit || unit->GetTypeId() != TYPEID_PLAYER) + { continue; + } } change = miscvalue1; @@ -1552,9 +1752,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: // miscvalue1 = item_id if (!miscvalue1) + { continue; + } if (miscvalue1 != achievementCriteria->equip_item.itemID) + { continue; + } change = 1; progressType = PROGRESS_HIGHEST; @@ -1562,9 +1766,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: // miscvalue1 = go entry if (!miscvalue1) + { continue; + } if (miscvalue1 != achievementCriteria->use_gameobject.goEntry) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1573,15 +1781,21 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data) + { continue; + } if (!data->Meets(GetPlayer(), unit)) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1589,9 +1803,13 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui } case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: if (!miscvalue1) + { continue; + } if (miscvalue1 != achievementCriteria->fish_in_gameobject.goEntry) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1599,18 +1817,20 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: { if (miscvalue1 && miscvalue1 != achievementCriteria->learn_skillline_spell.skillLine) + { continue; + } uint32 spellCount = 0; - for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); - spellIter != GetPlayer()->GetSpellMap().end(); - ++spellIter) + for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); spellIter != GetPlayer()->GetSpellMap().end(); ++spellIter) { SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellIter->first); for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) { if (skillIter->second->skillId == achievementCriteria->learn_skillline_spell.skillLine) + { ++spellCount; + } } } change = spellCount; @@ -1620,17 +1840,23 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } if (achievementCriteria->win_duel.duelCount) { // those requirements couldn't be found in the dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data) + { continue; + } if (!data->Meets(GetPlayer(), unit)) + { continue; + } } change = 1; @@ -1653,10 +1879,14 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case if (!miscvalue1) + { continue; + } ItemPrototype const* proto = ObjectMgr::GetItemPrototype(miscvalue1); if (!proto || proto->Quality < ITEM_QUALITY_EPIC) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; @@ -1664,17 +1894,19 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: { if (miscvalue1 && miscvalue1 != achievementCriteria->learn_skill_line.skillLine) + { continue; + } uint32 spellCount = 0; - for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); - spellIter != GetPlayer()->GetSpellMap().end(); - ++spellIter) + for (PlayerSpellMap::const_iterator spellIter = GetPlayer()->GetSpellMap().begin(); spellIter != GetPlayer()->GetSpellMap().end(); ++spellIter) { SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellIter->first); for (SkillLineAbilityMap::const_iterator skillIter = bounds.first; skillIter != bounds.second; ++skillIter) if (skillIter->second->skillId == achievementCriteria->learn_skill_line.skillLine) + { ++spellCount; + } } change = spellCount; progressType = PROGRESS_HIGHEST; @@ -1686,14 +1918,18 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui break; case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: if (!miscvalue1 || miscvalue1 != achievementCriteria->hk_class.classID) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; break; case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: if (!miscvalue1 || miscvalue1 != achievementCriteria->hk_race.raceID) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1705,7 +1941,9 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: { if (!miscvalue1 || achievementCriteria->highest_team_rating.teamtype != miscvalue1) + { continue; + } change = miscvalue2; progressType = PROGRESS_HIGHEST; @@ -1714,10 +1952,14 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: { if (!miscvalue1 || achievementCriteria->highest_personal_rating.teamtype != miscvalue1) + { continue; + } if (achievementCriteria->highest_personal_rating.teamrating != 0 && achievementCriteria->highest_personal_rating.teamrating > miscvalue2) + { continue; + } change = miscvalue2; progressType = PROGRESS_HIGHEST; @@ -1727,12 +1969,16 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { // This criteria is only called directly after login - with expected miscvalue1 == 1 if (!miscvalue1) + { continue; + } // They have no proper requirements in dbc AchievementCriteriaRequirementSet const* data = sAchievementMgr.GetCriteriaRequirementSet(achievementCriteria); if (!data || !data->Meets(GetPlayer(), NULL)) + { continue; + } change = 1; progressType = PROGRESS_ACCUMULATE; @@ -1951,7 +2197,9 @@ uint32 AchievementMgr::GetCriteriaProgressMaxCounter(AchievementCriteriaEntry co } if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER) + { resultValue = std::numeric_limits::max(); + } return resultValue; } @@ -2001,7 +2249,9 @@ void AchievementMgr::CompletedCriteriaFor(AchievementEntry const* achievement) } if (IsCompletedAchievement(achievement)) + { CompletedAchievement(achievement); + } } bool AchievementMgr::IsCompletedAchievement(AchievementEntry const* entry) @@ -2033,7 +2283,9 @@ bool AchievementMgr::IsCompletedAchievement(AchievementEntry const* entry) CriteriaProgressMap::const_iterator itrProgress = m_criteriaProgress.find(criteria->ID); if (itrProgress == m_criteriaProgress.end()) + { continue; + } CriteriaProgress const* progress = &itrProgress->second; count += progress->counter; @@ -2057,9 +2309,13 @@ bool AchievementMgr::IsCompletedAchievement(AchievementEntry const* entry) // found an uncompleted criteria, but DONT return false yet - there might be a completed criteria with ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL if (completed) + { ++count; + } else + { completed_all = false; + } // completed as have req. count of completed criterias if (achievementForTestCount > 0 && achievementForTestCount <= count) @@ -2085,7 +2341,9 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* criteri // change value must be in allowed value range for SET/HIGHEST directly if (changeValue > max_value) + { changeValue = max_value; + } CriteriaProgress* progress = NULL; uint32 old_value = 0; @@ -2159,21 +2417,27 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* criteri if (old_value < progress->counter) { if (IsCompletedCriteria(criteria, achievement)) + { CompletedCriteriaFor(achievement); + } // check again the completeness for SUMM and REQ COUNT achievements, // as they don't depend on the completed criteria but on the sum of the progress of each individual criteria if (achievement->flags & ACHIEVEMENT_FLAG_SUMM) { if (IsCompletedAchievement(achievement)) + { CompletedAchievement(achievement); + } } if (AchievementEntryList const* achRefList = sAchievementMgr.GetAchievementByReferencedId(achievement->ID)) { for (AchievementEntryList::const_iterator itr = achRefList->begin(); itr != achRefList->end(); ++itr) if (IsCompletedAchievement(*itr)) + { CompletedAchievement(*itr); + } } } // update dependent achievements state at criteria incomplete @@ -2188,13 +2452,17 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* criteri if (HasAchievement(achievement->ID)) if (!IsCompletedAchievement(achievement)) + { IncompletedAchievement(achievement); + } if (AchievementEntryList const* achRefList = sAchievementMgr.GetAchievementByReferencedId(achievement->ID)) for (AchievementEntryList::const_iterator itr = achRefList->begin(); itr != achRefList->end(); ++itr) if (HasAchievement((*itr)->ID)) if (!IsCompletedAchievement(*itr)) + { IncompletedAchievement(*itr); + } } } @@ -2214,7 +2482,9 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) // don't insert for ACHIEVEMENT_FLAG_REALM_FIRST_KILL since otherwise only the first group member would reach that achievement // TODO: where do set this instead? if (!(achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) + { sAchievementMgr.SetRealmCompleted(achievement); + } UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT); @@ -2231,7 +2501,9 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) if (uint32 titleId = reward->titleId[GetPlayer()->GetTeam() == HORDE ? 1 : 0]) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId)) + { GetPlayer()->SetTitle(titleEntry); + } } // mail @@ -2249,9 +2521,13 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) if (AchievementRewardLocale const* loc = sAchievementMgr.GetAchievementRewardLocale(achievement, GetPlayer()->getGender())) { if (loc->subject.size() > size_t(loc_idx) && !loc->subject[loc_idx].empty()) + { subject = loc->subject[loc_idx]; + } if (loc->text.size() > size_t(loc_idx) && !loc->text[loc_idx].empty()) + { text = loc->text[loc_idx]; + } } } @@ -2307,7 +2583,9 @@ void AchievementMgr::IncompletedAchievement(AchievementEntry const* achievement) if (uint32 titleId = reward->titleId[GetPlayer()->GetTeam() == HORDE ? 0 : 1]) { if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId)) + { GetPlayer()->SetTitle(titleEntry, true); + } } // items impossible remove in clear way... @@ -2540,7 +2818,9 @@ void AchievementGlobalMgr::LoadAchievementCriteriaList() AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId); if (!criteria) + { continue; + } MANGOS_ASSERT(criteria->requiredType < ACHIEVEMENT_CRITERIA_TYPE_TOTAL && "Not updated ACHIEVEMENT_CRITERIA_TYPE_TOTAL?"); @@ -2582,7 +2862,9 @@ void AchievementGlobalMgr::LoadAchievementReferenceList() AchievementEntry const* achievement = sAchievementStore.LookupEntry(entryId); if (!achievement || !achievement->refAchievement) + { continue; + } // Check refAchievement exists AchievementEntry const* refAchiev = sAchievementStore.LookupEntry(achievement->refAchievement); @@ -2647,11 +2929,15 @@ void AchievementGlobalMgr::LoadAchievementCriteriaRequirements() // counting disable criteria requirements if (data.requirementType == ACHIEVEMENT_CRITERIA_REQUIRE_DISABLED) + { ++disabled_count; + } // add real data only for not NONE requirements if (data.requirementType != ACHIEVEMENT_CRITERIA_REQUIRE_NONE) + { dataSet.Add(data); + } // counting requirements ++count; @@ -2665,13 +2951,17 @@ void AchievementGlobalMgr::LoadAchievementCriteriaRequirements() { AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId); if (!criteria) + { continue; + } switch (criteria->requiredType) { case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: if (!criteria->win_bg.additionalRequirement1_type && !criteria->win_bg.additionalRequirement2_type) + { continue; + } break; case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: break; // any cases @@ -2701,25 +2991,33 @@ void AchievementGlobalMgr::LoadAchievementCriteriaRequirements() break; case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: // need skip generic cases if (criteria->win_rated_arena.flag != ACHIEVEMENT_CRITERIA_CONDITION_NO_LOOSE) + { continue; + } break; case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: // any cases break; case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: // need skip generic cases if (criteria->do_emote.count == 0) + { continue; + } break; case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:// any cases break; case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: // skip statistics if (criteria->win_duel.duelCount == 0) + { continue; + } break; case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: // any cases break; case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: // need skip generic cases if (criteria->loot_type.lootTypeCount != 1) + { continue; + } break; default: // type not use DB data, ignore continue; @@ -2815,7 +3113,9 @@ void AchievementGlobalMgr::LoadRewards() reward.text = fields[7].GetCppString(); if (reward.gender >= MAX_GENDER) + { sLog.outErrorDb("Table `achievement_reward` (Entry: %u) has wrong gender %u.", entry, reward.gender); + } // GENDER_NONE must be single (so or already in and none must be attempt added new data or just adding and none in) // other duplicate cases prevented by DB primary key @@ -2831,7 +3131,9 @@ void AchievementGlobalMgr::LoadRewards() } } if (dup) + { continue; + } if ((reward.titleId[0] == 0) != (reward.titleId[1] == 0)) sLog.outErrorDb("Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) only for one from teams.", entry, reward.titleId[0], reward.titleId[1]); @@ -2875,13 +3177,19 @@ void AchievementGlobalMgr::LoadRewards() else { if (reward.itemId) + { sLog.outErrorDb("Table `achievement_reward` (Entry: %u) not have sender data but have item reward, item will not rewarded", entry); + } if (!reward.subject.empty()) + { sLog.outErrorDb("Table `achievement_reward` (Entry: %u) not have sender data but have mail subject.", entry); + } if (!reward.text.empty()) + { sLog.outErrorDb("Table `achievement_reward` (Entry: %u) not have sender data but have mail text.", entry); + } } if (reward.itemId) @@ -2941,7 +3249,9 @@ void AchievementGlobalMgr::LoadRewardLocales() data.gender = Gender(fields[1].GetUInt8()); if (data.gender >= MAX_GENDER) + { sLog.outErrorDb("Table `locales_achievement_reward` (Entry: %u) has wrong gender %u.", entry, data.gender); + } // GENDER_NONE must be single (so or already in and none must be attempt added new data or just adding and none in) // other duplicate cases prevented by DB primary key @@ -2957,7 +3267,9 @@ void AchievementGlobalMgr::LoadRewardLocales() } } if (dup) + { continue; + } for (int i = 1; i < MAX_LOCALE; ++i) { @@ -2968,7 +3280,9 @@ void AchievementGlobalMgr::LoadRewardLocales() if (idx >= 0) { if (data.subject.size() <= size_t(idx)) + { data.subject.resize(idx + 1); + } data.subject[idx] = str; } @@ -2980,7 +3294,9 @@ void AchievementGlobalMgr::LoadRewardLocales() if (idx >= 0) { if (data.text.size() <= size_t(idx)) + { data.text.resize(idx + 1); + } data.text[idx] = str; } diff --git a/src/game/WorldHandlers/ArenaTeamHandler.cpp b/src/game/WorldHandlers/ArenaTeamHandler.cpp index 2cbd17f02..8dd0f3a2d 100644 --- a/src/game/WorldHandlers/ArenaTeamHandler.cpp +++ b/src/game/WorldHandlers/ArenaTeamHandler.cpp @@ -60,7 +60,9 @@ void WorldSession::HandleInspectArenaTeamsOpcode(WorldPacket& recv_data) if (uint32 a_id = player->GetArenaTeamId(i)) { if (ArenaTeam* arenaTeam = sObjectMgr.GetArenaTeamById(a_id)) + { arenaTeam->InspectStats(this, player->GetObjectGuid()); + } } } } @@ -87,7 +89,9 @@ void WorldSession::HandleArenaTeamRosterOpcode(WorldPacket& recv_data) recv_data >> ArenaTeamId; if (ArenaTeam* arenateam = sObjectMgr.GetArenaTeamById(ArenaTeamId)) + { arenateam->Roster(this); + } } void WorldSession::HandleArenaTeamCreateOpcode(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/AuctionHouseHandler.cpp b/src/game/WorldHandlers/AuctionHouseHandler.cpp index 536e13b29..b9a635982 100644 --- a/src/game/WorldHandlers/AuctionHouseHandler.cpp +++ b/src/game/WorldHandlers/AuctionHouseHandler.cpp @@ -82,7 +82,9 @@ void WorldSession::SendAuctionCommandResult(AuctionEntry* auc, AuctionAction Act { case AUCTION_OK: if (Action == AUCTION_BID_PLACED) + { data << uint64(auc->GetAuctionOutBid()); // new AuctionOutBid? + } break; case AUCTION_ERR_INVENTORY: data << uint32(invError); @@ -126,7 +128,9 @@ void WorldSession::SendAuctionOwnerNotification(AuctionEntry* auction) ObjectGuid bidder_guid = ObjectGuid(); if (!auction->moneyDeliveryTime) // not sold yet + { bidder_guid = ObjectGuid(HIGHGUID_PLAYER, auction->bidder); + } // bidder==0 and moneyDeliveryTime==0 for expired auctions, and client shows error messages as described above // if bidder!=0 client updates auctions with new bid, outbid and bidderGuid @@ -160,7 +164,9 @@ void WorldSession::SendAuctionOutbiddedMail(AuctionEntry* auction) uint32 oldBidder_accId = 0; if (!oldBidder) + { oldBidder_accId = sObjectMgr.GetPlayerAccountIdByGUID(oldBidder_guid); + } // old bidder exist if (oldBidder || oldBidder_accId) @@ -169,7 +175,9 @@ void WorldSession::SendAuctionOutbiddedMail(AuctionEntry* auction) msgAuctionOutbiddedSubject << auction->itemTemplate << ":" << auction->itemRandomPropertyId << ":" << AUCTION_OUTBIDDED << ":" << auction->Id << ":" << auction->itemCount; if (oldBidder) + { oldBidder->GetSession()->SendAuctionBidderNotification(auction); + } MailDraft(msgAuctionOutbiddedSubject.str(), "") // TODO: fix body .SetMoney(auction->bid) @@ -185,7 +193,9 @@ void WorldSession::SendAuctionCancelledToBidderMail(AuctionEntry* auction) uint32 bidder_accId = 0; if (!bidder) + { bidder_accId = sObjectMgr.GetPlayerAccountIdByGUID(bidder_guid); + } // bidder exist if (bidder || bidder_accId) @@ -194,7 +204,9 @@ void WorldSession::SendAuctionCancelledToBidderMail(AuctionEntry* auction) msgAuctionCancelledSubject << auction->itemTemplate << ":" << auction->itemRandomPropertyId << ":" << AUCTION_CANCELLED_TO_BIDDER << ":" << auction->Id << ":" << auction->itemCount; if (bidder) + { bidder->GetSession()->SendAuctionRemovedNotification(auction); + } MailDraft(msgAuctionCancelledSubject.str(), "") // TODO: fix body .SetMoney(auction->bid) @@ -300,7 +312,9 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recv_data) ObjectGuid itemGuid = guids[i]; if (!itemGuid) + { continue; + } uint32 stackSize = stackSizes[i]; @@ -348,13 +362,19 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recv_data) } if (stackSize == 0) + { stackSize = 1; + } if (stackSize > it->GetMaxStackCount()) // too big stack size + { stackSize = it->GetMaxStackCount(); + } if (!pl->HasItemCount(it->GetEntry(), stackSize)) // not enough items + { continue; + } Item* newItem = it->CloneItem(stackSize); @@ -455,9 +475,13 @@ void WorldSession::HandleAuctionPlaceBid(WorldPacket& recv_data) SendAuctionCommandResult(auction, AUCTION_BID_PLACED, AUCTION_OK); if (auction->UpdateBid(price, pl)) + { pl->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID, price); + } else + { pl->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID, auction->buyout); + } } // this void is called when auction_owner cancels his auction @@ -507,7 +531,9 @@ void WorldSession::HandleAuctionRemoveItem(WorldPacket& recv_data) } if (auction->bidder) // if auction have real existed bidder send mail + { SendAuctionCancelledToBidderMail(auction); + } pl->ModifyMoney(-int64(auctionCut)); } diff --git a/src/game/WorldHandlers/CalendarHandler.cpp b/src/game/WorldHandlers/CalendarHandler.cpp index dd307f133..864fe50a9 100644 --- a/src/game/WorldHandlers/CalendarHandler.cpp +++ b/src/game/WorldHandlers/CalendarHandler.cpp @@ -133,16 +133,22 @@ void WorldSession::HandleCalendarGetCalendar(WorldPacket& /*recv_data*/) // skip mapDiff without global reset time if (!mapDiff->resetTime) + { continue; + } // skip non raid map MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); if (!mapEntry || !mapEntry->IsRaid()) + { continue; + } // skip already sent map (not same difficulty?) if (sentMaps.find(mapId) != sentMaps.end()) + { continue; + } uint32 resetTime = sMapPersistentStateMgr.GetScheduler().GetMaxResetTimeFor(mapDiff); @@ -173,13 +179,19 @@ void WorldSession::HandleCalendarGetCalendar(WorldPacket& /*recv_data*/) data << uint32(holiday->CalendarFilterType); // m_calendarFilterType for (uint8 j = 0; j < MAX_HOLIDAY_DATES; ++j) + { data << uint32(holiday->Date[j]); // 26 * m_date -- WritePackedTime ? + } for (uint8 j = 0; j < MAX_HOLIDAY_DURATIONS; ++j) + { data << uint32(holiday->Duration[j]); // 10 * m_duration + } for (uint8 j = 0; j < MAX_HOLIDAY_FLAGS; ++j) + { data << uint32(holiday->CalendarFlags[j]); // 10 * m_calendarFlags + } data << holiday->TextureFilename; // m_textureFilename (holiday name) }*/ @@ -196,9 +208,13 @@ void WorldSession::HandleCalendarGetEvent(WorldPacket& recv_data) recv_data >> eventId; if (CalendarEvent* event = sCalendarMgr.GetEventById(eventId)) + { sCalendarMgr.SendCalendarEvent(_player, event, CALENDAR_SENDTYPE_GET); + } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarGuildFilter(WorldPacket& recv_data) @@ -212,7 +228,9 @@ void WorldSession::HandleCalendarGuildFilter(WorldPacket& recv_data) recv_data >> minLevel >> maxLevel >> minRank; if (Guild* guild = sGuildMgr.GetGuildById(_player->GetGuildId())) + { guild->MassInviteToEvent(this, minLevel, maxLevel, minRank); + } DEBUG_FILTER_LOG(LOG_FILTER_CALENDAR, "Min level [%u], Max level [%u], Min rank [%u]", minLevel, maxLevel, minRank); } @@ -242,7 +260,9 @@ void WorldSession::HandleCalendarEventSignup(WorldPacket& recv_data) sCalendarMgr.SendCalendarClearPendingAction(_player); } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarArenaTeam(WorldPacket& recv_data) @@ -252,7 +272,9 @@ void WorldSession::HandleCalendarArenaTeam(WorldPacket& recv_data) recv_data >> areanTeamId; if (ArenaTeam* team = sObjectMgr.GetArenaTeamById(areanTeamId)) + { team->MassInviteToEvent(this); + } } void WorldSession::HandleCalendarAddEvent(WorldPacket& recv_data) @@ -377,7 +399,9 @@ void WorldSession::HandleCalendarUpdateEvent(WorldPacket& recv_data) type, flags, dungeonId, event->EventTime, title.c_str(), description.c_str(), eventId); } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarRemoveEvent(WorldPacket& recv_data) @@ -439,7 +463,9 @@ void WorldSession::HandleCalendarEventInvite(WorldPacket& recv_data) inviteeTeam = player->GetTeam(); inviteeGuildId = player->GetGuildId(); if (player->GetSocial()->HasIgnore(playerGuid)) + { isIgnored = true; + } } else { @@ -459,7 +485,9 @@ void WorldSession::HandleCalendarEventInvite(WorldPacket& recv_data) { Field* fields = result->Fetch(); if (fields[0].GetUInt8() & SOCIAL_FLAG_IGNORED) + { isIgnored = true; + } delete result; } } @@ -497,7 +525,9 @@ void WorldSession::HandleCalendarEventInvite(WorldPacket& recv_data) sCalendarMgr.AddInvite(event, playerGuid, inviteeGuid, CALENDAR_STATUS_INVITED, CALENDAR_RANK_PLAYER, "", time(NULL)); } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } else { @@ -568,10 +598,14 @@ void WorldSession::HandleCalendarEventRsvp(WorldPacket& recv_data) sCalendarMgr.SendCalendarClearPendingAction(_player); } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_NO_INVITE); // correct? + } } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarEventRemoveInvite(WorldPacket& recv_data) @@ -591,9 +625,13 @@ void WorldSession::HandleCalendarEventRemoveInvite(WorldPacket& recv_data) eventId, ownerInviteId, invitee.GetString().c_str(), inviteId); if (CalendarEvent* event = sCalendarMgr.GetEventById(eventId)) + { sCalendarMgr.RemoveInvite(eventId, inviteId, guid); + } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarEventStatus(WorldPacket& recv_data) @@ -641,10 +679,14 @@ void WorldSession::HandleCalendarEventStatus(WorldPacket& recv_data) sCalendarMgr.SendCalendarClearPendingAction(sObjectMgr.GetPlayer(invitee)); } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_NO_INVITE); + } } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarEventModeratorStatus(WorldPacket& recv_data) @@ -695,10 +737,14 @@ void WorldSession::HandleCalendarEventModeratorStatus(WorldPacket& recv_data) sCalendarMgr.SendCalendarEventModeratorStatusAlert(invite); } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_NO_INVITE); + } } else + { sCalendarMgr.SendCalendarCommandResult(_player, CALENDAR_ERROR_EVENT_INVALID); + } } void WorldSession::HandleCalendarComplain(WorldPacket& recv_data) @@ -773,10 +819,14 @@ void CalendarMgr::SendCalendarEventInviteAlert(CalendarInvite const* invite) if (event->IsGuildEvent() || event->IsGuildAnnouncement()) { if (Guild* guild = sGuildMgr.GetGuildById(event->GuildId)) + { guild->BroadcastPacket(&data); + } } else if (Player* player = sObjectMgr.GetPlayer(invite->InviteeGuid)) + { player->SendDirectMessage(&data); + } } void CalendarMgr::SendCalendarEventInvite(CalendarInvite const* invite) @@ -804,7 +854,9 @@ void CalendarMgr::SendCalendarEventInvite(CalendarInvite const* invite) data << uint8(invite->Status); data << uint8(!preInvite); if (!preInvite) + { data << secsToTimeBitFields(statusTime); + } data << uint8(invite->SenderGuid != invite->InviteeGuid); // false only if the invite is sign-up (invitee create himself his invite) DEBUG_FILTER_LOG(LOG_FILTER_CALENDAR, "SendCalendarInvit> %s senderGuid[%s], inviteeGuid[%s], EventId[" UI64FMTD "], Status[%u], InviteId[" UI64FMTD "]", @@ -814,10 +866,14 @@ void CalendarMgr::SendCalendarEventInvite(CalendarInvite const* invite) if (preInvite) { if (Player* sender = sObjectMgr.GetPlayer(invite->SenderGuid)) + { sender->SendDirectMessage(&data); + } } else + { SendPacketToAllEventRelatives(data, event); + } } void CalendarMgr::SendCalendarCommandResult(Player* player, CalendarError err, char const* param /*= NULL*/) @@ -1010,14 +1066,18 @@ void CalendarMgr::SendPacketToAllEventRelatives(WorldPacket packet, CalendarEven // Send packet to all guild members if (event->IsGuildEvent() || event->IsGuildAnnouncement()) if (Guild* guild = sGuildMgr.GetGuildById(event->GuildId)) + { guild->BroadcastPacket(&packet); + } // Send packet to all invitees if event is non-guild, in other case only to non-guild invitees (packet was broadcasted for them) CalendarInviteMap const* cInvMap = event->GetInviteMap(); for (CalendarInviteMap::const_iterator itr = cInvMap->begin(); itr != cInvMap->end(); ++itr) if (Player* player = sObjectMgr.GetPlayer(itr->second->InviteeGuid)) if (!event->IsGuildEvent() || (event->IsGuildEvent() && player->GetGuildId() != event->GuildId)) + { player->SendDirectMessage(&packet); + } } void CalendarMgr::SendCalendarRaidLockoutRemove(Player* player, DungeonPersistentState const* save) diff --git a/src/game/WorldHandlers/CellImpl.h b/src/game/WorldHandlers/CellImpl.h index 126218d57..4bf334eb6 100644 --- a/src/game/WorldHandlers/CellImpl.h +++ b/src/game/WorldHandlers/CellImpl.h @@ -82,7 +82,9 @@ Cell::Visit(const CellPair& standing_cell, TypeContainerVisitor &v } // lets limit the upper value for search radius if (radius > 333.0f) + { radius = 333.0f; + } // lets calculate object coord offsets from cell borders. CellArea area = Cell::CalculateCellArea(x, y, radius); @@ -187,7 +189,9 @@ inline void Cell::VisitGridObjects(const WorldObject* center_obj, T& visitor, fl CellPair p(MaNGOS::ComputeCellPair(center_obj->GetPositionX(), center_obj->GetPositionY())); Cell cell(p); if (dont_load) + { cell.SetNoCreate(); + } TypeContainerVisitor gnotifier(visitor); cell.Visit(p, gnotifier, *center_obj->GetMap(), *center_obj, radius); } @@ -198,7 +202,9 @@ inline void Cell::VisitWorldObjects(const WorldObject* center_obj, T& visitor, f CellPair p(MaNGOS::ComputeCellPair(center_obj->GetPositionX(), center_obj->GetPositionY())); Cell cell(p); if (dont_load) + { cell.SetNoCreate(); + } TypeContainerVisitor gnotifier(visitor); cell.Visit(p, gnotifier, *center_obj->GetMap(), *center_obj, radius); } @@ -209,7 +215,9 @@ inline void Cell::VisitAllObjects(const WorldObject* center_obj, T& visitor, flo CellPair p(MaNGOS::ComputeCellPair(center_obj->GetPositionX(), center_obj->GetPositionY())); Cell cell(p); if (dont_load) + { cell.SetNoCreate(); + } TypeContainerVisitor gnotifier(visitor); TypeContainerVisitor wnotifier(visitor); cell.Visit(p, gnotifier, *center_obj->GetMap(), *center_obj, radius); @@ -222,7 +230,9 @@ inline void Cell::VisitGridObjects(float x, float y, Map* map, T& visitor, float CellPair p(MaNGOS::ComputeCellPair(x, y)); Cell cell(p); if (dont_load) + { cell.SetNoCreate(); + } TypeContainerVisitor gnotifier(visitor); cell.Visit(p, gnotifier, *map, x, y, radius); } @@ -233,7 +243,9 @@ inline void Cell::VisitWorldObjects(float x, float y, Map* map, T& visitor, floa CellPair p(MaNGOS::ComputeCellPair(x, y)); Cell cell(p); if (dont_load) + { cell.SetNoCreate(); + } TypeContainerVisitor gnotifier(visitor); cell.Visit(p , gnotifier, *map, x, y, radius); } @@ -244,7 +256,9 @@ inline void Cell::VisitAllObjects(float x, float y, Map* map, T& visitor, float CellPair p(MaNGOS::ComputeCellPair(x, y)); Cell cell(p); if (dont_load) + { cell.SetNoCreate(); + } TypeContainerVisitor gnotifier(visitor); TypeContainerVisitor wnotifier(visitor); cell.Visit(p, gnotifier, *map, x, y, radius); diff --git a/src/game/WorldHandlers/Channel.cpp b/src/game/WorldHandlers/Channel.cpp index 402a23c36..97caa8266 100644 --- a/src/game/WorldHandlers/Channel.cpp +++ b/src/game/WorldHandlers/Channel.cpp @@ -41,15 +41,23 @@ Channel::Channel(const std::string& name, uint32 channel_id) m_flags |= CHANNEL_FLAG_GENERAL; // for all built-in channels if (ch->flags & CHANNEL_DBC_FLAG_TRADE) // for trade channel + { m_flags |= CHANNEL_FLAG_TRADE; + } if (ch->flags & CHANNEL_DBC_FLAG_CITY_ONLY2) // for city only channels + { m_flags |= CHANNEL_FLAG_CITY; + } if (ch->flags & CHANNEL_DBC_FLAG_LFG) // for LFG channel + { m_flags |= CHANNEL_FLAG_LFG; + } else // for all other channels + { m_flags |= CHANNEL_FLAG_NOT_LFG; + } } else // it's custom channel { @@ -227,7 +235,9 @@ void Channel::KickOrBan(Player* player, const char* targetName, bool ban) MakePlayerBanned(&data, targetGuid, guid); } else + { MakePlayerKicked(&data, targetGuid, guid); + } SendToAll(&data); m_players.erase(targetGuid); @@ -378,9 +388,13 @@ void Channel::SetMode(Player* player, const char* targetName, bool moderator, bo // set channel moderator if (moderator) + { SetModerator(targetGuid, set); + } else + { SetMute(targetGuid, set); + } } void Channel::SetOwner(ObjectGuid guid, bool exclaim) @@ -390,7 +404,9 @@ void Channel::SetOwner(ObjectGuid guid, bool exclaim) // [] will re-add player after it possible removed PlayerList::iterator p_itr = m_players.find(m_ownerGuid); if (p_itr != m_players.end()) + { p_itr->second.SetOwner(false); + } } m_ownerGuid = guid; @@ -550,9 +566,13 @@ void Channel::Announce(Player* player) WorldPacket data; if (m_announce) + { MakeAnnouncementsOn(&data, guid); + } else + { MakeAnnouncementsOff(&data, guid); + } SendToAll(&data); } @@ -582,9 +602,13 @@ void Channel::Moderate(Player* player) WorldPacket data; if (m_moderate) + { MakeModerationOn(&data, guid); + } else + { MakeModerationOff(&data, guid); + } SendToAll(&data); } @@ -624,7 +648,9 @@ void Channel::Say(Player* player, const char* text, uint32 lang) // send channel message if (sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHANNEL)) + { lang = LANG_UNIVERSAL; + } WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_CHANNEL, text, Language(lang), player->GetChatTag(), guid, player->GetName(), ObjectGuid(), "", m_name.c_str()); SendToAll(&data, !m_players[guid].IsModerator() ? guid : ObjectGuid()); @@ -694,13 +720,17 @@ void Channel::SendToAll(WorldPacket* data, ObjectGuid guid) for (PlayerList::const_iterator i = m_players.begin(); i != m_players.end(); ++i) if (Player* plr = sObjectMgr.GetPlayer(i->first)) if (!guid || !plr->GetSocial()->HasIgnore(guid)) + { plr->GetSession()->SendPacket(data); + } } void Channel::SendToOne(WorldPacket* data, ObjectGuid who) { if (Player* plr = ObjectMgr::GetPlayer(who)) + { plr->GetSession()->SendPacket(data); + } } void Channel::Voice(ObjectGuid /*guid1*/, ObjectGuid /*guid2*/) @@ -788,7 +818,9 @@ void Channel::MakeChannelOwner(WorldPacket* data) std::string name = ""; if (!sObjectMgr.GetPlayerNameByGUID(m_ownerGuid, name) || name.empty()) + { name = "PLAYER_NOT_FOUND"; + } MakeNotifyPacket(data, CHAT_CHANNEL_OWNER_NOTICE); *data << ((IsConstant() || !m_ownerGuid) ? "Nobody" : name); @@ -939,9 +971,13 @@ void Channel::JoinNotify(ObjectGuid guid) WorldPacket data; if (IsConstant()) + { data.Initialize(SMSG_USERLIST_ADD, 8 + 1 + 1 + 4 + GetName().size() + 1); + } else + { data.Initialize(SMSG_USERLIST_UPDATE, 8 + 1 + 1 + 4 + GetName().size() + 1); + } data << ObjectGuid(guid); data << uint8(GetPlayerFlags(guid)); diff --git a/src/game/WorldHandlers/Channel.h b/src/game/WorldHandlers/Channel.h index 16207446d..fa6afd4a9 100644 --- a/src/game/WorldHandlers/Channel.h +++ b/src/game/WorldHandlers/Channel.h @@ -132,20 +132,38 @@ class Channel bool IsOwner() { return flags & MEMBER_FLAG_OWNER; } void SetOwner(bool state) { - if (state) flags |= MEMBER_FLAG_OWNER; - else flags &= ~MEMBER_FLAG_OWNER; + if (state) + { + flags |= MEMBER_FLAG_OWNER; + } + else + { + flags &= ~MEMBER_FLAG_OWNER; + } } bool IsModerator() { return flags & MEMBER_FLAG_MODERATOR; } void SetModerator(bool state) { - if (state) flags |= MEMBER_FLAG_MODERATOR; - else flags &= ~MEMBER_FLAG_MODERATOR; + if (state) + { + flags |= MEMBER_FLAG_MODERATOR; + } + else + { + flags &= ~MEMBER_FLAG_MODERATOR; + } } bool IsMuted() { return flags & MEMBER_FLAG_MUTED; } void SetMuted(bool state) { - if (state) flags |= MEMBER_FLAG_MUTED; - else flags &= ~MEMBER_FLAG_MUTED; + if (state) + { + flags |= MEMBER_FLAG_MUTED; + } + else + { + flags &= ~MEMBER_FLAG_MUTED; + } } }; diff --git a/src/game/WorldHandlers/ChannelHandler.cpp b/src/game/WorldHandlers/ChannelHandler.cpp index b55e00ba0..30b82b753 100644 --- a/src/game/WorldHandlers/ChannelHandler.cpp +++ b/src/game/WorldHandlers/ChannelHandler.cpp @@ -48,7 +48,9 @@ void WorldSession::HandleJoinChannelOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetJoinChannel(channelname, channel_id)) + { chn->Join(_player, pass.c_str()); + } } void WorldSession::HandleLeaveChannelOpcode(WorldPacket& recvPacket) @@ -69,7 +71,9 @@ void WorldSession::HandleLeaveChannelOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) { if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Leave(_player, true); + } cMgr->LeftChannel(channelname); } } @@ -82,7 +86,9 @@ void WorldSession::HandleChannelListOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->List(_player); + } } void WorldSession::HandleChannelPasswordOpcode(WorldPacket& recvPacket) @@ -99,7 +105,9 @@ void WorldSession::HandleChannelPasswordOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Password(_player, pass.c_str()); + } } void WorldSession::HandleChannelSetOwnerOpcode(WorldPacket& recvPacket) @@ -122,7 +130,9 @@ void WorldSession::HandleChannelSetOwnerOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->SetOwner(_player->GetObjectGuid(), newp.c_str()); + } } void WorldSession::HandleChannelOwnerOpcode(WorldPacket& recvPacket) @@ -133,7 +143,9 @@ void WorldSession::HandleChannelOwnerOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->SendWhoOwner(_player); + } } void WorldSession::HandleChannelModeratorOpcode(WorldPacket& recvPacket) @@ -155,7 +167,9 @@ void WorldSession::HandleChannelModeratorOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->SetModerator(_player, otp.c_str()); + } } void WorldSession::HandleChannelUnmoderatorOpcode(WorldPacket& recvPacket) @@ -177,7 +191,9 @@ void WorldSession::HandleChannelUnmoderatorOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->UnsetMute(_player, otp.c_str()); + } } void WorldSession::HandleChannelMuteOpcode(WorldPacket& recvPacket) @@ -199,7 +215,9 @@ void WorldSession::HandleChannelMuteOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Invite(_player, otp.c_str()); + } } void WorldSession::HandleChannelUnmuteOpcode(WorldPacket& recvPacket) @@ -221,7 +239,9 @@ void WorldSession::HandleChannelUnmuteOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->UnsetMute(_player, otp.c_str()); + } } void WorldSession::HandleChannelInviteOpcode(WorldPacket& recvPacket) @@ -243,7 +263,9 @@ void WorldSession::HandleChannelInviteOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Invite(_player, otp.c_str()); + } } void WorldSession::HandleChannelKickOpcode(WorldPacket& recvPacket) @@ -265,7 +287,9 @@ void WorldSession::HandleChannelKickOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Kick(_player, otp.c_str()); + } } void WorldSession::HandleChannelBanOpcode(WorldPacket& recvPacket) @@ -287,7 +311,9 @@ void WorldSession::HandleChannelBanOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Ban(_player, otp.c_str()); + } } void WorldSession::HandleChannelUnbanOpcode(WorldPacket& recvPacket) @@ -309,7 +335,9 @@ void WorldSession::HandleChannelUnbanOpcode(WorldPacket& recvPacket) if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->UnBan(_player, otp.c_str()); + } } void WorldSession::HandleChannelAnnouncementsOpcode(WorldPacket& recvPacket) @@ -319,7 +347,9 @@ void WorldSession::HandleChannelAnnouncementsOpcode(WorldPacket& recvPacket) std::string channelname = recvPacket.ReadString(recvPacket.ReadBits(8)); if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Announce(_player); + } } void WorldSession::HandleChannelModerateOpcode(WorldPacket& recvPacket) @@ -330,7 +360,9 @@ void WorldSession::HandleChannelModerateOpcode(WorldPacket& recvPacket) recvPacket >> channelname; if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->Moderate(_player); + } } void WorldSession::HandleChannelDisplayListQueryOpcode(WorldPacket& recvPacket) @@ -340,7 +372,9 @@ void WorldSession::HandleChannelDisplayListQueryOpcode(WorldPacket& recvPacket) std::string channelname = recvPacket.ReadString(recvPacket.ReadBits(8)); if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if (Channel* chn = cMgr->GetChannel(channelname, _player)) + { chn->List(_player); + } } void WorldSession::HandleGetChannelMemberCountOpcode(WorldPacket& recvPacket) @@ -370,5 +404,7 @@ void WorldSession::HandleSetChannelWatchOpcode(WorldPacket& recvPacket) recvPacket >> channelname; /*if(ChannelMgr* cMgr = channelMgr(_player->GetTeam())) if(Channel *chn = cMgr->GetChannel(channelname, _player)) - chn->JoinNotify(_player->GetGUID());*/ + { + chn->JoinNotify(_player->GetGUID()); + }*/ } diff --git a/src/game/WorldHandlers/ChannelMgr.cpp b/src/game/WorldHandlers/ChannelMgr.cpp index 29bb75526..b409637c0 100644 --- a/src/game/WorldHandlers/ChannelMgr.cpp +++ b/src/game/WorldHandlers/ChannelMgr.cpp @@ -32,7 +32,9 @@ INSTANTIATE_SINGLETON_1(HordeChannelMgr); ChannelMgr* channelMgr(Team team) { if (sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHANNEL)) + { return &MaNGOS::Singleton::Instance(); // cross-faction + } if (team == ALLIANCE) { diff --git a/src/game/WorldHandlers/CharacterHandler.cpp b/src/game/WorldHandlers/CharacterHandler.cpp index 21d500027..2b05f4ce3 100644 --- a/src/game/WorldHandlers/CharacterHandler.cpp +++ b/src/game/WorldHandlers/CharacterHandler.cpp @@ -139,7 +139,10 @@ class CharacterHandler } void HandlePlayerLoginCallback(QueryResult * /*dummy*/, SqlQueryHolder* holder) { - if (!holder) return; + if (!holder) + { + return; + } WorldSession* session = sWorld.FindSession(((LoginQueryHolder*)holder)->GetAccountId()); if (!session) { @@ -228,7 +231,9 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) std::string name = recvData.ReadString(nameLength); if (unk) + { recvData.read_skip(); + } WorldPacket data(SMSG_CHAR_CREATE, 1); // returned with diff.values in all cases @@ -392,7 +397,9 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) if (acc_class == CLASS_DEATH_KNIGHT) { if (heroic_free_slots > 0) + { --heroic_free_slots; + } if (heroic_free_slots == 0) { @@ -407,7 +414,9 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) { uint32 acc_level = field[0].GetUInt32(); if (acc_level >= req_level_for_heroic) + { have_req_level_for_heroic = true; + } } } @@ -429,13 +438,17 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) while ((skipCinematics == CINEMATICS_SKIP_SAME_RACE && !have_same_race) || class_ == CLASS_DEATH_KNIGHT) { if (!result2->NextRow()) + { break; + } field = result2->Fetch(); acc_race = field[1].GetUInt32(); if (!have_same_race) + { have_same_race = race_ == acc_race; + } if (GetSecurity() == SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT) { @@ -443,7 +456,9 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) if (acc_class == CLASS_DEATH_KNIGHT) { if (heroic_free_slots > 0) + { --heroic_free_slots; + } if (heroic_free_slots == 0) { @@ -458,7 +473,9 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) { uint32 acc_level = field[0].GetUInt32(); if (acc_level >= req_level_for_heroic) + { have_req_level_for_heroic = true; + } } } } @@ -486,7 +503,9 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) } if ((have_same_race && skipCinematics == CINEMATICS_SKIP_SAME_RACE) || skipCinematics == CINEMATICS_SKIP_ALL) + { pNewChar->setCinematic(1); // not show intro + } pNewChar->SetAtLoginFlag(AT_LOGIN_FIRST); // First login @@ -846,33 +865,47 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) if (ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(pCurrChar->getClass())) { if (cEntry->CinematicSequence) + { pCurrChar->SendCinematicStart(cEntry->CinematicSequence); + } else if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(pCurrChar->getRace())) + { pCurrChar->SendCinematicStart(rEntry->CinematicSequence); + } } } uint32 miscRequirement = 0; AreaLockStatus lockStatus = AREA_LOCKSTATUS_OK; if (AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(pCurrChar->GetMapId())) + { lockStatus = pCurrChar->GetAreaTriggerLockStatus(at, pCurrChar->GetDifficulty(pCurrChar->GetMap()->IsRaid()), miscRequirement); + } else { // Some basic checks in case of a map without areatrigger MapEntry const* mapEntry = sMapStore.LookupEntry(pCurrChar->GetMapId()); if (!mapEntry) + { lockStatus = AREA_LOCKSTATUS_UNKNOWN_ERROR; + } else if (pCurrChar->GetSession()->Expansion() < mapEntry->Expansion()) + { lockStatus = AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION; + } } if (lockStatus != AREA_LOCKSTATUS_OK || !pCurrChar->GetMap()->Add(pCurrChar)) { // normal delayed teleport protection not applied (and this correct) for this case (Player object just created) AreaTrigger const* at = sObjectMgr.GetGoBackTrigger(pCurrChar->GetMapId()); if (at) + { lockStatus = pCurrChar->GetAreaTriggerLockStatus(at, pCurrChar->GetDifficulty(pCurrChar->GetMap()->IsRaid()), miscRequirement); + } if (!at || lockStatus != AREA_LOCKSTATUS_OK || !pCurrChar->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, pCurrChar->GetOrientation())) + { pCurrChar->TeleportToHomebind(); + } } sObjectAccessor.AddObject(pCurrChar); @@ -893,7 +926,9 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) // announce group about member online (must be after add to player list to receive announce to self) if (Group* group = pCurrChar->GetGroup()) + { group->SendUpdate(); + } // friend status sSocialMgr.SendFriendStatus(pCurrChar, FRIEND_ONLINE, pCurrChar->GetObjectGuid(), true); @@ -906,7 +941,9 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) { // not blizz like, we must correctly save and load player instead... if (pCurrChar->getRace() == RACE_NIGHTELF) + { pCurrChar->CastSpell(pCurrChar, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form) + } pCurrChar->CastSpell(pCurrChar, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?) pCurrChar->SetWaterWalk(true); @@ -916,17 +953,23 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) // reset for all pets before pet loading if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS)) + { Pet::resetTalentsForAllPetsOf(pCurrChar); + } // Load pet if any (if player not alive and in taxi flight or another then pet will remember as temporary unsummoned) pCurrChar->LoadPet(); // Set FFA PvP for non GM in non-rest mode if (sWorld.IsFFAPvPRealm() && !pCurrChar->isGameMaster() && !pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) + { pCurrChar->SetFFAPvP(true); + } if (pCurrChar->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) + { pCurrChar->SetContestedPvP(); + } // Apply at_login requests if (pCurrChar->HasAtLoginFlag(AT_LOGIN_RESET_SPELLS)) @@ -945,7 +988,9 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) // Used by Eluna #ifdef ENABLE_ELUNA if (pCurrChar->HasAtLoginFlag(AT_LOGIN_FIRST)) + { sEluna->OnFirstLogin(pCurrChar); + } #endif /* ENABLE_ELUNA */ @@ -957,20 +1002,28 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) /* If the server is shutting down, show shutdown time remaining */ if (sWorld.IsShutdowning()) + { sWorld.ShutdownMsg(true, pCurrChar); + } if (sWorld.getConfig(CONFIG_BOOL_ALL_TAXI_PATHS)) + { pCurrChar->SetTaxiCheater(true); + } if (pCurrChar->isGameMaster()) + { SendNotification(LANG_GM_ON); + } if (!pCurrChar->isGMVisible()) { SendNotification(LANG_INVISIBLE_INVISIBLE); SpellEntry const* invisibleAuraInfo = sSpellStore.LookupEntry(sWorld.getConfig(CONFIG_UINT32_GM_INVISIBLE_AURA)); if (invisibleAuraInfo && IsSpellAppliesAura(invisibleAuraInfo)) + { pCurrChar->CastSpell(pCurrChar, invisibleAuraInfo, true); + } } std::string IP_str = GetRemoteAddress(); @@ -978,7 +1031,9 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) GetAccountId(), IP_str.c_str(), pCurrChar->GetName(), pCurrChar->GetGUIDLow()); if (!pCurrChar->IsStandState() && !pCurrChar->hasUnitState(UNIT_STAT_STUNNED)) + { pCurrChar->SetStandState(UNIT_STAND_STATE_STAND); + } m_playerLoading = false; @@ -1143,7 +1198,9 @@ void WorldSession::HandleChangePlayerNameOpcodeCallBack(QueryResult* result, uin if (!session) { if (result) delete result; - return; + { + return; + } } if (!result) @@ -1316,7 +1373,9 @@ void WorldSession::HandleAlterAppearanceOpcode(WorldPacket& recv_data) _player->SetByteValue(PLAYER_BYTES, 3, uint8(Color)); _player->SetByteValue(PLAYER_BYTES_2, 0, uint8(bs_facialHair->hair_id)); if (_player->getRace() == RACE_TAUREN) + { _player->SetByteValue(PLAYER_BYTES, 0, uint8(skinTone_id)); + } _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP, 1); @@ -1467,7 +1526,9 @@ void WorldSession::HandleCharCustomizeOpcode(WorldPacket& recv_data) data << newname; if (!RESPONSE_SUCCESS) + { data << newname; + } SendPacket(&data); } @@ -1558,7 +1619,9 @@ void WorldSession::HandleEquipmentSetUseOpcode(WorldPacket& recv_data) // check if item slot is set to "ignored" (raw value == 1), must not be unequipped then if (itemGuid.GetRawValue() == 1) + { continue; + } Item* item = _player->GetItemByGuid(itemGuid); @@ -1568,7 +1631,9 @@ void WorldSession::HandleEquipmentSetUseOpcode(WorldPacket& recv_data) { Item* uItem = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (!uItem) + { continue; + } ItemPosCountVec sDest; InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sDest, uItem, false); @@ -1578,13 +1643,17 @@ void WorldSession::HandleEquipmentSetUseOpcode(WorldPacket& recv_data) _player->StoreItem(sDest, uItem, true); } else + { _player->SendEquipError(msg, uItem, NULL); + } continue; } if (item->GetPos() == dstpos) + { continue; + } _player->SwapItem(item->GetPos(), dstpos); } diff --git a/src/game/WorldHandlers/Chat.cpp b/src/game/WorldHandlers/Chat.cpp index bc7b36487..c4e57622b 100644 --- a/src/game/WorldHandlers/Chat.cpp +++ b/src/game/WorldHandlers/Chat.cpp @@ -917,9 +917,13 @@ bool ChatHandler::HasLowerSecurity(Player* target, ObjectGuid guid, bool strong) uint32 target_account = 0; if (target) + { target_session = target->GetSession(); + } else + { target_account = sObjectMgr.GetPlayerAccountIdByGUID(guid); + } if (!target_session && !target_account) { @@ -942,9 +946,13 @@ bool ChatHandler::HasLowerSecurityAccount(WorldSession* target, uint32 target_ac } if (target) + { target_sec = target->GetSecurity(); + } else if (target_account) + { target_sec = sAccountMgr.GetSecurity(target_account); + } else return true; // caller must report error for (target==NULL && target_account==0) @@ -1064,7 +1072,9 @@ void ChatHandler::CheckIntegrity(ChatCommand* table, ChatCommand* parentCommand) command->Name, parentCommand->Name, command->SecurityLevel, parentCommand->SecurityLevel); if (!parentCommand && strlen(command->Name) == 0) + { sLog.outError("Subcommand '' at top level"); + } if (command->ChildCommands) { @@ -1079,7 +1089,9 @@ void ChatHandler::CheckIntegrity(ChatCommand* table, ChatCommand* parentCommand) } if (parentCommand && strlen(command->Name) == 0) + { sLog.outError("Subcommand '' of command '%s' have subcommands", parentCommand->Name); + } CheckIntegrity(command->ChildCommands, command); } @@ -1160,12 +1172,16 @@ ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* { size_t len = strlen(table[i].Name); if (strncmp(table[i].Name, cmd.c_str(), len + 1) != 0) + { continue; + } } else { if (!hasStringAbbr(table[i].Name, cmd.c_str())) + { continue; + } } // select subcommand from child commands list if (table[i].ChildCommands != NULL) @@ -1180,11 +1196,15 @@ ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* { // if subcommand success search not return parent command, then this parent command is owner of child commands if (parentCommand) + { *parentCommand = parentSubcommand ? parentSubcommand : &table[i]; + } // Name == "" is special case: restore original command text for next level "" (where parentSubcommand==NULL) if (strlen(command->Name) == 0 && !parentSubcommand) + { text = oldchildtext; + } return CHAT_COMMAND_OK; } @@ -1193,7 +1213,9 @@ ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* // command not found directly in child command list, return child command list owner command = &table[i]; if (parentCommand) + { *parentCommand = NULL; // we don't known parent of table list at this point + } text = oldchildtext; // restore text to stated just after parse found parent command return CHAT_COMMAND_UNKNOWN_SUBCOMMAND; // we not found subcommand for table[i] @@ -1203,7 +1225,9 @@ ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* { // some deep subcommand not found, if this second level subcommand then parentCommand can be NULL, use known value for it if (parentCommand) + { *parentCommand = parentSubcommand ? parentSubcommand : &table[i]; + } return res; } } @@ -1211,21 +1235,29 @@ ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* // must be available (not checked for subcommands case because parent command expected have most low access that all subcommands always if (!allAvailable && !isAvailable(table[i])) + { continue; + } // must be have handler is explicitly selected if (!table[i].Handler) + { continue; + } // command found directly in to table command = &table[i]; // unknown table owner at this point if (parentCommand) + { *parentCommand = NULL; + } if (cmdNamePtr) + { *cmdNamePtr = cmd; + } return CHAT_COMMAND_OK; } @@ -1235,10 +1267,14 @@ ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* // unknown table owner at this point if (parentCommand) + { *parentCommand = NULL; + } if (cmdNamePtr) + { *cmdNamePtr = cmd; + } return CHAT_COMMAND_UNKNOWN; } @@ -1267,7 +1303,9 @@ void ChatHandler::ExecuteCommand(const char* text) if ((this->*(command->Handler))((char*)text)) // text content destroyed at call { if (command->SecurityLevel > SEC_PLAYER) + { LogCommand(fullcmd.c_str()); + } } // some commands have custom error messages. Don't send the default one in these cases. else if (!HasSentErrorMessage()) @@ -1368,9 +1406,13 @@ bool ChatHandler::SetDataForCommandInTable(ChatCommand* commandTable, uint32 id, { // command have subcommands, but not '' subcommand and then any data in `command` useless for it. if (cmdName.empty()) + { sLog.outErrorDb("Table `command` have command '%s' that only used with some subcommand selection, it can't have help or overwritten access level, skip.", cmdName.c_str()); + } else + { sLog.outErrorDb("Table `command` have unexpected subcommand '%s' in command '%s', skip.", cmdName.c_str(), fullcommand.c_str()); + } return false; } case CHAT_COMMAND_UNKNOWN: @@ -1416,7 +1458,9 @@ bool ChatHandler::ParseCommands(const char* text) /// skip first . or ! (in console allowed use command with . and ! and without its) if (text[0] == '!' || text[0] == '.') + { ++text; + } ExecuteCommand(text); @@ -1430,17 +1474,25 @@ bool ChatHandler::ShowHelpForSubCommands(ChatCommand* table, char const* cmd) { // must be available (ignore handler existence for show command with possible available subcommands if (!isAvailable(table[i])) + { continue; + } if (m_session) + { list += "\n "; + } else + { list += "\n\r "; + } list += table[i].Name; if (table[i].ChildCommands) + { list += " ..."; + } } if (list.empty()) @@ -1483,7 +1535,9 @@ bool ChatHandler::ShowHelpForCommand(ChatCommand* table, const char* cmd) cmd = ""; } else + { showCommand = command; + } childCommands = showCommand->ChildCommands; break; @@ -1521,7 +1575,9 @@ bool ChatHandler::ShowHelpForCommand(ChatCommand* table, const char* cmd) } if (command && command->Help.empty()) + { SendSysMessage(LANG_NO_HELP_CMD); + } return command || childCommands; } @@ -1582,9 +1638,13 @@ bool ChatHandler::isValidChatMessage(const char* message) if (commandChar == *validSequenceIterator) { if (validSequenceIterator == validSequence + 4) + { validSequenceIterator = validSequence; + } else + { ++validSequenceIterator; + } } else if (commandChar != '|') { @@ -1637,7 +1697,9 @@ bool ChatHandler::isValidChatMessage(const char* message) // no further pipe commands if (reader.eof()) + { break; + } char commandChar; reader >> commandChar; @@ -1648,9 +1710,13 @@ bool ChatHandler::isValidChatMessage(const char* message) if (commandChar == *validSequenceIterator) { if (validSequenceIterator == validSequence + 4) + { validSequenceIterator = validSequence; + } else + { ++validSequenceIterator; + } } else { @@ -1770,7 +1836,9 @@ bool ChatHandler::isValidChatMessage(const char* message) propertyId += c - '0'; } else if (c == '-') + { negativeNumber = true; + } else { return false; @@ -1778,7 +1846,9 @@ bool ChatHandler::isValidChatMessage(const char* message) } } if (negativeNumber) + { propertyId *= -1; + } if (propertyId > 0) { @@ -2176,7 +2246,9 @@ bool ChatHandler::isValidChatMessage(const char* message) // using strange database/client combinations can lead to this case expectedName = linkedItem->Name1; else + { expectedName = il->Name[dbIndex]; + } if (suffix) { expectedName += " "; @@ -2319,9 +2391,13 @@ bool ChatHandler::ExtractInt32(char** args, int32& val) long valRaw = strtol(*args, &tail, 10); if (tail != *args && isWhiteSpace(*tail)) + { *(tail++) = '\0'; + } else if (tail && *tail) // some not whitespace symbol + { return false; // args not modified and can be re-parsed + } if (valRaw < std::numeric_limits::min() || valRaw > std::numeric_limits::max()) { @@ -2373,9 +2449,13 @@ bool ChatHandler::ExtractUInt32Base(char** args, uint32& val, uint32 base) unsigned long valRaw = strtoul(*args, &tail, base); if (tail != *args && isWhiteSpace(*tail)) + { *(tail++) = '\0'; + } else if (tail && *tail) // some not whitespace symbol + { return false; // args not modified and can be re-parsed + } if (valRaw > std::numeric_limits::max()) { @@ -2409,9 +2489,13 @@ bool ChatHandler::ExtractUInt64(char** args, uint64& val) unsigned long valRaw = strtoul(*args, &tail, 10); if (tail != *args && isWhiteSpace(*tail)) + { *(tail++) = '\0'; + } else if (tail && *tail) // some not whitespace symbol + { return false; // args not modified and can be re-parsed + } if (valRaw > std::numeric_limits::max()) { @@ -2445,9 +2529,13 @@ bool ChatHandler::ExtractInt64(char** args, int64& val) long valRaw = strtol(*args, &tail, 10); if (tail != *args && isWhiteSpace(*tail)) + { *(tail++) = '\0'; + } else if (tail && *tail) // some not whitespace symbol + { return false; // args not modified and can be re-parsed + } if (valRaw < std::numeric_limits::min() || valRaw > std::numeric_limits::max()) { @@ -2498,9 +2586,13 @@ bool ChatHandler::ExtractFloat(char** args, float& val) double valRaw = strtod(*args, &tail); if (tail != *args && isWhiteSpace(*tail)) + { *(tail++) = '\0'; + } else if (tail && *tail) // some not whitespace symbol + { return false; // args not modified and can be re-parsed + } // value successfully extracted val = float(valRaw); @@ -2573,7 +2665,9 @@ char* ChatHandler::ExtractLiteralArg(char** args, char const* lit /*= NULL*/) ++largs; if (largs < l) + { l = largs; + } int diff = strncmp(head, lit, l); @@ -2598,7 +2692,9 @@ char* ChatHandler::ExtractLiteralArg(char** args, char const* lit /*= NULL*/) *args = head; } else + { *args = head + l; + } SkipWhiteSpaces(args); return arg; @@ -2637,7 +2733,9 @@ char* ChatHandler::ExtractQuotedArg(char** args, bool asis /*= false*/) char guard = (*args)[0]; if (guard == '[') + { guard = ']'; + } char* tail = (*args) + 1; // start scan after first quote symbol char* head = asis ? *args : tail; // start arg @@ -2653,12 +2751,16 @@ char* ChatHandler::ExtractQuotedArg(char** args, bool asis /*= false*/) if (!tail[1]) // quote is last char in string { if (!asis) + { *tail = '\0'; + } } else // quote isn't last char { if (asis) + { ++tail; + } *tail = '\0'; } @@ -2681,7 +2783,9 @@ char* ChatHandler::ExtractQuotedOrLiteralArg(char** args, bool asis /*= false*/) { char* arg = ExtractQuotedArg(args, asis); if (!arg) + { arg = ExtractLiteralArg(args); + } return arg; } @@ -2701,9 +2805,13 @@ bool ChatHandler::ExtractOnOff(char** args, bool& value) } if (strncmp(arg, "on", 3) == 0) + { value = true; + } else if (strncmp(arg, "off", 4) == 0) + { value = false; + } else { return false; @@ -2901,10 +3009,14 @@ char* ChatHandler::ExtractLinkArg(char** args, char const* const* linkTypes /*= // success if (*tail) // truncate all link string + { *(tail++) = '\0'; + } if (foundIdx) + { *foundIdx = linktype_idx; + } if (keyPair) { @@ -2941,7 +3053,9 @@ char* ChatHandler::ExtractArg(char** args, bool asis /*= false*/) char* arg = ExtractQuotedOrLiteralArg(args, asis); if (!arg) + { arg = ExtractLinkArg(args); + } return arg; } @@ -3024,7 +3138,9 @@ char* ChatHandler::ExtractKeyFromLink(char** text, char const* const* linkTypes, if (arg) { if (found_idx) + { *found_idx = -1; // special index case + } return arg; } @@ -3149,7 +3265,9 @@ uint32 ChatHandler::ExtractSpellIdFromLink(char** text) } if (rank < 0) // unlearned talent have in shift-link field -1 as rank + { rank = 0; + } return rank < MAX_TALENT_RANK ? talentEntry->RankID[rank] : 0; } @@ -3604,30 +3722,42 @@ bool ChatHandler::ExtractPlayerTarget(char** args, Player** player /*= NULL*/, O // if allowed player pointer if (player) + { *player = pl; + } // if need guid value from DB (in name case for check player existence) ObjectGuid guid = !pl && (player_guid || player_name) ? sObjectMgr.GetPlayerGuidByName(name) : ObjectGuid(); // if allowed player guid (if no then only online players allowed) if (player_guid) + { *player_guid = pl ? pl->GetObjectGuid() : guid; + } if (player_name) + { *player_name = pl || guid ? name : ""; + } } else { Player* pl = getSelectedPlayer(); // if allowed player pointer if (player) + { *player = pl; + } // if allowed player guid (if no then only online players allowed) if (player_guid) + { *player_guid = pl ? pl->GetObjectGuid() : ObjectGuid(); + } if (player_name) + { *player_name = pl ? pl->GetName() : ""; + } } // some from req. data must be provided (note: name is empty if player not exist) @@ -3665,10 +3795,14 @@ uint32 ChatHandler::ExtractAccountId(char** args, std::string* accountName /*= N account_id = targetPlayer->GetSession()->GetAccountId(); if (accountName) + { sAccountMgr.GetName(account_id, *accountName); + } if (targetIfNullArg) + { *targetIfNullArg = targetPlayer; + } return account_id; } @@ -3704,10 +3838,14 @@ uint32 ChatHandler::ExtractAccountId(char** args, std::string* accountName /*= N } if (accountName) + { *accountName = account_name; + } if (targetIfNullArg) + { *targetIfNullArg = NULL; + } return account_id; } @@ -3746,7 +3884,9 @@ bool ChatHandler::ExtractRaceMask(char** text, uint32& raceMask, char const** ma if (ExtractUInt32(text, raceMask)) { if (maskName) + { *maskName = "custom mask"; + } } else { @@ -3757,7 +3897,9 @@ bool ChatHandler::ExtractRaceMask(char** text, uint32& raceMask, char const** ma raceMask = itr->raceMask; if (maskName) + { *maskName = itr->literal; + } break; } } @@ -3853,9 +3995,13 @@ void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid) { uint16 top_pool_id = sPoolMgr.IsPartOfTopPool(pool_id); if (!top_pool_id || top_pool_id == pool_id) + { PSendSysMessage(LANG_NPC_GO_INFO_POOL, pool_id); + } else + { PSendSysMessage(LANG_NPC_GO_INFO_TOP_POOL, pool_id, top_pool_id); + } if (int16 event_id = sGameEventMgr.GetGameEventId(top_pool_id)) { @@ -3863,9 +4009,13 @@ void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid) GameEventData const& eventData = events[std::abs(event_id)]; if (event_id > 0) + { PSendSysMessage(LANG_NPC_GO_INFO_POOL_GAME_EVENT_S, top_pool_id, std::abs(event_id), eventData.description.c_str()); + } else + { PSendSysMessage(LANG_NPC_GO_INFO_POOL_GAME_EVENT_D, top_pool_id, std::abs(event_id), eventData.description.c_str()); + } } } else if (int16 event_id = sGameEventMgr.GetGameEventId(guid)) @@ -3874,9 +4024,13 @@ void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid) GameEventData const& eventData = events[std::abs(event_id)]; if (event_id > 0) + { PSendSysMessage(LANG_NPC_GO_INFO_GAME_EVENT_S, std::abs(event_id), eventData.description.c_str()); + } else + { PSendSysMessage(LANG_NPC_GO_INFO_GAME_EVENT_D, std::abs(event_id), eventData.description.c_str()); + } } } @@ -4003,7 +4157,9 @@ void ChatHandler::BuildChatPacket(WorldPacket& data, ChatMsg msgtype, char const data << addonPrefix; } else + { data << ObjectGuid(targetGuid); + } break; } MANGOS_ASSERT(message); @@ -4012,7 +4168,9 @@ void ChatHandler::BuildChatPacket(WorldPacket& data, ChatMsg msgtype, char const data << uint8(chatTag); if (isAchievement) + { data << uint32(achievementId); + } if (msgtype == CHAT_MSG_RAID_BOSS_WHISPER || msgtype == CHAT_MSG_RAID_BOSS_EMOTE) { diff --git a/src/game/WorldHandlers/ChatHandler.cpp b/src/game/WorldHandlers/ChatHandler.cpp index fbe4f8711..8eb833c19 100644 --- a/src/game/WorldHandlers/ChatHandler.cpp +++ b/src/game/WorldHandlers/ChatHandler.cpp @@ -50,7 +50,9 @@ bool WorldSession::processChatmessageFurtherAfterSecurityChecks(std::string& msg { // strip invisible characters for non-addon messages if (sWorld.getConfig(CONFIG_BOOL_CHAT_FAKE_MESSAGE_PREVENTING)) + { stripLineInvisibleChars(msg); + } if (sWorld.getConfig(CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY) && GetSecurity() < SEC_MODERATOR && !ChatHandler(this).isValidChatMessage(msg.c_str())) @@ -58,7 +60,9 @@ bool WorldSession::processChatmessageFurtherAfterSecurityChecks(std::string& msg sLog.outError("Player %s (GUID: %u) sent a chatmessage with an invalid link: %s", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow(), msg.c_str()); if (sWorld.getConfig(CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_KICK)) + { KickPlayer(); + } return false; } } @@ -137,12 +141,16 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) { // send in universal language if player in .gmon mode (ignore spell effects) if (_player->isGameMaster()) + { lang = LANG_UNIVERSAL; + } else { // send in universal language in two side iteration allowed mode if (sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT)) + { lang = LANG_UNIVERSAL; + } else { switch (type) @@ -154,13 +162,17 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) case CHAT_MSG_RAID_WARNING: // allow two side chat at group channel if two side group allowed if (sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP)) + { lang = LANG_UNIVERSAL; + } break; case CHAT_MSG_GUILD: case CHAT_MSG_OFFICER: // allow two side chat at guild channel if two side guild allowed if (sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD)) + { lang = LANG_UNIVERSAL; + } break; } } @@ -168,7 +180,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) // but overwrite it by SPELL_AURA_MOD_LANGUAGE auras (only single case used) Unit::AuraList const& ModLangAuras = _player->GetAurasByType(SPELL_AURA_MOD_LANGUAGE); if (!ModLangAuras.empty()) + { lang = ModLangAuras.front()->GetModifier()->m_miscvalue; + } } if (type != CHAT_MSG_AFK && type != CHAT_MSG_DND) @@ -185,7 +199,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } } else + { lang = LANG_UNIVERSAL; + } DEBUG_LOG("CHAT: packet received. type %u lang %u", type, lang); @@ -199,10 +215,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) msg = recv_data.ReadString(recv_data.ReadBits(9)); if (msg.empty()) + { break; + } if (ChatHandler(this).ParseCommands(msg.c_str())) + { break; + } if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) { @@ -210,7 +230,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } if (type == CHAT_MSG_SAY) { @@ -265,12 +287,16 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) return; } if (msg.empty()) + { break; + } if (!normalizePlayerName(to)) { SendPlayerNotFoundNotice(to); - { break; } + { + break; + } } Player* player = sObjectMgr.GetPlayer(to.c_str()); @@ -308,10 +334,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) msg = recv_data.ReadString(recv_data.ReadBits(9)); if (msg.empty()) + { break; + } if (ChatHandler(this).ParseCommands(msg.c_str())) + { break; + } if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) { @@ -319,7 +349,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } // if player is in battleground, he cannot say to battleground members by /p Group* group = GetPlayer()->GetOriginalGroup(); @@ -356,10 +388,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) msg = recv_data.ReadString(recv_data.ReadBits(9)); if (msg.empty()) + { break; + } if (ChatHandler(this).ParseCommands(msg.c_str())) + { break; + } if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) { @@ -367,7 +403,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } if (GetPlayer()->GetGuildId()) if (Guild* guild = sGuildMgr.GetGuildById(GetPlayer()->GetGuildId())) @@ -391,10 +429,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) msg = recv_data.ReadString(recv_data.ReadBits(9)); if (msg.empty()) + { break; + } if (ChatHandler(this).ParseCommands(msg.c_str())) + { break; + } if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) { @@ -402,7 +444,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } if (GetPlayer()->GetGuildId()) if (Guild* guild = sGuildMgr.GetGuildById(GetPlayer()->GetGuildId())) @@ -426,10 +470,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) msg = recv_data.ReadString(recv_data.ReadBits(9)); if (msg.empty()) + { break; + } if (ChatHandler(this).ParseCommands(msg.c_str())) + { break; + } if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) { @@ -437,7 +485,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } // if player is in battleground, he cannot say to battleground members by /ra Group* group = GetPlayer()->GetOriginalGroup(); @@ -468,10 +518,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) msg = recv_data.ReadString(recv_data.ReadBits(9)); if (msg.empty()) + { break; + } if (ChatHandler(this).ParseCommands(msg.c_str())) + { break; + } if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) { @@ -479,7 +533,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } // if player is in battleground, he cannot say to battleground members by /ra Group* group = GetPlayer()->GetOriginalGroup(); @@ -516,7 +572,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } Group* group = GetPlayer()->GetGroup(); if (!group || !group->isRaidGroup() || @@ -548,7 +606,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } // battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() Group* group = GetPlayer()->GetGroup(); @@ -581,7 +641,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } // battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() Group* group = GetPlayer()->GetGroup(); @@ -617,7 +679,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) } if (msg.empty()) + { break; + } if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) { @@ -646,16 +710,22 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) if (_player->isAFK()) // Already AFK { if (msg.empty()) + { _player->ToggleAFK(); // Remove AFK + } else + { _player->autoReplyMsg = msg; // Update message + } } else // New AFK mode { _player->autoReplyMsg = msg.empty() ? GetMangosString(LANG_PLAYER_AFK_DEFAULT) : msg; if (_player->isDND()) + { _player->ToggleDND(); + } _player->ToggleAFK(); } @@ -677,16 +747,22 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recv_data) if (_player->isDND()) // Already DND { if (msg.empty()) + { _player->ToggleDND(); // Remove DND + } else + { _player->autoReplyMsg = msg; // Update message + } } else // New DND mode { _player->autoReplyMsg = msg.empty() ? GetMangosString(LANG_PLAYER_DND_DEFAULT) : msg; if (_player->isAFK()) + { _player->ToggleAFK(); + } _player->ToggleDND(); } @@ -760,7 +836,9 @@ void WorldSession::HandleAddonMessagechatOpcode(WorldPacket& recv_data) if (_player->GetGuildId()) if (Guild* guild = sGuildMgr.GetGuildById(_player->GetGuildId())) + { guild->BroadcastAddonToGuild(this, msg, prefix); + } break; } @@ -773,7 +851,9 @@ void WorldSession::HandleAddonMessagechatOpcode(WorldPacket& recv_data) if (_player->GetGuildId()) if (Guild* guild = sGuildMgr.GetGuildById(_player->GetGuildId())) + { guild->BroadcastAddonToOfficers(this, msg, prefix); + } break; } case CHAT_MSG_WHISPER: @@ -786,11 +866,15 @@ void WorldSession::HandleAddonMessagechatOpcode(WorldPacket& recv_data) std::string targetName = recv_data.ReadString(targetLen); if (!normalizePlayerName(targetName)) + { break; + } Player* receiver = sObjectMgr.GetPlayer(targetName.c_str()); if (!receiver) + { break; + } WorldPacket data; ChatHandler::BuildChatPacket(data, type, msg.c_str(), LANG_UNIVERSAL, CHAT_TAG_NONE, ObjectGuid(), NULL, receiver->GetObjectGuid(), targetName.c_str(), NULL, 0, prefix.c_str()); @@ -808,7 +892,9 @@ void WorldSession::HandleAddonMessagechatOpcode(WorldPacket& recv_data) Group* group = _player->GetGroup(); if (!group || group->isBGGroup()) + { break; + } WorldPacket data; ChatHandler::BuildChatPacket(data, type, msg.c_str(), LANG_ADDON, CHAT_TAG_NONE, ObjectGuid(), NULL, ObjectGuid(), NULL, NULL, 0, prefix.c_str()); @@ -859,9 +945,13 @@ namespace MaNGOS data << uint32(i_emote_num); data << uint32(namlen); if (namlen > 1) + { data.append(nam, namlen); + } else + { data << uint8(0x00); + } DEBUG_LOG("SMSG_TEXT_EMOTE i_text_emote %u i_emote_num %u", i_text_emote, i_emote_num); @@ -923,7 +1013,9 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket& recv_data) { // in feign death state allowed only text emotes. if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) + { break; + } GetPlayer()->HandleEmoteCommand(emote_id); break; @@ -941,7 +1033,9 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket& recv_data) // Send scripted event call if (unit && unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->AI()) + { ((Creature*)unit)->AI()->ReceiveEmote(GetPlayer(), text_emote); + } } void WorldSession::HandleChatIgnoredOpcode(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/CreatureLinkingMgr.cpp b/src/game/WorldHandlers/CreatureLinkingMgr.cpp index 353857b95..34ea72c77 100644 --- a/src/game/WorldHandlers/CreatureLinkingMgr.cpp +++ b/src/game/WorldHandlers/CreatureLinkingMgr.cpp @@ -106,7 +106,9 @@ void CreatureLinkingMgr::LoadFromDB() tmp.masterDBGuid = 0; // Will be initialized for unique mobs in IsLinkingEntryValid (only for spawning dependend) if (!IsLinkingEntryValid(entry, &tmp, true)) + { continue; + } ++count; @@ -155,7 +157,9 @@ void CreatureLinkingMgr::LoadFromDB() tmp.searchRange = 0; if (!IsLinkingEntryValid(guid, &tmp, false)) + { continue; + } ++count; @@ -331,7 +335,9 @@ CreatureLinkingInfo const* CreatureLinkingMgr::GetLinkedTriggerInformation(uint3 // guid case CreatureLinkingMapBounds bounds = m_creatureLinkingGuidMap.equal_range(lowGuid); for (CreatureLinkingMap::const_iterator iter = bounds.first; iter != bounds.second;) + { return &(iter->second); + } // entry case bounds = m_creatureLinkingMap.equal_range(entry); @@ -421,7 +427,9 @@ void CreatureLinkingHolder::AddMasterToHolder(Creature* pCreature) BossGuidMapBounds bounds = m_masterGuid.equal_range(pCreature->GetEntry()); for (BossGuidMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr) if (itr->second == pCreature->GetObjectGuid()) + { return; // Already added + } m_masterGuid.insert(BossGuidMap::value_type(pCreature->GetEntry(), pCreature->GetObjectGuid())); } @@ -485,7 +493,9 @@ void CreatureLinkingHolder::DoCreatureLinkingEvent(CreatureLinkingEvent eventTyp { pMaster = pSource->GetMap()->GetCreature(itr->second); if (pMaster && IsSlaveInRangeOfBoss(pSource, pMaster, pInfo->searchRange)) + { break; + } } } else // guid case @@ -506,17 +516,25 @@ void CreatureLinkingHolder::DoCreatureLinkingEvent(CreatureLinkingEvent eventTyp } if (pMaster->IsInCombat()) + { pMaster->SetInCombatWith(pEnemy); + } else + { pMaster->AI()->AttackStart(pEnemy); + } break; case LINKING_EVENT_EVADE: if (!pMaster->IsAlive()) + { pMaster->Respawn(); + } break; case LINKING_EVENT_RESPAWN: if (pMaster->IsAlive()) + { SetFollowing(pSource, pMaster); + } break; case LINKING_EVENT_DIE: // Nothing linked for this case case LINKING_EVENT_DESPAWN: // Nothing linked for this case @@ -549,11 +567,15 @@ void CreatureLinkingHolder::ProcessSlaveGuidList(CreatureLinkingEvent eventType, // Ignore Pets if (pSlave->IsPet()) + { continue; + } // Handle single slave if (IsSlaveInRangeOfBoss(pSlave, pSource, searchRange)) + { ProcessSlave(eventType, pSource, flag, pSlave, pEnemy); + } } } @@ -571,42 +593,64 @@ void CreatureLinkingHolder::ProcessSlave(CreatureLinkingEvent eventType, Creatur } if (pSlave->IsInCombat()) + { pSlave->SetInCombatWith(pEnemy); + } else + { pSlave->AI()->AttackStart(pEnemy); + } } break; case LINKING_EVENT_EVADE: if (flag & FLAG_DESPAWN_ON_EVADE && pSlave->IsAlive()) + { pSlave->ForcedDespawn(); + } if (flag & FLAG_RESPAWN_ON_EVADE && !pSlave->IsAlive()) + { pSlave->Respawn(); + } break; case LINKING_EVENT_DIE: if (flag & FLAG_SELFKILL_ON_DEATH && pSlave->IsAlive()) + { pSlave->DealDamage(pSlave, pSlave->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + } if (flag & FLAG_DESPAWN_ON_DEATH && pSlave->IsAlive()) + { pSlave->ForcedDespawn(); + } if (flag & FLAG_RESPAWN_ON_DEATH && !pSlave->IsAlive()) + { pSlave->Respawn(); + } break; case LINKING_EVENT_RESPAWN: if (flag & FLAG_RESPAWN_ON_RESPAWN) { // Additional check to prevent endless loops (in case whole group respawns on first respawn) if (!pSlave->IsAlive() && pSlave->GetRespawnTime() > time(NULL)) + { pSlave->Respawn(); + } } else if (flag & FLAG_DESPAWN_ON_RESPAWN && pSlave->IsAlive()) + { pSlave->ForcedDespawn(); + } if (flag & FLAG_FOLLOW && pSlave->IsAlive() && !pSlave->IsInCombat()) + { SetFollowing(pSlave, pSource); + } break; case LINKING_EVENT_DESPAWN: if (flag & FLAG_DESPAWN_ON_DESPAWN && !pSlave->IsDespawned()) + { pSlave->ForcedDespawn(); + } break; } @@ -630,7 +674,9 @@ void CreatureLinkingHolder::SetFollowing(Creature* pWho, Creature* pWhom) // Atm this means we have to subtract the bounding radiuses dist = dist - pWho->GetObjectBoundingRadius() - pWhom->GetObjectBoundingRadius(); if (dist < 0.0f) + { dist = 0.0f; + } // Need to pass the relative angle to following float angle = atan2(dy, dx) - mO; @@ -721,7 +767,9 @@ bool CreatureLinkingHolder::CanSpawn(uint32 lowGuid, Map* _map, CreatureLinkingI if (pInfo->searchRange == 0) // Map wide case { if (!pInfo->masterDBGuid) + { return false; // This should never happen + } if (pInfo->linkingFlag & FLAG_CANT_SPAWN_IF_BOSS_DEAD) { @@ -779,7 +827,9 @@ bool CreatureLinkingHolder::TryFollowMaster(Creature* pCreature) { pMaster = pCreature->GetMap()->GetCreature(itr->second); if (pMaster && IsSlaveInRangeOfBoss(pCreature, pMaster, pInfo->searchRange)) + { break; + } } } else // guid case diff --git a/src/game/WorldHandlers/DisableMgr.cpp b/src/game/WorldHandlers/DisableMgr.cpp index 15185bd5b..290731d86 100644 --- a/src/game/WorldHandlers/DisableMgr.cpp +++ b/src/game/WorldHandlers/DisableMgr.cpp @@ -82,9 +82,13 @@ void LoadDisables() DisableData* data; if (m_DisableMap[type].find(entry) != m_DisableMap[type].end()) + { data = &m_DisableMap[type][entry]; + } else + { data = new DisableData(); + } data->flags = flags; @@ -104,10 +108,14 @@ void LoadDisables() } if (flags & SPELL_DISABLE_MAP) + { data->params[0].insert(data0 & 0xFFFF); + } if (flags & SPELL_DISABLE_AREA) + { data->params[1].insert(data0 >> 16); + } break; // checked later @@ -128,7 +136,9 @@ void LoadDisables() case MAP_INSTANCE: case MAP_RAID: if (flags) + { isFlagInvalid = true; + } break; case MAP_BATTLEGROUND: //case MAP_ARENA: [-ZERO] @@ -308,10 +318,14 @@ bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags { std::set const& mapIds = itr->second.params[0]; if (mapIds.find(unit->GetMapId()) != mapIds.end()) + { return true; // Spell is disabled on current map + } if (!(spellFlags & SPELL_DISABLE_AREA)) + { return false; // Spell is disabled on another map, but not this one, return false + } // Spell is disabled in an area, but not explicitly our current mapId. Continue processing. } @@ -320,7 +334,9 @@ bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags { std::set const& areaIds = itr->second.params[1]; if (areaIds.find(unit->GetAreaId()) != areaIds.end()) + { return true; // Spell is disabled in this area + } return false; // Spell is disabled in another area, but not this one, return false } else diff --git a/src/game/WorldHandlers/DuelHandler.cpp b/src/game/WorldHandlers/DuelHandler.cpp index f1ff8ed25..de3bf983a 100644 --- a/src/game/WorldHandlers/DuelHandler.cpp +++ b/src/game/WorldHandlers/DuelHandler.cpp @@ -75,7 +75,9 @@ void WorldSession::HandleDuelCancelledOpcode(WorldPacket& recvPacket) { GetPlayer()->CombatStopWithPets(true); if (GetPlayer()->duel->opponent) + { GetPlayer()->duel->opponent->CombatStopWithPets(true); + } GetPlayer()->CastSpell(GetPlayer(), 7267, true); // beg GetPlayer()->DuelComplete(DUEL_WON); diff --git a/src/game/WorldHandlers/GMTicketHandler.cpp b/src/game/WorldHandlers/GMTicketHandler.cpp index 0361edd0e..de62347f0 100644 --- a/src/game/WorldHandlers/GMTicketHandler.cpp +++ b/src/game/WorldHandlers/GMTicketHandler.cpp @@ -74,12 +74,18 @@ void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket & /*recv_data*/) if (ticket) { if (ticket->HasResponse()) + { SendGMResponse(ticket); + } else + { SendGMTicketGetTicket(0x06, ticket); + } } else + { SendGMTicketGetTicket(0x0A); + } } void WorldSession::HandleGMTicketUpdateTextOpcode(WorldPacket& recv_data) @@ -88,9 +94,13 @@ void WorldSession::HandleGMTicketUpdateTextOpcode(WorldPacket& recv_data) recv_data >> ticketText; if (GMTicket* ticket = sTicketMgr.GetGMTicket(GetPlayer()->GetObjectGuid())) + { ticket->SetText(ticketText.c_str()); + } else + { sLog.outError("Ticket update: Player %s (GUID: %u) doesn't have active ticket", GetPlayer()->GetName(), GetPlayer()->GetGUIDLow()); + } } void WorldSession::HandleGMTicketDeleteTicketOpcode(WorldPacket & /*recv_data*/) @@ -130,7 +140,9 @@ void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recv_data) } if (isFollowup) + { sTicketMgr.Delete(_player->GetObjectGuid()); + } sTicketMgr.Create(_player->GetObjectGuid(), ticketText.c_str()); @@ -145,7 +157,9 @@ void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recv_data) for (HashMapHolder::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { if (itr->second->GetSession()->GetSecurity() >= SEC_GAMEMASTER && itr->second->isAcceptTickets()) + { ChatHandler(itr->second).PSendSysMessage(LANG_COMMAND_TICKETNEW, GetPlayer()->GetName()); + } } } @@ -171,7 +185,9 @@ void WorldSession::HandleGMSurveySubmitOpcode(WorldPacket& recv_data) uint32 questionID; recv_data >> questionID; // GMSurveyQuestions.dbc if (!questionID) + { break; + } uint8 value; std::string unk_text; diff --git a/src/game/WorldHandlers/GameEventMgr.cpp b/src/game/WorldHandlers/GameEventMgr.cpp index c6aad4632..dfc273d77 100644 --- a/src/game/WorldHandlers/GameEventMgr.cpp +++ b/src/game/WorldHandlers/GameEventMgr.cpp @@ -76,7 +76,9 @@ uint32 GameEventMgr::NextCheck(uint16 entry) const // we return the delay before it ends delay = (mGameEvent[entry].length * MINUTE) - ((currenttime - mGameEvent[entry].start) % (mGameEvent[entry].occurence * MINUTE)); else // not in window, we return the delay before next start + { delay = (mGameEvent[entry].occurence * MINUTE) - ((currenttime - mGameEvent[entry].start) % (mGameEvent[entry].occurence * MINUTE)); + } // In case the end is before next check if (mGameEvent[entry].end < time_t(currenttime + delay)) { @@ -95,11 +97,15 @@ void GameEventMgr::StartEvent(uint16 event_id, bool overwrite /*=false*/, bool r { mGameEvent[event_id].start = time(NULL); if (mGameEvent[event_id].end <= mGameEvent[event_id].start) + { mGameEvent[event_id].end = mGameEvent[event_id].start + mGameEvent[event_id].length; + } } #ifdef ENABLE_ELUNA if (IsActiveEvent(event_id)) + { sEluna->OnGameEventStart(event_id); + } #endif /* ENABLE_ELUNA */ } @@ -110,11 +116,15 @@ void GameEventMgr::StopEvent(uint16 event_id, bool overwrite) { mGameEvent[event_id].start = time(NULL) - mGameEvent[event_id].length * MINUTE; if (mGameEvent[event_id].end <= mGameEvent[event_id].start) + { mGameEvent[event_id].end = mGameEvent[event_id].start + mGameEvent[event_id].length; + } } #ifdef ENABLE_ELUNA if (!IsActiveEvent(event_id)) + { sEluna->OnGameEventStop(event_id); + } #endif /* ENABLE_ELUNA */ } @@ -645,7 +655,9 @@ uint32 GameEventMgr::Update(ActiveEvents const* activeAtShutdown /*= NULL*/) for (uint16 itr = 1; itr < mGameEvent.size(); ++itr) { if (!mGameEvent[itr].isValid()) + { continue; + } // sLog.outErrorDb("Checking event %u",itr); if (CheckOneGameEvent(itr, currenttime)) @@ -661,7 +673,9 @@ uint32 GameEventMgr::Update(ActiveEvents const* activeAtShutdown /*= NULL*/) { // DEBUG_LOG("GameEvent %u is not active",itr->first); if (IsActiveEvent(itr)) + { StopEvent(itr); + } else { if (!m_IsGameEventsInit) @@ -675,7 +689,9 @@ uint32 GameEventMgr::Update(ActiveEvents const* activeAtShutdown /*= NULL*/) } calcDelay = NextCheck(itr); if (calcDelay < nextEventDelay) + { nextEventDelay = calcDelay; + } } BASIC_LOG("Next game event check in %u seconds.", nextEventDelay + 1); return (nextEventDelay + 1) * IN_MILLISECONDS; // Add 1 second to be sure event has started/stopped at next call @@ -706,7 +722,9 @@ void GameEventMgr::ApplyNewEvent(uint16 event_id, bool resume) CharacterDatabase.PExecute("INSERT INTO `game_event_status` (`event`) VALUES (%u)", event_id); if (sWorld.getConfig(CONFIG_BOOL_EVENT_ANNOUNCE)) + { sWorld.SendWorldText(LANG_EVENTMESSAGE, mGameEvent[event_id].description.c_str()); + } sLog.outString("GameEvent %u \"%s\" started.", event_id, mGameEvent[event_id].description.c_str()); // spawn positive event tagget objects @@ -722,7 +740,9 @@ void GameEventMgr::ApplyNewEvent(uint16 event_id, bool resume) // Not send mails at game event startup, if game event just resume after server shutdown (has been active at server before shutdown) if (!resume) + { SendEventMails(event_id); + } } void GameEventMgr::GameEventSpawn(int16 event_id) @@ -924,7 +944,9 @@ struct GameEventUpdateCreatureDataInMapsWorker // spells not casted for event remove case (sent NULL into update), do it if (!i_activate) + { pCreature->ApplyGameEventSpells(i_event_data, false); + } } } @@ -941,7 +963,9 @@ void GameEventMgr::UpdateCreatureData(int16 event_id, bool activate) // Remove the creature from grid CreatureData const* data = sObjectMgr.GetCreatureData(itr->first); if (!data) + { continue; + } // Update if spawned GameEventUpdateCreatureDataInMapsWorker worker(data->GetObjectGuid(itr->first), data, &itr->second, activate); @@ -1005,7 +1029,9 @@ void GameEventMgr::SendEventMails(int16 event_id) sMassMailMgr.AddMassMailTask(new MailDraft(itr->mailTemplateId), MailSender(MAIL_CREATURE, itr->senderEntry), ss.str().c_str()); } else + { sMassMailMgr.AddMassMailTask(new MailDraft(itr->mailTemplateId), MailSender(MAIL_CREATURE, itr->senderEntry), itr->raceMask); + } } } @@ -1016,7 +1042,9 @@ int16 GameEventMgr::GetGameEventId(uint32 guid_or_poolid) for (uint16 i = 0; i < mGameEventCreatureGuids.size(); ++i) // 0 <= i <= 2*(S := mGameEvent.size()) - 2 for (GuidList::const_iterator itr = mGameEventCreatureGuids[i].begin(); itr != mGameEventCreatureGuids[i].end(); ++itr) if (*itr == guid_or_poolid) + { return i + 1 - mGameEvent.size(); // -S *1 + 1 <= . <= 1*S - 1 + } return 0; } @@ -1027,7 +1055,9 @@ int16 GameEventMgr::GetGameEventId(uint32 guid_or_poolid) for (uint16 i = 0; i < mGameEventGameobjectGuids.size(); ++i) for (GuidList::const_iterator itr = mGameEventGameobjectGuids[i].begin(); itr != mGameEventGameobjectGuids[i].end(); ++itr) if (*itr == guid_or_poolid) + { return i + 1 - mGameEvent.size(); // -S *1 + 1 <= . <= 1*S - 1 + } return 0; } diff --git a/src/game/WorldHandlers/GossipDef.cpp b/src/game/WorldHandlers/GossipDef.cpp index dfb9fe062..52cfbb823 100644 --- a/src/game/WorldHandlers/GossipDef.cpp +++ b/src/game/WorldHandlers/GossipDef.cpp @@ -243,7 +243,9 @@ void PlayerMenu::SendPointOfInterest(uint32 poi_id) if (loc_idx >= 0) if (PointOfInterestLocale const* pl = sObjectMgr.GetPointOfInterestLocale(poi_id)) if (pl->IconName.size() > size_t(loc_idx) && !pl->IconName[loc_idx].empty()) + { icon_name = pl->IconName[loc_idx]; + } WorldPacket data(SMSG_GOSSIP_POI, (4 + 4 + 4 + 4 + 4 + 10)); // guess size data << uint32(poi->flags); @@ -298,14 +300,22 @@ void PlayerMenu::SendTalking(uint32 textID) data << pGossip->Options[i].Probability; if (Text_0[i].empty()) + { data << Text_1[i]; + } else + { data << Text_0[i]; + } if (Text_1[i].empty()) + { data << Text_0[i]; + } else + { data << Text_1[i]; + } data << pGossip->Options[i].Language; @@ -453,19 +463,33 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* pQuest, ObjectGuid guid if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId())) { if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty()) + { Title = ql->Title[loc_idx]; + } if (ql->Details.size() > (size_t)loc_idx && !ql->Details[loc_idx].empty()) + { Details = ql->Details[loc_idx]; + } if (ql->Objectives.size() > (size_t)loc_idx && !ql->Objectives[loc_idx].empty()) + { Objectives = ql->Objectives[loc_idx]; + } if (ql->PortraitGiverName.size() > (size_t)loc_idx && !ql->PortraitGiverName[loc_idx].empty()) + { PortraitGiverName = ql->PortraitGiverName[loc_idx]; + } if (ql->PortraitGiverText.size() > (size_t)loc_idx && !ql->PortraitGiverText[loc_idx].empty()) + { PortraitGiverText = ql->PortraitGiverText[loc_idx]; + } if (ql->PortraitTurnInName.size() > (size_t)loc_idx && !ql->PortraitTurnInName[loc_idx].empty()) + { PortraitTurnInName = ql->PortraitTurnInName[loc_idx]; + } if (ql->PortraitTurnInText.size() > (size_t)loc_idx && !ql->PortraitTurnInText[loc_idx].empty()) + { PortraitTurnInText = ql->PortraitTurnInText[loc_idx]; + } } } @@ -503,9 +527,13 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* pQuest, ObjectGuid guid } for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i) if (ItemPrototype const* IProto = ObjectMgr::GetItemPrototype(pQuest->RewChoiceItemId[i])) + { data << IProto->DisplayInfoID; + } else + { data << uint32(0); + } data << pQuest->GetRewItemsCount(); @@ -519,15 +547,23 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* pQuest, ObjectGuid guid } for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i) if (ItemPrototype const* IProto = ObjectMgr::GetItemPrototype(pQuest->RewItemId[i])) + { data << IProto->DisplayInfoID; + } else + { data << uint32(0); + } // send rewMoneyMaxLevel explicit for max player level, else send RewOrReqMoney if (GetMenuSession()->GetPlayer()->getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) + { data << pQuest->GetRewMoneyMaxLevel(); + } else + { data << pQuest->GetRewOrReqMoney(); + } data << pQuest->XPValue(GetMenuSession()->GetPlayer()); @@ -539,7 +575,9 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* pQuest, ObjectGuid guid data << uint32(0); // rep reward show mask? for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids + { data << pQuest->RewRepFaction[i]; + } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (if negative, from second row) { @@ -547,7 +585,9 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* pQuest, ObjectGuid guid } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override. No bonus is expected given + { data << int32(0); + } // data << int32(pQuest->RewRepValue[i]); // current field for store of rep value, can be reused to implement "override value" data << pQuest->GetRewSpell(); // reward spell, this spell will display (icon) (casted if RewSpellCast==0) @@ -607,27 +647,47 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* pQuest) if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId())) { if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty()) + { Title = ql->Title[loc_idx]; + } if (ql->Details.size() > (size_t)loc_idx && !ql->Details[loc_idx].empty()) + { Details = ql->Details[loc_idx]; + } if (ql->Objectives.size() > (size_t)loc_idx && !ql->Objectives[loc_idx].empty()) + { Objectives = ql->Objectives[loc_idx]; + } if (ql->EndText.size() > (size_t)loc_idx && !ql->EndText[loc_idx].empty()) + { EndText = ql->EndText[loc_idx]; + } if (ql->CompletedText.size() > (size_t)loc_idx && !ql->CompletedText[loc_idx].empty()) + { CompletedText = ql->CompletedText[loc_idx]; + } if (ql->PortraitGiverName.size() > (size_t)loc_idx && !ql->PortraitGiverName[loc_idx].empty()) + { PortraitGiverName = ql->PortraitGiverName[loc_idx]; + } if (ql->PortraitGiverText.size() > (size_t)loc_idx && !ql->PortraitGiverText[loc_idx].empty()) + { PortraitGiverText = ql->PortraitGiverText[loc_idx]; + } if (ql->PortraitTurnInName.size() > (size_t)loc_idx && !ql->PortraitTurnInName[loc_idx].empty()) + { PortraitTurnInName = ql->PortraitTurnInName[loc_idx]; + } if (ql->PortraitTurnInText.size() > (size_t)loc_idx && !ql->PortraitTurnInText[loc_idx].empty()) + { PortraitTurnInText = ql->PortraitTurnInText[loc_idx]; + } for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) if (ql->ObjectiveText[i].size() > (size_t)loc_idx && !ql->ObjectiveText[i][loc_idx].empty()) + { ObjectiveText[i] = ql->ObjectiveText[i][loc_idx]; + } } } @@ -655,7 +715,9 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* pQuest) /*if (pQuest->HasQuestFlag(QUEST_FLAGS_HIDDEN_REWARDS)) data << uint32(0); // Hide money rewarded else*/ + { data << uint32(pQuest->GetRewOrReqMoney()); // reward money (below max lvl) + } data << uint32(pQuest->GetRewMoneyMaxLevel()); // used in XP calculation at client data << uint32(pQuest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast==0) @@ -710,7 +772,9 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* pQuest) } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids + { data << uint32(pQuest->RewRepFaction[i]); + } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (if negative, from second row) { @@ -718,7 +782,9 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* pQuest) } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override. No bonus is expected given + { data << int32(0); + } // data << int32(pQuest->RewRepValue[i]); // current field for store of rep value, can be reused to implement "override value" data << pQuest->GetPointMapId(); @@ -800,17 +866,29 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGU if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId())) { if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty()) + { Title = ql->Title[loc_idx]; + } if (ql->OfferRewardText.size() > (size_t)loc_idx && !ql->OfferRewardText[loc_idx].empty()) + { OfferRewardText = ql->OfferRewardText[loc_idx]; + } if (ql->PortraitGiverName.size() > (size_t)loc_idx && !ql->PortraitGiverName[loc_idx].empty()) + { PortraitGiverName = ql->PortraitGiverName[loc_idx]; + } if (ql->PortraitGiverText.size() > (size_t)loc_idx && !ql->PortraitGiverText[loc_idx].empty()) + { PortraitGiverText = ql->PortraitGiverText[loc_idx]; + } if (ql->PortraitTurnInName.size() > (size_t)loc_idx && !ql->PortraitTurnInName[loc_idx].empty()) + { PortraitTurnInName = ql->PortraitTurnInName[loc_idx]; + } if (ql->PortraitTurnInText.size() > (size_t)loc_idx && !ql->PortraitTurnInText[loc_idx].empty()) + { PortraitTurnInText = ql->PortraitTurnInText[loc_idx]; + } } } @@ -836,7 +914,9 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGU for (uint32 i = 0; i < QUEST_EMOTE_COUNT; ++i) { if (pQuest->OfferRewardEmote[i] <= 0) + { break; + } ++EmoteCount; } @@ -858,9 +938,13 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGU } for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i) if (ItemPrototype const* pItem = ObjectMgr::GetItemPrototype(pQuest->RewChoiceItemId[i])) + { data << uint32(pItem->DisplayInfoID); + } else + { data << uint32(0); + } data << uint32(pQuest->GetRewItemsCount()); for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i) @@ -873,15 +957,23 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGU } for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i) if (ItemPrototype const* pItem = ObjectMgr::GetItemPrototype(pQuest->RewItemId[i])) + { data << uint32(pItem->DisplayInfoID); + } else + { data << uint32(0); + } // send rewMoneyMaxLevel explicit for max player level, else send RewOrReqMoney if (GetMenuSession()->GetPlayer()->getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL)) + { data << uint32(pQuest->GetRewMoneyMaxLevel()); + } else + { data << uint32(pQuest->GetRewOrReqMoney()); + } // xp data << uint32(pQuest->XPValue(GetMenuSession()->GetPlayer())); @@ -894,7 +986,9 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGU data << uint32(0); // rep reward show mask? for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids + { data << uint32(pQuest->RewRepFaction[i]); + } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (if negative, from second row) { @@ -902,7 +996,9 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGU } for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override. No diplomacy bonus is expected given, reward also does not display in chat window + { data << int32(0); + } // data << int32(pQuest->RewRepValue[i]); data << uint32(pQuest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast==0) @@ -945,9 +1041,13 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* pQuest, ObjectGuid npcG if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId())) { if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty()) + { Title = ql->Title[loc_idx]; + } if (ql->RequestItemsText.size() > (size_t)loc_idx && !ql->RequestItemsText[loc_idx].empty()) + { RequestItemsText = ql->RequestItemsText[loc_idx]; + } } } @@ -960,15 +1060,23 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* pQuest, ObjectGuid npcG data << uint32(0x00); // emote delay if (Completable) + { data << pQuest->GetCompleteEmote(); // emote id + } else + { data << pQuest->GetIncompleteEmote(); + } // Close Window after cancel if (CloseOnCancel) + { data << uint32(0x01); // auto finish + } else + { data << uint32(0x00); + } data << uint32(pQuest->GetQuestFlags()); // 3.3.3 questFlags data << uint32(pQuest->GetSuggestedPlayers()); // SuggestedGroupNum @@ -981,31 +1089,43 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* pQuest, ObjectGuid npcG for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { if (!pQuest->ReqItemId[i]) + { continue; + } pItem = ObjectMgr::GetItemPrototype(pQuest->ReqItemId[i]); data << uint32(pQuest->ReqItemId[i]); data << uint32(pQuest->ReqItemCount[i]); if (pItem) + { data << uint32(pItem->DisplayInfoID); + } else + { data << uint32(0); + } } data << uint32(pQuest->GetReqCurrencyCount()); for (int i = 0; i < QUEST_REQUIRED_CURRENCY_COUNT; ++i) { if (!pQuest->ReqCurrencyId[i]) + { continue; + } data << uint32(pQuest->ReqCurrencyId[i]); data << uint32(pQuest->ReqCurrencyCount[i]); } if (!Completable) // Completable = flags1 && flags2 && flags3 && flags4 + { data << uint32(0x00); // flags1 + } else + { data << uint32(0x03); + } data << uint32(0x04); // flags2 data << uint32(0x08); // flags3 diff --git a/src/game/WorldHandlers/GridMap.cpp b/src/game/WorldHandlers/GridMap.cpp index 6c20b40db..a0c474a66 100644 --- a/src/game/WorldHandlers/GridMap.cpp +++ b/src/game/WorldHandlers/GridMap.cpp @@ -209,7 +209,9 @@ bool GridMap::loadHeightData(FILE* in, uint32 offset, uint32 /*size*/) } } else + { m_gridGetHeight = &GridMap::getHeightFromFlat; + } return true; } @@ -601,7 +603,9 @@ GridMapLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 Re { area = GetAreaEntryByAreaID(area->zone); if (area) + { overrideLiquid = area->LiquidTypeOverride[liquidEntry->Type]; + } } if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(overrideLiquid)) @@ -780,7 +784,9 @@ GridMap* TerrainInfo::Load(const uint32 x, const uint32 y) // quick check if GridMap already loaded GridMap* pMap = m_GridMaps[x][y]; if (!pMap) + { pMap = LoadMapAndVMap(x, y); + } return pMap; } @@ -871,7 +877,9 @@ float TerrainInfo::GetHeightStatic(float x, float y, float z, bool useVmaps/*=tr // find raw .map surface under Z coordinates (or well-defined above) if (GridMap* gmap = const_cast(this)->GetGrid(x, y)) + { mapHeight = gmap->getHeight(x, y); + } if (useVmaps) { @@ -889,11 +897,15 @@ float TerrainInfo::GetHeightStatic(float x, float y, float z, bool useVmaps/*=tr // if not found in expected range, look for infinity range (case of far above floor, but below terrain-height) if (vmapHeight <= INVALID_HEIGHT) + { vmapHeight = vmgr->getHeight(GetMapId(), x, y, z2, 10000.0f); + } // still not found, look near terrain height if (vmapHeight <= INVALID_HEIGHT && mapHeight > INVALID_HEIGHT && z2 < mapHeight) + { vmapHeight = vmgr->getHeight(GetMapId(), x, y, mapHeight + 2.0f, DEFAULT_HEIGHT_SEARCH); + } } } @@ -911,10 +923,14 @@ float TerrainInfo::GetHeightStatic(float x, float y, float z, bool useVmaps/*=tr return vmapHeight; } else + { return mapHeight; // better use .map surface height + } } else + { return vmapHeight; // we have only vmapHeight (if have) + } } return mapHeight; @@ -947,7 +963,9 @@ inline bool IsOutdoorWMO(uint32 mogpFlags, int32 adtId, int32 rootId, int32 grou } if ((wmoEntry->Flags & 2) != 0) + { outdoor = false; + } } return outdoor; } @@ -1009,27 +1027,39 @@ uint16 TerrainInfo::GetAreaFlag(float x, float y, float z, bool* isOutdoors) con haveAreaInfo = true; wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId); if (wmoEntry) + { atEntry = GetAreaEntryByAreaID(wmoEntry->areaId); + } } uint16 areaflag; if (atEntry) + { areaflag = atEntry->exploreFlag; + } else { if (GridMap* gmap = const_cast(this)->GetGrid(x, y)) + { areaflag = gmap->getArea(x, y); + } // this used while not all *.map files generated (instances) else + { areaflag = GetAreaFlagByMapId(GetMapId()); + } } if (isOutdoors) { if (haveAreaInfo) + { *isOutdoors = IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry); + } else + { *isOutdoors = true; + } } return areaflag; } @@ -1080,11 +1110,15 @@ GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint { // hardcoded in client like this if (GetMapId() == 530 && liquid_type == 2) + { liquid_type = 15; + } uint32 liquidFlagType = 0; if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(liquid_type)) + { liquidFlagType = liq->Type; + } if (liquid_type && liquid_type < 21) { @@ -1095,7 +1129,9 @@ GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint { area = GetAreaEntryByAreaID(area->zone); if (area) + { overrideLiquid = area->LiquidTypeOverride[liquidFlagType]; + } } if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(overrideLiquid)) @@ -1143,7 +1179,9 @@ GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint { // hardcoded in client like this if (GetMapId() == 530 && map_data.entry == 2) + { map_data.entry = 15; + } *data = map_data; } return map_result; @@ -1218,7 +1256,9 @@ float TerrainInfo::GetWaterOrGroundLevel(float x, float y, float z, float* pGrou // we need ground level (including grid height version) for proper return water level in point float ground_z = GetHeightStatic(x, y, z, true, DEFAULT_WATER_SEARCH); if (pGround) + { *pGround = ground_z; + } GridMapLiquidData liquid_status; @@ -1238,7 +1278,9 @@ GridMap* TerrainInfo::GetGrid(const float x, const float y) // quick check if GridMap already loaded GridMap* pMap = m_GridMaps[gx][gy]; if (!pMap) + { pMap = LoadMapAndVMap(gx, gy); + } return pMap; } @@ -1302,7 +1344,9 @@ float TerrainInfo::GetWaterLevel(float x, float y, float z, float* pGround /*= N // we need ground level (including grid height version) for proper return water level in point float ground_z = GetHeightStatic(x, y, z, true, DEFAULT_WATER_SEARCH); if (pGround) + { *pGround = ground_z; + } GridMapLiquidData liquid_status; @@ -1348,7 +1392,9 @@ TerrainInfo* TerrainManager::LoadTerrain(const uint32 mapId) i_TerrainMap[mapId] = ptr; } else + { ptr = (*iter).second; + } return ptr; } diff --git a/src/game/WorldHandlers/GridNotifiers.cpp b/src/game/WorldHandlers/GridNotifiers.cpp index e4c530493..960ae0928 100644 --- a/src/game/WorldHandlers/GridNotifiers.cpp +++ b/src/game/WorldHandlers/GridNotifiers.cpp @@ -84,10 +84,14 @@ void VisibleNotifier::Notify() for (GuidSet::const_iterator iter = oor.begin(); iter != oor.end(); ++iter) { if (!iter->IsPlayer()) + { continue; + } if (Player* plr = ObjectAccessor::FindPlayer(*iter)) + { plr->UpdateVisibilityOf(plr->GetCamera().GetBody(), &player); + } } } @@ -98,7 +102,9 @@ void VisibleNotifier::Notify() { // target aura duration for caster show only if target exist at caster client if ((*vItr) != &player && (*vItr)->isType(TYPEMASK_UNIT)) + { player.SendAurasForTarget((Unit*)(*vItr)); + } } } @@ -111,10 +117,14 @@ void MessageDeliverer::Visit(CameraMapType& m) if (i_toSelf || owner != &i_player) { if (!i_player.InSamePhase(iter->getSource()->GetBody())) + { continue; + } if (WorldSession* session = owner->GetSession()) + { session->SendPacket(i_message); + } } } } @@ -126,10 +136,14 @@ void MessageDelivererExcept::Visit(CameraMapType& m) Player* owner = iter->getSource()->GetOwner(); if (!owner->InSamePhase(i_phaseMask) || owner == i_skipped_receiver) + { continue; + } if (WorldSession* session = owner->GetSession()) + { session->SendPacket(i_message); + } } } @@ -138,10 +152,14 @@ void ObjectMessageDeliverer::Visit(CameraMapType& m) for (CameraMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { if (!iter->getSource()->GetBody()->InSamePhase(i_phaseMask)) + { continue; + } if (WorldSession* session = iter->getSource()->GetOwner()->GetSession()) + { session->SendPacket(i_message); + } } } @@ -156,10 +174,14 @@ void MessageDistDeliverer::Visit(CameraMapType& m) (!i_dist || iter->getSource()->GetBody()->IsWithinDist(&i_player, i_dist))) { if (!i_player.InSamePhase(iter->getSource()->GetBody())) + { continue; + } if (WorldSession* session = owner->GetSession()) + { session->SendPacket(i_message); + } } } } @@ -171,10 +193,14 @@ void ObjectMessageDistDeliverer::Visit(CameraMapType& m) if (!i_dist || iter->getSource()->GetBody()->IsWithinDist(&i_object, i_dist)) { if (!i_object.InSamePhase(iter->getSource()->GetBody())) + { continue; + } if (WorldSession* session = iter->getSource()->GetOwner()->GetSession()) + { session->SendPacket(i_message); + } } } } @@ -269,7 +295,9 @@ void MaNGOS::CallOfHelpCreatureInRangeDo::operator()(Creature* u) } if (u->AI()) + { u->AI()->AttackStart(i_enemy); + } } bool MaNGOS::AnyAssistCreatureInRangeCheck::operator()(Creature* u) diff --git a/src/game/WorldHandlers/GridNotifiers.h b/src/game/WorldHandlers/GridNotifiers.h index e305ebc96..3ea66e114 100644 --- a/src/game/WorldHandlers/GridNotifiers.h +++ b/src/game/WorldHandlers/GridNotifiers.h @@ -156,7 +156,9 @@ namespace MaNGOS i_check = caster; Unit* owner = i_check->GetOwner(); if (owner) + { i_check = owner; + } } template inline void Visit(GridRefManager &) {} @@ -187,10 +189,14 @@ namespace MaNGOS for(CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (!i_check(itr->getSource())) + { continue; + } ..some code for update result and possible stop search } @@ -290,34 +296,44 @@ namespace MaNGOS { for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } void Visit(PlayerMapType& m) { for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } void Visit(CreatureMapType& m) { for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } void Visit(CorpseMapType& m) { for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } void Visit(DynamicObjectMapType& m) { for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } template void Visit(GridRefManager &) {} @@ -485,7 +501,9 @@ namespace MaNGOS { for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } template void Visit(GridRefManager &) {} @@ -536,7 +554,9 @@ namespace MaNGOS { for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) + { i_do(itr->getSource()); + } } template void Visit(GridRefManager &) {} @@ -558,7 +578,9 @@ namespace MaNGOS { Camera* camera = itr->getSource(); if (camera->GetBody()->InSamePhase(i_searcher) && camera->GetBody()->IsWithinDist(i_searcher, i_dist)) + { i_do(camera->GetOwner()); + } } } template void Visit(GridRefManager &) {} diff --git a/src/game/WorldHandlers/GridNotifiersImpl.h b/src/game/WorldHandlers/GridNotifiersImpl.h index 38c34390c..940fd4115 100644 --- a/src/game/WorldHandlers/GridNotifiersImpl.h +++ b/src/game/WorldHandlers/GridNotifiersImpl.h @@ -60,7 +60,9 @@ inline void PlayerCreatureRelocationWorker(Player* pl, Creature* c) if (!c->hasUnitState(UNIT_STAT_LOST_CONTROL)) { if (c->AI() && c->AI()->IsVisible(pl) && !c->IsInEvadeMode()) + { c->AI()->MoveInLineOfSight(pl); + } } } @@ -69,13 +71,17 @@ inline void CreatureCreatureRelocationWorker(Creature* c1, Creature* c2) if (!c1->hasUnitState(UNIT_STAT_LOST_CONTROL)) { if (c1->AI() && c1->AI()->IsVisible(c2) && !c1->IsInEvadeMode()) + { c1->AI()->MoveInLineOfSight(c2); + } } if (!c2->hasUnitState(UNIT_STAT_LOST_CONTROL)) { if (c2->AI() && c2->AI()->IsVisible(c1) && !c2->IsInEvadeMode()) + { c2->AI()->MoveInLineOfSight(c1); + } } } @@ -90,7 +96,9 @@ inline void MaNGOS::PlayerRelocationNotifier::Visit(CreatureMapType& m) { Creature* c = iter->getSource(); if (c->IsAlive()) + { PlayerCreatureRelocationWorker(&i_player, c); + } } } @@ -106,7 +114,9 @@ inline void MaNGOS::CreatureRelocationNotifier::Visit(PlayerMapType& m) { Player* player = iter->getSource(); if (player->IsAlive() && !player->IsTaxiFlying()) + { PlayerCreatureRelocationWorker(player, &i_creature); + } } } @@ -122,7 +132,9 @@ inline void MaNGOS::CreatureRelocationNotifier::Visit(CreatureMapType& m) { Creature* c = iter->getSource(); if (c != &i_creature && c->IsAlive()) + { CreatureCreatureRelocationWorker(c, &i_creature); + } } } @@ -257,7 +269,9 @@ void MaNGOS::WorldObjectSearcher::Visit(GameObjectMapType& m) for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -279,7 +293,9 @@ void MaNGOS::WorldObjectSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -301,7 +317,9 @@ void MaNGOS::WorldObjectSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -323,7 +341,9 @@ void MaNGOS::WorldObjectSearcher::Visit(CorpseMapType& m) for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -345,7 +365,9 @@ void MaNGOS::WorldObjectSearcher::Visit(DynamicObjectMapType& m) for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -361,7 +383,9 @@ void MaNGOS::WorldObjectLastSearcher::Visit(GameObjectMapType& m) for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -377,7 +401,9 @@ void MaNGOS::WorldObjectLastSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -393,7 +419,9 @@ void MaNGOS::WorldObjectLastSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -409,7 +437,9 @@ void MaNGOS::WorldObjectLastSearcher::Visit(CorpseMapType& m) for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -425,7 +455,9 @@ void MaNGOS::WorldObjectLastSearcher::Visit(DynamicObjectMapType& m) for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -442,7 +474,9 @@ void MaNGOS::WorldObjectListSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -451,7 +485,9 @@ void MaNGOS::WorldObjectListSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -460,7 +496,9 @@ void MaNGOS::WorldObjectListSearcher::Visit(CorpseMapType& m) for (CorpseMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -469,7 +507,9 @@ void MaNGOS::WorldObjectListSearcher::Visit(GameObjectMapType& m) for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -478,7 +518,9 @@ void MaNGOS::WorldObjectListSearcher::Visit(DynamicObjectMapType& m) for (DynamicObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } // Gameobject searchers @@ -495,7 +537,9 @@ void MaNGOS::GameObjectSearcher::Visit(GameObjectMapType& m) for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -511,10 +555,14 @@ void MaNGOS::GameObjectLastSearcher::Visit(GameObjectMapType& m) for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) + { i_object = itr->getSource(); + } } } @@ -524,7 +572,9 @@ void MaNGOS::GameObjectListSearcher::Visit(GameObjectMapType& m) for (GameObjectMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } // Unit searchers @@ -541,7 +591,9 @@ void MaNGOS::UnitSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -563,7 +615,9 @@ void MaNGOS::UnitSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -579,10 +633,14 @@ void MaNGOS::UnitLastSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) + { i_object = itr->getSource(); + } } } @@ -592,10 +650,14 @@ void MaNGOS::UnitLastSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) + { i_object = itr->getSource(); + } } } @@ -605,7 +667,9 @@ void MaNGOS::UnitListSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -614,7 +678,9 @@ void MaNGOS::UnitListSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } // Creature searchers @@ -631,7 +697,9 @@ void MaNGOS::CreatureSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -647,10 +715,14 @@ void MaNGOS::CreatureLastSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) + { i_object = itr->getSource(); + } } } @@ -660,7 +732,9 @@ void MaNGOS::CreatureListSearcher::Visit(CreatureMapType& m) for (CreatureMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -675,7 +749,9 @@ void MaNGOS::PlayerSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) { if (!itr->getSource()->InSamePhase(i_phaseMask)) + { continue; + } if (i_check(itr->getSource())) { @@ -691,7 +767,9 @@ void MaNGOS::PlayerListSearcher::Visit(PlayerMapType& m) for (PlayerMapType::iterator itr = m.begin(); itr != m.end(); ++itr) if (itr->getSource()->InSamePhase(i_phaseMask)) if (i_check(itr->getSource())) + { i_objects.push_back(itr->getSource()); + } } template @@ -705,7 +783,9 @@ void MaNGOS::LocalizedPacketDo::operator()(Player* p) if (i_data_cache.size() < cache_idx + 1 || !i_data_cache[cache_idx]) { if (i_data_cache.size() < cache_idx + 1) + { i_data_cache.resize(cache_idx + 1); + } data = new WorldPacket(); @@ -714,7 +794,9 @@ void MaNGOS::LocalizedPacketDo::operator()(Player* p) i_data_cache[cache_idx] = data; } else + { data = i_data_cache[cache_idx]; + } p->SendDirectMessage(data); } @@ -730,14 +812,18 @@ void MaNGOS::LocalizedPacketListDo::operator()(Player* p) if (i_data_cache.size() < cache_idx + 1 || i_data_cache[cache_idx].empty()) { if (i_data_cache.size() < cache_idx + 1) + { i_data_cache.resize(cache_idx + 1); + } data_list = &i_data_cache[cache_idx]; i_builder(*data_list, loc_idx); } else + { data_list = &i_data_cache[cache_idx]; + } for (size_t i = 0; i < data_list->size(); ++i) { diff --git a/src/game/WorldHandlers/Group.cpp b/src/game/WorldHandlers/Group.cpp index 590fdf8eb..3c67fdd1c 100644 --- a/src/game/WorldHandlers/Group.cpp +++ b/src/game/WorldHandlers/Group.cpp @@ -62,10 +62,14 @@ void Roll::CalculateCommonVoteMask(uint32 max_enchanting_skill) ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(itemid); if (itemProto->Flags2 & ITEM_FLAG2_NEED_ROLL_DISABLED) + { m_commonVoteMask = RollVoteMask(m_commonVoteMask & ~ROLL_VOTE_MASK_NEED); + } if (!itemProto->DisenchantID || uint32(itemProto->RequiredDisenchantSkill) > max_enchanting_skill) + { m_commonVoteMask = RollVoteMask(m_commonVoteMask & ~ROLL_VOTE_MASK_DISENCHANT); + } } RollVoteMask Roll::GetVoteMaskFor(Player* player) const @@ -100,11 +104,17 @@ Group::~Group() { DEBUG_LOG("Group::~Group: battleground group being deleted."); if (m_bgGroup->GetBgRaid(ALLIANCE) == this) + { m_bgGroup->SetBgRaid(ALLIANCE, NULL); + } else if (m_bgGroup->GetBgRaid(HORDE) == this) + { m_bgGroup->SetBgRaid(HORDE, NULL); + } else + { sLog.outError("Group::~Group: battleground group is not linked to the correct battleground."); + } } Rolls::iterator itr; while (!RollId.empty()) @@ -136,7 +146,9 @@ bool Group::Create(ObjectGuid guid, const char* name) m_groupType = isBGGroup() ? GROUPTYPE_BGRAID : GROUPTYPE_NORMAL; if (m_groupType & GROUPTYPE_RAID) + { _initRaidSubGroupsCounter(); + } m_lootMethod = GROUP_LOOT; m_lootThreshold = ITEM_QUALITY_UNCOMMON; @@ -180,7 +192,9 @@ bool Group::Create(ObjectGuid guid, const char* name) } if (!isBGGroup()) + { CharacterDatabase.CommitTransaction(); + } _updateLeaderFlag(); @@ -209,16 +223,22 @@ bool Group::LoadGroupFromDB(Field* fields) m_groupType = GroupType(fields[13].GetUInt8()); if (m_groupType & GROUPTYPE_RAID) + { _initRaidSubGroupsCounter(); + } uint32 diff = fields[14].GetUInt8(); if (diff >= MAX_DUNGEON_DIFFICULTY) + { diff = DUNGEON_DIFFICULTY_NORMAL; + } m_dungeonDifficulty = Difficulty(diff); uint32 r_diff = fields[15].GetUInt8(); if (r_diff >= MAX_RAID_DIFFICULTY) + { r_diff = RAID_DIFFICULTY_10MAN_NORMAL; + } m_raidDifficulty = Difficulty(r_diff); m_mainTankGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); @@ -270,7 +290,9 @@ void Group::ConvertToRaid() // update quest related GO states (quest activity dependent from raid membership) for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr) if (Player* player = sObjectMgr.GetPlayer(citr->guid)) + { player->UpdateForQuestWorldObjects(); + } } bool Group::AddInvite(Player* player) @@ -281,7 +303,9 @@ bool Group::AddInvite(Player* player) } Group* group = player->GetGroup(); if (group && group->isBGGroup()) + { group = player->GetOriginalGroup(); + } if (group) { return false; @@ -398,7 +422,9 @@ bool Group::AddMember(ObjectGuid guid, const char* name) // quest related GO state dependent from raid membership if (isRaidGroup()) + { player->UpdateForQuestWorldObjects(); + } } return true; @@ -415,7 +441,9 @@ uint32 Group::RemoveMember(ObjectGuid guid, uint8 method) { // quest related GO state dependent from raid membership if (isRaidGroup()) + { player->UpdateForQuestWorldObjects(); + } WorldPacket data; @@ -452,7 +480,9 @@ uint32 Group::RemoveMember(ObjectGuid guid, uint8 method) } // if group before remove <= 2 disband it else + { Disband(true); + } // Used by Eluna #ifdef ENABLE_ELUNA @@ -491,27 +521,39 @@ void Group::Disband(bool hideDestroy) { player = sObjectMgr.GetPlayer(citr->guid); if (!player) + { continue; + } // we cannot call _removeMember because it would invalidate member iterator // if we are removing player from battleground raid if (isBGGroup()) + { player->RemoveFromBattleGroundRaid(); + } else { // we can remove player who is in battleground from his original group if (player->GetOriginalGroup() == this) + { player->SetOriginalGroup(NULL); + } else + { player->SetGroup(NULL); + } } // quest related GO state dependent from raid membership if (isRaidGroup()) + { player->UpdateForQuestWorldObjects(); + } if (!player->GetSession()) + { continue; + } WorldPacket data; if (!hideDestroy) @@ -584,10 +626,14 @@ void Group::SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll& r) { Player* p = sObjectMgr.GetPlayer(itr->first); if (!p || !p->GetSession()) + { continue; + } if (itr->second == ROLL_NOT_VALID) + { continue; + } // dependent from player RollVoteMask mask = r.GetVoteMaskFor(p); @@ -614,10 +660,14 @@ void Group::SendLootRoll(ObjectGuid const& targetGuid, uint32 rollNumber, uint8 { Player* p = sObjectMgr.GetPlayer(itr->first); if (!p || !p->GetSession()) + { continue; + } if (itr->second != ROLL_NOT_VALID) + { p->GetSession()->SendPacket(&data); + } } } @@ -637,10 +687,14 @@ void Group::SendLootRollWon(ObjectGuid const& targetGuid, uint32 rollNumber, Rol { Player* p = sObjectMgr.GetPlayer(itr->first); if (!p || !p->GetSession()) + { continue; + } if (itr->second != ROLL_NOT_VALID) + { p->GetSession()->SendPacket(&data); + } } } @@ -657,10 +711,14 @@ void Group::SendLootAllPassed(Roll const& r) { Player* p = sObjectMgr.GetPlayer(itr->first); if (!p || !p->GetSession()) + { continue; + } if (itr->second != ROLL_NOT_VALID) + { p->GetSession()->SendPacket(&data); + } } } @@ -672,7 +730,9 @@ void Group::GroupLoot(WorldObject* pSource, Loot* loot) { LootItem& lootItem = loot->items[itemSlot]; if (lootItem.currency) + { continue; + } ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(lootItem.itemid); if (!itemProto) @@ -683,9 +743,13 @@ void Group::GroupLoot(WorldObject* pSource, Loot* loot) // roll for over-threshold item if it's one-player loot if (itemProto->Quality >= uint32(m_lootThreshold) && !lootItem.freeforall) + { StartLootRoll(pSource, GROUP_LOOT, loot, itemSlot, maxEnchantingSkill); + } else + { lootItem.is_underthreshold = 1; + } } } @@ -697,7 +761,9 @@ void Group::NeedBeforeGreed(WorldObject* pSource, Loot* loot) { LootItem& lootItem = loot->items[itemSlot]; if (lootItem.currency) + { continue; + } ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(lootItem.itemid); if (!itemProto) @@ -708,9 +774,13 @@ void Group::NeedBeforeGreed(WorldObject* pSource, Loot* loot) // only roll for one-player items, not for ones everyone can get if (itemProto->Quality >= uint32(m_lootThreshold) && !lootItem.freeforall) + { StartLootRoll(pSource, NEED_BEFORE_GREED, loot, itemSlot, maxEnchantingSkill); + } else + { lootItem.is_underthreshold = 1; + } } } @@ -719,13 +789,19 @@ void Group::MasterLoot(WorldObject* pSource, Loot* loot) for (LootItemList::iterator i = loot->items.begin(); i != loot->items.end(); ++i) { if (i->currency) + { continue; + } ItemPrototype const* item = ObjectMgr::GetItemPrototype(i->itemid); if (!item) + { continue; + } if (item->Quality < uint32(m_lootThreshold)) + { i->is_underthreshold = 1; + } } uint32 real_count = 0; @@ -737,7 +813,9 @@ void Group::MasterLoot(WorldObject* pSource, Loot* loot) { Player* looter = itr->getSource(); if (!looter->IsInWorld()) + { continue; + } if (looter->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) { @@ -752,7 +830,9 @@ void Group::MasterLoot(WorldObject* pSource, Loot* loot) { Player* looter = itr->getSource(); if (looter->IsWithinDist(pSource, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + { looter->GetSession()->SendPacket(&data); + } } } @@ -761,7 +841,9 @@ bool Group::CountRollVote(Player* player, ObjectGuid const& lootedTarget, uint32 Rolls::iterator rollI = RollId.begin(); for (; rollI != RollId.end(); ++rollI) if ((*rollI)->isValid() && (*rollI)->lootedTargetGUID == lootedTarget && (*rollI)->itemSlot == itemSlot) + { break; + } if (rollI == RollId.end()) { @@ -857,7 +939,9 @@ void Group::StartLootRoll(WorldObject* lootTarget, LootMethod method, Loot* loot { Player* playerToRoll = itr->getSource(); if (!playerToRoll || !playerToRoll->GetSession()) + { continue; + } if (lootItem.AllowedForPlayer(playerToRoll, lootTarget)) { @@ -875,7 +959,9 @@ void Group::StartLootRoll(WorldObject* lootTarget, LootMethod method, Loot* loot r->itemSlot = itemSlot; if (r->totalPlayersRolling == 1) // single looter + { r->playerVote.begin()->second = ROLL_NEED; + } else { // Only GO-group looting and NPC-group looting possible @@ -892,7 +978,9 @@ void Group::StartLootRoll(WorldObject* lootTarget, LootMethod method, Loot* loot RollId.push_back(r); } else // no looters?? + { delete r; + } } // called when roll timer expires @@ -928,7 +1016,9 @@ void Group::CountTheRoll(Rolls::iterator& rollI) for (Roll::PlayerVote::const_iterator itr = roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr) { if (itr->second != ROLL_NEED) + { continue; + } uint32 randomN = urand(1, 100); SendLootRoll(itr->first, randomN, ROLL_NEED, *roll); @@ -979,7 +1069,9 @@ void Group::CountTheRoll(Rolls::iterator& rollI) for (itr = roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr) { if (itr->second != ROLL_GREED && itr->second != ROLL_DISENCHANT) + { continue; + } uint32 randomN = urand(1, 100); SendLootRoll(itr->first, randomN, itr->second, *roll); @@ -1052,7 +1144,9 @@ void Group::SetTargetIcon(uint8 id, ObjectGuid whoGuid, ObjectGuid targetGuid) if (targetGuid) for (int i = 0; i < TARGET_ICON_COUNT; ++i) if (m_targetIcons[i] == targetGuid) + { SetTargetIcon(i, ObjectGuid(), ObjectGuid()); + } m_targetIcons[id] = targetGuid; @@ -1068,7 +1162,9 @@ static void GetDataForXPAtKill_helper(Player* player, Unit const* victim, uint32 { sum_level += player->getLevel(); if (!member_with_max_level || member_with_max_level->getLevel() < player->getLevel()) + { member_with_max_level = player; + } uint32 gray_level = MaNGOS::XP::GetGrayLevel(player->getLevel()); if (victim->getLevel() > gray_level && (!not_gray_member_with_max_level @@ -1082,14 +1178,20 @@ void Group::GetDataForXPAtKill(Unit const* victim, uint32& count, uint32& sum_le { Player* member = itr->getSource(); if (!member || !member->IsAlive()) // only for alive + { continue; + } // will proccesed later if (member == additional) + { continue; + } if (!member->IsAtGroupRewardDistance(victim)) // at req. distance + { continue; + } ++count; GetDataForXPAtKill_helper(member, victim, sum_level, member_with_max_level, not_gray_member_with_max_level); @@ -1118,7 +1220,9 @@ void Group::SendTargetIconList(WorldSession* session) for (int i = 0; i < TARGET_ICON_COUNT; ++i) { if (!m_targetIcons[i]) + { continue; + } data << uint8(i); data << m_targetIcons[i]; @@ -1133,7 +1237,9 @@ void Group::SendUpdate() { Player* player = sObjectMgr.GetPlayer(citr->guid); if (!player || !player->GetSession() || player->GetGroup() != this) + { continue; + } // guess size WorldPacket data(SMSG_GROUP_LIST, (1 + 1 + 1 + 1 + 8 + 4 + GetMembersCount() * 20)); data << uint8(m_groupType); // group type (flags in 3.3) @@ -1152,7 +1258,9 @@ void Group::SendUpdate() for (member_citerator citr2 = m_memberSlots.begin(); citr2 != m_memberSlots.end(); ++citr2) { if (citr->guid == citr2->guid) + { continue; + } Player* member = sObjectMgr.GetPlayer(citr2->guid); uint8 onlineState = (member) ? MEMBER_STATUS_ONLINE : MEMBER_STATUS_OFFLINE; onlineState = onlineState | ((isBGGroup()) ? MEMBER_STATUS_PVP : 0); @@ -1197,7 +1305,9 @@ void Group::UpdatePlayerOutOfRange(Player* pPlayer) for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) if (Player* player = itr->getSource()) if (player != pPlayer && !player->HaveAtClient(pPlayer)) + { player->GetSession()->SendPacket(&data); + } } void Group::BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group, ObjectGuid ignore) @@ -1206,10 +1316,14 @@ void Group::BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int { Player* pl = itr->getSource(); if (!pl || (ignore && pl->GetObjectGuid() == ignore) || (ignorePlayersInBGRaid && pl->GetGroup() != this)) + { continue; + } if (pl->GetSession() && (group == -1 || itr->getSubGroup() == group)) + { pl->GetSession()->SendPacket(packet); + } } } @@ -1220,7 +1334,9 @@ void Group::BroadcastReadyCheck(WorldPacket* packet) Player* pl = itr->getSource(); if (pl && pl->GetSession()) if (IsLeader(pl->GetObjectGuid()) || IsAssistant(pl->GetObjectGuid())) + { pl->GetSession()->SendPacket(packet); + } } } @@ -1280,9 +1396,13 @@ bool Group::_addMember(ObjectGuid guid, const char* name, bool isAssistant, uint uint32 lastMap = 0; if (player && player->IsInWorld()) + { lastMap = player->GetMapId(); + } else if (player && player->IsBeingTeleported()) + { lastMap = player->GetTeleportDest().mapid; + } MemberSlot member; member.guid = guid; @@ -1299,20 +1419,28 @@ bool Group::_addMember(ObjectGuid guid, const char* name, bool isAssistant, uint player->SetGroupInvite(NULL); // if player is in group and he is being added to BG raid group, then call SetBattleGroundRaid() if (player->GetGroup() && isBGGroup()) + { player->SetBattleGroundRaid(this, group); + } // if player is in bg raid and we are adding him to normal group, then call SetOriginalGroup() else if (player->GetGroup()) + { player->SetOriginalGroup(this, group); + } // if player is not in group, then call set group else + { player->SetGroup(this, group); + } if (player->IsInWorld()) { // if the same group invites the player back, cancel the homebind timer if (InstanceGroupBind* bind = GetBoundInstance(player->GetMapId(), player)) if (bind->state->GetInstanceId() == player->GetInstanceId()) + { player->m_InstanceValid = true; + } } } @@ -1341,14 +1469,20 @@ bool Group::_removeMember(ObjectGuid guid) { // if we are removing player from battleground raid if (isBGGroup()) + { player->RemoveFromBattleGroundRaid(); + } else { // we can remove player who is in battleground from his original group if (player->GetOriginalGroup() == this) + { player->SetOriginalGroup(NULL); + } else + { player->SetGroup(NULL); + } } } @@ -1370,7 +1504,9 @@ bool Group::_removeMember(ObjectGuid guid) if (m_leaderGuid == guid) // leader was removed { if (GetMembersCount() > 0) + { _setLeader(m_memberSlots.front().guid); + } return true; } @@ -1418,7 +1554,9 @@ void Group::_setLeader(ObjectGuid guid) m_boundInstances[i].erase(itr++); } else + { ++itr; + } } } } @@ -1454,25 +1592,37 @@ void Group::_removeRolls(ObjectGuid guid) } if (itr2->second == ROLL_GREED || itr2->second == ROLL_DISENCHANT) + { --roll->totalGreed; + } if (itr2->second == ROLL_NEED) + { --roll->totalNeed; + } if (itr2->second == ROLL_PASS) + { --roll->totalPass; + } if (itr2->second != ROLL_NOT_VALID) + { --roll->totalPlayersRolling; + } roll->playerVote.erase(itr2); if (!CountRollVote(guid, it, ROLL_NOT_EMITED_YET)) + { ++it; + } } } void Group::_updateLeaderFlag(const bool remove /*= false*/) { if (Player* player = sObjectMgr.GetPlayer(m_leaderGuid)) + { player->UpdateGroupLeaderFlag(remove); + } } bool Group::_setMembersGroup(ObjectGuid guid, uint8 group) @@ -1527,7 +1677,9 @@ bool Group::_setMainTank(ObjectGuid guid) } if (m_mainAssistantGuid == guid) + { _setMainAssistant(ObjectGuid()); + } } m_mainTankGuid = guid; @@ -1556,7 +1708,9 @@ bool Group::_setMainAssistant(ObjectGuid guid) } if (m_mainTankGuid == guid) + { _setMainTank(ObjectGuid()); + } } m_mainAssistantGuid = guid; @@ -1630,7 +1784,9 @@ void Group::ChangeMembersGroup(Player* player, uint8 group) if (_setMembersGroup(player->GetObjectGuid(), group)) { if (player->GetGroup() == this) + { player->GetGroupRef().setSubGroup(group); + } // if player is in BG raid, it is possible that he is also in normal raid - and that normal raid is stored in m_originalGroup reference else { @@ -1651,11 +1807,15 @@ uint32 Group::GetMaxSkillValueForGroup(SkillType skill) { Player* member = itr->getSource(); if (!member) + { continue; + } uint32 value = member->GetSkillValue(skill); if (maxvalue < value) + { maxvalue = value; + } } return maxvalue; @@ -1705,7 +1865,9 @@ void Group::UpdateLooterGuid(WorldObject* pSource, bool ifneed) SetLooterGuid(pl->GetObjectGuid()); SendUpdate(); if (refresh) // update loot for new looter + { pl->SendLoot(pSource->GetObjectGuid(), LOOT_CORPSE); + } return; } } @@ -1726,7 +1888,9 @@ void Group::UpdateLooterGuid(WorldObject* pSource, bool ifneed) SetLooterGuid(pl->GetObjectGuid()); SendUpdate(); if (refresh) // update loot for new looter + { pl->SendLoot(pSource->GetObjectGuid(), LOOT_CORPSE); + } return; } } @@ -1740,7 +1904,9 @@ GroupJoinBattlegroundResult Group::CanJoinBattleGroundQueue(BattleGround const* { BattlemasterListEntry const* bgEntry = sBattlemasterListStore.LookupEntry(bgOrTemplate->GetTypeID()); if (!bgEntry) + { return ERR_BATTLEGROUND_JOIN_FAILED; // shouldn't happen + } // check for min / max count uint32 memberscount = GetMembersCount(); @@ -1752,7 +1918,9 @@ GroupJoinBattlegroundResult Group::CanJoinBattleGroundQueue(BattleGround const* } if (memberscount > bgEntry->maxGroupSize) // no MinPlayerCount for battlegrounds + { return ERR_BATTLEGROUND_NONE; // ERR_GROUP_JOIN_BATTLEGROUND_TOO_MANY handled on client side + } // get a player as reference, to compare other players' stats to (arena team id, queue id based on level, etc.) Player* reference = GetFirstMember()->getSource(); @@ -1798,7 +1966,9 @@ GroupJoinBattlegroundResult Group::CanJoinBattleGroundQueue(BattleGround const* } // don't let join if someone from the group is already in that bg queue if (member->InBattleGroundQueueForBattleGroundQueueType(bgQueueTypeId)) + { return ERR_BATTLEGROUND_JOIN_FAILED; // not blizz-like + } // check for deserter debuff in case not arena queue if (bgOrTemplate->GetTypeID() != BATTLEGROUND_AA && !member->CanJoinToBattleground()) { @@ -1806,7 +1976,9 @@ GroupJoinBattlegroundResult Group::CanJoinBattleGroundQueue(BattleGround const* } // check if member can join any more battleground queues if (!member->HasFreeBattleGroundQueueId()) + { return ERR_BATTLEGROUND_TOO_MANY_QUEUES; // not blizz-like + } } return ERR_BATTLEGROUND_NONE; } @@ -1815,13 +1987,17 @@ void Group::SetDungeonDifficulty(Difficulty difficulty) { m_dungeonDifficulty = difficulty; if (!isBGGroup()) + { CharacterDatabase.PExecute("UPDATE `groups` SET `difficulty` = %u WHERE `groupId`='%u'", m_dungeonDifficulty, m_Id); + } for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) { Player* player = itr->getSource(); if (!player->GetSession() || player->getLevel() < LEVELREQUIREMENT_HEROIC) + { continue; + } player->SetDungeonDifficulty(difficulty); player->SendDungeonDifficulty(true); } @@ -1831,13 +2007,17 @@ void Group::SetRaidDifficulty(Difficulty difficulty) { m_raidDifficulty = difficulty; if (!isBGGroup()) + { CharacterDatabase.PExecute("UPDATE `groups` SET `raiddifficulty` = %u WHERE `groupId` = '%u'", m_raidDifficulty, m_Id); + } for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) { Player* player = itr->getSource(); if (!player->GetSession() || player->getLevel() < LEVELREQUIREMENT_HEROIC) + { continue; + } player->SetRaidDifficulty(difficulty); player->SendRaidDifficulty(true); } @@ -1889,7 +2069,9 @@ void Group::ResetInstances(InstanceResetMethod method, bool isRaid, Player* Send for (member_citerator itr = m_memberSlots.begin(); itr != m_memberSlots.end(); ++itr) { if (!ObjectAccessor::FindPlayer(itr->guid)) + { mapsWithOfflinePlayer.insert(itr->lastMap); // add last map from offline player + } } } @@ -1916,19 +2098,27 @@ void Group::ResetInstances(InstanceResetMethod method, bool isRaid, Player* Send bool isEmpty = true; // check if there are offline members on the map if (method != INSTANCE_RESET_GROUP_DISBAND && mapsWithOfflinePlayer.find(state->GetMapId()) != mapsWithOfflinePlayer.end()) + { isEmpty = false; + } // if the map is loaded, reset it if can if (isEmpty && entry->IsDungeon() && !(method == INSTANCE_RESET_GROUP_DISBAND && !state->CanReset())) if (Map* map = sMapMgr.FindMap(state->GetMapId(), state->GetInstanceId())) + { isEmpty = ((DungeonMap*)map)->Reset(method); + } if (SendMsgTo) { if (isEmpty) + { SendMsgTo->SendResetInstanceSuccess(state->GetMapId()); + } else + { SendMsgTo->SendResetInstanceFailed(0, state->GetMapId()); + } } // TODO - Adapt here when clear how difficulty changes must be handled @@ -1936,7 +2126,9 @@ void Group::ResetInstances(InstanceResetMethod method, bool isRaid, Player* Send { // do not reset the instance, just unbind if others are permanently bound to it if (state->CanReset()) + { state->DeleteFromDB(); + } else { CharacterDatabase.PExecute("DELETE FROM `group_instance` WHERE `instance` = '%u'", state->GetInstanceId()); @@ -1949,7 +2141,9 @@ void Group::ResetInstances(InstanceResetMethod method, bool isRaid, Player* Send state->RemoveGroup(this); } else + { ++itr; + } } } @@ -1966,7 +2160,9 @@ InstanceGroupBind* Group::GetBoundInstance(uint32 mapid, Player* player) // some instances only have one difficulty MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapid, difficulty); if (!mapDiff) + { difficulty = DUNGEON_DIFFICULTY_NORMAL; + } BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid); if (itr != m_boundInstances[difficulty].end()) @@ -2019,7 +2215,9 @@ InstanceGroupBind* Group::BindToInstance(DungeonPersistentState* state, bool per if (bind.state != state) { if (bind.state) + { bind.state->RemoveGroup(this); + } state->AddGroup(this); } @@ -2062,7 +2260,9 @@ void Group::_homebindIfInstance(Player* player) // unless the player is permanently saved to the instance InstancePlayerBind* playerBind = player->GetBoundInstance(map->GetId(), map->GetDifficulty()); if (!playerBind || !playerBind->perm) + { player->m_InstanceValid = false; + } } } } @@ -2071,7 +2271,9 @@ static void RewardGroupAtKill_helper(Player* pGroupGuy, Unit* pVictim, uint32 co { // honor can be in PvP and !PvP (racial leader) cases (for alive) if (pGroupGuy->IsAlive()) + { pGroupGuy->RewardHonor(pVictim, count); + } // xp and reputation only in !PvP case if (!PvP) @@ -2090,7 +2292,9 @@ static void RewardGroupAtKill_helper(Player* pGroupGuy, Unit* pVictim, uint32 co pGroupGuy->GiveXP(itr_xp, pVictim); if (Pet* pet = pGroupGuy->GetPet()) + { pet->GivePetXP(itr_xp / 2); + } } // quest objectives updated only for alive group member or dead but with not released body @@ -2099,7 +2303,9 @@ static void RewardGroupAtKill_helper(Player* pGroupGuy, Unit* pVictim, uint32 co // normal creature (not pet/etc) can be only in !PvP case if (pVictim->GetTypeId() == TYPEID_UNIT) if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry())) + { pGroupGuy->KilledMonster(normalInfo, pVictim->GetObjectGuid()); + } } } } @@ -2139,14 +2345,20 @@ void Group::RewardGroupAtKill(Unit* pVictim, Player* player_tap) { Player* pGroupGuy = itr->getSource(); if (!pGroupGuy) + { continue; + } // will proccessed later if (pGroupGuy == player_tap) + { continue; + } if (!pGroupGuy->IsAtGroupRewardDistance(pVictim)) + { continue; // member (alive or dead) or his corpse at req. distance + } RewardGroupAtKill_helper(pGroupGuy, pVictim, count, PvP, group_rate, sum_level, is_dungeon, not_gray_member_with_max_level, member_with_max_level, xp); } @@ -2155,7 +2367,9 @@ void Group::RewardGroupAtKill(Unit* pVictim, Player* player_tap) { // member (alive or dead) or his corpse at req. distance if (player_tap->IsAtGroupRewardDistance(pVictim)) + { RewardGroupAtKill_helper(player_tap, pVictim, count, PvP, group_rate, sum_level, is_dungeon, not_gray_member_with_max_level, member_with_max_level, xp); + } } } } diff --git a/src/game/WorldHandlers/Group.h b/src/game/WorldHandlers/Group.h index 8077cfb5a..d94e8d0ab 100644 --- a/src/game/WorldHandlers/Group.h +++ b/src/game/WorldHandlers/Group.h @@ -341,7 +341,9 @@ class Group return; } if (_setAssistantFlag(guid, state)) + { SendUpdate(); + } } void SetMainTank(ObjectGuid guid) { @@ -351,7 +353,9 @@ class Group } if (_setMainTank(guid)) + { SendUpdate(); + } } void SetMainAssistant(ObjectGuid guid) { @@ -361,7 +365,9 @@ class Group } if (_setMainAssistant(guid)) + { SendUpdate(); + } } void SetTargetIcon(uint8 id, ObjectGuid whoGuid, ObjectGuid targetGuid); @@ -432,7 +438,9 @@ class Group { // Sub group counters initialization if (!m_subGroupsCounts) + { m_subGroupsCounts = new uint8[MAX_RAID_SUBGROUPS]; + } memset((void*)m_subGroupsCounts, 0, MAX_RAID_SUBGROUPS * sizeof(uint8)); @@ -467,13 +475,17 @@ class Group void SubGroupCounterIncrease(uint8 subgroup) { if (m_subGroupsCounts) + { ++m_subGroupsCounts[subgroup]; + } } void SubGroupCounterDecrease(uint8 subgroup) { if (m_subGroupsCounts) + { --m_subGroupsCounts[subgroup]; + } } uint32 GetMaxSkillValueForGroup(SkillType skill); @@ -485,11 +497,17 @@ class Group { uint8 flags = 0; if (slot.assistant) + { flags |= GROUP_ASSISTANT; + } if (slot.guid == m_mainAssistantGuid) + { flags |= GROUP_MAIN_ASSISTANT; + } if (slot.guid == m_mainTankGuid) + { flags |= GROUP_MAIN_TANK; + } return GroupFlagMask(flags); } diff --git a/src/game/WorldHandlers/GroupHandler.cpp b/src/game/WorldHandlers/GroupHandler.cpp index 3371f0747..dfda09fd7 100644 --- a/src/game/WorldHandlers/GroupHandler.cpp +++ b/src/game/WorldHandlers/GroupHandler.cpp @@ -149,7 +149,9 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recv_data) Group* group = GetPlayer()->GetGroup(); if (group && group->isBGGroup()) + { group = GetPlayer()->GetOriginalGroup(); + } if (group && group->isRaidGroup() && !player->GetAllowLowLevelRaid() && (player->getLevel() < sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_FOR_RAID))) { @@ -166,7 +168,9 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recv_data) Group* group2 = player->GetGroup(); if (group2 && group2->isBGGroup()) + { group2 = player->GetOriginalGroup(); + } // player already in another group if (group2) @@ -231,7 +235,9 @@ void WorldSession::HandleGroupInviteResponseOpcode(WorldPacket& recv_data) bool unk = recv_data.ReadBit(); bool accepted = recv_data.ReadBit(); if (unk) + { recv_data.read_skip(); + } Group* group = GetPlayer()->GetGroupInvite(); if (!group) @@ -267,9 +273,13 @@ void WorldSession::HandleGroupInviteResponseOpcode(WorldPacket& recv_data) if (!group->IsCreated()) { if (leader) + { group->RemoveInvite(leader); + } if (group->Create(group->GetLeaderGuid(), group->GetLeaderName())) + { sObjectMgr.AddGroup(group); + } else { return; @@ -549,9 +559,13 @@ void WorldSession::HandleRandomRollOpcode(WorldPacket& recv_data) data << uint32(roll); data << GetPlayer()->GetObjectGuid(); if (GetPlayer()->GetGroup()) + { GetPlayer()->GetGroup()->BroadcastPacket(&data, false); + } else + { SendPacket(&data); + } } void WorldSession::HandleRaidTargetUpdateOpcode(WorldPacket& recv_data) @@ -644,11 +658,15 @@ void WorldSession::HandleGroupChangeSubGroupOpcode(WorldPacket& recv_data) // everything is fine, do it if (Player* player = sObjectMgr.GetPlayer(name.c_str())) + { group->ChangeMembersGroup(player, groupNr); + } else { if (ObjectGuid guid = sObjectMgr.GetPlayerGuidByName(name.c_str())) + { group->ChangeMembersGroup(guid, groupNr); + } } } @@ -712,9 +730,13 @@ void WorldSession::HandlePartyAssignmentOpcode(WorldPacket& recv_data) else { if (group->GetMainTankGuid() == guid) + { group->SetMainTank(ObjectGuid()); + } if (group->GetMainAssistantGuid() == guid) + { group->SetMainAssistant(ObjectGuid()); + } } } @@ -777,15 +799,21 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke uint32 mask = player->GetGroupUpdateFlag(); if (mask & GROUP_UPDATE_FLAG_POWER_TYPE) // if update power type, update current/max power also + { mask |= (GROUP_UPDATE_FLAG_CUR_POWER | GROUP_UPDATE_FLAG_MAX_POWER); + } if (mask & GROUP_UPDATE_FLAG_PET_POWER_TYPE) // same for pets + { mask |= (GROUP_UPDATE_FLAG_PET_CUR_POWER | GROUP_UPDATE_FLAG_PET_MAX_POWER); + } uint32 byteCount = 0; for (int i = 1; i < GROUP_UPDATE_FLAGS_COUNT; ++i) if (mask & (1 << i)) + { byteCount += GroupUpdateLength[i]; + } data->Initialize(SMSG_PARTY_MEMBER_STATS, 8 + 4 + byteCount); *data << player->GetPackGUID(); @@ -794,38 +822,60 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke if (mask & GROUP_UPDATE_FLAG_STATUS) { if (player->IsPvP()) + { *data << uint16(MEMBER_STATUS_ONLINE | MEMBER_STATUS_PVP); + } else + { *data << uint16(MEMBER_STATUS_ONLINE); + } } if (mask & GROUP_UPDATE_FLAG_CUR_HP) + { *data << uint32(player->GetHealth()); + } if (mask & GROUP_UPDATE_FLAG_MAX_HP) + { *data << uint32(player->GetMaxHealth()); + } Powers powerType = player->GetPowerType(); if (mask & GROUP_UPDATE_FLAG_POWER_TYPE) + { *data << uint8(powerType); + } if (mask & GROUP_UPDATE_FLAG_CUR_POWER) + { *data << uint16(player->GetPower(powerType)); + } if (mask & GROUP_UPDATE_FLAG_MAX_POWER) + { *data << uint16(player->GetMaxPower(powerType)); + } if (mask & GROUP_UPDATE_FLAG_LEVEL) + { *data << uint16(player->getLevel()); + } if (mask & GROUP_UPDATE_FLAG_ZONE) + { *data << uint16(player->GetZoneId()); + } if (mask & GROUP_UPDATE_FLAG_UNK) + { *data << uint16(0); + } if (mask & GROUP_UPDATE_FLAG_POSITION) + { *data << uint16(player->GetPositionX()) << uint16(player->GetPositionY()) << uint16(player->GetPositionZ()); + } if (mask & GROUP_UPDATE_FLAG_AURAS) { @@ -868,62 +918,92 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke Pet* pet = player->GetPet(); if (mask & GROUP_UPDATE_FLAG_PET_GUID) + { *data << (pet ? pet->GetObjectGuid() : ObjectGuid()); + } if (mask & GROUP_UPDATE_FLAG_PET_NAME) { if (pet) + { *data << pet->GetName(); + } else + { *data << uint8(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_MODEL_ID) { if (pet) + { *data << uint16(pet->GetDisplayId()); + } else + { *data << uint16(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_CUR_HP) { if (pet) + { *data << uint32(pet->GetHealth()); + } else + { *data << uint32(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_MAX_HP) { if (pet) + { *data << uint32(pet->GetMaxHealth()); + } else + { *data << uint32(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_POWER_TYPE) { if (pet) + { *data << uint8(pet->GetPowerType()); + } else + { *data << uint8(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_CUR_POWER) { if (pet) + { *data << uint16(pet->GetPower(pet->GetPowerType())); + } else + { *data << uint16(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_MAX_POWER) { if (pet) + { *data << uint16(pet->GetMaxPower(pet->GetPowerType())); + } else + { *data << uint16(0); + } } if (mask & GROUP_UPDATE_FLAG_PET_AURAS) @@ -975,7 +1055,9 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke } if (mask & GROUP_UPDATE_FLAG_VEHICLE_SEAT) + { *data << int32(0); + } if (mask & GROUP_UPDATE_FLAG_PHASE) { @@ -987,9 +1069,13 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke if (mask & GROUP_UPDATE_FLAG_VEHICLE_SEAT) { if (player->GetTransportInfo()) + { *data << uint32(((Unit*)player->GetTransportInfo()->GetTransport())->GetVehicleInfo()->GetVehicleEntry()->m_seatID[player->GetTransportInfo()->GetTransportSeat()]); + } else + { *data << uint32(0); + } } } @@ -1025,7 +1111,9 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket& recv_data) GROUP_UPDATE_FLAG_PHASE; if (pet) + { mask1 = 0x7FEFFEFF; // full mask & ~(GROUP_UPDATE_FLAG_VEHICLE_SEAT | GROUP_UPDATE_FLAG_UNK) + } Powers powerType = player->GetPowerType(); data << uint32(mask1); // group update mask @@ -1151,7 +1239,9 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket& recv_data) } if (player->GetTransportInfo()) // GROUP_UPDATE_FLAG_VEHICLE_SEAT + { data << uint32(((Unit*)player->GetTransportInfo()->GetTransport())->GetVehicleInfo()->GetVehicleEntry()->m_seatID[player->GetTransportInfo()->GetTransportSeat()]); + } data << uint32(8); // GROUP_UPDATE_FLAG_PHASE data << uint32(0); // GROUP_UPDATE_FLAG_PHASE @@ -1182,7 +1272,9 @@ void WorldSession::HandleOptOutOfLootOpcode(WorldPacket& recv_data) } if (unkn != 0) + { sLog.outError("CMSG_GROUP_PASS_ON_LOOT: activation not implemented!"); + } } void WorldSession::HandleSetAllowLowLevelRaidOpcode(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/GuildHandler.cpp b/src/game/WorldHandlers/GuildHandler.cpp index d36d8479d..3b63c93d8 100644 --- a/src/game/WorldHandlers/GuildHandler.cpp +++ b/src/game/WorldHandlers/GuildHandler.cpp @@ -100,7 +100,9 @@ void WorldSession::HandleGuildInviteOpcode(WorldPacket& recvPacket) Invitedname = recvPacket.ReadString(recvPacket.ReadBits(7)); if (normalizePlayerName(Invitedname)) + { player = ObjectAccessor::FindPlayerByName(Invitedname.c_str()); + } if (!player) { @@ -305,7 +307,9 @@ void WorldSession::HandleGuildDeclineOpcode(WorldPacket& recvPacket) DEBUG_LOG("WORLD: Received opcode %s", LookupOpcodeName(recvPacket.GetOpcode())); if (Player* inviter = sObjectMgr.GetPlayer(GetPlayer()->GetGuildInviterGuid())) + { inviter->SendGuildDeclined(GetPlayer()->GetName(), recvPacket.GetOpcode() == CMSG_GUILD_AUTO_DECLINE); + } GetPlayer()->SetGuildIdInvited(0); GetPlayer()->SetInGuild(0); @@ -363,7 +367,9 @@ void WorldSession::HandleGuildRosterOpcode(WorldPacket& recvPacket) guid1.GetString().c_str(), guid1.GetRawValue(), guid2.GetString().c_str(), guid2.GetRawValue()); if (Guild* guild = sGuildMgr.GetGuildById(_player->GetGuildId())) + { guild->Roster(this); + } } void WorldSession::HandleGuildPromoteOpcode(WorldPacket& recvPacket) @@ -808,9 +814,13 @@ void WorldSession::HandleGuildSetNoteOpcode(WorldPacket& recvPacket) } if (officer) + { slot->SetOFFNOTE(note); + } else + { slot->SetPNOTE(note); + } guild->Roster(this); } @@ -865,7 +875,9 @@ void WorldSession::HandleGuildRankOpcode(WorldPacket& recvPacket) guild->SetRankName(rankId, rankname); if (rankId == GR_GUILDMASTER) // prevent loss leader rights + { rights = GR_RIGHT_ALL; + } guild->SetRankRights(rankId, rights); @@ -1030,7 +1042,9 @@ void WorldSession::HandleGuildEventLogQueryOpcode(WorldPacket& /* recvPacket */) if (uint32 GuildId = GetPlayer()->GetGuildId()) if (Guild* pGuild = sGuildMgr.GetGuildById(GuildId)) + { pGuild->DisplayGuildEventLog(this); + } } /****** GUILD BANK *******/ @@ -1041,7 +1055,9 @@ void WorldSession::HandleGuildBankMoneyWithdrawn(WorldPacket& /* recv_data */) if (uint32 GuildId = GetPlayer()->GetGuildId()) if (Guild* pGuild = sGuildMgr.GetGuildById(GuildId)) + { pGuild->SendMoneyInfo(this, GetPlayer()->GetGUIDLow()); + } } void WorldSession::HandleGuildPermissions(WorldPacket& /* recv_data */) @@ -1356,9 +1372,13 @@ void WorldSession::HandleGuildBankSwapItems(WorldPacket& recv_data) // BankToChar swap or char to bank remaining if (ToChar) // Bank -> Char cases + { pGuild->MoveFromBankToChar(_player, BankTab, BankTabSlot, PlayerBag, PlayerSlot, SplitedAmount); + } else // Char -> Bank cases + { pGuild->MoveFromCharToBank(_player, PlayerBag, PlayerSlot, BankTab, BankTabSlot, SplitedAmount); + } } void WorldSession::HandleGuildBankBuyTab(WorldPacket& recv_data) @@ -1571,7 +1591,9 @@ void WorldSession::HandleGuildQueryRanksOpcode(WorldPacket& recv_data) recv_data.ReadGuidMask<2, 3, 0, 6, 4, 7, 5, 1>(guildGuid); recv_data.ReadGuidBytes<3, 4, 5, 7, 1, 0, 6, 2>(guildGuid); if (Guild* guild = sGuildMgr.GetGuildByGuid(guildGuid)) + { guild->QueryRanks(this); + } } void WorldSession::HandleGuildAutoDeclineToggleOpcode(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/ItemHandler.cpp b/src/game/WorldHandlers/ItemHandler.cpp index b110cf130..e0b26cec4 100644 --- a/src/game/WorldHandlers/ItemHandler.cpp +++ b/src/game/WorldHandlers/ItemHandler.cpp @@ -51,7 +51,9 @@ void WorldSession::HandleSplitItemOpcode(WorldPacket& recv_data) } if (count == 0) + { return; // check count - if zero it's fake packet + } if (!_player->IsValidPos(srcbag, srcslot, true)) { @@ -165,7 +167,9 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recv_data) Item* pSrcItem = _player->GetItemByPos(srcbag, srcslot); if (!pSrcItem) + { return; // only at cheat + } uint16 dest; InventoryResult msg = _player->CanEquipItem(NULL_SLOT, dest, pSrcItem, !pSrcItem->IsBag()); @@ -207,23 +211,33 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recv_data) { msg = _player->CanStoreItem(srcbag, srcslot, sSrc, pDstItem, true); if (msg != EQUIP_ERR_OK) + { msg = _player->CanStoreItem(srcbag, NULL_SLOT, sSrc, pDstItem, true); + } if (msg != EQUIP_ERR_OK) + { msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sSrc, pDstItem, true); + } } else if (_player->IsBankPos(src)) { msg = _player->CanBankItem(srcbag, srcslot, sSrc, pDstItem, true); if (msg != EQUIP_ERR_OK) + { msg = _player->CanBankItem(srcbag, NULL_SLOT, sSrc, pDstItem, true); + } if (msg != EQUIP_ERR_OK) + { msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, sSrc, pDstItem, true); + } } else if (_player->IsEquipmentPos(src)) { msg = _player->CanEquipItem(srcslot, eSrc, pDstItem, true); if (msg == EQUIP_ERR_OK) + { msg = _player->CanUnequipItem(eSrc, true); + } } if (msg != EQUIP_ERR_OK) @@ -241,11 +255,17 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recv_data) // add to src if (_player->IsInventoryPos(src)) + { _player->StoreItem(sSrc, pDstItem, true); + } else if (_player->IsBankPos(src)) + { _player->BankItem(sSrc, pDstItem, true); + } else if (_player->IsEquipmentPos(src)) + { _player->EquipItem(eSrc, pDstItem, true); + } _player->AutoUnequipOffhandIfNeed(); } @@ -294,7 +314,9 @@ void WorldSession::HandleDestroyItemOpcode(WorldPacket& recv_data) _player->DestroyItemCount(pItem, i_count, true); } else + { _player->DestroyItem(bag, slot, true); + } } void WorldSession::HandleReadItemOpcode(WorldPacket& recv_data) @@ -327,7 +349,9 @@ void WorldSession::HandleReadItemOpcode(WorldPacket& recv_data) SendPacket(&data); } else + { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + } } void WorldSession::HandlePageQuerySkippedOpcode(WorldPacket& recv_data) @@ -424,12 +448,16 @@ void WorldSession::HandleSellItemOpcode(WorldPacket& recv_data) pItem->SetCount(pItem->GetCount() - count); _player->ItemRemovedQuestCheck(pItem->GetEntry(), count); if (_player->IsInWorld()) + { pItem->SendCreateUpdateToPlayer(_player); + } pItem->SetState(ITEM_CHANGED, _player); _player->AddItemToBuyBackSlot(pNewItem); if (_player->IsInWorld()) + { pNewItem->SendCreateUpdateToPlayer(_player); + } } else { @@ -445,7 +473,9 @@ void WorldSession::HandleSellItemOpcode(WorldPacket& recv_data) _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS, money); } else + { _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); + } return; } } @@ -508,11 +538,15 @@ void WorldSession::HandleBuybackItem(WorldPacket& recvData) _player->StoreItem(dest, pItem, true); } else + { _player->SendEquipError(msg, pItem, NULL); + } return; } else + { _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, 0, 0); + } } void WorldSession::HandleBuyItemOpcode(WorldPacket& recvData) @@ -564,9 +598,13 @@ void WorldSession::HandleBuyItemOpcode(WorldPacket& recvData) // client side expected counting from 1, and we send to client vendorslot+1 already if (slot > 0) + { --slot; + } else + { return; // cheating + } switch (type) { @@ -578,7 +616,9 @@ void WorldSession::HandleBuyItemOpcode(WorldPacket& recvData) // find bag slot by bag guid if (bagGuid == _player->GetObjectGuid()) + { bag = INVENTORY_SLOT_BAG_0; + } else { for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) @@ -678,26 +718,38 @@ void WorldSession::SendListInventory(ObjectGuid vendorguid) { ItemPrototype const * pProto = ObjectMgr::GetItemPrototype(crItem->item); if (!pProto) + { continue; + } if (!_player->isGameMaster()) { // class wrong item skip only for bindable case if ((pProto->AllowableClass & _player->getClassMask()) == 0 && pProto->Bonding == BIND_WHEN_PICKED_UP) + { continue; + } // race wrong item skip always if ((pProto->Flags2 & ITEM_FLAG2_HORDE_ONLY) && _player->GetTeam() != HORDE) + { continue; + } if ((pProto->Flags2 & ITEM_FLAG2_ALLIANCE_ONLY) && _player->GetTeam() != ALLIANCE) + { continue; + } if ((pProto->AllowableRace & _player->getRaceMask()) == 0) + { continue; + } if (crItem->conditionId && !sObjectMgr.IsPlayerMeetToCondition(crItem->conditionId, _player, pCreature->GetMap(), pCreature, CONDITION_FROM_VENDOR)) + { continue; + } } // possible item coverting for BoA case @@ -708,13 +760,17 @@ void WorldSession::SendListInventory(ObjectGuid vendorguid) { // checked at convert data loading as existed if (uint32 newItemId = sObjectMgr.GetItemConvert(crItem->item, _player->getRaceMask())) + { pProto = ObjectMgr::GetItemPrototype(newItemId); + } } } ++count; if (count >= MAX_VENDOR_ITEMS) + { break; + } // reputation discount maxDurability = pProto->MaxDurability; @@ -728,14 +784,20 @@ void WorldSession::SendListInventory(ObjectGuid vendorguid) { CurrencyTypesEntry const * pCurrency = sCurrencyTypesStore.LookupEntry(crItem->item); if (!pCurrency) + { continue; + } if (pCurrency->Category == CURRENCY_CATEGORY_META) + { continue; + } ++count; if (count >= MAX_VENDOR_ITEMS) + { break; + } maxDurability = 0; price = 0; @@ -744,7 +806,9 @@ void WorldSession::SendListInventory(ObjectGuid vendorguid) buyCount = crItem->maxcount; } else + { continue; + } bitFlags.push_back(crItem->ExtendedCost == 0); bitFlags.push_back(true); // unk @@ -753,7 +817,9 @@ void WorldSession::SendListInventory(ObjectGuid vendorguid) buffer << uint32(maxDurability); if (crItem->ExtendedCost) + { buffer << uint32(crItem->ExtendedCost); + } buffer << uint32(crItem->item); buffer << uint32(crItem->type); @@ -1010,9 +1076,13 @@ void WorldSession::HandleSetAmmoOpcode(WorldPacket& recv_data) recv_data >> item; if (!item) + { GetPlayer()->RemoveAmmo(); + } else + { GetPlayer()->SetAmmo(item); + } } void WorldSession::SendEnchantmentLog(ObjectGuid targetGuid, ObjectGuid casterGuid, uint32 itemId, uint32 enchantId) @@ -1165,7 +1235,9 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) { ObjectGuid gemGuid = gemGuids[i]; if (!gemGuid) + { continue; + } if (!gemGuid.IsItem()) { @@ -1202,12 +1274,16 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) GemPropertiesEntry const* GemProps[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) // get geminfo from dbc storage + { GemProps[i] = (Gems[i]) ? sGemPropertiesStore.LookupEntry(Gems[i]->GetProto()->GemProperties) : NULL; + } for (int i = 0; i < MAX_GEM_SOCKETS; ++i) // check for hack maybe { if (!GemProps[i]) + { continue; + } // tried to put gem in socket where no socket exists (take care about prismatic sockets) if (!itemProto->Socket[i].Color) @@ -1252,7 +1328,9 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) for (int i = 0; i < MAX_GEM_SOCKETS; ++i) { if (!Gems[i]) + { continue; + } // continue check for case when attempt add 2 similar unique equipped gems in one item. ItemPrototype const* iGemProto = Gems[i]->GetProto(); @@ -1263,7 +1341,9 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) for (int j = 0; j < MAX_GEM_SOCKETS; ++j) { if (i == j) // skip self + { continue; + } if (Gems[j]) { @@ -1305,12 +1385,16 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(OldEnchants[j])) if (ItemPrototype const* jProto = ObjectMgr::GetItemPrototype(enchantEntry->GemID)) if (iGemProto->ItemLimitCategory == jProto->ItemLimitCategory) + { --limit_newcount; + } } // new gem if (iGemProto->ItemLimitCategory == Gems[j]->GetProto()->ItemLimitCategory) + { ++limit_newcount; + } } // existing gem else if (OldEnchants[j]) @@ -1318,7 +1402,9 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(OldEnchants[j])) if (ItemPrototype const* jProto = ObjectMgr::GetItemPrototype(enchantEntry->GemID)) if (iGemProto->ItemLimitCategory == jProto->ItemLimitCategory) + { ++limit_newcount; + } } } @@ -1359,7 +1445,9 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) uint32 count = 1; itemTarget->SetEnchantment(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i), GemEnchants[i], 0, 0, _player->GetObjectGuid()); if (Item* guidItem = gemGuids[i] ? _player->GetItemByGuid(gemGuids[i]) : NULL) + { _player->DestroyItemCount(guidItem, count, true); + } } } @@ -1603,15 +1691,21 @@ void WorldSession::SendItemSparseDb2Reply(uint32 entry) std::string name = proto->Name1; buff << uint16(name.length()); if (name.length()) + { buff << name; + } for (uint32 i = 0; i < 3; ++i) // other 3 names + { buff << uint16(0); + } std::string desc = proto->Description; buff << uint16(desc.length()); if (desc.length()) + { buff << desc; + } buff << uint32(proto->PageText); buff << uint32(proto->LanguageID); @@ -1692,7 +1786,9 @@ void WorldSession::HandleReforgeItemOpcode(WorldPacket& recvData) { // Reset the item if (item->IsEquipped()) + { player->ApplyReforgeEnchantment(item, false); + } item->ClearEnchantment(REFORGE_ENCHANTMENT_SLOT); SendReforgeResult(true); @@ -1724,6 +1820,8 @@ void WorldSession::HandleReforgeItemOpcode(WorldPacket& recvData) SendReforgeResult(true); if (item->IsEquipped()) + { player->ApplyReforgeEnchantment(item, true); + } } diff --git a/src/game/WorldHandlers/LFGHandler.cpp b/src/game/WorldHandlers/LFGHandler.cpp index 7b74d8b4f..bc9434201 100644 --- a/src/game/WorldHandlers/LFGHandler.cpp +++ b/src/game/WorldHandlers/LFGHandler.cpp @@ -47,12 +47,16 @@ void WorldSession::HandleLfgJoinOpcode(WorldPacket& recv_data) dungeons.resize(dungeonsCount); for (uint8 i = 0; i < dungeonsCount; ++i) + { recv_data >> dungeons[i]; // dungeons id/type + } recv_data >> counter2; // const count = 3, lua: GetLFGInfoLocal for (uint8 i = 0; i < counter2; ++i) + { recv_data >> Unused(); // lua: GetLFGInfoLocal + } recv_data >> comment; // lfg comment @@ -133,7 +137,9 @@ void WorldSession::SendLfgSearchResults(LfgType type, uint32 entry) if (flags & 0x10) { for (uint32 j = 0; j < 3; ++j) + { data << uint8(0); // roles + } } if (flags & 0x80) @@ -154,10 +160,14 @@ void WorldSession::SendLfgSearchResults(LfgType type, uint32 entry) Player* plr = iter->second; if (!plr || plr->GetTeam() != _player->GetTeam()) + { continue; + } if (!plr->IsInWorld()) + { continue; + } data << plr->GetObjectGuid(); // guid @@ -171,7 +181,9 @@ void WorldSession::SendLfgSearchResults(LfgType type, uint32 entry) data << uint8(plr->getRace()); for (uint32 i = 0; i < 3; ++i) + { data << uint8(0); // talent spec x/x/x + } data << uint32(0); // armor data << uint32(0); // spd/heal @@ -196,22 +208,34 @@ void WorldSession::SendLfgSearchResults(LfgType type, uint32 entry) } if (flags & 0x2) + { data << ""; // comment + } if (flags & 0x4) + { data << uint8(0); // group leader + } if (flags & 0x8) + { data << uint64(1); // group guid + } if (flags & 0x10) + { data << uint8(0); // roles + } if (flags & 0x20) + { data << uint32(plr->GetZoneId()); // areaid + } if (flags & 0x40) + { data << uint8(0); // status + } if (flags & 0x80) { @@ -312,13 +336,17 @@ void WorldSession::SendLfgUpdate(bool isGroup, LFGPlayerStatus status) isQueued = true; case LFG_UPDATE_PROPOSAL_BEGIN: if (isGroup) + { joinLFG = true; + } break; case LFG_UPDATE_STATUS: isQueued = (status.state == LFG_STATE_QUEUED); if (isGroup) + { joinLFG = (status.state != LFG_STATE_ROLECHECK) && (status.state != LFG_STATE_NONE); + } break; default: break; @@ -332,7 +360,9 @@ void WorldSession::SendLfgUpdate(bool isGroup, LFGPlayerStatus status) if (dungeonSize) { if (isGroup) + { data << uint8(joinLFG); + } data << uint8(isQueued); data << uint8(0); data << uint8(0); @@ -383,9 +413,13 @@ void WorldSession::SendLfgRoleCheckUpdate(LFGRoleCheck const& roleCheck) std::set dungeons; if (roleCheck.randomDungeonID) + { dungeons.insert(roleCheck.randomDungeonID); + } else + { dungeons = roleCheck.dungeonList; + } data << uint8(dungeons.size()); if (!dungeons.empty()) @@ -409,7 +443,9 @@ void WorldSession::SendLfgRoleCheckUpdate(LFGRoleCheck const& roleCheck) for (roleMap::const_iterator rItr = roleCheck.currentRoles.begin(); rItr != roleCheck.currentRoles.end(); ++rItr) { if (rItr->first == leaderGuid) + { continue; // exclude the leader + } ObjectGuid plrGuid = rItr->first; @@ -511,7 +547,9 @@ void WorldSession::SendLfgRewards(LFGRewards const& rewards) } } else + { data << uint8(0); + } SendPacket(&data); } @@ -529,7 +567,9 @@ void WorldSession::SendLfgBootUpdate(LFGBoot const& boot) { ++voteCount; if (it->second == LFG_ANSWER_AGREE) + { ++yayCount; + } } } diff --git a/src/game/WorldHandlers/LFGMgr.cpp b/src/game/WorldHandlers/LFGMgr.cpp index f1f6ee7e7..452bfe0eb 100644 --- a/src/game/WorldHandlers/LFGMgr.cpp +++ b/src/game/WorldHandlers/LFGMgr.cpp @@ -175,7 +175,9 @@ void LFGMgr::JoinLFG(uint32 roles, std::set dungeons, std::string commen // remove from that queue so they can later join this one queueSet::iterator qItr = m_queueSet.find(guid); if (qItr != m_queueSet.end()) + { m_queueSet.erase(qItr); + } // note: do we need to send a packet telling them the current queue is over? } @@ -276,7 +278,9 @@ void LFGMgr::JoinLFG(uint32 roles, std::set dungeons, std::string commen std::set::iterator setItr = dungeons.find(dungeonID); if (setItr != dungeons.end()) + { dungeons.erase(*setItr); + } } } } @@ -292,14 +296,20 @@ void LFGMgr::JoinLFG(uint32 roles, std::set dungeons, std::string commen std::set::iterator setItr = dungeons.find(dungeonID); if (setItr != dungeons.end()) + { dungeons.erase(*setItr); + } } } if (!dungeons.empty()) + { partyLockedDungeons.clear(); + } else + { result = (pGroup) ? ERR_LFG_NO_SLOTS_PARTY : ERR_LFG_NO_SLOTS_PLAYER; + } } // If our result is not ERR_LFG_OK, send join result now with err message @@ -486,16 +496,24 @@ LfgJoinResult LFGMgr::GetJoinResult(Player* plr) */ if (plr->HasAura(LFG_DESERTER_SPELL)) + { result = ERR_LFG_DESERTER_PLAYER; + } else if (plr->InBattleGround() || plr->InBattleGroundQueue() || plr->InArena()) + { result = ERR_LFG_CANT_USE_DUNGEONS; + } else if (plr->HasAura(LFG_COOLDOWN_SPELL)) + { result = ERR_LFG_RANDOM_COOLDOWN_PLAYER; + } if (pGroup) { if (pGroup->GetMembersCount() > 5) + { result = ERR_LFG_TOO_MANY_MEMBERS; + } else { uint8 currentMemberCount = 0; @@ -505,26 +523,40 @@ LfgJoinResult LFGMgr::GetJoinResult(Player* plr) { // check if the group members are level 15+ to use finder if (pGroupPlr->getLevel() < 15) + { result = ERR_LFG_CANT_USE_DUNGEONS; + } else if (pGroupPlr->HasAura(LFG_DESERTER_SPELL)) + { result = ERR_LFG_DESERTER_PARTY; + } else if (pGroupPlr->InBattleGround() || pGroupPlr->InBattleGroundQueue() || pGroupPlr->InArena()) + { result = ERR_LFG_CANT_USE_DUNGEONS; + } else if (pGroupPlr->HasAura(LFG_COOLDOWN_SPELL)) + { result = ERR_LFG_RANDOM_COOLDOWN_PARTY; + } else + { result = ERR_LFG_OK; + } ++currentMemberCount; } } if (result == ERR_LFG_OK && currentMemberCount != pGroup->GetMembersCount()) + { result = ERR_LFG_MEMBERS_NOT_PRESENT; + } } } else + { result = ERR_LFG_OK; + } return result; } @@ -535,7 +567,9 @@ LFGPlayerStatus LFGMgr::GetPlayerStatus(ObjectGuid guid) playerStatusMap::iterator it = m_playerStatusMap.find(guid); if (it != m_playerStatusMap.end()) + { status = it->second; + } return status; } @@ -829,7 +863,9 @@ void LFGMgr::AddToQueue(ObjectGuid guid) // just in case someone's already been in the queue. queueSet::iterator qItr = m_queueSet.find(guid); if (qItr == m_queueSet.end()) + { m_queueSet.insert(guid); + } } void LFGMgr::RemoveFromQueue(ObjectGuid guid) @@ -907,7 +943,9 @@ void LFGMgr::AddToWaitMap(uint8 role, std::set dungeons) { waitTimeMap::iterator it = m_avgWaitTime.find(*itr); if (it != m_avgWaitTime.end()) + { ++it->second.playerCount; + } else { LFGWait waitInfo(QUEUE_DEFAULT_TIME, -1, 1, false); @@ -937,7 +975,9 @@ void LFGMgr::FindSpecificQueueMatches(ObjectGuid guid) for (queueSet::iterator itr = m_queueSet.begin(); itr != m_queueSet.end(); ++itr) { if (*itr == guid) + { continue; + } LFGPlayers* matchInfo = GetPlayerOrPartyData(*itr); if (matchInfo) @@ -953,7 +993,9 @@ void LFGMgr::FindSpecificQueueMatches(ObjectGuid guid) for (std::set::iterator dItr = matchInfo->dungeonList.begin(); dItr != matchInfo->dungeonList.end(); ++itr) { if (queueInfo->dungeonList.find(*dItr) != queueInfo->dungeonList.end()) + { compatibleDungeons.insert(*dItr); + } } if (!compatibleDungeons.empty()) @@ -961,7 +1003,9 @@ void LFGMgr::FindSpecificQueueMatches(ObjectGuid guid) // check for player / role count and also team compatibility // if function returns true, then merge groups into one if (RoleMapsAreCompatible(queueInfo, matchInfo) && MatchesAreOfSameTeam(queueInfo, matchInfo)) + { MergeGroups(guid, *itr, compatibleDungeons); + } } } } @@ -992,7 +1036,9 @@ bool LFGMgr::RoleMapsAreCompatible(LFGPlayers* groupOne, LFGPlayers* groupTwo) return false; } else + { return true; // the player/role counts line up! + } } return false; } @@ -1047,7 +1093,9 @@ void LFGMgr::MergeGroups(ObjectGuid guidOne, ObjectGuid guidTwo, std::setneededTanks == 0) && (mainGroup->neededHealers == 0) && (mainGroup->neededDps == 0)) + { SendDungeonProposal(mainGroup); + } m_playerData.erase(guidTwo); } @@ -1131,15 +1179,21 @@ void LFGMgr::PerformRoleCheck(Player* pPlayer, Group* pGroup, uint8 roles) roleCheckMap::iterator it = m_roleCheckMap.find(groupGuid); if (it == m_roleCheckMap.end()) + { return; // no role check map found + } LFGRoleCheck roleCheck = it->second; bool roleChosen = roleCheck.state != LFG_ROLECHECK_DEFAULT && plrGuid; if (!plrGuid) + { roleCheck.state = LFG_ROLECHECK_ABORTED; // aborted if anyone cancels during role check + } else if (roles < PLAYER_ROLE_TANK) // kind of a sanity check- the client shouldn't allow this to happen + { roleCheck.state = LFG_ROLECHECK_NO_ROLE; + } else { roleCheck.currentRoles[plrGuid] = roles; @@ -1148,18 +1202,26 @@ void LFGMgr::PerformRoleCheck(Player* pPlayer, Group* pGroup, uint8 roles) do { if (rItr->second != PLAYER_ROLE_NONE) + { ++rItr; + } } while (rItr != roleCheck.currentRoles.end()); if (rItr == roleCheck.currentRoles.end()) // meaning that everyone confirmed their roles + { roleCheck.state = ValidateGroupRoles(roleCheck.currentRoles) ? LFG_ROLECHECK_FINISHED : LFG_ROLECHECK_MISSING_ROLE; + } } std::set dungeonBuff; if (roleCheck.randomDungeonID) + { dungeonBuff.insert(roleCheck.randomDungeonID); + } else + { dungeonBuff = roleCheck.dungeonList; + } partyForbidden nullForbidden; @@ -1167,7 +1229,9 @@ void LFGMgr::PerformRoleCheck(Player* pPlayer, Group* pGroup, uint8 roles) { ObjectGuid guidBuff = itr->first; if (roleChosen) + { SendRoleChosen(guidBuff, plrGuid, roles); // send SMSG_LFG_ROLE_CHOSEN to each player + } // send SMSG_LFG_ROLE_CHECK_UPDATE SendRoleCheckUpdate(guidBuff, roleCheck); @@ -1185,7 +1249,9 @@ void LFGMgr::PerformRoleCheck(Player* pPlayer, Group* pGroup, uint8 roles) break; default: if (roleCheck.leaderGuidRaw == guidBuff.GetRawValue()) + { SendLfgJoinResult(guidBuff, ERR_LFG_ROLE_CHECK_FAILED, LFG_STATE_ROLECHECK, nullForbidden); + } SetPlayerUpdateType(guidBuff, LFG_UPDATE_ROLECHECK_FAILED); SendLfgUpdate(guidBuff, GetPlayerStatus(guidBuff), true); break; @@ -1286,10 +1352,14 @@ void LFGMgr::SendDungeonProposal(LFGPlayers* lfgGroup) SetPlayerUpdateType(plrGuid, LFG_UPDATE_PROPOSAL_BEGIN); if (premadeGroup && pGroup->IsLeader(plrGuid)) + { newProposal.groupLeaderGuid = plrGuid.GetRawValue(); + } if (premadeGroup && !newProposal.groupRawGuid) + { newProposal.groupRawGuid = grpGuid.GetRawValue(); + } newProposal.groups[plrGuid] = grpGuid; @@ -1341,13 +1411,17 @@ bool LFGMgr::IsProposalSameGroup(LFGProposal const& proposal) ObjectGuid grpGuid = pGroup->GetObjectGuid(); if (firstLoop) + { priorGroupGuid = grpGuid; + } else { if (isSameGroup) { if (grpGuid != priorGroupGuid) + { isSameGroup = false; + } } } } @@ -1374,12 +1448,16 @@ void LFGMgr::ProposalUpdate(uint32 proposalID, ObjectGuid plrGuid, bool accepted // If the player declined, the proposal is over if (plrAnswer == LFG_ANSWER_DENY) + { ProposalDeclined(plrGuid, proposal); + } for (proposalAnswerMap::iterator it = proposal->answers.begin(); it != proposal->answers.end(); ++it) { if (it->second != LFG_ANSWER_AGREE) + { allOkay = false; + } } // if !allOkay, send proposal updates to all @@ -1412,7 +1490,9 @@ void LFGMgr::ProposalUpdate(uint32 proposalID, ObjectGuid plrGuid, bool accepted Player* pProposalPlayer = ObjectAccessor::FindPlayer(proposalPlrGuid); if (sendProposalUpdate) + { pProposalPlayer->GetSession()->SendLfgProposalUpdate(*proposal); + } // amount of time spent in queue int32 timeWaited = (joinedTime - proposal->joinedQueue) / IN_MILLISECONDS; @@ -1483,7 +1563,9 @@ void LFGMgr::CreateDungeonGroup(LFGProposal* proposal) Player* pGroupPlr = ObjectAccessor::FindPlayer(pGroupPlrGuid); if (it->second) + { pGroupPlr->GetGroup()->RemoveMember(pGroupPlrGuid, 0); + } if (!leaderIsSet) { @@ -1500,20 +1582,28 @@ void LFGMgr::CreateDungeonGroup(LFGProposal* proposal) pGroup->Create(leaderRef->GetObjectGuid(), leaderRef->GetName()); if (pGroupPlrGuid == leaderGuid) + { currentPlrIsLeader = true; + } } } } else + { pGroup->Create(pGroupPlrGuid, pGroupPlr->GetName()); + } if (!currentPlrIsLeader) + { pGroup->AddMember(pGroupPlrGuid, pGroupPlr->GetName()); + } leaderIsSet = true; } else if (leaderIsSet && pGroupPlrGuid != leaderGuid) + { pGroup->AddMember(pGroupPlrGuid, pGroupPlr->GetName()); + } } pGroup->SetAsLfgGroup(); } @@ -1589,11 +1679,17 @@ void LFGMgr::TeleportToDungeon(uint32 dungeonID, Group* pGroup) LFGTeleportError plrErr = LFG_TELEPORTERROR_OK; if (pGroupPlr->IsDead()) + { plrErr = LFG_TELEPORTERROR_PLAYER_DEAD; + } if (pGroupPlr->IsFalling()) + { plrErr = LFG_TELEPORTERROR_FALLING; + } if (pGroupPlr->GetVehicleInfo()) + { plrErr = LFG_TELEPORTERROR_IN_VEHICLE; + } lockedDungeons = FindRandomDungeonsNotForPlayer(pGroupPlr); //if (lockedDungeons.find(dungeon->Entry()) != lockedDungeons.end()) @@ -1678,16 +1774,22 @@ void LFGMgr::ProposalDeclined(ObjectGuid guid, LFGProposal* proposal) { //LeaveLFG(pGroupPlayer, true); if (pGroup && (pGroup->GetObjectGuid().GetRawValue() == proposal->groupRawGuid)) + { leaveGroupLFG = true; + } SendLfgUpdate(groupPlrGuid, GetPlayerStatus(groupPlrGuid), false); } else { if (proposal->groupRawGuid) + { SendLfgUpdate(groupPlrGuid, GetPlayerStatus(groupPlrGuid), true); + } else + { SendLfgUpdate(groupPlrGuid, GetPlayerStatus(groupPlrGuid), false); + } } } @@ -1879,7 +1981,9 @@ void LFGMgr::AttemptToKickPlayer(Group* pGroup, ObjectGuid guid, ObjectGuid kick SetPlayerState(pGroupPlrGuid, LFG_STATE_BOOT); if ( (pGroupPlrGuid != guid) && (pGroupPlrGuid != kicker) ) + { votes[pGroupPlrGuid] = LFG_ANSWER_PENDING; + } } } @@ -1889,7 +1993,9 @@ void LFGMgr::AttemptToKickPlayer(Group* pGroup, ObjectGuid guid, ObjectGuid kick for (GroupReference* it = pGroup->GetFirstMember(); it != NULL; it = it->next()) { if (Player* groupPlr = it->getSource()) + { groupPlr->GetSession()->SendLfgBootUpdate(boot); + } } } @@ -1924,9 +2030,13 @@ void LFGMgr::CastVote(Player* pPlayer, bool vote) { LFGProposalAnswer answer = pIt->second; if (answer == LFG_ANSWER_AGREE) + { ++yay; + } else if (answer == LFG_ANSWER_DENY) + { ++nay; + } } if (yay < REQUIRED_VOTES_FOR_BOOT && nay < REQUIRED_VOTES_FOR_BOOT) @@ -1974,7 +2084,9 @@ void LFGMgr::SendRoleChosen(ObjectGuid plrGuid, ObjectGuid confirmedGuid, uint8 Player* pPlayer = ObjectAccessor::FindPlayer(plrGuid); if (pPlayer) + { pPlayer->GetSession()->SendLfgRoleChosen(confirmedGuid.GetRawValue(), roles); + } } void LFGMgr::SendRoleCheckUpdate(ObjectGuid plrGuid, LFGRoleCheck const& roleCheck) @@ -1982,7 +2094,9 @@ void LFGMgr::SendRoleCheckUpdate(ObjectGuid plrGuid, LFGRoleCheck const& roleChe Player* pPlayer = ObjectAccessor::FindPlayer(plrGuid); if (pPlayer) + { pPlayer->GetSession()->SendLfgRoleCheckUpdate(roleCheck); + } } void LFGMgr::SendLfgUpdate(ObjectGuid plrGuid, LFGPlayerStatus status, bool isGroup) @@ -1990,7 +2104,9 @@ void LFGMgr::SendLfgUpdate(ObjectGuid plrGuid, LFGPlayerStatus status, bool isGr Player* pPlayer = ObjectAccessor::FindPlayer(plrGuid); if (pPlayer) + { pPlayer->GetSession()->SendLfgUpdate(isGroup, status); + } } void LFGMgr::SendLfgJoinResult(ObjectGuid plrGuid, LfgJoinResult result, LFGState state, partyForbidden const& lockedDungeons) @@ -1998,7 +2114,9 @@ void LFGMgr::SendLfgJoinResult(ObjectGuid plrGuid, LfgJoinResult result, LFGStat Player* pPlayer = ObjectAccessor::FindPlayer(plrGuid); if (pPlayer) + { pPlayer->GetSession()->SendLfgJoinResult(result, state, lockedDungeons); + } } void LFGMgr::RemoveOldRoleChecks() diff --git a/src/game/WorldHandlers/LootHandler.cpp b/src/game/WorldHandlers/LootHandler.cpp index 67581b3e1..6df3f35cf 100644 --- a/src/game/WorldHandlers/LootHandler.cpp +++ b/src/game/WorldHandlers/LootHandler.cpp @@ -136,12 +136,16 @@ void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recv_data) } if (pItem) + { pItem->SetLootState(ITEM_LOOT_CHANGED); + } if (currency) { if (CurrencyTypesEntry const * currencyEntry = sCurrencyTypesStore.LookupEntry(item->itemid)) + { player->ModifyCurrencyCount(item->itemid, int32(item->count * currencyEntry->GetPrecision())); + } player->SendNotifyLootItemRemoved(lootSlot, true); currency->is_looted = true; @@ -160,9 +164,13 @@ void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recv_data) qitem->is_looted = true; // freeforall is 1 if everyone's supposed to get the quest item. if (item->freeforall || loot->GetPlayerQuestItems().size() == 1) + { player->SendNotifyLootItemRemoved(lootSlot); + } else + { loot->NotifyQuestItemRemoved(qitem->index); + } } else { @@ -176,14 +184,18 @@ void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recv_data) { // not freeforall, notify everyone if (conditem) + { conditem->is_looted = true; + } loot->NotifyItemRemoved(lootSlot); } } // if only one person is supposed to loot the item, then set it to looted if (!item->freeforall) + { item->is_looted = true; + } --loot->unlootedCount; @@ -193,7 +205,9 @@ void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recv_data) player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM, item->itemid, item->count); } else + { player->SendEquipError(msg, NULL, NULL, item->itemid); + } } void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) @@ -218,7 +232,9 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) // not check distance for GO in case owned GO (fishing bobber case, for example) if (pGameObject && (pGameObject->GetOwnerGuid() == _player->GetObjectGuid() || pGameObject->IsWithinDistInMap(_player, INTERACTION_DISTANCE))) + { pLoot = &pGameObject->loot; + } break; } @@ -227,7 +243,9 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) Corpse* bones = _player->GetMap()->GetCorpse(guid); if (bones && bones->IsWithinDistInMap(_player, INTERACTION_DISTANCE)) + { pLoot = &bones->loot; + } break; } @@ -250,7 +268,9 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) bool ok_loot = pCreature && pCreature->IsAlive() == (player->getClass() == CLASS_ROGUE && pCreature->lootForPickPocketed); if (ok_loot && pCreature->IsWithinDistInMap(_player, INTERACTION_DISTANCE)) + { pLoot = &pCreature->loot ; + } break; } @@ -271,9 +291,13 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) { Player* playerGroup = itr->getSource(); if (!playerGroup) + { continue; + } if (player->IsWithinDistInMap(playerGroup, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + { playersNear.push_back(playerGroup); + } } uint64 money_per_player = uint32((pLoot->gold) / (playersNear.size())); @@ -309,7 +333,9 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) pLoot->gold = 0; if (pItem) + { pItem->SetLootState(ITEM_LOOT_CHANGED); + } } } @@ -338,7 +364,9 @@ void WorldSession::HandleLootReleaseOpcode(WorldPacket& recv_data) recv_data.read_skip(); // guid; if (ObjectGuid lootGuid = GetPlayer()->GetLootGuid()) + { DoLootRelease(lootGuid); + } } void WorldSession::DoLootRelease(ObjectGuid lguid) @@ -402,7 +430,9 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) int32 ReqValue = 175; LockEntry const* lockInfo = sLockStore.LookupEntry(go->GetGOInfo()->chest.lockId); if (lockInfo) + { ReqValue = lockInfo->Skill[0]; + } float skill = float(player->GetSkillValue(SKILL_MINING)) / (ReqValue + 25); double chance = pow(0.8 * chance_rate, 4 * (1 / double(max_amount)) * double(uses)); if (roll_chance_f(float(100.0f * chance + skill))) @@ -410,16 +440,24 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) go->SetLootState(GO_READY); } else // not have more uses + { go->SetLootState(GO_JUST_DEACTIVATED); + } } else // 100% chance until min uses + { go->SetLootState(GO_READY); + } } else // max uses already + { go->SetLootState(GO_JUST_DEACTIVATED); + } } else // not vein + { go->SetLootState(GO_JUST_DEACTIVATED); + } } else if (go->GetGoType() == GAMEOBJECT_TYPE_FISHINGHOLE) { @@ -430,10 +468,14 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) go->SetLootState(GO_JUST_DEACTIVATED); } else + { go->SetLootState(GO_READY); + } } else // not chest (or vein/herb/etc) + { go->SetLootState(GO_JUST_DEACTIVATED); + } loot->clear(); } @@ -477,7 +519,9 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) // >=5 checked in spell code, but will work for cheating cases also with removing from another stacks. if (count > 5) + { count = 5; + } // reset loot for allow repeat looting if stack > 5 pItem->loot.clear(); @@ -490,7 +534,9 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) case LOOT_DISENCHANTING: { if (!pItem->loot.isLooted()) + { player->AutoStoreLoot(pItem->loot); // can be lost if no space + } pItem->loot.clear(); pItem->SetLootState(ITEM_LOOT_REMOVED); player->DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), true); @@ -526,7 +572,9 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) // update next looter if (Group* group = pCreature->GetGroupLootRecipient()) if (group->GetLooterGuid() == player->GetObjectGuid()) + { group->UpdateLooterGuid(pCreature); + } if (loot->isLooted() && !pCreature->IsAlive()) { diff --git a/src/game/WorldHandlers/Mail.cpp b/src/game/WorldHandlers/Mail.cpp index 2160c9b5d..61366f04f 100644 --- a/src/game/WorldHandlers/Mail.cpp +++ b/src/game/WorldHandlers/Mail.cpp @@ -213,7 +213,9 @@ void MailDraft::SendReturnToSender(uint32 sender_acc, ObjectGuid sender_guid, Ob uint32 rc_account = 0; if (!receiver) + { rc_account = sObjectMgr.GetPlayerAccountIdByGUID(receiver_guid); + } if (!receiver && !rc_account) // sender not exist { @@ -261,7 +263,9 @@ void MailDraft::SendMailTo(MailReceiver const& receiver, MailSender const& sende uint32 pReceiverAccount = 0; if (!pReceiver) + { pReceiverAccount = sObjectMgr.GetPlayerAccountIdByGUID(receiver.GetPlayerGuid()); + } if (!pReceiver && !pReceiverAccount) // receiver not exist { @@ -275,7 +279,9 @@ void MailDraft::SendMailTo(MailReceiver const& receiver, MailSender const& sende if (pReceiver) { if (prepareItems(pReceiver)) + { has_items = true; + } } uint32 mailId = sObjectMgr.GenerateMailID(); @@ -285,10 +291,14 @@ void MailDraft::SendMailTo(MailReceiver const& receiver, MailSender const& sende uint32 expire_delay; // auction mail without any items and money (auction sale note) pending 1 hour if (sender.GetMailMessageType() == MAIL_AUCTION && m_items.empty() && !m_money) + { expire_delay = HOUR; + } // default case: expire time if COD 3 days, if no COD 30 days else + { expire_delay = (m_COD > 0) ? 3 * DAY : 30 * DAY; + } time_t expire_time = deliver_time + expire_delay; @@ -351,7 +361,9 @@ void MailDraft::SendMailTo(MailReceiver const& receiver, MailSender const& sende } } else if (!m_items.empty()) + { deleteIncludedItems(); + } } /** diff --git a/src/game/WorldHandlers/MailHandler.cpp b/src/game/WorldHandlers/MailHandler.cpp index 83c4b3909..23ffe5644 100644 --- a/src/game/WorldHandlers/MailHandler.cpp +++ b/src/game/WorldHandlers/MailHandler.cpp @@ -189,7 +189,9 @@ void WorldSession::HandleSendMail(WorldPacket& recv_data) ObjectGuid rc; if (normalizePlayerName(receiver)) + { rc = sObjectMgr.GetPlayerGuidByName(receiver); + } if (!rc) { @@ -389,7 +391,9 @@ void WorldSession::HandleMailMarkAsRead(WorldPacket& recv_data) if (Mail* m = pl->GetMail(mailId)) { if (pl->unReadMails) + { --pl->unReadMails; + } m->checked = m->checked | MAIL_CHECK_MASK_READ; pl->m_mailsUpdated = true; m->state = MAIL_STATE_CHANGED; @@ -477,16 +481,22 @@ void WorldSession::HandleMailReturnToSender(WorldPacket& recv_data) { MailDraft draft; if (m->mailTemplateId) + { draft.SetMailTemplate(m->mailTemplateId, false);// items already included + } else + { draft.SetSubjectAndBody(m->subject, m->body); + } if (m->HasItems()) { for (MailItemInfoVec::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2) { if (Item* item = pl->GetMItem(itr2->item_guid)) + { draft.AddItem(item); + } pl->RemoveMItem(itr2->item_guid); } @@ -562,13 +572,17 @@ void WorldSession::HandleMailTakeItem(WorldPacket& recv_data) sender_accId = sObjectMgr.GetPlayerAccountIdByGUID(sender_guid); if (!sObjectMgr.GetPlayerNameByGUID(sender_guid, sender_name)) + { sender_name = sObjectMgr.GetMangosStringForDBCLocale(LANG_UNKNOWN); + } } sLog.outCommand(GetAccountId(), "GM %s (Account: %u) receive mail item: %s (Entry: %u Count: %u) and send COD money: %u to player: %s (Account: %u)", GetPlayerName(), GetAccountId(), it->GetProto()->Name1, it->GetEntry(), it->GetCount(), m->COD, sender_name.c_str(), sender_accId); } else if (!sender) + { sender_accId = sObjectMgr.GetPlayerAccountIdByGUID(sender_guid); + } // check player existence if (sender || sender_accId) @@ -596,7 +610,9 @@ void WorldSession::HandleMailTakeItem(WorldPacket& recv_data) pl->SendMailResult(mailId, MAIL_ITEM_TAKEN, MAIL_OK, 0, itemId, count); } else + { pl->SendMailResult(mailId, MAIL_ITEM_TAKEN, MAIL_ERR_EQUIP_ERROR, msg); + } } /** * Handles the packet sent by the client when taking money from the mail. @@ -674,7 +690,9 @@ void WorldSession::HandleGetMailList(WorldPacket& recv_data) // skip deleted or not delivered (deliver delay not expired) mails if ((*itr)->state == MAIL_STATE_DELETED || cur_time < (*itr)->deliver_time) + { continue; + } uint8 item_count = (*itr)->items.size(); // max count is MAX_MAIL_ITEMS (12) @@ -812,7 +830,9 @@ void WorldSession::HandleMailCreateTextItem(WorldPacket& recv_data) bodyItem->SetText(mailTemplateEntry->content[GetSessionDbcLocale()]); } else + { bodyItem->SetText(m->body); + } bodyItem->SetGuidValue(ITEM_FIELD_CREATOR, ObjectGuid(HIGHGUID_PLAYER, m->sender)); bodyItem->SetFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_READABLE | ITEM_DYNFLAG_UNK15 | ITEM_DYNFLAG_UNK16); @@ -856,11 +876,15 @@ void WorldSession::HandleQueryNextMailTime(WorldPacket & /**recv_data*/) Mail* m = (*itr); // must be not checked yet if (m->checked & MAIL_CHECK_MASK_READ) + { continue; + } // and already delivered if (now < m->deliver_time) + { continue; + } data << ObjectGuid(HIGHGUID_PLAYER, m->sender); // sender guid @@ -881,7 +905,9 @@ void WorldSession::HandleQueryNextMailTime(WorldPacket & /**recv_data*/) ++count; if (count == 2) // do not display more than 2 mails + { break; + } } data.put(4, count); } diff --git a/src/game/WorldHandlers/Map.cpp b/src/game/WorldHandlers/Map.cpp index 7c02cd0c2..a207f1258 100644 --- a/src/game/WorldHandlers/Map.cpp +++ b/src/game/WorldHandlers/Map.cpp @@ -64,7 +64,9 @@ Map::~Map() } if (m_persistentState) - { m_persistentState->SetUsedByMapState(NULL); } // field pointer can be deleted after this + { + m_persistentState->SetUsedByMapState(NULL); // field pointer can be deleted after this + } //#ifdef ENABLE_ELUNA // if (Instanceable()) @@ -1012,7 +1014,9 @@ void Map::SendInitSelf(Player* player) // attach to player data current transport data if (Transport* transport = player->GetTransport()) + { transport->BuildCreateUpdateBlockForPlayer(&data, player); + } // build data for self presence in world at own client (one time for map) player->BuildCreateUpdateBlockForPlayer(&data, player); @@ -1120,9 +1124,13 @@ void Map::AddObjectToRemoveList(WorldObject* obj) #ifdef ENABLE_ELUNA if (Creature* creature = obj->ToCreature()) + { sEluna->OnRemove(creature); + } else if (GameObject* gameobject = obj->ToGameObject()) + { sEluna->OnRemove(gameobject); + } #endif /* ENABLE_ELUNA */ obj->CleanupsBeforeDelete(); // remove or simplify at least cross referenced links @@ -1234,7 +1242,9 @@ bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const CellPair p = MaNGOS::ComputeCellPair(plr->GetPositionX(), plr->GetPositionY()); if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) && (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord)) - { return true; } + { + return true; + } } for (ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter) @@ -1244,7 +1254,9 @@ bool Map::ActiveObjectsNearGrid(uint32 x, uint32 y) const CellPair p = MaNGOS::ComputeCellPair(obj->GetPositionX(), obj->GetPositionY()); if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) && (cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord)) - { return true; } + { + return true; + } } return false; @@ -1400,12 +1412,16 @@ void Map::CreateInstanceData(bool load) if (Instanceable()) { if (InstanceTemplate const* mInstance = ObjectMgr::GetInstanceTemplate(GetId())) + { i_script_id = mInstance->script_id; + } } else { if (WorldTemplate const* mInstance = ObjectMgr::GetWorldTemplate(GetId())) + { i_script_id = mInstance->script_id; + } } if (!i_script_id) @@ -1425,9 +1441,13 @@ void Map::CreateInstanceData(bool load) QueryResult* result; if (Instanceable()) + { result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE id = '%u'", i_InstanceId); + } else + { result = CharacterDatabase.PQuery("SELECT data FROM world WHERE map = '%u'", GetId()); + } if (result) { @@ -1444,7 +1464,9 @@ void Map::CreateInstanceData(bool load) { // for non-instanceable map always add data to table if not found, later code expected that for map in `word` exist always after load if (!Instanceable()) + { CharacterDatabase.PExecute("INSERT INTO world VALUES ('%u', '')", GetId()); + } } } else @@ -1637,7 +1659,9 @@ bool DungeonMap::Add(Player* player) } else // can not jump to a different instance without resetting it - { MANGOS_ASSERT(playerBind->state == GetPersistentState()); } + { + MANGOS_ASSERT(playerBind->state == GetPersistentState()); + } } } @@ -1776,7 +1800,9 @@ void DungeonMap::SetResetSchedule(bool on) // the reset time is only scheduled when there are no payers inside // it is assumed that the reset time will rarely (if ever) change while the reset is scheduled if (!HavePlayers() && !IsRaidOrHeroicDungeon()) + { sMapPersistentStateMgr.GetScheduler().ScheduleReset(on, GetPersistanceState()->GetResetTime(), DungeonResetEvent(RESET_EVENT_NORMAL_DUNGEON, GetId(), Difficulty(GetSpawnMode()), GetInstanceId())); + } } DungeonPersistentState* DungeonMap::GetPersistanceState() const @@ -2311,7 +2337,9 @@ bool Map::GetHeightInRange(uint32 phasemask, float x, float y, float& z, float m VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager(); if (!vmgr->isLineOfSightCalcEnabled()) + { vmgr = NULL; + } if (vmgr) { @@ -2321,7 +2349,9 @@ bool Map::GetHeightInRange(uint32 phasemask, float x, float y, float& z, float m // find raw height from .map file on X,Y coordinates if (GridMap* gmap = const_cast(m_TerrainData)->GetGrid(x, y)) // TODO:: find a way to remove that const_cast + { mapHeight = gmap->getHeight(x, y); + } float diffMaps = fabs(fabs(z) - fabs(mapHeight)); float diffVmaps = fabs(fabs(z) - fabs(vmapHeight)); @@ -2331,9 +2361,13 @@ bool Map::GetHeightInRange(uint32 phasemask, float x, float y, float& z, float m { // well we simply have to take the highest as normally there we cannot be on top of cavern is maxSearchDist is not too big if (vmapHeight > mapHeight) + { height = vmapHeight; + } else + { height = mapHeight; + } //sLog.outString("vmap %5.4f, map %5.4f, height %5.4f", vmapHeight, mapHeight, height); } @@ -2400,7 +2434,9 @@ bool Map::GetRandomPointUnderWater(uint32 phaseMask, float& x, float& y, float& { float min_z = z - 0.7f * radius; // 0.7 to have a bit a "flat" cylinder, TODO which value looks nicest if (min_z < ground) + { min_z = ground + 0.5f; // Get some space to prevent under map + } float liquidLevel = liquid_status.level - 2.0f; // just to make the generated point is in water and not on surface or a bit above @@ -2436,7 +2472,9 @@ bool Map::GetRandomPointInTheAir(uint32 phaseMask, float& x, float& y, float& z, { float min_z = z - 0.7f * radius; // 0.7 to have a bit a "flat" cylinder, TODO which value looks nicest if (min_z < ground) + { min_z = ground + 2.5f; // Get some space to prevent landing + } float max_z = std::max(z + 0.7f * radius, min_z); x = i_x; y = i_y; diff --git a/src/game/WorldHandlers/MapManager.cpp b/src/game/WorldHandlers/MapManager.cpp index e273c36da..02bac82e0 100644 --- a/src/game/WorldHandlers/MapManager.cpp +++ b/src/game/WorldHandlers/MapManager.cpp @@ -216,7 +216,9 @@ void MapManager::Update(uint32 diff) i_maps.erase(iter++); } else + { ++iter; + } } i_timer.SetCurrent(0); @@ -270,7 +272,9 @@ uint32 MapManager::GetNumInstances() { Map* map = itr->second; if (!map->IsDungeon()) continue; - ret += 1; + { + ret += 1; + } } return ret; } @@ -282,7 +286,9 @@ uint32 MapManager::GetNumPlayersInInstances() { Map* map = itr->second; if (!map->IsDungeon()) continue; - ret += map->GetPlayers().getSize(); + { + ret += map->GetPlayers().getSize(); + } } return ret; } @@ -311,7 +317,9 @@ Map* MapManager::CreateInstance(uint32 id, Player* player) map = FindMap(id, NewInstanceId); // it is possible that the save exists but the map doesn't if (!map) + { pNewMap = CreateDungeonMap(id, NewInstanceId, pSave->GetDifficulty(), pSave); + } } else { @@ -349,7 +357,9 @@ DungeonMap* MapManager::CreateDungeonMap(uint32 id, uint32 InstanceId, Difficult // some instances only have one difficulty if (!GetMapDifficultyData(id, difficulty)) + { difficulty = DUNGEON_DIFFICULTY_NORMAL; + } DEBUG_LOG("MapInstanced::CreateDungeonMap: %s map instance %d for %d created with difficulty %d", save ? "" : "new ", InstanceId, id, difficulty); diff --git a/src/game/WorldHandlers/MapManager.h b/src/game/WorldHandlers/MapManager.h index 35e466e5d..5c78bc610 100644 --- a/src/game/WorldHandlers/MapManager.h +++ b/src/game/WorldHandlers/MapManager.h @@ -82,15 +82,21 @@ class MapManager : public MaNGOS::Singleton MIN_MAP_UPDATE_DELAY) + { t = MIN_MAP_UPDATE_DELAY; + } i_timer.SetInterval(t); i_timer.Reset(); diff --git a/src/game/WorldHandlers/MapPersistentStateMgr.cpp b/src/game/WorldHandlers/MapPersistentStateMgr.cpp index 2102b6ac0..7385f245c 100644 --- a/src/game/WorldHandlers/MapPersistentStateMgr.cpp +++ b/src/game/WorldHandlers/MapPersistentStateMgr.cpp @@ -136,7 +136,9 @@ void MapPersistentState::SaveGORespawnTime(uint32 loguid, time_t t) void MapPersistentState::SetCreatureRespawnTime(uint32 loguid, time_t t) { if (t > sWorld.GetGameTime()) + { m_creatureRespawnTimes[loguid] = t; + } else { m_creatureRespawnTimes.erase(loguid); @@ -147,7 +149,9 @@ void MapPersistentState::SetCreatureRespawnTime(uint32 loguid, time_t t) void MapPersistentState::SetGORespawnTime(uint32 loguid, time_t t) { if (t > sWorld.GetGameTime()) + { m_goRespawnTimes[loguid] = t; + } else { m_goRespawnTimes.erase(loguid); @@ -354,7 +358,9 @@ uint32 DungeonResetScheduler::GetMaxResetTimeFor(MapDifficultyEntry const* mapDi uint32 delay = uint32(mapDiff->resetTime / DAY * sWorld.getConfig(CONFIG_FLOAT_RATE_INSTANCE_RESET_TIME)) * DAY; if (delay < DAY) // the reset_delay must be at least one day + { delay = DAY; + } return delay; } @@ -431,7 +437,9 @@ void DungeonResetScheduler::LoadResetTimes() // schedule the reset times for (InstResetTimeMapDiffType::iterator itr = instResetTime.begin(); itr != instResetTime.end(); ++itr) if (itr->second.second > now) + { ScheduleReset(true, itr->second.second, DungeonResetEvent(RESET_EVENT_NORMAL_DUNGEON, PAIR32_LOPART(itr->second.first), Difficulty(PAIR32_HIPART(itr->second.first)), itr->first)); + } } // load the global respawn times for raid/heroic instances @@ -484,12 +492,16 @@ void DungeonResetScheduler::LoadResetTimes() // skip mapDiff without global reset time if (!mapDiff->resetTime) + { continue; + } // only raid/heroic maps have a global reset time MapEntry const* mapEntry = sMapStore.LookupEntry(mapid); if (!mapEntry || !mapEntry->IsDungeon()) + { continue; + } uint32 period = GetMaxResetTimeFor(mapDiff); time_t t = GetResetTimeFor(mapid, difficulty); @@ -515,7 +527,9 @@ void DungeonResetScheduler::LoadResetTimes() ResetEventType type = RESET_EVENT_INFORM_1; for (; type < RESET_EVENT_INFORM_LAST; type = ResetEventType(type + 1)) if (t > time_t(now + resetEventTypeDelay[type])) + { break; + } ScheduleReset(true, t - resetEventTypeDelay[type], DungeonResetEvent(type, mapid, difficulty, 0)); } @@ -524,7 +538,9 @@ void DungeonResetScheduler::LoadResetTimes() void DungeonResetScheduler::ScheduleReset(bool add, time_t time, DungeonResetEvent event) { if (add) + { m_resetTimeQueue.insert(std::pair(time, event)); + } else { // find the event in the queue and remove it @@ -552,7 +568,9 @@ void DungeonResetScheduler::ScheduleReset(bool add, time_t time, DungeonResetEve } if (itr == m_resetTimeQueue.end()) + { sLog.outError("DungeonResetScheduler::ScheduleReset: cannot cancel the reset, the event(%d,%d,%d) was not found!", event.type, event.mapid, event.instanceId); + } } } } @@ -597,7 +615,9 @@ void DungeonResetScheduler::Update() ResetEventType type = RESET_EVENT_INFORM_1; for (; type < RESET_EVENT_INFORM_LAST; type = ResetEventType(type + 1)) if (next_reset > time_t(now + resetEventTypeDelay[type])) + { break; + } // add new scheduler event to the queue event.type = type; @@ -673,7 +693,9 @@ MapPersistentState* MapPersistentStateManager::AddPersistentState(MapEntry const // initialize reset time // for normal instances if no creatures are killed the instance will reset in two hours if (mapEntry->map_type == MAP_RAID || difficulty > DUNGEON_DIFFICULTY_NORMAL) + { resetTime = m_Scheduler.GetResetTimeFor(mapEntry->MapID, difficulty); + } else { resetTime = time(NULL) + 2 * HOUR; @@ -690,22 +712,34 @@ MapPersistentState* MapPersistentStateManager::AddPersistentState(MapEntry const { DungeonPersistentState* dungeonState = new DungeonPersistentState(mapEntry->MapID, instanceId, difficulty, resetTime, canReset, completedEncountersMask); if (!load) + { dungeonState->SaveToDB(); + } state = dungeonState; } else if (mapEntry->IsBattleGroundOrArena()) + { state = new BattleGroundPersistentState(mapEntry->MapID, instanceId, difficulty); + } else + { state = new WorldPersistentState(mapEntry->MapID); + } if (instanceId) + { m_instanceSaveByInstanceId[instanceId] = state; + } else + { m_instanceSaveByMapId[mapEntry->MapID] = state; + } if (initPools) + { state->InitPools(); + } return state; } @@ -764,7 +798,9 @@ void MapPersistentStateManager::RemovePersistentState(uint32 mapId, uint32 insta { PersistentStateMap::iterator itr = m_instanceSaveByMapId.find(mapId); if (itr != m_instanceSaveByMapId.end()) + { _ResetSave(m_instanceSaveByMapId, itr); + } } } @@ -970,7 +1006,9 @@ void MapPersistentStateManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficu // trigger the modification of the collection, which would invalidate the iterator and cause a crash. for (PersistentStateMap::iterator itr = m_instanceSaveByInstanceId.begin(); itr != m_instanceSaveByInstanceId.end(); ++itr) if (itr->second->GetMapId() == mapid && itr->second->GetDifficulty() == difficulty) + { unbindList.push_back((DungeonPersistentState *)itr->second); + } for (auto i : unbindList) { @@ -1010,7 +1048,9 @@ void MapPersistentStateManager::GetStatistics(uint32& numStates, uint32& numBoun for (PersistentStateMap::iterator itr = m_instanceSaveByInstanceId.begin(); itr != m_instanceSaveByInstanceId.end(); ++itr) { if (!itr->second->GetMapEntry()->IsDungeon()) + { continue; + } ++numStates; numBoundPlayers += ((DungeonPersistentState*)itr->second)->GetPlayerCount(); @@ -1030,10 +1070,14 @@ void MapPersistentStateManager::InitWorldMaps() for (uint32 mapid = 0; mapid < sMapStore.GetNumRows(); ++mapid) if (MapEntry const* entry = sMapStore.LookupEntry(mapid)) if (!entry->Instanceable()) + { state = AddPersistentState(entry, 0, REGULAR_DIFFICULTY, 0, false, true, false); + } if (state) + { state->InitPools(); + } } void MapPersistentStateManager::LoadCreatureRespawnTimes() @@ -1073,29 +1117,41 @@ void MapPersistentStateManager::LoadCreatureRespawnTimes() CreatureData const* data = sObjectMgr.GetCreatureData(loguid); if (!data) + { continue; + } MapEntry const* mapEntry = sMapStore.LookupEntry(data->mapid); if (!mapEntry) + { continue; + } if (instanceId) // In instance - mapId must be data->mapid and mapEntry must be Instanceable { if (mapId != data->mapid || !mapEntry->Instanceable()) + { continue; + } } else // Not in instance, mapEntry must not be Instanceable { if (mapEntry->Instanceable()) + { continue; + } } if (difficulty >= (!mapEntry->Instanceable() ? REGULAR_DIFFICULTY + 1 : (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))) + { continue; + } MapPersistentState* state = AddPersistentState(mapEntry, instanceId, Difficulty(difficulty), resetTime, mapEntry->IsDungeon(), true, true, completedEncounters); if (!state) + { continue; + } state->SetCreatureRespawnTime(loguid, time_t(respawn_time)); @@ -1147,29 +1203,41 @@ void MapPersistentStateManager::LoadGameobjectRespawnTimes() GameObjectData const* data = sObjectMgr.GetGOData(loguid); if (!data) + { continue; + } MapEntry const* mapEntry = sMapStore.LookupEntry(data->mapid); if (!mapEntry) + { continue; + } if (instanceId) // In instance - mapId must be data->mapid and mapEntry must be Instanceable { if (mapId != data->mapid || !mapEntry->Instanceable()) + { continue; + } } else // Not in instance, mapEntry must not be Instanceable { if (mapEntry->Instanceable()) + { continue; + } } if (difficulty >= (!mapEntry->Instanceable() ? REGULAR_DIFFICULTY + 1 : (mapEntry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))) + { continue; + } MapPersistentState* state = AddPersistentState(mapEntry, instanceId, Difficulty(difficulty), resetTime, mapEntry->IsDungeon(), true, true, completedEncounters); if (!state) + { continue; + } state->SetGORespawnTime(loguid, time_t(respawn_time)); diff --git a/src/game/WorldHandlers/MapPersistentStateMgr.h b/src/game/WorldHandlers/MapPersistentStateMgr.h index e778be7f3..10482e82a 100644 --- a/src/game/WorldHandlers/MapPersistentStateMgr.h +++ b/src/game/WorldHandlers/MapPersistentStateMgr.h @@ -93,7 +93,9 @@ class MapPersistentState { m_usedByMap = map; if (!map) + { UnloadIfEmpty(); + } } time_t GetCreatureRespawnTime(uint32 loguid) const @@ -415,15 +417,21 @@ inline void MapPersistentStateManager::DoForAllStatesWithMapId(uint32 mapId, Do& for (PersistentStateMap::iterator itr = m_instanceSaveByInstanceId.begin(); itr != m_instanceSaveByInstanceId.end();) { if (itr->second->GetMapId() == mapId) + { _do((itr++)->second); + } else + { ++itr; + } } } else { if (MapPersistentState* state = GetPersistentState(mapId, 0)) + { _do(state); + } } } diff --git a/src/game/WorldHandlers/MassMailMgr.cpp b/src/game/WorldHandlers/MassMailMgr.cpp index 682453d63..10402afd5 100644 --- a/src/game/WorldHandlers/MassMailMgr.cpp +++ b/src/game/WorldHandlers/MassMailMgr.cpp @@ -110,7 +110,9 @@ void MassMailMgr::Update(bool sendall /*= false*/) task.m_protoMail->SendMailTo(MailReceiver(receiver, receiver_guid), task.m_sender, MAIL_CHECK_MASK_RETURNED); if (!sendall) + { --maxcount; + } break; } @@ -122,11 +124,15 @@ void MassMailMgr::Update(bool sendall /*= false*/) draft.SendMailTo(MailReceiver(receiver, receiver_guid), task.m_sender, MAIL_CHECK_MASK_RETURNED); if (!sendall) + { --maxcount; + } } if (task.m_receivers.empty()) + { m_massMails.pop_front(); + } } while (!m_massMails.empty() && (sendall || maxcount > 0)); } diff --git a/src/game/WorldHandlers/MiscHandler.cpp b/src/game/WorldHandlers/MiscHandler.cpp index e8273eb5f..ea3b025b5 100644 --- a/src/game/WorldHandlers/MiscHandler.cpp +++ b/src/game/WorldHandlers/MiscHandler.cpp @@ -111,7 +111,9 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) recv_data >> zones_count; // zones count, client limit=10 (2.0.10) if (zones_count > 10) + { return; // can't be received from real client or broken packet + } for (uint32 i = 0; i < zones_count; ++i) { @@ -124,7 +126,9 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) recv_data >> str_count; // user entered strings count, client limit=4 (checked on 2.0.10) if (str_count > 4) + { return; // can't be received from real client or broken packet + } DEBUG_LOG("Minlvl %u, maxlvl %u, name %s, guild %s, racemask %u, classmask %u, zones %u, strings %u", level_min, level_max, player_name.c_str(), guild_name.c_str(), racemask, classmask, zones_count, str_count); @@ -135,7 +139,9 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) recv_data >> temp; // user entered string, it used as universal search pattern(guild+player name)? if (!Utf8toWStr(temp, str[i])) + { continue; + } wstrToLower(str[i]); @@ -154,7 +160,9 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) // client send in case not set max level value 100 but mangos support 255 max level, // update it to show GMs with characters after 100 level if (level_max >= MAX_LEVEL) + { level_max = STRONG_MAX_LEVEL; + } Team team = _player->GetTeam(); uint32 security = GetSecurity(); @@ -178,35 +186,49 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) { // player can see member of other team only if CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST if (pl->GetTeam() != team && !allowTwoSideWhoList) + { continue; + } // player can see MODERATOR, GAME MASTER, ADMINISTRATOR only if CONFIG_GM_IN_WHO_LIST if (pl->GetSession()->GetSecurity() > gmLevelInWhoList) + { continue; + } } // do not process players which are not in world if (!pl->IsInWorld()) + { continue; + } // check if target is globally visible for player if (!pl->IsVisibleGloballyFor(_player)) + { continue; + } // check if target's level is in level range uint32 lvl = pl->getLevel(); if (lvl < level_min || lvl > level_max) + { continue; + } // check if class matches classmask uint32 class_ = pl->getClass(); if (!(classmask & (1 << class_))) + { continue; + } // check if race matches racemask uint32 race = pl->getRace(); if (!(racemask & (1 << race))) + { continue; + } uint32 pzoneid = pl->GetZoneId(); uint8 gender = pl->getGender(); @@ -223,29 +245,41 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) z_show = false; } if (!z_show) + { continue; + } std::string pname = pl->GetName(); std::wstring wpname; if (!Utf8toWStr(pname, wpname)) + { continue; + } wstrToLower(wpname); if (!(wplayer_name.empty() || wpname.find(wplayer_name) != std::wstring::npos)) + { continue; + } std::string gname = sGuildMgr.GetGuildNameById(pl->GetGuildId()); std::wstring wgname; if (!Utf8toWStr(gname, wgname)) + { continue; + } wstrToLower(wgname); if (!(wguild_name.empty() || wgname.find(wguild_name) != std::wstring::npos)) + { continue; + } std::string aname; if (AreaTableEntry const* areaEntry = GetAreaEntryByAreaID(pzoneid)) + { aname = areaEntry->area_name[GetSessionDbcLocale()]; + } bool s_show = true; for (uint32 i = 0; i < str_count; ++i) @@ -263,11 +297,15 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) } } if (!s_show) + { continue; + } // 49 is maximum player count sent to client if (++matchcount > 49) + { continue; + } ++displaycount; @@ -281,7 +319,9 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) } if (sWorld.getConfig(CONFIG_UINT32_MAX_WHOLIST_RETURNS) && matchcount > sWorld.getConfig(CONFIG_UINT32_MAX_WHOLIST_RETURNS)) + { matchcount = sWorld.getConfig(CONFIG_UINT32_MAX_WHOLIST_RETURNS); + } data.put(0, displaycount); // insert right count, count displayed data.put(4, matchcount); // insert right count, count of matches @@ -295,7 +335,9 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) DEBUG_LOG("WORLD: Received opcode CMSG_LOGOUT_REQUEST, security %u", GetSecurity()); if (ObjectGuid lootGuid = GetPlayer()->GetLootGuid()) + { DoLootRelease(lootGuid); + } // Can not logout if... if (GetPlayer()->IsInCombat() || //...is in combat @@ -323,7 +365,9 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recv_data*/) { float height = GetPlayer()->GetMap()->GetHeight(GetPlayer()->GetPhaseMask(), GetPlayer()->GetPositionX(), GetPlayer()->GetPositionY(), GetPlayer()->GetPositionZ()); if ((GetPlayer()->GetPositionZ() < height + 0.1f) && !(GetPlayer()->IsInWater())) + { GetPlayer()->SetStandState(UNIT_STAND_STATE_SIT); + } GetPlayer()->SetRoot(true); GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); @@ -385,12 +429,16 @@ void WorldSession::HandleTogglePvP(WorldPacket& recv_data) if (GetPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP)) { if (!GetPlayer()->IsPvP() || GetPlayer()->pvpInfo.endTimer != 0) + { GetPlayer()->UpdatePvP(true, true); + } } else { if (!GetPlayer()->pvpInfo.inHostileArea && GetPlayer()->IsPvP()) + { GetPlayer()->pvpInfo.endTimer = time(NULL); // start toggle-off + } } } @@ -423,7 +471,9 @@ void WorldSession::HandleSetTargetOpcode(WorldPacket& recv_data) } if (FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(unit->getFaction())) + { _player->GetReputationMgr().SetVisible(factionTemplateEntry); + } } void WorldSession::HandleSetSelectionOpcode(WorldPacket& recv_data) @@ -458,7 +508,9 @@ void WorldSession::HandleSetSelectionOpcode(WorldPacket& recv_data) } if (FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(unit->getFaction())) + { _player->GetReputationMgr().SetVisible(factionTemplateEntry); + } } void WorldSession::HandleStandStateChangeOpcode(WorldPacket& recv_data) @@ -526,18 +578,28 @@ void WorldSession::HandleAddFriendOpcodeCallBack(QueryResult* result, uint32 acc if (friendGuid) { if (friendGuid == session->GetPlayer()->GetObjectGuid()) + { friendResult = FRIEND_SELF; + } else if (session->GetPlayer()->GetTeam() != team && !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_ADD_FRIEND) && session->GetSecurity() < SEC_MODERATOR) + { friendResult = FRIEND_ENEMY; + } else if (session->GetPlayer()->GetSocial()->HasFriend(friendGuid)) + { friendResult = FRIEND_ALREADY; + } else { Player* pFriend = ObjectAccessor::FindPlayer(friendGuid); if (pFriend && pFriend->IsInWorld() && pFriend->IsVisibleGloballyFor(session->GetPlayer())) + { friendResult = FRIEND_ADDED_ONLINE; + } else + { friendResult = FRIEND_ADDED_OFFLINE; + } if (!session->GetPlayer()->GetSocial()->AddToSocialList(friendGuid, false)) { @@ -612,16 +674,22 @@ void WorldSession::HandleAddIgnoreOpcodeCallBack(QueryResult* result, uint32 acc if (ignoreGuid) { if (ignoreGuid == session->GetPlayer()->GetObjectGuid()) + { ignoreResult = FRIEND_IGNORE_SELF; + } else if (session->GetPlayer()->GetSocial()->HasIgnore(ignoreGuid)) + { ignoreResult = FRIEND_IGNORE_ALREADY; + } else { ignoreResult = FRIEND_IGNORE_ADDED; // ignore list full if (!session->GetPlayer()->GetSocial()->AddToSocialList(ignoreGuid, true)) + { ignoreResult = FRIEND_IGNORE_FULL; + } } } @@ -664,9 +732,13 @@ void WorldSession::HandleBugOpcode(WorldPacket& recv_data) recv_data >> typelen >> type; if (suggestion == 0) + { DEBUG_LOG("WORLD: Received opcode CMSG_BUG [Bug Report]"); + } else + { DEBUG_LOG("WORLD: Received opcode CMSG_BUG [Suggestion]"); + } DEBUG_LOG("%s", type.c_str()); DEBUG_LOG("%s", content.c_str()); @@ -765,9 +837,13 @@ void WorldSession::HandleReturnToGraveyard(WorldPacket& /*recvPacket*/) // Special handle for battleground maps if (BattleGround* bg = pPlayer->GetBattleGround()) + { ClosestGrave = bg->GetClosestGraveYard(pPlayer); + } else + { ClosestGrave = sObjectMgr.GetClosestGraveYard(pPlayer->GetCorpse()->GetPositionX(), pPlayer->GetCorpse()->GetPositionY(), pPlayer->GetCorpse()->GetPositionZ(), pPlayer->GetCorpse()->GetMapId(), pPlayer->GetTeam()); + } // if no grave found, stay at the current location // and don't show spirit healer location @@ -786,7 +862,9 @@ void WorldSession::HandleReturnToGraveyard(WorldPacket& /*recvPacket*/) } if (updateVisibility && pPlayer->IsInWorld()) + { pPlayer->UpdateVisibilityAndView(); + } } } @@ -839,7 +917,9 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) if (pQuest) { if (player->GetQuestStatus(quest_id) == QUEST_STATUS_INCOMPLETE) + { player->AreaExploredOrEventHappens(quest_id); + } } } @@ -848,7 +928,9 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) { // set resting flag we are in the inn if (player->GetRestType() != REST_TYPE_IN_CITY) + { player->SetRestType(REST_TYPE_IN_TAVERN, Trigger_ID); + } return; } @@ -885,7 +967,9 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) { int32 corpseMapId = 0; if (Corpse* corpse = player->GetCorpse()) + { corpseMapId = corpse->GetMapId(); + } // check back way from corpse to entrance uint32 instance_map = corpseMapId; @@ -893,7 +977,9 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) { // most often fast case if (instance_map == targetMapEntry->MapID) + { break; + } InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(instance_map); instance_map = instance ? instance->parent : 0; @@ -1129,7 +1215,9 @@ void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket& recv_data) must be need use in mangos We substract server Lags to move time ( AntiLags ) for exmaple - GetPlayer()->ModifyLastMoveTime( -int32(time_skipped) ); + { + GetPlayer()->ModifyLastMoveTime( -int32(time_skipped) ); + } */ } @@ -1171,7 +1259,9 @@ void WorldSession::HandleSetActionBarTogglesOpcode(WorldPacket& recv_data) if (!GetPlayer()) // ignore until not logged (check needed because STATUS_AUTHED) { if (ActionBar != 0) + { sLog.outError("WorldSession::HandleSetActionBarToggles in not logged state with value: %u, ignored", uint32(ActionBar)); + } return; } @@ -1236,7 +1326,9 @@ void WorldSession::HandleInspectOpcode(WorldPacket& recvData) data << plr->GetObjectGuid(); if (sWorld.getConfig(CONFIG_BOOL_TALENTS_INSPECTING) || _player->isGameMaster()) + { plr->BuildPlayerTalentsInfoData(&data); + } else { data << uint32(0); // unspentTalentPoints @@ -1324,9 +1416,13 @@ void WorldSession::HandleWorldTeleportOpcode(WorldPacket& recv_data) DEBUG_LOG("Time %u sec, map=%u, x=%f, y=%f, z=%f, orient=%f", time / 1000, mapid, PositionX, PositionY, PositionZ, Orientation); if (GetSecurity() >= SEC_ADMINISTRATOR) + { GetPlayer()->TeleportTo(mapid, PositionX, PositionY, PositionZ, Orientation); + } else + { SendNotification(LANG_YOU_NOT_HAVE_PERMISSION); + } } void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) @@ -1367,13 +1463,19 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) Field* fields = result->Fetch(); std::string acc = fields[0].GetCppString(); if (acc.empty()) + { acc = "Unknown"; + } std::string email = fields[1].GetCppString(); if (email.empty()) + { email = "Unknown"; + } std::string lastip = fields[2].GetCppString(); if (lastip.empty()) + { lastip = "Unknown"; + } std::string msg = charname + "'s " + "account is " + acc + ", e-mail: " + email + ", last ip: " + lastip; @@ -1490,7 +1592,9 @@ void WorldSession::HandleSetTitleOpcode(WorldPacket& recv_data) } } else + { title = 0; + } GetPlayer()->SetUInt32Value(PLAYER_CHOSEN_TITLE, title); } @@ -1522,10 +1626,14 @@ void WorldSession::HandleResetInstancesOpcode(WorldPacket& /*recv_data*/) if (Group* pGroup = _player->GetGroup()) { if (pGroup->IsLeader(_player->GetObjectGuid())) + { pGroup->ResetInstances(INSTANCE_RESET_ALL, false, _player); + } } else + { _player->ResetInstances(INSTANCE_RESET_ALL, false); + } } void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recv_data) @@ -1812,7 +1920,9 @@ void WorldSession::HandleObjectUpdateFailedOpcode(WorldPacket& recvPacket) if (_player->IsInWorld()) { if (WorldObject* obj = _player->GetMap()->GetWorldObject(guid)) + { obj->SendCreateUpdateToPlayer(_player); + } } else { diff --git a/src/game/WorldHandlers/MoveMap.cpp b/src/game/WorldHandlers/MoveMap.cpp index 5449d2a08..c630529e1 100644 --- a/src/game/WorldHandlers/MoveMap.cpp +++ b/src/game/WorldHandlers/MoveMap.cpp @@ -354,7 +354,9 @@ namespace MMAP uint32 x = (i->first >> 16); uint32 y = (i->first & 0x0000FFFF); if (DT_SUCCESS != mmap->navMesh->removeTile(i->second, NULL, NULL)) + { sLog.outError("MMAP:unloadMap: Could not unload %03u%02i%02i.mmtile from navmesh", mapId, x, y); + } else { --loadedTiles; diff --git a/src/game/WorldHandlers/MoveMap.h b/src/game/WorldHandlers/MoveMap.h index fca23d18e..ed32745c7 100644 --- a/src/game/WorldHandlers/MoveMap.h +++ b/src/game/WorldHandlers/MoveMap.h @@ -62,7 +62,9 @@ namespace MMAP } if (navMesh) + { dtFreeNavMesh(navMesh); + } } dtNavMesh* navMesh; diff --git a/src/game/WorldHandlers/MovementHandler.cpp b/src/game/WorldHandlers/MovementHandler.cpp index 556f0fe77..54adf1255 100644 --- a/src/game/WorldHandlers/MovementHandler.cpp +++ b/src/game/WorldHandlers/MovementHandler.cpp @@ -83,7 +83,9 @@ void WorldSession::HandleMoveWorldportAckOpcode() if (mEntry->IsBattleGroundOrArena()) { if (GetPlayer()->GetBattleGroundId()) + { map = sMapMgr.FindMap(loc.mapid, GetPlayer()->GetBattleGroundId()); + } if (!map) { @@ -108,13 +110,17 @@ void WorldSession::HandleMoveWorldportAckOpcode() // reset instance validity, except if going to an instance inside an instance if (GetPlayer()->m_InstanceValid == false && !mInstance) + { GetPlayer()->m_InstanceValid = true; + } GetPlayer()->SetSemaphoreTeleportFar(false); // relocate the player to the teleport destination if (!map) + { map = sMapMgr.CreateMap(loc.mapid, GetPlayer()); + } GetPlayer()->SetMap(map); GetPlayer()->Relocate(loc.coord_x, loc.coord_y, loc.coord_z, loc.orientation); @@ -157,7 +163,9 @@ void WorldSession::HandleMoveWorldportAckOpcode() else if (BattleGround* bg = _player->GetBattleGround()) { if (_player->IsInvitedForBattleGroundInstance(_player->GetBattleGroundId())) + { bg->AddPlayer(_player); + } } } @@ -222,7 +230,9 @@ void WorldSession::HandleMoveWorldportAckOpcode() if (entry->Id != aura->GetModifier()->m_amount) { if (MountCapabilityEntry const* oldEntry = sMountCapabilityStore.LookupEntry(aura->GetModifier()->m_amount)) + { _player->RemoveAurasDueToSpell(oldEntry->SpeedModSpell); + } _player->CastSpell(_player, entry->SpeedModSpell, true); @@ -252,7 +262,9 @@ void WorldSession::HandleMoveWorldportAckOpcode() // honorless target if (GetPlayer()->pvpInfo.inHostileArea) + { GetPlayer()->CastSpell(GetPlayer(), 2479, true); + } // resummon pet GetPlayer()->ResummonPetTemporaryUnSummonedIfAny(); @@ -305,7 +317,9 @@ void WorldSession::HandleMoveTeleportAckOpcode(WorldPacket& recv_data) { // honorless target if (plMover->pvpInfo.inHostileArea) + { plMover->CastSpell(plMover, 2479, true); + } } // resummon pet @@ -346,17 +360,23 @@ void WorldSession::HandleMovementOpcodes(WorldPacket& recv_data) // fall damage generation (ignore in flight case that can be triggered also at lags in moment teleportation to another map). if (opcode == MSG_MOVE_FALL_LAND && plMover && !plMover->IsTaxiFlying()) + { plMover->HandleFall(movementInfo); + } /* process position-change */ HandleMoverRelocation(movementInfo); if (plMover) + { plMover->UpdateFallInformationIfNeed(movementInfo, opcode); + } // stop some emotes at player move if (mover && (mover->GetUInt32Value(UNIT_NPC_EMOTESTATE) != 0)) + { mover->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_ONESHOT_NONE); + } WorldPacket data(SMSG_PLAYER_MOVE, recv_data.size()); data << movementInfo; @@ -456,7 +476,9 @@ void WorldSession::HandleSetActiveMoverOpcode(WorldPacket& recv_data) else { if (Unit* mover = ObjectAccessor::GetUnit(*GetPlayer(), guid)) + { _player->SetMover(mover); + } } } @@ -618,7 +640,9 @@ bool WorldSession::VerifyMovementInfo(MovementInfo const& movementInfo, ObjectGu void WorldSession::HandleMoverRelocation(MovementInfo& movementInfo) { if (m_clientTimeDelay == 0) + { m_clientTimeDelay = WorldTimer::getMSTime() - movementInfo.GetTime(); + } movementInfo.UpdateTime(movementInfo.GetTime() + m_clientTimeDelay + MOVEMENT_PACKET_TIME_DELAY); Unit* mover = _player->GetMover(); @@ -659,7 +683,9 @@ void WorldSession::HandleMoverRelocation(MovementInfo& movementInfo) /* Movement should cancel looting */ if(ObjectGuid lootGUID = plMover->GetLootGuid()) + { plMover->SendLootRelease(lootGUID); + } if (movementInfo.GetPos()->z < -500.0f) { @@ -694,6 +720,8 @@ void WorldSession::HandleMoverRelocation(MovementInfo& movementInfo) else // creature charmed { if (mover->IsInWorld()) + { mover->GetMap()->CreatureRelocation((Creature*)mover, movementInfo.GetPos()->x, movementInfo.GetPos()->y, movementInfo.GetPos()->z, movementInfo.GetPos()->o); + } } } diff --git a/src/game/WorldHandlers/NPCHandler.cpp b/src/game/WorldHandlers/NPCHandler.cpp index 5fd307d4c..8b4206b09 100644 --- a/src/game/WorldHandlers/NPCHandler.cpp +++ b/src/game/WorldHandlers/NPCHandler.cpp @@ -199,7 +199,9 @@ void WorldSession::SendTrainerList(ObjectGuid guid, const std::string& strTitle) uint32 reqLevel = 0; if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell, &reqLevel)) + { continue; + } reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel); @@ -219,7 +221,9 @@ void WorldSession::SendTrainerList(ObjectGuid guid, const std::string& strTitle) uint32 reqLevel = 0; if (!_player->IsSpellFitByClassAndRace(tSpell->learnedSpell, &reqLevel)) + { continue; + } reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel); @@ -257,41 +261,55 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recv_data) uint32 trainState = 2; if (!unit->IsTrainerOf(_player, true)) + { trainState = 1; + } // check present spell in trainer spell list TrainerSpellData const* cSpells = unit->GetTrainerSpells(); TrainerSpellData const* tSpells = unit->GetTrainerTemplateSpells(); if (!cSpells && !tSpells) + { trainState = 1; + } // Try find spell in npc_trainer TrainerSpell const* trainer_spell = cSpells ? cSpells->Find(spellId) : NULL; // Not found, try find in npc_trainer_template if (!trainer_spell && tSpells) + { trainer_spell = tSpells->Find(spellId); + } // Not found anywhere, cheating? if (!trainer_spell) + { trainState = 1; + } // can't be learn, cheat? Or double learn with lags... uint32 reqLevel = 0; if (!_player->IsSpellFitByClassAndRace(trainer_spell->learnedSpell, &reqLevel)) + { trainState = 1; + } reqLevel = trainer_spell->isProvidedReqLevel ? trainer_spell->reqLevel : std::max(reqLevel, trainer_spell->reqLevel); if (_player->GetTrainerSpellState(trainer_spell, reqLevel) != TRAINER_SPELL_GREEN) + { trainState = 1; + } // apply reputation discount uint32 nSpellCost = uint32(floor(trainer_spell->spellCost * _player->GetReputationPriceDiscount(unit))); // check money requirement if (_player->GetMoney() < nSpellCost && trainState > 1) + { trainState = 0; + } if (trainState != 2) { @@ -316,9 +334,13 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recv_data) // learn explicitly or cast explicitly // TODO - Are these spells really cast correctly this way? if (trainer_spell->IsCastable()) + { _player->CastSpell(_player, trainer_spell->spell, true); + } else + { _player->learnSpell(spellId, false); + } sendData << ObjectGuid(guid); sendData << uint32(spellId); // should be same as in packet from client @@ -344,7 +366,9 @@ void WorldSession::HandleGossipHelloOpcode(WorldPacket& recv_data) pCreature->StopMoving(); if (pCreature->IsSpiritGuide()) + { pCreature->SendAreaSpiritHealerQueryOpcode(_player); + } if (!sScriptMgr.OnGossipHello(_player, pCreature)) { @@ -384,7 +408,9 @@ void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recv_data) } if (!sScriptMgr.OnGossipSelect(_player, pCreature, sender, action, code.empty() ? NULL : code.c_str())) + { _player->OnGossipSelect(pCreature, gossipListId, menuId); + } } else if (guid.IsGameObject()) { @@ -397,7 +423,9 @@ void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recv_data) } if (!sScriptMgr.OnGossipSelect(_player, pGo, sender, action, code.empty() ? NULL : code.c_str())) + { _player->OnGossipSelect(pGo, gossipListId, menuId); + } } } @@ -442,7 +470,9 @@ void WorldSession::SendSpiritResurrect() _player->GetPositionX(), _player->GetPositionY(), _player->GetPositionZ(), _player->GetMapId(), _player->GetTeam()); if (corpseGrave != ghostGrave) + { _player->TeleportTo(corpseGrave->map_id, corpseGrave->x, corpseGrave->y, corpseGrave->z, _player->GetOrientation()); + } // or update at original position else { @@ -677,7 +707,9 @@ void WorldSession::HandleStablePet(WorldPacket& recv_data) // slots ordered in query, and if not equal then free if (slot != free_slot) + { break; + } // this slot not free, skip ++free_slot; @@ -693,7 +725,9 @@ void WorldSession::HandleStablePet(WorldPacket& recv_data) SendStableResult(STABLE_SUCCESS_STABLE); } else + { SendStableResult(STABLE_ERR_STABLE); + } } void WorldSession::HandleUnstablePet(WorldPacket& recv_data) @@ -734,9 +768,13 @@ void WorldSession::HandleUnstablePet(WorldPacket& recv_data) { // if problem in exotic pet if (creatureInfo && creatureInfo->isTameable(true)) + { SendStableResult(STABLE_ERR_EXOTIC); + } else + { SendStableResult(STABLE_ERR_STABLE); + } return; } @@ -749,7 +787,9 @@ void WorldSession::HandleUnstablePet(WorldPacket& recv_data) // delete dead pet if (pet) + { pet->Unsummon(PET_SAVE_AS_DELETED, _player); + } Pet* newpet = new Pet(HUNTER_PET); if (!newpet->LoadPetFromDB(_player, creature_id, petnumber)) @@ -830,9 +870,13 @@ void WorldSession::HandleStableSwapPet(WorldPacket& recv_data) { // if problem in exotic pet if (creatureInfo && creatureInfo->isTameable(true)) + { SendStableResult(STABLE_ERR_EXOTIC); + } else + { SendStableResult(STABLE_ERR_STABLE); + } return; } @@ -847,7 +891,9 @@ void WorldSession::HandleStableSwapPet(WorldPacket& recv_data) SendStableResult(STABLE_ERR_STABLE); } else + { SendStableResult(STABLE_SUCCESS_UNSTABLE); + } } void WorldSession::HandleRepairItemOpcode(WorldPacket& recv_data) @@ -878,7 +924,9 @@ void WorldSession::HandleRepairItemOpcode(WorldPacket& recv_data) Item* item = _player->GetItemByGuid(itemGuid); if (item) + { TotalCost = _player->DurabilityRepair(item->GetPos(), true, discountMod, (guildBank > 0)); + } } else { diff --git a/src/game/WorldHandlers/ObjectGridLoader.cpp b/src/game/WorldHandlers/ObjectGridLoader.cpp index f2bbf053d..1e0f9e8f1 100644 --- a/src/game/WorldHandlers/ObjectGridLoader.cpp +++ b/src/game/WorldHandlers/ObjectGridLoader.cpp @@ -135,12 +135,16 @@ void LoadHelper(CellGuidSet const& guid_set, CellPair& cell, GridRefManager& obj->SetMap(map); obj->AddToWorld(); if (obj->IsActiveObject()) + { map->AddToActive(obj); + } obj->GetViewPoint().Event_AddedToWorld(&grid); if (bg) + { bg->OnObjectDBLoad(obj); + } ++count; } @@ -156,13 +160,17 @@ void LoadHelper(CellCorpseSet const& cell_corpses, CellPair& cell, CorpseMapType for (CellCorpseSet::const_iterator itr = cell_corpses.begin(); itr != cell_corpses.end(); ++itr) { if (itr->second != map->GetInstanceId()) + { continue; + } uint32 player_lowguid = itr->first; Corpse* obj = sObjectAccessor.GetCorpseForPlayerGUID(ObjectGuid(HIGHGUID_PLAYER, player_lowguid)); if (!obj) + { continue; + } grid.AddWorldObject(obj); @@ -170,7 +178,9 @@ void LoadHelper(CellCorpseSet const& cell_corpses, CellPair& cell, CorpseMapType obj->SetMap(map); obj->AddToWorld(); if (obj->IsActiveObject()) + { map->AddToActive(obj); + } ++count; } @@ -287,7 +297,9 @@ ObjectGridUnloader::Visit(GridRefManager &m) T* obj = m.getFirst()->getSource(); // if option set then object already saved at this moment if (!sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY)) + { obj->SaveRespawnTime(); + } ///- object must be out of world before delete obj->RemoveFromWorld(); ///- object will get delinked from the manager when deleted diff --git a/src/game/WorldHandlers/PetHandler.cpp b/src/game/WorldHandlers/PetHandler.cpp index 50740ec8f..8e180cc96 100644 --- a/src/game/WorldHandlers/PetHandler.cpp +++ b/src/game/WorldHandlers/PetHandler.cpp @@ -144,12 +144,16 @@ void WorldSession::HandlePetAction(WorldPacket& recv_data) ((Creature*)pet)->AI()->AttackStart(targetUnit); // 10% chance to play special warlock pet attack talk, else growl if (((Creature*)pet)->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && roll_chance_i(10)) + { pet->SendPetTalk((uint32)PET_TALK_ATTACK); + } pet->SendPetAIReaction(); } else + { pet->Attack(targetUnit, true); + } } } @@ -163,13 +167,17 @@ void WorldSession::HandlePetAction(WorldPacket& recv_data) { Pet* p = (Pet*)petC; if (p->getPetType() == HUNTER_PET) + { p->Unsummon(PET_SAVE_AS_DELETED, _player); + } else // dismissing a summoned pet is like killing them (this prevents returning a soulshard...) p->SetDeathState(CORPSE); } else // charmed + { _player->Uncharm(); + } if (petC->IsTemporarySummon()) // special case when pet was temporary summon through DoSummonPossesed { @@ -226,7 +234,9 @@ void WorldSession::HandlePetAction(WorldPacket& recv_data) { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if (!spellEffect) + { continue; + } if (spellEffect->EffectImplicitTargetA == TARGET_ALL_ENEMY_IN_AREA || spellEffect->EffectImplicitTargetA == TARGET_ALL_ENEMY_IN_AREA_INSTANT @@ -263,7 +273,9 @@ void WorldSession::HandlePetAction(WorldPacket& recv_data) ((Creature*)pet)->AI()->AttackStart(unit_target); // 10% chance to play special warlock pet attack talk, else growl if (((Creature*)pet)->IsPet() && ((Pet*)pet)->getPetType() == SUMMON_PET && pet != unit_target && roll_chance_i(10)) + { pet->SendPetTalk((uint32)PET_TALK_ATTACK); + } pet->SendPetAIReaction(); @@ -277,17 +289,23 @@ void WorldSession::HandlePetAction(WorldPacket& recv_data) { pet->SetInFront(unit_target); if (unit_target->GetTypeId() == TYPEID_PLAYER) + { pet->SendCreateUpdateToPlayer((Player*)unit_target); + } } else if (Unit* unit_target2 = spell->m_targets.getUnitTarget()) { pet->SetInFront(unit_target2); if (unit_target2->GetTypeId() == TYPEID_PLAYER) + { pet->SendCreateUpdateToPlayer((Player*)unit_target2); + } } if (Unit* powner = pet->GetCharmerOrOwner()) if (powner->GetTypeId() == TYPEID_PLAYER) + { pet->SendCreateUpdateToPlayer((Player*)powner); + } result = SPELL_CAST_OK; } @@ -303,16 +321,22 @@ void WorldSession::HandlePetAction(WorldPacket& recv_data) else { if (pet->HasAuraType(SPELL_AURA_MOD_POSSESS)) + { Spell::SendCastResult(GetPlayer(), spellInfo, 0, result); + } else { Unit* owner = pet->GetCharmerOrOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER) + { Spell::SendCastResult((Player*)owner, spellInfo, 0, result, true); + } } if (!((Creature*)pet)->HasSpellCooldown(spellid)) + { GetPlayer()->SendClearCooldown(spellid, pet); + } ((Pet*)pet)->SetSpellOpener(); spell->finish(false); @@ -403,7 +427,9 @@ void WorldSession::SendPetNameQuery(ObjectGuid petguid, uint32 petnumber) } } else + { data << uint8(0); + } _player->GetSession()->SendPacket(&data); } @@ -509,17 +535,25 @@ void WorldSession::HandlePetSetAction(WorldPacket& recv_data) if (act_state == ACT_ENABLED && spell_id) { if (pet->IsCharmed()) + { charmInfo->ToggleCreatureAutocast(spell_id, true); + } else + { ((Pet*)pet)->ToggleAutocast(spell_id, true); + } } // sign for no/turn off autocast else if (act_state == ACT_DISABLED && spell_id) { if (pet->IsCharmed()) + { charmInfo->ToggleCreatureAutocast(spell_id, false); + } else + { ((Pet*)pet)->ToggleAutocast(spell_id, false); + } } charmInfo->SetActionBar(position[i], spell_id, ActiveStates(act_state)); @@ -564,7 +598,9 @@ void WorldSession::HandlePetRename(WorldPacket& recv_data) pet->SetName(name); if (_player->GetGroup()) + { _player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_NAME); + } pet->RemoveByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED); @@ -619,7 +655,9 @@ void WorldSession::HandlePetAbandon(WorldPacket& recv_data) if (Creature* pet = _player->GetMap()->GetAnyTypeCreature(guid)) { if (pet->IsPet()) + { ((Pet*)pet)->Unsummon(PET_SAVE_AS_DELETED, _player); + } else if (pet->GetObjectGuid() == _player->GetCharmGuid()) { _player->Uncharm(); @@ -690,7 +728,9 @@ void WorldSession::HandlePetSpellAutocastOpcode(WorldPacket& recvPacket) // state can be used as boolean pet->GetCharmInfo()->ToggleCreatureAutocast(spellid, state); else + { ((Pet*)pet)->ToggleAutocast(spellid, state); + } charmInfo->SetSpellAutocast(spellid, state); } @@ -758,10 +798,14 @@ void WorldSession::HandlePetCastSpellOpcode(WorldPacket& recvPacket) { Unit* owner = pet->GetCharmerOrOwner(); if (owner && owner->GetTypeId() == TYPEID_PLAYER && !triggeredByAura) + { Spell::SendCastResult((Player*)owner, spellInfo, 0, result, true); + } if (!pet->HasSpellCooldown(spellid) && !triggeredByAura) + { GetPlayer()->SendClearCooldown(spellid, pet); + } spell->finish(false); delete spell; @@ -782,7 +826,9 @@ void WorldSession::SendPetNameInvalid(uint32 error, const std::string& name, Dec } } else + { data << uint8(0); + } SendPacket(&data); } @@ -837,6 +883,8 @@ void WorldSession::HandleDismissCritter(WorldPacket& recvData) if (_player->GetCritterGuid() == guid) { if (pet->GetTypeId() == TYPEID_UNIT && ((Creature*)pet)->IsTemporarySummon()) + { ((TemporarySummon*)pet)->UnSummon(); + } } } diff --git a/src/game/WorldHandlers/PetitionsHandler.cpp b/src/game/WorldHandlers/PetitionsHandler.cpp index ce46b225c..7066db5aa 100644 --- a/src/game/WorldHandlers/PetitionsHandler.cpp +++ b/src/game/WorldHandlers/PetitionsHandler.cpp @@ -204,7 +204,9 @@ void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recv_data) // result==NULL also correct in case no sign yet if (result) + { signs = (uint8)result->GetRowCount(); + } DEBUG_LOG("CMSG_PETITION_SHOW_SIGNATURES petition: %s", petitionguid.GetString().c_str()); @@ -287,7 +289,9 @@ void WorldSession::SendPetitionQueryOpcode(ObjectGuid petitionguid) data << uint32(0); // 13 count of next strings? for (int i = 0; i < 10; ++i) + { data << uint8(0); // some string + } data << uint32(0); // 14 data << uint32(0); // 15 0 - guild, 1 - arena team @@ -419,7 +423,9 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recv_data) // update for owner if online if (Player* owner = sObjectMgr.GetPlayer(ownerGuid)) + { owner->SendPetitionSignResult(petitionGuid, _player, PETITION_SIGN_ALREADY_SIGNED); + } return; } else if (playerGuid == _player->GetObjectGuid()) @@ -429,7 +435,9 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recv_data) // update for owner if online if (Player* owner = sObjectMgr.GetPlayer(ownerGuid)) + { owner->SendPetitionSignResult(petitionGuid, _player, PETITION_SIGN_ALREADY_SIGNED_OTHER); + } return; } } @@ -449,7 +457,9 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recv_data) // update for owner if online if (Player* owner = sObjectMgr.GetPlayer(ownerGuid)) + { owner->SendPetitionSignResult(petitionGuid, _player, PETITION_SIGN_OK); + } } void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recv_data) @@ -533,7 +543,9 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recv_data) result = CharacterDatabase.PQuery("SELECT `playerguid` FROM `petition_sign` WHERE `petitionguid` = '%u'", petitionGuid.GetCounter()); // result==NULL also correct charter without signs if (result) + { signs = (uint8)result->GetRowCount(); + } /// Send response WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8 + 8 + 4 + signs + signs * 12)); @@ -648,7 +660,9 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) ObjectGuid signGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (!signGuid) + { continue; + } guild->AddMember(signGuid, guild->GetLowestRank()); result->NextRow(); diff --git a/src/game/WorldHandlers/PoolManager.cpp b/src/game/WorldHandlers/PoolManager.cpp index e2deafe14..5109d0c9b 100644 --- a/src/game/WorldHandlers/PoolManager.cpp +++ b/src/game/WorldHandlers/PoolManager.cpp @@ -92,7 +92,9 @@ void SpawnedPoolData::RemoveSpawn(uint32 db_guid, uint32 pool_id) mSpawnedCreatures.erase(db_guid); uint32& val = mSpawnedPools[pool_id]; if (val > 0) + { --val; + } } template<> @@ -101,7 +103,9 @@ void SpawnedPoolData::RemoveSpawn(uint32 db_guid, uint32 pool_id) mSpawnedGameobjects.erase(db_guid); uint32& val = mSpawnedPools[pool_id]; if (val > 0) + { --val; + } } template<> @@ -110,7 +114,9 @@ void SpawnedPoolData::RemoveSpawn(uint32 sub_pool_id, uint32 pool_id) mSpawnedPools.erase(sub_pool_id); uint32& val = mSpawnedPools[pool_id]; if (val > 0) + { --val; + } } //////////////////////////////////////////////////////////// @@ -145,9 +151,13 @@ template void PoolGroup::AddEntry(PoolObject& poolitem, uint32 maxentries) { if (poolitem.chance != 0 && maxentries == 1) + { ExplicitlyChanced.push_back(poolitem); + } else + { EqualChanced.push_back(poolitem); + } } // Method to check the chances are proper in this object pool @@ -288,7 +298,9 @@ void PoolGroup::Despawn1Object(MapPersistentState& mapState, uint32 gu if (Map* dataMap = dataMapState->GetMap()) if (Creature* pCreature = dataMap->GetCreature(data->GetObjectGuid(guid))) + { pCreature->AddObjectToRemoveList(); + } } } } @@ -306,7 +318,9 @@ void PoolGroup::Despawn1Object(MapPersistentState& mapState, uint32 if (Map* dataMap = dataMapState->GetMap()) if (GameObject* pGameobject = dataMap->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, guid))) + { pGameobject->AddObjectToRemoveList(); + } } } } @@ -354,9 +368,13 @@ void PoolGroup::SpawnObject(MapPersistentState& mapState, uint32 limit, uint3 if (triggerFrom) { if (spawns.IsSpawnedObject(triggerFrom)) + { ++count; + } else + { triggerFrom = 0; + } } // This will try to spawn the rest of pool, not guaranteed @@ -364,9 +382,13 @@ void PoolGroup::SpawnObject(MapPersistentState& mapState, uint32 limit, uint3 { PoolObject* obj = RollOne(spawns, triggerFrom); if (!obj) + { continue; + } if (obj->guid == lastDespawned) + { continue; + } if (obj->guid == triggerFrom) { @@ -420,7 +442,9 @@ void PoolGroup::Spawn1Object(MapPersistentState& mapState, PoolObject* { pCreature->SetRespawnTime(pCreature->GetRespawnDelay()); if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY) || pCreature->IsWorldBoss()) + { pCreature->SaveRespawnTime(); + } } dataMap->Add(pCreature); } @@ -466,7 +490,9 @@ void PoolGroup::Spawn1Object(MapPersistentState& mapState, PoolObjec { pGameobject->SetRespawnTime(pGameobject->GetRespawnDelay()); if (sWorld.getConfig(CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY)) + { pGameobject->SaveRespawnTime(); + } } dataMap->Add(pGameobject); } @@ -477,7 +503,9 @@ void PoolGroup::Spawn1Object(MapPersistentState& mapState, PoolObjec { // for spawned by default object only if (data->spawntimesecs >= 0) + { dataMapState->SaveGORespawnTime(obj->guid, time(NULL) + data->spawntimesecs); + } } } } @@ -500,7 +528,9 @@ void PoolGroup::ReSpawn1Object(MapPersistentState& mapState, PoolObjec if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : sMapPersistentStateMgr.GetPersistentState(data->mapid, 0)) if (Map* dataMap = dataMapState->GetMap()) if (Creature* pCreature = dataMap->GetCreature(data->GetObjectGuid(obj->guid))) + { pCreature->GetMap()->Add(pCreature); + } } } @@ -514,7 +544,9 @@ void PoolGroup::ReSpawn1Object(MapPersistentState& mapState, PoolObj if (MapPersistentState* dataMapState = mapState.GetMapId() == data->mapid ? &mapState : sMapPersistentStateMgr.GetPersistentState(data->mapid, 0)) if (Map* dataMap = dataMapState->GetMap()) if (GameObject* pGameobject = dataMap->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, obj->guid))) + { pGameobject->GetMap()->Add(pGameobject); + } } } @@ -683,7 +715,9 @@ void PoolManager::LoadFromDB() } if (!mapChecker.CheckAndRemember(data->mapid, pool_id, "pool_creature", "creature guid")) + { continue; + } PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id]; @@ -755,7 +789,9 @@ void PoolManager::LoadFromDB() } if (!mapChecker.CheckAndRemember(data->mapid, pool_id, "pool_creature_template", "creature guid")) + { continue; + } PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id]; @@ -830,7 +866,9 @@ void PoolManager::LoadFromDB() } if (!mapChecker.CheckAndRemember(data->mapid, pool_id, "pool_gameobject", "gameobject guid")) + { continue; + } PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id]; @@ -912,7 +950,9 @@ void PoolManager::LoadFromDB() } if (!mapChecker.CheckAndRemember(data->mapid, pool_id, "pool_gameobject_template", "gameobject guid")) + { continue; + } PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id]; @@ -1058,7 +1098,9 @@ void PoolManager::Initialize(MapPersistentState* state) // spawn pools for expected map or for not initialized shared pools state for non-instanceable maps for (uint16 pool_entry = 0; pool_entry < mPoolTemplate.size(); ++pool_entry) if (mPoolTemplate[pool_entry].AutoSpawn) + { InitSpawnPool(*state, pool_entry); + } } // Call to spawn a pool, if cache if true the method will spawn only if cached entry is different @@ -1067,7 +1109,9 @@ template<> void PoolManager::SpawnPoolGroup(MapPersistentState& mapState, uint16 pool_id, uint32 db_guid, bool instantly) { if (!mPoolCreatureGroups[pool_id].isEmpty()) + { mPoolCreatureGroups[pool_id].SpawnObject(mapState, mPoolTemplate[pool_id].MaxLimit, db_guid, instantly); + } } // Call to spawn a pool, if cache if true the method will spawn only if cached entry is different @@ -1076,7 +1120,9 @@ template<> void PoolManager::SpawnPoolGroup(MapPersistentState& mapState, uint16 pool_id, uint32 db_guid, bool instantly) { if (!mPoolGameobjectGroups[pool_id].isEmpty()) + { mPoolGameobjectGroups[pool_id].SpawnObject(mapState, mPoolTemplate[pool_id].MaxLimit, db_guid, instantly); + } } // Call to spawn a pool, if cache if true the method will spawn only if cached entry is different @@ -1085,7 +1131,9 @@ template<> void PoolManager::SpawnPoolGroup(MapPersistentState& mapState, uint16 pool_id, uint32 sub_pool_id, bool instantly) { if (!mPoolPoolGroups[pool_id].isEmpty()) + { mPoolPoolGroups[pool_id].SpawnObject(mapState, mPoolTemplate[pool_id].MaxLimit, sub_pool_id, instantly); + } } /*! @@ -1101,13 +1149,19 @@ void PoolManager::SpawnPool(MapPersistentState& mapState, uint16 pool_id, bool i void PoolManager::DespawnPool(MapPersistentState& mapState, uint16 pool_id) { if (!mPoolCreatureGroups[pool_id].isEmpty()) + { mPoolCreatureGroups[pool_id].DespawnObject(mapState); + } if (!mPoolGameobjectGroups[pool_id].isEmpty()) + { mPoolGameobjectGroups[pool_id].DespawnObject(mapState); + } if (!mPoolPoolGroups[pool_id].isEmpty()) + { mPoolPoolGroups[pool_id].DespawnObject(mapState); + } } // Method that check chance integrity of the creatures and gameobjects in this pool @@ -1147,9 +1201,13 @@ template void PoolManager::UpdatePool(MapPersistentState& mapState, uint16 pool_id, uint32 db_guid_or_pool_id) { if (uint16 motherpoolid = IsPartOfAPool(pool_id)) + { SpawnPoolGroup(mapState, motherpoolid, pool_id, false); + } else + { SpawnPoolGroup(mapState, pool_id, db_guid_or_pool_id, false); + } } template void PoolManager::UpdatePool(MapPersistentState& mapState, uint16 pool_id, uint32 db_guid_or_pool_id); @@ -1219,7 +1277,9 @@ void PoolManager::InitSpawnPool(MapPersistentState& mapState, uint16 pool_id) { // spawn pool for expected map or for not initialized shared pools state for non-instanceable maps if (mPoolTemplate[pool_id].CanBeSpawnedAtMap(mapState.GetMapEntry())) + { SpawnPool(mapState, pool_id, true); + } } template diff --git a/src/game/WorldHandlers/PoolManager.h b/src/game/WorldHandlers/PoolManager.h index ea9aa42d3..db6dc6a20 100644 --- a/src/game/WorldHandlers/PoolManager.h +++ b/src/game/WorldHandlers/PoolManager.h @@ -154,7 +154,9 @@ class PoolManager if (uint16 pool_id = IsPartOfAPool(db_guid_or_pool_id)) { if (uint16 top_pool_id = IsPartOfTopPool(pool_id)) + { return top_pool_id; + } return pool_id; } @@ -222,7 +224,9 @@ inline uint16 PoolManager::IsPartOfAPool(uint32 db_guid) const { SearchMap::const_iterator itr = mCreatureSearchMap.find(db_guid); if (itr != mCreatureSearchMap.end()) + { return itr->second; + } return 0; } @@ -233,7 +237,9 @@ inline uint16 PoolManager::IsPartOfAPool(uint32 db_guid) const { SearchMap::const_iterator itr = mGameobjectSearchMap.find(db_guid); if (itr != mGameobjectSearchMap.end()) + { return itr->second; + } return 0; } @@ -244,7 +250,9 @@ inline uint16 PoolManager::IsPartOfAPool(uint32 pool_id) const { SearchMap::const_iterator itr = mPoolSearchMap.find(pool_id); if (itr != mPoolSearchMap.end()) + { return itr->second; + } return 0; } diff --git a/src/game/WorldHandlers/QueryHandler.cpp b/src/game/WorldHandlers/QueryHandler.cpp index c7d7f75fe..c5ff3bf1c 100644 --- a/src/game/WorldHandlers/QueryHandler.cpp +++ b/src/game/WorldHandlers/QueryHandler.cpp @@ -65,7 +65,9 @@ void WorldSession::SendNameQueryOpcode(Player* p) } } else + { data << uint8(0); // is not declined + } SendPacket(&data); } @@ -107,7 +109,9 @@ void WorldSession::SendNameQueryOpcodeFromDBCallBack(QueryResult* result, uint32 std::string name = fields[1].GetCppString(); uint8 pRace = 0, pGender = 0, pClass = 0; if (name.empty()) + { name = session->GetMangosString(LANG_NON_EXIST_CHARACTER); + } else { pRace = fields[2].GetUInt8(); @@ -135,7 +139,9 @@ void WorldSession::SendNameQueryOpcodeFromDBCallBack(QueryResult* result, uint32 } } else + { data << uint8(0); // is not declined + } session->SendPacket(&data); delete result; @@ -150,9 +156,13 @@ void WorldSession::HandleNameQueryOpcode(WorldPacket& recv_data) Player* pChar = sObjectMgr.GetPlayer(guid); if (pChar) + { SendNameQueryOpcode(pChar); + } else + { SendNameQueryOpcodeFromDB(guid); + } } void WorldSession::HandleQueryTimeOpcode(WorldPacket & /*recv_data*/) @@ -184,7 +194,9 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket& recv_data) data << name; for (uint8 i = 0; i < 7; ++i) + { data << uint8(0); // name2, name3, name4, always empty + } data << subName; data << ci->IconName; // "Directions" for guard, string for Icons 2.3.0 @@ -205,7 +217,9 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket& recv_data) data << float(ci->PowerMultiplier); // power modifier data << uint8(ci->RacialLeader); for (uint32 i = 0; i < 6; ++i) + { data << uint32(ci->QuestItems[i]); // itemId[6], quest drop + } data << uint32(ci->MovementTemplateId); // CreatureMovementInfo.dbc data << uint32(0); //unk SendPacket(&data); @@ -248,9 +262,13 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket& recv_data) if (gl) { if (gl->Name.size() > size_t(loc_idx) && !gl->Name[loc_idx].empty()) + { Name = gl->Name[loc_idx]; + } if (gl->CastBarCaption.size() > size_t(loc_idx) && !gl->CastBarCaption[loc_idx].empty()) + { CastBarCaption = gl->CastBarCaption[loc_idx]; + } } } DETAIL_LOG("WORLD: CMSG_GAMEOBJECT_QUERY '%s' - Entry: %u. ", info->name, entryID); @@ -266,7 +284,9 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket& recv_data) data.append(info->raw.data, 24); data << float(info->size); // go size for (uint32 i = 0; i < 6; ++i) + { data << uint32(info->questItems[i]); // itemId[6], quest drop + } SendPacket(&data); DEBUG_LOG("WORLD: Sent SMSG_GAMEOBJECT_QUERY_RESPONSE"); } @@ -383,14 +403,22 @@ void WorldSession::HandleNpcTextQueryOpcode(WorldPacket& recv_data) data << pGossip->Options[i].Probability; if (Text_0[i].empty()) + { data << Text_1[i]; + } else + { data << Text_0[i]; + } if (Text_1[i].empty()) + { data << Text_0[i]; + } else + { data << Text_1[i]; + } data << pGossip->Options[i].Language; @@ -440,7 +468,9 @@ void WorldSession::HandlePageTextQueryOpcode(WorldPacket& recv_data) if (pl) { if (pl->Text.size() > size_t(loc_idx) && !pl->Text[loc_idx].empty()) + { Text = pl->Text[loc_idx]; + } } } @@ -512,7 +542,9 @@ void WorldSession::HandleQuestPOIQueryOpcode(WorldPacket& recv_data) uint16 questSlot = _player->FindQuestSlot(questId); if (questSlot != MAX_QUEST_LOG_SIZE) + { questOk = _player->GetQuestSlotQuestId(questSlot) == questId; + } if (questOk) { diff --git a/src/game/WorldHandlers/QuestDef.cpp b/src/game/WorldHandlers/QuestDef.cpp index 36f74888e..ecd984655 100644 --- a/src/game/WorldHandlers/QuestDef.cpp +++ b/src/game/WorldHandlers/QuestDef.cpp @@ -229,31 +229,41 @@ Quest::Quest(Field* questRecord) for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i) { if (ReqItemId[i]) + { ++m_reqitemscount; + } } for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i) { if (ReqCreatureOrGOId[i]) + { ++m_reqCreatureOrGOcount; + } } for (int i = 0; i < QUEST_REWARDS_COUNT; ++i) { if (RewItemId[i]) + { ++m_rewitemscount; + } } for (int i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i) { if (RewChoiceItemId[i]) + { ++m_rewchoiceitemscount; + } } for (int i = 0; i < QUEST_REQUIRED_CURRENCY_COUNT; ++i) { if (ReqCurrencyId[i]) + { ++m_reqCurrencyCount; + } } } @@ -269,19 +279,25 @@ uint32 Quest::XPValue(Player* pPlayer) const // formula can possibly be organized better, using less if's and simplify some. if (QuestLevel != -1) + { baseLevel = QuestLevel; + } if (((baseLevel - playerLevel) + 10) * 2 > 10) { baseLevel = playerLevel; if (QuestLevel != -1) + { baseLevel = QuestLevel; + } if (((baseLevel - playerLevel) + 10) * 2 <= 10) { if (QuestLevel == -1) + { baseLevel = playerLevel; + } xpMultiplier = 2 * (baseLevel - playerLevel) + 20; } @@ -295,19 +311,25 @@ uint32 Quest::XPValue(Player* pPlayer) const baseLevel = playerLevel; if (QuestLevel != -1) + { baseLevel = QuestLevel; + } if (((baseLevel - playerLevel) + 10) * 2 >= 1) { baseLevel = playerLevel; if (QuestLevel != -1) + { baseLevel = QuestLevel; + } if (((baseLevel - playerLevel) + 10) * 2 <= 10) { if (QuestLevel == -1) + { baseLevel = playerLevel; + } xpMultiplier = 2 * (baseLevel - playerLevel) + 20; } @@ -329,13 +351,21 @@ uint32 Quest::XPValue(Player* pPlayer) const // round values if (rawXP > 1000) + { realXP = ((rawXP + 25) / 50 * 50); + } else if (rawXP > 500) + { realXP = ((rawXP + 12) / 25 * 25); + } else if (rawXP > 100) + { realXP = ((rawXP + 5) / 10 * 10); + } else + { realXP = ((rawXP + 2) / 5 * 5); + } } return realXP; @@ -367,7 +397,9 @@ bool Quest::IsAllowedInRaid() const uint32 Quest::CalculateRewardHonor(uint32 level) const { if (level > GT_MAX_LEVEL) + { level = GT_MAX_LEVEL; + } uint32 honor = 0; diff --git a/src/game/WorldHandlers/QuestHandler.cpp b/src/game/WorldHandlers/QuestHandler.cpp index 5db9d572a..dade21d10 100644 --- a/src/game/WorldHandlers/QuestHandler.cpp +++ b/src/game/WorldHandlers/QuestHandler.cpp @@ -66,7 +66,9 @@ void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recv_data) dialogStatus = sScriptMgr.GetDialogStatus(_player, cr_questgiver); if (dialogStatus > DIALOG_STATUS_REWARD_REP) + { dialogStatus = getDialogStatus(_player, cr_questgiver, DIALOG_STATUS_NONE); + } } break; } @@ -76,7 +78,9 @@ void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recv_data) dialogStatus = sScriptMgr.GetDialogStatus(_player, go_questgiver); if (dialogStatus > DIALOG_STATUS_REWARD_REP) + { dialogStatus = getDialogStatus(_player, go_questgiver, DIALOG_STATUS_NONE); + } break; } @@ -191,7 +195,9 @@ void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvData) Player* pPlayer = itr->getSource(); if (!pPlayer || pPlayer == _player) // not self + { continue; + } if (pPlayer->CanTakeQuest(qInfo, true)) { @@ -207,14 +213,18 @@ void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvData) } if (_player->CanCompleteQuest(quest)) + { _player->CompleteQuest(quest); + } _player->GetAchievementMgr().StartTimedAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, quest); _player->PlayerTalkClass->CloseGossip(); if (qInfo->GetSrcSpell() > 0) + { _player->CastSpell(_player, qInfo->GetSrcSpell(), true); + } return; } @@ -259,7 +269,9 @@ void WorldSession::HandleQuestgiverQueryQuestOpcode(WorldPacket& recvData) } if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest)) + { _player->PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, pObject->GetObjectGuid(), true); + } } void WorldSession::HandleQuestQueryOpcode(WorldPacket& recv_data) @@ -314,10 +326,14 @@ void WorldSession::HandleQuestgiverChooseRewardOpcode(WorldPacket& recv_data) // Send next quest if (Quest const* nextquest = _player->GetNextQuest(guid, pQuest)) + { _player->PlayerTalkClass->SendQuestGiverQuestDetails(nextquest, guid, true); + } } else + { _player->PlayerTalkClass->SendQuestGiverOfferReward(pQuest, guid, true); + } } } @@ -341,7 +357,9 @@ void WorldSession::HandleQuestgiverRequestRewardOpcode(WorldPacket& recv_data) } if (_player->CanCompleteQuest(quest)) + { _player->CompleteQuest(quest); + } if (_player->GetQuestStatus(quest) != QUEST_STATUS_COMPLETE) { @@ -349,7 +367,9 @@ void WorldSession::HandleQuestgiverRequestRewardOpcode(WorldPacket& recv_data) } if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest)) + { _player->PlayerTalkClass->SendQuestGiverOfferReward(pQuest, guid, true); + } } void WorldSession::HandleQuestgiverCancel(WorldPacket& /*recv_data*/) @@ -386,12 +406,16 @@ void WorldSession::HandleQuestLogRemoveQuest(WorldPacket& recv_data) if (uint32 quest = _player->GetQuestSlotQuestId(slot)) { if (!_player->TakeQuestSourceItem(quest, true)) + { return; // can't un-equip some items, reject quest cancel + } if (const Quest* pQuest = sObjectMgr.GetQuestTemplate(quest)) { if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED)) + { _player->RemoveTimedQuest(quest); + } for (int i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i) { @@ -399,7 +423,9 @@ void WorldSession::HandleQuestLogRemoveQuest(WorldPacket& recv_data) { ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(pQuest->ReqSourceId[i]); if (iProto && iProto->Bonding == BIND_QUEST_ITEM) + { _player->DestroyItemCount(pQuest->ReqSourceId[i], pQuest->ReqSourceCount[i], true, false, true); + } } } } @@ -455,7 +481,9 @@ void WorldSession::HandleQuestConfirmAccept(WorldPacket& recv_data) } if (_player->CanAddQuest(pQuest, true)) + { _player->AddQuest(pQuest, NULL); // NULL, this prevent DB script from duplicate running + } _player->ClearDividerGuid(); } @@ -481,16 +509,24 @@ void WorldSession::HandleQuestgiverCompleteQuest(WorldPacket& recv_data) if (_player->GetQuestStatus(quest) != QUEST_STATUS_COMPLETE) { if (pQuest->IsRepeatable()) + { _player->PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, _player->CanCompleteRepeatableQuest(pQuest), false); + } else + { _player->PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, _player->CanRewardQuest(pQuest, false), false); + } } else { if (pQuest->GetReqItemsCount() || pQuest->GetReqCurrencyCount()) // some items or currency required + { _player->PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, _player->CanRewardQuest(pQuest, false), false); + } else // no items required + { _player->PlayerTalkClass->SendQuestGiverOfferReward(pQuest, guid, true); + } } } } @@ -516,7 +552,9 @@ void WorldSession::HandlePushQuestToParty(WorldPacket& recvPacket) Player* pPlayer = itr->getSource(); if (!pPlayer || pPlayer == _player) // skip self + { continue; + } _player->SendPushToPartyResponse(pPlayer, QUEST_PARTY_MSG_SHARING_QUEST); @@ -619,19 +657,29 @@ uint32 WorldSession::getDialogStatus(Player* pPlayer, Object* questgiver, uint32 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) + { continue; + } QuestStatus status = pPlayer->GetQuestStatus(quest_id); if (status == QUEST_STATUS_COMPLETE && !pPlayer->GetQuestRewardStatus(quest_id)) + { dialogStatusNew = pQuest->IsRepeatable() ? DIALOG_STATUS_REWARD_REP : DIALOG_STATUS_REWARD; + } else if (pQuest->IsAutoComplete() && pPlayer->CanTakeQuest(pQuest, false)) + { dialogStatusNew = pQuest->IsRepeatable() ? DIALOG_STATUS_AVAILABLE_REP : DIALOG_STATUS_AVAILABLE; + } else if (status == QUEST_STATUS_INCOMPLETE) + { dialogStatusNew = DIALOG_STATUS_INCOMPLETE; + } if (dialogStatusNew > dialogStatus) + { dialogStatus = dialogStatusNew; + } } // check markings for quest-giver @@ -642,7 +690,9 @@ uint32 WorldSession::getDialogStatus(Player* pPlayer, Object* questgiver, uint32 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id); if (!pQuest || !pQuest->IsActive()) + { continue; + } QuestStatus status = pPlayer->GetQuestStatus(quest_id); @@ -660,20 +710,30 @@ uint32 WorldSession::getDialogStatus(Player* pPlayer, Object* questgiver, uint32 else if (lowLevelDiff < 0 || pPlayer->getLevel() <= pPlayer->GetQuestLevelForPlayer(pQuest) + uint32(lowLevelDiff)) { if (pQuest->HasQuestFlag(QUEST_FLAGS_DAILY) || pQuest->HasQuestFlag(QUEST_FLAGS_WEEKLY)) + { dialogStatusNew = DIALOG_STATUS_AVAILABLE_REP; + } else + { dialogStatusNew = DIALOG_STATUS_AVAILABLE; + } } else // player level much higher then quest-level + { dialogStatusNew = DIALOG_STATUS_LOW_LEVEL_AVAILABLE; + } } else + { dialogStatusNew = DIALOG_STATUS_UNAVAILABLE; + } } } if (dialogStatusNew > dialogStatus) + { dialogStatus = dialogStatusNew; + } } return dialogStatus; @@ -698,15 +758,21 @@ void WorldSession::HandleQuestgiverStatusMultipleQuery(WorldPacket& /*recvPacket Creature* questgiver = GetPlayer()->GetMap()->GetAnyTypeCreature(*itr); if (!questgiver || questgiver->IsHostileTo(_player)) + { continue; + } if (!questgiver->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER)) + { continue; + } dialogStatus = sScriptMgr.GetDialogStatus(_player, questgiver); if (dialogStatus > DIALOG_STATUS_REWARD_REP) + { dialogStatus = getDialogStatus(_player, questgiver, DIALOG_STATUS_NONE); + } data << questgiver->GetObjectGuid(); data << uint32(dialogStatus); @@ -717,15 +783,21 @@ void WorldSession::HandleQuestgiverStatusMultipleQuery(WorldPacket& /*recvPacket GameObject* questgiver = GetPlayer()->GetMap()->GetGameObject(*itr); if (!questgiver) + { continue; + } if (questgiver->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER) + { continue; + } dialogStatus = sScriptMgr.GetDialogStatus(_player, questgiver); if (dialogStatus > DIALOG_STATUS_REWARD_REP) + { dialogStatus = getDialogStatus(_player, questgiver, DIALOG_STATUS_NONE); + } data << questgiver->GetObjectGuid(); data << uint32(dialogStatus); diff --git a/src/game/WorldHandlers/ScriptMgr.cpp b/src/game/WorldHandlers/ScriptMgr.cpp index db1ace67f..9cb918d03 100644 --- a/src/game/WorldHandlers/ScriptMgr.cpp +++ b/src/game/WorldHandlers/ScriptMgr.cpp @@ -87,14 +87,18 @@ uint8 GetSpellStartDBScriptPriority(SpellEntry const* spellinfo, SpellEffectInde #else if (spellinfo->Effect[effIdx] == SPELL_EFFECT_SCRIPT_EFFECT) #endif - { return 10; } + { + return 10; + } #if defined (CATA) || defined(MISTS) if (spellEffect->Effect == SPELL_EFFECT_DUMMY) #else if (spellinfo->Effect[effIdx] == SPELL_EFFECT_DUMMY) #endif - { return 9; } + { + return 9; + } // NonExisting triggered spells can also start DB-Spell-Scripts #if defined (CATA) || defined(MISTS) @@ -102,7 +106,9 @@ uint8 GetSpellStartDBScriptPriority(SpellEntry const* spellinfo, SpellEffectInde #else if (spellinfo->Effect[effIdx] == SPELL_EFFECT_TRIGGER_SPELL && !sSpellStore.LookupEntry(spellinfo->EffectTriggerSpell[effIdx])) #endif - { return 5; } + { + return 5; + } // NonExisting trigger missile spells can also start DB-Spell-Scripts #if defined (CATA) || defined(MISTS) @@ -110,7 +116,9 @@ uint8 GetSpellStartDBScriptPriority(SpellEntry const* spellinfo, SpellEffectInde #else if (spellinfo->Effect[effIdx] == SPELL_EFFECT_TRIGGER_MISSILE && !sSpellStore.LookupEntry(spellinfo->EffectTriggerSpell[effIdx])) #endif - { return 4; } + { + return 4; + } // Can not start script return 0; @@ -669,7 +677,9 @@ void ScriptMgr::LoadScripts(DBScriptType type) #if defined (CATA) || defined(MISTS) SpellEffectEntry const* spellEffect = spell->GetSpellEffect(SpellEffectIndex(j)); if (!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_SEND_TAXI && spellEffect->EffectMiscValue == tmp.sendTaxiPath.taxiPathId) #else @@ -819,7 +829,9 @@ void ScriptMgr::LoadDbScripts(DBScriptType t) std::set eventIds; // Store possible event ids if (t == DBS_ON_EVENT) - CollectPossibleEventIds(eventIds); + { + CollectPossibleEventIds(eventIds); + } LoadScripts(t); ScriptChainMap& scm = m_dbScripts[t]; @@ -831,12 +843,16 @@ void ScriptMgr::LoadDbScripts(DBScriptType t) case DBS_ON_QUEST_START: case DBS_ON_QUEST_END: if (!sObjectMgr.GetQuestTemplate(itr->first)) - sLog.outErrorDb("Table `db_scripts [type = %d]` has not existing quest (Id: %u) as script id", t, itr->first); + { + sLog.outErrorDb("Table `db_scripts [type = %d]` has not existing quest (Id: %u) as script id", t, itr->first); + } break; case DBS_ON_CREATURE_DEATH: if (!sObjectMgr.GetCreatureTemplate(itr->first)) - sLog.outErrorDb("Table `db_scripts [type = %d]` has not existing creature (Entry: %u) as script id", t, itr->first); + { + sLog.outErrorDb("Table `db_scripts [type = %d]` has not existing creature (Entry: %u) as script id", t, itr->first); + } break; case DBS_ON_SPELL: @@ -859,24 +875,32 @@ void ScriptMgr::LoadDbScripts(DBScriptType t) } } if (!found) - sLog.outErrorDb("Table `db_scripts [type = %d]` has unsupported spell (Id: %u)", t, itr->first); + { + sLog.outErrorDb("Table `db_scripts [type = %d]` has unsupported spell (Id: %u)", t, itr->first); + } break; } case DBS_ON_GO_USE: if (!sObjectMgr.GetGOData(itr->first)) - sLog.outErrorDb("Table `db_scripts [type = %d]`, has not existing gameobject (GUID: %u) as script id", t, itr->first); + { + sLog.outErrorDb("Table `db_scripts [type = %d]`, has not existing gameobject (GUID: %u) as script id", t, itr->first); + } break; case DBS_ON_GOT_USE: if (!sObjectMgr.GetGameObjectInfo(itr->first)) - sLog.outErrorDb("Table `db_scripts [type = %d]` has not existing gameobject (Entry: %u) as script id", t, itr->first); + { + sLog.outErrorDb("Table `db_scripts [type = %d]` has not existing gameobject (Entry: %u) as script id", t, itr->first); + } break; case DBS_ON_EVENT: { std::set::const_iterator itr2 = eventIds.find(itr->first); if (itr2 == eventIds.end()) - sLog.outErrorDb("Table `db_scripts [type = %d]` has script (Id: %u) not referring to any fitting gameobject_template or any spell effect %u or path taxi node data", t, itr->first, SPELL_EFFECT_SEND_EVENT); + { + sLog.outErrorDb("Table `db_scripts [type = %d]` has script (Id: %u) not referring to any fitting gameobject_template or any spell effect %u or path taxi node data", t, itr->first, SPELL_EFFECT_SEND_EVENT); + } break; } default: @@ -920,10 +944,14 @@ void ScriptMgr::CheckScriptTexts(std::set& ids) for (int i = 0; i < MAX_TEXT_ID; ++i) { if (itrC->textId[i] && !sObjectMgr.GetMangosStringLocale(itrC->textId[i])) - sLog.outErrorDb("Table `db_script_string` is missing string id %u, used in `db_script [type = %d]` table, id %u.", itrC->textId[i], t, itrCM->first); + { + sLog.outErrorDb("Table `db_script_string` is missing string id %u, used in `db_script [type = %d]` table, id %u.", itrC->textId[i], t, itrCM->first); + } if (ids.find(itrC->textId[i]) != ids.end()) - ids.erase(itrC->textId[i]); + { + ids.erase(itrC->textId[i]); + } } } } @@ -1063,9 +1091,13 @@ bool ScriptAction::GetScriptProcessTargets(WorldObject* pOrigSource, WorldObject MaNGOS::CreatureLastSearcher searcher(pCreatureBuddy, u_check); if (m_script->data_flags & SCRIPT_FLAG_BUDDY_IS_PET) + { Cell::VisitWorldObjects(pSearcher, searcher, m_script->searchRadiusOrGuid); + } else // Normal Creature + { Cell::VisitGridObjects(pSearcher, searcher, m_script->searchRadiusOrGuid); + } } pBuddy = pCreatureBuddy; @@ -1447,7 +1479,9 @@ bool ScriptAction::HandleScriptStep() { GameObjectData const* goData = sObjectMgr.GetGOData(m_script->respawnGo.goGuid); if (!goData) - { break; } // checked at load + { + break; // checked at load + } // TODO - This was a change, was before current map of source pGo = m_map->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, goData->id, m_script->respawnGo.goGuid)); @@ -1476,7 +1510,9 @@ bool ScriptAction::HandleScriptStep() } if (pGo->isSpawned()) - { break; } // gameobject already spawned + { + break; // gameobject already spawned + } pGo->SetLootState(GO_READY); pGo->SetRespawnTime(time_to_despawn); // despawn object in ? seconds @@ -1546,7 +1582,9 @@ bool ScriptAction::HandleScriptStep() if ((m_script->command == SCRIPT_COMMAND_OPEN_DOOR && pDoor->GetGoState() != GO_STATE_READY) || (m_script->command == SCRIPT_COMMAND_CLOSE_DOOR && pDoor->GetGoState() == GO_STATE_READY)) - { break; } // to be opened door already open, or to be closed door already closed + { + break; // to be opened door already open, or to be closed door already closed + } pDoor->UseDoorOrButton(time_to_reset); @@ -1595,13 +1633,17 @@ bool ScriptAction::HandleScriptStep() ++filledCount; if (filledCount > 0) if (uint32 randomField = urand(0, filledCount)) // Random selection resulted in one of the dataint fields + { spell = m_script->textId[randomField - 1]; + } // TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast if (pSource && pSource->GetTypeId() == TYPEID_GAMEOBJECT) { ((Unit*)pTarget)->CastSpell(((Unit*)pTarget), spell, true, NULL, NULL, pSource->GetObjectGuid()); - { break; } + { + break; + } } if (LogIfNotUnit(pSource)) @@ -1632,7 +1674,9 @@ bool ScriptAction::HandleScriptStep() } if (m_script->data_flags & SCRIPT_FLAG_COMMAND_ADDITIONAL) + { pSource->PlayMusic(m_script->playSound.soundId, pSoundTarget); + } else { if (m_script->playSound.flags & 2) @@ -1687,7 +1731,9 @@ bool ScriptAction::HandleScriptStep() { Player* pPlayer = GetPlayerTargetOrSourceAndLog(pSource, pTarget); if (!pPlayer) + { break; + } pPlayer->SendMovieStart(m_script->playMovie.movieId); @@ -2001,12 +2047,18 @@ bool ScriptAction::HandleScriptStep() { Player* pPlayer = GetPlayerTargetOrSourceAndLog(pSource, pTarget); if (!pPlayer) + { break; + } if (m_script->xpDisabled.flags) + { pPlayer->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_XP_USER_DISABLED); + } else + { pPlayer->RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_XP_USER_DISABLED); + } break; } case SCRIPT_COMMAND_TERMINATE_COND: // 34 @@ -2065,14 +2117,20 @@ bool ScriptAction::HandleScriptStep() return false; } if (LogIfNotUnit(pTarget)) + { break; + } // if radius is provided send AI event around if (m_script->sendAIEvent.radius) + { ((Creature*)pSource)->AI()->SendAIEventAround(AIEventType(m_script->sendAIEvent.eventType), (Unit*)pTarget, 0, float(m_script->sendAIEvent.radius)); + } // else if no radius and target is creature send AI event to target else if (pTarget->GetTypeId() == TYPEID_UNIT) + { ((Creature*)pSource)->AI()->SendAIEvent(AIEventType(m_script->sendAIEvent.eventType), NULL, (Creature*)pTarget); + } break; } case SCRIPT_COMMAND_TURN_TO: // 36 @@ -2110,9 +2168,13 @@ bool ScriptAction::HandleScriptStep() { float orientation; if (m_script->data_flags & SCRIPT_FLAG_COMMAND_ADDITIONAL) + { orientation = pSource->GetOrientation() + m_script->o + 2 * M_PI_F; + } else + { orientation = m_script->o; + } pSource->GetRandomPoint(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), m_script->moveDynamic.maxDist, x, y, z, m_script->moveDynamic.minDist, (orientation == 0.0f ? NULL : &orientation)); @@ -2135,9 +2197,13 @@ bool ScriptAction::HandleScriptStep() MailSender sender; if (m_script->sendMail.altSender) + { sender = MailSender(MAIL_CREATURE, m_script->sendMail.altSender); + } else + { sender = MailSender(pSource); + } uint32 deliverDelay = m_script->textId[0] > 0 ? (uint32)m_script->textId[0] : 0; MailDraft(m_script->sendMail.mailTemplateId).SendMailTo(static_cast(pTarget), sender, MAIL_CHECK_MASK_HAS_BODY, deliverDelay); @@ -2146,15 +2212,21 @@ bool ScriptAction::HandleScriptStep() case SCRIPT_COMMAND_SET_FLY: // 39 { if (LogIfNotCreature(pSource)) + { break; + } // enable / disable the fly anim flag if (m_script->data_flags & SCRIPT_FLAG_COMMAND_ADDITIONAL) { if (m_script->fly.fly) + { pSource->SetByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_FLY_ANIM); + } else + { pSource->RemoveByteFlag(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_FLY_ANIM); + } } ((Creature*)pSource)->SetLevitate(!!m_script->fly.fly); @@ -2163,7 +2235,9 @@ bool ScriptAction::HandleScriptStep() case SCRIPT_COMMAND_DESPAWN_GO: // 40 { if (LogIfNotGameObject(pTarget)) + { break; + } // ToDo: Change this to pGo->ForcedDespawn() when function is implemented! ((GameObject*)pTarget)->SetLootState(GO_JUST_DEACTIVATED); @@ -2172,7 +2246,9 @@ bool ScriptAction::HandleScriptStep() case SCRIPT_COMMAND_RESPAWN: // 41 { if (LogIfNotCreature(pTarget)) + { break; + } ((Creature*)pTarget)->Respawn(); break; @@ -2194,21 +2270,29 @@ bool ScriptAction::HandleScriptStep() // main hand if (m_script->textId[0] >= 0) + { pCSource->SetVirtualItem(VIRTUAL_ITEM_SLOT_0, m_script->textId[0]); + } // off hand if (m_script->textId[1] >= 0) + { pCSource->SetVirtualItem(VIRTUAL_ITEM_SLOT_1, m_script->textId[1]); + } // ranged if (m_script->textId[2] >= 0) + { pCSource->SetVirtualItem(VIRTUAL_ITEM_SLOT_2, m_script->textId[2]); + } break; } case SCRIPT_COMMAND_RESET_GO: // 43 { if (LogIfNotGameObject(pTarget)) + { break; + } GameObject* pGoTarget = static_cast(pTarget); switch (pGoTarget->GetGoType()) @@ -2233,9 +2317,13 @@ bool ScriptAction::HandleScriptStep() Creature* pCSource = static_cast(pSource); if (pCSource->GetEntry() != m_script->updateTemplate.newTemplate) + { pCSource->UpdateEntry(m_script->updateTemplate.newTemplate, m_script->updateTemplate.newFactionTeam ? HORDE : ALLIANCE); + } else + { sLog.outErrorDb(" DB-SCRIPTS: Process table `db_scripts [type = %d]` id %u, command %u failed. Source already has specified creature entry.", m_type, m_script->id, m_script->command); + } break; } case SCRIPT_COMMAND_CHANGE_ENTRY: // 45 @@ -2338,11 +2426,15 @@ void ScriptMgr::LoadScriptBinding() break; case SCRIPTED_BATTLEGROUND: if (MapEntry const* mapEntry = sMapStore.LookupEntry(uint32(id))) + { exists = mapEntry->IsBattleGround(); + } break; case SCRIPTED_INSTANCE: if (MapEntry const* mapEntry = sMapStore.LookupEntry(uint32(id))) + { exists = mapEntry->IsDungeon(); + } break; case SCRIPTED_CONDITION: exists = sConditionStorage.LookupEntry(uint32(id)); @@ -2358,7 +2450,9 @@ void ScriptMgr::LoadScriptBinding() } if (type == SCRIPTED_SPELL || type == SCRIPTED_AURASPELL) + { id |= uint32(data) << 24; //incorporate spell effect number into the key + } m_scriptBind[type][id] = scriptId; } @@ -2455,7 +2549,9 @@ uint32 ScriptMgr::GetBoundScriptId(ScriptedObjectType entity, int32 entry) { EntryToScriptIdMap::iterator it = m_scriptBind[entity].find(entry); if (it != m_scriptBind[entity].end()) + { id = it->second; + } } else sLog.outErrorScriptLib("asking a script for non-existing entity type %u!", entity); @@ -2931,12 +3027,16 @@ void ScriptMgr::CollectPossibleEventIds(std::set& eventIds) #if defined (CATA) || defined(MISTS) SpellEffectEntry const* spellEffect = spell->GetSpellEffect(SpellEffectIndex(j)); if (!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_SEND_EVENT) { if (spellEffect->EffectMiscValue) + { eventIds.insert(spellEffect->EffectMiscValue); + } } #else if (spell->Effect[j] == SPELL_EFFECT_SEND_EVENT) @@ -2959,10 +3059,14 @@ void ScriptMgr::CollectPossibleEventIds(std::set& eventIds) TaxiPathNodeEntry const& node = sTaxiPathNodesByPath[path_idx][node_idx]; if (node.arrivalEventID) + { eventIds.insert(node.arrivalEventID); + } if (node.departureEventID) + { eventIds.insert(node.departureEventID); + } } } #endif @@ -2999,7 +3103,9 @@ bool StartEvents_Event(Map* map, uint32 id, Object* source, Object* target, bool #else if (map->IsBattleGroundOrArena()) #endif - { bg = ((BattleGroundMap*)map)->GetBG(); } + { + bg = ((BattleGroundMap*)map)->GetBG(); + } else // Use the go, because GOs don't move { opvp = sOutdoorPvPMgr.GetScript(((GameObject*)source)->GetZoneId()); diff --git a/src/game/WorldHandlers/ScriptMgr.h b/src/game/WorldHandlers/ScriptMgr.h index fb9663149..ddffb3eb2 100644 --- a/src/game/WorldHandlers/ScriptMgr.h +++ b/src/game/WorldHandlers/ScriptMgr.h @@ -622,7 +622,9 @@ class ScriptMgr ScriptChainMap const* GetScriptChainMap(DBScriptType type) { if ((type != DBS_INTERNAL) && type < DBS_END) + { return &m_dbScripts[type]; + } return NULL; } diff --git a/src/game/WorldHandlers/SkillDiscovery.cpp b/src/game/WorldHandlers/SkillDiscovery.cpp index 47cb903ec..92f421030 100644 --- a/src/game/WorldHandlers/SkillDiscovery.cpp +++ b/src/game/WorldHandlers/SkillDiscovery.cpp @@ -151,21 +151,29 @@ void LoadSkillDiscoveryTable() sLog.outString(); sLog.outString(">> Loaded %u skill discovery definitions", count); if (!ssNonDiscoverableEntries.str().empty()) + { sLog.outErrorDb("Some items can't be successfully discovered: have in chance field value < 0.000001 in `skill_discovery_template` DB table . List:\n%s", ssNonDiscoverableEntries.str().c_str()); + } // report about empty data for explicit discovery spells for (uint32 spell_id = 1; spell_id < sSpellStore.GetNumRows(); ++spell_id) { SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell_id); if (!spellEntry) + { continue; + } // skip not explicit discovery spells if (!IsExplicitDiscoverySpell(spellEntry)) + { continue; + } if (SkillDiscoveryStore.find(spell_id) == SkillDiscoveryStore.end()) + { sLog.outErrorDb("Spell (ID: %u) is 100%% chance random discovery ability but not have data in `skill_discovery_template` table", spell_id); + } } } @@ -186,7 +194,9 @@ uint32 GetExplicitDiscoverySpell(uint32 spellId, Player* player) for (SkillDiscoveryList::const_iterator item_iter = tab->second.begin(); item_iter != tab->second.end(); ++item_iter) if (item_iter->reqSkillValue <= skillvalue) if (!player->HasSpell(item_iter->spellId)) + { full_chance += item_iter->chance; + } float rate = full_chance / 100.0f; float roll = rand_chance_f() * rate; // roll now in range 0..full_chance @@ -194,10 +204,14 @@ uint32 GetExplicitDiscoverySpell(uint32 spellId, Player* player) for (SkillDiscoveryList::const_iterator item_iter = tab->second.begin(); item_iter != tab->second.end(); ++item_iter) { if (item_iter->reqSkillValue > skillvalue) + { continue; + } if (player->HasSpell(item_iter->spellId)) + { continue; + } if (item_iter->chance > roll) { diff --git a/src/game/WorldHandlers/SkillExtraItems.cpp b/src/game/WorldHandlers/SkillExtraItems.cpp index 697f35589..857bb38d0 100644 --- a/src/game/WorldHandlers/SkillExtraItems.cpp +++ b/src/game/WorldHandlers/SkillExtraItems.cpp @@ -132,17 +132,23 @@ bool canCreateExtraItems(Player* player, uint32 spellId, float& additionalChance // get the info for the specified spell SkillExtraItemMap::const_iterator ret = SkillExtraItemStore.find(spellId); if (ret == SkillExtraItemStore.end()) + { return false; + } SkillExtraItemEntry const* specEntry = &ret->second; // if no entry, then no extra items can be created if (!specEntry) + { return false; + } // the player doesn't have the required specialization, return false if (!player->HasSpell(specEntry->requiredSpecialization)) + { return false; + } // set the arguments to the appropriate values additionalChance = specEntry->additionalCreateChance; diff --git a/src/game/WorldHandlers/SkillHandler.cpp b/src/game/WorldHandlers/SkillHandler.cpp index a66fdb3d7..c6bec9e88 100644 --- a/src/game/WorldHandlers/SkillHandler.cpp +++ b/src/game/WorldHandlers/SkillHandler.cpp @@ -40,13 +40,17 @@ void WorldSession::HandleLearnTalentOpcode(WorldPacket& recv_data) recv_data >> talent_id >> requested_rank; if (_player->LearnTalent(talent_id, requested_rank)) + { _player->SendTalentsInfoData(false); + } else sLog.outError("WorldSession::HandleLearnTalentOpcode: learn talent %u rank %u failed for %s (account %u)", talent_id, requested_rank, GetPlayerName(), GetAccountId()); // if player has a pet, update owner talent auras if (_player->GetPet()) + { _player->GetPet()->CastOwnerTalentAuras(); + } } void WorldSession::HandleLearnPreviewTalents(WorldPacket& recvPacket) @@ -91,7 +95,9 @@ void WorldSession::HandleLearnPreviewTalents(WorldPacket& recvPacket) // if player has a pet, update owner talent auras if (_player->GetPet()) + { _player->GetPet()->CastOwnerTalentAuras(); + } } void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket& recv_data) @@ -124,7 +130,9 @@ void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket& recv_data) _player->SendTalentsInfoData(false); unit->CastSpell(_player, 14867, true); // spell: "Untalent Visual Effect" if (_player->GetPet()) + { _player->GetPet()->CastOwnerTalentAuras(); + } } void WorldSession::HandleUnlearnSkillOpcode(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/Spell.cpp b/src/game/WorldHandlers/Spell.cpp index 13eacb654..580979702 100644 --- a/src/game/WorldHandlers/Spell.cpp +++ b/src/game/WorldHandlers/Spell.cpp @@ -223,16 +223,22 @@ void SpellCastTargets::Update(Unit* caster) Player* player = ((Player*)caster); if (m_targetMask & TARGET_FLAG_ITEM) + { m_itemTarget = player->GetItemByGuid(m_itemTargetGUID); + } else if (m_targetMask & TARGET_FLAG_TRADE_ITEM) { if (TradeData* pTrade = player->GetTradeData()) if (m_itemTargetGUID.GetRawValue() < TRADE_SLOT_COUNT) + { m_itemTarget = pTrade->GetTraderData()->GetItem(TradeSlots(m_itemTargetGUID.GetRawValue())); + } } if (m_itemTarget) + { m_itemTargetEntry = m_itemTarget->GetEntry(); + } } } @@ -252,23 +258,33 @@ void SpellCastTargets::read(ByteBuffer& data, Unit* caster) // TARGET_FLAG_UNK2 is used for non-combat pets, maybe other? if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_UNK2)) + { data >> m_unitTargetGUID.ReadAsPacked(); + } if (m_targetMask & (TARGET_FLAG_OBJECT | TARGET_FLAG_GAMEOBJECT_ITEM)) + { data >> m_GOTargetGUID.ReadAsPacked(); + } if ((m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM)) && caster->GetTypeId() == TYPEID_PLAYER) + { data >> m_itemTargetGUID.ReadAsPacked(); + } if (m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE)) + { data >> m_CorpseTargetGUID.ReadAsPacked(); + } if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { data >> m_srcTransportGUID.ReadAsPacked(); data >> m_srcX >> m_srcY >> m_srcZ; if (!MaNGOS::IsValidMapCoord(m_srcX, m_srcY, m_srcZ)) + { throw ByteBufferException(false, data.rpos(), 0, data.size()); + } } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) @@ -276,11 +292,15 @@ void SpellCastTargets::read(ByteBuffer& data, Unit* caster) data >> m_destTransportGUID.ReadAsPacked(); data >> m_destX >> m_destY >> m_destZ; if (!MaNGOS::IsValidMapCoord(m_destX, m_destY, m_destZ)) + { throw ByteBufferException(false, data.rpos(), 0, data.size()); + } } if (m_targetMask & TARGET_FLAG_STRING) + { data >> m_strTarget; + } // find real units/GOs Update(caster); @@ -295,29 +315,45 @@ void SpellCastTargets::write(ByteBuffer& data) const if (m_targetMask & TARGET_FLAG_UNIT) { if (m_unitTarget) + { data << m_unitTarget->GetPackGUID(); + } else + { data << uint8(0); + } } else if (m_targetMask & TARGET_FLAG_OBJECT) { if (m_GOTarget) + { data << m_GOTarget->GetPackGUID(); + } else + { data << uint8(0); + } } else if (m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE)) + { data << m_CorpseTargetGUID.WriteAsPacked(); + } else + { data << uint8(0); + } } if (m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM)) { if (m_itemTarget) + { data << m_itemTarget->GetPackGUID(); + } else + { data << uint8(0); + } } if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) @@ -333,7 +369,9 @@ void SpellCastTargets::write(ByteBuffer& data) const } if (m_targetMask & TARGET_FLAG_STRING) + { data << m_strTarget; + } } void SpellCastTargets::ReadAdditionalData(WorldPacket& data, uint8& cast_flags) @@ -413,7 +451,9 @@ Spell::Spell(Unit* caster, SpellEntry const* info, bool triggered, ObjectGuid or if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER) { if (Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(RANGED_ATTACK)) + { m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->DamageType); + } } } // Set health leech amount to zero @@ -469,19 +509,31 @@ Spell::Spell(Unit* caster, SpellEntry const* info, bool triggered, ObjectGuid or { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if (spellEffect->Effect == 0) + { continue; + } if(!IsPositiveTarget(spellEffect->EffectImplicitTargetA, spellEffect->EffectImplicitTargetB)) + { m_canReflect = true; + } else + { m_canReflect = m_spellInfo->HasAttribute(SPELL_ATTR_EX_UNK7); + } if (m_canReflect) + { continue; + } else + { break; + } } } @@ -507,7 +559,9 @@ WorldObject* Spell::FindCorpseUsing() Cell::VisitGridObjects(m_caster, searcher, max_range); if (!result) + { Cell::VisitWorldObjects(m_caster, searcher, max_range); + } return result; } @@ -522,12 +576,16 @@ void Spell::FillTargetMap() { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // not call for empty effect. // Also some spells use not used effect targets for store targets for dummy effect in triggered spells if(spellEffect->Effect == SPELL_EFFECT_NONE) + { continue; + } // targets for TARGET_SCRIPT_COORDINATES (A) and TARGET_SCRIPT // for TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT (A) all is checked in Spell::CheckCast and in Spell::CheckItem @@ -541,14 +599,18 @@ void Spell::FillTargetMap() // TODO: find a way so this is not needed? // for area auras always add caster as target (needed for totems for example) if (IsAreaAuraEffect(spellEffect->Effect)) + { AddUnitTarget(m_caster, SpellEffectIndex(i)); + } // no double fill for same targets for (int j = 0; j < i; ++j) { SpellEffectEntry const* spellEffect1 = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if (!spellEffect1) + { continue; + } // Check if same target, but handle i.e. AreaAuras different if (spellEffect->EffectImplicitTargetA == spellEffect1->EffectImplicitTargetA && spellEffect->EffectImplicitTargetB == spellEffect1->EffectImplicitTargetB @@ -572,9 +634,13 @@ void Spell::FillTargetMap() { case TARGET_NONE: if (m_caster->GetObjectGuid().IsPet()) + { SetTargetMap(SpellEffectIndex(i), TARGET_SELF, tmpUnitLists[i /*==effToIndex[i]*/]); + } else + { SetTargetMap(SpellEffectIndex(i), TARGET_EFFECT_SELECT, tmpUnitLists[i /*==effToIndex[i]*/]); + } break; default: SetTargetMap(SpellEffectIndex(i), spellEffect->EffectImplicitTargetB, tmpUnitLists[i /*==effToIndex[i]*/]); @@ -591,7 +657,9 @@ void Spell::FillTargetMap() break; case TARGET_AREAEFFECT_INSTANT: // use B case that not dependent from from A in fact if((m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) == 0) + { m_targets.setDestination(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()); + } SetTargetMap(SpellEffectIndex(i), spellEffect->EffectImplicitTargetB, tmpUnitLists[i /*==effToIndex[i]*/]); break; case TARGET_BEHIND_VICTIM: // use B case that not dependent from from A in fact @@ -622,7 +690,9 @@ void Spell::FillTargetMap() // triggered spells get dest point from default target set, ignore it if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) || m_IsTriggeredSpell) if (WorldObject* castObject = GetCastingObject()) + { m_targets.setDestination(castObject->GetPositionX(), castObject->GetPositionY(), castObject->GetPositionZ()); + } SetTargetMap(SpellEffectIndex(i), spellEffect->EffectImplicitTargetB, tmpUnitLists[i /*==effToIndex[i]*/]); break; // target pre-selection required @@ -660,7 +730,9 @@ void Spell::FillTargetMap() if (spellEffect->Effect == SPELL_EFFECT_ENVIRONMENTAL_DAMAGE) { if(m_targets.getUnitTarget()) + { tmpUnitLists[i /*==effToIndex[i]*/].push_back(m_targets.getUnitTarget()); + } } else { @@ -706,7 +778,9 @@ void Spell::FillTargetMap() // triggered spells get dest point from default target set, ignore it if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) || m_IsTriggeredSpell) if (WorldObject* castObject = GetCastingObject()) + { m_targets.setDestination(castObject->GetPositionX(), castObject->GetPositionY(), castObject->GetPositionZ()); + } SetTargetMap(SpellEffectIndex(i), spellEffect->EffectImplicitTargetB, tmpUnitLists[i /*==effToIndex[i]*/]); break; // most A/B target pairs is self->negative and not expect adding caster to target list @@ -722,7 +796,9 @@ void Spell::FillTargetMap() case TARGET_EFFECT_SELECT: SetTargetMap(SpellEffectIndex(i), spellEffect->EffectImplicitTargetA, tmpUnitLists[i /*==effToIndex[i]*/]); if (Unit* currentTarget = m_targets.getUnitTarget()) + { tmpUnitLists[i /*==effToIndex[i]*/].push_back(currentTarget); + } break; default: SetTargetMap(SpellEffectIndex(i), spellEffect->EffectImplicitTargetA, tmpUnitLists[i /*==effToIndex[i]*/]); @@ -783,7 +859,9 @@ void Spell::FillTargetMap() continue; } else + { ++itr; + } } for (UnitList::const_iterator iunit = tmpUnitLists[effToIndex[i]].begin(); iunit != tmpUnitLists[effToIndex[i]].end(); ++iunit) @@ -805,11 +883,17 @@ void Spell::prepareDataForTriggerSystem() m_canTrigger = false; if (m_CastItem) + { m_canTrigger = false; // Do not trigger from item cast spell + } else if (!m_IsTriggeredSpell) + { m_canTrigger = true; // Normal cast - can trigger + } else if (!m_triggeredByAuraSpell) + { m_canTrigger = true; // Triggered from SPELL_EFFECT_TRIGGER_SPELL - can trigger + } if (!m_canTrigger) // Exceptions (some periodic triggers) { @@ -818,38 +902,54 @@ void Spell::prepareDataForTriggerSystem() case SPELLFAMILY_MAGE: // Arcane Missles / Blizzard triggers need do it if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000200080))) + { m_canTrigger = true; + } // Clearcasting trigger need do it else if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000200000000), 0x00000008)) + { m_canTrigger = true; + } // Replenish Mana, item spell with triggered cases (Mana Agate, etc mana gems) else if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0000010000000000))) + { m_canTrigger = true; + } break; case SPELLFAMILY_WARLOCK: // For Hellfire Effect / Rain of Fire / Seed of Corruption triggers need do it if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0000800000000060))) + { m_canTrigger = true; + } break; case SPELLFAMILY_PRIEST: // For Penance,Mind Sear,Mind Flay heal/damage triggers need do it if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0001800000800000), 0x00000040)) + { m_canTrigger = true; + } break; case SPELLFAMILY_ROGUE: // For poisons need do it if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x000000101001E000))) + { m_canTrigger = true; + } break; case SPELLFAMILY_HUNTER: // Hunter Rapid Killing/Explosive Trap Effect/Immolation Trap Effect/Frost Trap Aura/Snake Trap Effect/Explosive Shot if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0100200000000214), 0x200)) + { m_canTrigger = true; + } break; case SPELLFAMILY_PALADIN: // For Judgements (all) / Holy Shock triggers need do it if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0001000900B80400))) + { m_canTrigger = true; + } break; default: break; @@ -862,7 +962,9 @@ void Spell::prepareDataForTriggerSystem() case SPELL_DAMAGE_CLASS_MELEE: m_procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_SPELL_HIT; if (m_attackType == OFF_ATTACK) + { m_procAttacker |= PROC_FLAG_SUCCESSFUL_OFFHAND_HIT; + } m_procVictim = PROC_FLAG_TAKEN_MELEE_SPELL_HIT; break; case SPELL_DAMAGE_CLASS_RANGED: @@ -902,12 +1004,16 @@ void Spell::prepareDataForTriggerSystem() m_negativeEffectMask = 0x0; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) if (!IsPositiveEffect(m_spellInfo, SpellEffectIndex(i))) + { m_negativeEffectMask |= (1 << i); + } // Hunter traps spells (for Entrapment trigger) // Gives your Immolation Trap, Frost Trap, Explosive Trap, and Snake Trap .... if (m_spellInfo->IsFitToFamily(SPELLFAMILY_HUNTER, UI64LIT(0x000020000000001C))) + { m_procAttacker |= PROC_FLAG_ON_TRAP_ACTIVATION; + } } void Spell::CleanupTargetList() @@ -930,7 +1036,9 @@ void Spell::AddUnitTarget(Unit* pVictim, SpellEffectIndex effIndex) bool immuned = pVictim->IsImmuneToSpellEffect(m_spellInfo, effIndex, pVictim == m_caster); if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsTotem() && (m_spellFlags & SPELL_FLAG_REDIRECTED)) + { immuned = false; + } ObjectGuid targetGUID = pVictim->GetObjectGuid(); @@ -940,7 +1048,9 @@ void Spell::AddUnitTarget(Unit* pVictim, SpellEffectIndex effIndex) if (targetGUID == ihit->targetGUID) // Found in list { if (!immuned) + { ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned + } return; } } @@ -968,32 +1078,46 @@ void Spell::AddUnitTarget(Unit* pVictim, SpellEffectIndex effIndex) if (pVictim == affectiveObject) // Calculate dist to destination target also for self-cast spells { if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { dist = affectiveObject->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ); + } else // Must have Source Target + { dist = affectiveObject->GetDistance(m_targets.m_srcX, m_targets.m_srcY, m_targets.m_srcZ); + } } else // normal unit target, take distance + { dist = affectiveObject->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ()); + } if (dist < 5.0f) + { dist = 5.0f; + } target.timeDelay = (uint64) floor(dist / speed * 1000.0f); // Calculate minimum incoming time if (m_delayMoment == 0 || m_delayMoment > target.timeDelay) + { m_delayMoment = target.timeDelay; + } } // Spell casted on self - mostly TRIGGER_MISSILE code else if (m_spellInfo->GetSpeed() > 0.0f && affectiveObject && pVictim == affectiveObject) { float dist = 0.0f; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { dist = affectiveObject->GetDistance(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ); + } target.timeDelay = (uint64) floor(dist / m_spellInfo->GetSpeed() * 1000.0f); } else + { target.timeDelay = UI64LIT(0); + } // If target reflect spell back to caster if (target.missCondition == SPELL_MISS_REFLECT) @@ -1002,7 +1126,9 @@ void Spell::AddUnitTarget(Unit* pVictim, SpellEffectIndex effIndex) target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect); if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell + { target.reflectResult = SPELL_MISS_PARRY; + } // Increase time interval for reflected spells by 1.5 target.timeDelay += target.timeDelay >> 1; @@ -1010,7 +1136,9 @@ void Spell::AddUnitTarget(Unit* pVictim, SpellEffectIndex effIndex) m_spellFlags |= SPELL_FLAG_REFLECTED; } else + { target.reflectResult = SPELL_MISS_NONE; + } // Add target to list m_UniqueTargetInfo.push_back(target); @@ -1019,7 +1147,9 @@ void Spell::AddUnitTarget(Unit* pVictim, SpellEffectIndex effIndex) void Spell::AddUnitTarget(ObjectGuid unitGuid, SpellEffectIndex effIndex) { if (Unit* unit = m_caster->GetObjectGuid() == unitGuid ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGuid)) + { AddUnitTarget(unit, effIndex); + } } void Spell::AddGOTarget(GameObject* pVictim, SpellEffectIndex effIndex) @@ -1059,13 +1189,19 @@ void Spell::AddGOTarget(GameObject* pVictim, SpellEffectIndex effIndex) // calculate spell incoming interval float dist = affectiveObject->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ()); if (dist < 5.0f) + { dist = 5.0f; + } target.timeDelay = (uint64) floor(dist / speed * 1000.0f); if (m_delayMoment == 0 || m_delayMoment > target.timeDelay) + { m_delayMoment = target.timeDelay; + } } else + { target.timeDelay = UI64LIT(0); + } // Add target to list m_UniqueGOTargetInfo.push_back(target); @@ -1074,7 +1210,9 @@ void Spell::AddGOTarget(GameObject* pVictim, SpellEffectIndex effIndex) void Spell::AddGOTarget(ObjectGuid goGuid, SpellEffectIndex effIndex) { if (GameObject* go = m_caster->GetMap()->GetGameObject(goGuid)) + { AddGOTarget(go, effIndex); + } } void Spell::AddItemTarget(Item* pitem, SpellEffectIndex effIndex) @@ -1154,14 +1292,18 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // mark effects that were already handled in Spell::HandleDelayedSpellLaunch on spell launch as processed for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (IsEffectHandledOnDelayedSpellLaunch(m_spellInfo, SpellEffectIndex(i))) + { mask &= ~(1 << i); + } // maybe used in effects that are handled on hit m_damage += target->damage; } if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target + { DoSpellHitOnUnit(unit, mask); + } else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) { if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him @@ -1179,7 +1321,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) m_caster->IsVisibleForOrDetect(unit, unit, false)) { if (!unit->IsInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI()) + { ((Creature*)unit)->AI()->AttackedBy(real_caster); + } unit->AddThreat(real_caster); unit->SetInCombatWith(real_caster); @@ -1200,7 +1344,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL); } else + { procEx |= PROC_EX_NORMAL_HIT; + } uint32 absorb = 0; unitTarget->CalculateHealAbsorb(addhealth, &absorb); @@ -1215,7 +1361,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) int32 gain = caster->DealHeal(unitTarget, addhealth, m_spellInfo, crit, absorb); if (real_caster) + { unitTarget->GetHostileRefManager().threatAssist(real_caster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(m_spellInfo), m_spellInfo); + } } // Do damage and triggers else if (m_damage) @@ -1230,7 +1378,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) } // Add bonuses and fill damageInfo struct else + { caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo, m_attackType); + } unitTarget->CalculateAbsorbResistBlock(caster, &damageInfo, m_spellInfo); @@ -1244,7 +1394,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (m_canTrigger && missInfo != SPELL_MISS_REFLECT) + { caster->ProcDamageAndSpell(unitTarget, real_caster ? procAttacker : uint32(PROC_FLAG_NONE), procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo); + } // trigger weapon enchants for weapon based spells; exclude spells that stop attack, because may break CC if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->GetEquippedItemClass() == ITEM_CLASS_WEAPON && @@ -1257,7 +1409,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) if (classOpt && classOpt->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->GetSpellIconID() == 3172 && (classOpt->SpellFamilyFlags & UI64LIT(0x0004000000000000))) if(Aura* dummy = unitTarget->GetDummyAura(m_spellInfo->Id)) + { dummy->GetModifier()->m_amount = damageInfo.damage; + } caster->DealSpellDamage(&damageInfo, true); @@ -1277,7 +1431,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) { int32 bp = count * CalculateDamage(EFFECT_INDEX_2, unitTarget) * damageInfo.damage / 100; if (bp) + { caster->CastCustomSpell(unitTarget, 70890, &bp, NULL, NULL, true); + } } } } @@ -1289,7 +1445,9 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) procEx = createProcExtendMask(&damageInfo, missInfo); // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (m_canTrigger && missInfo != SPELL_MISS_REFLECT) + { caster->ProcDamageAndSpell(unit, real_caster ? procAttacker : uint32(PROC_FLAG_NONE), procVictim, procEx, 0, m_attackType, m_spellInfo); + } } // Call scripted function for AI if this spell is casted upon a creature @@ -1299,20 +1457,30 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm... ) if (real_caster && !((Creature*)unit)->IsPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) if (Player* p = real_caster->GetCharmerOrOwnerPlayerOrPlayerItself()) + { p->RewardPlayerAndGroupAtCast(unit, m_spellInfo->Id); + } if (((Creature*)unit)->AI()) + { ((Creature*)unit)->AI()->SpellHit(m_caster, m_spellInfo); + } } // Call scripted function for AI if this spell is casted by a creature if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI()) + { ((Creature*)m_caster)->AI()->SpellHitTarget(unit, m_spellInfo); + } if (real_caster && real_caster != m_caster && real_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)real_caster)->AI()) + { ((Creature*)real_caster)->AI()->SpellHitTarget(unit, m_spellInfo); + } if (m_spellAuraHolder) + { m_spellAuraHolder->SetState(SPELLAURAHOLDER_STATE_READY); + } } void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) @@ -1331,7 +1499,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) unit->IsImmuneToSpell(m_spellInfo, unit == realCaster))) { if (realCaster) + { realCaster->SendSpellMiss(unit, m_spellInfo->Id, SPELL_MISS_IMMUNE); + } ResetEffectDamageAndHeal(); return; @@ -1344,7 +1514,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) } if (realCaster && realCaster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)realCaster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit); + } if (realCaster && realCaster != unit) { @@ -1371,7 +1543,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) // not break stealth by cast targeting if (!m_spellInfo->HasAttribute(SPELL_ATTR_EX_NOT_BREAK_STEALTH)) + { unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); + } // can cause back attack (if detected), stealth removed at Spell::cast if spell break it if (!m_spellInfo->HasAttribute(SPELL_ATTR_EX3_NO_INITIAL_AGGRO) && !IsPositiveSpell(m_spellInfo->Id) && @@ -1379,23 +1553,31 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) { // use speedup check to avoid re-remove after above lines if (m_spellInfo->HasAttribute(SPELL_ATTR_EX_NOT_BREAK_STEALTH)) + { unit->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); + } // caster can be detected but have stealth aura m_caster->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); if (!unit->IsStandState() && !unit->hasUnitState(UNIT_STAT_STUNNED)) + { unit->SetStandState(UNIT_STAND_STATE_STAND); + } if (!unit->IsInCombat() && unit->GetTypeId() != TYPEID_PLAYER && ((Creature*)unit)->AI()) + { unit->AttackedBy(realCaster); + } unit->AddThreat(realCaster); unit->SetInCombatWith(realCaster); realCaster->SetInCombatWith(unit); if (Player* attackedPlayer = unit->GetCharmerOrOwnerPlayerOrPlayerItself()) + { realCaster->SetContestedPvP(attackedPlayer); + } } } else @@ -1410,7 +1592,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) // assisting case, healing and resurrection if (unit->hasUnitState(UNIT_STAT_ATTACK_PLAYER)) + { realCaster->SetContestedPvP(); + } if (unit->IsInCombat() && !m_spellInfo->HasAttribute(SPELL_ATTR_EX3_NO_INITIAL_AGGRO)) { @@ -1437,7 +1621,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) m_spellAuraHolder->setDiminishGroup(m_diminishGroup); } else + { m_spellAuraHolder = NULL; + } for (int effectNumber = 0; effectNumber < MAX_EFFECT_INDEX; ++effectNumber) { @@ -1452,7 +1638,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) // Apply multiplier mods if (realCaster) if (Player* modOwner = realCaster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier, this); + } m_damageMultipliers[effectNumber] *= multiplier; } } @@ -1491,7 +1679,9 @@ void Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask) unit->AddSpellAuraHolder(m_spellAuraHolder); } else + { delete m_spellAuraHolder; + } } } @@ -1517,14 +1707,18 @@ void Spell::DoAllEffectOnTarget(GOTargetInfo* target) for (int effectNumber = 0; effectNumber < MAX_EFFECT_INDEX; ++effectNumber) if (effectMask & (1 << effectNumber)) + { HandleEffects(NULL, NULL, go, SpellEffectIndex(effectNumber)); + } // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) // ignore autorepeat/melee casts for speed (not exist quest for spells (hm... ) if (!IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) { if (Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself()) + { p->RewardPlayerAndGroupAtCast(go, m_spellInfo->Id); + } } } @@ -1538,7 +1732,9 @@ void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) for (int effectNumber = 0; effectNumber < MAX_EFFECT_INDEX; ++effectNumber) if (effectMask & (1 << effectNumber)) + { HandleEffects(NULL, target->item, NULL, SpellEffectIndex(effectNumber)); + } } void Spell::HandleDelayedSpellLaunch(TargetInfo* target) @@ -1585,14 +1781,18 @@ void Spell::HandleDelayedSpellLaunch(TargetInfo* target) // Apply multiplier mods if (real_caster) if (Player* modOwner = real_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_EFFECT_PAST_FIRST, multiplier, this); + } m_damageMultipliers[effectNumber] *= multiplier; } } } if (m_damage > 0) + { caster->CalculateSpellDamage(&damageInfo, m_damage, m_spellInfo, m_attackType); + } } target->damage = damageInfo.damage; @@ -1605,14 +1805,20 @@ void Spell::InitializeDamageMultipliers() { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (spellEffect->Effect == 0) + { continue; + } uint32 EffectChainTarget = spellEffect->EffectChainTarget; if (Unit* realCaster = GetAffectiveCaster()) if (Player* modOwner = realCaster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, EffectChainTarget, this); + } m_damageMultipliers[i] = 1.0f; if( (spellEffect->EffectImplicitTargetA == TARGET_CHAIN_DAMAGE || spellEffect->EffectImplicitTargetA == TARGET_CHAIN_HEAL) && @@ -1639,7 +1845,9 @@ bool Spell::IsAliveUnitPresentInTargetList() // either unit is alive and normal spell, or unit dead and deathonly-spell if (unit && (unit->IsAlive() != IsDeathOnlySpell(m_spellInfo))) + { needAliveTargetMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target + } } } @@ -1745,7 +1953,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case TARGET_RANDOM_NEARBY_LOC: // special case for Fatal Attraction (BT, Mother Shahraz) if (m_spellInfo->Id == 40869) + { radius = 30.0f; + } // Get a random point in circle. Use sqrt(rand) to correct distribution when converting polar to Cartesian coordinates. radius *= sqrtf(rand_norm_f()); @@ -1870,7 +2080,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } if (tempTargetUnitMap.empty()) + { break; + } tempTargetUnitMap.sort(TargetDistanceOrderNear(m_caster)); @@ -1881,7 +2093,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& ++t, ++itr; if (!t) + { break; + } itr = tempTargetUnitMap.begin(); std::advance(itr, rand() % t); @@ -1899,7 +2113,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& while (t && next != tempTargetUnitMap.end()) { if (!prev->IsWithinDist(*next, CHAIN_SPELL_JUMP_RADIUS)) + { break; + } if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_ATTR_EX2_IGNORE_LOS) && !prev->IsWithinLOSInMap(*next)) { @@ -1926,7 +2142,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { Pet* tmpUnit = m_caster->GetPet(); if (!tmpUnit) break; - targetUnitMap.push_back(tmpUnit); + { + targetUnitMap.push_back(tmpUnit); + } break; } case TARGET_CHAIN_DAMAGE: @@ -1936,7 +2154,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& if (Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), this, effIndex)) { if (m_targets.getUnitTarget() && m_targets.getUnitTarget() != pUnitTarget) + { m_spellFlags |= SPELL_FLAG_REDIRECTED; + } m_targets.setUnitTarget(pUnitTarget); targetUnitMap.push_back(pUnitTarget); @@ -1947,13 +2167,17 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& Unit* pUnitTarget = m_targets.getUnitTarget(); WorldObject* originalCaster = GetAffectiveCasterObject(); if (!pUnitTarget || !originalCaster) + { break; + } unMaxTargets = EffectChainTarget; float max_range; if(m_spellInfo->GetDmgClass() == SPELL_DAMAGE_CLASS_MELEE) + { max_range = radius; + } else // FIXME: This very like horrible hack and wrong for most spells max_range = radius + unMaxTargets * CHAIN_SPELL_JUMP_RADIUS; @@ -1966,12 +2190,16 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } if (tempTargetUnitMap.empty()) + { break; + } tempTargetUnitMap.sort(TargetDistanceOrderNear(pUnitTarget)); if (*tempTargetUnitMap.begin() == pUnitTarget) + { tempTargetUnitMap.erase(tempTargetUnitMap.begin()); + } targetUnitMap.push_back(pUnitTarget); uint32 t = unMaxTargets - 1; @@ -1981,7 +2209,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& while (t && next != tempTargetUnitMap.end()) { if (!prev->IsWithinDist(*next, CHAIN_SPELL_JUMP_RADIUS)) + { break; + } if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_ATTR_EX2_IGNORE_LOS) && !prev->IsWithinLOSInMap(*next)) { @@ -2017,7 +2247,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case 63981: // Stone Grip (h) { if (Unit* pVictim = m_caster->getVictim()) + { targetUnitMap.remove(pVictim); + } break; } // Other special cases @@ -2047,7 +2279,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& default: // Select friendly targets for positive effect if (IsPositiveEffect(m_spellInfo, effIndex)) + { targetB = SPELL_TARGETS_FRIENDLY; + } break; } @@ -2063,16 +2297,22 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& for (UnitList::const_iterator iter = tempTargetUnitMap.begin(); iter != tempTargetUnitMap.end(); ++iter) { if ((*iter)->GetTypeId() != TYPEID_UNIT) + { continue; + } for (SQLMultiStorage::SQLMultiSIterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST) { if (i_spellST->CanNotHitWithSpellEffect(effIndex)) + { continue; + } // only creature entries supported for this target type if (i_spellST->type == SPELL_TARGET_TYPE_GAMEOBJECT) + { continue; + } if ((*iter)->GetEntry() == i_spellST->targetEntry) { @@ -2095,7 +2335,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case TARGET_AREAEFFECT_CUSTOM: { if (spellEffect && spellEffect->Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA) + { break; + } else if (spellEffect && spellEffect->Effect == SPELL_EFFECT_SUMMON) { targetUnitMap.push_back(m_caster); @@ -2112,16 +2354,22 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& for (UnitList::const_iterator iter = tempTargetUnitMap.begin(); iter != tempTargetUnitMap.end(); ++iter) { if ((*iter)->GetTypeId() != TYPEID_UNIT) + { continue; + } for (SQLMultiStorage::SQLMultiSIterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST) { if (i_spellST->CanNotHitWithSpellEffect(effIndex)) + { continue; + } // only creature entries supported for this target type if (i_spellST->type == SPELL_TARGET_TYPE_GAMEOBJECT) + { continue; + } if ((*iter)->GetEntry() == i_spellST->targetEntry) { @@ -2145,9 +2393,13 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& for (UnitList::iterator itr = targetUnitMap.begin(); itr != targetUnitMap.end();) { if (!(*itr)->IsTargetableForAttack(m_spellInfo->HasAttribute(SPELL_ATTR_EX3_CAST_ON_DEAD))) + { targetUnitMap.erase(itr++); + } else + { ++itr; + } } } break; @@ -2159,18 +2411,26 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& float x, y, z; if (targetMode == TARGET_AREAEFFECT_GO_AROUND_SOURCE && (m_targets.m_targetMask & TARGET_FLAG_SOURCE_LOCATION)) + { m_targets.getSource(x, y, z); + } else if (targetMode == TARGET_AREAEFFECT_GO_AROUND_DEST) + { m_targets.getDestination(x, y, z); + } else // can also happen for GO_AROUND_SOURCE without SOURCE_LOCATION + { m_caster->GetPosition(x, y, z); + } bool fixedTargetExist = false; SQLMultiStorage::SQLMSIteratorBounds bounds = sSpellScriptTargetStorage.getBounds(m_spellInfo->Id); for (SQLMultiStorage::SQLMultiSIterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST) { if (i_spellST->CanNotHitWithSpellEffect(effIndex)) + { continue; + } if (i_spellST->type == SPELL_TARGET_TYPE_GAMEOBJECT) { @@ -2217,7 +2477,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { // targets the ground, not the units in the area if(!spellEffect) + { break; + } switch(spellEffect->Effect) { @@ -2232,7 +2494,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& // Mind Sear, triggered if (m_spellInfo->IsFitToFamily(SPELLFAMILY_PRIEST, UI64LIT(0x0008000000000000))) if (Unit* unitTarget = m_targets.getUnitTarget()) + { targetUnitMap.remove(unitTarget); + } break; } @@ -2241,7 +2505,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case TARGET_DUELVSPLAYER_COORDINATES: { if (Unit* currentTarget = m_targets.getUnitTarget()) + { m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ()); + } break; } case TARGET_ALL_PARTY_AROUND_CASTER: @@ -2251,7 +2517,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& // only affect pet and owner targetUnitMap.push_back(m_caster); if (Unit* owner = m_caster->GetOwner()) + { targetUnitMap.push_back(owner); + } } else { @@ -2271,25 +2539,37 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { // in arena, target should be only caster if (m_caster->GetMap()->IsBattleArena()) + { targetUnitMap.push_back(m_caster); + } else + { FillRaidOrPartyManaPriorityTargets(targetUnitMap, m_caster, m_caster, radius, 10, true, false, true); + } } else if (m_spellInfo->Id == 52759) // Ancestral Awakening (special target selection) + { FillRaidOrPartyHealthPriorityTargets(targetUnitMap, m_caster, m_caster, radius, 1, true, false, true); + } else + { FillRaidOrPartyTargets(targetUnitMap, m_caster, m_caster, radius, true, true, IsPositiveSpell(m_spellInfo->Id)); + } break; } case TARGET_SINGLE_FRIEND: case TARGET_SINGLE_FRIEND_2: if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } break; case TARGET_NONCOMBAT_PET: if (Unit* target = m_targets.getUnitTarget()) if (target->GetTypeId() == TYPEID_UNIT && ((Creature*)target)->IsPet() && ((Pet*)target)->getPetType() == MINI_PET) + { targetUnitMap.push_back(target); + } break; case TARGET_SUMMONER: { @@ -2300,21 +2580,31 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } if (caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTemporarySummon()) + { targetUnitMap.push_back(((TemporarySummon*)(Creature*)caster)->GetSummoner()); + } else if (caster->GetTypeId() == TYPEID_GAMEOBJECT && !((GameObject*)caster)->HasStaticDBSpawnData()) + { targetUnitMap.push_back(((GameObject*)caster)->GetOwner()); + } else + { sLog.outError("SPELL: Spell ID %u with target ID %u was used by non temporary summon object %s.", m_spellInfo->Id, targetMode, caster->GetGuidStr().c_str()); + } break; } case TARGET_CONTROLLED_VEHICLE: if (m_caster->IsBoarded() && m_caster->GetTransportInfo()->IsOnVehicle()) + { targetUnitMap.push_back((Unit*)m_caster->GetTransportInfo()->GetTransport()); + } break; case TARGET_VEHICLE_DRIVER: if (m_caster->IsVehicle()) if (Unit* vehicleDriver = m_caster->GetCharmer()) + { targetUnitMap.push_back(vehicleDriver); + } break; case TARGET_VEHICLE_PASSENGER_0: case TARGET_VEHICLE_PASSENGER_1: @@ -2326,13 +2616,17 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case TARGET_VEHICLE_PASSENGER_7: if (m_caster->IsVehicle()) if (Unit* passenger = m_caster->GetVehicleInfo()->GetPassenger(targetMode - TARGET_VEHICLE_PASSENGER_0)) + { targetUnitMap.push_back(passenger); + } break; case TARGET_CASTER_COORDINATES: { // Check original caster is GO - set its coordinates as src cast if (WorldObject* caster = GetCastingObject()) + { m_targets.setSource(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ()); + } break; } case TARGET_ALL_HOSTILE_UNITS_AROUND_CASTER: @@ -2362,19 +2656,25 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& // checked in Spell::CheckCast if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Unit* target = m_caster->GetMap()->GetPet(((Player*)m_caster)->GetSelectionGuid())) + { targetUnitMap.push_back(target); + } } // Circle of Healing else if (m_spellInfo->GetSpellFamilyName() == SPELLFAMILY_PRIEST && m_spellInfo->GetSpellVisual() == 8253) { Unit* target = m_targets.getUnitTarget(); if (!target) + { target = m_caster; + } uint32 count = 5; // Glyph of Circle of Healing if (Aura const* glyph = m_caster->GetDummyAura(55675)) + { count += glyph->GetModifier()->m_amount; + } FillRaidOrPartyHealthPriorityTargets(targetUnitMap, m_caster, target, radius, count, true, false, true); } @@ -2383,13 +2683,17 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { Unit* target = m_targets.getUnitTarget(); if (!target) + { target = m_caster; + } uint32 count = CalculateDamage(EFFECT_INDEX_2, m_caster); // stored in dummy effect, affected by mods FillRaidOrPartyHealthPriorityTargets(targetUnitMap, m_caster, target, radius, count, true, false, true); } else + { FillAreaTargets(targetUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_FRIENDLY); + } break; // TARGET_SINGLE_PARTY means that the spells can only be casted on a party member and not on the caster (some seals, fire shield from imp, etc..) case TARGET_SINGLE_PARTY: @@ -2449,7 +2753,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } case TARGET_GAMEOBJECT: if (m_targets.getGOTarget()) + { AddGOTarget(m_targets.getGOTarget(), effIndex); + } break; case TARGET_IN_FRONT_OF_CASTER: { @@ -2475,7 +2781,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& SpellTargets targetB = SPELL_TARGETS_AOE_DAMAGE; if (spellEffect->Effect == SPELL_EFFECT_SCRIPT_EFFECT) + { targetB = SPELL_TARGETS_ALL; + } UnitList tempTargetUnitMap; SQLMultiStorage::SQLMSIteratorBounds bounds = sSpellScriptTargetStorage.getBounds(m_spellInfo->Id); @@ -2489,16 +2797,22 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& for (UnitList::const_iterator iter = tempTargetUnitMap.begin(); iter != tempTargetUnitMap.end(); ++iter) { if ((*iter)->GetTypeId() != TYPEID_UNIT) + { continue; + } for (SQLMultiStorage::SQLMultiSIterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST) { if (i_spellST->CanNotHitWithSpellEffect(effIndex)) + { continue; + } // only creature entries supported for this target type if (i_spellST->type == SPELL_TARGET_TYPE_GAMEOBJECT) + { continue; + } if ((*iter)->GetEntry() == i_spellST->targetEntry) { @@ -2545,29 +2859,41 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } case TARGET_GAMEOBJECT_ITEM: if (m_targets.getGOTargetGuid()) + { AddGOTarget(m_targets.getGOTarget(), effIndex); + } else if (m_targets.getItemTarget()) + { AddItemTarget(m_targets.getItemTarget(), effIndex); + } break; case TARGET_MASTER: if (Unit* owner = m_caster->GetCharmerOrOwner()) + { targetUnitMap.push_back(owner); + } break; case TARGET_ALL_ENEMY_IN_AREA_CHANNELED: // targets the ground, not the units in the area if (spellEffect && spellEffect->Effect!=SPELL_EFFECT_PERSISTENT_AREA_AURA) + { FillAreaTargets(targetUnitMap, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE); + } break; case TARGET_MINION: if(spellEffect && spellEffect->Effect != SPELL_EFFECT_DUEL) + { targetUnitMap.push_back(m_caster); + } break; case TARGET_SINGLE_ENEMY: { if (Unit* pUnitTarget = m_caster->SelectMagnetTarget(m_targets.getUnitTarget(), this, effIndex)) { if (m_targets.getUnitTarget() && m_targets.getUnitTarget() != pUnitTarget) + { m_spellFlags |= SPELL_FLAG_REDIRECTED; + } m_targets.setUnitTarget(pUnitTarget); targetUnitMap.push_back(pUnitTarget); @@ -2583,7 +2909,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { targetUnitMap.push_back(m_caster); if (owner->GetTypeId() == TYPEID_PLAYER) + { pTarget = (Player*)owner; + } } else if (m_caster->GetTypeId() == TYPEID_PLAYER) { @@ -2595,11 +2923,15 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { Unit* targetOwner = target->GetOwner(); if (targetOwner->GetTypeId() == TYPEID_PLAYER) + { pTarget = (Player*)targetOwner; + } } } else + { pTarget = (Player*)target; + } } } @@ -2617,18 +2949,24 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& if (Target && Target->GetSubGroup() == subgroup && !m_caster->IsHostileTo(Target)) { if (pTarget->IsWithinDistInMap(Target, radius)) + { targetUnitMap.push_back(Target); + } if (Pet* pet = Target->GetPet()) if (pTarget->IsWithinDistInMap(pet, radius)) + { targetUnitMap.push_back(pet); + } } } } else if (owner) { if (m_caster->IsWithinDistInMap(owner, radius)) + { targetUnitMap.push_back(owner); + } } else if (pTarget) { @@ -2636,16 +2974,22 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& if (Pet* pet = pTarget->GetPet()) if (m_caster->IsWithinDistInMap(pet, radius)) + { targetUnitMap.push_back(pet); + } } break; } case TARGET_SCRIPT: { if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } if (m_targets.getItemTarget()) + { AddItemTarget(m_targets.getItemTarget(), effIndex); + } break; } case TARGET_SELF_FISHING: @@ -2655,10 +2999,14 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { Unit* pUnitTarget = m_targets.getUnitTarget(); if (!pUnitTarget) + { break; + } if (EffectChainTarget <= 1) + { targetUnitMap.push_back(pUnitTarget); + } else { unMaxTargets = EffectChainTarget; @@ -2669,15 +3017,21 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& FillAreaTargets(tempTargetUnitMap, max_range, PUSH_SELF_CENTER, SPELL_TARGETS_FRIENDLY); if (m_caster != pUnitTarget && std::find(tempTargetUnitMap.begin(), tempTargetUnitMap.end(), m_caster) == tempTargetUnitMap.end()) + { tempTargetUnitMap.push_front(m_caster); + } tempTargetUnitMap.sort(TargetDistanceOrderNear(pUnitTarget)); if (tempTargetUnitMap.empty()) + { break; + } if (*tempTargetUnitMap.begin() == pUnitTarget) + { tempTargetUnitMap.erase(tempTargetUnitMap.begin()); + } targetUnitMap.push_back(pUnitTarget); uint32 t = unMaxTargets - 1; @@ -2687,7 +3041,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& while (t && next != tempTargetUnitMap.end()) { if (!prev->IsWithinDist(*next, CHAIN_SPELL_JUMP_RADIUS)) + { break; + } if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_ATTR_EX2_IGNORE_LOS) && !prev->IsWithinLOSInMap(*next)) { @@ -2744,7 +3100,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } } else if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } break; } case TARGET_TABLE_X_Y_Z_COORDINATES: @@ -2772,13 +3130,21 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& // explicit cast data from client or server-side cast // some spell at client send caster if (m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster) + { pTarget = m_targets.getUnitTarget(); + } else if (m_caster->getVictim()) + { pTarget = m_caster->getVictim(); + } else if (m_caster->GetTypeId() == TYPEID_PLAYER) + { pTarget = ObjectAccessor::GetUnit(*m_caster, ((Player*)m_caster)->GetSelectionGuid()); + } else if (m_targets.getUnitTarget()) + { pTarget = m_caster; + } if (pTarget) { @@ -2805,10 +3171,14 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case TARGET_DYNAMIC_OBJECT_COORDINATES: // if parent spell create dynamic object extract area from it if (DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell ? m_triggeredByAuraSpell->Id : m_spellInfo->Id)) + { m_targets.setDestination(dynObj->GetPositionX(), dynObj->GetPositionY(), dynObj->GetPositionZ()); + } // else use destination of target if no destination set (ie for Mind Sear - 53022) else if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) && m_targets.m_targetMask & TARGET_FLAG_UNIT) + { m_targets.setDestination(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ); + } break; case TARGET_DYNAMIC_OBJECT_FRONT: case TARGET_DYNAMIC_OBJECT_BEHIND: @@ -2823,10 +3193,14 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& // TODO: some summoned will make caster be half inside summoned object. Need to fix // that in the below code (nearpoint vs closepoint, etc). if (!spellEffect || spellEffect->GetRadiusIndex() == 0) + { radius = 0.0f; + } if (m_spellInfo->Id == 50019) // Hawk Hunting, problematic 50K radius + { radius = 10.0f; + } float angle = m_caster->GetOrientation(); switch (targetMode) @@ -2899,7 +3273,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& // add here custom effects that need default target. // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!! if(!spellEffect) + { break; + } switch(spellEffect->Effect) { @@ -2922,7 +3298,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case TYPEID_CORPSE: m_targets.setCorpseTarget((Corpse*)result); if (Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGuid())) + { targetUnitMap.push_back(owner); + } break; } } @@ -2930,7 +3308,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& { // clear cooldown at fail if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->RemoveSpellCooldown(m_spellInfo->Id, true); + } SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES); finish(false); } @@ -2938,12 +3318,16 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } default: if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } break; } // Add AoE target-mask to self, if no target-dest provided already if ((m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) == 0) + { m_targets.setDestination(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()); + } break; } case SPELL_EFFECT_BIND: @@ -2962,24 +3346,34 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case SPELL_EFFECT_REPUTATION: case SPELL_EFFECT_SEND_TAXI: if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example) else if (spellEffect->Effect == SPELL_EFFECT_TRIGGER_SPELL) + { targetUnitMap.push_back(m_caster); + } break; case SPELL_EFFECT_SUMMON_PLAYER: if (m_caster->GetTypeId() == TYPEID_PLAYER && ((Player*)m_caster)->GetSelectionGuid()) if (Player* target = sObjectMgr.GetPlayer(((Player*)m_caster)->GetSelectionGuid())) + { targetUnitMap.push_back(target); + } break; case SPELL_EFFECT_RESURRECT_NEW: if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } if (m_targets.getCorpseTargetGuid()) { if (Corpse* corpse = m_caster->GetMap()->GetCorpse(m_targets.getCorpseTargetGuid())) if (Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGuid())) + { targetUnitMap.push_back(owner); + } } break; case SPELL_EFFECT_TELEPORT_UNITS: @@ -2998,11 +3392,15 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& break; case SPELL_EFFECT_PERSISTENT_AREA_AURA: if (Unit* currentTarget = m_targets.getUnitTarget()) + { m_targets.setDestination(currentTarget->GetPositionX(), currentTarget->GetPositionY(), currentTarget->GetPositionZ()); + } break; case SPELL_EFFECT_LEARN_PET_SPELL: if (Pet* pet = m_caster->GetPet()) + { targetUnitMap.push_back(pet); + } break; case SPELL_EFFECT_ENCHANT_ITEM: case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: @@ -3011,7 +3409,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case SPELL_EFFECT_PROSPECTING: case SPELL_EFFECT_MILLING: if (m_targets.getItemTarget()) + { AddItemTarget(m_targets.getItemTarget(), effIndex); + } break; case SPELL_EFFECT_APPLY_AURA: switch(spellEffect->EffectApplyAuraName) @@ -3022,23 +3422,31 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& break; default: // apply to target in other case if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } break; } break; case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: // AreaAura if ((m_spellInfo->GetAttributes() == (SPELL_ATTR_NOT_SHAPESHIFT | SPELL_ATTR_UNK18 | SPELL_ATTR_CASTABLE_WHILE_MOUNTED | SPELL_ATTR_CASTABLE_WHILE_SITTING)) || (m_spellInfo->GetAttributes() == SPELL_ATTR_NOT_SHAPESHIFT)) + { SetTargetMap(effIndex, TARGET_AREAEFFECT_PARTY, targetUnitMap); + } break; case SPELL_EFFECT_SKIN_PLAYER_CORPSE: if (m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } else if (m_targets.getCorpseTargetGuid()) { if (Corpse* corpse = m_caster->GetMap()->GetCorpse(m_targets.getCorpseTargetGuid())) if (Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGuid())) + { targetUnitMap.push_back(owner); + } } break; default: @@ -3057,7 +3465,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& const SpellEffectEntry* spellEffect = m_spellInfo->GetSpellEffect(effIndex); if (targetMode != TARGET_SELF && targetMode != TARGET_SELF2 && (spellEffect && spellEffect->Effect != SPELL_EFFECT_SUMMON)) + { targetUnitMap.remove(m_caster); + } } if (unMaxTargets && targetUnitMap.size() > unMaxTargets) @@ -3093,7 +3503,9 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& } // the player's target will always be added to the map if (removed_utarget && m_targets.getUnitTarget()) + { targetUnitMap.push_back(m_targets.getUnitTarget()); + } } if (!tempTargetGOList.empty()) // GO CASE { @@ -3165,7 +3577,9 @@ void Spell::SpellStart(SpellCastTargets const* targets, Aura* triggeredByAura) m_targets = *targets; if (m_CastItem) + { m_CastItemGuid = m_CastItem->GetObjectGuid(); + } m_castPositionX = m_caster->GetPositionX(); m_castPositionY = m_caster->GetPositionY(); @@ -3173,7 +3587,9 @@ void Spell::SpellStart(SpellCastTargets const* targets, Aura* triggeredByAura) m_castOrientation = m_caster->GetOrientation(); if (triggeredByAura) + { m_triggeredByAuraSpell = triggeredByAura->GetSpellProto(); + } // create and add update event for this spell SpellEvent* Event = new SpellEvent(this); @@ -3205,7 +3621,9 @@ void Spell::SpellStart(SpellCastTargets const* targets, Aura* triggeredByAura) return; } else + { Prepare(); + } } void Spell::Prepare() @@ -3223,7 +3641,9 @@ void Spell::Prepare() ReSetTimer(); if (!m_IsTriggeredSpell) + { m_caster->RemoveAurasOnCast(m_spellInfo); + } // add non-triggered (with cast time and without) if (!m_IsTriggeredSpell) @@ -3238,11 +3658,15 @@ void Spell::Prepare() // Execute instant spells immediate if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat() && !IsChanneledSpell(m_spellInfo)) + { cast(); + } } // execute triggered without cast time explicitly in call point else if (m_timer == 0) + { cast(true); + } // else triggered with cast time will execute execute at next tick or later // without adding to cast type slot // will not show cast bar but will show effects at casting time etc @@ -3270,7 +3694,9 @@ void Spell::cancel() SendInterrupted(0); if (sendInterrupt) + { SendCastResult(SPELL_FAILED_INTERRUPTED); + } } break; case SPELL_STATE_CASTING: @@ -3281,7 +3707,9 @@ void Spell::cancel() { Unit* unit = m_caster->GetObjectGuid() == (*ihit).targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (unit && unit->IsAlive()) + { unit->RemoveAurasByCasterSpell(m_spellInfo->Id, m_caster->GetObjectGuid()); + } // prevent other effects applying if spell is already interrupted // i.e. if effects have different targets and it was interrupted on one of them when @@ -3294,7 +3722,9 @@ void Spell::cancel() SendInterrupted(0); if (sendInterrupt) + { SendCastResult(SPELL_FAILED_INTERRUPTED); + } } break; default: @@ -3337,7 +3767,9 @@ void Spell::cast(bool skipCheck) } if (m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster) + { m_caster->SetInFront(m_targets.getUnitTarget()); + } SpellCastResult castResult = CheckPower(); if (castResult != SPELL_CAST_OK) @@ -3372,7 +3804,9 @@ void Spell::cast(bool skipCheck) { // Bandages if (m_spellInfo->GetMechanic() == MECHANIC_BANDAGE) + { AddPrecastSpell(11196); // Recently Bandaged + } // Stoneskin else if (m_spellInfo->Id == 20594) AddTriggeredSpell(65116); // Stoneskin - armor 10% for 8 sec @@ -3380,28 +3814,40 @@ void Spell::cast(bool skipCheck) { AddPrecastSpell(96223); // Run Speed Marker if (m_caster->HasWorgenForm()) + { AddPrecastSpell(97709); // Altered Form + } } else if (m_spellInfo->Id == 68996) // Two Forms { if (m_caster->IsInWorgenForm()) + { m_caster->RemoveSpellsCausingAura(SPELL_AURA_WORGEN_TRANSFORM); + } else if (m_caster->HasWorgenForm()) + { AddPrecastSpell(97709); // Altered Form + } } // Chaos Bane strength buff else if (m_spellInfo->Id == 71904) + { AddTriggeredSpell(73422); + } // Weak Alcohol else if (m_spellInfo->Id == 1306 && m_spellInfo->GetSpellVisual(0) == 11359) + { AddTriggeredSpell(51655); // BOTM - Create Empty Brew Bottle + } break; } case SPELLFAMILY_MAGE: { // Ice Block if (classOpt && classOpt->SpellFamilyFlags & UI64LIT(0x0000008000000000)) + { AddPrecastSpell(41425); // Hypothermia + } // Icy Veins else if (m_spellInfo->Id == 12472) { @@ -3414,7 +3860,9 @@ void Spell::cast(bool skipCheck) } // Fingers of Frost else if (m_spellInfo->Id == 44544) + { AddPrecastSpell(74396); // Fingers of Frost + } break; } case SPELLFAMILY_WARRIOR: @@ -3423,20 +3871,26 @@ void Spell::cast(bool skipCheck) if (classOpt && (classOpt->SpellFamilyFlags & UI64LIT(0x0000020000000000)) && m_spellInfo->GetCategory()==1209) { if (m_caster->HasAura(58375)) // Glyph of Blocking + { AddTriggeredSpell(58374); // Glyph of Blocking + } } // Bloodrage if (classOpt && (classOpt->SpellFamilyFlags & UI64LIT(0x0000000000000100))) { if (m_caster->HasAura(70844)) // Item - Warrior T10 Protection 4P Bonus + { AddTriggeredSpell(70845); // Stoicism + } } // Bloodsurge (triggered), Sudden Death (triggered) else if (m_spellInfo->Id == 46916 || m_spellInfo->Id == 52437) // Item - Warrior T10 Melee 4P Bonus if (Aura* aur = m_caster->GetAura(70847, EFFECT_INDEX_0)) if (roll_chance_i(aur->GetModifier()->m_amount)) + { AddTriggeredSpell(70849); // Extra Charge! + } break; } case SPELLFAMILY_PRIEST: @@ -3447,7 +3901,9 @@ void Spell::cast(bool skipCheck) AddPrecastSpell(6788); // Weakened Soul // Prayer of Mending (jump animation), we need formal caster instead original for correct animation else if (classOpt && classOpt->SpellFamilyFlags & UI64LIT(0x0000002000000000)) + { AddTriggeredSpell(41637); + } switch (m_spellInfo->Id) { @@ -3468,16 +3924,22 @@ void Spell::cast(bool skipCheck) { // Faerie Fire (Feral) if (m_spellInfo->Id == 16857 && m_caster->GetShapeshiftForm() != FORM_CAT) + { AddTriggeredSpell(60089); + } // Clearcasting else if (m_spellInfo->Id == 16870) { if (m_caster->HasAura(70718)) // Item - Druid T10 Balance 2P Bonus + { AddPrecastSpell(70721); // Omen of Doom + } } // Berserk (Bear Mangle part) else if (m_spellInfo->Id == 50334) + { AddTriggeredSpell(58923); + } break; } case SPELLFAMILY_ROGUE: @@ -3492,16 +3954,22 @@ void Spell::cast(bool skipCheck) { // Deterrence if (m_spellInfo->Id == 19263) + { AddPrecastSpell(67801); + } // Kill Command else if (m_spellInfo->Id == 34026) { if (m_caster->HasAura(37483)) // Improved Kill Command - Item set bonus + { m_caster->CastSpell(m_caster, 37482, true);// Exploited Weakness + } } // Lock and Load else if (m_spellInfo->Id == 56453) + { AddPrecastSpell(67544); // Lock and Load Marker + } break; } case SPELLFAMILY_PALADIN: @@ -3510,13 +3978,17 @@ void Spell::cast(bool skipCheck) if (m_spellInfo->Id == 31842) { if (m_caster->HasAura(70755)) // Item - Paladin T10 Holy 2P Bonus + { AddPrecastSpell(71166); // Divine Illumination + } } // Hand of Reckoning else if (m_spellInfo->Id == 62124) { if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTargetGuid() != m_caster->GetObjectGuid()) + { AddPrecastSpell(67485); // Hand of Rekoning (no typos in name ;) ) + } } // Divine Shield, Divine Protection or Hand of Protection else if (classOpt && classOpt->SpellFamilyFlags & UI64LIT(0x0000000000400080)) @@ -3529,11 +4001,15 @@ void Spell::cast(bool skipCheck) { // only for self cast if (m_caster == m_targets.getUnitTarget()) + { AddPrecastSpell(25771); // Forbearance + } } // Avenging Wrath else if (classOpt && classOpt->SpellFamilyFlags & UI64LIT(0x0000200000000000)) + { AddPrecastSpell(61987); // Avenging Wrath Marker + } break; } case SPELLFAMILY_SHAMAN: @@ -3541,13 +4017,19 @@ void Spell::cast(bool skipCheck) SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(EFFECT_INDEX_0); // Bloodlust if (m_spellInfo->Id == 2825) + { AddPrecastSpell(57724); // Sated + } // Heroism else if (m_spellInfo->Id == 32182) + { AddPrecastSpell(57723); // Exhaustion + } // Spirit Walk else if (m_spellInfo->Id == 58875) + { AddPrecastSpell(58876); + } // Totem of Wrath else if (spellEffect && spellEffect->Effect==SPELL_EFFECT_APPLY_AREA_AURA_RAID && classOpt && classOpt->SpellFamilyFlags & UI64LIT(0x0000000004000000)) // only for main totem spell cast @@ -3558,7 +4040,9 @@ void Spell::cast(bool skipCheck) { // Chains of Ice if (m_spellInfo->Id == 45524) + { AddTriggeredSpell(55095); // Frost Fever + } break; } default: @@ -3572,7 +4056,9 @@ void Spell::cast(bool skipCheck) if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (!m_IsTriggeredSpell && m_CastItem) + { ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry()); + } ((Player*)m_caster)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id); @@ -3605,7 +4091,9 @@ void Spell::cast(bool skipCheck) Unit* procTarget = m_targets.getUnitTarget(); if (!procTarget) + { procTarget = m_caster; + } // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells float speed = m_spellInfo->GetSpeed() == 0.0f && m_triggeredBySpellInfo ? m_triggeredBySpellInfo->GetSpeed() : m_spellInfo->GetSpeed(); @@ -3704,7 +4192,9 @@ void Spell::handle_immediate() TakeCastItem(); if (m_spellState != SPELL_STATE_CASTING) + { finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell) + } } uint64 Spell::handle_delayed(uint64 t_offset) @@ -3723,9 +4213,13 @@ uint64 Spell::handle_delayed(uint64 t_offset) if (!ihit->processed) { if (ihit->timeDelay <= t_offset) + { DoAllEffectOnTarget(&(*ihit)); + } else if (next_time == 0 || ihit->timeDelay < next_time) + { next_time = ihit->timeDelay; + } } } @@ -3735,9 +4229,13 @@ uint64 Spell::handle_delayed(uint64 t_offset) if (!ighit->processed) { if (ighit->timeDelay <= t_offset) + { DoAllEffectOnTarget(&(*ighit)); + } else if (next_time == 0 || ighit->timeDelay < next_time) + { next_time = ighit->timeDelay; + } } } // All targets passed - need finish phase @@ -3768,7 +4266,9 @@ void Spell::_handle_immediate_phase() { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect || spellEffect->Effect == 0) + { continue; + } // apply Send Event effect to ground in case empty target lists if( spellEffect->Effect == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(SpellEffectIndex(j)) ) @@ -3779,7 +4279,9 @@ void Spell::_handle_immediate_phase() // Don't do spell log, if is school damage spell if(spellEffect->Effect == SPELL_EFFECT_SCHOOL_DAMAGE || spellEffect->Effect == 0) + { m_needSpellLog = false; + } } // initialize Diminishing Returns Data @@ -3797,7 +4299,9 @@ void Spell::_handle_immediate_phase() { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } // persistent area auras target only the ground if (spellEffect->Effect == SPELL_EFFECT_PERSISTENT_AREA_AURA || //summon a gameobject at the spell's destination xyz @@ -3810,7 +4314,9 @@ void Spell::_handle_finish_phase() { // spell log if (m_needSpellLog) + { SendLogExecute(); + } } void Spell::SendSpellCooldown() @@ -3867,10 +4373,14 @@ void Spell::update(uint32 difftime) { // always cancel for channeled spells if (m_spellState == SPELL_STATE_CASTING && !m_spellInfo->HasAttribute(SPELL_ATTR_EX5_CAN_CHANNEL_WHEN_MOVING)) + { cancel(); + } // don't cancel for melee, autorepeat, triggered and instant spells else if(!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell && (spellInterrupts && spellInterrupts->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT)) + { cancel(); + } } switch (m_spellState) @@ -3880,13 +4390,19 @@ void Spell::update(uint32 difftime) if (m_timer) { if (difftime >= m_timer) + { m_timer = 0; + } else + { m_timer -= difftime; + } } if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat()) + { cast(); + } } break; case SPELL_STATE_CASTING: { @@ -3904,12 +4420,16 @@ void Spell::update(uint32 difftime) { // certain channel spells are not interrupted if (!m_spellInfo->HasAttribute(SPELL_ATTR_EX_CHANNELED_1) && !m_spellInfo->HasAttribute(SPELL_ATTR_EX3_UNK28)) + { cancel(); + } } // check if player has turned if flag is set if( spellInterrupts && (spellInterrupts->ChannelInterruptFlags & CHANNEL_FLAG_TURNING) && m_castOrientation != m_caster->GetOrientation() ) + { cancel(); + } } // check if there are alive targets left @@ -3920,9 +4440,13 @@ void Spell::update(uint32 difftime) } if (difftime >= m_timer) + { m_timer = 0; + } else + { m_timer -= difftime; + } } if (m_timer == 0) @@ -3940,11 +4464,15 @@ void Spell::update(uint32 difftime) { TargetInfo const& target = *ihit; if (!target.targetGUID.IsCreatureOrVehicle()) + { continue; + } Unit* unit = m_caster->GetObjectGuid() == target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID); if (unit == NULL) + { continue; + } p->RewardPlayerAndGroupAtCast(unit, m_spellInfo->Id); } @@ -3955,7 +4483,9 @@ void Spell::update(uint32 difftime) GameObject* go = m_caster->GetMap()->GetGameObject(target.targetGUID); if (!go) + { continue; + } p->RewardPlayerAndGroupAtCast(go, m_spellInfo->Id); } @@ -3996,7 +4526,9 @@ void Spell::finish(bool ok) for (Unit::AuraList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i) { if (!(*i)->isAffectedOnSpell(m_spellInfo)) + { continue; + } for (TargetList::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition == SPELL_MISS_NONE) @@ -4012,7 +4544,9 @@ void Spell::finish(bool ok) int32 chance = m_caster->CalculateSpellDamage(unit, auraSpellInfo, auraSpellIdx, &auraBasePoints); if(roll_chance_i(chance)) if(SpellEffectEntry const* spellEffect = auraSpellInfo->GetSpellEffect(auraSpellIdx)) + { m_caster->CastSpell(unit, spellEffect->EffectTriggerSpell, true, NULL, (*i)); + } } } } @@ -4030,7 +4564,9 @@ void Spell::finish(bool ok) { m_caster->resetAttackTimer(BASE_ATTACK); if (m_caster->haveOffhandWeapon()) + { m_caster->resetAttackTimer(OFF_ATTACK); + } } /*if (IsRangedAttackResetSpell()) @@ -4053,25 +4589,35 @@ void Spell::finish(bool ok) } } if (needDrop) + { ((Player*)m_caster)->ClearComboPoints(); + } } // potions disabled by client, send event "not in combat" if need if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->UpdatePotionCooldown(this); + } // call triggered spell only at successful cast (after clear combo points -> for add some if need) if (!m_TriggerSpells.empty()) + { CastTriggerSpells(); + } // Stop Attack for some spells if (m_spellInfo->HasAttribute(SPELL_ATTR_STOP_ATTACK_TARGET)) + { m_caster->AttackStop(); + } // update encounter state if needed Map* map = m_caster->GetMap(); if (map->IsDungeon()) + { ((DungeonMap*)map)->GetPersistanceState()->UpdateEncounterState(ENCOUNTER_CREDIT_CAST_SPELL, m_spellInfo->Id); + } } void Spell::SendCastResult(SpellCastResult result) @@ -4138,7 +4684,9 @@ void Spell::SendCastResult(Player* caster, SpellEntry const* spellInfo, uint8 ca SpellTotemsEntry const* totems = spellInfo->GetSpellTotems(); for(int i = 0; i < MAX_SPELL_TOTEMS; ++i) if(totems && totems->Totem[i]) + { data << uint32(totems->Totem[i]); + } } break; case SPELL_FAILED_TOTEM_CATEGORY: @@ -4146,7 +4694,9 @@ void Spell::SendCastResult(Player* caster, SpellEntry const* spellInfo, uint8 ca SpellTotemsEntry const* totems = spellInfo->GetSpellTotems(); for(int i = 0; i < MAX_SPELL_TOTEM_CATEGORIES; ++i) if(totems && totems->TotemCategory[i]) + { data << uint32(totems->TotemCategory[i]); + } } break; case SPELL_FAILED_EQUIPPED_ITEM_CLASS: @@ -4211,7 +4761,9 @@ void Spell::SendSpellStart() uint32 castFlags = CAST_FLAG_HAS_TRAJECTORY; if (m_spellInfo->runeCostID) + { castFlags |= CAST_FLAG_UNKNOWN19; + } if ((m_caster->GetTypeId() == TYPEID_PLAYER || m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->IsPet()) && @@ -4226,9 +4778,13 @@ void Spell::SendSpellStart() WorldPacket data(SMSG_SPELL_START, (8 + 8 + 4 + 4 + 2)); if (m_CastItem) + { data << m_CastItem->GetPackGUID(); + } else + { data << m_caster->GetPackGUID(); + } data << m_caster->GetPackGUID(); data << uint8(m_cast_count); // pending spell cast @@ -4240,7 +4796,9 @@ void Spell::SendSpellStart() data << m_targets; if (castFlags & CAST_FLAG_PREDICTED_POWER) // predicted power + { data << uint32(m_caster->GetPower(Powers(m_spellInfo->GetPowerType()))); + } if (castFlags & CAST_FLAG_PREDICTED_RUNES) // predicted runes { @@ -4267,7 +4825,9 @@ void Spell::SendSpellStart() } if (castFlags & CAST_FLAG_AMMO) // projectile info + { WriteAmmoToPacket(&data); + } if (castFlags & CAST_FLAG_IMMUNITY) // cast immunity { @@ -4294,7 +4854,9 @@ void Spell::SendSpellStart() data << uint32(amt); data << uint8(type); if (type == DOT) + { data << m_caster->GetPackGUID(); + } } m_caster->SendMessageToSet(&data, true); @@ -4326,9 +4888,13 @@ void Spell::SendSpellGo() WorldPacket data(SMSG_SPELL_GO, 50); // guess size if (m_CastItem) + { data << m_CastItem->GetPackGUID(); + } else + { data << m_caster->GetPackGUID(); + } data << m_caster->GetPackGUID(); data << uint8(m_cast_count); // pending spell cast? @@ -4342,7 +4908,9 @@ void Spell::SendSpellGo() data << m_targets; if (castFlags & CAST_FLAG_PREDICTED_POWER) // predicted power + { data << uint32(m_caster->GetPower(Powers(m_spellInfo->GetPowerType()))); + } if (castFlags & CAST_FLAG_PREDICTED_RUNES) // predicted runes { @@ -4375,7 +4943,9 @@ void Spell::SendSpellGo() } if (castFlags & CAST_FLAG_AMMO) // projectile info + { WriteAmmoToPacket(&data); + } if (castFlags & CAST_FLAG_VISUAL_CHAIN) // spell visual chain effect { @@ -4414,7 +4984,9 @@ void Spell::WriteAmmoToPacket(WorldPacket* data) { ammoInventoryType = pItem->GetProto()->InventoryType; if (ammoInventoryType == INVTYPE_THROWN) + { ammoDisplayID = pItem->GetProto()->DisplayInfoID; + } else { if(m_caster->GetDummyAura(46699)) // Requires No Ammo @@ -4454,7 +5026,9 @@ void Spell::WriteAmmoToPacket(WorldPacket* data) } if (ammoDisplayID) + { break; + } } } } @@ -4490,11 +5064,15 @@ void Spell::WriteSpellGoTargets(WorldPacket* data) m_needAliveTargetMask |= ihit->effectMask; } else + { ++miss; + } } for (GOTargetList::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) + { *data << ighit->targetGUID; // Always hits + } data->put(count_pos, hit); @@ -4506,12 +5084,16 @@ void Spell::WriteSpellGoTargets(WorldPacket* data) *data << ihit->targetGUID; *data << uint8(ihit->missCondition); if (ihit->missCondition == SPELL_MISS_REFLECT) + { *data << uint8(ihit->reflectResult); + } } } // Reset m_needAliveTargetMask for non channeled spell if (!IsChanneledSpell(m_spellInfo)) + { m_needAliveTargetMask = 0; + } } void Spell::SendLogExecute() @@ -4521,9 +5103,13 @@ void Spell::SendLogExecute() WorldPacket data(SMSG_SPELLLOGEXECUTE, (8 + 4 + 4 + 4 + 4 + 8)); if (m_caster->GetTypeId() == TYPEID_PLAYER) + { data << m_caster->GetPackGUID(); + } else + { data << target->GetPackGUID(); + } data << uint32(m_spellInfo->Id); uint32 count1 = 1; @@ -4537,47 +5123,69 @@ void Spell::SendLogExecute() for (uint32 j = 0; j < count2; ++j) { if(!spellEffect) + { continue; + } switch(spellEffect->Effect) { case SPELL_EFFECT_POWER_DRAIN: case SPELL_EFFECT_POWER_BURN: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else + { data << uint8(0); + } data << uint32(0); data << uint32(0); data << float(0); break; case SPELL_EFFECT_ADD_EXTRA_ATTACKS: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else + { data << uint8(0); + } data << uint32(0); // count? break; case SPELL_EFFECT_INTERRUPT_CAST: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else + { data << uint8(0); + } data << uint32(0); // spellid break; case SPELL_EFFECT_DURABILITY_DAMAGE: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else + { data << uint8(0); + } data << uint32(0); data << uint32(0); break; case SPELL_EFFECT_OPEN_LOCK: if (Item* item = m_targets.getItemTarget()) + { data << item->GetPackGUID(); + } else + { data << uint8(0); + } break; case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_RANDOM_ITEM: @@ -4593,30 +5201,46 @@ void Spell::SendLogExecute() case SPELL_EFFECT_SUMMON_OBJECT_SLOT: case SPELL_EFFECT_171: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else if (m_targets.getItemTargetGuid()) + { data << m_targets.getItemTargetGuid().WriteAsPacked(); + } else if (GameObject* go = m_targets.getGOTarget()) + { data << go->GetPackGUID(); + } else + { data << uint8(0); // guid + } break; case SPELL_EFFECT_FEED_PET: data << uint32(m_targets.getItemTargetEntry()); break; case SPELL_EFFECT_DISMISS_PET: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else + { data << uint8(0); + } break; case SPELL_EFFECT_RESURRECT: case SPELL_EFFECT_RESURRECT_NEW: case SPELL_EFFECT_MASS_RESSURECTION: if (Unit* unit = m_targets.getUnitTarget()) + { data << unit->GetPackGUID(); + } else + { data << uint8(0); + } break; default: return; @@ -4658,7 +5282,9 @@ void Spell::SendChannelUpdate(uint32 time) player->SetCharm(NULL); if (possessed) + { player->SetClientControl(possessed, 0); + } player->SetMover(NULL); player->GetCamera().ResetView(); player->RemovePetActionBar(); @@ -4672,7 +5298,9 @@ void Spell::SendChannelUpdate(uint32 time) // Some possessed might want to despawn? if (possessed->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id && possessed->GetTypeId() == TYPEID_UNIT) + { ((Creature*)possessed)->ForcedDespawn(); + } } } @@ -4681,7 +5309,9 @@ void Spell::SendChannelUpdate(uint32 time) ObjectGuid target_guid = m_caster->GetChannelObjectGuid(); if (target_guid != m_caster->GetObjectGuid() && target_guid.IsUnit()) if (Unit* target = ObjectAccessor::GetUnit(*m_caster, target_guid)) + { target->RemoveAurasByCasterSpell(m_spellInfo->Id, m_caster->GetObjectGuid()); + } // Only finish channeling when latest channeled spell finishes if (m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != m_spellInfo->Id) @@ -4705,7 +5335,9 @@ void Spell::SendChannelStart(uint32 duration) // select dynobject created by first effect if any if (m_spellInfo->GetSpellEffectIdByIndex(EFFECT_INDEX_0) == SPELL_EFFECT_PERSISTENT_AREA_AURA) + { target = m_caster->GetDynObject(m_spellInfo->Id, EFFECT_INDEX_0); + } // select first not resisted target from target list for _0_ effect else if (!m_UniqueTargetInfo.empty()) { @@ -4756,7 +5388,9 @@ void Spell::SendChannelStart(uint32 duration) m_timer = duration; if (target) + { m_caster->SetChannelObjectGuid(target->GetObjectGuid()); + } m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id); } @@ -4828,7 +5462,9 @@ void Spell::TakeCastItem() if (proto->Spells[i].SpellCharges) { if (proto->Spells[i].SpellCharges < 0 && !(proto->ExtraFlags & ITEM_EXTRA_NON_CONSUMABLE)) + { expendable = true; + } int32 charges = m_CastItem->GetSpellCharges(i); @@ -4837,7 +5473,9 @@ void Spell::TakeCastItem() { (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use if (proto->Stackable == 1) + { m_CastItem->SetSpellCharges(i, charges); + } m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster); } @@ -4876,12 +5514,16 @@ void Spell::TakePower() if (ihit->targetGUID == targetGuid) { if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS) + { hit = false; + } if (ihit->missCondition != SPELL_MISS_NONE) { // lower spell cost on fail (by talent aura) if (Player* modOwner = ((Player*)m_caster)->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost); + } } break; } @@ -4917,7 +5559,9 @@ void Spell::TakePower() return; } else + { m_usedHolyPower = m_caster->GetPower(POWER_HOLY_POWER); + } } // Zealotry - does not take power @@ -4971,7 +5615,9 @@ SpellCastResult Spell::CheckRunePower() { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i]); + } } runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later @@ -4980,15 +5626,21 @@ SpellCastResult Spell::CheckRunePower() { RuneType rune = plr->GetCurrentRune(i); if (!plr->GetRuneCooldown(i) && runeCost[rune] > 0) + { --runeCost[rune]; + } } for (uint32 i = 0; i < RUNE_DEATH; ++i) if (runeCost[i] > 0) + { runeCost[RUNE_DEATH] += runeCost[i]; + } if (runeCost[RUNE_DEATH] > MAX_RUNES) + { return SPELL_FAILED_NO_POWER; // not sure if result code is correct + } return SPELL_CAST_OK; } @@ -5027,7 +5679,9 @@ void Spell::TakeRunePower(bool hit) { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i]); + } } runeCost[RUNE_DEATH] = 0; // calculated later @@ -5064,10 +5718,14 @@ void Spell::TakeRunePower(bool hit) // keep Death Rune type if missed if (hit) + { plr->RestoreBaseRune(i); + } if (runeCost[RUNE_DEATH] == 0) + { break; + } } } } @@ -5079,12 +5737,16 @@ void Spell::TakeRunePower(bool hit) if (rp) { if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, rp); + } rp = int32(sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_INCOME) * rp); rp += m_caster->GetTotalAuraModifier(SPELL_AURA_MOD_RUNIC_POWER_REGEN) * rp / 100; if (rp > 0) + { plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp); + } } } } @@ -5112,9 +5774,13 @@ void Spell::TakeReagents() for(uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x) { if(!spellReagents) + { continue; + } if(spellReagents->Reagent[x] <= 0) + { continue; + } uint32 itemid = spellReagents->Reagent[x]; uint32 itemcount = spellReagents->ReagentCount[x]; @@ -5142,7 +5808,9 @@ void Spell::TakeReagents() // if getItemTarget is also spell reagent if (m_targets.getItemTargetEntry() == itemid) + { m_targets.setItemTarget(NULL); + } p_caster->DestroyItemCount(itemid, itemcount, true); } @@ -5164,14 +5832,18 @@ void Spell::HandleThreatSpells() float threat = threatEntry->threat; if (threatEntry->ap_bonus != 0.0f) + { threat += threatEntry->ap_bonus * m_caster->GetTotalAttackPowerValue(GetWeaponAttackType(m_spellInfo)); + } bool positive = true; uint8 effectMask = 0; for (int i = 0; i < MAX_EFFECT_INDEX; ++i) if (SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i))) if (spellEffect->Effect) + { effectMask |= (1<missCondition != SPELL_MISS_NONE) + { continue; + } Unit* target = m_caster->GetObjectGuid() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (!target) + { continue; + } // positive spells distribute threat among all units that are in combat with target, like healing if (positive) @@ -5206,7 +5882,9 @@ void Spell::HandleThreatSpells() else { if (!target->CanHaveThreatList()) + { continue; + } target->AddThreat(m_caster, threat, false, GetSpellSchoolMask(m_spellInfo), m_spellInfo); } @@ -5572,7 +6250,9 @@ SpellCastResult Spell::CheckCast(bool strict) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if(spellEffect->EffectImplicitTargetA == TARGET_PET) { @@ -5622,7 +6302,9 @@ SpellCastResult Spell::CheckCast(bool strict) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(k)); if(!spellEffect) + { continue; + } if (IsExplicitPositiveTarget(spellEffect->EffectImplicitTargetA)) { if (!target_hostile_checked) @@ -5780,7 +6462,9 @@ SpellCastResult Spell::CheckCast(bool strict) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if (spellEffect->EffectImplicitTargetA == TARGET_SCRIPT || spellEffect->EffectImplicitTargetB == TARGET_SCRIPT || @@ -5794,13 +6478,19 @@ SpellCastResult Spell::CheckCast(bool strict) if (bounds.first == bounds.second) { if (spellEffect->EffectImplicitTargetA == TARGET_SCRIPT || spellEffect->EffectImplicitTargetB == TARGET_SCRIPT) + { sLog.outErrorDb("Spell entry %u, effect %i has EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT, but creature are not defined in `spell_script_target`", m_spellInfo->Id, j); + } if (spellEffect->EffectImplicitTargetA == TARGET_SCRIPT_COORDINATES || spellEffect->EffectImplicitTargetB == TARGET_SCRIPT_COORDINATES) + { sLog.outErrorDb("Spell entry %u, effect %i has EffectImplicitTargetA/EffectImplicitTargetB = TARGET_SCRIPT_COORDINATES, but gameobject or creature are not defined in `spell_script_target`", m_spellInfo->Id, j); + } if (spellEffect->EffectImplicitTargetA == TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT || spellEffect->EffectImplicitTargetB == TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT) + { sLog.outErrorDb("Spell entry %u, effect %i has EffectImplicitTargetA/EffectImplicitTargetB = TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT, but gameobject are not defined in `spell_script_target`", m_spellInfo->Id, j); + } } SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->GetRangeIndex()); @@ -5808,7 +6498,9 @@ SpellCastResult Spell::CheckCast(bool strict) // override range with default when it's not provided if (!range) + { range = m_caster->GetMap()->IsDungeon() ? DEFAULT_VISIBILITY_INSTANCE : DEFAULT_VISIBILITY_DISTANCE; + } Creature* targetExplicit = NULL; // used for cases where a target is provided (by script for example) Creature* creatureScriptTarget = NULL; @@ -5817,7 +6509,9 @@ SpellCastResult Spell::CheckCast(bool strict) for (SQLMultiStorage::SQLMultiSIterator i_spellST = bounds.first; i_spellST != bounds.second; ++i_spellST) { if (i_spellST->CanNotHitWithSpellEffect(SpellEffectIndex(j))) + { continue; + } switch (i_spellST->type) { @@ -5866,13 +6560,17 @@ SpellCastResult Spell::CheckCast(bool strict) { // always use spellMaxRange, in case GetLastRange returned different in a previous pass if (pTarget->IsWithinDistInMap(m_caster, GetSpellMaxRange(srange))) + { targetExplicit = (Creature*)pTarget; + } } else if (i_spellST->type == SPELL_TARGET_TYPE_CREATURE && pTarget->IsAlive()) { // always use spellMaxRange, in case GetLastRange returned different in a previous pass if (pTarget->IsWithinDistInMap(m_caster, GetSpellMaxRange(srange))) + { targetExplicit = (Creature*)pTarget; + } } } } @@ -5891,12 +6589,18 @@ SpellCastResult Spell::CheckCast(bool strict) // always prefer provided target if it's valid if (targetExplicit) + { creatureScriptTarget = targetExplicit; + } else if (p_Creature) + { creatureScriptTarget = p_Creature; + } if (creatureScriptTarget) + { goScriptTarget = NULL; + } break; } @@ -5912,7 +6616,9 @@ SpellCastResult Spell::CheckCast(bool strict) m_targets.setDestination(creatureScriptTarget->GetPositionX(), creatureScriptTarget->GetPositionY(), creatureScriptTarget->GetPositionZ()); if (spellEffect->EffectImplicitTargetA == TARGET_SCRIPT_COORDINATES && spellEffect->Effect != SPELL_EFFECT_PERSISTENT_AREA_AURA) + { AddUnitTarget(creatureScriptTarget, SpellEffectIndex(j)); + } } // store explicit target for TARGET_SCRIPT else @@ -5931,7 +6637,9 @@ SpellCastResult Spell::CheckCast(bool strict) m_targets.setDestination(goScriptTarget->GetPositionX(), goScriptTarget->GetPositionY(), goScriptTarget->GetPositionZ()); if (spellEffect->EffectImplicitTargetA == TARGET_SCRIPT_COORDINATES && spellEffect->Effect != SPELL_EFFECT_PERSISTENT_AREA_AURA) + { AddGOTarget(goScriptTarget, SpellEffectIndex(j)); + } } // store explicit target for TARGET_FOCUS_OR_SCRIPTED_GAMEOBJECT else @@ -5994,7 +6702,9 @@ SpellCastResult Spell::CheckCast(bool strict) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // for effects of spells that have only one target switch(spellEffect->Effect) { @@ -6099,7 +6809,9 @@ SpellCastResult Spell::CheckCast(bool strict) FillAreaTargets(targetsCombat, radius, PUSH_DEST_CENTER, SPELL_TARGETS_AOE_DAMAGE); if (targetsCombat.empty()) + { break; + } for (UnitList::iterator itr = targetsCombat.begin(); itr != targetsCombat.end(); ++itr) if ((*itr)->IsInCombat()) @@ -6188,7 +6900,9 @@ SpellCastResult Spell::CheckCast(bool strict) case SPELL_EFFECT_LEARN_SPELL: { if(spellEffect->EffectImplicitTargetA != TARGET_PET) + { break; + } Pet* pet = m_caster->GetPet(); @@ -6470,7 +7184,9 @@ SpellCastResult Spell::CheckCast(bool strict) { Pet* dbPet = new Pet; if (dbPet->LoadPetFromDB((Player*)m_caster, 0)) + { return SPELL_CAST_OK; // still returns an error to the player, so this error must come from somewhere else... + } else { delete dbPet; @@ -6484,7 +7200,9 @@ SpellCastResult Spell::CheckCast(bool strict) { if (strict) // Summoning Disorientation, trigger pet stun (cast by pet so it doesn't attack player) if (Pet* pet = ((Player*)m_caster)->GetPet()) + { pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetObjectGuid()); + } } else { @@ -6590,7 +7308,9 @@ SpellCastResult Spell::CheckCast(bool strict) // need further research with this SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if (!spellEffect) + { break; + } if (spellEffect->Effect != SPELL_EFFECT_LEAP) { @@ -6628,11 +7348,15 @@ SpellCastResult Spell::CheckCast(bool strict) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // Do not check in case of junk in DBC if (!IsAuraApplyEffect(m_spellInfo, SpellEffectIndex(i))) + { continue; + } // Possible Unit-target for the spell Unit* expectedTarget = GetPrefilledUnitTargetOrUnitTarget(SpellEffectIndex(i)); @@ -6837,7 +7561,9 @@ SpellCastResult Spell::CheckCast(bool strict) } if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem) + { break; + } if (expectedTarget->GetPowerType() != POWER_MANA) { @@ -6865,7 +7591,9 @@ SpellCastResult Spell::CheckCast(bool strict) bool boardedOnEachOther = m_caster->GetTransportInfo()->HasOnBoard(expectedTarget); // Check if trying to board a vehicle that has the current transport on board if (!boardedOnEachOther) + { boardedOnEachOther = expectedTarget->GetVehicleInfo()->HasOnBoard(m_caster); + } if (!boardedOnEachOther) { @@ -6984,7 +7712,9 @@ SpellCastResult Spell::CheckPetCast(Unit* target) } if (!target && m_targets.getUnitTarget()) + { target = m_targets.getUnitTarget(); + } bool need = false; bool script = false; @@ -6992,7 +7722,9 @@ SpellCastResult Spell::CheckPetCast(Unit* target) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (spellEffect->EffectImplicitTargetA == TARGET_CHAIN_DAMAGE || spellEffect->EffectImplicitTargetA == TARGET_SINGLE_FRIEND || @@ -7015,7 +7747,9 @@ SpellCastResult Spell::CheckPetCast(Unit* target) } } if (need) + { m_targets.setUnitTarget(target); + } else if (script == true) { return CheckCast(true); @@ -7027,7 +7761,9 @@ SpellCastResult Spell::CheckPetCast(Unit* target) if (_target && m_targets.m_targetMask & TARGET_FLAG_UNIT) { if (!_target->IsTargetableForAttack()) + { return SPELL_FAILED_BAD_TARGETS; // guessed error + } if (IsPositiveSpell(m_spellInfo->Id)) { @@ -7082,20 +7818,32 @@ SpellCastResult Spell::CheckCasterAuras() const { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (spellEffect->EffectApplyAuraName == SPELL_AURA_SCHOOL_IMMUNITY) + { school_immune |= uint32(spellEffect->EffectMiscValue); + } else if (spellEffect->EffectApplyAuraName == SPELL_AURA_MECHANIC_IMMUNITY) + { mechanic_immune |= 1 << uint32(spellEffect->EffectMiscValue-1); + } else if (spellEffect->EffectApplyAuraName == SPELL_AURA_MECHANIC_IMMUNITY_MASK) + { mechanic_immune |= uint32(spellEffect->EffectMiscValue); + } else if (spellEffect->EffectApplyAuraName == SPELL_AURA_DISPEL_IMMUNITY) + { dispel_immune |= GetDispellMask(DispelType(spellEffect->EffectMiscValue)); + } } // immune movement impairment and loss of control (spell data have special structure for mark this case) if (IsSpellRemoveAllMovementAndControlLossEffects(m_spellInfo)) + { mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK; + } } // Check whether the cast should be prevented by any state you might have. @@ -7110,7 +7858,9 @@ SpellCastResult Spell::CheckCasterAuras() const if (m_spellInfo->GetSpellFamilyName() == SPELLFAMILY_PRIEST && m_spellInfo->GetSpellIconID() == 2178) { if (!m_caster->HasAura(63248)) // Glyph of Pain Suppression + { spellUsableWhileStunned = false; + } } // spell is usable while stunned, check if caster has only mechanic stun auras, another stun types must prevent cast spell @@ -7125,19 +7875,31 @@ SpellCastResult Spell::CheckCasterAuras() const break; } if (!is_stun_mechanic) + { prevented_reason = SPELL_FAILED_STUNNED; + } } else + { prevented_reason = SPELL_FAILED_STUNNED; + } } else if (unitflag & UNIT_FLAG_CONFUSED && !m_spellInfo->HasAttribute(SPELL_ATTR_EX5_USABLE_WHILE_CONFUSED)) + { prevented_reason = SPELL_FAILED_CONFUSED; + } else if (unitflag & UNIT_FLAG_FLEEING && !m_spellInfo->HasAttribute(SPELL_ATTR_EX5_USABLE_WHILE_FEARED)) + { prevented_reason = SPELL_FAILED_FLEEING; + } else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->GetPreventionType() == SPELL_PREVENTION_TYPE_SILENCE) + { prevented_reason = SPELL_FAILED_SILENCED; + } else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->GetPreventionType() == SPELL_PREVENTION_TYPE_PACIFY) + { prevented_reason = SPELL_FAILED_PACIFIED; + } else if (m_caster->HasAuraType(SPELL_AURA_ALLOW_ONLY_ABILITY)) { Unit::AuraList const& casingLimit = m_caster->GetAurasByType(SPELL_AURA_ALLOW_ONLY_ABILITY); @@ -7164,18 +7926,26 @@ SpellCastResult Spell::CheckCasterAuras() const SpellEntry const* pEntry = holder->GetSpellProto(); if ((GetSpellSchoolMask(pEntry) & school_immune) && !pEntry->HasAttribute(SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE)) + { continue; + } if ((1<<(pEntry->GetDispel())) & dispel_immune) + { continue; + } for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) { Aura* aura = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); if (!aura) + { continue; + } if (GetSpellMechanicMask(pEntry, 1 << i) & mechanic_immune) + { continue; + } // Make a second check for spell failed so the right SPELL_FAILED message is returned. // That is needed when your casting is prevented by multiple states and you are only immune to some of them. switch (aura->GetModifier()->m_auraname) @@ -7232,7 +8002,9 @@ bool Spell::CanAutoCast(Unit* target) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } if(spellEffect->Effect == SPELL_EFFECT_APPLY_AURA) { if( m_spellInfo->GetStackAmount() <= 1) @@ -7321,7 +8093,9 @@ SpellCastResult Spell::CheckRange(bool strict) float min_range = GetSpellMinRange(srange, friendly); if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range); + } if (target && target != m_caster) { @@ -7424,15 +8198,21 @@ uint32 Spell::CalculatePowerCost(SpellEntry const* spellInfo, Unit* caster, Spel // Shiv - costs 20 + weaponSpeed*10 energy (apply only to non-triggered spell with energy cost) if (spellInfo->HasAttribute(SPELL_ATTR_EX4_SPELL_VS_EXTEND_COST)) + { powerCost += caster->GetAttackTime(OFF_ATTACK) / 100; + } // Apply cost mod by spell if (spell) if (Player* modOwner = caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COST, powerCost, spell); + } if (spellInfo->HasAttribute(SPELL_ATTR_LEVEL_DAMAGE_CALCULATION)) + { powerCost = int32(powerCost / (1.117f * spellInfo->GetSpellLevel() / caster->getLevel() - 0.1327f)); + } // PCT mod from user auras by school float pctCostMultiplier = 1.0f; @@ -7447,7 +8227,9 @@ uint32 Spell::CalculatePowerCost(SpellEntry const* spellInfo, Unit* caster, Spel // PCT mod from user auras by school powerCost = int32(powerCost * pctCostMultiplier); if (powerCost < 0) + { powerCost = 0; + } return powerCost; } @@ -7466,7 +8248,9 @@ SpellCastResult Spell::CheckPower() Player* playerCaster = (Player*)m_caster; uint32 diff = REGEN_TIME_FULL - m_caster->GetRegenTimer(); if (diff >= REGEN_TIME_PRECISE) + { playerCaster->RegenerateAll(diff); + } } // health as power used - need check health amount @@ -7571,7 +8355,9 @@ SpellCastResult Spell::CheckItems() } if (proto->Flags & ITEM_FLAG_ENCHANT_SCROLL) + { isScrollItem = true; + } for (int i = 0; i < 5; ++i) if (proto->Spells[i].SpellCharges) @@ -7589,10 +8375,14 @@ SpellCastResult Spell::CheckItems() { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } // skip check, pet not required like checks, and for TARGET_PET m_targets.getUnitTarget() is not the real target but the caster if (spellEffect->EffectImplicitTargetA == TARGET_PET) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_HEAL) { @@ -7678,7 +8468,9 @@ SpellCastResult Spell::CheckItems() for(uint32 i = 0; i < MAX_SPELL_REAGENTS; ++i) { if(spellReagents->Reagent[i] <= 0) + { continue; + } uint32 itemid = spellReagents->Reagent[i]; uint32 itemcount = spellReagents->ReagentCount[i]; @@ -7727,7 +8519,9 @@ SpellCastResult Spell::CheckItems() } } else + { totems -= 1; + } } if (totems != 0) @@ -7742,7 +8536,9 @@ SpellCastResult Spell::CheckItems() { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } switch (spellEffect->Effect) { case SPELL_EFFECT_CREATE_ITEM: @@ -7969,7 +8765,9 @@ SpellCastResult Spell::CheckItems() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER; if (m_attackType != RANGED_ATTACK) + { break; + } Item* pItem = ((Player*)m_caster)->GetWeaponForAttack(m_attackType, true, false); if (!pItem) { @@ -8008,7 +8806,9 @@ void Spell::Delayed() } if (m_spellState == SPELL_STATE_DELAYED) + { return; // spell is active and can't be time-backed + } if (isDelayableNoMore()) // Spells may only be delayed twice { @@ -8039,7 +8839,9 @@ void Spell::Delayed() m_timer = m_casttime; } else + { m_timer += delaytime; + } DETAIL_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime); @@ -8080,7 +8882,9 @@ void Spell::DelayedChannel() m_timer = 0; } else + { m_timer -= delaytime; + } DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer); @@ -8089,7 +8893,9 @@ void Spell::DelayedChannel() if ((*ihit).missCondition == SPELL_MISS_NONE) { if (Unit* unit = m_caster->GetObjectGuid() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) + { unit->DelaySpellAuraHolder(m_spellInfo->Id, delaytime, unit->GetObjectGuid()); + } } } @@ -8097,7 +8903,9 @@ void Spell::DelayedChannel() { // partially interrupt persistent area auras if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id, SpellEffectIndex(j))) + { dynObj->Delay(delaytime); + } } SendChannelUpdate(m_timer); @@ -8106,7 +8914,9 @@ void Spell::DelayedChannel() void Spell::UpdateOriginalCasterPointer() { if (m_originalCasterGUID == m_caster->GetObjectGuid()) + { m_originalCaster = m_caster; + } else if (m_originalCasterGUID.IsGameObject()) { GameObject* go = m_caster->IsInWorld() ? m_caster->GetMap()->GetGameObject(m_originalCasterGUID) : NULL; @@ -8126,9 +8936,13 @@ void Spell::UpdatePointers() m_targets.Update(m_caster); if (m_caster->GetTypeId() == TYPEID_PLAYER) + { m_CastItem = ((Player *)m_caster)->GetItemByGuid(m_CastItemGuid); + } else + { m_CastItem = NULL; + } } bool Spell::CheckTargetCreatureType(Unit* target) const @@ -8149,7 +8963,9 @@ bool Spell::CheckTargetCreatureType(Unit* target) const // Dismiss Pet, Taming Lesson and Control Robot skipped if (m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356 || m_spellInfo->Id == 30009) + { spellCreatureTargetMask = 0; + } if (spellCreatureTargetMask) { @@ -8263,7 +9079,9 @@ bool Spell::CheckTarget(Unit* target, SpellEffectIndex eff) break; case SPELL_EFFECT_DUMMY: if (m_spellInfo->Id != 20577) // Cannibalize + { break; + } // fall through case SPELL_EFFECT_RESURRECT_NEW: // player far away, maybe his corpse near? @@ -8373,7 +9191,9 @@ SpellEvent::SpellEvent(Spell* spell) : BasicEvent() SpellEvent::~SpellEvent() { if (m_Spell->getState() != SPELL_STATE_FINISHED) + { m_Spell->cancel(); + } if (m_Spell->IsDeletable()) { @@ -8390,7 +9210,9 @@ bool SpellEvent::Execute(uint64 e_time, uint32 p_time) { // update spell if it is not finished if (m_Spell->getState() != SPELL_STATE_FINISHED) + { m_Spell->update(p_time); + } // check spell state to process switch (m_Spell->getState()) @@ -8476,7 +9298,9 @@ void SpellEvent::Abort(uint64 /*e_time*/) { // oops, the spell we try to do is aborted if (m_Spell->getState() != SPELL_STATE_FINISHED) + { m_Spell->cancel(); + } } bool SpellEvent::IsDeletable() const @@ -8520,7 +9344,9 @@ SpellCastResult Spell::CanOpenLock(SpellEffectIndex effIndex, uint32 lockId, Ski // wrong locktype, skip if(uint32(m_spellInfo->GetEffectMiscValue(effIndex)) != lockInfo->Index[j]) + { continue; + } skillId = SkillByLockType(LockType(lockInfo->Index[j])); @@ -8534,9 +9360,13 @@ SpellCastResult Spell::CanOpenLock(SpellEffectIndex effIndex, uint32 lockId, Ski // castitem check: rogue using skeleton keys. the skill values should not be added in this case. // MAX_SKILL_TYPE - skill value Scales with caster level if (skillId == MAX_SKILL_TYPE) + { skillValue = m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER ? 0 : m_caster->getLevel() * 5; + } else + { skillValue = m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER ? 0 : ((Player*)m_caster)->GetSkillValue(skillId); + } skillValue += spellSkillBonus; @@ -8627,7 +9457,9 @@ void Spell::FillRaidOrPartyManaPriorityTargets(UnitList& targetUnitMap, Unit* me PrioritizeManaUnitQueue manaUsers; for (UnitList::const_iterator itr = targetUnitMap.begin(); itr != targetUnitMap.end(); ++itr) if ((*itr)->GetPowerType() == POWER_MANA && !(*itr)->IsDead()) + { manaUsers.push(PrioritizeManaUnitWraper(*itr)); + } targetUnitMap.clear(); while (!manaUsers.empty() && targetUnitMap.size() < count) @@ -8644,7 +9476,9 @@ void Spell::FillRaidOrPartyHealthPriorityTargets(UnitList& targetUnitMap, Unit* PrioritizeHealthUnitQueue healthQueue; for (UnitList::const_iterator itr = targetUnitMap.begin(); itr != targetUnitMap.end(); ++itr) if (!(*itr)->IsDead()) + { healthQueue.push(PrioritizeHealthUnitWraper(*itr)); + } targetUnitMap.clear(); while (!healthQueue.empty() && targetUnitMap.size() < count) @@ -8717,7 +9551,9 @@ void Spell::SelectMountByAreaAndSkill(Unit* target, SpellEntry const* parentSpel SpellCastResult locRes = sSpellMgr.GetSpellAllowedInLocationError(pSpell, target->GetMapId(), zone, area, target->GetCharmerOrOwnerPlayerOrPlayerItself()); if (locRes != SPELL_CAST_OK || !((Player*)target)->CanStartFlyInArea(target->GetMapId(), zone, area)) + { target->CastSpell(target, spellId150, true, NULL, NULL, ObjectGuid(), parentSpell); + } else if (spellIdSpecial > 0) { for (PlayerSpellMap::const_iterator iter = ((Player*)target)->GetSpellMap().begin(); iter != ((Player*)target)->GetSpellMap().end(); ++iter) @@ -8729,7 +9565,9 @@ void Spell::SelectMountByAreaAndSkill(Unit* target, SpellEntry const* parentSpel { SpellEffectEntry const* spellEffect = spellInfo->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if(spellEffect->EffectApplyAuraName == SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED) { @@ -8748,12 +9586,18 @@ void Spell::SelectMountByAreaAndSkill(Unit* target, SpellEntry const* parentSpel target->CastSpell(target, pSpell, true, NULL, NULL, ObjectGuid(), parentSpell); } else + { target->CastSpell(target, pSpell, true, NULL, NULL, ObjectGuid(), parentSpell); + } } else if (skillval >= 150 && spellId150 > 0) + { target->CastSpell(target, spellId150, true, NULL, NULL, ObjectGuid(), parentSpell); + } else if (spellId75 > 0) + { target->CastSpell(target, spellId75, true, NULL, NULL, ObjectGuid(), parentSpell); + } return; } @@ -8761,7 +9605,9 @@ void Spell::SelectMountByAreaAndSkill(Unit* target, SpellEntry const* parentSpel void Spell::ClearCastItem() { if (m_CastItem == m_targets.getItemTarget()) + { m_targets.setItemTarget(NULL); + } m_CastItem = NULL; m_CastItemGuid.Clear(); @@ -8799,22 +9645,32 @@ void Spell::TriggerGlobalCooldown() { // gcd modifier auras applied only to self spells and only player have mods for this if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this); + } // apply haste rating gcd = int32(float(gcd) * m_caster->GetFloatValue(UNIT_MOD_CAST_SPEED)); if (gcd < 1000) + { gcd = 1000; + } else if (gcd > 1500) + { gcd = 1500; + } } // global cooldown have only player or controlled units if (m_caster->GetCharmInfo()) + { m_caster->GetCharmInfo()->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd); + } else if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->GetGlobalCooldownMgr().AddGlobalCooldown(m_spellInfo, gcd); + } } void Spell::CancelGlobalCooldown() @@ -8832,17 +9688,25 @@ void Spell::CancelGlobalCooldown() // global cooldown have only player or controlled units if (m_caster->GetCharmInfo()) + { m_caster->GetCharmInfo()->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo); + } else if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->GetGlobalCooldownMgr().CancelGlobalCooldown(m_spellInfo); + } } void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& radius, uint32& EffectChainTarget, uint32& unMaxTargets) const { if (uint32 radiusIndex = spellEffect->GetRadiusIndex()) + { radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellEffect->GetRadiusIndex())); + } else + { radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellInfo->GetRangeIndex())); + } if (Unit* realCaster = GetAffectiveCaster()) { if (Player* modOwner = realCaster->GetSpellModOwner()) @@ -9076,7 +9940,9 @@ void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& r case SPELLFAMILY_MAGE: { if (m_spellInfo->Id == 38194) // Blink + { unMaxTargets = 1; + } break; } case SPELLFAMILY_WARRIOR: @@ -9084,20 +9950,26 @@ void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& r // Sunder Armor (main spell) if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000004000), 0x00000000) && m_spellInfo->GetSpellVisual() == 406) if (m_caster->HasAura(58387)) // Glyph of Sunder Armor + { EffectChainTarget = 2; + } break; } case SPELLFAMILY_DRUID: { // Starfall if (m_spellInfo->IsFitToFamilyMask(UI64LIT(0x0000000000000000), 0x00000100)) + { unMaxTargets = 2; + } break; } case SPELLFAMILY_DEATHKNIGHT: { if (m_spellInfo->GetSpellIconID() == 1737) // Corpse Explosion // TODO - spell 50445? + { unMaxTargets = 1; + } break; } case SPELLFAMILY_PALADIN: @@ -9109,9 +9981,13 @@ void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& r for(int i = 0; i < MAX_EFFECT_INDEX; ++i) if(SpellEffectEntry const* spellEffect = currSpell->m_spellInfo->GetSpellEffect(SpellEffectIndex(i))) if(spellEffect->EffectChainTarget > 0) + { EffectChainTarget = 0; // no chain targets + } if (currSpell->m_spellInfo->GetMaxAffectedTargets() > 0) + { EffectChainTarget = 0; // no chain targets + } } } break; @@ -9129,7 +10005,9 @@ void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& r case 24811: // Draw Spirit (Lethon) { if (spellEffect->EffectIndex == EFFECT_INDEX_0) // Copy range from EFF_1 to 0 + { radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellEffect->GetRadiusIndex())); + } break; } case 28241: // Poison (Naxxramas, Grobbulus Cloud) @@ -9137,7 +10015,9 @@ void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& r { uint32 auraId = (m_spellInfo->Id == 28241 ? 28158 : 54362); if (SpellAuraHolder* auraHolder = m_caster->GetSpellAuraHolder(auraId)) + { radius = 0.5f * (60000 - auraHolder->GetAuraDuration()) * 0.001f; + } break; } case 66881: // Slime Pool (ToCrusader, Acidmaw & DreadScale) @@ -9145,11 +10025,15 @@ void Spell::GetSpellRangeAndRadius(SpellEffectEntry const* spellEffect, float& r case 67639: // Slime Pool (ToCrusader, Acidmaw & DreadScale) (Mode 2) case 67640: // Slime Pool (ToCrusader, Acidmaw & DreadScale) (Mode 3) if (SpellAuraHolder* auraHolder = m_caster->GetSpellAuraHolder(66882)) + { radius = 0.5f * (60000 - auraHolder->GetAuraDuration()) * 0.001f; + } break; case 56438: // Arcane Overload if (Unit* realCaster = GetAffectiveCaster()) + { radius = radius * realCaster->GetObjectScale(); + } break; case 69057: // Bone Spike Graveyard (Icecrown Citadel, Lord Marrowgar encounter, 10N) case 70826: // Bone Spike Graveyard (Icecrown Citadel, Lord Marrowgar encounter, 25N) diff --git a/src/game/WorldHandlers/Spell.h b/src/game/WorldHandlers/Spell.h index c9111e83e..d296ac2ea 100644 --- a/src/game/WorldHandlers/Spell.h +++ b/src/game/WorldHandlers/Spell.h @@ -761,13 +761,19 @@ namespace MaNGOS { Player* pPlayer = itr->getSource(); if (!pPlayer->IsAlive() || pPlayer->IsTaxiFlying()) + { continue; + } if (i_originalCaster->IsFriendlyTo(pPlayer)) + { continue; + } if (pPlayer->IsWithinDist3d(i_spell.m_targets.m_destX, i_spell.m_targets.m_destY, i_spell.m_targets.m_destZ, i_radius)) + { i_data.push_back(pPlayer); + } } } template void Visit(GridRefManager&) {} @@ -796,7 +802,9 @@ namespace MaNGOS i_originalCaster(originalCaster), i_castingObject(i_spell.GetCastingObject()) { if (!i_originalCaster) + { i_originalCaster = i_spell.GetAffectiveCasterObject(); + } i_playerControlled = i_originalCaster ? i_originalCaster->IsControlledByPlayer() : false; switch (i_push_type) @@ -815,9 +823,13 @@ namespace MaNGOS break; case PUSH_DEST_CENTER: if (i_spell.m_targets.m_targetMask & TARGET_FLAG_SOURCE_LOCATION) + { i_spell.m_targets.getSource(i_centerX, i_centerY, i_centerZ); + } else + { i_spell.m_targets.getDestination(i_centerX, i_centerY, i_centerZ); + } break; case PUSH_TARGET_CENTER: if (Unit* target = i_spell.m_targets.getUnitTarget()) @@ -853,34 +865,48 @@ namespace MaNGOS { case SPELL_TARGETS_HOSTILE: if (!i_originalCaster->IsHostileTo(itr->getSource())) + { continue; + } break; case SPELL_TARGETS_NOT_FRIENDLY: if (i_originalCaster->IsFriendlyTo(itr->getSource())) + { continue; + } break; case SPELL_TARGETS_NOT_HOSTILE: if (i_originalCaster->IsHostileTo(itr->getSource())) + { continue; + } break; case SPELL_TARGETS_FRIENDLY: if (!i_originalCaster->IsFriendlyTo(itr->getSource())) + { continue; + } break; case SPELL_TARGETS_AOE_DAMAGE: { if (itr->getSource()->GetTypeId() == TYPEID_UNIT && ((Creature*)itr->getSource())->IsTotem()) + { continue; + } if (i_playerControlled) { if (i_originalCaster->IsFriendlyTo(itr->getSource())) + { continue; + } } else { if (!i_originalCaster->IsHostileTo(itr->getSource())) + { continue; + } } } break; @@ -894,35 +920,51 @@ namespace MaNGOS { case PUSH_IN_FRONT: if (i_castingObject->IsInFront((Unit*)(itr->getSource()), i_radius, 2 * M_PI_F / 3)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_IN_FRONT_90: if (i_castingObject->IsInFront((Unit*)(itr->getSource()), i_radius, M_PI_F / 2)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_IN_FRONT_30: if (i_castingObject->IsInFront((Unit*)(itr->getSource()), i_radius, M_PI_F / 6)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_IN_FRONT_15: if (i_castingObject->IsInFront((Unit*)(itr->getSource()), i_radius, M_PI_F / 12)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_IN_BACK: if (i_castingObject->IsInBack((Unit*)(itr->getSource()), i_radius, 2 * M_PI_F / 3)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_SELF_CENTER: if (i_castingObject->IsWithinDist((Unit*)(itr->getSource()), i_radius)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_DEST_CENTER: if (itr->getSource()->IsWithinDist3d(i_centerX, i_centerY, i_centerZ, i_radius)) + { i_data->push_back(itr->getSource()); + } break; case PUSH_TARGET_CENTER: if (i_spell.m_targets.getUnitTarget() && i_spell.m_targets.getUnitTarget()->IsWithinDist((Unit*)(itr->getSource()), i_radius)) + { i_data->push_back(itr->getSource()); + } break; } } diff --git a/src/game/WorldHandlers/SpellAuras.cpp b/src/game/WorldHandlers/SpellAuras.cpp index c7ad565b7..f82ef3d75 100644 --- a/src/game/WorldHandlers/SpellAuras.cpp +++ b/src/game/WorldHandlers/SpellAuras.cpp @@ -519,7 +519,9 @@ Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBas for (int t = 0; t < 3; ++t) { if (pEnchant->spellid[t] != spellproto->Id) + { continue; + } damage = uint32((item_rand_suffix->prefix[k] * castItem->GetItemSuffixFactor()) / 10000); break; @@ -527,7 +529,9 @@ Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBas } if (damage) + { break; + } } } } @@ -548,7 +552,9 @@ Aura::Aura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* currentBas // Start periodic on next tick or at aura apply if (!spellproto->HasAttribute(SPELL_ATTR_EX5_START_PERIODIC_AT_APPLY)) + { m_periodicTimer = m_modifier.periodictime; + } } Aura::~Aura() @@ -579,7 +585,9 @@ AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* cu m_areaAuraType = AREA_AURA_RAID; // Light's Beacon not applied to caster itself (TODO: more generic check for another similar spell if any?) if (target == caster_ptr && spellproto->Id == 53651) + { m_modifier.m_auraname = SPELL_AURA_NONE; + } break; case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: m_areaAuraType = AREA_AURA_FRIEND; @@ -587,7 +595,9 @@ AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* cu case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY: m_areaAuraType = AREA_AURA_ENEMY; if (target == caster_ptr) + { m_modifier.m_auraname = SPELL_AURA_NONE; // Do not do any effect on self + } break; case SPELL_EFFECT_APPLY_AREA_AURA_PET: m_areaAuraType = AREA_AURA_PET; @@ -595,7 +605,9 @@ AreaAura::AreaAura(SpellEntry const* spellproto, SpellEffectIndex eff, int32* cu case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: m_areaAuraType = AREA_AURA_OWNER; if (target == caster_ptr) + { m_modifier.m_auraname = SPELL_AURA_NONE; + } break; default: sLog.outError("Wrong spell effect in AreaAura constructor"); @@ -763,7 +775,9 @@ void AreaAura::Update(uint32 diff) Group* pGroup = NULL; if (owner->GetTypeId() == TYPEID_PLAYER) + { pGroup = ((Player*)owner)->GetGroup(); + } if (pGroup) { @@ -773,10 +787,14 @@ void AreaAura::Update(uint32 diff) if (Target && Target->IsAlive() && caster->IsFriendlyTo(Target)) { if (caster->IsWithinDistInMap(Target, m_radius)) + { targets.push_back(Target); + } Pet* pet = Target->GetPet(); if (pet && pet->IsAlive() && caster->IsWithinDistInMap(pet, m_radius)) + { targets.push_back(pet); + } } } } @@ -784,11 +802,15 @@ void AreaAura::Update(uint32 diff) { // add owner if (owner != caster && caster->IsWithinDistInMap(owner, m_radius)) + { targets.push_back(owner); + } // add caster's pet Unit* pet = caster->GetPet(); if (pet && caster->IsWithinDistInMap(pet, m_radius)) + { targets.push_back(pet); + } } break; } @@ -824,11 +846,17 @@ void AreaAura::Update(uint32 diff) SpellEntry const* actualSpellInfo; if (GetCasterGuid() == (*tIter)->GetObjectGuid()) // if caster is same as target then no need to change rank of the spell + { actualSpellInfo = GetSpellProto(); + } else + { actualSpellInfo = sSpellMgr.SelectAuraRankForLevel(GetSpellProto(), (*tIter)->getLevel()); // use spell id according level of the target + } if (!actualSpellInfo) + { continue; + } Unit::SpellAuraHolderBounds spair = (*tIter)->GetSpellAuraHolderBounds(actualSpellInfo->Id); // we need ignore present caster self applied are auras sometime @@ -836,24 +864,32 @@ void AreaAura::Update(uint32 diff) for (Unit::SpellAuraHolderMap::const_iterator i = spair.first; i != spair.second; ++i) { if (i->second->IsDeleted()) + { continue; + } Aura* aur = i->second->GetAuraByEffectIndex(m_effIndex); if (!aur) + { continue; + } switch (m_areaAuraType) { case AREA_AURA_ENEMY: // non caster self-casted auras (non stacked) if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE) + { apply = false; + } break; case AREA_AURA_RAID: // non caster self-casted auras (stacked from diff. casters) if (aur->GetModifier()->m_auraname != SPELL_AURA_NONE || i->second->GetCasterGuid() == GetCasterGuid()) + { apply = false; + } break; default: // in generic case not allow stacking area auras @@ -862,20 +898,28 @@ void AreaAura::Update(uint32 diff) } if (!apply) + { break; + } } if (!apply) + { continue; + } // Skip some targets (TODO: Might require better checks, also unclear how the actual caster must/can be handled) if (actualSpellInfo->HasAttribute(SPELL_ATTR_EX3_TARGET_ONLY_PLAYER) && (*tIter)->GetTypeId() != TYPEID_PLAYER) + { continue; + } int32 actualBasePoints = m_currentBasePoints; // recalculate basepoints for lower rank (all AreaAura spell not use custom basepoints?) if (actualSpellInfo != GetSpellProto()) + { actualBasePoints = actualSpellInfo->CalculateSimpleValue(m_effIndex); + } SpellAuraHolder* holder = (*tIter)->GetSpellAuraHolder(actualSpellInfo->Id, GetCasterGuid()); @@ -899,7 +943,9 @@ void AreaAura::Update(uint32 diff) holder->SetInUse(false); } else + { (*tIter)->AddSpellAuraHolder(holder); + } } } @@ -938,10 +984,14 @@ void AreaAura::Update(uint32 diff) { Player* checkTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself(); if (!checkTarget || !pGroup->SameSubGroup(check, checkTarget)) + { target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); + } } else + { target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); + } } } else if (m_areaAuraType == AREA_AURA_RAID) // Check if on same raid group @@ -956,16 +1006,22 @@ void AreaAura::Update(uint32 diff) { Player* checkTarget = target->GetCharmerOrOwnerPlayerOrPlayerItself(); if (!checkTarget || !checkTarget->GetGroup() || checkTarget->GetGroup()->GetId() != pGroup->GetId()) + { target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); + } } else + { target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); + } } } else if (m_areaAuraType == AREA_AURA_PET || m_areaAuraType == AREA_AURA_OWNER) { if (target->GetObjectGuid() != caster->GetCharmerOrOwnerGuid()) + { target->RemoveSingleAuraFromSpellAuraHolder(GetId(), GetEffIndex(), GetCasterGuid()); + } } } } @@ -1109,9 +1165,13 @@ void Aura::ReapplyAffectedPassiveAuras(Unit* target, bool owner_mode) { // only applied by self or aura caster if (itr->second->GetCasterGuid() == target->GetObjectGuid()) + { affectedSelf[itr->second->GetId()] = itr->second->GetCastItemGuid(); + } else if (itr->second->GetCasterGuid() == GetCasterGuid()) + { affectedAuraCaster.insert(itr->second->GetId()); + } } } @@ -1134,7 +1194,9 @@ void Aura::ReapplyAffectedPassiveAuras(Unit* target, bool owner_mode) { target->RemoveAurasDueToSpell(*set_itr); if (caster) + { caster->CastSpell(GetTarget(), *set_itr, true); + } } } } @@ -1179,7 +1241,9 @@ void Aura::ReapplyAffectedPassiveAuras() for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) if (Player* member = itr->getSource()) if (member != GetTarget() && member->IsInMap(GetTarget())) + { ReapplyAffectedPassiveAuras(member, false); + } } /*********************************************************/ @@ -1289,7 +1353,9 @@ void Aura::TriggerSpell() // case 6965: break; case 9712: // Thaumaturgy Channel if (Unit* caster = GetCaster()) + { caster->CastSpell(caster, 21029, true); + } return; // // Egan's Blaster // case 17368: break; @@ -1387,7 +1453,9 @@ void Aura::TriggerSpell() for (std::list::const_iterator itr = lList.begin(); itr != lList.end(); ++itr) if ((*itr)->IsAlive()) + { (*itr)->AddThreat(triggerTarget, float(5000)); + } return; } @@ -1410,11 +1478,15 @@ void Aura::TriggerSpell() Unit* pUnit = target->GetMap()->GetUnit((*itr)->getUnitGuid()); if (pUnit && target->GetThreatManager().getThreat(pUnit)) + { target->GetThreatManager().modifyThreatPercent(pUnit, -100); + } } if (Unit* pEnemy = target->SelectRandomUnfriendlyTarget(target->getVictim(), 100.0f)) + { ((Creature*)target)->AI()->AttackStart(pEnemy); + } return; } @@ -1428,9 +1500,13 @@ void Aura::TriggerSpell() // casted in left/right (but triggered spell have wide forward cone) float forward = target->GetOrientation(); if (tick <= 3) - { target->SetOrientation(forward + 0.75f * M_PI_F - tick * M_PI_F / 8); } // Left + { + target->SetOrientation(forward + 0.75f * M_PI_F - tick * M_PI_F / 8); // Left + } else - { target->SetOrientation(forward - 0.75f * M_PI_F + (8 - tick) * M_PI_F / 8); } // Right + { + target->SetOrientation(forward - 0.75f * M_PI_F + (8 - tick) * M_PI_F / 8); // Right + } triggerTarget->CastSpell(triggerTarget, spellForTick[tick], true, NULL, this, casterGUID); target->SetOrientation(forward); @@ -1526,7 +1602,9 @@ void Aura::TriggerSpell() if (pCaster->getVictim() && !pCaster->IsWithinDistInMap(target, 60.0f)) { if (Unit* pTarget = ((Creature*)pCaster)->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) + { target->CastSpell(pTarget, 28099, false);// Shock + } } else { @@ -1734,9 +1812,13 @@ void Aura::TriggerSpell() float newAngle = target->GetOrientation(); if (auraId == 37429) + { newAngle += 2 * M_PI_F / 100; + } else + { newAngle -= 2 * M_PI_F / 100; + } newAngle = NormalizeOrientation(newAngle); @@ -1772,7 +1854,9 @@ void Aura::TriggerSpell() } if (Unit* caster = GetCaster()) + { caster->CastSpell(caster, 38495, true, NULL, this); + } else { return; @@ -1828,9 +1912,13 @@ void Aura::TriggerSpell() { case 1: if (target->HasAura(40506)) + { target->RemoveAurasDueToSpell(40506); + } else + { trigger_spell_id = 40506; + } break; case 2: trigger_spell_id = 40510; @@ -1864,9 +1952,13 @@ void Aura::TriggerSpell() float newAngle = target->GetOrientation(); if (auraId == 42581) + { newAngle += 2 * M_PI_F / 100; + } else + { newAngle -= 2 * M_PI_F / 100; + } newAngle = NormalizeOrientation(newAngle); @@ -1980,7 +2072,9 @@ void Aura::TriggerSpell() if (Unit* expectedTarget = target->GetMap()->GetUnit((*itr)->getUnitGuid())) { if (expectedTarget->GetTypeId() == TYPEID_PLAYER) + { target->CastSpell(expectedTarget, 69015, true); + } } } return; @@ -2177,9 +2271,13 @@ void Aura::TriggerSpell() case 38443: // Totemic Mastery (Skyshatter Regalia (Shaman Tier 6) - bonus) { if (triggerTarget->IsAllTotemSlotsUsed()) + { triggerTarget->CastSpell(triggerTarget, 38437, true, NULL, this); + } else + { triggerTarget->RemoveAurasDueToSpell(38437); + } return; } default: @@ -2298,7 +2396,9 @@ void Aura::TriggerSpell() case 38736: // Rod of Purification - for quest 10839 (Veil Skith: Darkstone of Terokk) { if (Unit* caster = GetCaster()) + { caster->CastSpell(triggerTarget, trigger_spell_id, true, NULL, this); + } return; } case 43149: // Claw Rage @@ -2340,9 +2440,13 @@ void Aura::TriggerSpell() if (WorldObject* channelTarget = target->GetMap()->GetWorldObject(target->GetChannelObjectGuid())) { if (channelTarget->isType(TYPEMASK_UNIT)) + { triggerTarget = (Unit*)channelTarget; + } else + { triggerTargetObject = channelTarget; + } } } // or periodic aura at caster channel target @@ -2425,7 +2529,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) // FIX_ME: this is 2.0.12 threat effect replaced in 2.1.x by dummy aura, must be checked for correctness if (target->CanHaveThreatList()) if (Unit* caster = GetCaster()) + { target->AddThreat(caster, 10.0f, false, GetSpellSchoolMask(GetSpellProto()), GetSpellProto()); + } return; case 7057: // Haunting Spirits // expected to tick with 30 sec period (tick part see in Aura::PeriodicTick) @@ -2450,7 +2556,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 13139: // net-o-matic // root to self part of (root_target->charge->root_self sequence if (Unit* caster = GetCaster()) + { caster->CastSpell(caster, 13138, true, NULL, this); + } return; case 28832: // Mark of Korth'azz case 28833: // Mark of Blaumeux @@ -2473,7 +2581,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) } if (Unit* caster = GetCaster()) + { caster->CastCustomSpell(target, 28836, &damage, NULL, NULL, true, NULL, this); + } return; } case 31606: // Stormcrow Amulet @@ -2482,7 +2592,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) // we must assume db or script set display id to native at ending flight (if not, target is stuck with this model) if (cInfo) + { target->SetDisplayId(Creature::ChooseDisplayId(cInfo)); + } return; } @@ -2525,7 +2637,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) } case 39850: // Rocket Blast if (roll_chance_i(20)) // backfire stun + { target->CastSpell(target, 51581, true, NULL, this); + } return; case 43873: // Headless Horseman Laugh target->PlayDistanceSound(11965); @@ -2534,7 +2648,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // Escorting Alliance Deserter if (target->GetMiniPet()) + { target->CastSpell(target, 45957, true); + } return; } @@ -2601,16 +2717,22 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 63624: // Learn a Second Talent Specialization // Teach Learn Talent Specialization Switches, required for client triggered casts, allow after 30 sec delay if (target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->learnSpell(63680, false); + } return; case 63651: // Revert to One Talent Specialization // Teach Learn Talent Specialization Switches, remove if (target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->removeSpell(63680); + } return; case 64132: // Constrictor Tentacle if (target->GetTypeId() == TYPEID_PLAYER) + { target->CastSpell(target, 64133, true, NULL, this); + } return; case 65684: // Dark Essence target->RemoveAurasDueToSpell(65686); @@ -2629,11 +2751,15 @@ void Aura::HandleAuraDummy(bool apply, bool Real) return; case 70623: // Jaina's Call if (target->GetTypeId() == TYPEID_PLAYER) + { target->CastSpell(target, 70525, true, NULL, this); + } return; case 70638: // Call of Sylvanas if (target->GetTypeId() == TYPEID_PLAYER) + { target->CastSpell(target, 70639, true, NULL, this); + } return; case 71342: // Big Love Rocket Spell::SelectMountByAreaAndSkill(target, GetSpellProto(), 71344, 71345, 71346, 71347, 0); @@ -2889,7 +3015,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) } if (finalSpellId) + { caster->CastSpell(target, finalSpellId, true, NULL, this); + } return; } @@ -2922,7 +3050,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) // Idom Rool Camera Shake <- wtf, don't drink while making spellnames? if (Unit* caster = GetCaster()) + { caster->CastSpell(caster, 12816, true); + } return; } @@ -2937,28 +3067,36 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 32045: // Soul Charge { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 32054, true, NULL, this); + } return; } case 32051: // Soul Charge { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 32057, true, NULL, this); + } return; } case 32052: // Soul Charge { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 32053, true, NULL, this); + } return; } case 32286: // Focus Target Visual { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 32301, true, NULL, this); + } return; } @@ -2966,7 +3104,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 59628: // Tricks of the Trade, triggered buff { if (Unit* pCaster = GetCaster()) + { pCaster->GetHostileRefManager().ResetThreatRedirection(); + } return; } case 36730: // Flame Strike @@ -3010,7 +3150,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) // Captured Totem Test Credit if (Player* pPlayer = pCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) + { pPlayer->CastSpell(pPlayer, 42455, true); + } } return; @@ -3023,21 +3165,27 @@ void Aura::HandleAuraDummy(bool apply, bool Real) Unit* pCaster = GetCaster(); if (pSummon && pCaster) + { pSummon->GetMotionMaster()->MovePoint(0, pCaster->GetPositionX(), pCaster->GetPositionY(), pCaster->GetPositionZ()); + } return; } case 43681: // Inactive { if (m_removeMode == AURA_REMOVE_BY_EXPIRE && target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->ToggleAFK(); + } return; } case 43969: // Feathered Charm { // Steelfeather Quest Credit, Are there any requirements for this, like area? if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 43984, true); + } return; } @@ -3055,7 +3203,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // Kill target if dispelled if (m_removeMode == AURA_REMOVE_BY_DISPEL) + { target->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + } return; } case 45963: // Call Alliance Deserter @@ -3084,7 +3234,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // Blood Oath if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 50001, true, NULL, this); + } return; } @@ -3112,7 +3264,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) if (Unit* pCaster = GetCaster()) { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { pCaster->CastSpell(target, 51872, true, NULL, this); + } } return; @@ -3120,7 +3274,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 52098: // Charge Up { if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 52092, true, NULL, this); + } return; } @@ -3152,7 +3308,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // Towers of Certain Doom: Skorn Cannonfire if (m_removeMode == AURA_REMOVE_BY_DEFAULT) + { target->CastSpell(target, 43069, true); + } return; } @@ -3171,7 +3329,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 61900: // Electrical Charge { if (m_removeMode == AURA_REMOVE_BY_DEATH) + { target->CastSpell(target, GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_0), true); + } return; } @@ -3189,7 +3349,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) if (classOptions && classOptions->SpellFamilyName == SPELLFAMILY_MAGE && (classOptions->SpellFamilyFlags & UI64LIT(0x2000000000000))) { if (m_removeMode == AURA_REMOVE_BY_EXPIRE || m_removeMode == AURA_REMOVE_BY_DISPEL) + { target->CastSpell(target, m_modifier.m_amount, true, NULL, this); + } return; } @@ -3233,7 +3395,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) caster->CastSpell(target, 24659, true, NULL, NULL, GetCasterGuid()); } else + { target->RemoveAurasDueToSpell(24659); + } return; } case 24661: // Restless Strength @@ -3249,7 +3413,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) caster->CastSpell(target, 24662, true, NULL, NULL, GetCasterGuid()); } else + { target->RemoveAurasDueToSpell(24662); + } return; } case 29266: // Permanent Feign Death @@ -3274,7 +3440,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) // Some appear to be used depending on creature location, in water, at solid ground, in air/suspended, etc // For now, just handle all the same way if (target->GetTypeId() == TYPEID_UNIT) + { target->SetFeignDeath(apply); + } return; } @@ -3317,9 +3485,13 @@ void Aura::HandleAuraDummy(bool apply, bool Real) if (owner && owner->GetTypeId() == TYPEID_PLAYER) { if (apply) + { owner->CastSpell(owner, 8985, true); + } else + { ((Player*)owner)->RemovePet(PET_SAVE_REAGENTS); + } } return; } @@ -3335,9 +3507,13 @@ void Aura::HandleAuraDummy(bool apply, bool Real) if (owner && owner->GetTypeId() == TYPEID_PLAYER) { if (apply) + { owner->CastSpell(owner, 19704, true); + } else + { ((Player*)owner)->RemovePet(PET_SAVE_REAGENTS); + } } return; } @@ -3359,11 +3535,15 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // aura animate dead (fainted) state for the duration, but we need to animate the death itself (correct way below?) if (Unit* pCaster = GetCaster()) + { pCaster->ApplyModFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH, apply); + } // Beam to Zelfrax at remove if (!apply) + { target->CastSpell(target, 42517, true); + } return; } case 42583: // Claw Rage @@ -3376,16 +3556,22 @@ void Aura::HandleAuraDummy(bool apply, bool Real) } if (apply) + { caster->FixateTarget(target); + } else if (target->GetObjectGuid() == caster->GetFixateTargetGuid()) + { caster->FixateTarget(NULL); + } return; } case 43874: // Scourge Mur'gul Camp: Force Shield Arcane Purple x3 target->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE, apply); if (apply) + { target->addUnitState(UNIT_STAT_ROOT); + } return; case 47178: // Plague Effect Self target->SetFeared(apply, GetCasterGuid(), GetId()); @@ -3400,10 +3586,14 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // Play part 1 if (apply) + { target->PlayDirectSound(14970, (Player*)target); + } // continue in 58205 else + { target->CastSpell(target, 58205, true); + } } return; case 58205: // LK Intro VO (2) @@ -3411,25 +3601,37 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // Play part 2 if (apply) + { target->PlayDirectSound(14971, (Player*)target); + } // Play part 3 else + { target->PlayDirectSound(14972, (Player*)target); + } } return; case 27978: case 40131: if (apply) + { target->m_AuraFlags |= UNIT_AURAFLAG_ALIVE_INVISIBLE; + } else + { target->m_AuraFlags &= ~UNIT_AURAFLAG_ALIVE_INVISIBLE; + } return; case 66936: // Submerge case 66948: // Submerge if (apply) + { target->CastSpell(target, 66969, true); + } else + { target->RemoveAurasDueToSpell(66969); + } return; } break; @@ -3443,13 +3645,17 @@ void Aura::HandleAuraDummy(bool apply, bool Real) { // NOTE: for avoid use additional field damage stored in dummy value (replace unused 100% if (apply) + { m_modifier.m_amount = 0; // use value as damage counter instead redundant 100% percent + } else { int32 bp0 = m_modifier.m_amount; if (Unit* caster = GetCaster()) + { target->CastCustomSpell(caster, 48210, &bp0, NULL, NULL, true, NULL, this); + } } } break; @@ -3470,7 +3676,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) target->CastSpell(target, 62071, true); } else + { target->RemoveAurasDueToSpell(62071); + } return; } case 61336: // Survival Instincts @@ -3486,7 +3694,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) target->CastCustomSpell(target, 50322, &bp0, NULL, NULL, true); } else + { target->RemoveAurasDueToSpell(50322); + } return; } } @@ -3561,7 +3771,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) target->CastSpell(target, spell_id, true); } else + { target->RemoveAurasDueToSpell(spell_id); + } return; } break; @@ -3572,12 +3784,16 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 57934: // Tricks of the Trade, main spell { if (apply) + { GetHolder()->SetAuraCharges(1); // not have proper charges set in spell data + } else { // used for direct in code aura removes and spell proc event charges expire if (m_removeMode != AURA_REMOVE_BY_DEFAULT) + { target->GetHostileRefManager().ResetThreatRedirection(); + } } return; } @@ -3590,12 +3806,16 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 34477: // Misdirection, main spell { if (apply) + { GetHolder()->SetAuraCharges(1); // not have proper charges set in spell data + } else { // used for direct in code aura removes and spell proc event charges expire if (m_removeMode != AURA_REMOVE_BY_DEFAULT) + { target->GetHostileRefManager().ResetThreatRedirection(); + } } return; } @@ -3609,9 +3829,13 @@ void Aura::HandleAuraDummy(bool apply, bool Real) case 25899: // Greater Blessing of Sanctuary { if (apply) + { target->CastSpell(target, 67480, true, NULL, this); + } else + { target->RemoveAurasDueToSpell(67480); + } return; } } @@ -3630,9 +3854,13 @@ void Aura::HandleAuraDummy(bool apply, bool Real) Totem* totem = target->GetTotem(TOTEM_SLOT_AIR); if (totem && apply) + { ((Player*)target)->GetCamera().SetView(totem); + } else + { ((Player*)target)->GetCamera().ResetView(); + } return; } @@ -3645,9 +3873,13 @@ void Aura::HandleAuraDummy(bool apply, bool Real) if (PetAura const* petSpell = sSpellMgr.GetPetAura(GetId(), m_effIndex)) { if (apply) + { target->AddPetAura(petSpell); + } else + { target->RemovePetAura(petSpell); + } return; } @@ -3668,7 +3900,9 @@ void Aura::HandleAuraDummy(bool apply, bool Real) // script has to "handle with care", only use where data are not ok to use in the above code. if (target->GetTypeId() == TYPEID_UNIT) + { sScriptMgr.OnAuraDummy(this, apply); + } } void Aura::HandleAuraMounted(bool apply, bool Real) @@ -3685,7 +3919,9 @@ void Aura::HandleAuraMounted(bool apply, bool Real) { // Running Wild if (GetId() == 87840) + { target->Mount(target->getGender() == GENDER_MALE ? 29422 : 29423, GetId()); + } CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (!ci) @@ -3706,12 +3942,16 @@ void Aura::HandleAuraMounted(bool apply, bool Real) target->SetVehicleId(ci->VehicleTemplateId, ci->Entry); if (target->GetTypeId() == TYPEID_PLAYER) + { target->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE); + } } target->Mount(display_id, GetId()); if (MountCapabilityEntry const* mountCapability = target->GetMountCapability(uint32(GetMiscBValue()))) + { target->CastSpell(target, mountCapability->SpeedModSpell, true); + } } else { @@ -3719,13 +3959,17 @@ void Aura::HandleAuraMounted(bool apply, bool Real) // remove speed aura if (MountCapabilityEntry const* mountCapability = target->GetMountCapability(m_modifier.m_amount)) + { target->RemoveAurasByCasterSpell(mountCapability->SpeedModSpell, target->GetObjectGuid()); + } CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(m_modifier.m_miscvalue); if (ci && target->IsVehicle() && ci->VehicleTemplateId == target->GetVehicleInfo()->GetVehicleEntry()->m_ID) { if (target->GetTypeId() == TYPEID_PLAYER) + { target->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_PLAYER_VEHICLE); + } target->SetVehicleId(0, 0); } @@ -3802,21 +4046,29 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) // since no field in creature_templates describes wether an alliance or // horde modelid should be used at shapeshifting if (target->GetTypeId() != TYPEID_PLAYER) + { modelid = ssEntry->modelID_A; + } else { // players are a bit different since the dbc has seldomly an horde modelid if (Player::TeamForRace(target->getRace()) == HORDE) { if (ssEntry->modelID_H) + { modelid = ssEntry->modelID_H; // 3.2.3 only the moonkin form has this information + } else // get model for race + { modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, target->getRaceMask()); + } } // nothing found in above, so use default if (!modelid) + { modelid = ssEntry->modelID_A; + } } } @@ -3858,7 +4110,9 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) // and polymorphic affects if (target->IsPolymorphed()) + { target->RemoveAurasDueToSpell(target->getTransForm()); + } break; } @@ -3874,7 +4128,9 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) target->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT, GetHolder()); if (modelid > 0) + { target->SetDisplayId(modelid); + } // now only powertype must be set switch (form) @@ -3896,7 +4152,9 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) { // reset power to default values only at power change if (target->GetPowerType() != PowerType) + { target->SetPowerType(PowerType); + } switch (form) { @@ -3929,7 +4187,9 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) { target->SetPower(POWER_RAGE, 0); if (irand(1, 100) <= furorChance) + { target->CastSpell(target, 17057, true, NULL, this); + } } break; } @@ -3944,15 +4204,22 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) PlayerSpellMap const& sp_list = ((Player*)target)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { - if(itr->second.state == PLAYERSPELL_REMOVED) continue; + if(itr->second.state == PLAYERSPELL_REMOVED) + { + continue; + } SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first); if (spellInfo && spellInfo->GetSpellFamilyName() == SPELLFAMILY_WARRIOR && spellInfo->Id == 139) + { Rage_val += target->CalculateSpellDamage(target, spellInfo, EFFECT_INDEX_0) * 10; + } } } if (target->GetPower(POWER_RAGE) > Rage_val) + { target->SetPower(POWER_RAGE, Rage_val); + } break; } default: @@ -3967,15 +4234,21 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) if (target->GetTypeId() == TYPEID_PLAYER) for (uint32 i = 0; i < 8; ++i) if (ssEntry->spellId[i]) + { ((Player*)target)->addSpell(ssEntry->spellId[i], true, false, false, false); + } } else { if (modelid > 0) + { target->SetDisplayId(target->GetNativeDisplayId()); + } if (target->getClass() == CLASS_DRUID) + { target->SetPowerType(POWER_MANA); + } target->SetShapeshiftForm(FORM_NONE); @@ -3985,12 +4258,16 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) case FORM_BEAR: case FORM_CAT: if (Aura* dummy = target->GetDummyAura(37315)) + { target->CastSpell(target, 37316, true, NULL, dummy); + } break; // Nordrassil Regalia - bonus case FORM_MOONKIN: if (Aura* dummy = target->GetDummyAura(37324)) + { target->CastSpell(target, 37325, true, NULL, dummy); + } break; default: break; @@ -4000,7 +4277,9 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) if (target->GetTypeId() == TYPEID_PLAYER) for (uint32 i = 0; i < 8; ++i) if (ssEntry->spellId[i]) + { ((Player*)target)->removeSpell(ssEntry->spellId[i], false, false, false); + } } // adding/removing linked auras @@ -4008,11 +4287,15 @@ void Aura::HandleAuraModShapeshift(bool apply, bool Real) HandleShapeshiftBoosts(apply); if (target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->InitDataForForm(); + } // update form-dependent armor specializations if (target->GetTypeId() == TYPEID_PLAYER && ((Player*)target)->getClass() == CLASS_DRUID) + { ((Player*)target)->UpdateArmorSpecializations(); + } } void Aura::HandleAuraTransform(bool apply, bool Real) @@ -4247,7 +4530,9 @@ void Aura::HandleAuraTransform(bool apply, bool Real) sLog.outError("Auras: unknown creature id = %d (only need its modelid) Form Spell Aura Transform in Spell ID = %d", m_modifier.m_miscvalue, GetId()); } else - { model_id = Creature::ChooseDisplayId(ci); } // Will use the default model here + { + model_id = Creature::ChooseDisplayId(ci); // Will use the default model here + } // Polymorph (sheep/penguin case) if (GetSpellProto()->GetSpellFamilyName() == SPELLFAMILY_MAGE && GetSpellProto()->Id == 82) @@ -4269,16 +4554,22 @@ void Aura::HandleAuraTransform(bool apply, bool Real) // creature case, need to update equipment if additional provided if (ci && target->GetTypeId() == TYPEID_UNIT) + { ((Creature*)target)->LoadEquipment(ci->EquipmentTemplateId, false); + } // Dragonmaw Illusion (set mount model also) if (GetId() == 42016 && target->GetMountID() && !target->GetAurasByType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED).empty()) + { target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314); + } } // update active transform spell only not set or not overwriting negative by positive case if (!target->getTransForm() || !IsPositiveSpell(GetId()) || IsPositiveSpell(target->getTransForm())) + { target->setTransForm(GetId()); + } // polymorph case if (Real && target->GetTypeId() == TYPEID_PLAYER && target->IsPolymorphed()) @@ -4286,11 +4577,15 @@ void Aura::HandleAuraTransform(bool apply, bool Real) // for players, start regeneration after 1s (in polymorph fast regeneration case) // only if caster is Player (after patch 2.4.2) if (GetCasterGuid().IsPlayer()) + { ((Player*)target)->setRegenTimer(1 * IN_MILLISECONDS); + } // dismount polymorphed target (after patch 2.4.2) if (target->IsMounted()) + { target->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED, GetHolder()); + } } } else // !apply @@ -4301,7 +4596,9 @@ void Aura::HandleAuraTransform(bool apply, bool Real) // apply default equipment for creature case if (target->GetTypeId() == TYPEID_UNIT) + { ((Creature*)target)->LoadEquipment(((Creature*)target)->GetCreatureInfo()->EquipmentTemplateId, true); + } // re-apply some from still active with preference negative cases Unit::AuraList const& otherTransforms = target->GetAurasByType(SPELL_AURA_TRANSFORM); @@ -4332,7 +4629,9 @@ void Aura::HandleAuraTransform(bool apply, bool Real) uint32 display_id = Creature::ChooseDisplayId(ci); CreatureModelInfo const* minfo = sObjectMgr.GetCreatureModelRandomGender(display_id); if (minfo) + { display_id = minfo->modelid; + } target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, display_id); } @@ -4420,7 +4719,9 @@ void Aura::HandleChannelDeathItem(bool apply, bool Real) // Only from non-grey units if (!((Player*)caster)->isHonorOrXPTarget(victim) || (victim->GetTypeId() == TYPEID_UNIT && !((Player*)caster)->isAllowedToLoot((Creature*)victim))) - { return; } + { + return; + } } // Adding items @@ -4447,7 +4748,9 @@ void Aura::HandleChannelDeathItem(bool apply, bool Real) { // Glyph of Soul Shard if (caster->HasAura(58070) && roll_chance_i(40)) + { caster->CastSpell(caster, 58068, true, NULL, this); + } } } } @@ -4590,7 +4893,9 @@ void Aura::HandleModPossess(bool apply, bool Real) caster->TakePossessOf(target); } else + { caster->ResetControlState(); + } } void Aura::HandleModPossessPet(bool apply, bool Real) @@ -4635,7 +4940,9 @@ void Aura::HandleModPossessPet(bool apply, bool Real) caster->TakePossessOf(target); } else + { caster->ResetControlState(); + } } void Aura::HandleAuraModPetTalentsPoints(bool /*Apply*/, bool Real) @@ -4647,7 +4954,9 @@ void Aura::HandleAuraModPetTalentsPoints(bool /*Apply*/, bool Real) // Recalculate pet talent points if (Pet* pet = GetTarget()->GetPet()) + { pet->InitTalentForLevel(); + } } void Aura::HandleModCharm(bool apply, bool Real) @@ -4711,9 +5020,13 @@ void Aura::HandleModCharm(bool apply, bool Real) if (target->GetByteValue(UNIT_FIELD_BYTES_0, 1) == 0) { if (cinfo->UnitClass == 0) + { sLog.outErrorDb("Creature (Entry: %u) have UnitClass = 0 but used in charmed spell, that will be result client crash.", cinfo->Entry); + } else + { sLog.outError("Creature (Entry: %u) have UnitClass = %u but at charming have class 0!!! that will be result client crash.", cinfo->Entry, cinfo->UnitClass); + } target->SetByteValue(UNIT_FIELD_BYTES_0, 1, CLASS_MAGE); } @@ -4736,7 +5049,9 @@ void Aura::HandleModCharm(bool apply, bool Real) target->SetCharmerGuid(ObjectGuid()); if (target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->setFactionForRace(target->getRace()); + } else { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); @@ -4749,10 +5064,14 @@ void Aura::HandleModCharm(bool apply, bool Real) target->setFaction(owner->getFaction()); } else if (cinfo) + { target->setFaction(cinfo->FactionAlliance); + } } else if (cinfo) // normal creature + { target->setFaction(cinfo->FactionAlliance); + } // restore UNIT_FIELD_BYTES_0 if (cinfo && caster->GetTypeId() == TYPEID_PLAYER && caster->getClass() == CLASS_WARLOCK && cinfo->CreatureType == CREATURE_TYPE_DEMON) @@ -4878,7 +5197,9 @@ void Aura::HandleAuraModDisarm(bool apply, bool Real) } if (apply) + { target->SetAttackTime(attack_type, BASE_ATTACK_TIME); + } else { ((Player*)target)->SetRegularAttackTime(); @@ -4918,7 +5239,9 @@ void Aura::HandleAuraModStun(bool apply, bool Real) target->SetRoot(true); } else + { target->StopMoving(); + } // Summon the Naj'entus Spine GameObject on target if spell is Impaling Spine if (GetId() == 39837) @@ -4933,7 +5256,9 @@ void Aura::HandleAuraModStun(bool apply, bool Real) target->GetMap()->Add(pObj); } else + { delete pObj; + } } } else @@ -5101,7 +5426,9 @@ void Aura::HandleModStealth(bool apply, bool Real) { // Master of Subtlety if ((*i)->GetSpellProto()->Id == 2114) + { target->CastSpell(target, 31666, true); + } // Overkill else if ((*i)->GetId() == 58426 && classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000400000)) { @@ -5172,7 +5499,9 @@ void Aura::HandleInvisibility(bool apply, bool Real) } if (GetId() == 48809) // Binding Life + { target->CastSpell(target, GetSpellProto()->CalculateSimpleValue(m_effIndex), true); + } } } @@ -5275,7 +5604,9 @@ void Aura::HandleAuraModRoot(bool apply, bool Real) target->clearUnitState(UNIT_STAT_ROOT); if (!target->hasUnitState(UNIT_STAT_STUNNED) && (target->GetTypeId() == TYPEID_PLAYER)) // prevent allow move if have also stun effect + { target->SetRoot(false); + } } } @@ -5297,7 +5628,9 @@ void Aura::HandleAuraModSilence(bool apply, bool Real) if (Spell* spell = target->GetCurrentSpell(CurrentSpellTypes(i))) if(spell->m_spellInfo->GetPreventionType() == SPELL_PREVENTION_TYPE_SILENCE) // Stop spells on prepare or casting state - { target->InterruptSpell(CurrentSpellTypes(i), false); } + { + target->InterruptSpell(CurrentSpellTypes(i), false); + } } else { @@ -5485,11 +5818,15 @@ void Aura::HandleAuraModIncreaseFlightSpeed(bool apply, bool Real) // Players on flying mounts must be immune to polymorph if (target->GetTypeId() == TYPEID_PLAYER) + { target->ApplySpellImmune(GetId(), IMMUNITY_MECHANIC, MECHANIC_POLYMORPH, apply); + } // Dragonmaw Illusion (overwrite mount model, mounted aura already applied) if (apply && target->HasAura(42016, EFFECT_INDEX_0) && target->GetMountID()) + { target->SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 16314); + } // Festive Holiday Mount if (apply && GetSpellProto()->Id != 1794 && target->HasAura(62061)) @@ -5521,7 +5858,9 @@ void Aura::HandleAuraModIncreaseFlightSpeed(bool apply, bool Real) } } if (changedSpeed) + { break; + } } } } @@ -5556,7 +5895,9 @@ void Aura::HandleAuraModDecreaseSpeed(bool apply, bool Real) if (GetId() == 33572) { if (GetStackAmount() >= 5 && !target->HasAura(33652)) + { target->CastSpell(target, 33652, true); + } } } @@ -5590,7 +5931,9 @@ void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/) // Forbearance // in DBC wrong mechanic immune since 3.0.x if (GetId() == 25771) + { misc = MECHANIC_IMMUNE_SHIELD; + } Unit* target = GetTarget(); @@ -5600,7 +5943,9 @@ void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/) // immune movement impairment and loss of control (spell data have special structure for mark this case) if (IsSpellRemoveAllMovementAndControlLossEffects(GetSpellProto())) + { mechanic = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK; + } target->RemoveAurasAtMechanicImmunity(mechanic, GetId()); } @@ -5620,9 +5965,13 @@ void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/) if ((*i)->GetSpellProto()->Id == 2229) { if (apply) + { owner->CastSpell(owner, 34471, true, NULL, this); + } else + { owner->RemoveAurasDueToSpell(34471); + } break; } } @@ -5630,7 +5979,9 @@ void Aura::HandleModMechanicImmunity(bool apply, bool /*Real*/) } // Heroic Fury (Intercept cooldown remove) else if (apply && GetSpellProto()->Id == 60970 && target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->RemoveSpellCooldown(20252, true); + } } void Aura::HandleModMechanicImmunityMask(bool apply, bool /*Real*/) @@ -5773,16 +6124,22 @@ void Aura::HandleAuraProcTriggerSpell(bool apply, bool Real) // some spell have charges by functionality not have its in spell data case 28200: // Ascendance (Talisman of Ascendance trinket) if (apply) + { GetHolder()->SetAuraCharges(6); + } break; case 50720: // Vigilance (threat transfering) if (apply) { if (Unit* caster = GetCaster()) + { target->CastSpell(caster, 59665, true); + } } else + { target->GetHostileRefManager().ResetThreatRedirection(); + } break; default: break; @@ -5818,12 +6175,16 @@ void Aura::HandlePeriodicTriggerSpell(bool apply, bool /*Real*/) { case 66: // Invisibility if (m_removeMode == AURA_REMOVE_BY_EXPIRE) + { target->CastSpell(target, 32612, true, NULL, this); + } return; case 42783: // Wrath of the Astrom... if (m_removeMode == AURA_REMOVE_BY_EXPIRE && GetEffIndex() + 1 < MAX_EFFECT_INDEX) + { target->CastSpell(target, GetSpellProto()->CalculateSimpleValue(SpellEffectIndex(GetEffIndex() + 1)), true); + } return; case 46221: // Animal Blood @@ -5839,7 +6200,9 @@ void Aura::HandlePeriodicTriggerSpell(bool apply, bool /*Real*/) if (m_removeMode == AURA_REMOVE_BY_EXPIRE) { if (Unit* pCaster = GetCaster()) + { pCaster->CastSpell(target, m_spellEffect->EffectTriggerSpell, true, NULL, this); + } } return; @@ -5873,7 +6236,9 @@ void Aura::HandlePeriodicEnergize(bool apply, bool Real) case 54833: // Glyph of Innervate (value%/2 of casters base mana) { if (Unit* caster = GetCaster()) + { m_modifier.m_amount = int32(caster->GetCreateMana() * GetBasePoints() / (200 * GetAuraMaxTicks())); + } break; } case 29166: // Innervate (value% of casters base mana) @@ -5882,7 +6247,9 @@ void Aura::HandlePeriodicEnergize(bool apply, bool Real) { // Glyph of Innervate if (caster->HasAura(54832)) + { caster->CastSpell(caster, 54833, true, NULL, this); + } m_modifier.m_amount = int32(caster->GetCreateMana() * GetBasePoints() / (100 * GetAuraMaxTicks())); } @@ -5940,7 +6307,9 @@ void Aura::HandleAuraPeriodicDummy(bool apply, bool Real) } } else + { target->RemoveAurasDueToSpell(31665); + } break; } } @@ -5952,7 +6321,9 @@ void Aura::HandleAuraPeriodicDummy(bool apply, bool Real) // Explosive Shot if (apply && !loading && caster) + { m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(RANGED_ATTACK) * 14 / 100); + } break; } } @@ -5989,7 +6360,9 @@ void Aura::HandlePeriodicHeal(bool apply, bool /*Real*/) int32 ap = int32(0.22f * caster->GetTotalAttackPowerValue(BASE_ATTACK)); int32 holy = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(GetSpellProto())); if (holy < 0) + { holy = 0; + } holy = int32(holy * 377 / 1000); m_modifier.m_amount += ap > holy ? ap : holy; } @@ -6005,7 +6378,9 @@ void Aura::HandlePeriodicHeal(bool apply, bool /*Real*/) // Rejuvenation if (GetSpellProto()->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000010))) if (caster->HasAura(64760)) // Item - Druid T8 Restoration 4P Bonus + { caster->CastCustomSpell(target, 64801, &m_modifier.m_amount, NULL, NULL, true, NULL); + } } } @@ -6036,7 +6411,9 @@ void Aura::HandleDamagePercentTaken(bool apply, bool Real) // Glyph of Salvation if (target->GetObjectGuid() == GetCasterGuid()) if (Aura* aur = target->GetAura(63225, EFFECT_INDEX_0)) + { m_modifier.m_amount -= aur->GetModifier()->m_amount; + } } } } @@ -6103,7 +6480,9 @@ void Aura::HandlePeriodicDamage(bool apply, bool Real) if (classOptions->SpellFamilyFlags & UI64LIT(0x000000000000800000)) { if (caster->GetTypeId() != TYPEID_PLAYER) + { break; + } // 0.01*$AP*cp uint8 cp = ((Player*)caster)->GetComboPoints(); @@ -6128,7 +6507,9 @@ void Aura::HandlePeriodicDamage(bool apply, bool Real) if (classOptions->SpellFamilyFlags & UI64LIT(0x000000000000100000)) { if (caster->GetTypeId() != TYPEID_PLAYER) + { break; + } // 1 point : ${($m1+$b1*1+0.015*$AP)*4} damage over 8 secs // 2 points: ${($m1+$b1*2+0.024*$AP)*5} damage over 10 secs // 3 points: ${($m1+$b1*3+0.03*$AP)*6} damage over 12 secs @@ -6137,7 +6518,9 @@ void Aura::HandlePeriodicDamage(bool apply, bool Real) float AP_per_combo[6] = {0.0f, 0.015f, 0.024f, 0.03f, 0.03428571f, 0.0375f}; uint8 cp = ((Player*)caster)->GetComboPoints(); if (cp > 5) cp = 5; - m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * AP_per_combo[cp]); + { + m_modifier.m_amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * AP_per_combo[cp]); + } } break; } @@ -6150,7 +6533,9 @@ void Aura::HandlePeriodicDamage(bool apply, bool Real) float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)); if (holy < 0) + { holy = 0; + } m_modifier.m_amount += int32(GetStackAmount()) * (int32(ap * 0.025f) + int32(holy * 13 / 1000)); } break; @@ -6164,7 +6549,9 @@ void Aura::HandlePeriodicDamage(bool apply, bool Real) // SpellDamageBonusDone for magic spells uint32 dmgClass = spellProto->GetDmgClass(); if(dmgClass == SPELL_DAMAGE_CLASS_NONE || dmgClass == SPELL_DAMAGE_CLASS_MAGIC) + { m_modifier.m_amount = caster->SpellDamageBonusDone(target, GetSpellProto(), m_modifier.m_amount, DOT, GetStackAmount()); + } // MeleeDamagebonusDone for weapon based spells else { @@ -6178,7 +6565,9 @@ void Aura::HandlePeriodicDamage(bool apply, bool Real) { // Parasitic Shadowfiend - handle summoning of two Shadowfiends on DoT expire if (spellProto->Id == 41917) + { target->CastSpell(target, 41915, true); + } } } @@ -6258,7 +6647,9 @@ void Aura::HandleAuraModResistanceExclusive(bool apply, bool /*Real*/) { GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), BASE_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER) + { GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply); + } } } } @@ -6271,7 +6662,9 @@ void Aura::HandleAuraModResistance(bool apply, bool /*Real*/) { GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + x), TOTAL_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet()) + { GetTarget()->ApplyResistanceBuffModsMod(SpellSchools(x), m_positive, float(m_modifier.m_amount), apply); + } } } } @@ -6358,7 +6751,9 @@ void Aura::HandleAuraModStat(bool apply, bool /*Real*/) // m_target->ApplyStatMod(Stats(i), m_modifier.m_amount,apply); GetTarget()->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_VALUE, float(m_modifier.m_amount), apply); if (GetTarget()->GetTypeId() == TYPEID_PLAYER || ((Creature*)GetTarget())->IsPet()) + { GetTarget()->ApplyStatBuffMod(Stats(i), float(m_modifier.m_amount), apply); + } } } } @@ -6418,7 +6813,9 @@ void Aura::HandleAuraModDispelResist(bool apply, bool Real) } if (GetId() == 33206) + { GetTarget()->CastSpell(GetTarget(), 44416, true, NULL, this, GetCasterGuid()); + } } void Aura::HandleModSpellDamagePercentFromAttackPower(bool /*apply*/, bool /*Real*/) @@ -6476,7 +6873,9 @@ void Aura::HandleModTotalPercentStat(bool apply, bool /*Real*/) { target->HandleStatModifier(UnitMods(UNIT_MOD_STAT_START + i), TOTAL_PCT, float(m_modifier.m_amount), apply); if (target->GetTypeId() == TYPEID_PLAYER || ((Creature*)target)->IsPet()) + { target->ApplyStatPercentBuffMod(Stats(i), float(m_modifier.m_amount), apply); + } } } @@ -6523,7 +6922,9 @@ void Aura::HandleAuraModTotalManaPercentRegen(bool apply, bool /*Real*/) } if (!GetSpellProto()->HasAttribute(SPELL_ATTR_EX5_START_PERIODIC_AT_APPLY)) + { m_periodicTimer = m_modifier.periodictime; + } m_isPeriodic = apply; } @@ -6536,7 +6937,9 @@ void Aura::HandleModRegen(bool apply, bool /*Real*/) // eating } if (!GetSpellProto()->HasAttribute(SPELL_ATTR_EX5_START_PERIODIC_AT_APPLY)) + { m_periodicTimer = 5000; + } m_isPeriodic = apply; } @@ -6612,9 +7015,13 @@ void Aura::HandleModManaRegen(bool /*apply*/, bool Real) void Aura::HandleComprehendLanguage(bool apply, bool /*Real*/) { if (apply) + { GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG); + } else + { GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_COMPREHEND_LANG); + } } void Aura::HandleAuraModIncreaseHealth(bool apply, bool Real) @@ -6630,7 +7037,9 @@ void Aura::HandleAuraModIncreaseHealth(bool apply, bool Real) case 55233: // Vampiric Blood case 61254: // Will of Sartharion (Obsidian Sanctum) if (Real && apply) + { m_modifier.m_amount = target->GetMaxHealth() * m_modifier.m_amount / 100; + } // no break here // Cases where m_amount already has the correct value (spells cast with CastCustomSpell or absolute values) @@ -6686,7 +7095,9 @@ void Aura::HandleAuraModIncreaseMaxHealth(bool apply, bool /*Real*/) { uint32 newhealth = uint32(ceil((double)target->GetMaxHealth() * healthPercentage)); if (newhealth == 0) + { newhealth = 1; + } target->SetHealth(newhealth); } @@ -7007,7 +7418,9 @@ void Aura::HandleAuraModAttackPowerOfArmor(bool /*apply*/, bool Real) // Recalculate bonus if (GetTarget()->GetTypeId() == TYPEID_PLAYER) + { ((Player*)GetTarget())->UpdateAttackPowerAndDamage(false); + } } /********************************/ /*** DAMAGE BONUS ***/ @@ -7335,7 +7748,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) spellId1 = 49868; if (target->GetTypeId() == TYPEID_PLAYER) // Spell 49868 have same category as main form spell and share cooldown + { ((Player*)target)->RemoveSpellCooldown(49868); + } break; case FORM_GHOSTWOLF: spellId1 = 67116; @@ -7363,13 +7778,17 @@ void Aura::HandleShapeshiftBoosts(bool apply) if (spellId1) { if(target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->RemoveSpellCooldown(spellId1); + } target->CastSpell(target, spellId1, true, NULL, this ); } if (spellId2) { if(target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)target)->RemoveSpellCooldown(spellId2); + } target->CastSpell(target, spellId2, true, NULL, this); } @@ -7405,7 +7824,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) itr = tAuras.begin(); } else + { ++itr; + } } // Master Shapeshifter @@ -7435,7 +7856,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) // Savage Roar if (form == FORM_CAT && ((Player*)target)->HasAura(52610)) + { target->CastSpell(target, 62071, true); + } // Survival of the Fittest (Armor part) if (form == FORM_BEAR) @@ -7448,7 +7871,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) { int32 bp = (*i)->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_2); if (bp) + { target->CastCustomSpell(target, 62069, &bp, NULL, NULL, true, NULL, this); + } break; } } @@ -7475,7 +7900,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) } if (spell_id) + { target->CastSpell(target, spell_id, true, NULL, this); + } break; } } @@ -7491,7 +7918,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) { int32 HotWMod = (*i)->GetModifier()->m_amount; if (GetModifier()->m_miscvalue == FORM_CAT) + { HotWMod /= 2; + } target->CastCustomSpell(target, HotWSpellId, &HotWMod, NULL, NULL, true, NULL, this); break; @@ -7511,7 +7940,9 @@ void Aura::HandleShapeshiftBoosts(bool apply) target->RemoveAurasDueToSpell(spellId2); } if (MasterShaperSpellId) + { target->RemoveAurasDueToSpell(MasterShaperSpellId); + } if (target->GetTypeId() == TYPEID_PLAYER) { @@ -7520,12 +7951,18 @@ void Aura::HandleShapeshiftBoosts(bool apply) for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if (itr->second.state == PLAYERSPELL_REMOVED) continue; - if (itr->first == spellId1 || itr->first == spellId2) continue; + { + if (itr->first == spellId1 || itr->first == spellId2) continue; + } SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (!spellInfo || !IsPassiveSpell(spellInfo)) + { continue; + } if (spellInfo->HasAttribute(SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT) && (spellInfo->GetStancesNot() & (1 << (form - 1)))) + { target->CastSpell(target, itr->first, true, NULL, this); + } } } @@ -7554,7 +7991,9 @@ void Aura::HandleAuraEmpathy(bool apply, bool /*Real*/) CreatureInfo const* ci = ObjectMgr::GetCreatureTemplate(GetTarget()->GetEntry()); if (ci && ci->CreatureType == CREATURE_TYPE_BEAST) + { GetTarget()->ApplyModUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_SPECIALINFO, apply); + } } void Aura::HandleAuraUntrackable(bool apply, bool /*Real*/) @@ -7630,7 +8069,9 @@ void Aura::HandleModRating(bool apply, bool Real) for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating) if (m_modifier.m_miscvalue & (1 << rating)) + { ((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), m_modifier.m_amount, apply); + } } void Aura::HandleModRatingFromStat(bool apply, bool Real) @@ -7648,7 +8089,9 @@ void Aura::HandleModRatingFromStat(bool apply, bool Real) // Just recalculate ratings for (uint32 rating = 0; rating < MAX_COMBAT_RATING; ++rating) if (m_modifier.m_miscvalue & (1 << rating)) + { ((Player*)GetTarget())->ApplyRatingMod(CombatRating(rating), 0, apply); + } } void Aura::HandleForceMoveForward(bool apply, bool Real) @@ -7659,9 +8102,13 @@ void Aura::HandleForceMoveForward(bool apply, bool Real) } if (apply) + { GetTarget()->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); + } else + { GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); + } } void Aura::HandleAuraModExpertise(bool /*apply*/, bool /*Real*/) @@ -7686,17 +8133,23 @@ void Aura::HandleModTargetResistance(bool apply, bool Real) // applied to damage as HandleNoImmediateEffect in Unit::CalculateAbsorbAndResist and Unit::CalcArmorReducedDamage // show armor penetration if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)) + { target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, m_modifier.m_amount, apply); + } // show as spell penetration only full spell penetration bonuses (all resistances except armor and holy if (target->GetTypeId() == TYPEID_PLAYER && (m_modifier.m_miscvalue & SPELL_SCHOOL_MASK_SPELL) == SPELL_SCHOOL_MASK_SPELL) + { target->ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, m_modifier.m_amount, apply); + } } void Aura::HandleModShieldBlockDamage(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() == TYPEID_PLAYER) + { ((Player*)GetTarget())->HandleBaseModValue(SHIELD_BLOCK_DAMAGE_VALUE, FLAT_MOD, float(m_modifier.m_amount), apply); + } } void Aura::HandleAuraRetainComboPoints(bool apply, bool Real) @@ -7795,7 +8248,9 @@ void Aura::HandleSchoolAbsorb(bool apply, bool Real) case SPELLFAMILY_GENERIC: // Stoicism if (spellProto->Id == 70845) + { DoneActualBenefit = caster->GetMaxHealth() * 0.20f; + } break; case SPELLFAMILY_PRIEST: // Power Word: Shield @@ -7882,7 +8337,9 @@ void Aura::HandleSchoolAbsorb(bool apply, bool Real) { // energize target if (!roll_chance_i((*itr)->GetModifier()->m_amount) || caster->HasAura(63853)) + { break; + } switch (target->GetPowerType()) { @@ -7944,7 +8401,9 @@ void Aura::PeriodicTick() if( spellProto->GetSpellEffectIdByIndex(GetEffIndex()) == SPELL_EFFECT_PERSISTENT_AREA_AURA && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) - { return; } + { + return; + } // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) @@ -8037,7 +8496,9 @@ void Aura::PeriodicTick() } // 9..12 ticks, 3/2 from normal tick damage else if (GetAuraTicks() >= 9) - { pdamage += (pdamage + 1) / 2; } // +1 prevent 0.5 damage possible lost at 1..4 ticks + { + pdamage += (pdamage + 1) / 2; // +1 prevent 0.5 damage possible lost at 1..4 ticks + } // 5..8 ticks have normal tick damage } @@ -8055,7 +8516,9 @@ void Aura::PeriodicTick() // only from players // FIXME: need use SpellDamageBonus instead? if (pCaster->GetTypeId() == TYPEID_PLAYER) + { pdamage -= target->GetDamageReduction(pdamage); + } target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !GetSpellProto()->HasAttribute(SPELL_ATTR_EX_CANT_REFLECTED)); @@ -8120,7 +8583,9 @@ void Aura::PeriodicTick() if( spellProto->GetSpellEffectIdByIndex(GetEffIndex()) == SPELL_EFFECT_PERSISTENT_AREA_AURA && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) - { return; } + { + return; + } // Check for immune if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) @@ -8157,7 +8622,9 @@ void Aura::PeriodicTick() // only from players // FIXME: need use SpellDamageBonus instead? if (GetCasterGuid().IsPlayer()) + { pdamage -= target->GetDamageReduction(pdamage); + } target->CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), DOT, pdamage, &absorb, &resist, !spellProto->HasAttribute(SPELL_ATTR_EX_CANT_REFLECTED)); @@ -8206,7 +8673,9 @@ void Aura::PeriodicTick() int32 gain = pCaster->DealHeal(pCaster, heal - absorbHeal, spellProto, false, absorbHeal); // Health Leech effects do not generate healing aggro if (m_modifier.m_auraname == SPELL_AURA_PERIODIC_LEECH) + { break; + } pCaster->GetHostileRefManager().threatAssist(pCaster, gain * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); break; } @@ -8223,11 +8692,15 @@ void Aura::PeriodicTick() // don't heal target if max health or if not alive, mostly death persistent effects from items if (!target->IsAlive() || (target->GetHealth() == target->GetMaxHealth())) + { canApplyHealthPart = false; + } // heal for caster damage (must be alive) if (target != pCaster && spellProto->GetSpellVisual(0) == 163 && !pCaster->IsAlive()) + { canApplyHealthPart = false; + } if (canApplyHealthPart) { @@ -8237,7 +8710,9 @@ void Aura::PeriodicTick() uint32 pdamage; if (m_modifier.m_auraname == SPELL_AURA_OBS_MOD_HEALTH) + { pdamage = uint32(target->GetMaxHealth() * amount / 100); + } else { pdamage = amount; @@ -8252,7 +8727,9 @@ void Aura::PeriodicTick() if (GetAuraTicks() != 1) // Item - Druid T10 Restoration 2P Bonus if (Aura* aura = pCaster->GetAura(70658, EFFECT_INDEX_0)) + { addition += abs(int32((addition * aura->GetModifier()->m_amount) / ((ticks - 1) * 100))); + } pdamage = int32(pdamage) + addition; } @@ -8283,7 +8760,9 @@ void Aura::PeriodicTick() // add HoTs to amount healed in bgs if (pCaster->GetTypeId() == TYPEID_PLAYER) if (BattleGround* bg = ((Player*)pCaster)->GetBattleGround()) + { bg->UpdatePlayerScore(((Player*)pCaster), SCORE_HEALING_DONE, gain); + } target->GetHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); @@ -8347,7 +8826,9 @@ void Aura::PeriodicTick() if( GetSpellProto()->GetSpellEffectIdByIndex(GetEffIndex()) == SPELL_EFFECT_PERSISTENT_AREA_AURA && pCaster->SpellHitResult(target, spellProto, false) != SPELL_MISS_NONE) - { return; } + { + return; + } // Check for immune (not use charges) if (target->IsImmunedToDamage(GetSpellSchoolMask(spellProto))) @@ -8366,7 +8847,9 @@ void Aura::PeriodicTick() uint32 maxmana = pCaster->GetMaxPower(power) * pdamage * 2 / 100; pdamage = target->GetMaxPower(power) * pdamage / 100; if (pdamage > maxmana) + { pdamage = maxmana; + } } DETAIL_FILTER_LOG(LOG_FILTER_PERIODIC_AFFECTS, "PeriodicTick: %s power leech of %s for %u dmg inflicted by %u", @@ -8376,7 +8859,9 @@ void Aura::PeriodicTick() // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (power == POWER_MANA) + { drain_amount -= target->GetCritDamageReduction(drain_amount); + } target->ModifyPower(power, -drain_amount); @@ -8402,7 +8887,9 @@ void Aura::PeriodicTick() if (GetId() == 5138) // Drain Mana if (Aura* petPart = GetHolder()->GetAuraByEffectIndex(EFFECT_INDEX_1)) if (int pet_gain = gain_amount * petPart->GetModifier()->m_amount / 100) + { pCaster->CastCustomSpell(pCaster, 32554, &pet_gain, NULL, NULL, true); + } target->AddThreat(pCaster, float(gain) * 0.5f, pInfo.critical, GetSpellSchoolMask(spellProto), spellProto); } @@ -8476,7 +8963,9 @@ void Aura::PeriodicTick() int32 gain = target->ModifyPower(power, pdamage); if (Unit* pCaster = GetCaster()) + { target->GetHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); + } break; } case SPELL_AURA_OBS_MOD_MANA: @@ -8506,7 +8995,9 @@ void Aura::PeriodicTick() int32 gain = target->ModifyPower(POWER_MANA, pdamage); if (Unit* pCaster = GetCaster()) + { target->GetHostileRefManager().threatAssist(pCaster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); + } break; } case SPELL_AURA_POWER_BURN_MANA: @@ -8540,7 +9031,9 @@ void Aura::PeriodicTick() // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (powerType == POWER_MANA) + { pdamage -= target->GetCritDamageReduction(pdamage); + } uint32 gain = uint32(-target->ModifyPower(powerType, -pdamage)); @@ -8580,7 +9073,9 @@ void Aura::PeriodicTick() int32 gain = target->ModifyHealth(m_modifier.m_amount); if (Unit* caster = GetCaster()) + { target->GetHostileRefManager().threatAssist(caster, float(gain) * 0.5f * sSpellMgr.GetSpellThreatMultiplier(spellProto), spellProto); + } break; } case SPELL_AURA_MOD_POWER_REGEN: @@ -8612,10 +9107,14 @@ void Aura::PeriodicTick() // amount = 1+ 16 = 17 = 3,4*5 = 10,2*5/3 // so 17 is rounded amount for 5 sec tick grow ~ 1 range grow in 3 sec if (powerType == POWER_RAGE) + { target->ModifyPower(powerType, m_modifier.m_amount * 3 / 5); + } // Butchery else if (powerType == POWER_RUNIC_POWER && target->IsInCombat()) + { target->ModifyPower(powerType, m_modifier.m_amount); + } break; } // Here tick dummy auras @@ -8675,7 +9174,9 @@ void Aura::PeriodicDummyTick() } case 7057: // Haunting Spirits if (roll_chance_i(33)) + { target->CastSpell(target, m_modifier.m_amount, true, NULL, this); + } return; // // Panda // case 19230: break; @@ -8860,9 +9361,13 @@ void Aura::PeriodicDummyTick() target->CastSpell(target, chance ? 48631 : 48632, true, NULL, this); if (GetAuraTicks() % 2) // which doctor at odd tick + { target->CastSpell(target, chance ? 48636 : 48635, true, NULL, this); + } else // or harponeer, at even tick + { target->CastSpell(target, chance ? 48634 : 48633, true, NULL, this); + } return; } @@ -8873,14 +9378,18 @@ void Aura::PeriodicDummyTick() case 59807: // Corpse Explode (heroic) { if (GetAuraTicks() == 3 && target->GetTypeId() == TYPEID_UNIT) + { ((Creature*)target)->ForcedDespawn(); + } if (GetAuraTicks() != 2) { return; } if (Unit* pCaster = GetCaster()) + { pCaster->CastSpell(target, spell->Id == 49555 ? 49618 : 59809, true); + } return; } @@ -8923,11 +9432,17 @@ void Aura::PeriodicDummyTick() // Cast different spell depending on trigger position // This will summon a different npc entry on each location - each of those has individual movement patern if (target->GetPositionZ() < 750.0f) + { target->CastSpell(target, summonSpells[spell->Id - 53035][0], true, NULL, this); + } else if (target->GetPositionX() > 500.0f) + { target->CastSpell(target, summonSpells[spell->Id - 53035][1], true, NULL, this); + } else + { target->CastSpell(target, summonSpells[spell->Id - 53035][2], true, NULL, this); + } return; } @@ -8946,7 +9461,9 @@ void Aura::PeriodicDummyTick() case 61968: // Flash Freeze { if (GetAuraTicks() == 1 && !target->HasAura(62464)) + { target->CastSpell(target, 61970, true, NULL, this); + } return; } case 62018: // Collapse @@ -8969,10 +9486,14 @@ void Aura::PeriodicDummyTick() // if player is moving remove one aura stack if (((Player*)target)->isMoving()) + { target->RemoveAuraHolderFromStack(62039); + } // otherwise add one aura stack each 3 seconds else if (GetAuraTicks() % 3 && !target->HasAura(62821)) + { target->CastSpell(target, 62039, true, NULL, this); + } return; } case 62039: // Biting Cold @@ -8994,23 +9515,33 @@ void Aura::PeriodicDummyTick() // cast Slag Imbued if the target survives up to the last tick if (GetAuraTicks() == 10) + { target->CastSpell(target, 63536, true, NULL, this); + } return; } case 63050: // Sanity { if (GetHolder()->GetStackAmount() <= 25 && !target->HasAura(63752)) + { target->CastSpell(target, 63752, true); + } else if (GetHolder()->GetStackAmount() > 25 && target->HasAura(63752)) + { target->RemoveAurasDueToSpell(63752); + } return; } case 63382: // Rapid Burst { if (GetAuraTicks() % 2) + { target->CastSpell(target, target->GetMap()->IsRegularDifficulty() ? 64019 : 64532, true); + } else + { target->CastSpell(target, target->GetMap()->IsRegularDifficulty() ? 63387 : 64531, true); + } return; } case 64101: // Defend @@ -9075,7 +9606,9 @@ void Aura::PeriodicDummyTick() int32 lifeLeeched = int32(target->GetHealth() * m_modifier.m_amount * 0.01f); if (lifeLeeched < 250) + { lifeLeeched = 250; + } // Leeching swarm damage caster->CastCustomSpell(target, 66240, &lifeLeeched, NULL, NULL, true, NULL, this); @@ -9103,9 +9636,13 @@ void Aura::PeriodicDummyTick() // Sweep around float newAngle = target->GetOrientation(); if (spell->Id == 68875) + { newAngle += 0.09f; + } else + { newAngle -= 0.09f; + } newAngle = NormalizeOrientation(newAngle); @@ -9152,7 +9689,9 @@ void Aura::PeriodicDummyTick() } } else + { target->RemoveAurasDueToSpell(58670); + } } break; } @@ -9167,7 +9706,9 @@ void Aura::PeriodicDummyTick() return; } if (Unit* pCaster = GetCaster()) + { pCaster->CastSpell(pCaster, GetSpellProto()->CalculateSimpleValue(m_effIndex), true, NULL, this); + } return; } default: @@ -9268,7 +9809,9 @@ void Aura::PeriodicDummyTick() { Unit* victim = target->getVictim(); if (victim && victim->GetHealth() * 100 < victim->GetMaxHealth() * 35) + { target->CastSpell(target, spell->Id == 53511 ? 60096 : 60097, true, NULL, this); + } return; } default: @@ -9283,7 +9826,9 @@ void Aura::PeriodicDummyTick() { // Periodic need for remove visual on stun/fear/silence lost if (!target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED)) + { target->RemoveAurasDueToSpell(52179); + } return; } break; @@ -9294,7 +9839,9 @@ void Aura::PeriodicDummyTick() if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000000020)) { if (Unit* caster = GetCaster()) + { caster->CastCustomSpell(target, 52212, &m_modifier.m_amount, NULL, NULL, true, NULL, this); + } return; } // Raise Dead @@ -9311,7 +9858,9 @@ void Aura::PeriodicDummyTick() Modifier* mod = slow->GetModifier(); mod->m_amount += m_modifier.m_amount; if (mod->m_amount > 0) mod->m_amount = 0; - slow->ApplyModifier(true, true); + { + slow->ApplyModifier(true, true); + } } return; } @@ -9353,7 +9902,9 @@ void Aura::PeriodicDummyTick() if (Unit* caster = GetCaster()) { if (target && target->GetTypeId() == TYPEID_UNIT) + { sScriptMgr.OnEffectDummy(caster, GetId(), GetEffIndex(), (Creature*)target, ObjectGuid()); + } } } @@ -9469,7 +10020,9 @@ void Aura::HandleAuraControlVehicle(bool apply, bool Real) target->GetVehicleInfo()->Board(caster, GetBasePoints() - 1); } else + { target->GetVehicleInfo()->UnBoard(caster, m_removeMode == AURA_REMOVE_BY_TRACKING); + } } void Aura::HandleAuraAddMechanicAbilities(bool apply, bool Real) @@ -9501,7 +10054,9 @@ void Aura::HandleAuraAddMechanicAbilities(bool apply, bool Real) // serverside just needs to register the new spells so that player isn't kicked as cheater for (int i = 0; i < MAX_OVERRIDE_SPELLS; ++i) if (uint32 spellId = spellSet->Spells[i]) + { static_cast(target)->addSpell(spellId, true, false, false, false); + } //target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, i_OverrideSetId); } @@ -9510,7 +10065,9 @@ void Aura::HandleAuraAddMechanicAbilities(bool apply, bool Real) //target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, 0); for (int i = 0; i < MAX_OVERRIDE_SPELLS; ++i) if (uint32 spellId = spellSet->Spells[i]) + { static_cast(target)->removeSpell(spellId, false , false, false); + } } } @@ -9524,7 +10081,9 @@ void Aura::HandleAuraOpenStable(bool apply, bool Real) Player* player = (Player*)GetTarget(); if (apply) + { player->GetSession()->SendStablePet(player->GetObjectGuid()); + } // client auto close stable dialog at !apply aura } @@ -9545,7 +10104,9 @@ void Aura::HandleAuraMirrorImage(bool apply, bool Real) Unit* caster = GetCaster(); if (caster->GetTypeId() == TYPEID_PLAYER) // TODO - Verify! Does it take a 'pseudo-race' (from display-id) for creature-mirroring, and what is sent in SMSG_MIRRORIMAGE_DATA + { pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 0, caster->getRace()); + } pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 1, caster->getClass()); pCreature->SetByteValue(UNIT_FIELD_BYTES_0, 2, caster->getGender()); @@ -9587,7 +10148,9 @@ void Aura::HandleMirrorName(bool apply, bool Real) } if (apply) + { target->SetName(caster->GetName()); + } else { CreatureInfo const* cinfo = ((Creature*)target)->GetCreatureInfo(); @@ -9660,10 +10223,14 @@ void Aura::HandlePhase(bool apply, bool Real) { Unit::AuraList const& phases = target->GetAurasByType(SPELL_AURA_PHASE); if (!phases.empty()) + { target->RemoveAurasDueToSpell(phases.front()->GetId(), GetHolder()); + } Unit::AuraList const& phases2 = target->GetAurasByType(SPELL_AURA_PHASE_2); if (!phases2.empty()) + { target->RemoveAurasDueToSpell(phases2.front()->GetId(), GetHolder()); + } } target->SetPhaseMask(apply ? GetMiscValue() : uint32(PHASEMASK_NORMAL), true); @@ -9690,7 +10257,9 @@ void Aura::HandleAuraSafeFall(bool Apply, bool Real) // only special case if (Apply && Real && GetId() == 32474 && GetTarget()->GetTypeId() == TYPEID_PLAYER) + { ((Player*)GetTarget())->ActivateTaxiPathTo(506, GetId()); + } } bool Aura::IsCritFromAbilityAura(Unit* caster, uint32& damage) @@ -9761,7 +10330,9 @@ void Aura::HandleAuraMastery(bool apply, bool Real) void Aura::HandleAuraModBlockCritChance(bool apply, bool Real) { if (GetTarget()->GetTypeId() == TYPEID_PLAYER) + { ((Player*)GetTarget())->ApplyModUInt32Value(PLAYER_SHIELD_BLOCK_CRIT_PERCENTAGE, m_modifier.m_amount, apply); + } } void Aura::HandlePreventResurrection(bool apply, bool Real) @@ -9778,9 +10349,13 @@ void Aura::HandlePreventResurrection(bool apply, bool Real) } if (apply) + { target->RemoveByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER); + } else if (!target->GetMap()->Instanceable()) + { target->SetByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER); + } } void Aura::HandleFactionOverride(bool apply, bool Real) @@ -9797,9 +10372,13 @@ void Aura::HandleFactionOverride(bool apply, bool Real) } if (apply) + { target->setFaction(GetMiscValue()); + } else + { target->RestoreOriginalFaction(); + } } @@ -9826,7 +10405,9 @@ void Aura::HandleTriggerLinkedAura(bool apply, bool Real) target->CastSpell(target, spellInfo, true, NULL, this); } else + { target->RemoveAurasByCasterSpell(linkedSpell, GetCasterGuid()); + } } bool Aura::IsLastAuraOnHolder() @@ -10014,15 +10595,23 @@ void SpellAuraHolder::_AddSpellAuraHolder() } if (GetCasterGuid() == GetTarget()->GetObjectGuid()) + { flags |= AFLAG_NOT_CASTER; + } if (!m_spellProto->HasAttribute(SPELL_ATTR_EX5_HIDE_DURATION) && GetSpellMaxDuration(m_spellProto) > 0) + { flags |= AFLAG_DURATION; + } if (IsPositive()) + { flags |= AFLAG_POSITIVE; + } else + { flags |= AFLAG_NEGATIVE; + } if (m_spellProto->HasAttribute(SPELL_ATTR_EX8_AURA_SENDS_AMOUNT) && flags & (AFLAG_EFF_INDEX_0 | AFLAG_EFF_INDEX_1 | AFLAG_EFF_INDEX_2)) @@ -10048,43 +10637,63 @@ void SpellAuraHolder::_AddSpellAuraHolder() // Sitdown on apply aura req seated if (m_spellProto->GetAuraInterruptFlags() & AURA_INTERRUPT_FLAG_NOT_SEATED && !m_target->IsSitState()) + { m_target->SetStandState(UNIT_STAND_STATE_SIT); + } // register aura diminishing on apply if (getDiminishGroup() != DIMINISHING_NONE) + { m_target->ApplyDiminishingAura(getDiminishGroup(), true); + } // Update Seals information if (IsSealSpell(m_spellProto)) + { m_target->ModifyAuraState(AURA_STATE_JUDGEMENT, true); + } // Conflagrate aura state on Immolate and Shadowflame if (m_spellProto->IsFitToFamily(SPELLFAMILY_WARLOCK, UI64LIT(0x0000000000000004), 0x00000002)) + { m_target->ModifyAuraState(AURA_STATE_CONFLAGRATE, true); + } // Faerie Fire (druid versions) if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000400))) + { m_target->ModifyAuraState(AURA_STATE_FAERIE_FIRE, true); + } // Victorious if (m_spellProto->IsFitToFamily(SPELLFAMILY_WARRIOR, UI64LIT(0x0004000000000000))) + { m_target->ModifyAuraState(AURA_STATE_WARRIOR_VICTORY_RUSH, true); + } // Swiftmend state on Regrowth & Rejuvenation if (m_spellProto->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000000000000050))) + { m_target->ModifyAuraState(AURA_STATE_SWIFTMEND, true); + } // Deadly poison aura state if (m_spellProto->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000000010000))) + { m_target->ModifyAuraState(AURA_STATE_DEADLY_POISON, true); + } // Enrage aura state if (m_spellProto->GetDispel() == DISPEL_ENRAGE) + { m_target->ModifyAuraState(AURA_STATE_ENRAGE, true); + } // Bleeding aura state if (GetAllSpellMechanicMask(m_spellProto) & (1 << (MECHANIC_BLEED - 1))) + { m_target->ModifyAuraState(AURA_STATE_BLEEDING, true); + } } } @@ -10101,13 +10710,17 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() if (caster && IsPersistent()) if (DynamicObject* dynObj = caster->GetDynObject(GetId())) + { dynObj->RemoveAffected(m_target); + } // remove at-store spell cast items (for all remove modes?) if (m_target->GetTypeId() == TYPEID_PLAYER && m_removeMode != AURA_REMOVE_BY_DEFAULT && m_removeMode != AURA_REMOVE_BY_DELETE) if (ObjectGuid castItemGuid = GetCastItemGuid()) if (Item* castItem = ((Player*)m_target)->GetItemByGuid(castItemGuid)) + { ((Player*)m_target)->DestroyItemWithOnStoreSpell(castItem, GetId()); + } // passive auras do not get put in slots - said who? ;) // Note: but totem can be not accessible for aura target in time remove (to far for find in grid) @@ -10148,7 +10761,9 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() //***************************************************** // Enrage aura state if(m_spellProto->GetDispel() == DISPEL_ENRAGE) + { m_target->ModifyAuraState(AURA_STATE_ENRAGE, false); + } // Bleeding aura state if (GetAllSpellMechanicMask(m_spellProto) & (1 << (MECHANIC_BLEED - 1))) @@ -10166,7 +10781,9 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() } if (!found) + { m_target->ModifyAuraState(AURA_STATE_BLEEDING, false); + } } uint32 removeState = 0; @@ -10176,7 +10793,9 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() { case SPELLFAMILY_PALADIN: if (IsSealSpell(m_spellProto)) - { removeState = AURA_STATE_JUDGEMENT; } // Update Seals information + { + removeState = AURA_STATE_JUDGEMENT; // Update Seals information + } break; case SPELLFAMILY_WARLOCK: // Conflagrate aura state on Immolate and Shadowflame, @@ -10188,7 +10807,9 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() break; case SPELLFAMILY_DRUID: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000400))) + { removeState = AURA_STATE_FAERIE_FIRE; // Faerie Fire (druid versions) + } else if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000000050))) { removeFamilyFlag = ClassFamilyMask(UI64LIT(0x00000000000050)); @@ -10197,15 +10818,21 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() break; case SPELLFAMILY_WARRIOR: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0004000000000000))) + { removeState = AURA_STATE_WARRIOR_VICTORY_RUSH; // Victorious + } break; case SPELLFAMILY_ROGUE: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x0000000000010000))) + { removeState = AURA_STATE_DEADLY_POISON; // Deadly poison aura state + } break; case SPELLFAMILY_HUNTER: if (m_spellProto->IsFitToFamilyMask(UI64LIT(0x1000000000000000))) + { removeState = AURA_STATE_FAERIE_FIRE; // Sting (hunter versions) + } } // Remove state (but need check other auras for it) @@ -10235,7 +10862,9 @@ void SpellAuraHolder::_RemoveSpellAuraHolder() { if (GetSpellProto()->HasAttribute(SPELL_ATTR_DISABLED_WHILE_ACTIVE)) // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases) - { ((Player*)caster)->SendCooldownEvent(GetSpellProto()); } + { + ((Player*)caster)->SendCooldownEvent(GetSpellProto()); + } } } } @@ -10246,7 +10875,9 @@ void SpellAuraHolder::CleanupTriggeredSpells() { SpellEffectEntry const* spellEffect = m_spellProto->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (!spellEffect->EffectApplyAuraName) { @@ -10274,7 +10905,9 @@ void SpellAuraHolder::CleanupTriggeredSpells() // TODO: is there a spell flag, which can solve this in a more sophisticated way? if (spellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_TRIGGER_SPELL && GetSpellDuration(m_spellProto) == int32(spellEffect->EffectAmplitude)) - { continue; } + { + continue; + } m_target->RemoveAurasDueToSpell(tSpellId); } @@ -10340,7 +10973,9 @@ void SpellAuraHolder::SetStackAmount(uint32 stackAmount) if (refresh) // Stack increased refresh duration - { RefreshHolder(); } + { + RefreshHolder(); + } else // Stack decreased only send update SendAuraUpdate(false); @@ -10397,7 +11032,9 @@ bool SpellAuraHolder::IsWeaponBuffCoexistableWith(SpellAuraHolder const* ref) co // Limit to Weapon-Slots if (!castItem->IsEquipped() || (castItem->GetSlot() != EQUIPMENT_SLOT_MAINHAND && castItem->GetSlot() != EQUIPMENT_SLOT_OFFHAND)) - { return false; } + { + return false; + } // form different weapons return ref->GetCastItemGuid() && ref->GetCastItemGuid() != GetCastItemGuid(); @@ -10493,7 +11130,9 @@ void SpellAuraHolder::SendAuraUpdate(bool remove) const data << uint32(0); } else + { BuildUpdatePacket(data); + } m_target->SendMessageToSet(&data, true); } @@ -10563,7 +11202,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) // Removal is needed here because the dummy aura handler is applied / removed at stacks change if (!apply) if (Unit* caster = GetCaster()) + { caster->RemoveAurasDueToSpell(34027); + } return; } case 62692: // Aura of Despair @@ -10605,7 +11246,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) cast_at_remove = true; // first rank have 50% chance if ((*itr)->GetId() != 44745 || roll_chance_i(50)) + { spellId1 = 55080; + } break; } } @@ -10622,7 +11265,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) case 11129: // Combustion (remove triggered aura stack) { if(!apply) + { spellId1 = 28682; + } else { return; @@ -10632,7 +11277,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) case 28682: // Combustion (remove main aura) { if(!apply) + { spellId1 = 11129; + } else { return; @@ -10665,7 +11312,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) case 74396: // Fingers of Frost (remove main aura) { if (!apply) + { spellId1 = 44544; + } else { return; @@ -10743,9 +11392,13 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) // Glyph of Shadowflame Unit* caster; if (!apply) + { spellId1 = 63311; + } else if (((caster = GetCaster())) && caster->HasAura(63310)) + { spellId1 = 63311; + } else { return; @@ -10807,7 +11460,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) } // Holy Walk if (caster == m_target && caster->HasAura(33333)) + { caster->CastSpell(caster, 96219, true); + } return; } @@ -10833,10 +11488,14 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) } if (roll_chance_i(chance)) + { spellId1 = 64134; // Body and Soul (periodic dispel effect) + } } else + { spellId1 = 64134; // Body and Soul (periodic dispel effect) + } break; } // Dispersion mana reg and immunity @@ -10853,9 +11512,13 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) { // Barkskin if (GetId() == 22812 && m_target->HasAura(63057)) // Glyph of Barkskin + { spellId1 = 63058; // Glyph - Barkskin 01 + } else if (!apply && GetId() == 5229) // Enrage (Druid Bear) + { spellId1 = 51185; // King of the Jungle (Enrage damage aura) + } else { return; @@ -10867,7 +11530,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000000040) && GetSpellProto()->GetCategory() == 44) { if (!apply || m_target->HasAura(58039)) // Glyph of Blurred Speed + { spellId1 = 61922; // Sprint (waterwalk) + } else { return; @@ -10885,7 +11550,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) case 34074: // Aspect of the Viper { if (!apply || m_target->HasAura(60144)) // Viper Attack Speed + { spellId1 = 61609; // Vicious Viper + } else { return; @@ -10906,9 +11573,13 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) if (apply) { if (m_target->HasAura(35029)) // Focused Fire, rank 1 + { spellId1 = 60110; // Kill Command, Focused Fire rank 1 bonus + } else if (m_target->HasAura(35030)) // Focused Fire, rank 2 + { spellId1 = 60113; // Kill Command, Focused Fire rank 2 bonus + } else { return; @@ -10920,7 +11591,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) spellId2 = 60110; // Kill Command, Focused Fire rank 1 bonus spellId3 = 60113; // Kill Command, Focused Fire rank 2 bonus if (Unit* pet = m_target->GetPet()) + { pet->RemoveAurasDueToSpell(58914); // Kill Command, pet aura + } } break; } @@ -10974,7 +11647,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) // triggered spell have same category as main spell and cooldown if (apply && m_target->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_target)->RemoveSpellCooldown(61848); + } } else { @@ -10989,7 +11664,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) if (m_spellProto->Id == 31884) // Avenging Wrath { if (!apply) + { spellId1 = 57318; // Sanctified Wrath (triggered) + } else { int32 percent = 0; @@ -11070,9 +11747,13 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) } if (heal_pct) + { m_target->CastCustomSpell(m_target, 63611, &heal_pct, NULL, NULL, true, NULL, NULL, GetCasterGuid()); + } else + { m_target->RemoveAurasDueToSpell(63611); + } } else spellId1 = 63611; // Improved Blood Presence, trigger for heal @@ -11099,7 +11780,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) spellId2 = 49772; // Unholy Presence, speed part, spell1 used for Improvement presence fit to own presence } else + { spellId1 = 49772; // Unholy Presence move speed + } if (GetId() == 48265 || GetId() == 48266) // Unholy Presence or Blood Presence { @@ -11121,12 +11804,18 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) } if (stamina_pct) + { m_target->CastCustomSpell(m_target, 61261, &stamina_pct, NULL, NULL, true, NULL, NULL, GetCasterGuid()); + } else + { m_target->RemoveAurasDueToSpell(61261); + } } else + { spellId1 = 61261; // Frost Presence, stamina + } if (GetId() == 48265) // Unholy Presence { @@ -11179,7 +11868,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) m_target->CastCustomSpell(m_target, 63611, &bp, NULL, NULL, true, NULL, NULL, GetCasterGuid()); } else + { m_target->RemoveAurasDueToSpell(63611); + } return; } @@ -11200,7 +11891,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) m_target->CastCustomSpell(m_target, 61261, &bp0, &bp1, NULL, true, NULL, NULL, GetCasterGuid()); } else + { m_target->RemoveAurasDueToSpell(61261); + } return; } @@ -11222,7 +11915,9 @@ void SpellAuraHolder::HandleSpellSpecificBoosts(bool apply) // if presence active: Frost Presence or Blood Presence if (!apply || m_target->HasAura(48263) || m_target->HasAura(48266)) + { spellId1 = 49772; + } else { return; @@ -11294,13 +11989,17 @@ void SpellAuraHolder::Update(uint32 diff) { for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) if (Aura* aura = m_auras[i]) + { aura->UpdateAura(diff); + } if (m_duration > 0) { m_duration -= diff; if (m_duration < 0) + { m_duration = 0; + } m_timeCla -= diff; @@ -11316,9 +12015,13 @@ void SpellAuraHolder::Update(uint32 diff) if (int32 manaPerSecond = spellPower->manaPerSecond) { if (powertype == POWER_HEALTH) + { caster->ModifyHealth(-manaPerSecond); + } else + { caster->ModifyPower(powertype, -manaPerSecond); + } } } } @@ -11340,7 +12043,9 @@ void SpellAuraHolder::Update(uint32 diff) float max_range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(m_spellProto->GetRangeIndex())); if (Player* modOwner = caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(GetId(), SPELLMOD_RANGE, max_range); + } if (!caster->IsWithinDistInMap(m_target, max_range)) { @@ -11374,7 +12079,9 @@ void SpellAuraHolder::SetAuraMaxDuration(int32 duration) SetAuraFlags(GetAuraFlags() | AFLAG_DURATION); } else + { SetAuraFlags(GetAuraFlags() & ~AFLAG_DURATION); + } } bool SpellAuraHolder::HasMechanic(uint32 mechanic) const @@ -11492,7 +12199,9 @@ void SpellAuraHolder::UnregisterAndCleanupTrackedAuras() ObjectGuid vehicleGuid = find->second; scTarget.erase(find); if (Unit* vehicle = caster->GetMap()->GetUnit(vehicleGuid)) + { vehicle->RemoveAurasDueToSpell(GetSpellProto()->Id, NULL, AURA_REMOVE_BY_DEFAULT); + } } } } diff --git a/src/game/WorldHandlers/SpellAuras.h b/src/game/WorldHandlers/SpellAuras.h index 46e0a020f..2b243c5d9 100644 --- a/src/game/WorldHandlers/SpellAuras.h +++ b/src/game/WorldHandlers/SpellAuras.h @@ -144,11 +144,15 @@ class SpellAuraHolder void SetInUse(bool state) { if (state) + { ++m_in_use; + } else { if (m_in_use) + { --m_in_use; + } } } @@ -181,7 +185,9 @@ class SpellAuraHolder m_procCharges = charges; if (update) + { SendAuraUpdate(false); + } } bool DropAuraCharge() // return true if last charge dropped { @@ -472,7 +478,9 @@ class Aura m_modifier.periodictime = periodicTime; if (uint32 maxticks = GetAuraMaxTicks()) + { m_periodicTick = maxticks - GetAuraDuration() / m_modifier.periodictime; + } } bool IsPositive() { return m_positive; } @@ -484,11 +492,15 @@ class Aura void SetInUse(bool state) { if (state) + { ++m_in_use; + } else { if (m_in_use) + { --m_in_use; + } } } void ApplyModifier(bool apply, bool Real = false); @@ -496,7 +508,9 @@ class Aura { m_modifier.m_amount = amount; if (update) + { GetHolder()->SendAuraUpdate(false); + } } void UpdateAura(uint32 diff) { SetInUse(true); Update(diff); SetInUse(false); } diff --git a/src/game/WorldHandlers/SpellEffects.cpp b/src/game/WorldHandlers/SpellEffects.cpp index e08cd12ec..f62af8cce 100644 --- a/src/game/WorldHandlers/SpellEffects.cpp +++ b/src/game/WorldHandlers/SpellEffects.cpp @@ -310,7 +310,9 @@ void Spell::EffectInstaKill(SpellEffectEntry const* /*effect*/) } if (m_caster == unitTarget) // prevent interrupt message + { finish(); + } WorldObject* caster = GetCastingObject(); // we need the original casting object @@ -337,7 +339,9 @@ void Spell::EffectEnvironmentalDMG(SpellEffectEntry const* effect) m_caster->SendSpellNonMeleeDamageLog(m_caster, m_spellInfo->Id, damage, GetSpellSchoolMask(m_spellInfo), absorb, resist, false, 0, false); if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->EnvironmentalDamage(DAMAGE_FIRE, damage); + } } void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) @@ -381,7 +385,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) uint32 count = 0; for(TargetList::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if(ihit->effectMask & (1<EffectIndex)) + { ++count; + } damage /= count; // divide to all targets break; @@ -391,7 +397,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) { damage = unitTarget->GetHealth() / 2; if (damage < 200) + { damage = 200; + } break; } // Intercept (warrior spell trigger) @@ -413,7 +421,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) // Lightning Strike case 37841: if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->HasAura(37830)) // Repolarized Magneto Sphere + { ((Player*)unitTarget)->KilledMonsterCredit(21910); + } break; // Cataclysmic Bolt // Cataclysmic Bolt @@ -426,7 +436,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) case 50341: { if (SpellEffectIndex(effect->EffectIndex) == EFFECT_INDEX_2) + { damage = int32(unitTarget->GetMaxHealth() * 0.3f); + } break; } // Tympanic Tantrum @@ -460,7 +472,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) // remove Arcane Blast buffs at any non-Arcane Blast arcane damage spell. // NOTE: it removed at hit instead cast because currently spell done-damage calculated at hit instead cast if ((m_spellInfo->GetSchoolMask() & SPELL_SCHOOL_MASK_ARCANE) && !(classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x20000000))) + { m_caster->RemoveAurasDueToSpell(36032); // Arcane Blast buff + } break; case SPELLFAMILY_WARRIOR: { @@ -477,19 +491,27 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) } // Revenge ${$m1+$AP*0.310} to ${$M1+$AP*0.310} else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000000400)) + { damage+= uint32(m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.310f); + } // Heroic Throw ${$m1+$AP*.50} else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000100000000)) + { damage+= uint32(m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.5f); + } // Shattering Throw ${$m1+$AP*.50} else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0040000000000000)) + { damage+= uint32(m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.5f); + } // Shockwave ${$m3/100*$AP} else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000800000000000)) { int32 pct = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, EFFECT_INDEX_2); if (pct > 0) + { damage += int32(m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * pct / 100); + } break; } // Thunder Clap @@ -514,7 +536,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) // Immolate SpellClassOptionsEntry const* immSpellClassOpt = (*i)->GetSpellProto()->GetSpellClassOptions(); if(!immSpellClassOpt) + { continue; + } if(immSpellClassOpt->SpellFamilyName == SPELLFAMILY_WARLOCK && (immSpellClassOpt->SpellFamilyFlags & UI64LIT(0x00000000000004))) { @@ -542,16 +566,22 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) { Unit* owner = m_caster->GetOwner(); if (!owner) + { break; + } uint32 counter = 0; Unit::AuraList const& dotAuras = unitTarget->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE); for (Unit::AuraList::const_iterator itr = dotAuras.begin(); itr != dotAuras.end(); ++itr) if ((*itr)->GetCasterGuid() == owner->GetObjectGuid()) + { ++counter; + } if (counter) + { damage += (counter * owner->CalculateSpellDamage(unitTarget, m_spellInfo, EFFECT_INDEX_2) * damage) / 100.0f; + } } // Conflagrate - consumes Immolate or Shadowflame else if (m_spellInfo->GetTargetAuraState() == AURA_STATE_CONFLAGRATE) @@ -575,7 +605,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) // Shadowflame if ((*i)->GetSpellProto()->IsFitToFamilyMask(UI64LIT(0x0000000000000000), 0x00000002)) + { aura = *i; // remember but wait possible Immolate as primary priority + } } // found Immolate or Shadowflame @@ -586,7 +618,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) // Glyph of Conflagrate if (!m_caster->HasAura(56235)) + { unitTarget->RemoveAurasByCasterSpell(aura->GetId(), m_caster->GetObjectGuid()); + } break; } } @@ -596,7 +630,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) { // Shadow Word: Death - deals damage equal to damage done to caster if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000200000000)) + { m_caster->CastCustomSpell(m_caster, 32409, &damage, 0, 0, true); + } // Improved Mind Blast (Mind Blast in shadow form bonus) else if (m_caster->GetShapeshiftForm() == FORM_SHADOW && (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x00002000))) { @@ -659,7 +695,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) { SpellClassOptionsEntry const* poisonClassOptions = (*itr)->GetSpellProto()->GetSpellClassOptions(); if(!poisonClassOptions) + { continue; + } if( poisonClassOptions->SpellFamilyName==SPELLFAMILY_ROGUE && (poisonClassOptions->SpellFamilyFlags & UI64LIT(0x10000)) && (*itr)->GetCasterGuid() == m_caster->GetObjectGuid()) @@ -675,7 +713,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) uint32 spellId = poison->GetId(); uint32 doses = poison->GetStackAmount(); if (doses > combo) + { doses = combo; + } // Master Poisoner Unit::AuraList const& auraList = ((Player*)m_caster)->GetAurasByType(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL); @@ -685,21 +725,27 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) { if (int32 chance = (*iter)->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_2)) if (roll_chance_i(chance)) + { needConsume = false; + } break; } } if (needConsume) + { unitTarget->RemoveAuraHolderFromStack(spellId, doses, m_caster->GetObjectGuid()); + } damage *= doses; damage += int32(((Player*)m_caster)->GetTotalAttackPowerValue(BASE_ATTACK) * 0.09f * doses); } // Eviscerate and Envenom Bonus Damage (item set effect) if (m_caster->GetDummyAura(37169)) + { damage += ((Player*)m_caster)->GetComboPoints() * 40; + } } } // Eviscerate @@ -712,7 +758,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) // Eviscerate and Envenom Bonus Damage (item set effect) if (m_caster->GetDummyAura(37169)) + { damage += combo * 40; + } } } break; @@ -723,7 +771,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) if (m_spellInfo->GetSpellIconID() == 1578) { if (m_caster->HasAura(57627)) // Charge 6 sec post-affect + { damage *= 2; + } } // Steady Shot else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x100000000)) @@ -741,7 +791,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = m_caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(m_spellInfo)); if (holy < 0) + { holy = 0; + } damage += int32(ap * 0.2f) + int32(holy * 32 / 100); } // Judgement of Vengeance/Corruption ${1+0.22*$SPH+0.14*$AP} + 10% for each application of Holy Vengeance/Blood Corruption on the target @@ -758,7 +810,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = m_caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(m_spellInfo)); if (holy < 0) + { holy = 0; + } damage += int32(ap * 0.14f) + int32(holy * 22 / 100); // Get stack of Holy Vengeance on the target added by caster uint32 stacks = 0; @@ -773,7 +827,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) } // + 10% for each application of Holy Vengeance on the target if (stacks) + { damage += damage * stacks * 10 / 100; + } } // Avenger's Shield ($m1+0.07*$SPH+0.07*$AP) - ranged sdb for future else if (classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000004000)) @@ -781,7 +837,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = m_caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(m_spellInfo)); if (holy < 0) + { holy = 0; + } damage += int32(ap * 0.07f) + int32(holy * 7 / 100); } // Hammer of Wrath ($m1+0.15*$SPH+0.15*$AP) - ranged type sdb future fix @@ -790,7 +848,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = m_caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(m_spellInfo)); if (holy < 0) + { holy = 0; + } damage += int32(ap * 0.15f) + int32(holy * 15 / 100); } // Hammer of the Righteous @@ -812,7 +872,9 @@ void Spell::EffectSchoolDMG(SpellEffectEntry const* effect) } if (damage >= 0) + { m_damage += damage; + } } } @@ -928,11 +990,17 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) uint32 roll = urand(0, 99); if (roll < 2) // 2% for 30 sec self root (off-like chance unknown) + { spell_id = 16566; + } else if (roll < 4) // 2% for 20 sec root, charge to target (off-like chance unknown) + { spell_id = 13119; + } else // normal root + { spell_id = 13099; + } m_caster->CastSpell(unitTarget, spell_id, true, NULL); return; @@ -977,20 +1045,30 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) uint32 spell_id = 0; uint32 roll = urand(0, 99); if (roll < 25) // Fireball (25% chance) + { spell_id = 15662; + } else if (roll < 50) // Frostbolt (25% chance) + { spell_id = 11538; + } else if (roll < 70) // Chain Lighting (20% chance) + { spell_id = 21179; + } else if (roll < 77) // Polymorph (10% chance, 7% to target) + { spell_id = 14621; + } else if (roll < 80) // Polymorph (10% chance, 3% to self, backfire) { spell_id = 14621; newTarget = m_caster; } else if (roll < 95) // Enveloping Winds (15% chance) + { spell_id = 25189; + } else // Summon Felhund minion (5% chance) { spell_id = 14642; @@ -1177,7 +1255,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) case 20577: // Cannibalize { if (unitTarget) + { m_caster->CastSpell(m_caster, 20578, false, NULL); + } return; } @@ -1191,7 +1271,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // Spell used by Azuregos to teleport all the players to him // This also resets the target threat if (m_caster->GetThreatManager().getThreat(unitTarget)) + { m_caster->GetThreatManager().modifyThreatPercent(unitTarget, -100); + } // cast summon player m_caster->CastSpell(unitTarget, 21150, true); @@ -1294,20 +1376,30 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) { int32 r = irand(0, 119); if (r < 20) // Transporter Malfunction - 1/6 polymorph + { m_caster->CastSpell(m_caster, 23444, true); + } else if (r < 100) // Evil Twin - 4/6 evil twin + { m_caster->CastSpell(m_caster, 23445, true); + } else // Transporter Malfunction - 1/6 miss the target + { m_caster->CastSpell(m_caster, 36902, true); + } return; } case 23453: // Gnomish Transporter - Ultrasafe Transporter: Gadgetzan { if (roll_chance_i(50)) // Gadgetzan Transporter - success + { m_caster->CastSpell(m_caster, 23441, true); + } else // Gadgetzan Transporter Failure - failure + { m_caster->CastSpell(m_caster, 23446, true); + } return; } @@ -1417,7 +1509,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) case 29858: // Soulshatter { if (unitTarget && unitTarget->GetTypeId() == TYPEID_UNIT && unitTarget->IsHostileTo(m_caster)) + { m_caster->CastSpell(unitTarget, 32835, true); + } return; } @@ -1459,9 +1553,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (roll_chance_i(86)) // Nigh-Invulnerability - success + { m_caster->CastSpell(m_caster, 30456, true, m_CastItem); + } else // Complete Vulnerability - backfire in 14% casts + { m_caster->CastSpell(m_caster, 30457, true, m_CastItem); + } return; } @@ -1473,9 +1571,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (roll_chance_i(80)) // Poultryized! - success + { m_caster->CastSpell(unitTarget, 30501, true, m_CastItem); + } else // Poultryized! - backfire 20% + { m_caster->CastSpell(unitTarget, 30504, true, m_CastItem); + } return; } @@ -1731,9 +1833,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (roll_chance_i(66)) + { m_caster->CastSpell(m_caster, 42289, true, m_CastItem); + } else + { m_caster->CastSpell(m_caster, 42288, true); + } return; } @@ -1894,15 +2000,21 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) { // Skip Non-Players if (!itr->targetGUID.IsPlayer()) + { continue; + } if (Unit* target = m_caster->GetMap()->GetPlayer(itr->targetGUID)) + { possibleTargets.push_back(target); + } } // Cast Siphon Soul channeling spell if (!possibleTargets.empty()) + { m_caster->CastSpell(possibleTargets[urand(0, possibleTargets.size() - 1)], 43501, false); + } return; } @@ -2109,7 +2221,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (unitTarget->GetTypeId() == TYPEID_UNIT) + { ((Creature*)unitTarget)->ForcedDespawn(); + } } return; @@ -2180,7 +2294,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) Creature* creatureTarget = (Creature*)unitTarget; if (const SpellCastTimesEntry* pCastTime = sSpellCastTimesStore.LookupEntry(pSpell->GetCastingTimeIndex())) + { creatureTarget->ForcedDespawn(pCastTime->CastTime + 1); + } } return; } @@ -2259,7 +2375,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) if (SpellEffectEntry const* pSpellEffect = pSpell->GetSpellEffect(EFFECT_INDEX_0)) if (const SpellEntry *pSpellCredit = sSpellStore.LookupEntry(pSpellEffect->EffectTriggerSpell)) if(SpellEffectEntry const* pSpellCreditEffect = pSpellCredit->GetSpellEffect(EFFECT_INDEX_0)) + { ((Player*)m_caster)->KilledMonsterCredit(pSpellCreditEffect->EffectMiscValue); + } ((Creature*)unitTarget)->ForcedDespawn(); } @@ -2320,7 +2438,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // The additional castspell arguments are needed here to remove reagents for triggered spells if (spellId) + { m_caster->CastSpell(m_caster, spellId, true, m_CastItem, NULL, m_caster->GetObjectGuid(), m_spellInfo); + } return; } @@ -2613,9 +2733,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // guessed chances if (roll_chance_i(75)) + { m_caster->CastSpell(unitTarget, roll_chance_i(50) ? 51332 : 51366, true, m_CastItem); + } else + { m_caster->CastSpell(unitTarget, 51331, true, m_CastItem); + } return; } @@ -2627,9 +2751,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (roll_chance_i(75)) + { m_caster->CastSpell(unitTarget, 51370, true, m_CastItem); + } else + { m_caster->CastSpell(m_caster, 51345, true); + } return; } @@ -2673,7 +2801,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (BattleGround* bg = ((Player*)m_caster)->GetBattleGround()) + { bg->EventPlayerDroppedFlag((Player*)m_caster); + } m_caster->CastSpell(m_caster, 30452, true, NULL); return; @@ -2739,7 +2869,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) if (pTargetDummy) { if (unitTarget->hasUnitState(UNIT_STAT_FOLLOW | UNIT_STAT_FOLLOW_MOVE)) + { unitTarget->GetMotionMaster()->MovementExpired(); + } unitTarget->MonsterMoveWithSpeed(pTargetDummy->GetPositionX(), pTargetDummy->GetPositionY(), pTargetDummy->GetPositionZ(), 24.f); @@ -2779,7 +2911,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // This might not be the best way, and effect may need some adjustment. Removal of any aura from surrounding dummy creatures? if (((Creature*)unitTarget)->AI()) + { ((Creature*)unitTarget)->AI()->AttackStart(m_caster); + } return; } @@ -2791,7 +2925,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (Player* pPlayer = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) + { pPlayer->KilledMonsterCredit(unitTarget->GetEntry(), unitTarget->GetObjectGuid()); + } return; } @@ -2805,7 +2941,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) uint32 reqAuraID = m_spellInfo->CalculateSimpleValue(EFFECT_INDEX_1); if (m_caster->HasAura(reqAuraID, EFFECT_INDEX_0)) + { m_caster->CastSpell(m_caster, spellID, true, NULL); + } return; } case EFFECT_INDEX_1: // additional data for dummy[0] @@ -2924,7 +3062,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // Set rep to baserep + basepoints (expecting spillover for oposite faction -> become hated) // Not when player already has equal or higher rep with this faction if (pPlayer->GetReputationMgr().GetBaseReputation(factionEntry) < rep_change) + { pPlayer->GetReputationMgr().SetReputation(factionEntry, rep_change); + } // EFFECT_INDEX_2 most likely update at war state, we already handle this in SetReputation } @@ -3000,9 +3140,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (roll_chance_i(95)) // Nitro Boosts - success + { m_caster->CastSpell(m_caster, 54861, true, m_CastItem); + } else // Knocked Up - backfire 5% + { m_caster->CastSpell(m_caster, 46014, true, m_CastItem); + } return; } @@ -3200,7 +3344,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (m_caster->GetThreatManager().getThreat(unitTarget)) + { m_caster->GetThreatManager().modifyThreatPercent(unitTarget, -100); + } return; } case 64172: // Titanic Storm @@ -3327,9 +3473,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) if (unitTarget->GetTypeId() == TYPEID_PLAYER) { if (unitTarget->HasAuraOfDifficulty(65686)) + { unitTarget->CastSpell(unitTarget, 67590, true); + } else + { m_caster->CastSpell(m_caster, 65795, true); + } ((Creature*)m_caster)->ForcedDespawn(); } @@ -3345,9 +3495,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) if (unitTarget->GetTypeId() == TYPEID_PLAYER) { if (unitTarget->HasAuraOfDifficulty(65684)) + { unitTarget->CastSpell(unitTarget, 67590, true); + } else + { m_caster->CastSpell(m_caster, 65808, true); + } ((Creature*)m_caster)->ForcedDespawn(); } @@ -3553,16 +3707,22 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) ((Player*)m_caster)->RemoveSpellCooldown((itr++)->first, true); } else + { ++itr; + } } return; } case 31687: // Summon Water Elemental { if (m_caster->HasAura(70937)) // Glyph of Eternal Water (permanent limited by known spells version) + { m_caster->CastSpell(m_caster, 70908, true); + } else // temporary version + { m_caster->CastSpell(m_caster, 70907, true); + } return; } @@ -3588,7 +3748,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) { // Blink if (unitTarget) + { m_caster->CastSpell(unitTarget, 38203, true); + } return; } @@ -3636,13 +3798,17 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // up to max 30 rage cost if (rage > 300) + { rage = 300; + } // Glyph of Execution bonus uint32 rage_modified = rage; if (Aura* aura = m_caster->GetDummyAura(58367)) + { rage_modified += aura->GetModifier()->m_amount * 10; + } int32 basePoints0 = damage+int32(rage_modified * effect->DmgMultiplier + m_caster->GetTotalAttackPowerValue(BASE_ATTACK)*0.2f); @@ -3661,7 +3827,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // saved rage top stored in next affect uint32 lastrage = (*itr)->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_1) * 10; if (lastrage < rage) + { rage -= lastrage; + } break; } } @@ -3770,7 +3938,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) Unit::AuraList const& auraDummy = m_caster->GetAurasByType(SPELL_AURA_DUMMY); for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr != auraDummy.end(); ++itr) if((*itr)->GetSpellProto()->GetSpellFamilyName()==SPELLFAMILY_WARLOCK && (*itr)->GetSpellProto()->GetSpellIconID() == 208) + { mana = ((*itr)->GetModifier()->m_amount + 100)* mana / 100; + } m_caster->CastCustomSpell(unitTarget, 31818, &mana, NULL, NULL, true); @@ -3780,7 +3950,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) for (Unit::AuraList::const_iterator itr = mod.begin(); itr != mod.end(); ++itr) { if((*itr)->GetSpellProto()->GetSpellFamilyName()==SPELLFAMILY_WARLOCK && (*itr)->GetSpellProto()->GetSpellIconID() == 1982) + { manaFeedVal+= (*itr)->GetModifier()->m_amount; + } } if (manaFeedVal > 0) { @@ -3789,7 +3961,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } } else + { SendCastResult(SPELL_FAILED_FIZZLE); + } return; } @@ -3824,9 +3998,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // replace cast by selected spell, this also make it interruptible including target death case if (m_caster->IsFriendlyTo(unitTarget)) + { m_caster->CastSpell(unitTarget, heal, false); + } else + { m_caster->CastSpell(unitTarget, hurt, false); + } return; } @@ -3841,7 +4019,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) if (m_caster->GetCreatureType() == CREATURE_TYPE_BEAST || m_caster->IsMounted()) { if (m_triggeredByAuraSpell) + { m_caster->RemoveAurasDueToSpell(m_triggeredByAuraSpell->Id); + } return; } @@ -3899,11 +4079,15 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) for (int s = 0; s < 3; ++s) { if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL) + { continue; + } SpellEntry const* combatEntry = sSpellStore.LookupEntry(pEnchant->spellid[s]); if (!combatEntry || combatEntry->GetDispel() != DISPEL_POISON) + { continue; + } m_caster->CastSpell(unitTarget, combatEntry, true, item); } @@ -3925,9 +4109,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first); SpellClassOptionsEntry const* prepClassOptions = spellInfo->GetSpellClassOptions(); if (prepClassOptions && prepClassOptions->SpellFamilyName == SPELLFAMILY_ROGUE && (prepClassOptions->SpellFamilyFlags & UI64LIT(0x0000024000000860))) + { ((Player*)m_caster)->RemoveSpellCooldown((itr++)->first,true); + } else + { ++itr; + } } return; } @@ -3970,7 +4158,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (found) + { m_damage += damage; + } return; } @@ -4010,9 +4200,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) SpellEntry const* spellInfo = sSpellStore.LookupEntry(itr->first); if (spellInfo->GetSpellFamilyName() == SPELLFAMILY_HUNTER && spellInfo->Id != 23989 && GetSpellRecoveryTime(spellInfo) > 0 ) + { ((Player*)m_caster)->RemoveSpellCooldown((itr++)->first,true); + } else + { ++itr; + } } return; } @@ -4084,9 +4278,13 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) } if (m_caster->IsFriendlyTo(unitTarget)) + { m_caster->CastSpell(unitTarget, heal, true); + } else + { m_caster->CastSpell(unitTarget, hurt, true); + } return; } @@ -4125,7 +4323,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) { Player* player = friendTarget->GetCharmerOrOwnerPlayerOrPlayerItself(); if (!player || !player->IsInSameRaidWith((Player*)m_caster)) + { friendTarget = NULL; + } } // non-standard cast requirement check @@ -4188,7 +4388,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) if (shamClassOptions && (shamClassOptions->SpellFamilyFlags & UI64LIT(0x0000000004000000)) && m_spellInfo->GetSpellIconID()==1673) { if (unitTarget) + { m_caster->CastSpell(unitTarget, 52025, true); + } return; } // Healing Stream Totem @@ -4210,11 +4412,15 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) // only its have dummy with specific icon if ((*i)->GetSpellProto()->GetSpellFamilyName() == SPELLFAMILY_SHAMAN && (*i)->GetSpellProto()->GetSpellIconID() == 338) + { damage += (*i)->GetModifier()->m_amount * damage / 100; + } // Glyph of Healing Stream Totem if (Aura* dummy = owner->GetDummyAura(55456)) + { damage += dummy->GetModifier()->m_amount * damage / 100; + } } m_caster->CastCustomSpell(unitTarget, 52042, &damage, NULL, NULL, true, 0, 0, m_originalCasterGUID); } @@ -4257,7 +4463,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // Glyph of Mana Tide if (Unit* owner = m_caster->GetOwner()) if (Aura* dummy = owner->GetDummyAura(55441)) + { damage += dummy->GetModifier()->m_amount; + } // Regenerate 6% of Total Mana Every 3 secs int32 EffectBasePoints0 = unitTarget->GetMaxPower(POWER_MANA) * damage / 100; m_caster->CastCustomSpell(unitTarget, 39609, &EffectBasePoints0, NULL, NULL, true, NULL, NULL, m_originalCasterGUID); @@ -4362,7 +4570,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) ++count; // max. 15% if (count == 3) + { break; + } } } @@ -4423,7 +4633,9 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) return; } else + { break; + } } } @@ -4445,11 +4657,17 @@ void Spell::EffectDummy(SpellEffectEntry const* effect) // So called only for not processed cases bool libraryResult = false; if (gameObjTarget) + { libraryResult = sScriptMgr.OnEffectDummy(m_caster, m_spellInfo->Id, SpellEffectIndex(effect->EffectIndex), gameObjTarget, m_originalCasterGUID); + } else if (unitTarget && unitTarget->GetTypeId() == TYPEID_UNIT) + { libraryResult = sScriptMgr.OnEffectDummy(m_caster, m_spellInfo->Id, SpellEffectIndex(effect->EffectIndex), (Creature*)unitTarget, m_originalCasterGUID); + } else if (itemTarget) + { libraryResult = sScriptMgr.OnEffectDummy(m_caster, m_spellInfo->Id, SpellEffectIndex(effect->EffectIndex), itemTarget, m_originalCasterGUID); + } if (libraryResult || !unitTarget) { @@ -4550,7 +4768,9 @@ void Spell::EffectTriggerSpell(SpellEffectEntry const* effect) if (!unitTarget) { if (gameObjTarget || itemTarget) + { sLog.outError("Spell::EffectTriggerSpell (Spell: %u): Unsupported non-unit case!", m_spellInfo->Id); + } return; } @@ -4574,7 +4794,9 @@ void Spell::EffectTriggerSpell(SpellEffectEntry const* effect) uint32 spellId = 1784; // reset cooldown on it if needed if (((Player*)unitTarget)->HasSpellCooldown(spellId)) + { ((Player*)unitTarget)->RemoveSpellCooldown(spellId); + } m_caster->CastSpell(unitTarget, spellId, true); return; @@ -4610,14 +4832,18 @@ void Spell::EffectTriggerSpell(SpellEffectEntry const* effect) case 41967: // Priest Shadowfiend (34433) need apply mana gain trigger aura on pet { if (Unit* pet = unitTarget->GetPet()) + { pet->CastSpell(pet, 28305, true); + } return; } case 58832: // Mirror Image { // Glyph of Mirror Image if (m_caster->HasAura(63093)) + { m_caster->CastSpell(m_caster, 65047, true, m_CastItem, NULL, m_originalCasterGUID); + } break; } } @@ -4738,16 +4964,24 @@ void Spell::EffectJump(SpellEffectEntry const* effect) // some spell at client send caster Unit* pTarget = NULL; if (m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster) + { pTarget = m_targets.getUnitTarget(); + } else if (unitTarget->getVictim()) + { pTarget = m_caster->getVictim(); + } else if (m_caster->GetTypeId() == TYPEID_PLAYER) + { pTarget = m_caster->GetMap()->GetUnit(((Player*)m_caster)->GetSelectionGuid()); + } o = pTarget ? pTarget->GetOrientation() : m_caster->GetOrientation(); } else + { o = m_caster->GetOrientation(); + } } else if (unitTarget) { @@ -4808,7 +5042,9 @@ void Spell::EffectTeleportUnits(SpellEffectEntry const* effect) // TODO - Use // Target dependend on TargetB, if there is none provided, decide dependend on A uint32 targetType = effect->EffectImplicitTargetB; if (!targetType) + { targetType = effect->EffectImplicitTargetA; + } switch (targetType) { @@ -4834,9 +5070,13 @@ void Spell::EffectTeleportUnits(SpellEffectEntry const* effect) // TODO - Use } if (st->target_mapId == unitTarget->GetMapId()) + { unitTarget->NearTeleportTo(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, unitTarget == m_caster); + } else if (unitTarget->GetTypeId() == TYPEID_PLAYER) + { ((Player*)unitTarget)->TeleportTo(st->target_mapId, st->target_X, st->target_Y, st->target_Z, st->target_Orientation, unitTarget == m_caster ? TELE_TO_SPELL : 0); + } break; } case TARGET_EFFECT_SELECT: @@ -4858,11 +5098,17 @@ void Spell::EffectTeleportUnits(SpellEffectEntry const* effect) // TODO - Use // explicit cast data from client or server-side cast // some spell at client send caster if (m_targets.getUnitTarget() && m_targets.getUnitTarget() != unitTarget) + { pTarget = m_targets.getUnitTarget(); + } else if (unitTarget->getVictim()) + { pTarget = unitTarget->getVictim(); + } else if (unitTarget->GetTypeId() == TYPEID_PLAYER) + { pTarget = unitTarget->GetMap()->GetUnit(((Player*)unitTarget)->GetSelectionGuid()); + } // Init dest coordinates float x = m_targets.m_destX; @@ -4901,9 +5147,13 @@ void Spell::EffectTeleportUnits(SpellEffectEntry const* effect) // TODO - Use if (r >= 70) // 7/12 success { if (r < 100) // 4/12 evil twin + { m_caster->CastSpell(m_caster, 23445, true); + } else // 1/12 fire + { m_caster->CastSpell(m_caster, 23449, true); + } } return; } @@ -4935,9 +5185,13 @@ void Spell::EffectTeleportUnits(SpellEffectEntry const* effect) // TODO - Use // Transform { if (((Player*)m_caster)->GetTeam() == ALLIANCE) + { m_caster->CastSpell(m_caster, 36897, true); + } else + { m_caster->CastSpell(m_caster, 36899, true); + } break; } case 6: @@ -4976,9 +5230,13 @@ void Spell::EffectTeleportUnits(SpellEffectEntry const* effect) // TODO - Use // Transform { if (((Player*)m_caster)->GetTeam() == ALLIANCE) + { m_caster->CastSpell(m_caster, 36897, true); + } else + { m_caster->CastSpell(m_caster, 36899, true); + } break; } } @@ -5006,7 +5264,9 @@ void Spell::EffectApplyAura(SpellEffectEntry const* effect) // FIXME: currently we can't have auras applied explicitly by gameobjects // so for auras from wild gameobjects (no owner) target used if (m_originalCasterGUID.IsGameObject()) + { caster = unitTarget; + } else { return; @@ -5072,13 +5332,19 @@ void Spell::EffectPowerDrain(SpellEffectEntry const* effect) // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) uint32 power = damage; if (drain_power == POWER_MANA) + { power -= unitTarget->GetCritDamageReduction(power); + } int32 new_damage; if (curPower < power) + { new_damage = curPower; + } else + { new_damage = power; + } unitTarget->ModifyPower(drain_power, -new_damage); @@ -5087,10 +5353,14 @@ void Spell::EffectPowerDrain(SpellEffectEntry const* effect) { float manaMultiplier = effect->EffectMultipleValue; if(manaMultiplier==0) + { manaMultiplier = 1; + } if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_MULTIPLE_VALUE, manaMultiplier); + } int32 gain = int32(new_damage * manaMultiplier); @@ -5140,7 +5410,9 @@ void Spell::EffectPowerBurn(SpellEffectEntry const* effect) int32 maxdamage = m_caster->GetMaxPower(powertype) * damage * 2 / 100; damage = unitTarget->GetMaxPower(powertype) * damage / 100; if (damage > maxdamage) + { damage = maxdamage; + } } int32 curPower = int32(unitTarget->GetPower(powertype)); @@ -5148,7 +5420,9 @@ void Spell::EffectPowerBurn(SpellEffectEntry const* effect) // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) int32 power = damage; if (powertype == POWER_MANA) + { power -= unitTarget->GetCritDamageReduction(power); + } int32 new_damage = (curPower < power) ? curPower : power; @@ -5156,7 +5430,9 @@ void Spell::EffectPowerBurn(SpellEffectEntry const* effect) float multiplier = effect->EffectMultipleValue; if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_MULTIPLE_VALUE, multiplier); + } new_damage = int32(new_damage * multiplier); m_damage += new_damage; @@ -5181,7 +5457,9 @@ void Spell::EffectHeal(SpellEffectEntry const* /*effect*/) float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = caster->SpellBaseHealingBonusDone(GetSpellSchoolMask(m_spellInfo)); if (holy < 0) + { holy = 0; + } addhealth += int32(ap * 0.15) + int32(holy * 15 / 100); } // Vessel of the Naaru (Vial of the Sunwell trinket) @@ -5192,15 +5470,21 @@ void Spell::EffectHeal(SpellEffectEntry const* /*effect*/) Unit::AuraList const& mDummyAuras = m_caster->GetAurasByType(SPELL_AURA_DUMMY); for (Unit::AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) if ((*i)->GetId() == 45062) + { damageAmount += (*i)->GetModifier()->m_amount; + } if (damageAmount) + { m_caster->RemoveAurasDueToSpell(45062); + } addhealth += damageAmount; } // Death Pact (percent heal) else if (m_spellInfo->Id == 48743) + { addhealth = addhealth * unitTarget->GetMaxHealth() / 100; + } // Swiftmend - consumes Regrowth or Rejuvenation else if (m_spellInfo->GetTargetAuraState() == AURA_STATE_SWIFTMEND && unitTarget->HasAuraState(AURA_STATE_SWIFTMEND)) { @@ -5215,7 +5499,9 @@ void Spell::EffectHeal(SpellEffectEntry const* /*effect*/) (smClassOptions->SpellFamilyFlags & UI64LIT(0x0000000000000050))) { if (!targetAura || (*i)->GetAuraDuration() < targetAura->GetAuraDuration()) + { targetAura = *i; + } } } @@ -5230,7 +5516,9 @@ void Spell::EffectHeal(SpellEffectEntry const* /*effect*/) { targetSpellEffect = targetAura->GetSpellProto()->GetSpellEffect(SpellEffectIndex(idx)); if(targetSpellEffect && targetSpellEffect->EffectApplyAuraName == SPELL_AURA_PERIODIC_HEAL) + { break; + } ++idx; } @@ -5239,7 +5527,9 @@ void Spell::EffectHeal(SpellEffectEntry const* /*effect*/) // Glyph of Swiftmend if (!caster->HasAura(54824)) + { unitTarget->RemoveAurasDueToSpell(targetAura->GetId()); + } addhealth += tickheal * tickcount; } @@ -5248,7 +5538,9 @@ void Spell::EffectHeal(SpellEffectEntry const* /*effect*/) { Player* player = (Player*)unitTarget; if (player->HasSkill(SKILL_ENGINEERING)) + { addhealth += int32(addhealth * 0.25); + } } // Chain Healing @@ -5341,12 +5633,16 @@ void Spell::EffectHealthLeech(SpellEffectEntry const* effect) uint32 curHealth = unitTarget->GetHealth(); damage = m_caster->SpellNonMeleeDamageLog(unitTarget, m_spellInfo->Id, damage); if ((int32)curHealth < damage) + { damage = curHealth; + } float multiplier = effect->EffectMultipleValue; if (Player* modOwner = m_caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_MULTIPLE_VALUE, multiplier); + } int32 heal = int32(damage * multiplier); if (m_caster->IsAlive()) @@ -5392,9 +5688,13 @@ void Spell::DoCreateItem(SpellEffectEntry const* effect, uint32 itemtype) uint32 num_to_add = damage; if (num_to_add < 1) + { num_to_add = 1; + } if (num_to_add > pProto->GetMaxStackSize()) + { num_to_add = pProto->GetMaxStackSize(); + } // init items_count to 1, since 1 item will be created regardless of specialization int items_count = 1; @@ -5421,7 +5721,9 @@ void Spell::DoCreateItem(SpellEffectEntry const* effect, uint32 itemtype) { // convert to possible store amount if (msg == EQUIP_ERR_INVENTORY_FULL || msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS) + { num_to_add -= no_space; + } else { // ignore mana gem case (next effect will recharge existing example) @@ -5450,14 +5752,18 @@ void Spell::DoCreateItem(SpellEffectEntry const* effect, uint32 itemtype) // set the "Crafted by ..." property of the item if (pItem->GetProto()->Class != ITEM_CLASS_CONSUMABLE && pItem->GetProto()->Class != ITEM_CLASS_QUEST) + { pItem->SetGuidValue(ITEM_FIELD_CREATOR, player->GetObjectGuid()); + } // send info to the client player->SendNewItem(pItem, num_to_add, true, !bg_mark); // we succeeded in creating at least one item, so a levelup is possible if (!bg_mark) + { player->UpdateCraftSkill(m_spellInfo->Id); + } } } @@ -5478,7 +5784,9 @@ void Spell::EffectCreateItem2(SpellEffectEntry const* effect) uint32 item_id = effect->EffectItemType; if (item_id) + { DoCreateItem(effect, item_id); + } // not explicit loot (with fake item drop if need) if (IsLootCraftingSpell(m_spellInfo)) @@ -5517,12 +5825,16 @@ void Spell::EffectPersistentAA(SpellEffectEntry const* effect) Unit* pCaster = GetAffectiveCaster(); // FIXME: in case wild GO will used wrong affective caster (target in fact) as dynobject owner if (!pCaster) + { pCaster = m_caster; + } float radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(effect->GetRadiusIndex())); if (Player* modOwner = pCaster->GetSpellModOwner()) + { modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius); + } DynamicObject* dynObj = new DynamicObject; if (!dynObj->Create(pCaster->GetMap()->GenerateLocalLowGuid(HIGHGUID_DYNAMICOBJECT), pCaster, m_spellInfo->Id, SpellEffectIndex(effect->EffectIndex), m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, m_duration, radius, DYNAMIC_OBJECT_AREA_SPELL)) @@ -5583,7 +5895,9 @@ void Spell::EffectEnergize(SpellEffectEntry const* effect) { Player* player = (Player*)unitTarget; if (player->HasSkill(SKILL_ENGINEERING)) + { damage += int32(damage * 0.25); + } } break; } @@ -5592,7 +5906,9 @@ void Spell::EffectEnergize(SpellEffectEntry const* effect) } if (level_diff > 0) + { damage -= level_multiplier * level_diff; + } if (damage < 0) { @@ -5616,7 +5932,9 @@ void Spell::EffectEnergize(SpellEffectEntry const* effect) { uint32 spell_id = itr->second->GetId(); if (uint32 mask = sSpellMgr.GetSpellElixirMask(spell_id)) + { elixir_mask |= mask; + } } // get available elixir mask any not active type from battle/guardian (and flask if no any) @@ -5630,11 +5948,15 @@ void Spell::EffectEnergize(SpellEffectEntry const* effect) if (itr->second & elixir_mask) { if (itr->second & (ELIXIR_UNSTABLE_MASK | ELIXIR_SHATTRATH_MASK)) + { continue; + } SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first); if (spellInfo && (spellInfo->GetSpellLevel() < m_spellInfo->GetSpellLevel() || spellInfo->GetSpellLevel() > unitTarget->getLevel())) + { continue; + } elixirs.push_back(itr->first); } @@ -5746,7 +6068,9 @@ void Spell::EffectOpenLock(SpellEffectEntry const* effect) { // check if it's correct bg if (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_AV) + { bg->EventPlayerClickedOnFlag(player, gameObjTarget); + } return; } } @@ -5757,7 +6081,9 @@ void Spell::EffectOpenLock(SpellEffectEntry const* effect) if (BattleGround* bg = player->GetBattleGround()) { if (bg->GetTypeID() == BATTLEGROUND_EY) + { bg->EventPlayerClickedOnFlag(player, gameObjTarget); + } return; } } @@ -5788,7 +6114,9 @@ void Spell::EffectOpenLock(SpellEffectEntry const* effect) // mark item as unlocked if (itemTarget) + { itemTarget->SetFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_UNLOCKED); + } SendLoot(guid, LOOT_SKINNING, LockType(effect->EffectMiscValue)); @@ -5918,7 +6246,9 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) // basepoints of SUMMON_PROP_GROUP_VEHICLE is often a spellId, set amount to 1 if (summon_prop->Group == SUMMON_PROP_GROUP_VEHICLE || summon_prop->Group == SUMMON_PROP_GROUP_UNCONTROLLABLE_VEHICLE || summon_prop->Group == SUMMON_PROP_GROUP_CONTROLLABLE) + { amount = 1; + } // Get casting object WorldObject* realCaster = GetCastingObject(); @@ -5930,7 +6260,9 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) Unit* responsibleCaster = m_originalCaster; if (realCaster->GetTypeId() == TYPEID_GAMEOBJECT) + { responsibleCaster = ((GameObject*)realCaster)->GetOwner(); + } // Expected Level (Totem, Pet and Critter may not use this) uint32 level = responsibleCaster ? responsibleCaster->getLevel() : m_caster->getLevel(); @@ -5951,7 +6283,9 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) // Set middle position if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(summonPositions[0].x, summonPositions[0].y, summonPositions[0].z); + } else { realCaster->GetPosition(summonPositions[0].x, summonPositions[0].y, summonPositions[0].z); @@ -5969,13 +6303,17 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) { realCaster->GetRandomPoint(summonPositions[0].x, summonPositions[0].y, summonPositions[0].z, radius, itr->x, itr->y, itr->z); if (realCaster->GetMap()->GetHitPosition(summonPositions[0].x, summonPositions[0].y, summonPositions[0].z, itr->x, itr->y, itr->z, m_caster->GetPhaseMask(), -0.5f)) + { realCaster->UpdateAllowedPositionZ(itr->x, itr->y, itr->z); + } } else // Get a point near the caster { realCaster->GetRandomPoint(summonPositions[0].x, summonPositions[0].y, summonPositions[0].z, radius, itr->x, itr->y, itr->z); if (realCaster->GetMap()->GetHitPosition(summonPositions[0].x, summonPositions[0].y, summonPositions[0].z, itr->x, itr->y, itr->z, m_caster->GetPhaseMask(), -0.5f)) + { realCaster->UpdateAllowedPositionZ(itr->x, itr->y, itr->z); + } } } @@ -5994,9 +6332,13 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) // 121: 23035, battlestands // 647: 52893, Anti-Magic Zone (npc used) if (prop_id == 121 || prop_id == 647) + { summonResult = DoSummonTotem(effect); + } else + { summonResult = DoSummonWild(summonPositions, summon_prop, effect, level); + } break; } case UNITNAME_SUMMON_TITLE_PET: @@ -6010,7 +6352,9 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) { // * Stone Statue, etc -- fits much better totem AI if (m_spellInfo->GetSpellIconID() == 2056) + { summonResult = DoSummonTotem(effect); + } else { // possible sort totems/guardians only by summon creature type @@ -6023,21 +6367,31 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) // FIXME: not all totems and similar cases selected by this check... if (cInfo->CreatureType == CREATURE_TYPE_TOTEM) + { summonResult = DoSummonTotem(effect); + } else + { summonResult = DoSummonGuardian(summonPositions, summon_prop, effect, level); + } } } else + { summonResult = DoSummonGuardian(summonPositions, summon_prop, effect, level); + } break; } case UNITNAME_SUMMON_TITLE_CONSTRUCT: { if (prop_id == 2913) // Scrapbot + { summonResult = DoSummonWild(summonPositions, summon_prop, effect, level); + } else + { summonResult = DoSummonGuardian(summonPositions, summon_prop, effect, level); + } break; } case UNITNAME_SUMMON_TITLE_TOTEM: @@ -6046,9 +6400,13 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) case UNITNAME_SUMMON_TITLE_COMPANION: // slot 6 set for critters that can help to player in fighting if (summon_prop->Slot == 6) + { summonResult = DoSummonGuardian(summonPositions, summon_prop, effect, level); + } else + { summonResult = DoSummonCritter(summonPositions, summon_prop, effect, level); + } break; case UNITNAME_SUMMON_TITLE_OPPONENT: case UNITNAME_SUMMON_TITLE_VEHICLE: @@ -6069,7 +6427,9 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) // 1562 - force of nature - sid 33831 // 1161 - feral spirit - sid 51533 if (prop_id == 1562) // 3 uncontrolable instead of one controllable :/ + { summonResult = DoSummonGuardian(summonPositions, summon_prop, effect, level); + } break; } case SUMMON_PROP_GROUP_CONTROLLABLE: @@ -6089,7 +6449,9 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) } if (!summonResult) + { return; // No further handling required + } for (itr = summonPositions.begin(); itr != summonPositions.end(); ++itr) { @@ -6101,10 +6463,14 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) } if (summon_prop->FactionId) + { itr->creature->setFaction(summon_prop->FactionId); + } // Else set faction to summoner's faction for pet-like summoned else if ((summon_prop->Flags & SUMMON_PROP_FLAG_INHERIT_FACTION) || !itr->creature->IsTemporarySummon()) + { itr->creature->setFaction(responsibleCaster ? responsibleCaster->getFaction() : m_caster->getFaction()); + } if (!itr->creature->IsTemporarySummon()) { @@ -6114,9 +6480,13 @@ void Spell::EffectSummonType(SpellEffectEntry const* effect) // Notify Summoner if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI()) + { ((Creature*)m_caster)->AI()->JustSummoned(itr->creature); + } if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(itr->creature); + } } } } @@ -6148,7 +6518,9 @@ bool Spell::DoSummonWild(CreatureSummonPositions& list, SummonPropertiesEntry co // Notify original caster if not done already if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(summon); + } } else { @@ -6182,7 +6554,9 @@ bool Spell::DoSummonCritter(CreatureSummonPositions& list, SummonPropertiesEntry // despawn old pet before summon new if (old_critter) + { m_caster->RemoveMiniPet(); + } // for (CreatureSummonPositions::iterator itr = list.begin(); itr != list.end(); ++itr) CreatureCreatePos pos(m_caster->GetMap(), list[0].x, list[0].y, list[0].z, m_caster->GetOrientation(), m_caster->GetPhaseMask()); @@ -6216,7 +6590,9 @@ bool Spell::DoSummonCritter(CreatureSummonPositions& list, SummonPropertiesEntry // some mini-pets have quests // set timer for unsummon if (m_duration > 0) + { critter->SetDuration(m_duration); + } m_caster->SetMiniPet(critter); @@ -6257,7 +6633,9 @@ bool Spell::DoSummonGuardian(CreatureSummonPositions& list, SummonPropertiesEntr // protectors allowed only in single amount if (petType == PROTECTOR_PET) if (Pet* old_protector = m_caster->GetProtectorPet()) + { old_protector->Unsummon(PET_SAVE_AS_DELETED, m_caster); + } // in another case summon new for (CreatureSummonPositions::iterator itr = list.begin(); itr != list.end(); ++itr) @@ -6279,7 +6657,9 @@ bool Spell::DoSummonGuardian(CreatureSummonPositions& list, SummonPropertiesEntr spawnCreature->SetRespawnCoord(pos); if (m_duration > 0) + { spawnCreature->SetDuration(m_duration); + } CreatureInfo const* cInfo = spawnCreature->GetCreatureInfo(); @@ -6299,11 +6679,17 @@ bool Spell::DoSummonGuardian(CreatureSummonPositions& list, SummonPropertiesEntr charmInfo->SetPetNumber(pet_number, false); if (spawnCreature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE)) + { charmInfo->SetReactState(REACT_PASSIVE); + } else if ((cInfo->ExtraFlags & CREATURE_EXTRA_FLAG_NO_MELEE) || petType == PROTECTOR_PET) + { charmInfo->SetReactState(REACT_DEFENSIVE); + } else + { charmInfo->SetReactState(REACT_AGGRESSIVE); + } } m_caster->AddGuardian(spawnCreature); @@ -6320,7 +6706,9 @@ bool Spell::DoSummonTotem(SpellEffectEntry const* effect, uint8 slot_dbc) // unsummon old totem if (slot < MAX_TOTEM_SLOT) if (Totem* OldTotem = m_caster->GetTotem(TotemSlot(slot))) + { OldTotem->UnSummon(); + } // FIXME: Setup near to finish point because GetObjectBoundingRadius set in Create but some Create calls can be dependent from proper position // if totem have creature_template_addon.auras with persistent point for example or script call @@ -6346,7 +6734,9 @@ bool Spell::DoSummonTotem(SpellEffectEntry const* effect, uint8 slot_dbc) pTotem->SetRespawnCoord(pos); if (slot < MAX_TOTEM_SLOT) + { m_caster->_AddTotem(TotemSlot(slot), pTotem); + } // pTotem->SetName(""); // generated by client pTotem->SetOwner(m_caster); @@ -6363,13 +6753,19 @@ bool Spell::DoSummonTotem(SpellEffectEntry const* effect, uint8 slot_dbc) pTotem->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); if (m_caster->GetTypeId() == TYPEID_PLAYER) + { pTotem->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); + } if (m_caster->IsPvP()) + { pTotem->SetPvP(true); + } if (m_caster->IsFFAPvP()) + { pTotem->SetFFAPvP(true); + } // sending SMSG_TOTEM_CREATED before add to map (done in Summon) if (slot < MAX_TOTEM_SLOT && m_caster->GetTypeId() == TYPEID_PLAYER) @@ -6404,7 +6800,9 @@ bool Spell::DoSummonPossessed(CreatureSummonPositions& list, SummonPropertiesEnt // Notify Summoner if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(list[0].creature); + } return true; } @@ -6433,7 +6831,9 @@ bool Spell::DoSummonPet(SpellEffectEntry const* effect) // set timer for unsummon if (m_duration > 0) + { spawnCreature->SetDuration(m_duration); + } if (m_caster->GetTypeId() == TYPEID_PLAYER) { @@ -6441,7 +6841,9 @@ bool Spell::DoSummonPet(SpellEffectEntry const* effect) { // Summon in dest location if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { spawnCreature->Relocate(m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, -m_caster->GetOrientation()); + } return true; } @@ -6449,13 +6851,17 @@ bool Spell::DoSummonPet(SpellEffectEntry const* effect) spawnCreature->setPetType(SUMMON_PET); } else + { spawnCreature->setPetType(GUARDIAN_PET); + } // Summon in dest location CreatureCreatePos pos(m_caster->GetMap(), m_targets.m_destX, m_targets.m_destY, m_targets.m_destZ, -m_caster->GetOrientation(), m_caster->GetPhaseMask()); if (!(m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION)) + { pos = CreatureCreatePos(m_caster, -m_caster->GetOrientation()); + } Map* map = m_caster->GetMap(); uint32 pet_number = sObjectMgr.GeneratePetNumber(); @@ -6504,13 +6910,17 @@ bool Spell::DoSummonPet(SpellEffectEntry const* effect) { ((Creature*)m_originalCaster)->AI()->JustSummoned(spawnCreature); if (m_originalCaster->IsInCombat() && !(spawnCreature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))) + { ((Creature*)spawnCreature)->AI()->AttackStart(m_originalCaster->getAttackerForHelper()); + } } else if ((m_caster->GetTypeId() == TYPEID_UNIT) && ((Creature*)m_caster)->AI()) { ((Creature*)m_caster)->AI()->JustSummoned(spawnCreature); if (m_caster->IsInCombat() && !(spawnCreature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))) + { ((Creature*)spawnCreature)->AI()->AttackStart(m_caster->getAttackerForHelper()); + } } } @@ -6548,9 +6958,13 @@ bool Spell::DoSummonVehicle(CreatureSummonPositions& list, SummonPropertiesEntry // Board the caster right after summoning SpellEntry const* controlSpellEntry = sSpellStore.LookupEntry(effect->CalculateSimpleValue()); if (controlSpellEntry && IsSpellHaveAura(controlSpellEntry, SPELL_AURA_CONTROL_VEHICLE)) + { m_caster->CastSpell(spawnCreature, controlSpellEntry, true); + } else + { m_caster->CastSpell(spawnCreature, SPELL_RIDE_VEHICLE_HARDCODED, true); + } // If the boarding failed... if (!spawnCreature->HasAuraType(SPELL_AURA_CONTROL_VEHICLE)) @@ -6561,13 +6975,19 @@ bool Spell::DoSummonVehicle(CreatureSummonPositions& list, SummonPropertiesEntry // Notify Summoner if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(spawnCreature); + } #ifdef ENABLE_ELUNA if (Unit* summoner = m_caster->ToUnit()) + { sEluna->OnSummoned(spawnCreature, summoner); + } else if (m_originalCaster) if (Unit* summoner = m_originalCaster->ToUnit()) + { sEluna->OnSummoned(spawnCreature, summoner); + } #endif /* ENABLE_ELUNA */ return true; } @@ -6582,7 +7002,9 @@ void Spell::EffectLearnSpell(SpellEffectEntry const* effect) if (unitTarget->GetTypeId() != TYPEID_PLAYER) { if (m_caster->GetTypeId() == TYPEID_PLAYER) + { EffectLearnPetSpell(effect); + } return; } @@ -6621,19 +7043,27 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) { bool positive = true; if (!holder->IsPositive()) + { positive = false; + } else + { positive = !holder->GetSpellProto()->HasAttribute(SPELL_ATTR_NEGATIVE); + } // do not remove positive auras if friendly target // negative auras if non-friendly target if (positive == unitTarget->IsFriendlyTo(m_caster)) + { continue; + } } // Unholy Blight prevents dispel of diseases from target else if (holder->GetSpellProto()->GetDispel() == DISPEL_DISEASE) if (unitTarget->HasAura(50536)) + { continue; + } dispel_list.push_back(std::pair(holder, holder->GetStackAmount())); } @@ -6646,7 +7076,9 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) // some spells have effect value = 0 and all from its by meaning expect 1 if (!damage) + { damage = 1; + } // Dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && !dispel_list.empty(); ++count) @@ -6661,7 +7093,9 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) // remove entry from dispel_list if nothing left in stack if (dispel_itr->second == 0) + { dispel_list.erase(dispel_itr); + } SpellEntry const* spellInfo = holder->GetSpellProto(); // Base dispel chance @@ -6671,11 +7105,15 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) if (Unit* caster = holder->GetCaster()) { if (Player* modOwner = caster->GetSpellModOwner()) + { modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_RESIST_DISPEL_CHANCE, miss_chance, this); + } } // Try dispel if (roll_chance_i(miss_chance)) + { fail_list.push_back(spellInfo->Id); + } else { bool foundDispelled = false; @@ -6689,7 +7127,9 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) } } if (!foundDispelled) + { success_list.push_back(std::pair(holder, 1)); + } } } // Send success log and really remove auras @@ -6728,7 +7168,9 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) data << unitTarget->GetObjectGuid(); // Victim GUID data << uint32(m_spellInfo->Id); // Dispel spell id for (std::list< uint32 >::iterator j = fail_list.begin(); j != fail_list.end(); ++j) + { data << uint32(*j); // Spell Id + } m_caster->SendMessageToSet(&data, true); } } @@ -6737,7 +7179,9 @@ void Spell::EffectDispel(SpellEffectEntry const* effect) void Spell::EffectDualWield(SpellEffectEntry const* /*effect*/) { if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) + { ((Player*)unitTarget)->SetCanDualWield(true); + } } void Spell::EffectPull(SpellEffectEntry const* /*effect*/) @@ -6764,7 +7208,9 @@ void Spell::EffectDistract(SpellEffectEntry const* /*effect*/) unitTarget->clearUnitState(UNIT_STAT_MOVING); if (unitTarget->GetTypeId() == TYPEID_UNIT) + { unitTarget->GetMotionMaster()->MoveDistract(damage * IN_MILLISECONDS); + } } void Spell::EffectPickPocket(SpellEffectEntry const* /*effect*/) @@ -6837,7 +7283,9 @@ void Spell::EffectTeleUnitsFaceCaster(SpellEffectEntry const* effect) float fx, fy, fz; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(fx, fy, fz); + } else { float dis = GetSpellRadius(sSpellRadiusStore.LookupEntry(effect->GetRadiusIndex())); @@ -6927,7 +7375,9 @@ void Spell::EffectEnchantItemPerm(SpellEffectEntry const* effect) // Using enchant stored on scroll does not increase enchanting skill! (Already granted on scroll creation) if (!(m_CastItem && m_CastItem->GetProto()->Flags & ITEM_FLAG_ENCHANT_SCROLL)) + { p_caster->UpdateCraftSkill(m_spellInfo->Id); + } if (item_owner != p_caster && p_caster->GetSession()->GetSecurity() > SEC_PLAYER && sWorld.getConfig(CONFIG_BOOL_GM_LOG_TRADE)) { @@ -7090,29 +7540,47 @@ void Spell::EffectEnchantItemTmp(SpellEffectEntry const* effect) // rogue family enchantments exception by duration if (m_spellInfo->Id == 38615) + { duration = 1800; // 30 mins + } // other rogue family enchantments always 1 hour (some have spell damage=0, but some have wrong data in EffBasePoints) else if(classOptions && classOptions->SpellFamilyName == SPELLFAMILY_ROGUE) + { duration = 3600; // 1 hour + } // shaman family enchantments else if(classOptions && classOptions->SpellFamilyName == SPELLFAMILY_SHAMAN) + { duration = 1800; // 30 mins + } // other cases with this SpellVisual already selected else if (m_spellInfo->GetSpellVisual(0) == 215) + { duration = 1800; // 30 mins + } // some fishing pole bonuses else if (m_spellInfo->GetSpellVisual(0) == 563) + { duration = 600; // 10 mins + } // shaman rockbiter enchantments else if (m_spellInfo->GetSpellVisual(0) == 0) + { duration = 1800; // 30 mins + } else if (m_spellInfo->Id == 29702) + { duration = 300; // 5 mins + } else if (m_spellInfo->Id == 37360) + { duration = 300; // 5 mins + } // default case else + { duration = 3600; // 1 hour + } // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); @@ -7164,10 +7632,14 @@ void Spell::EffectTameCreature(SpellEffectEntry const* /*effect*/) pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); if (plr->IsPvP()) + { pet->SetPvP(true); + } if (plr->IsFFAPvP()) + { pet->SetFFAPvP(true); + } pet->GetCharmInfo()->SetPetNumber(sObjectMgr.GeneratePetNumber(), true); @@ -7228,7 +7700,9 @@ void Spell::EffectSummonPet(SpellEffectEntry const* effect) default: { if (Pet* OldSummon = m_caster->GetPet()) + { OldSummon->Unsummon(PET_SAVE_NOT_IN_SLOT, m_caster); + } // Load pet from db; if any to load if (NewSummon->LoadPetFromDB((Player*)m_caster, petentry)) @@ -7246,7 +7720,9 @@ void Spell::EffectSummonPet(SpellEffectEntry const* effect) } } else + { NewSummon->setPetType(GUARDIAN_PET); + } CreatureInfo const* cInfo = petentry ? ObjectMgr::GetCreatureTemplate(petentry) : NULL; if (!cInfo) @@ -7302,10 +7778,14 @@ void Spell::EffectSummonPet(SpellEffectEntry const* effect) NewSummon->SetName(sObjectMgr.GeneratePetName(petentry)); if (m_caster->IsPvP()) + { NewSummon->SetPvP(true); + } if (m_caster->IsFFAPvP()) + { NewSummon->SetFFAPvP(true); + } NewSummon->SavePetToDB(PET_SAVE_AS_CURRENT); ((Player*)m_caster)->PetSpellInitialize(); @@ -7318,13 +7798,17 @@ void Spell::EffectSummonPet(SpellEffectEntry const* effect) { ((Creature*)m_originalCaster)->AI()->JustSummoned(NewSummon); if (m_originalCaster->IsInCombat() && !(NewSummon->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))) + { ((Creature*)NewSummon)->AI()->AttackStart(m_originalCaster->getAttackerForHelper()); + } } else if ((m_caster->GetTypeId() == TYPEID_UNIT) && ((Creature*)m_caster)->AI()) { ((Creature*)m_caster)->AI()->JustSummoned(NewSummon); if (m_caster->IsInCombat() && !(NewSummon->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PASSIVE))) + { ((Creature*)NewSummon)->AI()->AttackStart(m_caster->getAttackerForHelper()); + } } } } @@ -7385,7 +7869,9 @@ void Spell::EffectTaunt(SpellEffectEntry const* /*effect*/) // Also use this effect to set the taunter's threat to the taunted creature's highest value if (unitTarget->CanHaveThreatList() && unitTarget->GetThreatManager().getCurrentVictim()) + { unitTarget->GetThreatManager().addThreat(m_caster, unitTarget->GetThreatManager().getCurrentVictim()->getThreat()); + } } void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) @@ -7444,7 +7930,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) uint32 count = 0; for(TargetList::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if(ihit->effectMask & (1<EffectIndex)) + { ++count; + } totalDamagePercentMod /= float(count); // divide to all targets break; @@ -7470,7 +7958,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) // Devastate causing Sunder Armor Effect // and no need to cast over max stack amount if (!sunder || sunder->GetStackAmount() < sunder->GetSpellProto()->GetStackAmount()) + { m_caster->CastSpell(unitTarget, 58567, true); + } } break; } @@ -7482,7 +7972,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) bool found = false; // fast check if (unitTarget->HasAuraState(AURA_STATE_DEADLY_POISON)) + { found = true; + } // full aura scan else { @@ -7498,28 +7990,36 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) } if (found) + { totalDamagePercentMod *= 1.2f; // 120% if poisoned + } } // Fan of Knives else if (m_caster->GetTypeId()==TYPEID_PLAYER && classOptions && (classOptions->SpellFamilyFlags & UI64LIT(0x0004000000000000))) { Item* weapon = ((Player*)m_caster)->GetWeaponForAttack(m_attackType, true, true); if (weapon && weapon->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) + { totalDamagePercentMod *= 1.5f; // 150% to daggers + } } // Ghostly Strike else if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Id == 14278) { Item* weapon = ((Player*)m_caster)->GetWeaponForAttack(m_attackType, true, true); if (weapon && weapon->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) + { totalDamagePercentMod *= 1.44f; // 144% to daggers + } } // Hemorrhage else if (m_caster->GetTypeId() == TYPEID_PLAYER && classOptions && (classOptions->SpellFamilyFlags & UI64LIT(0x2000000))) { Item* weapon = ((Player*)m_caster)->GetWeaponForAttack(m_attackType, true, true); if (weapon && weapon->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) + { totalDamagePercentMod *= 1.45f; // 145% to daggers + } } break; } @@ -7531,7 +8031,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = m_caster->SpellBaseDamageBonusDone(GetSpellSchoolMask(m_spellInfo)); if (holy < 0) + { holy = 0; + } spell_bonus += int32(ap * 0.08f) + int32(holy * 13 / 100); } break; @@ -7596,7 +8098,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) // Heart Strike secondary target if (m_spellInfo->GetSpellIconID() == 3145) if (m_targets.getUnitTarget() != unitTarget) + { weaponDamagePercentMod /= 2.0f; + } } // Glyph of Blood Strike if( classOptions && classOptions->SpellFamilyFlags & UI64LIT(0x0000000000400000) && @@ -7611,7 +8115,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) { int32 rp = m_caster->GetPower(POWER_RUNIC_POWER) / 10; if (rp > 25) + { rp = 25; + } totalDamagePercentMod *= 1.0f + rp / 100.0f; } // Glyph of Plague Strike @@ -7629,7 +8135,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) { SpellEffectEntry const* spellEffect = m_spellInfo->GetSpellEffect(SpellEffectIndex(j)); if(!spellEffect) + { continue; + } switch(spellEffect->Effect) { @@ -7654,7 +8162,9 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) // apply weaponDamagePercentMod to spell bonus also if (spellBonusNeedWeaponDamagePercentMod) + { spell_bonus = int32(spell_bonus * weaponDamagePercentMod); + } // non-weapon damage int32 bonus = spell_bonus + fixed_bonus; @@ -7688,13 +8198,17 @@ void Spell::EffectWeaponDmg(SpellEffectEntry const* effect) if (m_spellInfo->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000002000000))) { if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->AddComboPoints(unitTarget, 1); + } } // Mangle (Cat): CP else if (m_spellInfo->IsFitToFamily(SPELLFAMILY_DRUID, UI64LIT(0x0000040000000000))) { if (m_caster->GetTypeId() == TYPEID_PLAYER) + { ((Player*)m_caster)->AddComboPoints(unitTarget, 1); + } } } @@ -7765,13 +8279,19 @@ void Spell::EffectSummonObjectWild(SpellEffectEntry const* effect) WorldObject* target = focusObject; if (!target) + { target = m_caster; + } float x, y, z; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(x, y, z); + } else + { m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); + } Map* map = target->GetMap(); @@ -7822,9 +8342,13 @@ void Spell::EffectSummonObjectWild(SpellEffectEntry const* effect) pGameObj->SummonLinkedTrapIfAny(); if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI()) + { ((Creature*)m_caster)->AI()->JustSummoned(pGameObj); + } if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(pGameObj); + } } void Spell::EffectScriptEffect(SpellEffectEntry const* effect) @@ -7939,7 +8463,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (spellId) + { m_caster->CastSpell(m_caster, spellId, true); + } return; } @@ -7969,9 +8495,13 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (roll_chance_i(14)) // Trick (can be different critter models). 14% since below can have 1 of 6 + { m_caster->CastSpell(m_caster, 24753, true); + } else // Random Costume, 6 different (plus add. for gender) + { m_caster->CastSpell(m_caster, 24720, true); + } return; } @@ -8164,9 +8694,13 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // Two separate mounts depending on area id (allows use both in and out of specific instance) if (unitTarget->GetAreaId() == 3428) + { unitTarget->CastSpell(unitTarget, 25863, false); + } else + { unitTarget->CastSpell(unitTarget, 26655, false); + } return; } @@ -8224,7 +8758,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) int32 damage = unitTarget->GetHealth() - unitTarget->GetMaxHealth() * downToHealthPercent; if (damage > 0) + { m_caster->CastCustomSpell(unitTarget, 28375, &damage, NULL, NULL, true); + } return; } case 28560: // Summon Blizzard @@ -8266,14 +8802,22 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) uint32 rand = urand(0, 99); if (rand < 10) + { creature_id = 17034; + } else if (rand < 60) + { creature_id = 17035; + } else + { creature_id = 17039; + } if (WorldObject* pSource = GetAffectiveCasterObject()) + { pSource->SummonCreature(creature_id, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_OOC_OR_DEAD_DESPAWN, 120 * IN_MILLISECONDS); + } return; } case 29830: // Mirren's Drinking Hat @@ -8293,7 +8837,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (item) + { DoCreateItem(effect,item); + } break; } @@ -8701,7 +9247,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) if (pSummon->GetSummonerGuid() == m_caster->GetObjectGuid()) { if (pTarget->hasUnitState(UNIT_STAT_ROAMING | UNIT_STAT_ROAMING_MOVE)) + { pTarget->GetMotionMaster()->MovementExpired(); + } // trigger cast of quest complete script (see code for this spell below) pTarget->CastSpell(pTarget, 44462, true); @@ -8756,7 +9304,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // all ok, so make summoner cast the quest complete if (Unit* pSummoner = pSummon->GetSummoner()) + { pSummoner->CastSpell(pSummoner, pSpell, true); + } } return; @@ -8943,7 +9493,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (pPlayer->HasAura(45674) || pPlayer->HasAura(45675) || pPlayer->HasAura(45678) || pPlayer->HasAura(45682) || pPlayer->HasAura(45684)) + { pPlayer->CastSpell(pPlayer, 45686, true); + } m_caster->CastSpell(m_caster, 45685, true); @@ -9082,7 +9634,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } // "escort" aura is present so break; and let DB table dbscripts_on_spell be used and process further. else + { break; + } } case 46203: // Goblin Weather Machine { @@ -9140,9 +9694,13 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (unitTarget->GetAreaId() == 4157) + { unitTarget->CastSpell(unitTarget, 47324, true); + } else if (unitTarget->GetAreaId() == 4156) + { unitTarget->CastSpell(unitTarget, 47325, true); + } break; } @@ -9333,7 +9891,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) Unit* pSummoner = unitTarget->GetMap()->GetUnit(pSummon->GetSummonerGuid()); if (pSummoner && pSummoner == pCaster) + { pSummon->UnSummon(); + } return; } @@ -9397,12 +9957,16 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) { case EFFECT_INDEX_1: if (((Player*)m_originalCaster)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)) + { unitTarget->CastSpell(m_originalCaster, effect->CalculateSimpleValue(), true); + } return; case EFFECT_INDEX_2: if (((Player*)m_originalCaster)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) + { unitTarget->CastSpell(m_originalCaster, effect->CalculateSimpleValue(), true); + } return; default: @@ -9424,7 +9988,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) if (pSummon->GetSummonerGuid().IsPlayer()) { if (Player* pSummoner = sObjectMgr.GetPlayer(pSummon->GetSummonerGuid())) + { pSummoner->CastSpell(pSummoner, effect->CalculateSimpleValue(), true); + } } } @@ -9612,7 +10178,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) { // Is this all to be done at completion? if (Pet* pPet = m_caster->FindGuardianWithEntry(pSpell->GetEffectMiscValue(EFFECT_INDEX_0))) + { pPet->Unsummon(PET_SAVE_AS_DELETED, m_caster); + } } return; } @@ -9680,7 +10248,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (spellId) + { m_caster->CastSpell(m_caster, spellId, true); + } break; } @@ -9828,7 +10398,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) uint32 questID = m_spellInfo->CalculateSimpleValue(EFFECT_INDEX_1); if (((Player*)unitTarget)->GetQuestStatus(questID) == QUEST_STATUS_COMPLETE && !((Player*)unitTarget)->GetQuestRewardStatus(questID)) + { unitTarget->CastSpell(unitTarget, spellID, true); + } return; } @@ -9841,10 +10413,14 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // return from top if (((Player*)unitTarget)->GetAreaId() == 4637) + { unitTarget->CastSpell(unitTarget, 59316, true); + } // teleport atop else + { unitTarget->CastSpell(unitTarget, 59314, true); + } return; } // random spell learn instead placeholder @@ -9899,7 +10475,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // learn random explicit discovery recipe (if any) if (uint32 discoveredSpell = GetExplicitDiscoverySpell(m_spellInfo->Id, (Player*)m_caster)) + { ((Player*)m_caster)->learnSpell(discoveredSpell, false); + } return; } @@ -9933,7 +10511,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (unitTarget->HasAura(62239)) + { unitTarget->RemoveAurasDueToSpell(62239); + } else { uint32 stackAmount = urand(1, GetSpellStore()->LookupEntry(62239)->GetStackAmount()); @@ -9966,7 +10546,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) }; if (Unit* summoner = unitTarget->GetMap()->GetUnit(((TemporarySummon*)unitTarget)->GetSummonerGuid())) + { summoner->RemoveAurasDueToSpell(ownerAura); + } return; } case 62381: // Chill @@ -9992,7 +10574,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) unitTarget->CastSpell(unitTarget, 64474, true); if (m_caster->getVictim()) + { ((Creature*)unitTarget)->AI()->AttackStart(m_caster->getVictim()); + } return; } case 62524: // Attuned to Nature 2 Dose Reduction @@ -10090,7 +10674,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) owner->CastSpell(unitTarget, 63130, true); } else if (owner->HasAura(63130)) + { owner->RemoveAurasDueToSpell(63130); + } return; } @@ -10130,7 +10716,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) unitTarget->CastSpell(unitTarget, 63131, true); // Shield Level 2 } else + { unitTarget->CastSpell(unitTarget, 63130, true); // Shield Level 1 + } return; } case 63122: // Clear Insane @@ -10383,7 +10971,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // too low/high? if (roll_chance_i(33)) + { spellId = 66737; // angry + } else { switch (rand() % 3) @@ -10395,7 +10985,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (spellId) + { m_caster->CastSpell(m_caster, spellId, true); + } return; } @@ -10449,9 +11041,13 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) if (playerAura && playerAura->GetStackAmount() == 100) { if (unitTarget->HasAuraOfDifficulty(65684)) + { unitTarget->CastSpell(unitTarget, 65724, true); + } else if (unitTarget->HasAuraOfDifficulty(65686)) + { unitTarget->CastSpell(unitTarget, 65748, true); + } unitTarget->RemoveAurasDueToSpell(m_spellInfo->Id); } @@ -10482,7 +11078,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } case 68861: // Consume Soul (ICC FoS: Bronjahm) if (unitTarget) + { unitTarget->CastSpell(unitTarget, effect->CalculateSimpleValue(), true); + } return; case 68871: // Wailing Souls // Left or Right direction? @@ -10630,7 +11228,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) uint32 auraStacks = 0; if (SpellAuraHolder* playerAura = unitTarget->GetSpellAuraHolder(72371)) + { auraStacks = playerAura->GetStackAmount(); + } int32 missingStacks = unitTarget->GetPower(unitTarget->GetPowerType()) - auraStacks; if (missingStacks <= 0) @@ -10650,11 +11250,15 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) uint32 auraStacks = 0; if (SpellAuraHolder* playerAura = unitTarget->GetSpellAuraHolder(m_spellInfo->Id)) + { auraStacks = playerAura->GetStackAmount(); + } // cast Gastric Explosion on 10 stacks if (auraStacks >= 10) + { unitTarget->CastSpell(unitTarget, 72227, true, NULL, NULL, m_caster->GetObjectGuid()); + } return; } case 72257: // Remove Marks of the Fallen Champion @@ -10700,7 +11304,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (Player* target = (Player*)unitTarget) + { target->CastSpell(target, target->GetTeam() == ALLIANCE ? 71351 : 71542, true); + } return; } case 73142: // Bone Spike Graveyard (during storm) @@ -10846,7 +11452,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) { // Divine Plea, refresh on target (3 aura slots) if (SpellAuraHolder* holder = unitTarget->GetSpellAuraHolder(54428)) + { holder->RefreshHolder(); + } return; } @@ -10904,12 +11512,16 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) { SpellAuraHolder* holder = i->second; if (holder->GetCasterGuid() != m_caster->GetObjectGuid()) + { continue; + } // Search only Serpent Sting, Viper Sting, Scorpid Sting auras SpellClassOptionsEntry const* stingClassOptions = holder->GetSpellProto()->GetSpellClassOptions(); if (!stingClassOptions || !stingClassOptions->SpellFamilyFlags.IsFitToFamilyMask(UI64LIT(0x000000800000C000))) + { continue; + } // Refresh aura duration holder->RefreshHolder(); @@ -10917,7 +11529,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) Aura* aura = holder->GetAuraByEffectIndex(EFFECT_INDEX_0); if (!aura) + { continue; + } // Serpent Sting - Instantly deals 40% of the damage done by your Serpent Sting. if (stingClassOptions->IsFitToFamilyMask(UI64LIT(0x0000000000004000))) @@ -10932,7 +11546,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) { uint32 target_max_mana = unitTarget->GetMaxPower(POWER_MANA); if (!target_max_mana) + { continue; + } // ignore non positive values (can be result apply spellmods to aura damage uint32 pdamage = aura->GetModifier()->m_amount > 0 ? aura->GetModifier()->m_amount : 0; @@ -10942,7 +11558,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) pdamage = target_max_mana * pdamage / 100; if (pdamage > maxmana) + { pdamage = maxmana; + } pdamage *= 4; // total aura damage basePoint = pdamage * 60 / 100; @@ -10952,7 +11570,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // Scorpid Sting - Attempts to Disarm the target for 10 sec. This effect cannot occur more than once per 1 minute. if (stingClassOptions->IsFitToFamilyMask(UI64LIT(0x0000000000008000))) + { spellId = 53359; // Chimera Shot - Scorpid + } // ?? nothing say in spell desc (possibly need addition check) // if ((familyFlag & UI64LIT(0x0000010000000000)) || // dot // (familyFlag & UI64LIT(0x0000100000000000))) // stun @@ -10962,7 +11582,9 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) } if (spellId) + { m_caster->CastCustomSpell(target, spellId, &basePoint, 0, 0, false); + } return; } @@ -11035,11 +11657,15 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) { // search seal (offensive seals have judgement's aura dummy spell id in 2 effect if ((*itr)->GetEffIndex() != EFFECT_INDEX_2 || !IsSealSpell((*itr)->GetSpellProto())) + { continue; + } spellId2 = (*itr)->GetModifier()->m_amount; SpellEntry const* judge = sSpellStore.LookupEntry(spellId2); if (!judge) + { continue; + } break; } @@ -11050,17 +11676,23 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) for (Unit::AuraList::const_iterator itr = procTriggerAuras.begin(); itr != procTriggerAuras.end(); ++itr) { if ((*itr)->GetEffIndex() != EFFECT_INDEX_0 || !IsSealSpell((*itr)->GetSpellProto())) + { continue; + } spellId2 = 54158; break; } } if (spellId1) + { m_caster->CastSpell(unitTarget, spellId1, true); + } if (spellId2) + { m_caster->CastSpell(unitTarget, spellId2, true); + } return; } @@ -11152,11 +11784,15 @@ void Spell::EffectScriptEffect(SpellEffectEntry const* effect) // Blood Plague if (mainTarget->HasAura(55078)) + { m_caster->CastSpell(unitTarget, 55078, true); + } // Frost Fever if (mainTarget->HasAura(55095)) + { m_caster->CastSpell(unitTarget, 55095, true); + } break; } @@ -11204,7 +11840,9 @@ void Spell::EffectSanctuary(SpellEffectEntry const* /*effect*/) // Vanish allows to remove all threat and cast regular stealth so other spells can be used if (m_spellInfo->IsFitToFamily(SPELLFAMILY_ROGUE, UI64LIT(0x0000000000000800))) + { ((Player*)m_caster)->RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT); + } } void Spell::EffectAddComboPoints(SpellEffectEntry const* effect /*effect*/) @@ -11618,7 +12256,9 @@ void Spell::EffectEnchantHeldItem(SpellEffectEntry const* effect) uint32 enchant_id = effect->EffectMiscValue; int32 duration = m_duration; // Try duration index first... if (!duration) + { duration = m_currentBasePoints[SpellEffectIndex(effect->EffectIndex)]; // Base points after... + } if (!duration) duration = 10; // 10 seconds for enchants which don't have listed duration @@ -11677,7 +12317,9 @@ void Spell::EffectInebriate(SpellEffectEntry const* /*effect*/) { drunkValue = 100; if (roll_chance_i(25)) + { player->CastSpell(player, 67468, false); // Drunken Vomit + } } player->SetDrunkValue(drunkValue, m_CastItem ? m_CastItem->GetEntry() : 0); } @@ -11751,7 +12393,9 @@ void Spell::EffectSummonObject(SpellEffectEntry const* effect) if (ObjectGuid guid = m_caster->m_ObjectSlotGuid[slot]) { if (GameObject* obj = m_caster ? m_caster->GetMap()->GetGameObject(guid) : NULL) + { obj->SetLootState(GO_JUST_DEACTIVATED); + } m_caster->m_ObjectSlotGuid[slot].Clear(); } @@ -11760,10 +12404,14 @@ void Spell::EffectSummonObject(SpellEffectEntry const* effect) float x, y, z; // If dest location if present if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(x, y, z); + } // Summon in random point all other units if location present else + { m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); + } Map* map = m_caster->GetMap(); if (!pGameObj->Create(map->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), go_id, map, @@ -11785,9 +12433,13 @@ void Spell::EffectSummonObject(SpellEffectEntry const* effect) pGameObj->SummonLinkedTrapIfAny(); if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI()) + { ((Creature*)m_caster)->AI()->JustSummoned(pGameObj); + } if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(pGameObj); + } } void Spell::EffectResurrect(SpellEffectEntry const* /*effect*/) @@ -11820,7 +12472,9 @@ void Spell::EffectResurrect(SpellEffectEntry const* /*effect*/) if (roll_chance_i(failChance)) { if (failSpellId) + { m_caster->CastSpell(m_caster, failSpellId, true, m_CastItem); + } return; } break; @@ -11861,13 +12515,17 @@ void Spell::EffectAddExtraAttacks(SpellEffectEntry const* /*effect*/) void Spell::EffectParry(SpellEffectEntry const* /*effect*/) { if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) + { ((Player*)unitTarget)->SetCanParry(true); + } } void Spell::EffectBlock(SpellEffectEntry const* /*effect*/) { if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) + { ((Player*)unitTarget)->SetCanBlock(true); + } } void Spell::EffectLeapForward(SpellEffectEntry const* effect) @@ -11896,7 +12554,9 @@ void Spell::EffectLeapForward(SpellEffectEntry const* effect) if (unitTarget->GetMap()->GetTerrain()->IsInWater(nextPos.x, nextPos.y, nextPos.z, &liquidData)) { if (fabs(nextPos.z - liquidData.level) < 10.0f) + { nextPos.z = liquidData.level - IN_OR_UNDER_LIQUID_RANGE; + } } else { @@ -11916,7 +12576,9 @@ void Spell::EffectLeapForward(SpellEffectEntry const* effect) // fix origin position if player was jumping and near of the ground but not in ground if (fabs(prevPos.z - groundZ) > 0.5f) + { prevPos.z = groundZ; + } //check if in liquid bool isPrevInLiquid = unitTarget->GetMap()->GetTerrain()->IsInWater(prevPos.x, prevPos.y, prevPos.z); @@ -11961,7 +12623,9 @@ void Spell::EffectLeapForward(SpellEffectEntry const* effect) } } else + { isOnGround = true; // player is on ground + } if (isInLiquid || (!isInLiquidTested && unitTarget->GetMap()->GetTerrain()->IsInWater(nextPos.x, nextPos.y, nextPos.z, &liquidData))) { @@ -11974,9 +12638,13 @@ void Spell::EffectLeapForward(SpellEffectEntry const* effect) } if ((liquidData.level - IN_OR_UNDER_LIQUID_RANGE) > nextPos.z) + { nextPos.z = prevPos.z; // we are under water so next z equal prev z + } else + { nextPos.z = liquidData.level - IN_OR_UNDER_LIQUID_RANGE; // we are on water surface, so next z equal liquid level + } isInLiquid = true; @@ -12122,7 +12790,9 @@ void Spell::EffectSelfResurrect(SpellEffectEntry const* effect) { health = uint32(damage / 100.0f * unitTarget->GetMaxHealth()); if (unitTarget->GetMaxPower(POWER_MANA) > 0) + { mana = uint32(damage / 100.0f * unitTarget->GetMaxPower(POWER_MANA)); + } } Player* plr = ((Player*)unitTarget); @@ -12176,14 +12846,18 @@ void Spell::EffectCharge(SpellEffectEntry const* /*effect*/) unitTarget->GetContactPoint(m_caster, x, y, z, 3.666666f); if (unitTarget->GetTypeId() != TYPEID_PLAYER) + { ((Creature*)unitTarget)->StopMoving(); + } // Only send MOVEMENTFLAG_WALK_MODE, client has strange issues with other move flags m_caster->MonsterMoveWithSpeed(x, y, z, 24.f, true, true); // not all charge effects used in negative spells if (unitTarget != m_caster && !IsPositiveSpell(m_spellInfo->Id)) + { m_caster->Attack(unitTarget, true); + } } void Spell::EffectCharge2(SpellEffectEntry const* /*effect*/) @@ -12194,10 +12868,14 @@ void Spell::EffectCharge2(SpellEffectEntry const* /*effect*/) m_targets.getDestination(x, y, z); if (unitTarget->GetTypeId() != TYPEID_PLAYER) + { ((Creature*)unitTarget)->StopMoving(); + } } else if (unitTarget && unitTarget != m_caster) + { unitTarget->GetContactPoint(m_caster, x, y, z, 3.666666f); + } else { return; @@ -12208,7 +12886,9 @@ void Spell::EffectCharge2(SpellEffectEntry const* /*effect*/) // not all charge effects used in negative spells if (unitTarget && unitTarget != m_caster && !IsPositiveSpell(m_spellInfo->Id)) + { m_caster->Attack(unitTarget, true); + } } void Spell::EffectKnockBack(SpellEffectEntry const* effect) @@ -12240,7 +12920,9 @@ void Spell::EffectPlayerPull(SpellEffectEntry const* effect) float dist = unitTarget->GetDistance2d(m_caster); if (damage && dist > damage) + { dist = float(damage); + } unitTarget->KnockBackFrom(m_caster, -dist, float(effect->EffectMiscValue) / 10); } @@ -12264,9 +12946,13 @@ void Spell::EffectDispelMechanic(SpellEffectEntry const* effect) { unitTarget->RemoveAurasDueToSpell(spell->Id); if (Auras.empty()) + { break; + } else + { next = Auras.begin(); + } } } } @@ -12321,7 +13007,9 @@ void Spell::EffectSummonAllTotems(SpellEffectEntry const* effect) if (ActionButton const* actionButton = ((Player*)m_caster)->GetActionButton(start_button + slot)) if (actionButton->GetType() == ACTION_BUTTON_SPELL) if (uint32 spell_id = actionButton->GetAction()) + { m_caster->CastSpell(unitTarget, spell_id, true); + } } void Spell::EffectDestroyAllTotems(SpellEffectEntry const* /*effect*/) @@ -12345,7 +13033,9 @@ void Spell::EffectDestroyAllTotems(SpellEffectEntry const* /*effect*/) } if (mana) + { m_caster->CastCustomSpell(m_caster, 39104, &mana, NULL, NULL, true); + } } void Spell::EffectBreakPlayerTargeting (SpellEffectEntry const* /*effect*/) @@ -12384,7 +13074,9 @@ void Spell::EffectDurabilityDamage(SpellEffectEntry const* effect) } if (Item* item = ((Player*)unitTarget)->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) + { ((Player*)unitTarget)->DurabilityPointsLoss(item, damage); + } } void Spell::EffectDurabilityDamagePCT(SpellEffectEntry const* effect) @@ -12416,7 +13108,9 @@ void Spell::EffectDurabilityDamagePCT(SpellEffectEntry const* effect) } if (Item* item = ((Player*)unitTarget)->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) + { ((Player*)unitTarget)->DurabilityLoss(item, double(damage) / 100.0f); + } } void Spell::EffectModifyThreatPercent(SpellEffectEntry const* /*effect*/) @@ -12437,9 +13131,13 @@ void Spell::EffectTransmitted(SpellEffectEntry const* effect) { case 29886: // Create Soulwell if (m_caster->HasAura(18692)) + { name_id = 183510; + } else if (m_caster->HasAura(18693)) + { name_id = 183511; + } break; default: break; @@ -12456,7 +13154,9 @@ void Spell::EffectTransmitted(SpellEffectEntry const* effect) float fx, fy, fz; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(fx, fy, fz); + } // FIXME: this can be better check for most objects but still hack else if (effect->GetRadiusIndex() && m_spellInfo->GetSpeed() == 0) { @@ -12496,7 +13196,9 @@ void Spell::EffectTransmitted(SpellEffectEntry const* effect) } } else + { m_caster->GetClosePoint(fx, fy, fz, DEFAULT_WORLD_OBJECT_SIZE, dis); + } } Map* cMap = m_caster->GetMap(); @@ -12575,9 +13277,13 @@ void Spell::EffectTransmitted(SpellEffectEntry const* effect) pGameObj->SummonLinkedTrapIfAny(); if (m_caster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_caster)->AI()) + { ((Creature*)m_caster)->AI()->JustSummoned(pGameObj); + } if (m_originalCaster && m_originalCaster != m_caster && m_originalCaster->GetTypeId() == TYPEID_UNIT && ((Creature*)m_originalCaster)->AI()) + { ((Creature*)m_originalCaster)->AI()->JustSummoned(pGameObj); + } } void Spell::EffectProspecting(SpellEffectEntry const* /*effect*/) @@ -12680,7 +13386,9 @@ void Spell::EffectStealBeneficialBuff(SpellEffectEntry const* effect) { // Need check for passive? this if (holder->IsPositive() && !holder->IsPassive() && !holder->GetSpellProto()->HasAttribute(SPELL_ATTR_EX4_NOT_STEALABLE)) + { steal_list.push_back(holder); + } } } // Ok if exist some buffs for dispel try dispel it @@ -12708,7 +13416,9 @@ void Spell::EffectStealBeneficialBuff(SpellEffectEntry const* effect) --list_size; } else + { ++j; + } } } // Really try steal and send log @@ -12884,13 +13594,17 @@ void Spell::EffectTitanGrip(SpellEffectEntry const* effect) { // Make sure "Titan's Grip" (49152) penalty spell does not silently change if (effect->EffectMiscValue != 49152) + { sLog.outError("Spell::EffectTitanGrip: Spell %u has unexpected EffectMiscValue '%u'", m_spellInfo->Id, effect->EffectMiscValue); + } if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) { Player* plr = (Player*)m_caster; plr->SetCanTitanGrip(true); if (plr->HasTwoHandWeaponInOneHand() && !plr->HasAura(49152)) + { plr->CastSpell(plr, 49152, true); + } } } @@ -12986,13 +13700,17 @@ void Spell::EffectBind(SpellEffectEntry const* effect) loc.coord_z = st->target_Z; loc.orientation = st->target_Orientation; if (!area_id) + { area_id = sTerrainMgr.GetAreaId(loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z); + } } else { player->GetPosition(loc); if (!area_id) + { area_id = player->GetAreaId(); + } } player->SetHomebindToLocation(loc, area_id); @@ -13034,9 +13752,13 @@ void Spell::EffectRestoreItemCharges(SpellEffectEntry const* effect) // In case item from limited category recharge any from category, is this valid checked early in spell checks Item* item; if (itemProto->ItemLimitCategory) + { item = ((Player*)unitTarget)->GetItemByLimitedCategory(itemProto->ItemLimitCategory); + } else + { item = player->GetItemByEntry(effect->EffectItemType); + } if (!item) { @@ -13055,7 +13777,9 @@ void Spell::EffectRedirectThreat(SpellEffectEntry const* effect) if (m_spellInfo->Id == 59665) // Vigilance if (Aura* glyph = unitTarget->GetDummyAura(63326)) // Glyph of Vigilance + { damage += glyph->GetModifier()->m_amount; + } m_caster->GetHostileRefManager().SetThreatRedirection(unitTarget->GetObjectGuid(), uint32(damage)); } @@ -13099,7 +13823,9 @@ void Spell::EffectQuestOffer(SpellEffectEntry const* effect) Player* player = (Player*)unitTarget; if (player->CanTakeQuest(quest, false)) + { player->PlayerTalkClass->SendQuestGiverQuestDetails(quest, player->GetObjectGuid(), true); + } } } @@ -13130,9 +13856,13 @@ void Spell::EffectKnockBackFromPosition(SpellEffectEntry const* effect) float x, y, z; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(x, y, z); + } else + { m_caster->GetPosition(x, y, z); + } float angle = unitTarget->GetAngle(x, y) + M_PI_F; float horizontalSpeed = effect->EffectMiscValue * 0.1f; @@ -13149,9 +13879,13 @@ void Spell::EffectGravityPull(SpellEffectEntry const* effect) float x, y, z; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) + { m_targets.getDestination(x, y, z); + } else + { m_caster->GetPosition(x, y, z); + } float speed = float(effect->EffectMiscValue) * 0.15f; float height = float(unitTarget->GetDistance(x, y, z) * 0.2f); @@ -13198,10 +13932,14 @@ void Spell::EffectCreateTamedPet(SpellEffectEntry const* effect) newTamedPet->GetCharmInfo()->SetPetNumber(petNumber, true); if (unitTarget->IsPvP()) + { newTamedPet->SetPvP(true); + } if (unitTarget->IsFFAPvP()) + { newTamedPet->SetFFAPvP(true); + } newTamedPet->InitStatsForLevel(unitTarget->getLevel()); newTamedPet->InitPetCreateSpells(); diff --git a/src/game/WorldHandlers/SpellHandler.cpp b/src/game/WorldHandlers/SpellHandler.cpp index 5a38add8d..ce1e61627 100644 --- a/src/game/WorldHandlers/SpellHandler.cpp +++ b/src/game/WorldHandlers/SpellHandler.cpp @@ -180,7 +180,9 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) Spell::SendCastResult(_player,spellInfo,cast_count,SPELL_FAILED_NO_VALID_TARGETS); // for explicit target spells else + { Spell::SendCastResult(_player, spellInfo, cast_count, SPELL_FAILED_BAD_TARGETS); + } } return; } @@ -280,7 +282,9 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) stmt.PExecute(pItem->GetGUIDLow()); } else + { pUser->SendLoot(pItem->GetObjectGuid(), LOOT_CORPSE); + } } void WorldSession::HandleGameObjectUseOpcode(WorldPacket& recv_data) @@ -447,7 +451,9 @@ void WorldSession::HandleCastSpellOpcode(WorldPacket& recvPacket) Unit::AuraList swaps = mover->GetAurasByType(SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS); Unit::AuraList const& swaps2 = mover->GetAurasByType(SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS_2); if (!swaps2.empty()) + { swaps.insert(swaps.end(), swaps2.begin(), swaps2.end()); + } for (Unit::AuraList::const_iterator itr = swaps.begin(); itr != swaps.end(); ++itr) { @@ -474,7 +480,9 @@ void WorldSession::HandleCastSpellOpcode(WorldPacket& recvPacket) { // if rank not found then function return NULL but in explicit cast case original spell can be casted and later failed with appropriate error message if (SpellEntry const* actualSpellInfo = sSpellMgr.SelectAuraRankForLevel(spellInfo, target->getLevel())) + { spellInfo = actualSpellInfo; + } } Spell* spell = new Spell(mover, spellInfo, triggeredByAura ? true : false, mover->GetObjectGuid(), triggeredByAura ? triggeredByAura->GetSpellProto() : NULL); @@ -494,10 +502,14 @@ void WorldSession::HandleCancelCastOpcode(WorldPacket& recvPacket) recvPacket.FlushBits(); if (hasCounter) + { recvPacket >> counter; + } if (hasSpellId) + { recvPacket >> spellId; + } // ignore for remote control state (for player case) Unit* mover = _player->GetMover(); @@ -513,7 +525,9 @@ void WorldSession::HandleCancelCastOpcode(WorldPacket& recvPacket) } if (mover->IsNonMeleeSpellCasted(false)) + { mover->InterruptNonMeleeSpells(false, spellId); + } } void WorldSession::HandleCancelAuraOpcode(WorldPacket& recvPacket) @@ -596,7 +610,9 @@ void WorldSession::HandleCancelAuraOpcode(WorldPacket& recvPacket) { if (Spell* curSpell = _player->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) if (curSpell->m_spellInfo->Id == spellId) + { _player->InterruptSpell(CURRENT_CHANNELED_SPELL); + } return; } @@ -702,7 +718,9 @@ void WorldSession::HandleTotemDestroyed(WorldPacket& recvPacket) } if (Totem* totem = GetPlayer()->GetTotem(TotemSlot(slotId))) + { totem->UnSummon(); + } } void WorldSession::HandleSelfResOpcode(WorldPacket& /*recv_data*/) @@ -718,7 +736,9 @@ void WorldSession::HandleSelfResOpcode(WorldPacket& /*recv_data*/) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(_player->GetUInt32Value(PLAYER_SELF_RES_SPELL)); if (spellInfo) + { _player->CastSpell(_player, spellInfo, false); + } _player->SetUInt32Value(PLAYER_SELF_RES_SPELL, 0); } @@ -774,9 +794,13 @@ void WorldSession::HandleSpellClick(WorldPacket& recv_data) Unit* target = (itr->second.castFlags & 0x2) ? (Unit*)_player : (Unit*)unit; if (itr->second.spellId) + { caster->CastSpell(target, itr->second.spellId, true); + } else + { sLog.outError("WorldSession::HandleSpellClick: npc_spell_click with entry %u has 0 in spell_id. Not handled custom case?", unit->GetEntry()); + } } } } @@ -831,9 +855,13 @@ void WorldSession::HandleGetMirrorimageData(WorldPacket& recv_data) data << pPlayer->GetGuildGuid(); if (pPlayer->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM)) + { data << (uint32)0; + } else + { data << (uint32)pPlayer->GetItemDisplayIdInSlot(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_HEAD); + } data << (uint32)pPlayer->GetItemDisplayIdInSlot(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_SHOULDERS); data << (uint32)pPlayer->GetItemDisplayIdInSlot(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_BODY); @@ -845,9 +873,13 @@ void WorldSession::HandleGetMirrorimageData(WorldPacket& recv_data) data << (uint32)pPlayer->GetItemDisplayIdInSlot(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_HANDS); if (pPlayer->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK)) + { data << (uint32)0; + } else + { data << (uint32)pPlayer->GetItemDisplayIdInSlot(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_BACK); + } data << (uint32)pPlayer->GetItemDisplayIdInSlot(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_TABARD); } diff --git a/src/game/WorldHandlers/TaxiHandler.cpp b/src/game/WorldHandlers/TaxiHandler.cpp index 7738895b5..bc076b9cc 100644 --- a/src/game/WorldHandlers/TaxiHandler.cpp +++ b/src/game/WorldHandlers/TaxiHandler.cpp @@ -125,7 +125,9 @@ void WorldSession::SendDoFlight(uint32 mountDisplayId, uint32 path, uint32 pathN GetPlayer()->GetMotionMaster()->MovementExpired(false); if (mountDisplayId) + { GetPlayer()->Mount(mountDisplayId); + } GetPlayer()->GetMotionMaster()->MoveTaxiFlight(path, pathNode); } @@ -136,7 +138,9 @@ bool WorldSession::SendLearnNewTaxiNode(Creature* unit) uint32 curloc = sObjectMgr.GetNearestTaxiNode(unit->GetPositionX(), unit->GetPositionY(), unit->GetPositionZ(), unit->GetMapId(), GetPlayer()->GetTeam()); if (curloc == 0) + { return true; // `true` send to avoid WorldSession::SendTaxiMenu call with one more curlock seartch with same false result. + } if (GetPlayer()->m_taxi.SetTaximaskNode(curloc)) { @@ -269,12 +273,18 @@ void WorldSession::HandleMoveSplineDoneOpcode(WorldPacket& recv_data) sObjectMgr.GetTaxiPath(sourcenode, destinationnode, path, cost); if (path && mountDisplayId) + { SendDoFlight(mountDisplayId, path, 1); // skip start fly node + } else + { GetPlayer()->m_taxi.ClearTaxiDestinations(); // clear problematic path and next + } } else + { GetPlayer()->m_taxi.ClearTaxiDestinations(); // not destinations, clear source node + } } void WorldSession::HandleActivateTaxiOpcode(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/TradeHandler.cpp b/src/game/WorldHandlers/TradeHandler.cpp index b2df3ad26..8f358c267 100644 --- a/src/game/WorldHandlers/TradeHandler.cpp +++ b/src/game/WorldHandlers/TradeHandler.cpp @@ -112,7 +112,9 @@ void WorldSession::SendUpdateTrade(bool trader_state /*= true*/) uint8 itemCount = 0; for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i) if (Item* item = view_trade->GetItem(TradeSlots(i))) + { ++itemCount; + } data.WriteBits(itemCount, 22); @@ -238,21 +240,33 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[]) if (myItems[i]) { if (!traderCanTrade) + { sLog.outError("trader can't store item: %s", myItems[i]->GetGuidStr().c_str()); + } if (_player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, myItems[i], false) == EQUIP_ERR_OK) + { _player->MoveItemToInventory(playerDst, myItems[i], true, true); + } else + { sLog.outError("player can't take item back: %s", myItems[i]->GetGuidStr().c_str()); + } } // return the already removed items to the original owner if (hisItems[i]) { if (!playerCanTrade) + { sLog.outError("player can't store item: %s", hisItems[i]->GetGuidStr().c_str()); + } if (trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, hisItems[i], false) == EQUIP_ERR_OK) + { trader->MoveItemToInventory(traderDst, hisItems[i], true, true); + } else + { sLog.outError("trader can't take item back: %s", hisItems[i]->GetGuidStr().c_str()); + } } } } @@ -296,9 +310,13 @@ static void clearAcceptTradeMode(Item** myItems, Item** hisItems) for (int i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i) { if (myItems[i]) + { myItems[i]->SetInTrade(false); + } if (hisItems[i]) + { hisItems[i]->SetInTrade(false); + } } } @@ -529,10 +547,14 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& recvPacket) trader->ModifyMoney(my_trade->GetMoney()); if (my_spell) + { my_spell->SpellStart(&my_targets); + } if (his_spell) + { his_spell->SpellStart(&his_targets); + } // cleanup clearAcceptTradeMode(my_trade, his_trade); @@ -593,7 +615,9 @@ void WorldSession::HandleCancelTradeOpcode(WorldPacket& /*recvPacket*/) { // sent also after LOGOUT COMPLETE if (_player) // needed because STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT + { _player->TradeCancel(true); + } } void WorldSession::HandleInitiateTradeOpcode(WorldPacket& recvPacket) diff --git a/src/game/WorldHandlers/TransportSystem.cpp b/src/game/WorldHandlers/TransportSystem.cpp index 17382ce31..6449c7299 100644 --- a/src/game/WorldHandlers/TransportSystem.cpp +++ b/src/game/WorldHandlers/TransportSystem.cpp @@ -70,7 +70,9 @@ void TransportBase::Update(uint32 diff) m_updatePositionsTimer = 500; } else + { m_updatePositionsTimer -= diff; + } } // Update the global positions of all passengers @@ -107,11 +109,15 @@ void TransportBase::UpdateGlobalPositionOf(WorldObject* passenger, float lx, flo m_owner->GetMap()->PlayerRelocation((Player*)passenger, gx, gy, gz, go); } else + { m_owner->GetMap()->CreatureRelocation((Creature*)passenger, gx, gy, gz, go); + } // If passenger is vehicle if (((Unit*)passenger)->IsVehicle()) + { ((Unit*)passenger)->GetVehicleInfo()->UpdateGlobalPositions(); + } } // ToDo: Add gameobject relocation // ToDo: Add passenger relocation for MO transports @@ -157,7 +163,9 @@ bool TransportBase::HasOnBoard(WorldObject const* passenger) const return true; } else + { passenger = passenger->GetTransportInfo()->GetTransport(); + } } return false; diff --git a/src/game/WorldHandlers/Transports.cpp b/src/game/WorldHandlers/Transports.cpp index fb65841be..70dbe9190 100644 --- a/src/game/WorldHandlers/Transports.cpp +++ b/src/game/WorldHandlers/Transports.cpp @@ -283,7 +283,9 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set& mapids) { // remember first stop frame if (firstStop == -1) + { firstStop = i; + } lastStop = i; } } @@ -293,9 +295,13 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set& mapids) { int j = (i + lastStop) % keyFrames.size(); if (keyFrames[j].node->actionFlag == 2) + { tmpDist = 0; + } else + { tmpDist += keyFrames[j].distFromPrev; + } keyFrames[j].distSinceStop = tmpDist; } @@ -305,20 +311,30 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set& mapids) tmpDist += keyFrames[(j + 1) % keyFrames.size()].distFromPrev; keyFrames[j].distUntilStop = tmpDist; if (keyFrames[j].node->actionFlag == 2) + { tmpDist = 0; + } } for (size_t i = 0; i < keyFrames.size(); ++i) { if (keyFrames[i].distSinceStop < (30 * 30 * 0.5f)) + { keyFrames[i].tFrom = sqrt(2 * keyFrames[i].distSinceStop); + } else + { keyFrames[i].tFrom = ((keyFrames[i].distSinceStop - (30 * 30 * 0.5f)) / 30) + 30; + } if (keyFrames[i].distUntilStop < (30 * 30 * 0.5f)) + { keyFrames[i].tTo = sqrt(2 * keyFrames[i].distUntilStop); + } else + { keyFrames[i].tTo = ((keyFrames[i].distUntilStop - (30 * 30 * 0.5f)) / 30) + 30; + } keyFrames[i].tFrom *= 1000; keyFrames[i].tTo *= 1000; @@ -333,7 +349,9 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set& mapids) int t = 0; bool teleport = false; if (keyFrames[keyFrames.size() - 1].node->mapid != keyFrames[0].node->mapid) + { teleport = true; + } WayPoint pos(keyFrames[0].node->mapid, keyFrames[0].node->x, keyFrames[0].node->y, keyFrames[0].node->z, teleport, keyFrames[0].node->arrivalEventID, keyFrames[0].node->departureEventID); @@ -372,7 +390,9 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set& mapids) // sLog.outString("T: %d, D: %f, x: %f, y: %f, z: %f", t, d, newX, newY, newZ); pos = WayPoint(keyFrames[i].node->mapid, newX, newY, newZ, teleport); if (teleport) + { m_WayPoints[t] = pos; + } } if (tFrom < tTo) // caught in tFrom dock's "gravitational pull" @@ -405,9 +425,13 @@ bool Transport::GenerateWaypoints(uint32 pathid, std::set& mapids) } if (keyFrames[i + 1].tFrom > keyFrames[i + 1].tTo) + { t += 100 - ((long)keyFrames[i + 1].tTo % 100); + } else + { t += (long)keyFrames[i + 1].tTo % 100; + } bool teleport = false; if ((keyFrames[i + 1].node->actionFlag == 1) || (keyFrames[i + 1].node->mapid != keyFrames[i].node->mapid)) @@ -449,7 +473,9 @@ void Transport::MoveToNextWayPoint() ++m_next; if (m_next == m_WayPoints.end()) + { m_next = m_WayPoints.begin(); + } } void Transport::TeleportTransport(uint32 newMapid, float x, float y, float z) @@ -506,7 +532,9 @@ bool Transport::AddPassenger(Player* passenger) bool Transport::RemovePassenger(Player* passenger) { if (m_passengers.erase(passenger)) + { DETAIL_LOG("Player %s removed from transport %s.", passenger->GetName(), GetName()); + } return true; } @@ -548,7 +576,9 @@ void Transport::Update(uint32 update_diff, uint32 /*p_time*/) m_nextNodeTime = m_curr->first; if (m_curr == m_WayPoints.begin()) + { DETAIL_FILTER_LOG(LOG_FILTER_TRANSPORT_MOVES, " ************ BEGIN ************** %s", GetName()); + } DETAIL_FILTER_LOG(LOG_FILTER_TRANSPORT_MOVES, "%s moved to %f %f %f %d", GetName(), m_curr->second.x, m_curr->second.y, m_curr->second.z, m_curr->second.mapid); } @@ -613,6 +643,8 @@ void Transport::DoEventIfAny(WayPointMap::value_type const& node, bool departure DEBUG_FILTER_LOG(LOG_FILTER_TRANSPORT_MOVES, "Taxi %s event %u of node %u of %s \"%s\") path", departure ? "departure" : "arrival", eventid, node.first, GetGuidStr().c_str(), GetName()); if (!sScriptMgr.OnProcessEvent(eventid, this, this, departure)) + { GetMap()->ScriptsStart(DBS_ON_EVENT, eventid, this, this); + } } } diff --git a/src/game/WorldHandlers/UnitAuraProcHandler.cpp b/src/game/WorldHandlers/UnitAuraProcHandler.cpp index 43517dea0..114d8e0df 100644 --- a/src/game/WorldHandlers/UnitAuraProcHandler.cpp +++ b/src/game/WorldHandlers/UnitAuraProcHandler.cpp @@ -463,9 +463,13 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* pVictim, SpellAuraHolder* holder, S // Get EventProcFlag uint32 EventProcFlag; if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags + { EventProcFlag = spellProcEvent->procFlags; + } else + { EventProcFlag = spellProto->GetProcFlags(); // else get from spell proto + } // Continue if no trigger exist if (!EventProcFlag) { @@ -484,7 +488,9 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* pVictim, SpellAuraHolder* holder, S bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim); // Shadow Word: Death - can trigger from every kill if (holder->GetId() == 32409) + { allow = true; + } if (!allow) { return false; @@ -506,11 +512,17 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* pVictim, SpellAuraHolder* holder, S { Item* item = NULL; if (attType == BASE_ATTACK) + { item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); + } else if (attType == OFF_ATTACK) + { item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); + } else + { item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); + } if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<GetProto()->SubClass) & eqItems->EquippedItemSubClassMask)) { @@ -531,7 +543,9 @@ bool Unit::IsTriggeredAtSpellProcEvent(Unit* pVictim, SpellAuraHolder* holder, S float chance = (float)spellProto->GetProcChance(); // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance; if (spellProcEvent && spellProcEvent->customChance) + { chance = spellProcEvent->customChance; + } // If PPM exist calculate chance from PPM if (!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0) { @@ -609,12 +623,18 @@ SpellAuraProcResult Unit::HandleHasteAuraProc(Unit* pVictim, uint32 damage, Aura } if (basepoints0) + { CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); + } else + { CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); + } if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } @@ -684,12 +704,18 @@ SpellAuraProcResult Unit::HandleSpellCritChanceAuraProc(Unit* pVictim, uint32 /* } if (basepoints0) + { CastCustomSpell(target, triggered_spell_id, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); + } else + { CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); + } if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } @@ -724,7 +750,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // return damage % to attacker but < 50% own total health basepoints[0] = triggerAmount * int32(damage) / 100; if (basepoints[0] > (int32)GetMaxHealth() / 2) + { basepoints[0] = (int32)GetMaxHealth() / 2; + } triggered_spell_id = 25997; break; @@ -873,7 +901,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura iter = Auras.begin(); } else + { ++iter; + } } return SPELL_AURA_PROC_OK; } @@ -960,7 +990,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura target = this; if (roll_chance_i(10)) + { ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL); + } break; } // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck) @@ -1123,7 +1155,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura { // also decrease owner buff stack if (Unit* owner = GetOwner()) + { owner->RemoveAuraHolderFromStack(34027); + } // Remove only single aura from stack if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1)) @@ -1194,10 +1228,14 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // will added first to stack if (!aurHolder) + { CastSpell(this, 72521, true); // Shadowmourne Visual Low + } // half stack else if (aurHolder->GetStackAmount() + 1 == 6) + { CastSpell(this, 72523, true); // Shadowmourne Visual High + } // full stack else if (aurHolder->GetStackAmount() + 1 >= aurHolder->GetSpellProto()->GetStackAmount()) { @@ -1295,7 +1333,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura } // Critical counted -> roll chance if (roll_chance_i(triggerAmount)) + { CastSpell(this, 48108, true, castItem, triggeredByAura); + } } mod->m_amount = 25; return SPELL_AURA_PROC_OK; @@ -1561,7 +1601,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura { // Glyph of Siphon Life if (Aura* aur = GetAura(56216, EFFECT_INDEX_0)) + { triggerAmount += triggerAmount * aur->GetModifier()->m_amount / 100; + } basepoints[0] = int32(damage * triggerAmount / 100); triggered_spell_id = 63106; @@ -1676,10 +1718,14 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura { // Shadow Word: Pain if (procClassOptions && procClassOptions->SpellFamilyFlags & UI64LIT(0x0000000000008000)) + { triggered_spell_id = 40441; + } // Renew else if (procClassOptions && procClassOptions->SpellFamilyFlags & UI64LIT(0x0000000000000010)) + { triggered_spell_id = 40440; + } else { return SPELL_AURA_PROC_FAILED; @@ -1878,9 +1924,13 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura float radius; SpellEffectEntry const* spellEffect = procSpell->GetSpellEffect(EFFECT_INDEX_0); if (spellEffect && spellEffect->GetRadiusIndex()) + { radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellEffect->GetRadiusIndex())); + } else + { radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(procSpell->GetRangeIndex())); + } ((Player*)this)->ApplySpellMod(procSpell->Id, SPELLMOD_RADIUS, radius); @@ -2141,7 +2191,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura float ap = GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_HOLY); if (holy < 0) + { holy = 0; + } basepoints[0] = GetAttackTime(BASE_ATTACK) * int32(ap * 0.022f + 0.044f * holy) / 1000; break; } @@ -2283,7 +2335,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // At melee attack or Hammer of the Righteous spell damage considered as melee attack if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595)) + { triggered_spell_id = 31803; // Holy Vengeance + } // Add 5-stack effect from Holy Vengeance uint32 stacks = 0; @@ -2297,7 +2351,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura } } if (stacks >= 5) + { CastSpell(target, 42463, true, NULL, triggeredByAura); + } break; } // Judgements of the Wise @@ -2401,7 +2457,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // At melee attack or Hammer of the Righteous spell damage considered as melee attack if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595)) + { triggered_spell_id = 53742; // Blood Corruption + } // Add 5-stack effect from Blood Corruption uint32 stacks = 0; @@ -2415,7 +2473,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura } } if (stacks >= 5) + { CastSpell(target, 53739, true, NULL, triggeredByAura); + } break; } // Glyph of Holy Light @@ -2485,7 +2545,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura return SPELL_AURA_PROC_OK; } else + { triggered_spell_id = 71432; + } break; } @@ -2623,7 +2685,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // Totem of Splintering if (Aura* aura = GetAura(60764, EFFECT_INDEX_0)) + { extra_attack_power += aura->GetModifier()->m_amount; + } // Off-Hand case if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND) @@ -2642,7 +2706,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // apply cooldown before cast to prevent processing itself if (cooldown) + { ((Player*)this)->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown); + } // Attack Twice for (uint32 i = 0; i < 2; ++i) @@ -2930,12 +2996,16 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // Remove cooldown (Chain Lightning - have Category Recovery time) if (procClassOptions && procClassOptions->SpellFamilyFlags & UI64LIT(0x0000000000000002)) + { ((Player*)this)->RemoveSpellCooldown(spellId); + } CastSpell(pVictim, spellId, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } @@ -2969,7 +3039,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura } CastSpell(target, spell, true, castItem, triggeredByAura); if ((*itr)->GetHolder()->DropAuraCharge()) + { RemoveAuraHolderFromStack((*itr)->GetId()); + } return SPELL_AURA_PROC_OK; } } @@ -2995,7 +3067,9 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura // make triggered cast apply after current damage spell processing for prevent remove by it if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) + { spell->AddTriggeredSpell(63685); + } return SPELL_AURA_PROC_OK; } break; @@ -3211,10 +3285,14 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit* pVictim, uint32 damage, Aura basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL, true, castItem, triggeredByAura); else + { CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); + } if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } @@ -3236,7 +3314,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0}; if (triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE) + { basepoints[0] = triggerAmount; + } Item* castItem = triggeredByAura->GetCastItemGuid() && GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; @@ -3282,9 +3362,13 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d case 46939: // Black Bow of the Betrayer // On successful melee or ranged attack gain 8 mana and if possible drain 8 mana from the target. if (IsAlive()) + { CastSpell(this, 29471, true, castItem, triggeredByAura); + } if (pVictim && pVictim->IsAlive()) + { CastSpell(pVictim, 27526, true, castItem, triggeredByAura); + } return SPELL_AURA_PROC_OK; case 31255: // Deadly Swiftness (Rank 1) { @@ -3390,7 +3474,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d case 64148: // Diminsh Power { if (Unit* caster = triggeredByAura->GetCaster()) + { caster->InterruptNonMeleeSpells(false); + } return SPELL_AURA_PROC_OK; } case 64415: // // Val'anyr Hammer of Ancient Kings - Equip Effect @@ -3408,7 +3494,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d // need scale damage base at stack size if (SpellEntry const* trigEntry = sSpellStore.LookupEntry(trigger_spell_id)) + { basepoints[EFFECT_INDEX_0] = trigEntry->CalculateSimpleValue(EFFECT_INDEX_0) * triggeredByAura->GetStackAmount(); + } break; } @@ -3425,7 +3513,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d // need scale damage base at stack size if (SpellEntry const* trigEntry = sSpellStore.LookupEntry(trigger_spell_id)) + { basepoints[EFFECT_INDEX_0] = trigEntry->CalculateSimpleValue(EFFECT_INDEX_0) * triggeredByAura->GetStackAmount(); + } break; } @@ -3518,9 +3608,13 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d float weaponDamage; // DW should benefit of attack power, damage percent mods etc. if (haveOffhandWeapon() && getAttackTimer(BASE_ATTACK) > getAttackTimer(OFF_ATTACK)) + { weaponDamage = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE)) / 2; + } else + { weaponDamage = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE)) / 2; + } switch (auraSpellInfo->Id) { @@ -3668,11 +3762,15 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d target = this; // increase healing factor with each critical strike. Patch 3.0.2 if (Aura* old_aura = GetAura(trigger_spell_id, EFFECT_INDEX_0)) + { basepoints[0] += old_aura->GetModifier()->m_amount; + } } // Glyph of Shadow Word: Pain else if (auraSpellInfo->Id == 55681) + { basepoints[0] = triggerAmount * GetCreateMana() / 100; + } break; } case SPELLFAMILY_DRUID: @@ -3942,7 +4040,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d } // Damage from Lightning Shield (The Ten Storms set) else if (auraSpellInfo->Id == 23552) + { trigger_spell_id = 27635; + } // Mana Surge (The Earthfury set) else if (auraSpellInfo->Id == 23572) { @@ -3965,7 +4065,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d } if (pVictim && pVictim->IsAlive()) + { pVictim->GetThreatManager().modifyThreatPercent(this, -10); + } basepoints[0] = triggerAmount * GetMaxHealth() / 100; trigger_spell_id = 31616; @@ -4104,7 +4206,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later. int32 curBonus = 0; if (Aura* aur = owner->GetAura(48090, EFFECT_INDEX_0)) + { curBonus = aur->GetModifier()->m_amount; + } int32 spellDamage = owner->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_MAGIC) - curBonus; if (spellDamage <= 0) { @@ -4128,7 +4232,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d { // Remove cooldown on Shield Slam if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->RemoveSpellCategoryCooldown(1209, true); + } break; } // Maelstrom Weapon @@ -4216,7 +4322,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d { // Howling Blast cooldown reset if (GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->RemoveSpellCategoryCooldown(1248, true); + } break; } // Druid - Savage Defense @@ -4234,7 +4342,9 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d // try detect target manually if not set if (target == NULL) + { target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim; + } // default case if (!target || (target != this && !target->IsAlive())) @@ -4249,10 +4359,14 @@ SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit* pVictim, uint32 d basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL, true, castItem, triggeredByAura); else + { CastSpell(target, trigger_spell_id, true, castItem, triggeredByAura); + } if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(trigger_spell_id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } @@ -4399,7 +4513,9 @@ SpellAuraProcResult Unit::HandleOverrideClassScriptAuraProc(Unit* pVictim, uint3 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } @@ -4421,9 +4537,13 @@ SpellAuraProcResult Unit::HandleMendingAuraProc(Unit* /*pVictim*/, uint32 /*dama SpellEffectEntry const* spellEffect = spellProto->GetSpellEffect(effIdx); float radius; if (spellEffect && spellEffect->GetRadiusIndex()) + { radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellEffect->GetRadiusIndex())); + } else + { radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->GetRangeIndex())); + } if (Player* caster = ((Player*)triggeredByAura->GetCaster())) { @@ -4438,7 +4558,9 @@ SpellAuraProcResult Unit::HandleMendingAuraProc(Unit* /*pVictim*/, uint32 /*dama { Aura* aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); if (!aur) + { continue; + } int32 basePoints = aur->GetBasePoints(); Aura* new_aur = CreateAura(spellProto, aur->GetEffIndex(), &basePoints, new_holder, target, caster); @@ -4539,7 +4661,9 @@ SpellAuraProcResult Unit::HandleAddPctModifierAuraProc(Unit* /*pVictim*/, uint32 { // last charge and crit if (triggeredByAura->GetHolder()->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT)) + { return SPELL_AURA_PROC_OK; // charge counting (will removed) + } CastSpell(this, 28682, true, castItem, triggeredByAura); return (procEx & PROC_EX_CRITICAL_HIT) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; // charge update only at crit hits, no hidden cooldowns @@ -4556,7 +4680,9 @@ SpellAuraProcResult Unit::HandleAddPctModifierAuraProc(Unit* /*pVictim*/, uint32 { SpellEffectEntry const* spellEffect = procSpell->GetSpellEffect(SpellEffectIndex(i)); if(!spellEffect) + { continue; + } if (spellEffect->Effect == SPELL_EFFECT_ENERGIZE) { int32 mana = procSpell->CalculateSimpleValue(SpellEffectIndex(i)); @@ -4691,7 +4817,9 @@ SpellAuraProcResult Unit::HandleManaShieldAuraProc(Unit* pVictim, uint32 /*damag CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) + { ((Player*)this)->AddSpellCooldown(triggered_spell_id, 0, time(NULL) + cooldown); + } return SPELL_AURA_PROC_OK; } diff --git a/src/game/WorldHandlers/VehicleHandler.cpp b/src/game/WorldHandlers/VehicleHandler.cpp index 3dcf80033..9a91685e2 100644 --- a/src/game/WorldHandlers/VehicleHandler.cpp +++ b/src/game/WorldHandlers/VehicleHandler.cpp @@ -75,7 +75,9 @@ void WorldSession::HandleRequestVehicleExit(WorldPacket& recvPacket) // Check for exit flag if (VehicleSeatEntry const* seatEntry = vehicle->GetVehicleInfo()->GetSeatEntry(transportInfo->GetTransportSeat())) if (seatEntry->m_flags & SEAT_FLAG_CAN_EXIT) + { vehicle->RemoveSpellsCausingAura(SPELL_AURA_CONTROL_VEHICLE, _player->GetObjectGuid()); + } } void WorldSession::HandleRequestVehicleSwitchSeat(WorldPacket& recvPacket) @@ -154,10 +156,14 @@ void WorldSession::HandleChangeSeatsOnControlledVehicle(WorldPacket& recvPacket) SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(destVehicle->GetEntry()); for (SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr) if (itr->second.IsFitToRequirements(_player, destVehicle->GetTypeId() == TYPEID_UNIT ? (Creature*)destVehicle : NULL)) + { _player->CastSpell(destVehicle, itr->second.spellId, true); + } } else + { srcVehicle->GetVehicleInfo()->SwitchSeat(_player, seat); + } } void WorldSession::HandleRideVehicleInteract(WorldPacket& recvPacket) @@ -216,7 +222,9 @@ void WorldSession::HandleEjectPassenger(WorldPacket& recvPacket) // Check for eject flag if (VehicleSeatEntry const* seatEntry = vehicleInfo->GetSeatEntry(passenger->GetTransportInfo()->GetTransportSeat())) if (seatEntry->m_flagsB & VEHICLE_SEAT_FLAG_B_EJECTABLE) + { _player->RemoveSpellsCausingAura(SPELL_AURA_CONTROL_VEHICLE, passengerGuid); + } } void WorldSession::HandleRequestVehiclePrevSeat(WorldPacket& recv_data) diff --git a/src/game/WorldHandlers/WaypointManager.cpp b/src/game/WorldHandlers/WaypointManager.cpp index 9ca013d79..99e51b7b2 100644 --- a/src/game/WorldHandlers/WaypointManager.cpp +++ b/src/game/WorldHandlers/WaypointManager.cpp @@ -142,7 +142,9 @@ void WaypointManager::Load() } if (cData->movementType != WAYPOINT_MOTION_TYPE) + { creatureNoMoveType.insert(id); + } WaypointPath& path = m_pathTemplateMap[id << 8]; WaypointNode& node = path[point]; @@ -219,7 +221,9 @@ void WaypointManager::Load() if (be.emote) { if (!sEmotesStore.LookupEntry(be.emote)) + { sLog.outErrorDb("Waypoint path %u (Point %u) are using emote %u, but emote does not exist.", id, point, be.emote); + } } // save memory by not storing empty behaviors @@ -229,7 +233,9 @@ void WaypointManager::Load() ++total_behaviors; } else + { node.behavior = NULL; + } } while (result->NextRow()); @@ -380,7 +386,9 @@ void WaypointManager::Load() if (be.emote) { if (!sEmotesStore.LookupEntry(be.emote)) + { sLog.outErrorDb("Waypoint template path %u (point %u) are using emote %u, but emote does not exist.", entry, point, be.emote); + } } // save memory by not storing empty behaviors @@ -390,7 +398,9 @@ void WaypointManager::Load() ++total_behaviors; } else + { node.behavior = NULL; + } } while (result->NextRow()); @@ -478,9 +488,13 @@ WaypointNode const* WaypointManager::AddNode(uint32 entry, uint32 dbGuid, uint32 WaypointPath& path = (*wpMap)[key]; if (pointId == 0 && !path.empty()) // Start with highest waypoint + { pointId = path.rbegin()->first + 1; + } else if (pointId == 0) + { pointId = 1; + } uint32 nextPoint = pointId; WaypointNode temp = WaypointNode(x, y, z, 100, 0, 0, NULL); @@ -504,7 +518,9 @@ WaypointNode const* WaypointManager::AddNode(uint32 entry, uint32 dbGuid, uint32 for (WaypointPath::reverse_iterator rItr = path.rbegin(); rItr != path.rend() && rItr->first > pointId; ++rItr) { if (rItr->first <= nextPoint) + { WorldDatabase.PExecuteLog("UPDATE `%s` SET `point`=`point`+1 WHERE `%s`=%u AND `point`=%u", table, key_field, key, rItr->first - 1); + } } // Insert new Point to database WorldDatabase.PExecuteLog("INSERT INTO `%s` (`%s`,`point`,`position_x`,`position_y`,`position_z`,`orientation`) VALUES (%u,%u, %f,%f,%f, 100)", table, key_field, key, pointId, x, y, z); @@ -539,7 +555,9 @@ void WaypointManager::DeletePath(uint32 id) WorldDatabase.PExecuteLog("DELETE FROM `creature_movement` WHERE `id`=%u", id); WaypointPathMap::iterator itr = m_pathMap.find(id); if (itr != m_pathMap.end()) + { _clearPath(itr->second); + } // the path is not removed from the map, just cleared // WMGs have pointers to the path, so deleting them would crash // this wastes some memory, but these functions are @@ -595,7 +613,9 @@ void WaypointManager::SetNodeWaittime(uint32 entry, uint32 dbGuid, uint32 point, WaypointPath::iterator find = path->find(point); if (find != path->end()) + { find->second.delay = waittime; + } } void WaypointManager::SetNodeOrientation(uint32 entry, uint32 dbGuid, uint32 point, int32 pathId, WaypointPathOrigin wpOrigin, float orientation) @@ -619,7 +639,9 @@ void WaypointManager::SetNodeOrientation(uint32 entry, uint32 dbGuid, uint32 poi WaypointPath::iterator find = path->find(point); if (find != path->end()) + { find->second.orientation = orientation; + } } /// return true if a valid scriptId is provided @@ -644,7 +666,9 @@ bool WaypointManager::SetNodeScriptId(uint32 entry, uint32 dbGuid, uint32 point, WaypointPath::iterator find = path->find(point); if (find != path->end()) + { find->second.script_id = scriptId; + } ScriptChainMap const* scm = sScriptMgr.GetScriptChainMap(DBS_ON_CREATURE_MOVEMENT); if (!scm) @@ -691,13 +715,17 @@ void WaypointManager::CheckTextsExistance(std::set& ids) { for (WaypointPath::const_iterator pItr = pmItr->second.begin(); pItr != pmItr->second.end(); ++pItr) if (pItr->second.behavior) + { CheckWPText(false, pmItr->first, pItr->first, pItr->second.behavior, ids); + } } for (WaypointPathMap::const_iterator pmItr = m_pathTemplateMap.begin(); pmItr != m_pathTemplateMap.end(); ++pmItr) { for (WaypointPath::const_iterator pItr = pmItr->second.begin(); pItr != pmItr->second.end(); ++pItr) if (pItr->second.behavior) + { CheckWPText(true, pmItr->first, pItr->first, pItr->second.behavior, ids); + } } } diff --git a/src/game/WorldHandlers/WaypointManager.h b/src/game/WorldHandlers/WaypointManager.h index 90b7c12b4..8ad1f7907 100644 --- a/src/game/WorldHandlers/WaypointManager.h +++ b/src/game/WorldHandlers/WaypointManager.h @@ -94,14 +94,18 @@ class WaypointManager WaypointPath* path = GetPath(lowGuid); path = GetPath(lowGuid); if (path && wpOrigin) + { *wpOrigin = PATH_FROM_GUID; + } // No movement found for guid if (!path) { path = GetPathTemplate(entry); if (path && wpOrigin) + { *wpOrigin = PATH_FROM_ENTRY; + } } return path; diff --git a/src/game/WorldHandlers/Weather.cpp b/src/game/WorldHandlers/Weather.cpp index 95e35aae5..f3a33b0b3 100644 --- a/src/game/WorldHandlers/Weather.cpp +++ b/src/game/WorldHandlers/Weather.cpp @@ -169,13 +169,21 @@ bool Weather::ReGenerate() uint32 rnd = urand(1, 100); if (rnd <= chance1) + { m_type = WEATHER_TYPE_RAIN; + } else if (rnd <= chance2) + { m_type = WEATHER_TYPE_SNOW; + } else if (rnd <= chance3) + { m_type = WEATHER_TYPE_STORM; + } else + { m_type = WEATHER_TYPE_FINE; + } /// New weather statistics (if not fine): ///- 85% light @@ -258,9 +266,13 @@ bool Weather::UpdateWeather() ///- Send the weather packet to all players in this zone if (m_grade >= 1) + { m_grade = 0.9999f; + } else if (m_grade < 0) + { m_grade = 0.0001f; + } WeatherState state = GetWeatherState(); @@ -499,7 +511,9 @@ void WeatherSystem::UpdateWeathers(uint32 diff) m_weathers.erase(itr++); } else + { ++itr; + } } } diff --git a/src/game/WorldHandlers/Weather.h b/src/game/WorldHandlers/Weather.h index 62d40a429..db857a87c 100644 --- a/src/game/WorldHandlers/Weather.h +++ b/src/game/WorldHandlers/Weather.h @@ -158,9 +158,13 @@ class WeatherMgr { WeatherZoneMap::const_iterator itr = mWeatherZoneMap.find(zone_id); if (itr != mWeatherZoneMap.end()) + { return &itr->second; + } else + { return NULL; + } } private: diff --git a/src/game/WorldHandlers/World.cpp b/src/game/WorldHandlers/World.cpp index fbcdefb65..77606b700 100644 --- a/src/game/WorldHandlers/World.cpp +++ b/src/game/WorldHandlers/World.cpp @@ -199,10 +199,14 @@ Player* World::FindPlayerInZone(uint32 zone) for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) { if (!itr->second) + { continue; + } Player* player = itr->second->GetPlayer(); if (!player) + { continue; + } if (player->IsInWorld() && player->GetZoneId() == zone) { // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone. @@ -760,7 +764,9 @@ void World::LoadConfigSettings(bool reload) setConfig(CONFIG_BOOL_WEATHER, "ActivateWeather", true); if (configNoReload(reload, CONFIG_UINT32_EXPANSION, "Expansion", MAX_EXPANSION)) + { setConfigMinMax(CONFIG_UINT32_EXPANSION, "Expansion", MAX_EXPANSION, 0, MAX_EXPANSION); + } setConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT, "ChatFlood.MessageCount", 10); setConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY, "ChatFlood.MessageDelay", 1); @@ -814,9 +820,13 @@ void World::LoadConfigSettings(bool reload) // always use declined names in the russian client if (getConfig(CONFIG_UINT32_REALM_ZONE) == REALM_ZONE_RUSSIAN) + { setConfig(CONFIG_BOOL_DECLINED_NAMES_USED, true); + } else + { setConfig(CONFIG_BOOL_DECLINED_NAMES_USED, "DeclinedNames", false); + } setConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER, "Battleground.CastDeserter", true); setConfigMinMax(CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN, "Battleground.QueueAnnouncer.Join", 0, 0, 2); @@ -856,7 +866,9 @@ void World::LoadConfigSettings(bool reload) sLog.outString("Client cache version set to: %u", clientCacheId); } else + { sLog.outError("ClientCacheVersion can't be negative %d, ignored.", clientCacheId); + } } setConfig(CONFIG_UINT32_INSTANT_LOGOUT, "InstantLogout", SEC_MODERATOR); @@ -1835,7 +1847,9 @@ void World::Update(uint32 diff) /// Handle daily quests reset time if (m_gameTime > m_NextDailyQuestReset) + { ResetDailyQuests(); + } ///
  • Handle auctions when the timer has passed if (m_timers[WUPDATE_AUCTIONS].Passed()) @@ -2409,9 +2423,13 @@ void World::InitWeeklyQuestResetTime() { QueryResult* result = CharacterDatabase.Query("SELECT `NextWeeklyQuestResetTime` FROM `saved_variables`"); if (!result) + { m_NextWeeklyQuestReset = time_t(time(NULL)); // game time not yet init + } else + { m_NextWeeklyQuestReset = time_t((*result)[0].GetUInt64()); + } // generate time by config time_t curTime = time(NULL); @@ -2428,24 +2446,34 @@ void World::InitWeeklyQuestResetTime() // next reset time before current moment if (curTime >= nextWeekResetTime) + { nextWeekResetTime += WEEK; + } // normalize reset time m_NextWeeklyQuestReset = m_NextWeeklyQuestReset < curTime ? nextWeekResetTime - WEEK : nextWeekResetTime; if (!result) + { CharacterDatabase.PExecute("INSERT INTO `saved_variables` (`NextWeeklyQuestResetTime`) VALUES ('" UI64FMTD "')", uint64(m_NextWeeklyQuestReset)); + } else + { delete result; + } } void World::InitDailyQuestResetTime() { QueryResult* result = CharacterDatabase.Query("SELECT `NextDailyQuestResetTime` FROM `saved_variables`"); if (!result) + { m_NextDailyQuestReset = time_t(time(NULL)); // game time not yet init + } else + { m_NextDailyQuestReset = time_t((*result)[0].GetUInt64()); + } // generate time by config time_t curTime = time(NULL); @@ -2459,15 +2487,21 @@ void World::InitDailyQuestResetTime() // next reset time before current moment if (curTime >= nextDayResetTime) + { nextDayResetTime += DAY; + } // normalize reset time m_NextDailyQuestReset = m_NextDailyQuestReset < curTime ? nextDayResetTime - DAY : nextDayResetTime; if (!result) + { CharacterDatabase.PExecute("INSERT INTO `saved_variables` (`NextDailyQuestResetTime`) VALUES ('" UI64FMTD "')", uint64(m_NextDailyQuestReset)); + } else + { delete result; + } } void World::SetMonthlyQuestResetTime(bool initialize) @@ -2477,9 +2511,13 @@ void World::SetMonthlyQuestResetTime(bool initialize) QueryResult* result = CharacterDatabase.Query("SELECT `NextMonthlyQuestResetTime` FROM `saved_variables`"); if (!result) + { m_NextMonthlyQuestReset = time_t(time(NULL)); + } else + { m_NextMonthlyQuestReset = time_t((*result)[0].GetUInt64()); + } delete result; } @@ -2520,9 +2558,13 @@ void World::InitCurrencyResetTime() { QueryResult* result = CharacterDatabase.Query("SELECT `NextCurrenciesResetTime` FROM `saved_variables`"); if (!result) + { m_NextCurrencyReset = time_t(time(NULL)); // game time not yet init + } else + { m_NextCurrencyReset = time_t((*result)[0].GetUInt64()); + } // re-init case or not exists if (!m_NextCurrencyReset) @@ -2542,25 +2584,35 @@ void World::InitCurrencyResetTime() // next reset time before current moment if (curTime >= nextWeekResetTime) + { nextWeekResetTime += getConfig(CONFIG_UINT32_CURRENCY_RESET_INTERVAL) * DAY; + } // normalize reset time m_NextCurrencyReset = m_NextCurrencyReset < curTime ? nextWeekResetTime - getConfig(CONFIG_UINT32_CURRENCY_RESET_INTERVAL) * DAY : nextWeekResetTime; } if (!result) + { CharacterDatabase.PExecute("INSERT INTO `saved_variables` (`NextCurrenciesResetTime`) VALUES ('" UI64FMTD "')", uint64(m_NextCurrencyReset)); + } else + { delete result; + } } void World::InitRandomBGResetTime() { QueryResult * result = CharacterDatabase.Query("SELECT `NextRandomBGResetTime` FROM `saved_variables`"); if (!result) + { m_NextRandomBGReset = time_t(time(NULL)); // game time not yet init + } else + { m_NextRandomBGReset = time_t((*result)[0].GetUInt64()); + } // generate time by config time_t curTime = time(NULL); @@ -2574,14 +2626,20 @@ void World::InitRandomBGResetTime() // next reset time before current moment if (curTime >= nextDayResetTime) + { nextDayResetTime += DAY; + } // normalize reset time m_NextRandomBGReset = m_NextRandomBGReset < curTime ? nextDayResetTime - DAY : nextDayResetTime; if (!result) + { CharacterDatabase.PExecute("INSERT INTO `saved_variables` (`NextRandomBGResetTime`) VALUES ('" UI64FMTD "')", uint64(m_NextRandomBGReset)); + } else + { delete result; + } } void World::ResetDailyQuests() @@ -2590,7 +2648,9 @@ void World::ResetDailyQuests() CharacterDatabase.Execute("DELETE FROM `character_queststatus_daily`"); for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) if (itr->second->GetPlayer()) + { itr->second->GetPlayer()->ResetDailyQuestStatus(); + } m_NextDailyQuestReset = time_t(m_NextDailyQuestReset + DAY); CharacterDatabase.PExecute("UPDATE `saved_variables` SET `NextDailyQuestResetTime` = '" UI64FMTD "'", uint64(m_NextDailyQuestReset)); @@ -2602,7 +2662,9 @@ void World::ResetWeeklyQuests() CharacterDatabase.Execute("DELETE FROM `character_queststatus_weekly`"); for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) if (itr->second->GetPlayer()) + { itr->second->GetPlayer()->ResetWeeklyQuestStatus(); + } m_NextWeeklyQuestReset = time_t(m_NextWeeklyQuestReset + WEEK); CharacterDatabase.PExecute("UPDATE `saved_variables` SET `NextWeeklyQuestResetTime` = '" UI64FMTD "'", uint64(m_NextWeeklyQuestReset)); @@ -2615,7 +2677,9 @@ void World::ResetMonthlyQuests() for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) if (itr->second->GetPlayer()) + { itr->second->GetPlayer()->ResetMonthlyQuestStatus(); + } SetMonthlyQuestResetTime(false); } @@ -2626,7 +2690,9 @@ void World::ResetCurrencyWeekCounts() for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr) if (itr->second->GetPlayer()) + { itr->second->GetPlayer()->ResetCurrencyWeekCounts(); + } for(ObjectMgr::ArenaTeamMap::iterator titr = sObjectMgr.GetArenaTeamMapBegin(); titr != sObjectMgr.GetArenaTeamMapEnd(); ++titr) { @@ -2970,7 +3036,9 @@ void World::LoadBroadcastStrings() uint32 ratio = fields[2].GetUInt32(); if (ratio == 0) - continue; + { + continue; + } m_broadcastWeight += ratio; @@ -3005,7 +3073,9 @@ void World::AutoBroadcast() for (it = m_broadcastList.begin(); it != m_broadcastList.end(); ++it) { if (rn <= it->freq) - break; + { + break; + } } SendWorldText(LANG_AUTOBROADCAST, it->text.c_str()); } diff --git a/src/game/movement/MoveSpline.cpp b/src/game/movement/MoveSpline.cpp index cfd625d95..378ddb0f3 100644 --- a/src/game/movement/MoveSpline.cpp +++ b/src/game/movement/MoveSpline.cpp @@ -48,9 +48,13 @@ namespace Movement spline.evaluate_percent(point_Idx, u, c); if (splineflags.animation) + { ;// MoveSplineFlag::Animation disables falling or parabolic movement + } else if (splineflags.parabolic) + { computeParabolicElevation(c.z); + } else if (splineflags.falling) { computeFallElevation(c.z); @@ -78,7 +82,9 @@ namespace Movement } if (splineflags.orientationInversed) + { c.orientation = -c.orientation; + } } return c; } diff --git a/src/game/movement/MoveSpline.h b/src/game/movement/MoveSpline.h index 436df66a6..9a5ce7f25 100644 --- a/src/game/movement/MoveSpline.h +++ b/src/game/movement/MoveSpline.h @@ -228,7 +228,9 @@ namespace Movement { MANGOS_ASSERT(Initialized()); do - { handler(_updateState(difftime)); } + { + handler(_updateState(difftime)); + } while (difftime > 0); } diff --git a/src/game/movement/MoveSplineInit.cpp b/src/game/movement/MoveSplineInit.cpp index 9fb2d20ec..9f39b2269 100644 --- a/src/game/movement/MoveSplineInit.cpp +++ b/src/game/movement/MoveSplineInit.cpp @@ -76,7 +76,9 @@ namespace Movement // If boarded use current local position if (transportInfo) + { transportInfo->GetLocalPosition(real_position.x, real_position.y, real_position.z, real_position.orientation); + } // there is a big chance that current position is unknown if current state is not finalized, need compute it // this also allows calculate spline position and update map position in much greater intervals @@ -97,9 +99,13 @@ namespace Movement uint32 moveFlags = unit.m_movementInfo.GetMovementFlags(); if (args.flags.walkmode) + { moveFlags |= MOVEFLAG_WALK_MODE; + } else + { moveFlags &= ~MOVEFLAG_WALK_MODE; + } moveFlags |= MOVEFLAG_FORWARD; @@ -148,12 +154,16 @@ namespace Movement // If boarded use current local position if (transportInfo) + { transportInfo->GetLocalPosition(real_position.x, real_position.y, real_position.z, real_position.orientation); + } // there is a big chance that current position is unknown if current state is not finalized, need compute it // this also allows calculate spline position and update map position in much greater intervals if (!move_spline.Finalized() && !transportInfo) + { real_position = move_spline.ComputePosition(); + } if (args.path.empty()) { diff --git a/src/game/movement/packet_builder.cpp b/src/game/movement/packet_builder.cpp index a823ee1fb..dbb9aab89 100644 --- a/src/game/movement/packet_builder.cpp +++ b/src/game/movement/packet_builder.cpp @@ -150,7 +150,9 @@ namespace Movement bool hasFullSpline = !move_spline.Finalized(); data.WriteBit(hasFullSpline); if (!hasFullSpline) + { return; + } MoveSplineFlag splineFlags = move_spline.splineflags; uint32 nodes = move_spline.getPath().size(); @@ -207,26 +209,36 @@ namespace Movement if (hasUnkSplineCounter) { for (int i = 0; i < unkSplineCounter; ++i) + { data << float(0.0f) << float(0.0f); + } } if (move_spline.splineflags & MoveSplineFlag::Final_Target) + { data.WriteGuidBytes<3, 2, 0, 5, 6, 7, 4, 1>(ObjectGuid(move_spline.facing.target)); + } data << int32(move_spline.timePassed()); data << int32(move_spline.Duration()); if (hasSplineVerticalAcceleration) + { data << float(move_spline.vertical_acceleration); // added in 3.1 + } data << float(1.f); data << float(1.f); if (move_spline.splineflags & MoveSplineFlag::Final_Point) + { data << float(move_spline.facing.f.x) << float(move_spline.facing.f.z) << float(move_spline.facing.f.y); + } if (hasSplineStartTime) + { data << int32(move_spline.effect_start_time); // added in 3.1 + } for (uint32 i = 0; i < nodes; ++i) { @@ -236,7 +248,9 @@ namespace Movement } if (move_spline.splineflags & MoveSplineFlag::Final_Angle) + { data << float(NormalizeOrientation(move_spline.facing.angle)); + } } if (!move_spline.isCyclic()) @@ -247,7 +261,9 @@ namespace Movement data << float(dest.y); } else + { data << Vector3::zero(); + } data << uint32(move_spline.GetId()); } diff --git a/src/game/movement/spline.h b/src/game/movement/spline.h index 0d36b3d60..e4a3b22a7 100644 --- a/src/game/movement/spline.h +++ b/src/game/movement/spline.h @@ -468,7 +468,9 @@ namespace Movement new_length = cacher(*this, i); if (new_length < 0) // length overflowed, assign to max positive value (stop case only?) + { new_length = std::numeric_limits::max(); + } lengths[++i] = new_length; diff --git a/src/game/movement/spline.impl.h b/src/game/movement/spline.impl.h index 62b0cacaa..08c1f8bde 100644 --- a/src/game/movement/spline.impl.h +++ b/src/game/movement/spline.impl.h @@ -70,9 +70,13 @@ namespace Movement while ((lengths[i] > length) || (lengths[i + 1] <= length)) { if (lengths[i] > length) + { hi = i - 1; // too big + } else if (lengths[i + 1] <= length) + { lo = i + 1; // too small + } i = (hi + lo) / 2; }*/ @@ -80,7 +84,9 @@ namespace Movement index_type i = index_lo; index_type N = index_hi; while (i + 1 < N && lengths[i + 1] < length_) - { ++i; } + { + ++i; + } return i; } diff --git a/src/game/vmap/BIH.h b/src/game/vmap/BIH.h index a4d67cc41..26c89680f 100644 --- a/src/game/vmap/BIH.h +++ b/src/game/vmap/BIH.h @@ -313,7 +313,9 @@ class BIH else { if (axis > 2) - { return; } // should not happen + { + return; // should not happen + } float tf = (intBitsToFloat(tree[node + offsetFront[axis]]) - org[axis]) * invDir[axis]; float tb = (intBitsToFloat(tree[node + offsetBack[axis]]) - org[axis]) * invDir[axis]; node = offset; @@ -421,7 +423,9 @@ class BIH else // BVH2 node (empty space cut off left and right) { if (axis > 2) - { return; } // should not happen + { + return; // should not happen + } float tl = intBitsToFloat(tree[node + 1]); float tr = intBitsToFloat(tree[node + 2]); node = offset; diff --git a/src/game/vmap/MapTree.cpp b/src/game/vmap/MapTree.cpp index bf6b171af..b0b6d07ec 100644 --- a/src/game/vmap/MapTree.cpp +++ b/src/game/vmap/MapTree.cpp @@ -170,7 +170,9 @@ namespace VMAP // return false if distance is over max float, in case of cheater teleporting to the end of the universe if (maxDist == std::numeric_limits::max() || maxDist == std::numeric_limits::infinity()) - { return false; } + { + return false; + } // valid map coords should *never ever* produce float overflow, but this would produce NaNs too: MANGOS_ASSERT(maxDist < std::numeric_limits::max()); diff --git a/src/game/vmap/TileAssembler.cpp b/src/game/vmap/TileAssembler.cpp index 616acda6b..3bc9fbb2d 100644 --- a/src/game/vmap/TileAssembler.cpp +++ b/src/game/vmap/TileAssembler.cpp @@ -424,7 +424,9 @@ namespace VMAP { if (fread(&displayId, sizeof(uint32), 1, model_list) != 1) if (feof(model_list)) // EOF flag is only set after failed reading attempt + { break; + } if (fread(&name_length, sizeof(uint32), 1, model_list) != 1 || name_length >= sizeof(buff) diff --git a/src/game/vmap/VMapFactory.cpp b/src/game/vmap/VMapFactory.cpp index 2a59e5a8d..e9b2dd13c 100644 --- a/src/game/vmap/VMapFactory.cpp +++ b/src/game/vmap/VMapFactory.cpp @@ -122,7 +122,9 @@ namespace VMAP IVMapManager* VMapFactory::createOrGetVMapManager() { if (gVMapManager == 0) - { gVMapManager = new VMapManager2(); } // should be taken from config ... Please change if you like :-) + { + gVMapManager = new VMapManager2(); // should be taken from config ... Please change if you like :-) + } return gVMapManager; } diff --git a/src/mangosd/SOAP/SoapThread.cpp b/src/mangosd/SOAP/SoapThread.cpp index 6884448f3..3ec75308e 100644 --- a/src/mangosd/SOAP/SoapThread.cpp +++ b/src/mangosd/SOAP/SoapThread.cpp @@ -41,13 +41,19 @@ struct SOAPCommand { public: void appendToPrintBuffer(const char* msg) - { m_printBuffer += msg; } + { + m_printBuffer += msg; + } void setCommandSuccess(bool val) - { m_success = val; } + { + m_success = val; + } bool hasCommandSucceeded() - { return m_success; } + { + return m_success; + } static void print(void* callbackArg, const char* msg) { @@ -101,7 +107,9 @@ class SoapPool : public ACE_Task SoapThread::~SoapThread() { if(pool_) + { delete pool_; + } } int SoapThread::open(void* unused) diff --git a/src/shared/Auth/AuthCrypt.cpp b/src/shared/Auth/AuthCrypt.cpp index 3793c5e1c..97d68ae35 100644 --- a/src/shared/Auth/AuthCrypt.cpp +++ b/src/shared/Auth/AuthCrypt.cpp @@ -71,7 +71,9 @@ void AuthCrypt::Init(BigNumber* K) void AuthCrypt::DecryptRecv(uint8* data, size_t len) { if (!_initialized) + { return; + } _clientDecrypt.UpdateData(len, data); } @@ -79,7 +81,9 @@ void AuthCrypt::DecryptRecv(uint8* data, size_t len) void AuthCrypt::EncryptSend(uint8* data, size_t len) { if (!_initialized) + { return; + } _serverEncrypt.UpdateData(len, data); } diff --git a/src/shared/Auth/BigNumber.cpp b/src/shared/Auth/BigNumber.cpp index a049ce2c7..2086b80f7 100644 --- a/src/shared/Auth/BigNumber.cpp +++ b/src/shared/Auth/BigNumber.cpp @@ -206,12 +206,16 @@ uint8 *BigNumber::AsByteArray(int minSize, bool reverse) // If we need more bytes than length of BigNumber set the rest to 0 if (length > numBytes) + { memset((void*)_array, 0, length); + } BN_bn2bin(_bn, (unsigned char*)_array); if (reverse) + { std::reverse(_array, _array + numBytes); + } return _array; } diff --git a/src/shared/Auth/WardenKeyGeneration.h b/src/shared/Auth/WardenKeyGeneration.h index dd7b9ee12..ae262ea5f 100644 --- a/src/shared/Auth/WardenKeyGeneration.h +++ b/src/shared/Auth/WardenKeyGeneration.h @@ -57,7 +57,9 @@ public: for (uint32 i = 0; i < sz; ++i) { if (taken == 20) + { FillUp(); + } buf[i] = o0[taken]; taken++; diff --git a/src/shared/Config/Config.cpp b/src/shared/Config/Config.cpp index f7c2a4d43..98e93ca0e 100644 --- a/src/shared/Config/Config.cpp +++ b/src/shared/Config/Config.cpp @@ -113,7 +113,9 @@ bool Config::GetBoolDefault(const char* name, bool def) if (strcmp(str, "true") == 0 || strcmp(str, "TRUE") == 0 || strcmp(str, "yes") == 0 || strcmp(str, "YES") == 0 || strcmp(str, "1") == 0) - { return true; } + { + return true; + } else { return false; diff --git a/src/shared/DataStores/DB2FileLoader.cpp b/src/shared/DataStores/DB2FileLoader.cpp index 077be18fc..fd8941647 100644 --- a/src/shared/DataStores/DB2FileLoader.cpp +++ b/src/shared/DataStores/DB2FileLoader.cpp @@ -156,9 +156,13 @@ bool DB2FileLoader::Load(const char *filename, const char *fmt) { fieldsOffset[i] = fieldsOffset[i - 1]; if (fmt[i - 1] == 'b' || fmt[i - 1] == 'X') // byte fields + { fieldsOffset[i] += 1; + } else // 4 byte fields (int32/float/strings) + { fieldsOffset[i] += 4; + } } data = new unsigned char[recordSize*recordCount+stringSize]; @@ -177,9 +181,13 @@ bool DB2FileLoader::Load(const char *filename, const char *fmt) DB2FileLoader::~DB2FileLoader() { if(data) + { delete [] data; + } if(fieldsOffset) + { delete [] fieldsOffset; + } } DB2FileLoader::Record DB2FileLoader::getRecord(size_t id) @@ -240,7 +248,9 @@ uint32 DB2FileLoader::GetFormatStringsFields(const char * format) uint32 stringfields = 0; for(uint32 x=0; format[x];++x) if (format[x] == DBC_FF_STRING) + { ++stringfields; + } return stringfields; } diff --git a/src/shared/DataStores/DB2Store.h b/src/shared/DataStores/DB2Store.h index 1e0d7fbd5..292397a86 100644 --- a/src/shared/DataStores/DB2Store.h +++ b/src/shared/DataStores/DB2Store.h @@ -45,7 +45,9 @@ public: DB2FileLoader db2; // Check if load was sucessful, only then continue if(!db2.Load(fn, fmt)) + { return false; + } fieldCount = db2.GetCols(); @@ -66,12 +68,16 @@ public: { // DBC must be already loaded using Load if(!indexTable) + { return false; + } DB2FileLoader db2; // Check if load was successful, only then continue if(!db2.Load(fn, fmt)) + { return false; + } // load strings from another locale dbc data m_stringPoolList.push_back(db2.AutoProduceStrings(fmt,(char*)m_dataTable,loc)); @@ -82,7 +88,9 @@ public: void Clear() { if (!indexTable) + { return; + } delete[] ((char*)indexTable); indexTable = NULL; diff --git a/src/shared/DataStores/DBCFileLoader.cpp b/src/shared/DataStores/DBCFileLoader.cpp index 73b38b8a1..7368eb5a4 100644 --- a/src/shared/DataStores/DBCFileLoader.cpp +++ b/src/shared/DataStores/DBCFileLoader.cpp @@ -182,7 +182,9 @@ uint32 DBCFileLoader::GetFormatStringsFields(const char * format) uint32 stringfields = 0; for(uint32 x=0; format[x];++x) if (format[x] == DBC_FF_STRING) + { ++stringfields; + } return stringfields; } diff --git a/src/shared/DataStores/DBCStore.h b/src/shared/DataStores/DBCStore.h index f70db14b8..284d94831 100644 --- a/src/shared/DataStores/DBCStore.h +++ b/src/shared/DataStores/DBCStore.h @@ -129,7 +129,9 @@ class DBCStorage { T const* node = LookupEntry(i); if (!node) + { continue; + } data[i] = node; } loaded = true; diff --git a/src/shared/Database/Field.h b/src/shared/Database/Field.h index 6db8bdb5d..cbc01314c 100644 --- a/src/shared/Database/Field.h +++ b/src/shared/Database/Field.h @@ -169,7 +169,9 @@ class Field { int64 value = 0; if (!mValue || sscanf(mValue, SI64FMTD, &value) == -1) + { return 0; + } return value; } diff --git a/src/shared/Linux/PosixDaemon.cpp b/src/shared/Linux/PosixDaemon.cpp index 3ed7e0441..2c73a5af0 100644 --- a/src/shared/Linux/PosixDaemon.cpp +++ b/src/shared/Linux/PosixDaemon.cpp @@ -90,11 +90,17 @@ void startDaemon(uint32_t timeout) } if (!freopen("/dev/null", "rt", stdin)) + { exit(EXIT_FAILURE); + } if (!freopen("/dev/null", "wt", stdout)) + { exit(EXIT_FAILURE); + } if (!freopen("/dev/null", "wt", stderr)) + { exit(EXIT_FAILURE); + } } void stopDaemon() diff --git a/src/shared/Log/Log.cpp b/src/shared/Log/Log.cpp index f6da80e53..e8afe66ed 100644 --- a/src/shared/Log/Log.cpp +++ b/src/shared/Log/Log.cpp @@ -77,6 +77,7 @@ Log::Log() : #ifdef ENABLE_ELUNA elunaErrLogfile(NULL), #endif /* ENABLE_ELUNA */ + eventAiErLogfile(NULL), scriptErrLogFile(NULL), worldLogfile(NULL), wardenLogfile(NULL), m_colored(false), m_includeTime(false), m_gmlog_per_account(false), m_scriptLibName(NULL) { @@ -186,6 +187,7 @@ void Log::SetColor(bool stdout_stream, Color color) fprintf((stdout_stream ? stdout : stderr), "\x1b[%d%sm", UnixColorFG[color], (color >= YELLOW && color < Color_count ? ";1" : "")); #endif + } void Log::ResetColor(bool stdout_stream) @@ -196,6 +198,7 @@ void Log::ResetColor(bool stdout_stream) #else fprintf((stdout_stream ? stdout : stderr), "\x1b[0m"); #endif + } void Log::SetLogLevel(char* level) @@ -293,6 +296,7 @@ void Log::Initialize() #ifdef ENABLE_ELUNA elunaErrLogfile = openLogFile("ElunaErrorLogFile", NULL, "a"); #endif /* ENABLE_ELUNA */ + eventAiErLogfile = openLogFile("EventAIErrorLogFile", NULL, "a"); raLogfile = openLogFile("RaLogFile", NULL, "a"); worldLogfile = openLogFile("WorldLogFile", "WorldLogTimestamp", "a"); @@ -589,7 +593,9 @@ void Log::outErrorDb(const char* err, ...) void Log::outErrorEluna() { if (m_includeTime) + { outTime(); + } fprintf(stderr, "\n"); @@ -623,10 +629,14 @@ void Log::outErrorEluna(const char* err, ...) } if (m_colored) + { SetColor(false, m_colors[LogError]); + } if (m_includeTime) + { outTime(); + } va_list ap; @@ -635,7 +645,9 @@ void Log::outErrorEluna(const char* err, ...) va_end(ap); if (m_colored) + { ResetColor(false); + } fprintf(stderr, "\n"); @@ -853,7 +865,6 @@ void Log::outDetail(const char* str, ...) void Log::outDebug(const char* str, ...) { -#ifdef MANGOS_DEBUG if (!str) { return; @@ -898,7 +909,6 @@ void Log::outDebug(const char* str, ...) } fflush(stdout); -#endif } void Log::outCommand(uint32 account, const char* str, ...) @@ -994,32 +1004,36 @@ void Log::outWarden(const char* str, ...) { return; } - - if (m_colored) + if (m_logLevel >= LOG_LVL_DETAIL) { - SetColor(true, m_colors[LogNormal]); + if (m_colored) + { + SetColor(true, m_colors[LogNormal]); + } + + if (m_includeTime) + { + outTime(); + } + + va_list ap; + + va_start(ap, str); + vutf8printf(stdout, str, &ap); + va_end(ap); + + if (m_colored) + { + ResetColor(true); + } + + printf("\n"); } - if (m_includeTime) + if (wardenLogfile && m_logFileLevel >= LOG_LVL_DETAIL) { - outTime(); - } + va_list ap; - va_list ap; - - va_start(ap, str); - vutf8printf(stdout, str, &ap); - va_end(ap); - - if (m_colored) - { - ResetColor(true); - } - - printf("\n"); - - if (wardenLogfile) - { outTimestamp(wardenLogfile); fprintf(wardenLogfile, "[Warden]: "); @@ -1163,7 +1177,7 @@ void Log::outWorldPacketDump(uint32 socket, uint32 opcode, char const* opcodeNam outTimestamp(worldLogfile); - fprintf(worldLogfile, "\n%s:\nSOCKET: %u\nLENGTH: %lu\nOPCODE: %s (0x%.4X)\nDATA:\n", + fprintf(worldLogfile, "\n%s:\nSOCKET: %u\nLENGTH: " SIZEFMTD "\nOPCODE: %s (0x%.4X)\nDATA:\n", incoming ? "CLIENT" : "SERVER", socket, packet->size(), opcodeName, opcode); diff --git a/src/shared/Log/Log.h b/src/shared/Log/Log.h index e41c2ece5..cbc3e9794 100644 --- a/src/shared/Log/Log.h +++ b/src/shared/Log/Log.h @@ -28,8 +28,6 @@ #include "Common/Common.h" #include "Policies/Singleton.h" -#include - class Config; class ByteBuffer; @@ -158,7 +156,9 @@ class Log : public MaNGOS::Singleton::Instance() #define BASIC_LOG(...) \ - do { \ + do \ + { \ if (sLog.HasLogLevelOrHigher(LOG_LVL_BASIC)) \ + { \ sLog.outBasic(__VA_ARGS__); \ + } \ } while(0) #define BASIC_FILTER_LOG(F,...) \ - do { \ + do \ + { \ if (sLog.HasLogLevelOrHigher(LOG_LVL_BASIC) && !sLog.HasLogFilter(F)) \ + { \ sLog.outBasic(__VA_ARGS__); \ + } \ } while(0) #define DETAIL_LOG(...) \ - do { \ + do \ + { \ if (sLog.HasLogLevelOrHigher(LOG_LVL_DETAIL)) \ + { \ sLog.outDetail(__VA_ARGS__); \ - } while(0) + } \ + } \ + while(0) #define DETAIL_FILTER_LOG(F,...) \ - do { \ + do \ + { \ if (sLog.HasLogLevelOrHigher(LOG_LVL_DETAIL) && !sLog.HasLogFilter(F)) \ + { \ sLog.outDetail(__VA_ARGS__); \ - } while(0) + } \ + } \ + while(0) -#ifdef MANGOS_DEBUG - #define DEBUG_LOG(...) \ - do { \ +#define DEBUG_LOG(...) \ + do \ + { \ if (sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG)) \ + { \ sLog.outDebug(__VA_ARGS__); \ - } while(0) + } \ + } \ + while(0) - #define DEBUG_FILTER_LOG(F,...) \ - do { \ +#define DEBUG_FILTER_LOG(F,...) \ + do \ + { \ if (sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG) && !sLog.HasLogFilter(F)) \ + { \ sLog.outDebug(__VA_ARGS__); \ - } while(0) -#else - #define DEBUG_LOG(...) - #define DEBUG_FILTER_LOG(F,...) -#endif + } \ + } \ + while(0) #define ERROR_DB_FILTER_LOG(F,...) \ - do { \ + do \ + { \ if (!sLog.HasLogFilter(F)) \ + { \ sLog.outErrorDb(__VA_ARGS__); \ - } while(0) + } \ + } \ + while(0) #define ERROR_DB_STRICT_LOG(...) \ ERROR_DB_FILTER_LOG(LOG_FILTER_DB_STRICTED_CHECK, __VA_ARGS__) diff --git a/src/shared/Threading/DelayExecutor.cpp b/src/shared/Threading/DelayExecutor.cpp index ffd6fb50d..bd959d0f8 100644 --- a/src/shared/Threading/DelayExecutor.cpp +++ b/src/shared/Threading/DelayExecutor.cpp @@ -41,10 +41,14 @@ DelayExecutor::DelayExecutor() DelayExecutor::~DelayExecutor() { if (pre_svc_hook_) + { delete pre_svc_hook_; + } if (post_svc_hook_) + { delete post_svc_hook_; + } deactivate(); } @@ -66,21 +70,27 @@ int DelayExecutor::deactivate() int DelayExecutor::svc() { if (pre_svc_hook_) + { pre_svc_hook_->call(); + } for (;;) { ACE_Method_Request* rq = queue_.dequeue(); if (!rq) + { break; + } rq->call(); delete rq; } if (post_svc_hook_) + { post_svc_hook_->call(); + } return 0; } @@ -98,10 +108,14 @@ int DelayExecutor::activate(int num_threads, ACE_Method_Request* pre_svc_hook, A } if (pre_svc_hook_) + { delete pre_svc_hook_; + } if (post_svc_hook_) + { delete post_svc_hook_; + } pre_svc_hook_ = pre_svc_hook; post_svc_hook_ = post_svc_hook; diff --git a/src/shared/Utilities/ByteBuffer.h b/src/shared/Utilities/ByteBuffer.h index 43f195cd2..20e04df40 100644 --- a/src/shared/Utilities/ByteBuffer.h +++ b/src/shared/Utilities/ByteBuffer.h @@ -217,7 +217,9 @@ class ByteBuffer { --_bitpos; if (bit) + { _curbitval |= (1 << (_bitpos)); + } if (_bitpos == 0) { @@ -254,7 +256,9 @@ class ByteBuffer uint32 value = 0; for (int32 i = bits-1; i >= 0; --i) if (ReadBit()) + { value |= (1 << i); + } return value; } @@ -263,13 +267,17 @@ class ByteBuffer void ReadByteSeq(uint8& b) { if (b != 0) + { b ^= read(); + } } void WriteByteSeq(uint8 b) { if (b != 0) + { append(b ^ 1); + } } BitStream ReadBitStream(uint32 len) @@ -298,7 +306,9 @@ class ByteBuffer for (uint8 i = 0; i < byteCount; i++) if (guidByte[byteOrder[i + bytePos]]) + { (*this) << uint8(guidByte[byteOrder[i + bytePos]] ^ 1); + } } template @@ -689,14 +699,18 @@ class ByteBuffer uint8& operator[](size_t const pos) { if (pos >= size()) + { throw ByteBufferException(false, pos, 1, size()); + } return _storage[pos]; } uint8 const& operator[](size_t const pos) const { if (pos >= size()) + { throw ByteBufferException(false, pos, 1, size()); + } return _storage[pos]; } diff --git a/src/shared/Utilities/Util.cpp b/src/shared/Utilities/Util.cpp index 8c1af40c5..036279bb3 100644 --- a/src/shared/Utilities/Util.cpp +++ b/src/shared/Utilities/Util.cpp @@ -321,9 +321,13 @@ std::string MoneyToString(uint64 money) uint32 copp = (money % 10000) % 100; std::stringstream ss; if (gold) + { ss << gold << "g"; + } if (silv || gold) + { ss << silv << "s"; + } ss << copp << "c"; return ss.str(); diff --git a/src/shared/Win/ServiceWin32.cpp b/src/shared/Win/ServiceWin32.cpp index 9ddac2d00..8bb695033 100644 --- a/src/shared/Win/ServiceWin32.cpp +++ b/src/shared/Win/ServiceWin32.cpp @@ -207,10 +207,14 @@ void WINAPI ServiceControlHandler(DWORD controlCode) default: if (controlCode >= 128 && controlCode <= 255) // user defined control code - { break; } + { + break; + } else // unrecognized control code - { break; } + { + break; + } } SetServiceStatus(serviceStatusHandle, &serviceStatus); diff --git a/src/shared/Win/WheatyExceptionReport.cpp b/src/shared/Win/WheatyExceptionReport.cpp index 0a569e6b3..e4e3c7cb0 100644 --- a/src/shared/Win/WheatyExceptionReport.cpp +++ b/src/shared/Win/WheatyExceptionReport.cpp @@ -152,7 +152,9 @@ BOOL WheatyExceptionReport::_GetProcessorName(TCHAR* sProcessorName, DWORD maxco // Skip spaces TCHAR* psz = szTmp; while (iswspace(*psz)) - { ++psz; } + { + ++psz; + } _tcsncpy(sProcessorName, psz, maxcount); return TRUE; } @@ -514,9 +516,7 @@ BOOL WheatyExceptionReport::GetLogicalAddress( // Iterate through the section table, looking for the one that encompasses // the linear address. - for (unsigned i = 0; - i < pNtHdr->FileHeader.NumberOfSections; - ++i, ++pSection) + for (unsigned i = 0; i < pNtHdr->FileHeader.NumberOfSections; ++i, ++pSection) { DWORD_PTR sectionStart = pSection->VirtualAddress; DWORD_PTR sectionEnd = sectionStart @@ -600,9 +600,13 @@ void WheatyExceptionReport::WriteStackDetails( SymFunctionTableAccess64, SymGetModuleBase64, 0)) - { break; } + { + break; + } if (0 == sf.AddrFrame.Offset) // Basic sanity check to make sure - { break; } // the frame is OK. Bail if not. + { + break; // the frame is OK. Bail if not. + } #ifdef _M_IX86 _tprintf(_T("%08X %08X "), sf.AddrPC.Offset, sf.AddrFrame.Offset); #endif @@ -682,7 +686,9 @@ WheatyExceptionReport::EnumerateSymbolsCallback( { if (FormatSymbolValue(pSymInfo, (STACKFRAME*)UserContext, szBuffer, sizeof(szBuffer))) - { _tprintf(_T("\t%s\r\n"), szBuffer); } + { + _tprintf(_T("\t%s\r\n"), szBuffer); + } } __except(1) { diff --git a/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.cpp b/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.cpp index 03c9bdc9c..bb9ebd927 100644 --- a/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.cpp +++ b/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.cpp @@ -2,7 +2,7 @@ * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * - * Copyright (C) 2005-2020 MaNGOS + * Copyright (C) 2005-2020 MaNGOS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -45,21 +45,28 @@ namespace MMAP string name("meshes/%03u%02i%02i."); -#define DEBUG_WRITE(fileExtension,data) \ - do { \ - sprintf(fileName, (name + fileExtension).c_str(), mapID, tileY, tileX); \ - FILE* file = fopen(fileName, "wb"); \ - if (!file) \ - { \ - char message[1024]; \ - sprintf(message, "%sFailed to open %s for writing!\n", tileString, fileName); \ - perror(message); \ - } \ - else \ - debugWrite(file, data); \ - if(file) fclose(file); \ - printf("%sWriting debug output... \r", tileString); \ - } while (false) + // TODO: What the heck are these trailing \/ about in the following lines +#define DEBUG_WRITE(fileExtension,data) \ + do \ + { \ + sprintf(fileName, (name + fileExtension).c_str(), mapID, tileY, tileX); \ + FILE* file = fopen(fileName, "wb"); \ + if (!file) \ + { \ + char message[1024]; \ + sprintf(message, "%sFailed to open %s for writing!\n", tileString, fileName); \ + perror(message); \ + } \ + else \ + { \ + debugWrite(file, data); \ + } \ + if(file) fclose(file); \ + { \ + printf("%sWriting debug output... \r", tileString); \ + } \ + } \ + while (false) if (heightfield) { diff --git a/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.h b/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.h index 95a6e8c65..370f13634 100644 --- a/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.h +++ b/src/tools/Extractor_projects/Movemap-Generator/IntermediateValues.h @@ -2,7 +2,7 @@ * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * - * Copyright (C) 2005-2020 MaNGOS + * Copyright (C) 2005-2020 MaNGOS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/src/tools/Extractor_projects/Movemap-Generator/MMapCommon.h b/src/tools/Extractor_projects/Movemap-Generator/MMapCommon.h index 6053b1ac8..717a24064 100644 --- a/src/tools/Extractor_projects/Movemap-Generator/MMapCommon.h +++ b/src/tools/Extractor_projects/Movemap-Generator/MMapCommon.h @@ -76,12 +76,16 @@ namespace MMAP break; } if (*str == '\0') - { return false; } // reached end of string without matching next filter character + { + return false; // reached end of string without matching next filter character + } str++; } } else if (*filter != *str) - { return false; } // mismatch + { + return false; // mismatch + } filter++; str++; diff --git a/src/tools/Extractor_projects/Movemap-Generator/TerrainBuilder.cpp b/src/tools/Extractor_projects/Movemap-Generator/TerrainBuilder.cpp index ddf661311..1a05051be 100644 --- a/src/tools/Extractor_projects/Movemap-Generator/TerrainBuilder.cpp +++ b/src/tools/Extractor_projects/Movemap-Generator/TerrainBuilder.cpp @@ -224,7 +224,9 @@ namespace MMAP float* liquid_map = NULL; if (!(lheader.flags & MAP_LIQUID_NO_TYPE)) + { fread(liquid_type, sizeof(liquid_type), 1, mapFile); + } if (!(lheader.flags & MAP_LIQUID_NO_HEIGHT)) { @@ -893,7 +895,9 @@ namespace MMAP float size; if (10 != sscanf(buf, "%d %d,%d (%f %f %f) (%f %f %f) %f", &mid, &tx, &ty, &p0[0], &p0[1], &p0[2], &p1[0], &p1[1], &p1[2], &size)) - { continue; } + { + continue; + } if ((mapID == mid) && (tileX == tx) && (tileY == ty)) { diff --git a/src/tools/Extractor_projects/Movemap-Generator/generator.cpp b/src/tools/Extractor_projects/Movemap-Generator/generator.cpp index daea1b23a..53f82c222 100644 --- a/src/tools/Extractor_projects/Movemap-Generator/generator.cpp +++ b/src/tools/Extractor_projects/Movemap-Generator/generator.cpp @@ -371,9 +371,13 @@ int main(int argc, char** argv) builder.buildSingleTile(mapnum, tileX, tileY); } else if (mapnum >= 0) + { builder.buildMap(uint32(mapnum)); + } else + { builder.buildAllMaps(); + } return silent ? 1 : finish(" Movemap build is complete! Press enter to exit\n", 1); diff --git a/src/tools/Extractor_projects/map-extractor/System.cpp b/src/tools/Extractor_projects/map-extractor/System.cpp index cd287306d..49e59bb53 100644 --- a/src/tools/Extractor_projects/map-extractor/System.cpp +++ b/src/tools/Extractor_projects/map-extractor/System.cpp @@ -149,47 +149,69 @@ void HandleArgs(int argc, char* arg[]) // f - use float to int conversion // h - limit minimum height if (arg[c][0] != '-') + { Usage(arg[0]); + } switch (arg[c][1]) { case 'i': if (c + 1 < argc) // all ok + { strcpy(input_path, arg[(c++) + 1]); + } else + { Usage(arg[0]); + } break; case 'o': if (c + 1 < argc) // all ok + { strcpy(output_path, arg[(c++) + 1]); + } else + { Usage(arg[0]); + } break; case 'f': if (c + 1 < argc) // all ok + { CONF_allow_float_to_int = atoi(arg[(c++) + 1]) != 0; + } else + { Usage(arg[0]); + } break; case 'e': if (c + 1 < argc) // all ok { CONF_extract = atoi(arg[(c++) + 1]); if (!(CONF_extract > 0 && CONF_extract < 4)) + { Usage(arg[0]); + } } else + { Usage(arg[0]); + } break; case 'b': if (c + 1 < argc) // all ok { CONF_max_build = atoi(arg[(c++) + 1]); if (CONF_max_build < MIN_SUPPORTED_BUILD) + { Usage(arg[0]); + } } else + { Usage(arg[0]); + } break; default: Usage(arg[0]); @@ -535,7 +557,9 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* { ChunkedFile adt; if (!adt.loadFile(hWorldMPQ, filename)) + { return false; + } // Prepare map header map_fileheader map; @@ -562,7 +586,9 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* // Area data if (mcnk->areaid <= uMaxAreaId && pAreas[mcnk->areaid] != 0xFFFF) + { area_flags[mcnk->iy][mcnk->ix] = pAreas[mcnk->areaid]; + } // Height // Height values for triangles stored in order: @@ -645,7 +671,9 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* { liquid_show[cy][cx] = true; if (liquid->flags[y][x] & (1 << 7)) + { liquid_flags[mcnk->iy][mcnk->ix] |= MAP_LIQUID_TYPE_DARK_WATER; + } ++count; } } @@ -669,7 +697,9 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* } if (!count && liquid_flags[mcnk->iy][mcnk->ix]) + { fprintf(stderr, "Wrong liquid detect in MCLQ chunk"); + } for (int y = 0; y <= ADT_CELL_SIZE; ++y) { @@ -704,7 +734,9 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* { adt_liquid_header *h = h2o->getLiquidData(i, j); if (!h) + { continue; + } int count = 0; uint64 show = h2o->getLiquidShowMap(h); @@ -739,11 +771,15 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* { uint8* lm = h2o->getLiquidLightMap(h); if (!lm) + { liquid_flags[i][j] |= MAP_LIQUID_TYPE_DARK_WATER; + } } if (!count && liquid_flags[i][j]) + { printf("Wrong liquid detect in MH2O chunk"); + } float* height = h2o->getLiquidHeightMap(h); int pos = 0; @@ -755,9 +791,13 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* int cx = j * ADT_CELL_SIZE + x + h->xOffset; if (height) + { liquid_height[cy][cx] = height[pos]; + } else + { liquid_height[cy][cx] = h->heightLevel1; + } pos++; } @@ -1059,9 +1099,13 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* } if (hasHoles) + { map.holesSize = sizeof(holes); + } else + { map.holesSize = 0; + } // Ok all data prepared - store it FILE* output = fopen(filename2, "wb"); @@ -1120,7 +1164,9 @@ bool ConvertADT(HANDLE hWorldMPQ, char *filename, char *filename2, int /*cell_y* // store hole data if (hasHoles) + { fwrite(holes, map.holesSize, 1, output); + } fclose(output); @@ -1205,7 +1251,9 @@ bool ExtractFile(HANDLE fileInArchive, char const* filename) { SFileReadFile(fileInArchive, buffer, sizeof(buffer), &readBytes, NULL); if (readBytes > 0) + { fwrite(buffer, 1, readBytes, output); + } } fclose(output); @@ -1261,7 +1309,9 @@ void ExtractDBCFiles(HANDLE localeMpqHandle, int locale, bool basicLocale) } if (ExtractFile(dbcFile, filename.c_str())) + { ++count; + } if (!FileExists(filename.c_str())) { @@ -1276,23 +1326,35 @@ void AppendPatchMPQFilesToList(char const* subdir, char const* suffix, char cons { char dirname[512]; if (subdir) + { sprintf(dirname, "%s/Data/%s", input_path, subdir); + } else + { sprintf(dirname, "%s/Data", input_path); + } char scanname[512]; if (suffix) + { sprintf(scanname, "wow-update-%s-%%u.MPQ", suffix); + } else + { sprintf(scanname, "wow-update-%%u.MPQ"); + } #ifdef WIN32 char maskname[512]; if (suffix) + { sprintf(maskname, "%s/wow-update-%s-*.MPQ", dirname, suffix); + } else + { sprintf(maskname, "%s/wow-update-*.MPQ", dirname); + } WIN32_FIND_DATA ffd; HANDLE hFind = FindFirstFile(maskname, &ffd); @@ -1302,11 +1364,15 @@ void AppendPatchMPQFilesToList(char const* subdir, char const* suffix, char cons do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { continue; + } uint32 ubuild = 0; if (sscanf(ffd.cFileName, scanname, &ubuild) == 1 && (!CONF_max_build || ubuild <= CONF_max_build)) + { updates[ubuild] = UpdatesPair(ffd.cFileName, section); + } } while (FindNextFile(hFind, &ffd) != 0); @@ -1321,7 +1387,9 @@ void AppendPatchMPQFilesToList(char const* subdir, char const* suffix, char cons dirent* dirp; while ((dirp = readdir(dp)) != NULL) if (sscanf(dirp->d_name, scanname, &ubuild) == 1 && (!CONF_max_build || ubuild <= CONF_max_build)) + { updates[ubuild] = UpdatesPair(dirp->d_name, section); + } closedir(dp); } @@ -1361,56 +1429,74 @@ void LoadLocaleMPQFiles(HANDLE &localeMpqHandle, int const locale) for (int i = 0; Builds[i] <= CONF_TargetBuild; ++i) { if (Builds[i] == 0 || Builds[i] > CONF_TargetBuild) // should not need to do this, but it's being naughty! + { continue; + } sprintf(filename, "%s/Data/wow-update-base-%u.MPQ", input_path, Builds[i]); printf("\nPatching : %s\n", filename); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(localeMpqHandle, filename, prefix, 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } for (Updates::const_iterator itr = updates.begin(); itr != updates.end(); ++itr) { if (!itr->second.second) + { sprintf(filename, "%s/Data/%s/%s", input_path, Locales[locale], itr->second.first.c_str()); + } else + { sprintf(filename, "%s/Data/%s", input_path, itr->second.first.c_str()); + } printf("\nPatching : %s\n", filename); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(localeMpqHandle, filename, itr->second.second ? itr->second.second : "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } // ./Data/Cache patch-base files for (int i = 0; Builds[i] <= CONF_TargetBuild; ++i) { if (Builds[i] == 0 || Builds[i] > CONF_TargetBuild) // should not need to do this, but it's being naughty! + { continue; + } sprintf(filename, "%s/Data/Cache/patch-base-%u.MPQ", input_path, Builds[i]); printf("\nPatching : %s\n", filename); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(localeMpqHandle, filename, prefix, 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } // ./Data/Cache/ patch files for (int i = 0; Builds[i] <= CONF_TargetBuild; ++i) { if (Builds[i] == 0 || Builds[i] > CONF_TargetBuild) // should not need to do this, but it's being naughty! + { continue; + } sprintf(filename, "%s/Data/Cache/%s/patch-%s-%u.MPQ", input_path, Locales[locale], Locales[locale], Builds[i]); printf("\nPatching : %s\n", filename); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(localeMpqHandle, filename, prefix, 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } } @@ -1463,12 +1549,16 @@ void LoadBaseMPQFiles(HANDLE &hWorldMPQ) for (int i = 0; Builds[i] <= CONF_TargetBuild; ++i) { if (Builds[i] == 0 || Builds[i] > CONF_TargetBuild) // should not need to do this, but it's being naughty! + { continue; + } sprintf(filename, "%s/Data/wow-update-base-%u.MPQ", input_path, Builds[i]); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(hWorldMPQ, filename, "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } printf("update-base files loaded\n"); @@ -1477,12 +1567,16 @@ void LoadBaseMPQFiles(HANDLE &hWorldMPQ) for (int i = 0; Builds[i] <= CONF_TargetBuild; ++i) { if (Builds[i] == 0 || Builds[i] > CONF_TargetBuild) // should not need to do this, but it's being naughty! + { continue; + } sprintf(filename, "%s/Data/Cache/patch-base-%u.MPQ", input_path, Builds[i]); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(hWorldMPQ, filename, "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } setvbuf (stdout, NULL, _IONBF, 0); printf(" patch-base files loaded\n"); @@ -1539,7 +1633,9 @@ int main(int argc, char* arg[]) ExtractDBCFiles(hLocaleMpqHandle, i, true); } else + { ExtractDBCFiles(hLocaleMpqHandle, i, false); + } } } @@ -1568,4 +1664,4 @@ int main(int argc, char* arg[]) printf("\n\nExtraction Completed !!!\n\n"); return 0; -} \ No newline at end of file +} diff --git a/src/tools/Extractor_projects/shared/ExtractorCommon.cpp b/src/tools/Extractor_projects/shared/ExtractorCommon.cpp index 5f248e2f6..69bae3e41 100644 --- a/src/tools/Extractor_projects/shared/ExtractorCommon.cpp +++ b/src/tools/Extractor_projects/shared/ExtractorCommon.cpp @@ -77,10 +77,14 @@ FILE* openWoWExe() { #ifdef WIN32 if (fopen_s(&pFile, ExeFileName[iFileCount], "rb") == 0) + { return pFile; ///< successfully located the WoW executable + } #else if ((pFile = fopen(ExeFileName[iFileCount], "rb"))) + { return pFile; ///< successfully located the WoW executable + } #endif } diff --git a/src/tools/Extractor_projects/vmap-extractor/adtfile.cpp b/src/tools/Extractor_projects/vmap-extractor/adtfile.cpp index b41e07c6d..1021938a2 100644 --- a/src/tools/Extractor_projects/vmap-extractor/adtfile.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/adtfile.cpp @@ -36,7 +36,9 @@ const char* GetPlainName(const char* FileName) const char* szTemp; if ((szTemp = strrchr(FileName, '\\')) != NULL) + { FileName = szTemp + 1; + } return FileName; } @@ -45,7 +47,9 @@ char* GetPlainName(char* FileName) char* szTemp; if ((szTemp = strrchr(FileName, '\\')) != NULL) + { FileName = szTemp + 1; + } return FileName; } @@ -74,7 +78,9 @@ void fixname2(char* name, size_t len) for (size_t i = 0; i < len - 3; i++) { if (name[i] == ' ') + { name[i] = '_'; + } } } diff --git a/src/tools/Extractor_projects/vmap-extractor/dbcfile.cpp b/src/tools/Extractor_projects/vmap-extractor/dbcfile.cpp index 2e75858b3..2be813217 100644 --- a/src/tools/Extractor_projects/vmap-extractor/dbcfile.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/dbcfile.cpp @@ -108,7 +108,9 @@ DBCFile::~DBCFile() { delete [] _data; if (_file != NULL) + { SFileCloseFile(_file); + } } DBCFile::Record DBCFile::getRecord(size_t id) @@ -124,7 +126,9 @@ size_t DBCFile::getMaxId() size_t maxId = 0; for (size_t i = 0; i < getRecordCount(); ++i) if (maxId < getRecord(i).getUInt(0)) + { maxId = getRecord(i).getUInt(0); + } return maxId; } diff --git a/src/tools/Extractor_projects/vmap-extractor/gameobject_extract.cpp b/src/tools/Extractor_projects/vmap-extractor/gameobject_extract.cpp index 89bc19f7b..b473fa4c1 100644 --- a/src/tools/Extractor_projects/vmap-extractor/gameobject_extract.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/gameobject_extract.cpp @@ -65,7 +65,9 @@ void ExtractGameobjectModels() path = it->getString(1); if (path.length() < 4) + { continue; + } fixnamen((char*)path.c_str(), path.size()); char* name = GetPlainName((char*)path.c_str()); @@ -73,7 +75,9 @@ void ExtractGameobjectModels() char const* ch_ext = GetExtension(name); if (!ch_ext) + { continue; + } //strToLower(ch_ext); diff --git a/src/tools/Extractor_projects/vmap-extractor/mpqfile.cpp b/src/tools/Extractor_projects/vmap-extractor/mpqfile.cpp index cb3d6b781..dae0318e3 100644 --- a/src/tools/Extractor_projects/vmap-extractor/mpqfile.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/mpqfile.cpp @@ -14,7 +14,9 @@ MPQFile::MPQFile(HANDLE mpq, const char* filename): { int error = GetLastError(); if ( error != ERROR_FILE_NOT_FOUND ) + { fprintf(stderr, "Can't open %s, err=%u!\n", filename, GetLastError()); + } eof = true; return; } @@ -84,6 +86,8 @@ void MPQFile::seekRelative(int offset) void MPQFile::close() { if (buffer) delete[] buffer; - buffer = 0; + { + buffer = 0; + } eof = true; } diff --git a/src/tools/Extractor_projects/vmap-extractor/vmapexport.cpp b/src/tools/Extractor_projects/vmap-extractor/vmapexport.cpp index f4e172124..8484a47ec 100644 --- a/src/tools/Extractor_projects/vmap-extractor/vmapexport.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/vmapexport.cpp @@ -132,23 +132,35 @@ void AppendPatchMPQFilesToList(char const* subdir, char const* suffix, char cons { char dirname[512]; if (subdir) + { sprintf(dirname, "%s/Data/%s", input_path, subdir); + } else + { sprintf(dirname, "%s/Data", input_path); + } char scanname[512]; if (suffix) + { sprintf(scanname, "wow-update-%s-%%u.MPQ", suffix); + } else + { sprintf(scanname, "wow-update-%%u.MPQ"); + } #ifdef WIN32 char maskname[512]; if (suffix) + { sprintf(maskname, "%s/wow-update-%s-*.MPQ", dirname, suffix); + } else + { sprintf(maskname, "%s/wow-update-*.MPQ", dirname); + } WIN32_FIND_DATA ffd; HANDLE hFind = FindFirstFile(maskname, &ffd); @@ -158,11 +170,15 @@ void AppendPatchMPQFilesToList(char const* subdir, char const* suffix, char cons do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { continue; + } uint32 ubuild = 0; if (sscanf(ffd.cFileName, scanname, &ubuild) == 1 && (!CONF_max_build || ubuild <= CONF_max_build)) + { updates[ubuild] = UpdatesPair(ffd.cFileName, section); + } } while (FindNextFile(hFind, &ffd) != 0); @@ -177,7 +193,9 @@ void AppendPatchMPQFilesToList(char const* subdir, char const* suffix, char cons dirent* dirp; while ((dirp = readdir(dp)) != NULL) if (sscanf(dirp->d_name, scanname, &ubuild) == 1 && (!CONF_max_build || ubuild <= CONF_max_build)) + { updates[ubuild] = UpdatesPair(dirp->d_name, section); + } closedir(dp); } @@ -214,21 +232,29 @@ bool LoadLocaleMPQFile(int const locale) //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(LocaleMpq, filename, "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } for (Updates::const_iterator itr = updates.begin(); itr != updates.end(); ++itr) { if (!itr->second.second) + { sprintf(filename, "%s/Data/%s/%s", input_path, Locales[locale], itr->second.first.c_str()); + } else + { sprintf(filename, "%s/Data/%s", input_path, itr->second.first.c_str()); + } printf("\nPatching : %s\n", filename); //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(LocaleMpq, filename, itr->second.second ? itr->second.second : "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } // ./Data/Cache patch-base files @@ -240,7 +266,9 @@ bool LoadLocaleMPQFile(int const locale) //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(LocaleMpq, filename, "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } // ./Data/Cache/ patch files @@ -252,7 +280,9 @@ bool LoadLocaleMPQFile(int const locale) //if (!OpenArchive(filename)) if (!SFileOpenPatchArchive(LocaleMpq, filename, "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } return true; @@ -265,7 +295,9 @@ void LoadCommonMPQFiles(uint32 build) if (!SFileOpenArchive(filename, 0, MPQ_OPEN_READ_ONLY, &WorldMpq)) { if (GetLastError() != ERROR_FILE_NOT_FOUND) + { _tprintf(_T("Cannot open archive %s\n"), filename); + } return; } @@ -273,15 +305,21 @@ void LoadCommonMPQFiles(uint32 build) for (int i = 1; i < count; ++i) { if (build < 15211 && !strcmp("misc.MPQ", CONF_mpq_list[i])) // 4.3.2 and higher MPQ + { continue; + } _stprintf(filename, _T("%s/Data/%s"), input_path, CONF_mpq_list[i]); if (!SFileOpenPatchArchive(WorldMpq, filename, "", 0)) { if (GetLastError() != ERROR_FILE_NOT_FOUND) + { _tprintf(_T("Cannot open archive %s\n"), filename); + } else + { _tprintf(_T("Not found %s\n"), filename); + } } else { @@ -327,9 +365,13 @@ void LoadCommonMPQFiles(uint32 build) if (!SFileOpenPatchArchive(WorldMpq, filename, prefix, 0)) { if (GetLastError() != ERROR_FILE_NOT_FOUND) + { _tprintf(_T("Cannot open patch archive %s\n"), filename); + } else + { _tprintf(_T("Not found %s\n"), filename); + } continue; } else @@ -367,7 +409,9 @@ void LoadCommonMPQFiles(uint32 build) printf("\nPatching : %s\n", filename); if (!SFileOpenPatchArchive(WorldMpq, filename, "", 0)) + { printf("Error open patch archive: %s\n\n", filename); + } } } void strToLower(char* str) @@ -468,7 +512,9 @@ bool ExtractWmo() SFileFindClose(find); if (success) + { printf("\nExtract wmo complete (No (fatal) errors)\n"); + } return success; } @@ -498,7 +544,9 @@ bool ExtractSingleWmo(std::string& fname) { int m = cpy[i]; if (isdigit(m)) + { p++; + } } } @@ -554,7 +602,9 @@ bool ExtractSingleWmo(std::string& fname) // Delete the extracted file in the case of an error if (!file_ok) + { remove(szLocalFile); + } return true; } @@ -616,7 +666,9 @@ bool processArgv(int argc, char** argv) hasInputPathParam = true; strcpy(input_path, argv[i + 1]); if (input_path[strlen(input_path) - 1] != '\\' || input_path[strlen(input_path) - 1] != '/') + { strcat(input_path, "/"); + } ++i; } else @@ -635,7 +687,9 @@ bool processArgv(int argc, char** argv) else if (strcmp("-b", argv[i]) == 0) { if (i + 1 < argc) // all ok + { CONF_TargetBuild = atoi(argv[i++ + 1]); + } } else { @@ -724,7 +778,9 @@ int main(int argc, char** argv) if (!LoadLocaleMPQFile(i)) { if (GetLastError() != ERROR_FILE_NOT_FOUND) + { printf("Unable to load %s locale archives!\n", Locales[i]); + } continue; } @@ -782,9 +838,13 @@ int main(int argc, char** argv) printf("Extract for %s. Work complete. ", szRawVMAPMagic); if (!bCreatedVmapsFolder || !bExtractedWMOfiles) + { printf("There were errors.\n"); + } else + { printf("No errors.\n"); + } delete [] LiqType; return 0; diff --git a/src/tools/Extractor_projects/vmap-extractor/wdtfile.cpp b/src/tools/Extractor_projects/vmap-extractor/wdtfile.cpp index ad5c2911c..d773fb493 100644 --- a/src/tools/Extractor_projects/vmap-extractor/wdtfile.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/wdtfile.cpp @@ -32,7 +32,9 @@ char* wdtGetPlainName(char* FileName) char* szTemp; if ((szTemp = strrchr(FileName, '\\')) != NULL) + { FileName = szTemp + 1; + } return FileName; } diff --git a/src/tools/Extractor_projects/vmap-extractor/wmo.cpp b/src/tools/Extractor_projects/vmap-extractor/wmo.cpp index 48dc2fa11..4a4369c16 100644 --- a/src/tools/Extractor_projects/vmap-extractor/wmo.cpp +++ b/src/tools/Extractor_projects/vmap-extractor/wmo.cpp @@ -356,7 +356,9 @@ int WMOGroup::ConvertToVMAPGroupWmo(FILE* output, WMORoot* rootWMO, bool pPrecis // Skip no collision triangles if (MOPY[2 * i]&WMO_MATERIAL_NO_COLLISION || !(MOPY[2 * i] & (WMO_MATERIAL_HINT | WMO_MATERIAL_COLLIDE_HIT))) - { continue; } + { + continue; + } // Use this triangle for (int j = 0; j < 3; ++j) {