From 85a7d5ce9ac68b30da2277cc91d4b70358f1880d Mon Sep 17 00:00:00 2001 From: ariel- Date: Mon, 19 Jun 2017 23:20:06 -0300 Subject: Core: ported headers cleanup from master branch --- src/CMakeLists.txt | 7 + src/common/Banner.cpp | 38 + src/common/Banner.h | 31 + src/common/Collision/BoundingIntervalHierarchy.h | 12 +- .../Collision/BoundingIntervalHierarchyWrapper.h | 8 +- src/common/Collision/DynamicTree.cpp | 24 +- src/common/Collision/DynamicTree.h | 6 +- src/common/Collision/Management/IVMapManager.h | 8 +- src/common/Collision/Management/MMapFactory.cpp | 6 +- src/common/Collision/Management/MMapManager.cpp | 13 +- src/common/Collision/Management/VMapFactory.cpp | 4 +- src/common/Collision/Management/VMapManager2.cpp | 8 +- src/common/Collision/Management/VMapManager2.h | 4 +- src/common/Collision/Maps/MapDefines.h | 17 + src/common/Collision/Maps/MapTree.cpp | 22 +- src/common/Collision/Maps/MapTree.h | 4 +- src/common/Collision/Maps/TileAssembler.cpp | 23 +- src/common/Collision/Maps/TileAssembler.h | 2 +- src/common/Collision/Models/GameObjectModel.cpp | 4 +- src/common/Collision/Models/GameObjectModel.h | 2 +- src/common/Collision/Models/ModelInstance.cpp | 6 +- src/common/Collision/Models/ModelInstance.h | 14 +- src/common/Collision/Models/WorldModel.cpp | 54 +- src/common/Collision/Models/WorldModel.h | 20 +- src/common/Collision/RegularGrid.h | 26 +- src/common/Collision/VMapTools.h | 148 ---- src/common/Common.h | 74 +- src/common/Configuration/BuiltInConfig.h | 2 +- src/common/Configuration/Config.cpp | 50 +- src/common/Configuration/Config.h | 16 +- src/common/Cryptography/ARC4.cpp | 8 +- src/common/Cryptography/BigNumber.cpp | 2 +- src/common/Cryptography/BigNumber.h | 2 +- src/common/Cryptography/HMACSHA1.cpp | 11 +- src/common/Cryptography/HMACSHA1.h | 6 +- src/common/Cryptography/OpenSSLCrypto.cpp | 6 +- src/common/DataStores/DBCFileLoader.cpp | 316 ++++++++ src/common/DataStores/DBCFileLoader.h | 114 +++ src/common/Debugging/Errors.cpp | 12 +- src/common/Debugging/WheatyExceptionReport.cpp | 5 +- src/common/Debugging/WheatyExceptionReport.h | 6 +- src/common/Define.h | 2 +- src/common/GitRevision.cpp | 17 + src/common/GitRevision.h | 1 - src/common/Logging/Appender.cpp | 20 +- src/common/Logging/Appender.h | 79 +- src/common/Logging/AppenderConsole.cpp | 15 +- src/common/Logging/AppenderConsole.h | 5 +- src/common/Logging/AppenderFile.cpp | 18 +- src/common/Logging/AppenderFile.h | 4 +- src/common/Logging/Log.cpp | 150 ++-- src/common/Logging/Log.h | 100 +-- src/common/Logging/LogCommon.h | 52 ++ src/common/Logging/LogMessage.cpp | 43 ++ src/common/Logging/LogMessage.h | 51 ++ src/common/Logging/LogOperation.cpp | 9 + src/common/Logging/LogOperation.h | 8 +- src/common/Logging/Logger.cpp | 12 +- src/common/Logging/Logger.h | 15 +- src/common/Metric/Metric.cpp | 99 ++- src/common/Metric/Metric.h | 55 +- src/common/PrecompiledHeaders/commonPCH.cpp | 17 + src/common/PrecompiledHeaders/commonPCH.h | 52 +- src/common/Threading/ProcessPriority.cpp | 97 +++ src/common/Threading/ProcessPriority.h | 84 +-- src/common/Utilities/AsioHacksFwd.h | 68 ++ src/common/Utilities/AsioHacksImpl.h | 32 + src/common/Utilities/EventMap.cpp | 16 + src/common/Utilities/EventMap.h | 19 +- src/common/Utilities/EventProcessor.cpp | 2 +- src/common/Utilities/EventProcessor.h | 4 +- src/common/Utilities/Hash.h | 51 ++ src/common/Utilities/Optional.h | 25 + src/common/Utilities/OptionalFwd.h | 31 + src/common/Utilities/Random.cpp | 5 +- src/common/Utilities/Random.h | 1 - src/common/Utilities/StartProcess.cpp | 29 +- src/common/Utilities/StartProcess.h | 11 +- src/common/Utilities/StringFormat.h | 2 +- src/common/Utilities/TaskScheduler.cpp | 1 + src/common/Utilities/TaskScheduler.h | 12 +- src/common/Utilities/Timer.h | 1 + src/common/Utilities/Util.cpp | 64 +- src/common/Utilities/Util.h | 72 +- src/server/CMakeLists.txt | 4 +- src/server/authserver/Authentication/AuthCodes.cpp | 2 +- src/server/authserver/Authentication/TOTP.cpp | 6 +- src/server/authserver/Authentication/TOTP.h | 2 +- src/server/authserver/Main.cpp | 35 +- .../authserver/PrecompiledHeaders/authPCH.cpp | 17 + src/server/authserver/PrecompiledHeaders/authPCH.h | 17 + src/server/authserver/Server/AuthSession.cpp | 33 +- src/server/database/Database/AdhocStatement.cpp | 8 +- src/server/database/Database/AdhocStatement.h | 10 +- src/server/database/Database/DatabaseEnv.cpp | 6 +- src/server/database/Database/DatabaseEnv.h | 28 +- src/server/database/Database/DatabaseEnvFwd.h | 54 ++ src/server/database/Database/DatabaseLoader.cpp | 10 +- src/server/database/Database/DatabaseLoader.h | 9 +- src/server/database/Database/DatabaseWorker.cpp | 1 - src/server/database/Database/DatabaseWorker.h | 8 +- .../database/Database/DatabaseWorkerPool.cpp | 134 +++- src/server/database/Database/DatabaseWorkerPool.h | 123 +-- src/server/database/Database/Field.cpp | 305 +++++++- src/server/database/Database/Field.h | 388 +--------- .../Database/Implementation/CharacterDatabase.cpp | 13 + .../Database/Implementation/CharacterDatabase.h | 10 +- .../Database/Implementation/LoginDatabase.cpp | 17 +- .../Database/Implementation/LoginDatabase.h | 10 +- .../Database/Implementation/WorldDatabase.cpp | 13 + .../Database/Implementation/WorldDatabase.h | 10 +- src/server/database/Database/MySQLConnection.cpp | 91 ++- src/server/database/Database/MySQLConnection.h | 66 +- src/server/database/Database/MySQLThreading.cpp | 32 + src/server/database/Database/MySQLThreading.h | 18 +- src/server/database/Database/PreparedStatement.cpp | 89 ++- src/server/database/Database/PreparedStatement.h | 12 +- src/server/database/Database/QueryCallback.cpp | 11 +- src/server/database/Database/QueryCallback.h | 15 +- src/server/database/Database/QueryHolder.cpp | 117 +-- src/server/database/Database/QueryHolder.h | 16 +- src/server/database/Database/QueryResult.cpp | 149 +++- src/server/database/Database/QueryResult.h | 38 +- src/server/database/Database/SQLOperation.h | 10 +- src/server/database/Database/Transaction.cpp | 11 +- src/server/database/Database/Transaction.h | 14 +- src/server/database/Logging/AppenderDB.cpp | 6 +- src/server/database/Logging/AppenderDB.h | 2 +- .../database/PrecompiledHeaders/databasePCH.cpp | 17 + .../database/PrecompiledHeaders/databasePCH.h | 55 +- src/server/database/Updater/DBUpdater.cpp | 33 +- src/server/database/Updater/DBUpdater.h | 29 +- src/server/database/Updater/UpdateFetcher.cpp | 31 +- src/server/database/Updater/UpdateFetcher.h | 46 +- src/server/game/AI/CoreAI/CombatAI.cpp | 13 +- src/server/game/AI/CoreAI/CombatAI.h | 2 - src/server/game/AI/CoreAI/GameObjectAI.cpp | 11 + src/server/game/AI/CoreAI/GameObjectAI.h | 14 +- src/server/game/AI/CoreAI/GuardAI.cpp | 15 +- src/server/game/AI/CoreAI/GuardAI.h | 1 + src/server/game/AI/CoreAI/PetAI.cpp | 22 +- src/server/game/AI/CoreAI/ReactorAI.cpp | 2 +- src/server/game/AI/CoreAI/ReactorAI.h | 2 - src/server/game/AI/CoreAI/TotemAI.cpp | 4 +- src/server/game/AI/CoreAI/UnitAI.cpp | 102 ++- src/server/game/AI/CoreAI/UnitAI.h | 120 ++- src/server/game/AI/CreatureAI.cpp | 28 +- src/server/game/AI/CreatureAI.h | 21 +- src/server/game/AI/CreatureAIFactory.h | 3 + src/server/game/AI/CreatureAIImpl.h | 24 +- src/server/game/AI/CreatureAIRegistry.cpp | 15 +- src/server/game/AI/GameObjectAIFactory.h | 3 + src/server/game/AI/PlayerAI/PlayerAI.cpp | 39 +- src/server/game/AI/PlayerAI/PlayerAI.h | 27 +- src/server/game/AI/ScriptedAI/ScriptedCreature.cpp | 56 +- src/server/game/AI/ScriptedAI/ScriptedCreature.h | 39 +- src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp | 23 +- src/server/game/AI/ScriptedAI/ScriptedEscortAI.h | 7 +- .../game/AI/ScriptedAI/ScriptedFollowerAI.cpp | 22 +- src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h | 7 +- src/server/game/AI/SmartScripts/SmartAI.cpp | 29 +- src/server/game/AI/SmartScripts/SmartAI.h | 24 +- src/server/game/AI/SmartScripts/SmartScript.cpp | 243 +++++- src/server/game/AI/SmartScripts/SmartScript.h | 213 +----- src/server/game/AI/SmartScripts/SmartScriptMgr.cpp | 222 +++++- src/server/game/AI/SmartScripts/SmartScriptMgr.h | 215 +----- src/server/game/Accounts/AccountMgr.cpp | 13 +- src/server/game/Accounts/RBAC.cpp | 3 +- src/server/game/Accounts/RBAC.h | 3 +- src/server/game/Achievements/AchievementMgr.cpp | 37 +- src/server/game/Achievements/AchievementMgr.h | 21 +- src/server/game/Addons/AddonMgr.cpp | 2 +- src/server/game/AuctionHouse/AuctionHouseMgr.cpp | 38 +- src/server/game/AuctionHouse/AuctionHouseMgr.h | 15 +- .../game/AuctionHouseBot/AuctionHouseBot.cpp | 15 +- src/server/game/AuctionHouseBot/AuctionHouseBot.h | 7 +- .../game/AuctionHouseBot/AuctionHouseBotBuyer.cpp | 16 +- .../game/AuctionHouseBot/AuctionHouseBotBuyer.h | 4 +- .../game/AuctionHouseBot/AuctionHouseBotSeller.cpp | 23 +- src/server/game/Battlefield/Battlefield.cpp | 9 +- src/server/game/Battlefield/Battlefield.h | 23 +- src/server/game/Battlefield/BattlefieldMgr.cpp | 1 + .../game/Battlefield/Zones/BattlefieldWG.cpp | 25 +- src/server/game/Battlegrounds/Arena.cpp | 42 +- src/server/game/Battlegrounds/ArenaScore.h | 37 +- src/server/game/Battlegrounds/ArenaTeam.cpp | 25 +- src/server/game/Battlegrounds/ArenaTeam.h | 2 +- src/server/game/Battlegrounds/ArenaTeamMgr.cpp | 8 +- src/server/game/Battlegrounds/ArenaTeamMgr.h | 1 + src/server/game/Battlegrounds/Battleground.cpp | 84 ++- src/server/game/Battlegrounds/Battleground.h | 40 +- src/server/game/Battlegrounds/BattlegroundMgr.cpp | 82 +- src/server/game/Battlegrounds/BattlegroundMgr.h | 5 +- .../game/Battlegrounds/BattlegroundQueue.cpp | 23 +- src/server/game/Battlegrounds/BattlegroundScore.h | 20 +- .../game/Battlegrounds/Zones/BattlegroundAB.cpp | 30 +- .../game/Battlegrounds/Zones/BattlegroundAB.h | 9 +- .../game/Battlegrounds/Zones/BattlegroundAV.cpp | 35 +- .../game/Battlegrounds/Zones/BattlegroundAV.h | 14 +- .../game/Battlegrounds/Zones/BattlegroundBE.cpp | 1 + .../game/Battlegrounds/Zones/BattlegroundDS.cpp | 2 + .../game/Battlegrounds/Zones/BattlegroundDS.h | 2 + .../game/Battlegrounds/Zones/BattlegroundEY.cpp | 59 +- .../game/Battlegrounds/Zones/BattlegroundEY.h | 14 +- .../game/Battlegrounds/Zones/BattlegroundIC.cpp | 34 +- .../game/Battlegrounds/Zones/BattlegroundIC.h | 9 +- .../game/Battlegrounds/Zones/BattlegroundNA.cpp | 1 + .../game/Battlegrounds/Zones/BattlegroundRL.cpp | 1 + .../game/Battlegrounds/Zones/BattlegroundRV.cpp | 1 + .../game/Battlegrounds/Zones/BattlegroundSA.cpp | 22 +- .../game/Battlegrounds/Zones/BattlegroundSA.h | 15 +- .../game/Battlegrounds/Zones/BattlegroundWS.cpp | 16 +- .../game/Battlegrounds/Zones/BattlegroundWS.h | 9 +- src/server/game/Calendar/CalendarMgr.cpp | 15 +- src/server/game/Calendar/CalendarMgr.h | 13 +- src/server/game/Chat/Channels/Channel.cpp | 11 +- src/server/game/Chat/Channels/Channel.h | 7 +- src/server/game/Chat/Channels/ChannelAppenders.h | 7 +- src/server/game/Chat/Channels/ChannelMgr.cpp | 2 + src/server/game/Chat/Channels/ChannelMgr.h | 8 +- src/server/game/Chat/Chat.cpp | 32 +- src/server/game/Chat/Chat.h | 14 +- src/server/game/Chat/ChatLink.cpp | 7 +- src/server/game/Chat/ChatLink.h | 4 +- src/server/game/Combat/ThreatManager.cpp | 20 +- src/server/game/Combat/ThreatManager.h | 2 +- src/server/game/Conditions/ConditionMgr.cpp | 13 +- src/server/game/Conditions/ConditionMgr.h | 6 +- src/server/game/Conditions/DisableMgr.cpp | 9 +- src/server/game/Conditions/DisableMgr.h | 1 - src/server/game/DataStores/DBCEnums.h | 28 +- src/server/game/DataStores/DBCStores.cpp | 557 ++++++-------- src/server/game/DataStores/DBCStores.h | 15 +- src/server/game/DataStores/DBCStructure.h | 19 +- src/server/game/DataStores/M2Stores.cpp | 159 ++-- src/server/game/DataStores/M2Stores.h | 13 +- src/server/game/DungeonFinding/LFG.cpp | 1 + src/server/game/DungeonFinding/LFG.h | 5 +- src/server/game/DungeonFinding/LFGMgr.cpp | 70 +- src/server/game/DungeonFinding/LFGMgr.h | 17 +- src/server/game/DungeonFinding/LFGPlayerData.h | 2 +- src/server/game/DungeonFinding/LFGQueue.cpp | 8 +- src/server/game/DungeonFinding/LFGQueue.h | 2 +- src/server/game/DungeonFinding/LFGScripts.cpp | 12 +- src/server/game/Entities/Corpse/Corpse.cpp | 5 +- src/server/game/Entities/Corpse/Corpse.h | 6 +- src/server/game/Entities/Creature/Creature.cpp | 82 +- src/server/game/Entities/Creature/Creature.h | 417 +---------- src/server/game/Entities/Creature/CreatureData.h | 370 +++++++++ .../game/Entities/Creature/CreatureGroups.cpp | 15 +- src/server/game/Entities/Creature/CreatureGroups.h | 7 +- src/server/game/Entities/Creature/GossipDef.cpp | 18 +- src/server/game/Entities/Creature/GossipDef.h | 7 +- .../game/Entities/Creature/TemporarySummon.cpp | 14 +- .../game/Entities/Creature/TemporarySummon.h | 18 +- .../game/Entities/DynamicObject/DynamicObject.cpp | 26 +- .../game/Entities/DynamicObject/DynamicObject.h | 4 +- src/server/game/Entities/GameObject/GameObject.cpp | 76 +- src/server/game/Entities/GameObject/GameObject.h | 657 +--------------- .../game/Entities/GameObject/GameObjectData.h | 618 +++++++++++++++ src/server/game/Entities/Item/Container/Bag.cpp | 12 +- src/server/game/Entities/Item/Container/Bag.h | 5 +- src/server/game/Entities/Item/Item.cpp | 136 ++-- src/server/game/Entities/Item/Item.h | 176 +---- src/server/game/Entities/Item/ItemDefines.h | 161 ++++ .../game/Entities/Item/ItemEnchantmentMgr.cpp | 48 ++ src/server/game/Entities/Item/ItemEnchantmentMgr.h | 1 + src/server/game/Entities/Item/ItemTemplate.h | 14 +- src/server/game/Entities/Object/MovementInfo.h | 96 +++ src/server/game/Entities/Object/Object.cpp | 135 ++-- src/server/game/Entities/Object/Object.h | 255 +------ src/server/game/Entities/Object/ObjectDefines.h | 65 +- src/server/game/Entities/Object/ObjectGuid.cpp | 5 +- src/server/game/Entities/Object/ObjectGuid.h | 26 +- .../game/Entities/Object/ObjectPosSelector.cpp | 8 +- .../game/Entities/Object/ObjectPosSelector.h | 10 +- src/server/game/Entities/Object/Position.cpp | 75 +- src/server/game/Entities/Object/Position.h | 156 ++-- .../game/Entities/Object/Updates/UpdateData.cpp | 10 +- .../game/Entities/Object/Updates/UpdateData.h | 3 +- .../game/Entities/Object/Updates/UpdateMask.h | 5 +- src/server/game/Entities/Pet/Pet.cpp | 46 +- src/server/game/Entities/Player/CinematicMgr.cpp | 29 +- src/server/game/Entities/Player/CinematicMgr.h | 4 +- src/server/game/Entities/Player/EquipmentSet.h | 58 ++ src/server/game/Entities/Player/KillRewarder.cpp | 2 +- src/server/game/Entities/Player/Player.cpp | 831 ++++++++++----------- src/server/game/Entities/Player/Player.h | 380 ++-------- src/server/game/Entities/Player/PlayerTaxi.cpp | 156 ++++ src/server/game/Entities/Player/PlayerTaxi.h | 83 ++ src/server/game/Entities/Player/SocialMgr.cpp | 5 +- src/server/game/Entities/Player/SocialMgr.h | 3 +- src/server/game/Entities/Player/TradeData.cpp | 1 + src/server/game/Entities/Totem/Totem.cpp | 2 +- src/server/game/Entities/Transport/Transport.cpp | 48 +- src/server/game/Entities/Transport/Transport.h | 6 +- src/server/game/Entities/Unit/StatSystem.cpp | 7 +- src/server/game/Entities/Unit/Unit.cpp | 281 +++---- src/server/game/Entities/Unit/Unit.h | 468 ++---------- src/server/game/Entities/Unit/UnitDefines.h | 352 +++++++++ src/server/game/Entities/Vehicle/Vehicle.cpp | 28 +- src/server/game/Entities/Vehicle/Vehicle.h | 4 +- src/server/game/Entities/Vehicle/VehicleDefines.h | 4 +- src/server/game/Events/GameEventMgr.cpp | 36 +- src/server/game/Events/GameEventMgr.h | 5 + src/server/game/Globals/ObjectAccessor.cpp | 12 +- src/server/game/Globals/ObjectAccessor.h | 31 +- src/server/game/Globals/ObjectMgr.cpp | 137 ++-- src/server/game/Globals/ObjectMgr.h | 277 +++++-- src/server/game/Grids/Cells/Cell.h | 4 +- src/server/game/Grids/Dynamic/TypeContainer.h | 143 ++++ .../game/Grids/Dynamic/TypeContainerFunctions.h | 217 ++++++ .../game/Grids/Dynamic/TypeContainerVisitor.h | 104 +++ src/server/game/Grids/GridRefManager.h | 2 +- src/server/game/Grids/GridStates.cpp | 5 +- src/server/game/Grids/NGrid.cpp | 29 + src/server/game/Grids/NGrid.h | 16 +- src/server/game/Grids/Notifiers/GridNotifiers.cpp | 2 +- src/server/game/Grids/Notifiers/GridNotifiers.h | 41 +- .../game/Grids/Notifiers/GridNotifiersImpl.h | 8 +- src/server/game/Grids/ObjectGridLoader.cpp | 13 +- src/server/game/Grids/ObjectGridLoader.h | 2 +- src/server/game/Groups/Group.cpp | 161 ++-- src/server/game/Groups/Group.h | 17 +- src/server/game/Groups/GroupMgr.cpp | 14 +- src/server/game/Guilds/Guild.cpp | 104 ++- src/server/game/Guilds/Guild.h | 78 +- src/server/game/Guilds/GuildMgr.cpp | 12 +- src/server/game/Guilds/GuildMgr.h | 9 +- src/server/game/Handlers/ArenaTeamHandler.cpp | 16 +- src/server/game/Handlers/AuctionHouseHandler.cpp | 25 +- src/server/game/Handlers/BattleGroundHandler.cpp | 86 ++- src/server/game/Handlers/BattlefieldHandler.cpp | 10 +- src/server/game/Handlers/CalendarHandler.cpp | 36 +- src/server/game/Handlers/ChannelHandler.cpp | 7 +- src/server/game/Handlers/CharacterHandler.cpp | 58 +- src/server/game/Handlers/ChatHandler.cpp | 39 +- src/server/game/Handlers/CombatHandler.cpp | 11 +- src/server/game/Handlers/DuelHandler.cpp | 2 +- src/server/game/Handlers/GroupHandler.cpp | 9 +- src/server/game/Handlers/GuildHandler.cpp | 12 +- src/server/game/Handlers/ItemHandler.cpp | 105 +-- src/server/game/Handlers/LFGHandler.cpp | 12 +- src/server/game/Handlers/LootHandler.cpp | 24 +- src/server/game/Handlers/MailHandler.cpp | 35 +- src/server/game/Handlers/MiscHandler.cpp | 89 +-- src/server/game/Handlers/MovementHandler.cpp | 4 +- src/server/game/Handlers/NPCHandler.cpp | 35 +- src/server/game/Handlers/NPCHandler.h | 6 +- src/server/game/Handlers/PetHandler.cpp | 44 +- src/server/game/Handlers/PetitionsHandler.cpp | 35 +- src/server/game/Handlers/QueryHandler.cpp | 24 +- src/server/game/Handlers/QuestHandler.cpp | 34 +- src/server/game/Handlers/ReferAFriendHandler.cpp | 7 +- src/server/game/Handlers/SkillHandler.cpp | 5 +- src/server/game/Handlers/SocialHandler.cpp | 11 +- src/server/game/Handlers/SpellHandler.cpp | 49 +- src/server/game/Handlers/TaxiHandler.cpp | 11 +- src/server/game/Handlers/TicketHandler.cpp | 20 +- src/server/game/Handlers/TradeHandler.cpp | 36 +- src/server/game/Handlers/VehicleHandler.cpp | 8 +- src/server/game/Handlers/VoiceChatHandler.cpp | 1 + src/server/game/Instances/InstanceSaveMgr.cpp | 45 +- src/server/game/Instances/InstanceSaveMgr.h | 11 +- src/server/game/Instances/InstanceScript.cpp | 71 +- src/server/game/Instances/InstanceScript.h | 70 +- src/server/game/Loot/Loot.cpp | 777 +++++++++++++++++++ src/server/game/Loot/Loot.h | 279 +++++++ src/server/game/Loot/LootItemStorage.cpp | 3 + src/server/game/Loot/LootItemStorage.h | 2 +- src/server/game/Loot/LootMgr.cpp | 759 +------------------ src/server/game/Loot/LootMgr.h | 292 +------- src/server/game/Mails/Mail.cpp | 22 +- src/server/game/Mails/Mail.h | 3 +- src/server/game/Maps/Map.cpp | 161 +++- src/server/game/Maps/Map.h | 146 ++-- src/server/game/Maps/MapInstanced.cpp | 28 +- src/server/game/Maps/MapInstanced.h | 8 +- src/server/game/Maps/MapManager.cpp | 10 +- src/server/game/Maps/MapManager.h | 8 +- src/server/game/Maps/MapObject.h | 60 ++ src/server/game/Maps/MapReference.cpp | 40 + src/server/game/Maps/MapReference.h | 23 +- src/server/game/Maps/MapScripts.cpp | 68 +- src/server/game/Maps/TransportMgr.cpp | 73 +- src/server/game/Maps/TransportMgr.h | 28 +- src/server/game/Maps/ZoneScript.cpp | 24 + src/server/game/Maps/ZoneScript.h | 12 +- src/server/game/Miscellaneous/Formulas.h | 12 +- src/server/game/Miscellaneous/SharedDefines.h | 37 +- src/server/game/Motd/ServerMotd.cpp | 8 +- src/server/game/Motd/ServerMotd.h | 1 + src/server/game/Movement/MotionMaster.cpp | 25 +- src/server/game/Movement/MotionMaster.h | 17 +- .../ConfusedMovementGenerator.cpp | 13 +- .../MovementGenerators/ConfusedMovementGenerator.h | 4 +- .../FormationMovementGenerator.cpp | 4 +- .../MovementGenerators/HomeMovementGenerator.cpp | 5 +- .../MovementGenerators/PointMovementGenerator.cpp | 8 +- .../MovementGenerators/PointMovementGenerator.h | 8 +- .../MovementGenerators/RandomMovementGenerator.cpp | 6 +- .../MovementGenerators/RandomMovementGenerator.h | 4 +- .../SplineChainMovementGenerator.h | 4 +- .../TargetedMovementGenerator.cpp | 9 +- .../WaypointMovementGenerator.cpp | 22 +- .../MovementGenerators/WaypointMovementGenerator.h | 9 +- src/server/game/Movement/PathGenerator.cpp | 48 +- src/server/game/Movement/PathGenerator.h | 27 +- src/server/game/Movement/Spline/MoveSpline.cpp | 39 +- src/server/game/Movement/Spline/MoveSpline.h | 33 +- src/server/game/Movement/Spline/MoveSplineFlag.h | 31 +- src/server/game/Movement/Spline/MoveSplineInit.cpp | 55 +- src/server/game/Movement/Spline/MoveSplineInit.h | 64 +- .../game/Movement/Spline/MoveSplineInitArgs.h | 34 +- .../game/Movement/Spline/MovementPacketBuilder.cpp | 60 +- .../game/Movement/Spline/MovementPacketBuilder.h | 33 +- src/server/game/Movement/Spline/MovementTypedefs.h | 24 +- src/server/game/Movement/Spline/MovementUtil.cpp | 26 +- src/server/game/Movement/Spline/Spline.cpp | 34 +- src/server/game/Movement/Spline/Spline.h | 38 +- src/server/game/Movement/Spline/SplineChain.h | 6 +- src/server/game/Movement/Spline/SplineImpl.h | 24 +- .../game/Movement/Waypoints/WaypointManager.h | 4 +- src/server/game/OutdoorPvP/OutdoorPvP.cpp | 35 +- src/server/game/OutdoorPvP/OutdoorPvP.h | 22 +- src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp | 13 +- src/server/game/OutdoorPvP/OutdoorPvPMgr.h | 5 +- src/server/game/Petitions/PetitionMgr.cpp | 5 +- src/server/game/Petitions/PetitionMgr.h | 1 - src/server/game/Pools/PoolMgr.cpp | 13 +- src/server/game/PrecompiledHeaders/gamePCH.cpp | 17 + src/server/game/PrecompiledHeaders/gamePCH.h | 32 +- src/server/game/Quests/QuestDef.cpp | 10 +- src/server/game/Quests/QuestDef.h | 28 +- src/server/game/Reputation/ReputationMgr.cpp | 11 +- src/server/game/Reputation/ReputationMgr.h | 6 +- src/server/game/Scripting/ScriptMgr.cpp | 108 +-- src/server/game/Scripting/ScriptMgr.h | 96 +-- src/server/game/Scripting/ScriptReloadMgr.cpp | 40 +- src/server/game/Scripting/ScriptSystem.cpp | 28 +- src/server/game/Scripting/ScriptSystem.h | 46 +- src/server/game/Server/Packet.cpp | 49 ++ src/server/game/Server/Packet.h | 23 +- src/server/game/Server/Packets/PacketUtilities.cpp | 33 + src/server/game/Server/Packets/PacketUtilities.h | 63 +- src/server/game/Server/Protocol/Opcodes.cpp | 46 +- src/server/game/Server/Protocol/Opcodes.h | 44 +- src/server/game/Server/Protocol/PacketLog.cpp | 6 +- src/server/game/Server/Protocol/PacketLog.h | 2 +- src/server/game/Server/WorldSession.cpp | 90 ++- src/server/game/Server/WorldSession.h | 26 +- src/server/game/Server/WorldSocket.cpp | 14 +- src/server/game/Server/WorldSocketMgr.h | 2 +- src/server/game/Skills/SkillDiscovery.cpp | 9 +- src/server/game/Skills/SkillExtraItems.cpp | 3 +- src/server/game/Spells/Auras/SpellAuraDefines.h | 14 +- src/server/game/Spells/Auras/SpellAuraEffects.cpp | 150 ++-- src/server/game/Spells/Auras/SpellAuras.cpp | 73 +- src/server/game/Spells/Auras/SpellAuras.h | 13 +- src/server/game/Spells/Spell.cpp | 289 ++++--- src/server/game/Spells/Spell.h | 84 ++- src/server/game/Spells/SpellEffects.cpp | 174 ++--- src/server/game/Spells/SpellHistory.cpp | 14 +- src/server/game/Spells/SpellHistory.h | 14 +- src/server/game/Spells/SpellInfo.cpp | 69 +- src/server/game/Spells/SpellInfo.h | 22 +- src/server/game/Spells/SpellMgr.cpp | 67 +- src/server/game/Spells/SpellMgr.h | 9 +- src/server/game/Spells/SpellScript.cpp | 48 +- src/server/game/Spells/SpellScript.h | 47 +- src/server/game/Texts/ChatTextBuilder.cpp | 38 + src/server/game/Texts/ChatTextBuilder.h | 27 +- src/server/game/Texts/CreatureTextMgr.cpp | 45 +- src/server/game/Texts/CreatureTextMgr.h | 169 +---- src/server/game/Texts/CreatureTextMgrImpl.h | 170 +++++ src/server/game/Tickets/TicketMgr.cpp | 41 +- src/server/game/Tickets/TicketMgr.h | 29 +- src/server/game/Time/GameTime.h | 1 - src/server/game/Tools/CharacterDatabaseCleaner.cpp | 9 +- src/server/game/Tools/CharacterDatabaseCleaner.h | 2 +- src/server/game/Tools/PlayerDump.cpp | 19 +- src/server/game/Warden/Warden.cpp | 13 +- src/server/game/Warden/Warden.h | 2 +- src/server/game/Warden/WardenCheckMgr.cpp | 5 +- src/server/game/Warden/WardenWin.cpp | 2 + src/server/game/Weather/Weather.cpp | 10 +- src/server/game/Weather/Weather.h | 2 +- src/server/game/Weather/WeatherMgr.cpp | 9 +- src/server/game/World/World.cpp | 107 ++- src/server/game/World/World.h | 54 +- src/server/scripts/Commands/cs_account.cpp | 63 +- src/server/scripts/Commands/cs_achievement.cpp | 5 +- src/server/scripts/Commands/cs_ahbot.cpp | 51 +- src/server/scripts/Commands/cs_arena.cpp | 21 +- src/server/scripts/Commands/cs_ban.cpp | 31 +- src/server/scripts/Commands/cs_bf.cpp | 17 +- src/server/scripts/Commands/cs_cast.cpp | 33 +- src/server/scripts/Commands/cs_character.cpp | 34 +- src/server/scripts/Commands/cs_cheat.cpp | 24 +- src/server/scripts/Commands/cs_debug.cpp | 100 ++- src/server/scripts/Commands/cs_deserter.cpp | 11 +- src/server/scripts/Commands/cs_disable.cpp | 20 +- src/server/scripts/Commands/cs_event.cpp | 9 +- src/server/scripts/Commands/cs_gm.cpp | 15 +- src/server/scripts/Commands/cs_go.cpp | 40 +- src/server/scripts/Commands/cs_gobject.cpp | 52 +- src/server/scripts/Commands/cs_group.cpp | 16 +- src/server/scripts/Commands/cs_guild.cpp | 20 +- src/server/scripts/Commands/cs_honor.cpp | 11 +- src/server/scripts/Commands/cs_instance.cpp | 16 +- src/server/scripts/Commands/cs_learn.cpp | 31 +- src/server/scripts/Commands/cs_lfg.cpp | 16 +- src/server/scripts/Commands/cs_list.cpp | 24 +- src/server/scripts/Commands/cs_lookup.cpp | 23 +- src/server/scripts/Commands/cs_message.cpp | 16 +- src/server/scripts/Commands/cs_misc.cpp | 114 +-- src/server/scripts/Commands/cs_mmaps.cpp | 23 +- src/server/scripts/Commands/cs_modify.cpp | 91 +-- src/server/scripts/Commands/cs_npc.cpp | 21 +- src/server/scripts/Commands/cs_pet.cpp | 14 +- src/server/scripts/Commands/cs_quest.cpp | 21 +- src/server/scripts/Commands/cs_rbac.cpp | 35 +- src/server/scripts/Commands/cs_reload.cpp | 211 +++--- src/server/scripts/Commands/cs_reset.cpp | 13 +- src/server/scripts/Commands/cs_send.cpp | 33 +- src/server/scripts/Commands/cs_server.cpp | 12 +- src/server/scripts/Commands/cs_tele.cpp | 23 +- src/server/scripts/Commands/cs_ticket.cpp | 50 +- src/server/scripts/Commands/cs_titles.cpp | 9 +- src/server/scripts/Commands/cs_wp.cpp | 51 +- .../EasternKingdoms/AlteracValley/boss_balinda.cpp | 1 + .../BlackrockDepths/blackrock_depths.cpp | 28 +- .../BlackrockDepths/blackrock_depths.h | 9 + .../BlackrockDepths/boss_ambassador_flamelash.cpp | 3 +- .../BlackrockDepths/boss_coren_direbrew.cpp | 45 +- .../boss_emperor_dagran_thaurissan.cpp | 6 +- .../BlackrockDepths/boss_general_angerforge.cpp | 3 +- .../boss_high_interrogator_gerstahn.cpp | 3 +- .../BlackrockDepths/boss_magmus.cpp | 5 +- .../BlackrockDepths/boss_moira_bronzebeard.cpp | 3 +- .../BlackrockDepths/boss_tomb_of_seven.cpp | 9 +- .../BlackrockDepths/instance_blackrock_depths.cpp | 255 +++---- .../BlackrockSpire/blackrock_spire.h | 8 + .../BlackrockSpire/boss_drakkisath.cpp | 4 +- .../BlackrockSpire/boss_gizrul_the_slavener.cpp | 5 +- .../BlackrockMountain/BlackrockSpire/boss_gyth.cpp | 7 +- .../BlackrockSpire/boss_halycon.cpp | 4 +- .../BlackrockSpire/boss_highlord_omokk.cpp | 4 +- .../BlackrockSpire/boss_lord_valthalak.cpp | 5 +- .../BlackrockSpire/boss_mother_smolderweb.cpp | 4 +- .../BlackrockSpire/boss_overlord_wyrmthalak.cpp | 5 +- .../BlackrockSpire/boss_pyroguard_emberseer.cpp | 41 +- .../BlackrockSpire/boss_quartermaster_zigris.cpp | 4 +- .../BlackrockSpire/boss_rend_blackhand.cpp | 21 +- .../boss_shadow_hunter_voshgajin.cpp | 4 +- .../BlackrockSpire/boss_the_beast.cpp | 4 +- .../BlackrockSpire/boss_urok_doomhowl.cpp | 4 +- .../BlackrockSpire/boss_warmaster_voone.cpp | 4 +- .../BlackrockSpire/instance_blackrock_spire.cpp | 23 +- .../BlackwingLair/blackwing_lair.h | 10 +- .../BlackwingLair/boss_broodlord_lashlayer.cpp | 4 +- .../BlackwingLair/boss_chromaggus.cpp | 9 +- .../BlackwingLair/boss_ebonroc.cpp | 4 +- .../BlackwingLair/boss_firemaw.cpp | 4 +- .../BlackwingLair/boss_flamegor.cpp | 4 +- .../BlackwingLair/boss_nefarian.cpp | 14 +- .../BlackwingLair/boss_razorgore.cpp | 12 +- .../BlackwingLair/boss_vaelastrasz.cpp | 11 +- .../BlackwingLair/instance_blackwing_lair.cpp | 11 +- .../MoltenCore/boss_baron_geddon.cpp | 6 +- .../BlackrockMountain/MoltenCore/boss_garr.cpp | 8 +- .../BlackrockMountain/MoltenCore/boss_gehennas.cpp | 6 +- .../BlackrockMountain/MoltenCore/boss_golemagg.cpp | 10 +- .../BlackrockMountain/MoltenCore/boss_lucifron.cpp | 6 +- .../BlackrockMountain/MoltenCore/boss_magmadar.cpp | 6 +- .../MoltenCore/boss_majordomo_executus.cpp | 12 +- .../BlackrockMountain/MoltenCore/boss_ragnaros.cpp | 9 +- .../BlackrockMountain/MoltenCore/boss_shazzrah.cpp | 8 +- .../MoltenCore/boss_sulfuron_harbinger.cpp | 8 +- .../MoltenCore/instance_molten_core.cpp | 12 +- .../BlackrockMountain/MoltenCore/molten_core.h | 15 +- .../EasternKingdoms/Deadmines/boss_mr_smite.cpp | 8 +- .../EasternKingdoms/Deadmines/deadmines.cpp | 7 +- .../scripts/EasternKingdoms/Deadmines/deadmines.h | 9 + .../Deadmines/instance_deadmines.cpp | 28 +- .../EasternKingdoms/Gnomeregan/gnomeregan.cpp | 30 +- .../EasternKingdoms/Gnomeregan/gnomeregan.h | 9 + .../Gnomeregan/instance_gnomeregan.cpp | 10 +- .../EasternKingdoms/Karazhan/boss_curator.cpp | 2 +- .../Karazhan/boss_maiden_of_virtue.cpp | 2 +- .../EasternKingdoms/Karazhan/boss_midnight.cpp | 12 +- .../EasternKingdoms/Karazhan/boss_moroes.cpp | 19 +- .../EasternKingdoms/Karazhan/boss_netherspite.cpp | 9 +- .../EasternKingdoms/Karazhan/boss_nightbane.cpp | 16 +- .../Karazhan/boss_prince_malchezaar.cpp | 22 +- .../Karazhan/boss_shade_of_aran.cpp | 13 +- .../Karazhan/boss_terestian_illhoof.cpp | 3 +- .../EasternKingdoms/Karazhan/bosses_opera.cpp | 35 +- .../EasternKingdoms/Karazhan/instance_karazhan.cpp | 7 +- .../scripts/EasternKingdoms/Karazhan/karazhan.cpp | 19 +- .../scripts/EasternKingdoms/Karazhan/karazhan.h | 4 +- .../MagistersTerrace/boss_felblood_kaelthas.cpp | 39 +- .../MagistersTerrace/boss_priestess_delrissa.cpp | 31 +- .../MagistersTerrace/boss_selin_fireheart.cpp | 9 +- .../MagistersTerrace/boss_vexallus.cpp | 7 +- .../instance_magisters_terrace.cpp | 16 +- .../MagistersTerrace/magisters_terrace.cpp | 8 +- .../MagistersTerrace/magisters_terrace.h | 9 + .../EasternKingdoms/ScarletEnclave/chapter1.cpp | 27 +- .../EasternKingdoms/ScarletEnclave/chapter2.cpp | 14 +- .../EasternKingdoms/ScarletEnclave/chapter5.cpp | 16 +- .../ScarletEnclave/zone_the_scarlet_enclave.cpp | 11 +- .../ScarletMonastery/boss_headless_horseman.cpp | 50 +- .../ScarletMonastery/boss_herod.cpp | 4 +- .../boss_high_inquisitor_fairbanks.cpp | 5 +- .../ScarletMonastery/boss_houndmaster_loksey.cpp | 2 +- .../ScarletMonastery/boss_interrogator_vishas.cpp | 6 +- .../boss_mograine_and_whitemane.cpp | 13 +- .../instance_scarlet_monastery.cpp | 20 +- .../ScarletMonastery/scarlet_monastery.h | 4 +- .../Scholomance/boss_darkmaster_gandling.cpp | 40 +- .../Scholomance/boss_death_knight_darkreaver.cpp | 3 +- .../Scholomance/boss_doctor_theolen_krastinov.cpp | 4 +- .../Scholomance/boss_illucia_barov.cpp | 4 +- .../Scholomance/boss_instructor_malicia.cpp | 4 +- .../Scholomance/boss_jandice_barov.cpp | 3 +- .../Scholomance/boss_kirtonos_the_herald.cpp | 28 +- .../EasternKingdoms/Scholomance/boss_kormok.cpp | 13 +- .../Scholomance/boss_lord_alexei_barov.cpp | 4 +- .../Scholomance/boss_lorekeeper_polkelt.cpp | 4 +- .../Scholomance/boss_ras_frostwhisper.cpp | 3 +- .../Scholomance/boss_the_ravenian.cpp | 4 +- .../EasternKingdoms/Scholomance/boss_vectus.cpp | 3 +- .../Scholomance/instance_scholomance.cpp | 4 +- .../EasternKingdoms/Scholomance/scholomance.h | 9 + .../ShadowfangKeep/boss_apothecary_hummel.cpp | 20 +- .../ShadowfangKeep/instance_shadowfang_keep.cpp | 11 +- .../ShadowfangKeep/shadowfang_keep.cpp | 18 +- .../ShadowfangKeep/shadowfang_keep.h | 9 + .../Stratholme/boss_baron_rivendare.cpp | 3 +- .../Stratholme/boss_baroness_anastari.cpp | 3 +- .../Stratholme/boss_cannon_master_willey.cpp | 3 +- .../Stratholme/boss_dathrohan_balnazzar.cpp | 3 +- .../Stratholme/boss_magistrate_barthilas.cpp | 2 +- .../Stratholme/boss_maleki_the_pallid.cpp | 3 +- .../EasternKingdoms/Stratholme/boss_nerubenkan.cpp | 3 +- .../Stratholme/boss_order_of_silver_hand.cpp | 3 +- .../Stratholme/boss_postmaster_malown.cpp | 2 +- .../Stratholme/boss_ramstein_the_gorger.cpp | 4 +- .../Stratholme/boss_timmy_the_cruel.cpp | 3 +- .../Stratholme/instance_stratholme.cpp | 12 +- .../EasternKingdoms/Stratholme/stratholme.cpp | 18 +- .../EasternKingdoms/Stratholme/stratholme.h | 9 + .../SunkenTemple/instance_sunken_temple.cpp | 8 +- .../EasternKingdoms/SunkenTemple/sunken_temple.cpp | 11 +- .../EasternKingdoms/SunkenTemple/sunken_temple.h | 9 + .../SunwellPlateau/boss_brutallus.cpp | 2 + .../SunwellPlateau/boss_eredar_twins.cpp | 13 +- .../SunwellPlateau/boss_felmyst.cpp | 16 +- .../SunwellPlateau/boss_kalecgos.cpp | 15 +- .../SunwellPlateau/boss_kiljaeden.cpp | 21 +- .../EasternKingdoms/SunwellPlateau/boss_muru.cpp | 16 +- .../SunwellPlateau/instance_sunwell_plateau.cpp | 4 +- .../SunwellPlateau/sunwell_plateau.h | 4 +- .../TheStockade/instance_the_stockade.cpp | 1 + .../EasternKingdoms/Uldaman/boss_archaedas.cpp | 24 +- .../EasternKingdoms/Uldaman/boss_ironaya.cpp | 3 +- .../EasternKingdoms/Uldaman/instance_uldaman.cpp | 12 +- .../scripts/EasternKingdoms/Uldaman/uldaman.cpp | 10 +- .../scripts/EasternKingdoms/Uldaman/uldaman.h | 9 + .../EasternKingdoms/ZulAman/boss_akilzon.cpp | 17 +- .../EasternKingdoms/ZulAman/boss_halazzi.cpp | 6 +- .../EasternKingdoms/ZulAman/boss_hexlord.cpp | 15 +- .../EasternKingdoms/ZulAman/boss_janalai.cpp | 16 +- .../EasternKingdoms/ZulAman/boss_nalorakk.cpp | 6 +- .../EasternKingdoms/ZulAman/boss_zuljin.cpp | 7 +- .../EasternKingdoms/ZulAman/instance_zulaman.cpp | 5 +- .../scripts/EasternKingdoms/ZulAman/zulaman.cpp | 13 +- .../scripts/EasternKingdoms/ZulAman/zulaman.h | 8 +- .../EasternKingdoms/ZulGurub/boss_arlokk.cpp | 10 +- .../EasternKingdoms/ZulGurub/boss_gahzranka.cpp | 2 +- .../EasternKingdoms/ZulGurub/boss_grilek.cpp | 2 +- .../EasternKingdoms/ZulGurub/boss_hakkar.cpp | 3 +- .../EasternKingdoms/ZulGurub/boss_hazzarah.cpp | 3 +- .../EasternKingdoms/ZulGurub/boss_jeklik.cpp | 3 +- .../EasternKingdoms/ZulGurub/boss_jindo.cpp | 9 +- .../EasternKingdoms/ZulGurub/boss_mandokir.cpp | 7 +- .../EasternKingdoms/ZulGurub/boss_marli.cpp | 7 +- .../EasternKingdoms/ZulGurub/boss_renataki.cpp | 2 +- .../EasternKingdoms/ZulGurub/boss_thekal.cpp | 12 +- .../EasternKingdoms/ZulGurub/boss_venoxis.cpp | 2 +- .../EasternKingdoms/ZulGurub/boss_wushoolay.cpp | 2 +- .../EasternKingdoms/ZulGurub/instance_zulgurub.cpp | 20 +- .../scripts/EasternKingdoms/ZulGurub/zulgurub.h | 9 +- .../scripts/EasternKingdoms/zone_blasted_lands.cpp | 6 +- .../scripts/EasternKingdoms/zone_duskwood.cpp | 3 +- .../scripts/EasternKingdoms/zone_ghostlands.cpp | 7 +- .../scripts/EasternKingdoms/zone_hinterlands.cpp | 5 +- .../EasternKingdoms/zone_silverpine_forest.cpp | 6 +- .../EasternKingdoms/zone_stormwind_city.cpp | 8 +- .../EasternKingdoms/zone_stranglethorn_vale.cpp | 2 +- .../EasternKingdoms/zone_swamp_of_sorrows.cpp | 19 +- .../EasternKingdoms/zone_tirisfal_glades.cpp | 4 +- .../scripts/EasternKingdoms/zone_undercity.cpp | 4 +- .../EasternKingdoms/zone_western_plaguelands.cpp | 2 +- src/server/scripts/Events/childrens_week.cpp | 4 +- src/server/scripts/Events/fireworks_show.cpp | 115 +-- .../BlackfathomDeeps/blackfathom_deeps.cpp | 18 +- .../Kalimdor/BlackfathomDeeps/blackfathom_deeps.h | 9 + .../Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp | 2 +- .../Kalimdor/BlackfathomDeeps/boss_gelihast.cpp | 2 +- .../Kalimdor/BlackfathomDeeps/boss_kelris.cpp | 2 +- .../instance_blackfathom_deeps.cpp | 12 +- .../BattleForMountHyjal/boss_anetheron.cpp | 15 +- .../BattleForMountHyjal/boss_archimonde.cpp | 23 +- .../BattleForMountHyjal/boss_azgalor.cpp | 9 +- .../BattleForMountHyjal/boss_kazrogal.cpp | 17 +- .../BattleForMountHyjal/boss_rage_winterchill.cpp | 7 +- .../CavernsOfTime/BattleForMountHyjal/hyjal.cpp | 11 +- .../CavernsOfTime/BattleForMountHyjal/hyjal.h | 9 + .../CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp | 35 +- .../CavernsOfTime/BattleForMountHyjal/hyjalAI.h | 1 - .../BattleForMountHyjal/hyjal_trash.cpp | 91 ++- .../BattleForMountHyjal/instance_hyjal.cpp | 12 +- .../CullingOfStratholme/boss_chrono_lord_epoch.cpp | 4 +- .../boss_infinite_corruptor.cpp | 6 +- .../CullingOfStratholme/boss_mal_ganis.cpp | 7 +- .../CullingOfStratholme/boss_meathook.cpp | 2 +- .../boss_salramm_the_fleshcrafter.cpp | 2 +- .../CullingOfStratholme/culling_of_stratholme.cpp | 16 +- .../CullingOfStratholme/culling_of_stratholme.h | 11 +- .../instance_culling_of_stratholme.cpp | 9 +- .../boss_captain_skarloc.cpp | 3 +- .../EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp | 5 +- .../boss_leutenant_drake.cpp | 14 +- .../instance_old_hillsbrad.cpp | 8 +- .../EscapeFromDurnholdeKeep/old_hillsbrad.cpp | 18 +- .../EscapeFromDurnholdeKeep/old_hillsbrad.h | 9 + .../CavernsOfTime/TheBlackMorass/boss_aeonus.cpp | 5 +- .../TheBlackMorass/boss_chrono_lord_deja.cpp | 5 +- .../CavernsOfTime/TheBlackMorass/boss_temporus.cpp | 6 +- .../TheBlackMorass/instance_the_black_morass.cpp | 14 +- .../TheBlackMorass/the_black_morass.cpp | 14 +- .../TheBlackMorass/the_black_morass.h | 9 + .../Kalimdor/DireMaul/instance_dire_maul.cpp | 2 +- .../Kalimdor/Maraudon/boss_celebras_the_cursed.cpp | 3 +- .../scripts/Kalimdor/Maraudon/boss_landslide.cpp | 3 +- .../scripts/Kalimdor/Maraudon/boss_noxxion.cpp | 3 +- .../Kalimdor/Maraudon/boss_princess_theradras.cpp | 4 +- .../Kalimdor/Maraudon/instance_maraudon.cpp | 4 +- src/server/scripts/Kalimdor/Maraudon/maraudon.h | 31 + .../scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp | 18 +- .../Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp | 11 +- .../scripts/Kalimdor/OnyxiasLair/onyxias_lair.h | 10 + .../RagefireChasm/instance_ragefire_chasm.cpp | 1 + .../boss_amnennar_the_coldbringer.cpp | 2 +- .../Kalimdor/RazorfenDowns/boss_glutton.cpp | 2 +- .../RazorfenDowns/boss_mordresh_fire_eye.cpp | 2 +- .../Kalimdor/RazorfenDowns/boss_tuten_kash.cpp | 2 +- .../RazorfenDowns/instance_razorfen_downs.cpp | 6 +- .../Kalimdor/RazorfenDowns/razorfen_downs.cpp | 23 +- .../Kalimdor/RazorfenDowns/razorfen_downs.h | 6 +- .../RazorfenKraul/instance_razorfen_kraul.cpp | 9 +- .../Kalimdor/RazorfenKraul/razorfen_kraul.cpp | 9 +- .../Kalimdor/RazorfenKraul/razorfen_kraul.h | 10 + .../Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp | 11 +- .../scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp | 18 +- .../Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp | 13 +- .../scripts/Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp | 2 +- .../Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp | 27 +- .../Kalimdor/RuinsOfAhnQiraj/boss_rajaxx.cpp | 6 +- .../RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp | 4 +- .../Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h | 9 + .../Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp | 11 +- .../Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp | 30 +- .../Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp | 4 +- .../Kalimdor/TempleOfAhnQiraj/boss_huhuran.cpp | 3 +- .../Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp | 4 +- .../Kalimdor/TempleOfAhnQiraj/boss_sartura.cpp | 5 +- .../Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp | 9 +- .../TempleOfAhnQiraj/boss_twinemperors.cpp | 30 +- .../Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp | 10 +- .../instance_temple_of_ahnqiraj.cpp | 134 ++-- .../TempleOfAhnQiraj/mob_anubisath_sentinel.cpp | 14 +- .../Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h | 9 + .../WailingCaverns/instance_wailing_caverns.cpp | 7 +- .../Kalimdor/WailingCaverns/wailing_caverns.cpp | 30 +- .../Kalimdor/WailingCaverns/wailing_caverns.h | 9 + .../scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp | 3 +- .../Kalimdor/ZulFarrak/instance_zulfarrak.cpp | 11 +- .../scripts/Kalimdor/ZulFarrak/zulfarrak.cpp | 26 +- src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h | 9 + src/server/scripts/Kalimdor/boss_azuregos.cpp | 10 +- src/server/scripts/Kalimdor/zone_ashenvale.cpp | 6 +- src/server/scripts/Kalimdor/zone_azshara.cpp | 10 +- .../scripts/Kalimdor/zone_azuremyst_isle.cpp | 15 +- .../scripts/Kalimdor/zone_bloodmyst_isle.cpp | 21 +- src/server/scripts/Kalimdor/zone_darkshore.cpp | 2 +- src/server/scripts/Kalimdor/zone_desolace.cpp | 7 +- src/server/scripts/Kalimdor/zone_durotar.cpp | 26 +- .../scripts/Kalimdor/zone_dustwallow_marsh.cpp | 18 +- src/server/scripts/Kalimdor/zone_felwood.cpp | 3 +- src/server/scripts/Kalimdor/zone_feralas.cpp | 7 +- src/server/scripts/Kalimdor/zone_moonglade.cpp | 14 +- src/server/scripts/Kalimdor/zone_orgrimmar.cpp | 11 +- src/server/scripts/Kalimdor/zone_silithus.cpp | 23 +- src/server/scripts/Kalimdor/zone_tanaris.cpp | 9 +- src/server/scripts/Kalimdor/zone_the_barrens.cpp | 12 +- .../scripts/Kalimdor/zone_thousand_needles.cpp | 6 +- src/server/scripts/Kalimdor/zone_ungoro_crater.cpp | 6 +- src/server/scripts/Kalimdor/zone_winterspring.cpp | 39 +- .../Northrend/AzjolNerub/Ahnkahet/ahnkahet.h | 6 +- .../AzjolNerub/Ahnkahet/boss_amanitar.cpp | 16 +- .../AzjolNerub/Ahnkahet/boss_elder_nadox.cpp | 15 +- .../AzjolNerub/Ahnkahet/boss_herald_volazj.cpp | 16 +- .../Ahnkahet/boss_jedoga_shadowseeker.cpp | 14 +- .../AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp | 22 +- .../AzjolNerub/Ahnkahet/instance_ahnkahet.cpp | 7 +- .../Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h | 9 + .../AzjolNerub/AzjolNerub/boss_anubarak.cpp | 27 +- .../AzjolNerub/AzjolNerub/boss_hadronox.cpp | 40 +- .../AzjolNerub/boss_krikthir_the_gatewatcher.cpp | 34 +- .../AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp | 40 +- .../ObsidianSanctum/boss_sartharion.cpp | 10 +- .../ObsidianSanctum/instance_obsidian_sanctum.cpp | 3 + .../ObsidianSanctum/obsidian_sanctum.cpp | 20 +- .../ObsidianSanctum/obsidian_sanctum.h | 8 +- .../RubySanctum/boss_baltharus_the_warborn.cpp | 7 +- .../RubySanctum/boss_general_zarithrian.cpp | 6 +- .../ChamberOfAspects/RubySanctum/boss_halion.cpp | 54 +- .../RubySanctum/boss_saviana_ragefire.cpp | 9 +- .../RubySanctum/instance_ruby_sanctum.cpp | 13 +- .../ChamberOfAspects/RubySanctum/ruby_sanctum.cpp | 11 +- .../ChamberOfAspects/RubySanctum/ruby_sanctum.h | 25 +- .../TrialOfTheChampion/boss_argent_challenge.cpp | 22 +- .../TrialOfTheChampion/boss_black_knight.cpp | 8 +- .../TrialOfTheChampion/boss_grand_champions.cpp | 22 +- .../instance_trial_of_the_champion.cpp | 21 +- .../TrialOfTheChampion/trial_of_the_champion.cpp | 13 +- .../TrialOfTheChampion/trial_of_the_champion.h | 9 + .../TrialOfTheCrusader/boss_anubarak_trial.cpp | 27 +- .../TrialOfTheCrusader/boss_faction_champions.cpp | 95 ++- .../TrialOfTheCrusader/boss_lord_jaraxxus.cpp | 21 +- .../TrialOfTheCrusader/boss_northrend_beasts.cpp | 51 +- .../TrialOfTheCrusader/boss_twin_valkyr.cpp | 40 +- .../instance_trial_of_the_crusader.cpp | 28 +- .../TrialOfTheCrusader/trial_of_the_crusader.cpp | 89 ++- .../TrialOfTheCrusader/trial_of_the_crusader.h | 133 +--- .../Northrend/DraktharonKeep/boss_king_dred.cpp | 4 +- .../Northrend/DraktharonKeep/boss_novos.cpp | 16 +- .../Northrend/DraktharonKeep/boss_tharon_ja.cpp | 4 +- .../Northrend/DraktharonKeep/boss_trollgore.cpp | 23 +- .../Northrend/DraktharonKeep/drak_tharon_keep.h | 8 +- .../DraktharonKeep/instance_drak_tharon_keep.cpp | 6 +- .../FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp | 12 +- .../ForgeOfSouls/boss_devourer_of_souls.cpp | 26 +- .../FrozenHalls/ForgeOfSouls/forge_of_souls.cpp | 8 +- .../FrozenHalls/ForgeOfSouls/forge_of_souls.h | 8 + .../ForgeOfSouls/instance_forge_of_souls.cpp | 8 +- .../FrozenHalls/HallsOfReflection/boss_falric.cpp | 4 +- .../FrozenHalls/HallsOfReflection/boss_horAI.cpp | 53 ++ .../FrozenHalls/HallsOfReflection/boss_horAI.h | 32 + .../FrozenHalls/HallsOfReflection/boss_marwyn.cpp | 7 +- .../HallsOfReflection/halls_of_reflection.cpp | 26 +- .../HallsOfReflection/halls_of_reflection.h | 51 +- .../instance_halls_of_reflection.cpp | 14 +- .../PitOfSaron/boss_forgemaster_garfrost.cpp | 10 +- .../FrozenHalls/PitOfSaron/boss_krickandick.cpp | 15 +- .../PitOfSaron/boss_scourgelord_tyrannus.cpp | 36 +- .../PitOfSaron/instance_pit_of_saron.cpp | 24 +- .../FrozenHalls/PitOfSaron/pit_of_saron.cpp | 36 +- .../FrozenHalls/PitOfSaron/pit_of_saron.h | 22 +- .../Northrend/Gundrak/boss_drakkari_colossus.cpp | 4 +- .../scripts/Northrend/Gundrak/boss_gal_darah.cpp | 8 +- .../scripts/Northrend/Gundrak/boss_moorabi.cpp | 4 +- .../scripts/Northrend/Gundrak/boss_slad_ran.cpp | 10 +- src/server/scripts/Northrend/Gundrak/gundrak.h | 4 +- .../scripts/Northrend/Gundrak/instance_gundrak.cpp | 13 +- .../IcecrownCitadel/boss_blood_prince_council.cpp | 28 +- .../IcecrownCitadel/boss_blood_queen_lana_thel.cpp | 41 +- .../IcecrownCitadel/boss_deathbringer_saurfang.cpp | 35 +- .../Northrend/IcecrownCitadel/boss_festergut.cpp | 20 +- .../boss_icecrown_gunship_battle.cpp | 84 ++- .../IcecrownCitadel/boss_lady_deathwhisper.cpp | 24 +- .../IcecrownCitadel/boss_lord_marrowgar.cpp | 19 +- .../IcecrownCitadel/boss_professor_putricide.cpp | 57 +- .../Northrend/IcecrownCitadel/boss_rotface.cpp | 24 +- .../Northrend/IcecrownCitadel/boss_sindragosa.cpp | 48 +- .../IcecrownCitadel/boss_the_lich_king.cpp | 110 ++- .../IcecrownCitadel/boss_valithria_dreamwalker.cpp | 18 +- .../Northrend/IcecrownCitadel/icecrown_citadel.cpp | 73 +- .../Northrend/IcecrownCitadel/icecrown_citadel.h | 47 +- .../IcecrownCitadel/icecrown_citadel_teleport.cpp | 6 +- .../IcecrownCitadel/instance_icecrown_citadel.cpp | 22 +- .../Northrend/IsleOfConquest/isle_of_conquest.cpp | 20 +- .../Northrend/Naxxramas/boss_anubrekhan.cpp | 8 +- .../scripts/Northrend/Naxxramas/boss_faerlina.cpp | 9 +- .../Northrend/Naxxramas/boss_four_horsemen.cpp | 25 +- .../scripts/Northrend/Naxxramas/boss_gluth.cpp | 14 +- .../scripts/Northrend/Naxxramas/boss_gothik.cpp | 30 +- .../scripts/Northrend/Naxxramas/boss_grobbulus.cpp | 17 +- .../scripts/Northrend/Naxxramas/boss_heigan.cpp | 20 +- .../scripts/Northrend/Naxxramas/boss_kelthuzad.cpp | 30 +- .../scripts/Northrend/Naxxramas/boss_loatheb.cpp | 11 +- .../scripts/Northrend/Naxxramas/boss_maexxna.cpp | 16 +- .../scripts/Northrend/Naxxramas/boss_noth.cpp | 5 +- .../scripts/Northrend/Naxxramas/boss_patchwerk.cpp | 11 +- .../scripts/Northrend/Naxxramas/boss_razuvious.cpp | 9 +- .../scripts/Northrend/Naxxramas/boss_sapphiron.cpp | 19 +- .../scripts/Northrend/Naxxramas/boss_thaddius.cpp | 59 +- .../Northrend/Naxxramas/instance_naxxramas.cpp | 13 +- src/server/scripts/Northrend/Naxxramas/naxxramas.h | 17 +- .../Northrend/Nexus/EyeOfEternity/boss_malygos.cpp | 89 +-- .../Nexus/EyeOfEternity/eye_of_eternity.h | 9 + .../EyeOfEternity/instance_eye_of_eternity.cpp | 12 +- .../Northrend/Nexus/Nexus/boss_anomalus.cpp | 9 +- .../Northrend/Nexus/Nexus/boss_keristrasza.cpp | 15 +- .../Northrend/Nexus/Nexus/boss_magus_telestra.cpp | 9 +- .../Nexus/Nexus/boss_nexus_commanders.cpp | 4 +- .../scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp | 7 +- .../Northrend/Nexus/Nexus/instance_nexus.cpp | 5 +- src/server/scripts/Northrend/Nexus/Nexus/nexus.h | 8 + .../scripts/Northrend/Nexus/Oculus/boss_drakos.cpp | 6 +- .../scripts/Northrend/Nexus/Oculus/boss_eregos.cpp | 6 +- .../scripts/Northrend/Nexus/Oculus/boss_urom.cpp | 3 +- .../scripts/Northrend/Nexus/Oculus/boss_varos.cpp | 13 +- .../Northrend/Nexus/Oculus/instance_oculus.cpp | 26 +- .../scripts/Northrend/Nexus/Oculus/oculus.cpp | 31 +- src/server/scripts/Northrend/Nexus/Oculus/oculus.h | 8 +- .../Ulduar/HallsOfLightning/boss_bjarngrim.cpp | 8 +- .../Ulduar/HallsOfLightning/boss_ionar.cpp | 11 +- .../Ulduar/HallsOfLightning/boss_loken.cpp | 6 +- .../Ulduar/HallsOfLightning/boss_volkhan.cpp | 15 +- .../Ulduar/HallsOfLightning/halls_of_lightning.h | 8 +- .../instance_halls_of_lightning.cpp | 28 +- .../Ulduar/HallsOfStone/boss_krystallus.cpp | 5 +- .../Ulduar/HallsOfStone/boss_maiden_of_grief.cpp | 3 +- .../Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp | 5 +- .../Ulduar/HallsOfStone/halls_of_stone.cpp | 10 +- .../Northrend/Ulduar/HallsOfStone/halls_of_stone.h | 8 +- .../HallsOfStone/instance_halls_of_stone.cpp | 24 +- .../Ulduar/Ulduar/boss_algalon_the_observer.cpp | 33 +- .../Ulduar/Ulduar/boss_assembly_of_iron.cpp | 19 +- .../Northrend/Ulduar/Ulduar/boss_auriaya.cpp | 2 + .../Ulduar/Ulduar/boss_flame_leviathan.cpp | 26 +- .../scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp | 14 +- .../Northrend/Ulduar/Ulduar/boss_general_vezax.cpp | 29 +- .../scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp | 15 +- .../scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp | 13 +- .../Northrend/Ulduar/Ulduar/boss_kologarn.cpp | 10 +- .../Northrend/Ulduar/Ulduar/boss_mimiron.cpp | 115 +-- .../Northrend/Ulduar/Ulduar/boss_razorscale.cpp | 22 +- .../Northrend/Ulduar/Ulduar/boss_thorim.cpp | 49 +- .../scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp | 41 +- .../Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp | 98 +-- .../Northrend/Ulduar/Ulduar/instance_ulduar.cpp | 16 +- .../scripts/Northrend/Ulduar/Ulduar/ulduar.h | 6 +- .../UtgardeKeep/boss_ingvar_the_plunderer.cpp | 13 +- .../UtgardeKeep/UtgardeKeep/boss_keleseth.cpp | 5 +- .../UtgardeKeep/boss_skarvald_dalronn.cpp | 2 + .../UtgardeKeep/instance_utgarde_keep.cpp | 22 +- .../UtgardeKeep/UtgardeKeep/utgarde_keep.cpp | 21 +- .../UtgardeKeep/UtgardeKeep/utgarde_keep.h | 8 +- .../UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp | 18 +- .../UtgardeKeep/UtgardePinnacle/boss_skadi.cpp | 33 +- .../UtgardeKeep/UtgardePinnacle/boss_svala.cpp | 7 +- .../UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp | 6 +- .../UtgardePinnacle/instance_utgarde_pinnacle.cpp | 3 + .../UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h | 6 +- .../Northrend/VaultOfArchavon/boss_archavon.cpp | 25 +- .../Northrend/VaultOfArchavon/boss_emalon.cpp | 8 +- .../Northrend/VaultOfArchavon/boss_koralon.cpp | 17 +- .../Northrend/VaultOfArchavon/boss_toravon.cpp | 10 +- .../VaultOfArchavon/instance_vault_of_archavon.cpp | 10 +- .../Northrend/VaultOfArchavon/vault_of_archavon.h | 9 + .../Northrend/VioletHold/boss_cyanigosa.cpp | 5 +- .../scripts/Northrend/VioletHold/boss_erekem.cpp | 3 + .../scripts/Northrend/VioletHold/boss_ichoron.cpp | 25 +- .../Northrend/VioletHold/boss_lavanthor.cpp | 1 + .../scripts/Northrend/VioletHold/boss_moragg.cpp | 3 +- .../scripts/Northrend/VioletHold/boss_xevozz.cpp | 8 +- .../scripts/Northrend/VioletHold/boss_zuramat.cpp | 1 + .../Northrend/VioletHold/instance_violet_hold.cpp | 30 +- .../scripts/Northrend/VioletHold/violet_hold.cpp | 117 ++- .../scripts/Northrend/VioletHold/violet_hold.h | 4 +- .../scripts/Northrend/zone_borean_tundra.cpp | 42 +- .../scripts/Northrend/zone_crystalsong_forest.cpp | 3 +- src/server/scripts/Northrend/zone_dalaran.cpp | 13 +- src/server/scripts/Northrend/zone_dragonblight.cpp | 16 +- .../scripts/Northrend/zone_grizzly_hills.cpp | 23 +- .../scripts/Northrend/zone_howling_fjord.cpp | 12 +- src/server/scripts/Northrend/zone_icecrown.cpp | 6 +- .../scripts/Northrend/zone_sholazar_basin.cpp | 18 +- src/server/scripts/Northrend/zone_storm_peaks.cpp | 62 +- src/server/scripts/Northrend/zone_wintergrasp.cpp | 55 +- src/server/scripts/Northrend/zone_zuldrak.cpp | 103 ++- src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp | 30 +- src/server/scripts/OutdoorPvP/OutdoorPvPEP.h | 2 +- src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp | 8 +- src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp | 244 +++--- src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp | 19 +- src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp | 86 +-- src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp | 78 +- src/server/scripts/OutdoorPvP/OutdoorPvPZM.h | 12 +- .../Auchindoun/AuchenaiCrypts/auchenai_crypts.h | 8 +- .../AuchenaiCrypts/boss_exarch_maladaar.cpp | 8 +- .../boss_shirrak_the_dead_watcher.cpp | 11 +- .../AuchenaiCrypts/instance_auchenai_crypts.cpp | 3 +- .../ManaTombs/boss_nexusprince_shaffar.cpp | 9 +- .../Auchindoun/ManaTombs/instance_mana_tombs.cpp | 1 + .../Outland/Auchindoun/ManaTombs/mana_tombs.h | 8 +- .../SethekkHalls/boss_darkweaver_syth.cpp | 8 +- .../SethekkHalls/boss_talon_king_ikiss.cpp | 4 +- .../SethekkHalls/instance_sethekk_halls.cpp | 5 +- .../Auchindoun/SethekkHalls/sethekk_halls.h | 8 +- .../ShadowLabyrinth/boss_ambassador_hellmaw.cpp | 4 +- .../boss_blackheart_the_inciter.cpp | 1 + .../ShadowLabyrinth/boss_grandmaster_vorpil.cpp | 9 +- .../Auchindoun/ShadowLabyrinth/boss_murmur.cpp | 9 +- .../ShadowLabyrinth/instance_shadow_labyrinth.cpp | 5 +- .../ShadowLabyrinth/shadow_labyrinth.cpp | 4 +- .../Auchindoun/ShadowLabyrinth/shadow_labyrinth.h | 8 +- .../scripts/Outland/BlackTemple/black_temple.cpp | 13 +- .../scripts/Outland/BlackTemple/black_temple.h | 6 +- .../Outland/BlackTemple/boss_gurtogg_bloodboil.cpp | 12 +- .../scripts/Outland/BlackTemple/boss_illidan.cpp | 62 +- .../Outland/BlackTemple/boss_illidari_council.cpp | 51 +- .../Outland/BlackTemple/boss_mother_shahraz.cpp | 26 +- .../BlackTemple/boss_reliquary_of_souls.cpp | 16 +- .../Outland/BlackTemple/boss_shade_of_akama.cpp | 20 +- .../scripts/Outland/BlackTemple/boss_supremus.cpp | 6 +- .../Outland/BlackTemple/boss_teron_gorefiend.cpp | 37 +- .../Outland/BlackTemple/boss_warlord_najentus.cpp | 16 +- .../Outland/BlackTemple/instance_black_temple.cpp | 7 +- .../SerpentShrine/boss_fathomlord_karathress.cpp | 23 +- .../SerpentShrine/boss_hydross_the_unstable.cpp | 7 +- .../SerpentShrine/boss_lady_vashj.cpp | 22 +- .../SerpentShrine/boss_leotheras_the_blind.cpp | 31 +- .../SerpentShrine/boss_lurker_below.cpp | 54 +- .../SerpentShrine/boss_morogrim_tidewalker.cpp | 7 +- .../SerpentShrine/instance_serpent_shrine.cpp | 22 +- .../SerpentShrine/serpent_shrine.h | 9 + .../SteamVault/boss_hydromancer_thespia.cpp | 4 +- .../SteamVault/boss_mekgineer_steamrigger.cpp | 6 +- .../SteamVault/boss_warlord_kalithresh.cpp | 9 +- .../SteamVault/instance_steam_vault.cpp | 4 + .../CoilfangReservoir/SteamVault/steam_vault.h | 6 +- .../CoilfangReservoir/TheSlavePens/boss_ahune.cpp | 64 +- .../TheSlavePens/boss_mennu_the_betrayer.cpp | 2 +- .../TheSlavePens/boss_quagmirran.cpp | 2 +- .../TheSlavePens/boss_rokmar_the_crackler.cpp | 2 +- .../TheSlavePens/instance_the_slave_pens.cpp | 2 + .../TheSlavePens/the_slave_pens.h | 8 + .../TheUnderbog/boss_hungarfen.cpp | 5 +- .../TheUnderbog/boss_the_black_stalker.cpp | 4 +- .../TheUnderbog/instance_the_underbog.cpp | 4 +- .../CoilfangReservoir/TheUnderbog/the_underbog.h | 31 + .../scripts/Outland/GruulsLair/boss_gruul.cpp | 20 +- .../Outland/GruulsLair/boss_high_king_maulgar.cpp | 13 +- .../scripts/Outland/GruulsLair/gruuls_lair.h | 8 +- .../Outland/GruulsLair/instance_gruuls_lair.cpp | 54 +- .../HellfireCitadel/BloodFurnace/blood_furnace.h | 6 +- .../HellfireCitadel/BloodFurnace/boss_broggok.cpp | 15 +- .../BloodFurnace/boss_kelidan_the_breaker.cpp | 4 +- .../BloodFurnace/instance_blood_furnace.cpp | 32 +- .../HellfireRamparts/boss_omor_the_unscarred.cpp | 9 +- .../HellfireRamparts/boss_vazruden_the_herald.cpp | 15 +- .../boss_watchkeeper_gargolmar.cpp | 4 +- .../HellfireRamparts/hellfire_ramparts.h | 9 + .../instance_hellfire_ramparts.cpp | 6 +- .../MagtheridonsLair/boss_magtheridon.cpp | 35 +- .../instance_magtheridons_lair.cpp | 7 +- .../MagtheridonsLair/magtheridons_lair.h | 9 + .../ShatteredHalls/boss_nethekurse.cpp | 8 +- .../ShatteredHalls/boss_warbringer_omrogg.cpp | 6 +- .../boss_warchief_kargath_bladefist.cpp | 5 +- .../ShatteredHalls/instance_shattered_halls.cpp | 38 +- .../ShatteredHalls/shattered_halls.cpp | 15 +- .../ShatteredHalls/shattered_halls.h | 20 +- .../scripts/Outland/TempestKeep/Eye/boss_alar.cpp | 20 +- .../Outland/TempestKeep/Eye/boss_astromancer.cpp | 29 +- .../Outland/TempestKeep/Eye/boss_kaelthas.cpp | 33 +- .../Outland/TempestKeep/Eye/boss_void_reaver.cpp | 9 +- .../Outland/TempestKeep/Eye/instance_the_eye.cpp | 18 +- .../scripts/Outland/TempestKeep/Eye/the_eye.cpp | 2 +- .../scripts/Outland/TempestKeep/Eye/the_eye.h | 9 + .../Mechanar/boss_gatewatcher_gyrokill.cpp | 4 +- .../Mechanar/boss_gatewatcher_ironhand.cpp | 4 +- .../Mechanar/boss_mechano_lord_capacitus.cpp | 29 +- .../Mechanar/boss_nethermancer_sepethrea.cpp | 8 +- .../Mechanar/boss_pathaleon_the_calculator.cpp | 7 +- .../TempestKeep/Mechanar/instance_mechanar.cpp | 35 +- .../Outland/TempestKeep/Mechanar/mechanar.h | 9 + .../Outland/TempestKeep/arcatraz/arcatraz.cpp | 6 +- .../Outland/TempestKeep/arcatraz/arcatraz.h | 8 +- .../arcatraz/boss_dalliah_the_doomsayer.cpp | 4 +- .../arcatraz/boss_harbinger_skyriss.cpp | 6 +- .../arcatraz/boss_wrath_scryer_soccothrates.cpp | 5 +- .../arcatraz/boss_zereketh_the_unbound.cpp | 2 +- .../TempestKeep/arcatraz/instance_arcatraz.cpp | 24 +- .../botanica/boss_commander_sarannis.cpp | 5 +- .../botanica/boss_high_botanist_freywinn.cpp | 4 +- .../Outland/TempestKeep/botanica/boss_laj.cpp | 2 +- .../botanica/boss_thorngrin_the_tender.cpp | 2 +- .../TempestKeep/botanica/boss_warp_splinter.cpp | 10 +- .../TempestKeep/botanica/instance_the_botanica.cpp | 4 +- .../Outland/TempestKeep/botanica/the_botanica.h | 9 + .../scripts/Outland/boss_doomlord_kazzak.cpp | 10 +- .../scripts/Outland/zone_blades_edge_mountains.cpp | 24 +- .../scripts/Outland/zone_hellfire_peninsula.cpp | 8 +- src/server/scripts/Outland/zone_nagrand.cpp | 13 +- src/server/scripts/Outland/zone_netherstorm.cpp | 16 +- .../scripts/Outland/zone_shadowmoon_valley.cpp | 30 +- .../scripts/Outland/zone_terokkar_forest.cpp | 8 +- src/server/scripts/Outland/zone_zangarmarsh.cpp | 4 +- src/server/scripts/Pet/pet_dk.cpp | 5 +- src/server/scripts/Pet/pet_generic.cpp | 6 +- src/server/scripts/Pet/pet_hunter.cpp | 19 +- src/server/scripts/Pet/pet_mage.cpp | 9 +- src/server/scripts/ScriptPCH.cpp | 21 +- src/server/scripts/ScriptPCH.h | 30 +- src/server/scripts/Spells/spell_dk.cpp | 352 ++++----- src/server/scripts/Spells/spell_druid.cpp | 223 +++--- src/server/scripts/Spells/spell_generic.cpp | 365 ++++----- src/server/scripts/Spells/spell_holiday.cpp | 182 +++-- src/server/scripts/Spells/spell_hunter.cpp | 147 ++-- src/server/scripts/Spells/spell_item.cpp | 491 ++++++------ src/server/scripts/Spells/spell_mage.cpp | 152 ++-- src/server/scripts/Spells/spell_paladin.cpp | 308 ++++---- src/server/scripts/Spells/spell_pet.cpp | 20 +- src/server/scripts/Spells/spell_priest.cpp | 133 ++-- src/server/scripts/Spells/spell_quest.cpp | 155 ++-- src/server/scripts/Spells/spell_rogue.cpp | 138 ++-- src/server/scripts/Spells/spell_shaman.cpp | 193 ++--- src/server/scripts/Spells/spell_warlock.cpp | 152 ++-- src/server/scripts/Spells/spell_warrior.cpp | 135 ++-- src/server/scripts/World/action_ip_logger.cpp | 6 +- src/server/scripts/World/areatrigger_scripts.cpp | 9 +- src/server/scripts/World/boss_emerald_dragons.cpp | 21 +- src/server/scripts/World/chat_log.cpp | 4 +- src/server/scripts/World/duel_reset.cpp | 7 +- src/server/scripts/World/go_scripts.cpp | 18 +- src/server/scripts/World/guards.cpp | 7 +- src/server/scripts/World/item_scripts.cpp | 40 +- src/server/scripts/World/mob_generic_creature.cpp | 7 +- src/server/scripts/World/npc_innkeeper.cpp | 4 +- src/server/scripts/World/npc_professions.cpp | 11 +- src/server/scripts/World/npcs_special.cpp | 57 +- src/server/shared/DataStores/DBCDatabaseLoader.cpp | 193 +++++ src/server/shared/DataStores/DBCDatabaseLoader.h | 43 ++ src/server/shared/DataStores/DBCFileLoader.cpp | 322 -------- src/server/shared/DataStores/DBCFileLoader.h | 113 --- src/server/shared/DataStores/DBCStorageIterator.h | 69 ++ src/server/shared/DataStores/DBCStore.cpp | 76 ++ src/server/shared/DataStores/DBCStore.h | 306 ++------ src/server/shared/Dynamic/FactoryHolder.h | 2 +- src/server/shared/Dynamic/LinkedList.h | 12 +- .../shared/Dynamic/LinkedReference/Reference.h | 12 +- src/server/shared/Dynamic/ObjectRegistry.h | 2 + src/server/shared/Dynamic/TypeContainer.h | 143 ---- src/server/shared/Dynamic/TypeContainerFunctions.h | 217 ------ src/server/shared/Dynamic/TypeContainerVisitor.h | 104 --- src/server/shared/Memory.h | 17 +- src/server/shared/Networking/AsyncAcceptor.h | 3 +- src/server/shared/Packets/ByteBuffer.cpp | 76 +- src/server/shared/Packets/ByteBuffer.h | 167 +---- src/server/shared/PrecompiledHeaders/sharedPCH.cpp | 17 + src/server/shared/PrecompiledHeaders/sharedPCH.h | 28 +- src/server/shared/Realm/Realm.cpp | 19 +- src/server/shared/Realm/Realm.h | 11 +- src/server/shared/Realm/RealmList.cpp | 35 +- src/server/shared/Realm/RealmList.h | 33 +- src/server/worldserver/CommandLine/CliRunnable.cpp | 22 +- src/server/worldserver/Main.cpp | 84 ++- .../worldserver/PrecompiledHeaders/worldPCH.cpp | 17 + .../worldserver/PrecompiledHeaders/worldPCH.h | 17 + src/server/worldserver/RemoteAccess/RASession.cpp | 18 +- src/server/worldserver/RemoteAccess/RASession.h | 4 +- src/server/worldserver/TCSoap/TCSoap.h | 4 +- src/tools/map_extractor/CMakeLists.txt | 4 + src/tools/map_extractor/System.cpp | 58 +- src/tools/map_extractor/dbcfile.cpp | 2 +- src/tools/map_extractor/dbcfile.h | 6 +- src/tools/map_extractor/mpq_libmpq.cpp | 4 +- src/tools/map_extractor/mpq_libmpq04.h | 12 +- src/tools/mmaps_generator/CMakeLists.txt | 4 + src/tools/mmaps_generator/IntermediateValues.cpp | 10 +- src/tools/mmaps_generator/IntermediateValues.h | 14 +- src/tools/mmaps_generator/MapBuilder.cpp | 26 +- src/tools/mmaps_generator/MapBuilder.h | 8 +- src/tools/mmaps_generator/PathCommon.h | 14 +- src/tools/mmaps_generator/PathGenerator.cpp | 13 +- src/tools/mmaps_generator/TerrainBuilder.cpp | 107 +-- src/tools/mmaps_generator/TerrainBuilder.h | 10 +- src/tools/vmap4_assembler/CMakeLists.txt | 8 +- src/tools/vmap4_assembler/VMapAssembler.cpp | 3 + src/tools/vmap4_extractor/CMakeLists.txt | 18 +- src/tools/vmap4_extractor/adtfile.cpp | 12 +- src/tools/vmap4_extractor/adtfile.h | 2 +- src/tools/vmap4_extractor/dbcfile.cpp | 4 +- src/tools/vmap4_extractor/dbcfile.h | 8 +- src/tools/vmap4_extractor/loadlib/loadlib.h | 26 +- src/tools/vmap4_extractor/model.cpp | 30 +- src/tools/vmap4_extractor/model.h | 4 +- src/tools/vmap4_extractor/mpq_libmpq.cpp | 4 +- src/tools/vmap4_extractor/mpq_libmpq04.h | 12 +- src/tools/vmap4_extractor/vec3d.h | 95 +-- src/tools/vmap4_extractor/vmapexport.cpp | 47 +- src/tools/vmap4_extractor/wdtfile.cpp | 8 +- src/tools/vmap4_extractor/wmo.cpp | 40 +- src/tools/vmap4_extractor/wmo.h | 2 +- 1211 files changed, 21836 insertions(+), 19088 deletions(-) create mode 100644 src/common/Banner.cpp create mode 100644 src/common/Banner.h delete mode 100644 src/common/Collision/VMapTools.h create mode 100644 src/common/DataStores/DBCFileLoader.cpp create mode 100644 src/common/DataStores/DBCFileLoader.h create mode 100644 src/common/Logging/LogCommon.h create mode 100644 src/common/Logging/LogMessage.cpp create mode 100644 src/common/Logging/LogMessage.h create mode 100644 src/common/Threading/ProcessPriority.cpp create mode 100644 src/common/Utilities/AsioHacksFwd.h create mode 100644 src/common/Utilities/AsioHacksImpl.h create mode 100644 src/common/Utilities/Hash.h create mode 100644 src/common/Utilities/Optional.h create mode 100644 src/common/Utilities/OptionalFwd.h create mode 100644 src/server/database/Database/DatabaseEnvFwd.h create mode 100644 src/server/database/Database/MySQLThreading.cpp create mode 100644 src/server/game/Entities/Creature/CreatureData.h create mode 100644 src/server/game/Entities/GameObject/GameObjectData.h create mode 100644 src/server/game/Entities/Item/ItemDefines.h create mode 100644 src/server/game/Entities/Object/MovementInfo.h create mode 100644 src/server/game/Entities/Player/EquipmentSet.h create mode 100644 src/server/game/Entities/Player/PlayerTaxi.cpp create mode 100644 src/server/game/Entities/Player/PlayerTaxi.h create mode 100644 src/server/game/Entities/Unit/UnitDefines.h create mode 100644 src/server/game/Grids/Dynamic/TypeContainer.h create mode 100644 src/server/game/Grids/Dynamic/TypeContainerFunctions.h create mode 100644 src/server/game/Grids/Dynamic/TypeContainerVisitor.h create mode 100644 src/server/game/Grids/NGrid.cpp create mode 100644 src/server/game/Loot/Loot.cpp create mode 100644 src/server/game/Loot/Loot.h create mode 100644 src/server/game/Maps/MapObject.h create mode 100644 src/server/game/Maps/MapReference.cpp create mode 100644 src/server/game/Maps/ZoneScript.cpp create mode 100644 src/server/game/Server/Packet.cpp create mode 100644 src/server/game/Server/Packets/PacketUtilities.cpp create mode 100644 src/server/game/Texts/ChatTextBuilder.cpp create mode 100644 src/server/game/Texts/CreatureTextMgrImpl.h create mode 100644 src/server/scripts/Kalimdor/Maraudon/maraudon.h create mode 100644 src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp create mode 100644 src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h create mode 100644 src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h create mode 100644 src/server/shared/DataStores/DBCDatabaseLoader.cpp create mode 100644 src/server/shared/DataStores/DBCDatabaseLoader.h delete mode 100644 src/server/shared/DataStores/DBCFileLoader.cpp delete mode 100644 src/server/shared/DataStores/DBCFileLoader.h create mode 100644 src/server/shared/DataStores/DBCStorageIterator.h create mode 100644 src/server/shared/DataStores/DBCStore.cpp delete mode 100644 src/server/shared/Dynamic/TypeContainer.h delete mode 100644 src/server/shared/Dynamic/TypeContainerFunctions.h delete mode 100644 src/server/shared/Dynamic/TypeContainerVisitor.h (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 48839d5907f..3565bd07894 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -8,6 +8,13 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +if(WIN32) + set(sources_windows + ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.cpp + ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.h + ) +endif(WIN32) + add_subdirectory(genrev) add_subdirectory(common) diff --git a/src/common/Banner.cpp b/src/common/Banner.cpp new file mode 100644 index 00000000000..e927ac6ef4a --- /dev/null +++ b/src/common/Banner.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "Banner.h" +#include "GitRevision.h" +#include "StringFormat.h" + +void Trinity::Banner::Show(char const* applicationName, void(*log)(char const* text), void(*logExtraInfo)()) +{ + log(Trinity::StringFormat("%s (%s)", GitRevision::GetFullVersion(), applicationName).c_str()); + log(" to stop.\n"); + log(" ______ __"); + log("/\\__ _\\ __ __/\\ \\__"); + log("\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); + log(" \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); + log(" \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); + log(" \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); + log(" \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); + log(" C O R E /\\___/"); + log("http://TrinityCore.org \\/__/\n"); + + if (logExtraInfo) + logExtraInfo(); +} diff --git a/src/common/Banner.h b/src/common/Banner.h new file mode 100644 index 00000000000..a23377ea04b --- /dev/null +++ b/src/common/Banner.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef TrinityCore_Banner_h__ +#define TrinityCore_Banner_h__ + +#include "Define.h" + +namespace Trinity +{ + namespace Banner + { + TC_COMMON_API void Show(char const* applicationName, void(*log)(char const* text), void(*logExtraInfo)()); + } +} + +#endif // TrinityCore_Banner_h__ diff --git a/src/common/Collision/BoundingIntervalHierarchy.h b/src/common/Collision/BoundingIntervalHierarchy.h index a80759f6cf7..539e535fa14 100644 --- a/src/common/Collision/BoundingIntervalHierarchy.h +++ b/src/common/Collision/BoundingIntervalHierarchy.h @@ -19,9 +19,9 @@ #ifndef _BIH_H #define _BIH_H -#include "G3D/Vector3.h" -#include "G3D/Ray.h" -#include "G3D/AABox.h" +#include +#include +#include #include "Define.h" @@ -80,8 +80,8 @@ class TC_COMMON_API BIH } public: BIH() { init_empty(); } - template< class BoundsFunc, class PrimArray > - void build(const PrimArray &primitives, BoundsFunc &getBounds, uint32 leafSize = 3, bool printStats=false) + template + void build(PrimArray const& primitives, BoundsFunc& getBounds, uint32 leafSize = 3, bool printStats = false) { if (primitives.size() == 0) { @@ -118,7 +118,7 @@ class TC_COMMON_API BIH uint32 primCount() const { return uint32(objects.size()); } template - void intersectRay(const G3D::Ray &r, RayCallback& intersectCallback, float &maxDist, bool stopAtFirst=false) const + void intersectRay(const G3D::Ray &r, RayCallback& intersectCallback, float &maxDist, bool stopAtFirst = false) const { float intervalMin = -1.f; float intervalMax = -1.f; diff --git a/src/common/Collision/BoundingIntervalHierarchyWrapper.h b/src/common/Collision/BoundingIntervalHierarchyWrapper.h index b7f78ea7baf..32c99798768 100644 --- a/src/common/Collision/BoundingIntervalHierarchyWrapper.h +++ b/src/common/Collision/BoundingIntervalHierarchyWrapper.h @@ -19,10 +19,10 @@ #ifndef _BIH_WRAP #define _BIH_WRAP -#include "G3D/Table.h" -#include "G3D/Array.h" -#include "G3D/Set.h" #include "BoundingIntervalHierarchy.h" +#include +#include +#include template > @@ -80,7 +80,7 @@ public: uint32 Idx = 0; const T * temp; if (m_obj2Idx.getRemove(&obj, temp, Idx)) - m_objects[Idx] = NULL; + m_objects[Idx] = nullptr; else m_objects_to_push.remove(&obj); } diff --git a/src/common/Collision/DynamicTree.cpp b/src/common/Collision/DynamicTree.cpp index 38e10318a57..46dfdb1707e 100644 --- a/src/common/Collision/DynamicTree.cpp +++ b/src/common/Collision/DynamicTree.cpp @@ -41,20 +41,20 @@ int CHECK_TREE_PERIOD = 200; } // namespace template<> struct HashTrait< GameObjectModel>{ - static size_t hashCode(const GameObjectModel& g) { return (size_t)(void*)&g; } + static size_t hashCode(GameObjectModel const& g) { return (size_t)(void*)&g; } }; template<> struct PositionTrait< GameObjectModel> { - static void getPosition(const GameObjectModel& g, G3D::Vector3& p) { p = g.getPosition(); } + static void getPosition(GameObjectModel const& g, G3D::Vector3& p) { p = g.getPosition(); } }; template<> struct BoundsTrait< GameObjectModel> { - static void getBounds(const GameObjectModel& g, G3D::AABox& out) { out = g.getBounds();} - static void getBounds2(const GameObjectModel* g, G3D::AABox& out) { out = g->getBounds();} + static void getBounds(GameObjectModel const& g, G3D::AABox& out) { out = g.getBounds();} + static void getBounds2(GameObjectModel const* g, G3D::AABox& out) { out = g->getBounds();} }; /* -static bool operator == (const GameObjectModel& mdl, const GameObjectModel& mdl2){ +static bool operator==(GameObjectModel const& mdl, GameObjectModel const& mdl2){ return &mdl == &mdl2; } */ @@ -72,13 +72,13 @@ struct DynTreeImpl : public ParentTree/*, public Intersectable*/ { } - void insert(const Model& mdl) + void insert(Model const& mdl) { base::insert(mdl); ++unbalanced_times; } - void remove(const Model& mdl) + void remove(Model const& mdl) { base::remove(mdl); ++unbalanced_times; @@ -115,17 +115,17 @@ DynamicMapTree::~DynamicMapTree() delete impl; } -void DynamicMapTree::insert(const GameObjectModel& mdl) +void DynamicMapTree::insert(GameObjectModel const& mdl) { impl->insert(mdl); } -void DynamicMapTree::remove(const GameObjectModel& mdl) +void DynamicMapTree::remove(GameObjectModel const& mdl) { impl->remove(mdl); } -bool DynamicMapTree::contains(const GameObjectModel& mdl) const +bool DynamicMapTree::contains(GameObjectModel const& mdl) const { return impl->contains(mdl); } @@ -145,7 +145,7 @@ struct DynamicTreeIntersectionCallback bool did_hit; uint32 phase_mask; DynamicTreeIntersectionCallback(uint32 phasemask) : did_hit(false), phase_mask(phasemask) { } - bool operator()(const G3D::Ray& r, const GameObjectModel& obj, float& distance) + bool operator()(G3D::Ray const& r, GameObjectModel const& obj, float& distance) { did_hit = obj.intersectRay(r, distance, true, phase_mask, VMAP::ModelIgnoreFlags::Nothing); return did_hit; @@ -161,7 +161,7 @@ struct DynamicTreeIntersectionCallback_WithLogger { TC_LOG_DEBUG("maps", "Dynamic Intersection log"); } - bool operator()(const G3D::Ray& r, const GameObjectModel& obj, float& distance) + bool operator()(G3D::Ray const& r, GameObjectModel const& obj, float& distance) { TC_LOG_DEBUG("maps", "testing intersection with %s", obj.name.c_str()); bool hit = obj.intersectRay(r, distance, true, phase_mask, VMAP::ModelIgnoreFlags::Nothing); diff --git a/src/common/Collision/DynamicTree.h b/src/common/Collision/DynamicTree.h index 49458393906..0e1d1f0342b 100644 --- a/src/common/Collision/DynamicTree.h +++ b/src/common/Collision/DynamicTree.h @@ -52,9 +52,9 @@ public: float getHeight(float x, float y, float z, float maxSearchDist, uint32 phasemask) const; - void insert(const GameObjectModel&); - void remove(const GameObjectModel&); - bool contains(const GameObjectModel&) const; + void insert(GameObjectModel const&); + void remove(GameObjectModel const&); + bool contains(GameObjectModel const&) const; void balance(); void update(uint32 diff); diff --git a/src/common/Collision/Management/IVMapManager.h b/src/common/Collision/Management/IVMapManager.h index e77987a721d..0371135cfa5 100644 --- a/src/common/Collision/Management/IVMapManager.h +++ b/src/common/Collision/Management/IVMapManager.h @@ -19,10 +19,10 @@ #ifndef _IVMAPMANAGER_H #define _IVMAPMANAGER_H -#include #include "Define.h" #include "ModelIgnoreFlags.h" -#include "Common.h" +#include "Optional.h" +#include //=========================================================== @@ -83,9 +83,9 @@ namespace VMAP virtual ~IVMapManager(void) { } - virtual int loadMap(const char* pBasePath, unsigned int pMapId, int x, int y) = 0; + virtual int loadMap(char const* pBasePath, unsigned int pMapId, int x, int y) = 0; - virtual LoadResult existsMap(const char* pBasePath, unsigned int pMapId, int x, int y) = 0; + virtual LoadResult existsMap(char const* pBasePath, unsigned int pMapId, int x, int y) = 0; virtual void unloadMap(unsigned int pMapId, int x, int y) = 0; virtual void unloadMap(unsigned int pMapId) = 0; diff --git a/src/common/Collision/Management/MMapFactory.cpp b/src/common/Collision/Management/MMapFactory.cpp index 1257d852697..02295c2b2db 100644 --- a/src/common/Collision/Management/MMapFactory.cpp +++ b/src/common/Collision/Management/MMapFactory.cpp @@ -23,11 +23,11 @@ namespace MMAP { // ######################## MMapFactory ######################## // our global singleton copy - MMapManager* g_MMapManager = NULL; + MMapManager* g_MMapManager = nullptr; MMapManager* MMapFactory::createOrGetMMapManager() { - if (g_MMapManager == NULL) + if (g_MMapManager == nullptr) g_MMapManager = new MMapManager(); return g_MMapManager; @@ -38,7 +38,7 @@ namespace MMAP if (g_MMapManager) { delete g_MMapManager; - g_MMapManager = NULL; + g_MMapManager = nullptr; } } } \ No newline at end of file diff --git a/src/common/Collision/Management/MMapManager.cpp b/src/common/Collision/Management/MMapManager.cpp index cec5c0da7f0..ff87ed369cc 100644 --- a/src/common/Collision/Management/MMapManager.cpp +++ b/src/common/Collision/Management/MMapManager.cpp @@ -17,6 +17,7 @@ */ #include "MMapManager.h" +#include "Errors.h" #include "Log.h" #include "Config.h" #include "MapDefines.h" @@ -39,7 +40,7 @@ namespace MMAP void MMapManager::InitializeThreadUnsafe(const std::vector& mapIds) { // the caller must pass the list of all mapIds that will be used in the VMapManager2 lifetime - for (const uint32& mapId : mapIds) + for (uint32 const& mapId : mapIds) loadedMMaps.insert(MMapDataSet::value_type(mapId, nullptr)); thread_safe_environment = false; @@ -222,7 +223,7 @@ namespace MMAP dtTileRef tileRef = mmap->loadedTileRefs[packedGridPos]; // unload, and mark as non loaded - if (dtStatusFailed(mmap->navMesh->removeTile(tileRef, NULL, NULL))) + if (dtStatusFailed(mmap->navMesh->removeTile(tileRef, nullptr, nullptr))) { // this is technically a memory leak // if the grid is later reloaded, dtNavMesh::addTile will return error but no extra memory is used @@ -257,7 +258,7 @@ namespace MMAP { uint32 x = (i->first >> 16); uint32 y = (i->first & 0x0000FFFF); - if (dtStatusFailed(mmap->navMesh->removeTile(i->second, NULL, NULL))) + if (dtStatusFailed(mmap->navMesh->removeTile(i->second, nullptr, nullptr))) TC_LOG_ERROR("maps", "MMAP:unloadMap: Could not unload %03u%02i%02i.mmtile from navmesh", mapId, x, y); else { @@ -304,7 +305,7 @@ namespace MMAP { MMapDataSet::const_iterator itr = GetMMapData(mapId); if (itr == loadedMMaps.end()) - return NULL; + return nullptr; return itr->second->navMesh; } @@ -313,7 +314,7 @@ namespace MMAP { MMapDataSet::const_iterator itr = GetMMapData(mapId); if (itr == loadedMMaps.end()) - return NULL; + return nullptr; MMapData* mmap = itr->second; if (mmap->navMeshQueries.find(instanceId) == mmap->navMeshQueries.end()) @@ -325,7 +326,7 @@ namespace MMAP { dtFreeNavMeshQuery(query); TC_LOG_ERROR("maps", "MMAP:GetNavMeshQuery: Failed to initialize dtNavMeshQuery for mapId %03u instanceId %u", mapId, instanceId); - return NULL; + return nullptr; } TC_LOG_DEBUG("maps", "MMAP:GetNavMeshQuery: created dtNavMeshQuery for mapId %03u instanceId %u", mapId, instanceId); diff --git a/src/common/Collision/Management/VMapFactory.cpp b/src/common/Collision/Management/VMapFactory.cpp index f36f237c4b2..f8c4be61617 100644 --- a/src/common/Collision/Management/VMapFactory.cpp +++ b/src/common/Collision/Management/VMapFactory.cpp @@ -21,7 +21,7 @@ namespace VMAP { - IVMapManager* gVMapManager = NULL; + IVMapManager* gVMapManager = nullptr; //=============================================== // just return the instance @@ -37,6 +37,6 @@ namespace VMAP void VMapFactory::clear() { delete gVMapManager; - gVMapManager = NULL; + gVMapManager = nullptr; } } diff --git a/src/common/Collision/Management/VMapManager2.cpp b/src/common/Collision/Management/VMapManager2.cpp index 33bf7338616..7c894efa1ca 100644 --- a/src/common/Collision/Management/VMapManager2.cpp +++ b/src/common/Collision/Management/VMapManager2.cpp @@ -55,7 +55,7 @@ namespace VMAP void VMapManager2::InitializeThreadUnsafe(const std::vector& mapIds) { // the caller must pass the list of all mapIds that will be used in the VMapManager2 lifetime - for (const uint32& mapId : mapIds) + for (uint32 const& mapId : mapIds) iInstanceMapTrees.insert(InstanceTreeMap::value_type(mapId, nullptr)); thread_safe_environment = false; @@ -82,7 +82,7 @@ namespace VMAP return fname.str(); } - int VMapManager2::loadMap(const char* basePath, unsigned int mapId, int x, int y) + int VMapManager2::loadMap(char const* basePath, unsigned int mapId, int x, int y) { int result = VMAP_LOAD_RESULT_IGNORED; if (isMapLoadingEnabled()) @@ -323,7 +323,7 @@ namespace VMAP { VMAP_ERROR_LOG("misc", "VMapManager2: could not load '%s%s.vmo'", basepath.c_str(), filename.c_str()); delete worldmodel; - return NULL; + return nullptr; } VMAP_DEBUG_LOG("maps", "VMapManager2: loading file '%s%s'", basepath.c_str(), filename.c_str()); @@ -355,7 +355,7 @@ namespace VMAP } } - LoadResult VMapManager2::existsMap(const char* basePath, unsigned int mapId, int x, int y) + LoadResult VMapManager2::existsMap(char const* basePath, unsigned int mapId, int x, int y) { return StaticMapTree::CanLoadMap(std::string(basePath), mapId, x, y); } diff --git a/src/common/Collision/Management/VMapManager2.h b/src/common/Collision/Management/VMapManager2.h index 3fdc427d6eb..b8d59b9c09e 100644 --- a/src/common/Collision/Management/VMapManager2.h +++ b/src/common/Collision/Management/VMapManager2.h @@ -102,7 +102,7 @@ namespace VMAP ~VMapManager2(void); void InitializeThreadUnsafe(const std::vector& mapIds); - int loadMap(const char* pBasePath, unsigned int mapId, int x, int y) override; + int loadMap(char const* pBasePath, unsigned int mapId, int x, int y) override; void unloadMap(unsigned int mapId, int x, int y) override; void unloadMap(unsigned int mapId) override; @@ -128,7 +128,7 @@ namespace VMAP { return getMapFileName(mapId); } - virtual LoadResult existsMap(const char* basePath, unsigned int mapId, int x, int y) override; + virtual LoadResult existsMap(char const* basePath, unsigned int mapId, int x, int y) override; void getInstanceMapTree(InstanceTreeMap &instanceMapTree); diff --git a/src/common/Collision/Maps/MapDefines.h b/src/common/Collision/Maps/MapDefines.h index 4b53975237e..3dd19735ff9 100644 --- a/src/common/Collision/Maps/MapDefines.h +++ b/src/common/Collision/Maps/MapDefines.h @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #ifndef _MAPDEFINES_H #define _MAPDEFINES_H diff --git a/src/common/Collision/Maps/MapTree.cpp b/src/common/Collision/Maps/MapTree.cpp index f3fe8c1f56f..1f2a8a60c73 100644 --- a/src/common/Collision/Maps/MapTree.cpp +++ b/src/common/Collision/Maps/MapTree.cpp @@ -37,7 +37,7 @@ namespace VMAP { public: MapRayCallback(ModelInstance* val, ModelIgnoreFlags ignoreFlags): prims(val), hit(false), flags(ignoreFlags) { } - bool operator()(const G3D::Ray& ray, uint32 entry, float& distance, bool pStopAtFirstHit=true) + bool operator()(const G3D::Ray& ray, uint32 entry, float& distance, bool pStopAtFirstHit = true) { bool result = prims[entry].intersectRay(ray, distance, pStopAtFirstHit, flags); if (result) @@ -55,7 +55,7 @@ namespace VMAP { public: AreaInfoCallback(ModelInstance* val): prims(val) { } - void operator()(const Vector3& point, uint32 entry) + void operator()(Vector3 const& point, uint32 entry) { #ifdef VMAP_DEBUG TC_LOG_DEBUG("maps", "AreaInfoCallback: trying to intersect '%s'", prims[entry].name.c_str()); @@ -71,7 +71,7 @@ namespace VMAP { public: LocationInfoCallback(ModelInstance* val, LocationInfo &info): prims(val), locInfo(info), result(false) { } - void operator()(const Vector3& point, uint32 entry) + void operator()(Vector3 const& point, uint32 entry) { #ifdef VMAP_DEBUG TC_LOG_DEBUG("maps", "LocationInfoCallback: trying to intersect '%s'", prims[entry].name.c_str()); @@ -113,15 +113,15 @@ namespace VMAP return false; } - bool StaticMapTree::GetLocationInfo(const Vector3 &pos, LocationInfo &info) const + bool StaticMapTree::GetLocationInfo(Vector3 const& pos, LocationInfo &info) const { LocationInfoCallback intersectionCallBack(iTreeValues, info); iTree.intersectPoint(pos, intersectionCallBack); return intersectionCallBack.result; } - StaticMapTree::StaticMapTree(uint32 mapID, const std::string &basePath) : - iMapID(mapID), iIsTiled(false), iTreeValues(NULL), + StaticMapTree::StaticMapTree(uint32 mapID, std::string const& basePath) : + iMapID(mapID), iIsTiled(false), iTreeValues(nullptr), iNTreeValues(0), iBasePath(basePath) { if (iBasePath.length() > 0 && iBasePath[iBasePath.length()-1] != '/' && iBasePath[iBasePath.length()-1] != '\\') @@ -153,7 +153,7 @@ namespace VMAP } //========================================================= - bool StaticMapTree::isInLineOfSight(const Vector3& pos1, const Vector3& pos2, ModelIgnoreFlags ignoreFlag) const + bool StaticMapTree::isInLineOfSight(Vector3 const& pos1, Vector3 const& pos2, ModelIgnoreFlags ignoreFlag) const { float maxDist = (pos2 - pos1).magnitude(); // return false if distance is over max float, in case of cheater teleporting to the end of the universe @@ -178,9 +178,9 @@ namespace VMAP Return the hit pos or the original dest pos */ - bool StaticMapTree::getObjectHitPos(const Vector3& pPos1, const Vector3& pPos2, Vector3& pResultHitPos, float pModifyDist) const + bool StaticMapTree::getObjectHitPos(Vector3 const& pPos1, Vector3 const& pPos2, Vector3& pResultHitPos, float pModifyDist) const { - bool result=false; + bool result = false; float maxDist = (pPos2 - pPos1).magnitude(); // valid map coords should *never ever* produce float overflow, but this would produce NaNs too ASSERT(maxDist < std::numeric_limits::max()); @@ -223,7 +223,7 @@ namespace VMAP //========================================================= - float StaticMapTree::getHeight(const Vector3& pPos, float maxSearchDist) const + float StaticMapTree::getHeight(Vector3 const& pPos, float maxSearchDist) const { float height = G3D::finf(); Vector3 dir = Vector3(0, 0, -1); @@ -438,7 +438,7 @@ namespace VMAP FILE* tf = fopen(tilefile.c_str(), "rb"); if (tf) { - bool result=true; + bool result = true; char chunk[8]; if (!readChunk(tf, chunk, VMAP_MAGIC, 8)) result = false; diff --git a/src/common/Collision/Maps/MapTree.h b/src/common/Collision/Maps/MapTree.h index bc18e07789b..6dc32c1241a 100644 --- a/src/common/Collision/Maps/MapTree.h +++ b/src/common/Collision/Maps/MapTree.h @@ -36,8 +36,8 @@ namespace VMAP { LocationInfo(): hitInstance(nullptr), hitModel(nullptr), ground_Z(-G3D::finf()) { } int32 rootId; - const ModelInstance* hitInstance; - const GroupModel* hitModel; + ModelInstance const* hitInstance; + GroupModel const* hitModel; float ground_Z; }; diff --git a/src/common/Collision/Maps/TileAssembler.cpp b/src/common/Collision/Maps/TileAssembler.cpp index 2c4d3105050..fe00458cf6d 100644 --- a/src/common/Collision/Maps/TileAssembler.cpp +++ b/src/common/Collision/Maps/TileAssembler.cpp @@ -32,7 +32,7 @@ using std::pair; template<> struct BoundsTrait { - static void getBounds(const VMAP::ModelSpawn* const &obj, G3D::AABox& out) { out = obj->getBounds(); } + static void getBounds(VMAP::ModelSpawn const* const& obj, G3D::AABox& out) { out = obj->getBounds(); } }; namespace VMAP @@ -43,7 +43,7 @@ namespace VMAP return memcmp(dest, compare, len) == 0; } - Vector3 ModelPosition::transform(const Vector3& pIn) const + Vector3 ModelPosition::transform(Vector3 const& pIn) const { Vector3 out = pIn * iScale; out = iRotation * out; @@ -53,7 +53,7 @@ namespace VMAP //================================================================= TileAssembler::TileAssembler(const std::string& pSrcDirName, const std::string& pDestDirName) - : iDestDir(pDestDirName), iSrcDir(pSrcDirName), iFilterMethod(NULL), iCurrentUniqueNameId(0) + : iDestDir(pDestDirName), iSrcDir(pSrcDirName), iFilterMethod(nullptr), iCurrentUniqueNameId(0) { //mkdir(iDestDir); //init(); @@ -136,10 +136,8 @@ namespace VMAP // global map spawns (WDT), if any (most instances) if (success && fwrite("GOBJ", 4, 1, mapfile) != 1) success = false; - for (TileMap::iterator glob=globalRange.first; glob != globalRange.second && success; ++glob) - { + for (TileMap::iterator glob = globalRange.first; glob != globalRange.second && success; ++glob) success = ModelSpawn::writeToFile(mapfile, map_iter->second->UniqueEntries[glob->second]); - } fclose(mapfile); @@ -150,7 +148,7 @@ namespace VMAP TileMap::iterator tile; for (tile = tileEntries.begin(); tile != tileEntries.end(); ++tile) { - const ModelSpawn &spawn = map_iter->second->UniqueEntries[tile->second]; + ModelSpawn const& spawn = map_iter->second->UniqueEntries[tile->second]; if (spawn.flags & MOD_WORLDSPAWN) // WDT spawn, saved as tile 65/65 currently... continue; uint32 nSpawns = tileEntries.count(tile->first); @@ -171,7 +169,7 @@ namespace VMAP { if (s) ++tile; - const ModelSpawn &spawn2 = map_iter->second->UniqueEntries[tile->second]; + ModelSpawn const& spawn2 = map_iter->second->UniqueEntries[tile->second]; success = success && ModelSpawn::writeToFile(tilefile, spawn2); // MapTree nodes to update when loading tile: std::map::iterator nIdx = modelNodeIdx.find(spawn2.ID); @@ -266,9 +264,9 @@ namespace VMAP printf("Warning: '%s' does not seem to be a M2 model!\n", modelFilename.c_str()); AABox modelBound; - bool boundEmpty=true; + bool boundEmpty = true; - for (uint32 g=0; g& vertices = raw_model.groupsArray[g].vertexArray; @@ -284,7 +282,10 @@ namespace VMAP Vector3 v = modelPosition.transform(vertices[i]); if (boundEmpty) - modelBound = AABox(v, v), boundEmpty=false; + { + modelBound = AABox(v, v); + boundEmpty = false; + } else modelBound.merge(v); } diff --git a/src/common/Collision/Maps/TileAssembler.h b/src/common/Collision/Maps/TileAssembler.h index ae0585dbd57..f11f2682a0d 100644 --- a/src/common/Collision/Maps/TileAssembler.h +++ b/src/common/Collision/Maps/TileAssembler.h @@ -76,7 +76,7 @@ namespace VMAP class WmoLiquid* liquid; GroupModel_Raw() : mogpflags(0), GroupWMOID(0), liquidflags(0), - liquid(NULL) { } + liquid(nullptr) { } ~GroupModel_Raw(); bool Read(FILE* f); diff --git a/src/common/Collision/Models/GameObjectModel.cpp b/src/common/Collision/Models/GameObjectModel.cpp index 2950a48c21b..992ec59e1af 100644 --- a/src/common/Collision/Models/GameObjectModel.cpp +++ b/src/common/Collision/Models/GameObjectModel.cpp @@ -30,7 +30,7 @@ using G3D::AABox; struct GameobjectModelData { - GameobjectModelData(const std::string& name_, const AABox& box) : + GameobjectModelData(std::string const& name_, AABox const& box) : bound(box), name(name_) { } AABox bound; @@ -147,7 +147,7 @@ GameObjectModel* GameObjectModel::Create(std::unique_ptrinitialize(std::move(modelOwner), dataPath)) { delete mdl; - return NULL; + return nullptr; } return mdl; diff --git a/src/common/Collision/Models/GameObjectModel.h b/src/common/Collision/Models/GameObjectModel.h index c121e421e6d..72fee944380 100644 --- a/src/common/Collision/Models/GameObjectModel.h +++ b/src/common/Collision/Models/GameObjectModel.h @@ -50,7 +50,7 @@ public: class TC_COMMON_API GameObjectModel /*, public Intersectable*/ { - GameObjectModel() : phasemask(0), iInvScale(0), iScale(0), iModel(NULL) { } + GameObjectModel() : phasemask(0), iInvScale(0), iScale(0), iModel(nullptr) { } public: std::string name; diff --git a/src/common/Collision/Models/ModelInstance.cpp b/src/common/Collision/Models/ModelInstance.cpp index 3390b233c82..3eeb0e8c669 100644 --- a/src/common/Collision/Models/ModelInstance.cpp +++ b/src/common/Collision/Models/ModelInstance.cpp @@ -25,13 +25,13 @@ using G3D::Ray; namespace VMAP { - ModelInstance::ModelInstance(const ModelSpawn &spawn, WorldModel* model): ModelSpawn(spawn), iModel(model) + ModelInstance::ModelInstance(ModelSpawn const& spawn, WorldModel* model): ModelSpawn(spawn), iModel(model) { iInvRot = G3D::Matrix3::fromEulerAnglesZYX(G3D::pif()*iRot.y/180.f, G3D::pif()*iRot.x/180.f, G3D::pif()*iRot.z/180.f).inverse(); iInvScale = 1.f/iScale; } - bool ModelInstance::intersectRay(const G3D::Ray& pRay, float& pMaxDist, bool pStopAtFirstHit, ModelIgnoreFlags ignoreFlags) const + bool ModelInstance::intersectRay(G3D::Ray const& pRay, float& pMaxDist, bool pStopAtFirstHit, ModelIgnoreFlags ignoreFlags) const { if (!iModel) { @@ -196,7 +196,7 @@ namespace VMAP return true; } - bool ModelSpawn::writeToFile(FILE* wf, const ModelSpawn &spawn) + bool ModelSpawn::writeToFile(FILE* wf, ModelSpawn const& spawn) { uint32 check=0; check += fwrite(&spawn.flags, sizeof(uint32), 1, wf); diff --git a/src/common/Collision/Models/ModelInstance.h b/src/common/Collision/Models/ModelInstance.h index 3036ac10117..fa53ceab70d 100644 --- a/src/common/Collision/Models/ModelInstance.h +++ b/src/common/Collision/Models/ModelInstance.h @@ -52,25 +52,25 @@ namespace VMAP float iScale; G3D::AABox iBound; std::string name; - bool operator==(const ModelSpawn &other) const { return ID == other.ID; } + bool operator==(ModelSpawn const& other) const { return ID == other.ID; } //uint32 hashCode() const { return ID; } // temp? const G3D::AABox& getBounds() const { return iBound; } static bool readFromFile(FILE* rf, ModelSpawn &spawn); - static bool writeToFile(FILE* rw, const ModelSpawn &spawn); + static bool writeToFile(FILE* rw, ModelSpawn const& spawn); }; class TC_COMMON_API ModelInstance: public ModelSpawn { public: ModelInstance(): iInvScale(0.0f), iModel(nullptr) { } - ModelInstance(const ModelSpawn &spawn, WorldModel* model); + ModelInstance(ModelSpawn const& spawn, WorldModel* model); void setUnloaded() { iModel = nullptr; } - bool intersectRay(const G3D::Ray& pRay, float& pMaxDist, bool pStopAtFirstHit, ModelIgnoreFlags ignoreFlags) const; - void intersectPoint(const G3D::Vector3& p, AreaInfo &info) const; - bool GetLocationInfo(const G3D::Vector3& p, LocationInfo &info) const; - bool GetLiquidLevel(const G3D::Vector3& p, LocationInfo &info, float &liqHeight) const; + bool intersectRay(G3D::Ray const& pRay, float& pMaxDist, bool pStopAtFirstHit, ModelIgnoreFlags ignoreFlags) const; + void intersectPoint(G3D::Vector3 const& p, AreaInfo &info) const; + bool GetLocationInfo(G3D::Vector3 const& p, LocationInfo &info) const; + bool GetLiquidLevel(G3D::Vector3 const& p, LocationInfo &info, float &liqHeight) const; WorldModel* getWorldModel() { return iModel; } protected: G3D::Matrix3 iInvRot; diff --git a/src/common/Collision/Models/WorldModel.cpp b/src/common/Collision/Models/WorldModel.cpp index d04bcf4d241..7a40ba215cf 100644 --- a/src/common/Collision/Models/WorldModel.cpp +++ b/src/common/Collision/Models/WorldModel.cpp @@ -32,7 +32,7 @@ template<> struct BoundsTrait namespace VMAP { - bool IntersectTriangle(const MeshTriangle &tri, std::vector::const_iterator points, const G3D::Ray &ray, float &distance) + bool IntersectTriangle(MeshTriangle const& tri, std::vector::const_iterator points, G3D::Ray const& ray, float& distance) { static const float EPS = 1e-5f; @@ -85,8 +85,8 @@ namespace VMAP class TriBoundFunc { public: - TriBoundFunc(std::vector &vert): vertices(vert.begin()) { } - void operator()(const MeshTriangle &tri, G3D::AABox &out) const + TriBoundFunc(std::vector& vert): vertices(vert.begin()) { } + void operator()(MeshTriangle const& tri, G3D::AABox& out) const { G3D::Vector3 lo = vertices[tri.idx0]; G3D::Vector3 hi = lo; @@ -102,14 +102,14 @@ namespace VMAP // ===================== WmoLiquid ================================== - WmoLiquid::WmoLiquid(uint32 width, uint32 height, const Vector3 &corner, uint32 type): + WmoLiquid::WmoLiquid(uint32 width, uint32 height, Vector3 const& corner, uint32 type) : iTilesX(width), iTilesY(height), iCorner(corner), iType(type) { - iHeight = new float[(width+1)*(height+1)]; + iHeight = new float[(width + 1) * (height + 1)]; iFlags = new uint8[width*height]; } - WmoLiquid::WmoLiquid(const WmoLiquid &other): iHeight(nullptr), iFlags(nullptr) + WmoLiquid::WmoLiquid(WmoLiquid const& other): iHeight(nullptr), iFlags(nullptr) { *this = other; // use assignment operator... } @@ -120,7 +120,7 @@ namespace VMAP delete[] iFlags; } - WmoLiquid& WmoLiquid::operator=(const WmoLiquid &other) + WmoLiquid& WmoLiquid::operator=(WmoLiquid const& other) { if (this == &other) return *this; @@ -147,7 +147,7 @@ namespace VMAP return *this; } - bool WmoLiquid::GetLiquidHeight(const Vector3 &pos, float &liqHeight) const + bool WmoLiquid::GetLiquidHeight(Vector3 const& pos, float &liqHeight) const { float tx_f = (pos.x - iCorner.x)/LIQUID_TILE_SIZE; uint32 tx = uint32(tx_f); @@ -180,7 +180,7 @@ namespace VMAP 0 1 */ - const uint32 rowOffset = iTilesX + 1; + uint32 const rowOffset = iTilesX + 1; if (dx > dy) // case (a) { float sx = iHeight[tx+1 + ty * rowOffset] - iHeight[tx + ty * rowOffset]; @@ -260,7 +260,7 @@ namespace VMAP // ===================== GroupModel ================================== - GroupModel::GroupModel(const GroupModel &other): + GroupModel::GroupModel(GroupModel const& other): iBound(other.iBound), iMogpFlags(other.iMogpFlags), iGroupWMOID(other.iGroupWMOID), vertices(other.vertices), triangles(other.triangles), meshTree(other.meshTree), iLiquid(nullptr) { @@ -331,7 +331,7 @@ namespace VMAP triangles.clear(); vertices.clear(); delete iLiquid; - iLiquid = NULL; + iLiquid = nullptr; if (result && fread(&iBound, sizeof(G3D::AABox), 1, rf) != 1) result = false; if (result && fread(&iMogpFlags, sizeof(uint32), 1, rf) != 1) result = false; @@ -367,12 +367,13 @@ namespace VMAP struct GModelRayCallback { - GModelRayCallback(const std::vector &tris, const std::vector &vert): + GModelRayCallback(std::vector const& tris, const std::vector &vert): vertices(vert.begin()), triangles(tris.begin()), hit(false) { } - bool operator()(const G3D::Ray& ray, uint32 entry, float& distance, bool /*pStopAtFirstHit*/) + bool operator()(G3D::Ray const& ray, uint32 entry, float& distance, bool /*pStopAtFirstHit*/) { bool result = IntersectTriangle(triangles[entry], vertices, ray, distance); - if (result) hit=true; + if (result) + hit = true; return hit; } std::vector::const_iterator vertices; @@ -380,7 +381,7 @@ namespace VMAP bool hit; }; - bool GroupModel::IntersectRay(const G3D::Ray &ray, float &distance, bool stopAtFirstHit) const + bool GroupModel::IntersectRay(G3D::Ray const& ray, float& distance, bool stopAtFirstHit) const { if (triangles.empty()) return false; @@ -390,7 +391,7 @@ namespace VMAP return callback.hit; } - bool GroupModel::IsInsideObject(const Vector3 &pos, const Vector3 &down, float &z_dist) const + bool GroupModel::IsInsideObject(Vector3 const& pos, Vector3 const& down, float& z_dist) const { if (triangles.empty() || !iBound.contains(pos)) return false; @@ -404,7 +405,7 @@ namespace VMAP return hit; } - bool GroupModel::GetLiquidLevel(const Vector3 &pos, float &liqHeight) const + bool GroupModel::GetLiquidLevel(Vector3 const& pos, float& liqHeight) const { if (iLiquid) return iLiquid->GetLiquidHeight(pos, liqHeight); @@ -427,7 +428,7 @@ namespace VMAP // ===================== WorldModel ================================== - void WorldModel::setGroupModels(std::vector &models) + void WorldModel::setGroupModels(std::vector& models) { groupModels.swap(models); groupTree.build(groupModels, BoundsTrait::getBounds, 1); @@ -435,18 +436,19 @@ namespace VMAP struct WModelRayCallBack { - WModelRayCallBack(const std::vector &mod): models(mod.begin()), hit(false) { } - bool operator()(const G3D::Ray& ray, uint32 entry, float& distance, bool pStopAtFirstHit) + WModelRayCallBack(std::vector const& mod): models(mod.begin()), hit(false) { } + bool operator()(G3D::Ray const& ray, uint32 entry, float& distance, bool pStopAtFirstHit) { bool result = models[entry].IntersectRay(ray, distance, pStopAtFirstHit); - if (result) hit=true; + if (result) + hit = true; return hit; } std::vector::const_iterator models; bool hit; }; - bool WorldModel::IntersectRay(const G3D::Ray &ray, float &distance, bool stopAtFirstHit, ModelIgnoreFlags ignoreFlags) const + bool WorldModel::IntersectRay(G3D::Ray const& ray, float& distance, bool stopAtFirstHit, ModelIgnoreFlags ignoreFlags) const { // If the caller asked us to ignore certain objects we should check flags if ((ignoreFlags & ModelIgnoreFlags::M2) != ModelIgnoreFlags::Nothing) @@ -468,14 +470,14 @@ namespace VMAP class WModelAreaCallback { public: - WModelAreaCallback(const std::vector &vals, const Vector3 &down): + WModelAreaCallback(std::vector const& vals, Vector3 const& down) : prims(vals.begin()), hit(vals.end()), minVol(G3D::finf()), zDist(G3D::finf()), zVec(down) { } std::vector::const_iterator prims; std::vector::const_iterator hit; float minVol; float zDist; Vector3 zVec; - void operator()(const Vector3& point, uint32 entry) + void operator()(Vector3 const& point, uint32 entry) { float group_Z; //float pVol = prims[entry].GetBound().volume(); @@ -492,7 +494,7 @@ namespace VMAP hit = prims + entry; } #ifdef VMAP_DEBUG - const GroupModel &gm = prims[entry]; + GroupModel const& gm = prims[entry]; printf("%10u %8X %7.3f, %7.3f, %7.3f | %7.3f, %7.3f, %7.3f | z=%f, p_z=%f\n", gm.GetWmoID(), gm.GetMogpFlags(), gm.GetBound().low().x, gm.GetBound().low().y, gm.GetBound().low().z, gm.GetBound().high().x, gm.GetBound().high().y, gm.GetBound().high().z, group_Z, point.z); @@ -553,7 +555,7 @@ namespace VMAP if (result && fwrite(&RootWMOID, sizeof(uint32), 1, wf) != 1) result = false; // write group models - count=groupModels.size(); + count = groupModels.size(); if (count) { if (result && fwrite("GMOD", 1, 4, wf) != 4) result = false; diff --git a/src/common/Collision/Models/WorldModel.h b/src/common/Collision/Models/WorldModel.h index df472708209..935598d3941 100644 --- a/src/common/Collision/Models/WorldModel.h +++ b/src/common/Collision/Models/WorldModel.h @@ -48,11 +48,11 @@ namespace VMAP class TC_COMMON_API WmoLiquid { public: - WmoLiquid(uint32 width, uint32 height, const G3D::Vector3 &corner, uint32 type); - WmoLiquid(const WmoLiquid &other); + WmoLiquid(uint32 width, uint32 height, G3D::Vector3 const& corner, uint32 type); + WmoLiquid(WmoLiquid const& other); ~WmoLiquid(); - WmoLiquid& operator=(const WmoLiquid &other); - bool GetLiquidHeight(const G3D::Vector3 &pos, float &liqHeight) const; + WmoLiquid& operator=(WmoLiquid const& other); + bool GetLiquidHeight(G3D::Vector3 const& pos, float& liqHeight) const; uint32 GetType() const { return iType; } float *GetHeightStorage() { return iHeight; } uint8 *GetFlagsStorage() { return iFlags; } @@ -61,7 +61,7 @@ namespace VMAP static bool readFromFile(FILE* rf, WmoLiquid* &liquid); void getPosInfo(uint32 &tilesX, uint32 &tilesY, G3D::Vector3 &corner) const; private: - WmoLiquid() : iTilesX(0), iTilesY(0), iCorner(), iType(0), iHeight(NULL), iFlags(NULL) { } + WmoLiquid() : iTilesX(0), iTilesY(0), iCorner(), iType(0), iHeight(nullptr), iFlags(nullptr) { } uint32 iTilesX; //!< number of tiles in x direction, each uint32 iTilesY; G3D::Vector3 iCorner; //!< the lower corner @@ -74,15 +74,15 @@ namespace VMAP class TC_COMMON_API GroupModel { public: - GroupModel() : iBound(), iMogpFlags(0), iGroupWMOID(0), iLiquid(NULL) { } - GroupModel(const GroupModel &other); - GroupModel(uint32 mogpFlags, uint32 groupWMOID, const G3D::AABox &bound): - iBound(bound), iMogpFlags(mogpFlags), iGroupWMOID(groupWMOID), iLiquid(NULL) { } + GroupModel() : iBound(), iMogpFlags(0), iGroupWMOID(0), iLiquid(nullptr) { } + GroupModel(GroupModel const& other); + GroupModel(uint32 mogpFlags, uint32 groupWMOID, G3D::AABox const& bound): + iBound(bound), iMogpFlags(mogpFlags), iGroupWMOID(groupWMOID), iLiquid(nullptr) { } ~GroupModel() { delete iLiquid; } //! pass mesh data to object and create BIH. Passed vectors get get swapped with old geometry! void setMeshData(std::vector &vert, std::vector &tri); - void setLiquidData(WmoLiquid*& liquid) { iLiquid = liquid; liquid = NULL; } + void setLiquidData(WmoLiquid*& liquid) { iLiquid = liquid; liquid = nullptr; } bool IntersectRay(const G3D::Ray &ray, float &distance, bool stopAtFirstHit) const; bool IsInsideObject(const G3D::Vector3 &pos, const G3D::Vector3 &down, float &z_dist) const; bool GetLiquidLevel(const G3D::Vector3 &pos, float &liqHeight) const; diff --git a/src/common/Collision/RegularGrid.h b/src/common/Collision/RegularGrid.h index 4d045179290..0800276f065 100644 --- a/src/common/Collision/RegularGrid.h +++ b/src/common/Collision/RegularGrid.h @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #ifndef _REGULAR_GRID_H #define _REGULAR_GRID_H @@ -86,15 +103,18 @@ public: struct Cell { int x, y; - bool operator == (const Cell& c2) const { return x == c2.x && y == c2.y;} + bool operator==(Cell const& c2) const + { + return x == c2.x && y == c2.y; + } static Cell ComputeCell(float fx, float fy) { - Cell c = { int(fx * (1.f/CELL_SIZE) + (CELL_NUMBER/2)), int(fy * (1.f/CELL_SIZE) + (CELL_NUMBER/2)) }; + Cell c = { int(fx * (1.f / CELL_SIZE) + (CELL_NUMBER / 2)), int(fy * (1.f / CELL_SIZE) + (CELL_NUMBER / 2)) }; return c; } - bool isValid() const { return x >= 0 && x < CELL_NUMBER && y >= 0 && y < CELL_NUMBER;} + bool isValid() const { return x >= 0 && x < CELL_NUMBER && y >= 0 && y < CELL_NUMBER; } }; Node& getGrid(int x, int y) diff --git a/src/common/Collision/VMapTools.h b/src/common/Collision/VMapTools.h deleted file mode 100644 index b73e524ce5a..00000000000 --- a/src/common/Collision/VMapTools.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2010 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 the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef _VMAPTOOLS_H -#define _VMAPTOOLS_H - -#include -#include - -/** -The Class is mainly taken from G3D/AABSPTree.h but modified to be able to use our internal data structure. -This is an iterator that helps us analysing the BSP-Trees. -The collision detection is modified to return true, if we are inside an object. -*/ - -namespace VMAP -{ - template - class IntersectionCallBack { - public: - TValue* closestEntity; - G3D::Vector3 hitLocation; - G3D::Vector3 hitNormal; - - void operator()(const G3D::Ray& ray, const TValue* entity, bool pStopAtFirstHit, float& distance) { - entity->intersect(ray, distance, pStopAtFirstHit, hitLocation, hitNormal); - } - }; - - //============================================================== - //============================================================== - //============================================================== - - class TC_COMMON_API MyCollisionDetection - { - private: - public: - - static bool collisionLocationForMovingPointFixedAABox( - const G3D::Vector3& origin, - const G3D::Vector3& dir, - const G3D::AABox& box, - G3D::Vector3& location, - bool& Inside) - { - - // Integer representation of a floating-point value. -#define IR(x) (reinterpret_cast(x)) - - Inside = true; - const G3D::Vector3& MinB = box.low(); - const G3D::Vector3& MaxB = box.high(); - G3D::Vector3 MaxT(-1.0f, -1.0f, -1.0f); - - // Find candidate planes. - for (int i = 0; i < 3; ++i) - { - if (origin[i] < MinB[i]) - { - location[i] = MinB[i]; - Inside = false; - - // Calculate T distances to candidate planes - if (IR(dir[i])) - { - MaxT[i] = (MinB[i] - origin[i]) / dir[i]; - } - } - else if (origin[i] > MaxB[i]) - { - location[i] = MaxB[i]; - Inside = false; - - // Calculate T distances to candidate planes - if (IR(dir[i])) - { - MaxT[i] = (MaxB[i] - origin[i]) / dir[i]; - } - } - } - - if (Inside) - { - // definite hit - location = origin; - return true; - } - - // Get largest of the maxT's for final choice of intersection - int WhichPlane = 0; - if (MaxT[1] > MaxT[WhichPlane]) - { - WhichPlane = 1; - } - - if (MaxT[2] > MaxT[WhichPlane]) - { - WhichPlane = 2; - } - - // Check final candidate actually inside box - if (IR(MaxT[WhichPlane]) & 0x80000000) - { - // Miss the box - return false; - } - - for (int i = 0; i < 3; ++i) - { - if (i != WhichPlane) - { - location[i] = origin[i] + MaxT[WhichPlane] * dir[i]; - if ((location[i] < MinB[i]) || - (location[i] > MaxB[i])) - { - // On this plane we're outside the box extents, so - // we miss the box - return false; - } - } - } - /* - // Choose the normal to be the plane normal facing into the ray - normal = G3D::Vector3::zero(); - normal[WhichPlane] = (dir[WhichPlane] > 0) ? -1.0 : 1.0; - */ - return true; - -#undef IR - } - }; -} -#endif diff --git a/src/common/Common.h b/src/common/Common.h index 1097249bcab..78b7df6a895 100644 --- a/src/common/Common.h +++ b/src/common/Common.h @@ -20,38 +20,9 @@ #define TRINITYCORE_COMMON_H #include "Define.h" - -#include -#include -#include -#include -#include #include -#include -#include -#include #include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "Debugging/Errors.h" - -#include "Threading/LockedQueue.h" +#include #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS # include @@ -61,7 +32,6 @@ # define BOOST_ASIO_HAS_MOVE # endif // !defined(BOOST_ASIO_HAS_MOVE) # endif // if TRINITY_COMPILER == TRINITY_COMPILER_INTEL - #else # include # include @@ -69,12 +39,11 @@ # include # include # include +# include #endif #if TRINITY_COMPILER == TRINITY_COMPILER_MICROSOFT -#include - #define snprintf _snprintf #define atoll _atoi64 #define vsnprintf _vsnprintf @@ -87,8 +56,6 @@ #endif -inline float finiteAlways(float f) { return std::isfinite(f) ? f : 0.0f; } - inline unsigned long atoul(char const* str) { return strtoul(str, nullptr, 10); } inline unsigned long long atoull(char const* str) { return strtoull(str, nullptr, 10); } @@ -114,7 +81,7 @@ enum AccountTypes SEC_CONSOLE = 4 // must be always last in list, accounts must have less security level always also }; -enum LocaleConstant +enum LocaleConstant : uint8 { LOCALE_enUS = 0, LOCALE_koKR = 1, @@ -136,11 +103,9 @@ enum LocaleConstant TC_COMMON_API extern char const* localeNames[TOTAL_LOCALES]; -TC_COMMON_API LocaleConstant GetLocaleByName(const std::string& name); - -typedef std::vector StringVector; +TC_COMMON_API LocaleConstant GetLocaleByName(std::string const& name); -// we always use stdlibc++ std::max/std::min, undefine some not C++ standard defines (Win API and some other platforms) +// we always use stdlib std::max/std::min, undefine some not C++ standard defines (Win API and some other platforms) #ifdef max #undef max #endif @@ -155,33 +120,26 @@ typedef std::vector StringVector; #define MAX_QUERY_LEN 32*1024 -//! Optional helper class to wrap optional values within. -template -using Optional = boost::optional; - namespace Trinity { //! std::make_unique implementation (TODO: remove this once C++14 is supported) template - std::unique_ptr make_unique(Args&& ...args) + inline auto make_unique(Args&& ...args) -> + typename std::enable_if::value, std::unique_ptr>::type { return std::unique_ptr(new T(std::forward(args)...)); } -} -//! Hash implementation for std::pair to allow using pairs in unordered_set or as key for unordered_map -//! Individual types used in pair must be hashable by boost::hash -namespace std -{ - template - struct hash> + template + inline auto make_unique(std::size_t size) -> + typename std::enable_if::value && std::extent::value == 0, std::unique_ptr>::type { - public: - size_t operator()(std::pair const& key) const - { - return boost::hash_value(key); - } - }; + return std::unique_ptr(new typename std::remove_extent::type[size]()); + } + + template + inline auto make_unique(Args&&...) -> + typename std::enable_if::value != 0, void>::type = delete; } #endif diff --git a/src/common/Configuration/BuiltInConfig.h b/src/common/Configuration/BuiltInConfig.h index cc21555f4bf..a818407fb74 100644 --- a/src/common/Configuration/BuiltInConfig.h +++ b/src/common/Configuration/BuiltInConfig.h @@ -18,8 +18,8 @@ #ifndef BUILT_IN_CONFIG_H #define BUILT_IN_CONFIG_H -#include #include "Define.h" +#include /// Provides helper functions to access built-in values /// which can be overwritten in config diff --git a/src/common/Configuration/Config.cpp b/src/common/Configuration/Config.cpp index be05916e805..d4e56716501 100644 --- a/src/common/Configuration/Config.cpp +++ b/src/common/Configuration/Config.cpp @@ -16,14 +16,23 @@ * with this program. If not, see . */ -#include -#include -#include -#include #include "Config.h" #include "Log.h" +#include "Util.h" +#include +#include +#include +#include -using namespace boost::property_tree; +namespace bpt = boost::property_tree; + +namespace +{ + std::string _filename; + std::vector _args; + bpt::ptree _config; + std::mutex _configLock; +} bool ConfigMgr::LoadInitial(std::string const& file, std::vector args, std::string& error) @@ -35,8 +44,8 @@ bool ConfigMgr::LoadInitial(std::string const& file, std::vector ar try { - ptree fullTree; - ini_parser::read_ini(file, fullTree); + bpt::ptree fullTree; + bpt::ini_parser::read_ini(file, fullTree); if (fullTree.empty()) { @@ -47,7 +56,7 @@ bool ConfigMgr::LoadInitial(std::string const& file, std::vector ar // Since we're using only one section per config file, we skip the section and have direct property access _config = fullTree.begin()->second; } - catch (ini_parser::ini_parser_error const& e) + catch (bpt::ini_parser::ini_parser_error const& e) { if (e.line() == 0) error = e.message() + " (" + e.filename() + ")"; @@ -75,14 +84,14 @@ T ConfigMgr::GetValueDefault(std::string const& name, T def) const { try { - return _config.get(ptree::path_type(name, '/')); + return _config.get(bpt::ptree::path_type(name, '/')); } - catch (boost::property_tree::ptree_bad_path) + catch (bpt::ptree_bad_path) { TC_LOG_WARN("server.loading", "Missing name %s in config file %s, add \"%s = %s\" to this file", name.c_str(), _filename.c_str(), name.c_str(), std::to_string(def).c_str()); } - catch (boost::property_tree::ptree_bad_data) + catch (bpt::ptree_bad_data) { TC_LOG_ERROR("server.loading", "Bad value defined for name %s in config file %s, going to use %s instead", name.c_str(), _filename.c_str(), std::to_string(def).c_str()); @@ -96,14 +105,14 @@ std::string ConfigMgr::GetValueDefault(std::string const& name, std { try { - return _config.get(ptree::path_type(name, '/')); + return _config.get(bpt::ptree::path_type(name, '/')); } - catch (boost::property_tree::ptree_bad_path) + catch (bpt::ptree_bad_path) { TC_LOG_WARN("server.loading", "Missing name %s in config file %s, add \"%s = %s\" to this file", name.c_str(), _filename.c_str(), name.c_str(), def.c_str()); } - catch (boost::property_tree::ptree_bad_data) + catch (bpt::ptree_bad_data) { TC_LOG_ERROR("server.loading", "Bad value defined for name %s in config file %s, going to use %s instead", name.c_str(), _filename.c_str(), def.c_str()); @@ -123,7 +132,7 @@ bool ConfigMgr::GetBoolDefault(std::string const& name, bool def) const { std::string val = GetValueDefault(name, std::string(def ? "1" : "0")); val.erase(std::remove(val.begin(), val.end(), '"'), val.end()); - return (val == "1" || val == "true" || val == "TRUE" || val == "yes" || val == "YES"); + return StringToBool(val); } int ConfigMgr::GetIntDefault(std::string const& name, int def) const @@ -142,13 +151,18 @@ std::string const& ConfigMgr::GetFilename() return _filename; } -std::list ConfigMgr::GetKeysByString(std::string const& name) +std::vector const& ConfigMgr::GetArguments() const +{ + return _args; +} + +std::vector ConfigMgr::GetKeysByString(std::string const& name) { std::lock_guard lock(_configLock); - std::list keys; + std::vector keys; - for (const ptree::value_type& child : _config) + for (bpt::ptree::value_type const& child : _config) if (child.first.compare(0, name.length(), name) == 0) keys.push_back(child.first); diff --git a/src/common/Configuration/Config.h b/src/common/Configuration/Config.h index 1e0f558b007..df82a4e6668 100644 --- a/src/common/Configuration/Config.h +++ b/src/common/Configuration/Config.h @@ -20,12 +20,8 @@ #define CONFIG_H #include "Define.h" - #include -#include #include -#include -#include class TC_COMMON_API ConfigMgr { @@ -36,8 +32,7 @@ class TC_COMMON_API ConfigMgr public: /// Method used only for loading main configuration files (authserver.conf and worldserver.conf) - bool LoadInitial(std::string const& file, std::vector args, - std::string& error); + bool LoadInitial(std::string const& file, std::vector args, std::string& error); static ConfigMgr* instance(); @@ -49,15 +44,10 @@ public: float GetFloatDefault(std::string const& name, float def) const; std::string const& GetFilename(); - std::vector const& GetArguments() const { return _args; } - std::list GetKeysByString(std::string const& name); + std::vector const& GetArguments() const; + std::vector GetKeysByString(std::string const& name); private: - std::string _filename; - std::vector _args; - boost::property_tree::ptree _config; - std::mutex _configLock; - template T GetValueDefault(std::string const& name, T def) const; }; diff --git a/src/common/Cryptography/ARC4.cpp b/src/common/Cryptography/ARC4.cpp index 1a568f99700..ee5837b5b42 100644 --- a/src/common/Cryptography/ARC4.cpp +++ b/src/common/Cryptography/ARC4.cpp @@ -21,16 +21,16 @@ ARC4::ARC4(uint32 len) : m_ctx() { EVP_CIPHER_CTX_init(&m_ctx); - EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), NULL, NULL, NULL); + EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), nullptr, nullptr, nullptr); EVP_CIPHER_CTX_set_key_length(&m_ctx, len); } ARC4::ARC4(uint8 *seed, uint32 len) : m_ctx() { EVP_CIPHER_CTX_init(&m_ctx); - EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), NULL, NULL, NULL); + EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), nullptr, nullptr, nullptr); EVP_CIPHER_CTX_set_key_length(&m_ctx, len); - EVP_EncryptInit_ex(&m_ctx, NULL, NULL, seed, NULL); + EVP_EncryptInit_ex(&m_ctx, nullptr, nullptr, seed, nullptr); } ARC4::~ARC4() @@ -40,7 +40,7 @@ ARC4::~ARC4() void ARC4::Init(uint8 *seed) { - EVP_EncryptInit_ex(&m_ctx, NULL, NULL, seed, NULL); + EVP_EncryptInit_ex(&m_ctx, nullptr, nullptr, seed, nullptr); } void ARC4::UpdateData(int len, uint8 *data) diff --git a/src/common/Cryptography/BigNumber.cpp b/src/common/Cryptography/BigNumber.cpp index fe048104f85..c67e8c8fbbc 100644 --- a/src/common/Cryptography/BigNumber.cpp +++ b/src/common/Cryptography/BigNumber.cpp @@ -112,7 +112,7 @@ BigNumber BigNumber::operator/=(BigNumber const& bn) BN_CTX *bnctx; bnctx = BN_CTX_new(); - BN_div(_bn, NULL, _bn, bn._bn, bnctx); + BN_div(_bn, nullptr, _bn, bn._bn, bnctx); BN_CTX_free(bnctx); return *this; diff --git a/src/common/Cryptography/BigNumber.h b/src/common/Cryptography/BigNumber.h index c8ca5860933..8936ffffe53 100644 --- a/src/common/Cryptography/BigNumber.h +++ b/src/common/Cryptography/BigNumber.h @@ -19,8 +19,8 @@ #ifndef _AUTH_BIGNUMBER_H #define _AUTH_BIGNUMBER_H -#include #include "Define.h" +#include #include struct bignum_st; diff --git a/src/common/Cryptography/HMACSHA1.cpp b/src/common/Cryptography/HMACSHA1.cpp index a10c012e896..c6936cacaef 100644 --- a/src/common/Cryptography/HMACSHA1.cpp +++ b/src/common/Cryptography/HMACSHA1.cpp @@ -18,12 +18,13 @@ #include "HMACSHA1.h" #include "BigNumber.h" -#include "Common.h" +#include "Errors.h" +#include -HmacHash::HmacHash(uint32 len, uint8 *seed) +HmacHash::HmacHash(uint32 len, uint8* seed) { HMAC_CTX_init(&m_ctx); - HMAC_Init_ex(&m_ctx, seed, len, EVP_sha1(), NULL); + HMAC_Init_ex(&m_ctx, seed, len, EVP_sha1(), nullptr); memset(m_digest, 0, sizeof(m_digest)); } @@ -32,12 +33,12 @@ HmacHash::~HmacHash() HMAC_CTX_cleanup(&m_ctx); } -void HmacHash::UpdateData(const std::string &str) +void HmacHash::UpdateData(std::string const& str) { HMAC_Update(&m_ctx, (uint8 const*)str.c_str(), str.length()); } -void HmacHash::UpdateData(const uint8* data, size_t len) +void HmacHash::UpdateData(uint8 const* data, size_t len) { HMAC_Update(&m_ctx, data, len); } diff --git a/src/common/Cryptography/HMACSHA1.h b/src/common/Cryptography/HMACSHA1.h index 19db12f82c0..972c9b02012 100644 --- a/src/common/Cryptography/HMACSHA1.h +++ b/src/common/Cryptography/HMACSHA1.h @@ -31,10 +31,10 @@ class BigNumber; class TC_COMMON_API HmacHash { public: - HmacHash(uint32 len, uint8 *seed); + HmacHash(uint32 len, uint8* seed); ~HmacHash(); - void UpdateData(const std::string &str); - void UpdateData(const uint8* data, size_t len); + void UpdateData(std::string const& str); + void UpdateData(uint8 const* data, size_t len); void Finalize(); uint8 *ComputeHash(BigNumber* bn); uint8 *GetDigest() { return (uint8*)m_digest; } diff --git a/src/common/Cryptography/OpenSSLCrypto.cpp b/src/common/Cryptography/OpenSSLCrypto.cpp index 7a97cc2375e..3f7bdef9fce 100644 --- a/src/common/Cryptography/OpenSSLCrypto.cpp +++ b/src/common/Cryptography/OpenSSLCrypto.cpp @@ -23,7 +23,7 @@ std::vector cryptoLocks; -static void lockingCallback(int mode, int type, const char* /*file*/, int /*line*/) +static void lockingCallback(int mode, int type, char const* /*file*/, int /*line*/) { if (mode & CRYPTO_LOCK) cryptoLocks[type]->lock(); @@ -49,8 +49,8 @@ void OpenSSLCrypto::threadsSetup() void OpenSSLCrypto::threadsCleanup() { - CRYPTO_set_locking_callback(NULL); - CRYPTO_THREADID_set_callback(NULL); + CRYPTO_set_locking_callback(nullptr); + CRYPTO_THREADID_set_callback(nullptr); for(int i = 0 ; i < CRYPTO_num_locks(); ++i) { delete cryptoLocks[i]; diff --git a/src/common/DataStores/DBCFileLoader.cpp b/src/common/DataStores/DBCFileLoader.cpp new file mode 100644 index 00000000000..c1102c25d8c --- /dev/null +++ b/src/common/DataStores/DBCFileLoader.cpp @@ -0,0 +1,316 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include +#include +#include + +#include "DBCFileLoader.h" +#include "Errors.h" + +DBCFileLoader::DBCFileLoader() : recordSize(0), recordCount(0), fieldCount(0), stringSize(0), fieldsOffset(nullptr), data(nullptr), stringTable(nullptr) { } + +bool DBCFileLoader::Load(char const* filename, char const* fmt) +{ + uint32 header; + if (data) + { + delete [] data; + data = nullptr; + } + + FILE* f = fopen(filename, "rb"); + if (!f) + return false; + + if (fread(&header, 4, 1, f) != 1) // Number of records + { + fclose(f); + return false; + } + + + EndianConvert(header); + + if (header != 0x43424457) //'WDBC' + { + fclose(f); + return false; + } + + if (fread(&recordCount, 4, 1, f) != 1) // Number of records + { + fclose(f); + return false; + } + + EndianConvert(recordCount); + + if (fread(&fieldCount, 4, 1, f) != 1) // Number of fields + { + fclose(f); + return false; + } + + EndianConvert(fieldCount); + + if (fread(&recordSize, 4, 1, f) != 1) // Size of a record + { + fclose(f); + return false; + } + + EndianConvert(recordSize); + + if (fread(&stringSize, 4, 1, f) != 1) // String size + { + fclose(f); + return false; + } + + EndianConvert(stringSize); + + fieldsOffset = new uint32[fieldCount]; + fieldsOffset[0] = 0; + for (uint32 i = 1; i < fieldCount; ++i) + { + fieldsOffset[i] = fieldsOffset[i - 1]; + if (fmt[i - 1] == 'b' || fmt[i - 1] == 'X') // byte fields + fieldsOffset[i] += sizeof(uint8); + else // 4 byte fields (int32/float/strings) + fieldsOffset[i] += sizeof(uint32); + } + + data = new unsigned char[recordSize * recordCount + stringSize]; + stringTable = data + recordSize*recordCount; + + if (fread(data, recordSize * recordCount + stringSize, 1, f) != 1) + { + fclose(f); + return false; + } + + fclose(f); + + return true; +} + +DBCFileLoader::~DBCFileLoader() +{ + delete[] data; + + delete[] fieldsOffset; +} + +DBCFileLoader::Record DBCFileLoader::getRecord(size_t id) +{ + assert(data); + return Record(*this, data + id * recordSize); +} + +uint32 DBCFileLoader::GetFormatRecordSize(char const* format, int32* index_pos) +{ + uint32 recordsize = 0; + int32 i = -1; + for (uint32 x = 0; format[x]; ++x) + { + switch (format[x]) + { + case FT_FLOAT: + recordsize += sizeof(float); + break; + case FT_INT: + recordsize += sizeof(uint32); + break; + case FT_STRING: + recordsize += sizeof(char*); + break; + case FT_SORT: + i = x; + break; + case FT_IND: + i = x; + recordsize += sizeof(uint32); + break; + case FT_BYTE: + recordsize += sizeof(uint8); + break; + case FT_NA: + case FT_NA_BYTE: + break; + case FT_LOGIC: + ASSERT(false && "Attempted to load DBC files that do not have field types that match what is in the core. Check DBCfmt.h or your DBC files."); + break; + default: + ASSERT(false && "Unknown field format character in DBCfmt.h"); + break; + } + } + + if (index_pos) + *index_pos = i; + + return recordsize; +} + +char* DBCFileLoader::AutoProduceData(char const* format, uint32& records, char**& indexTable) +{ + /* + format STRING, NA, FLOAT, NA, INT <=> + struct{ + char* field0, + float field1, + int field2 + }entry; + + this func will generate entry[rows] data; + */ + + typedef char* ptr; + if (strlen(format) != fieldCount) + return nullptr; + + //get struct size and index pos + int32 i; + uint32 recordsize = GetFormatRecordSize(format, &i); + + if (i >= 0) + { + uint32 maxi = 0; + //find max index + for (uint32 y = 0; y < recordCount; ++y) + { + uint32 ind = getRecord(y).getUInt(i); + if (ind > maxi) + maxi = ind; + } + + ++maxi; + records = maxi; + indexTable = new ptr[maxi]; + memset(indexTable, 0, maxi * sizeof(ptr)); + } + else + { + records = recordCount; + indexTable = new ptr[recordCount]; + } + + char* dataTable = new char[recordCount * recordsize]; + + uint32 offset = 0; + + for (uint32 y = 0; y < recordCount; ++y) + { + if (i >= 0) + indexTable[getRecord(y).getUInt(i)] = &dataTable[offset]; + else + indexTable[y] = &dataTable[offset]; + + for (uint32 x=0; x < fieldCount; ++x) + { + switch (format[x]) + { + case FT_FLOAT: + *((float*)(&dataTable[offset])) = getRecord(y).getFloat(x); + offset += sizeof(float); + break; + case FT_IND: + case FT_INT: + *((uint32*)(&dataTable[offset])) = getRecord(y).getUInt(x); + offset += sizeof(uint32); + break; + case FT_BYTE: + *((uint8*)(&dataTable[offset])) = getRecord(y).getUInt8(x); + offset += sizeof(uint8); + break; + case FT_STRING: + *((char**)(&dataTable[offset])) = nullptr; // will replace non-empty or "" strings in AutoProduceStrings + offset += sizeof(char*); + break; + case FT_LOGIC: + ASSERT(false && "Attempted to load DBC files that do not have field types that match what is in the core. Check DBCfmt.h or your DBC files."); + break; + case FT_NA: + case FT_NA_BYTE: + case FT_SORT: + break; + default: + ASSERT(false && "Unknown field format character in DBCfmt.h"); + break; + } + } + } + + return dataTable; +} + +char* DBCFileLoader::AutoProduceStrings(char const* format, char* dataTable) +{ + if (strlen(format) != fieldCount) + return nullptr; + + char* stringPool = new char[stringSize]; + memcpy(stringPool, stringTable, stringSize); + + uint32 offset = 0; + + for (uint32 y = 0; y < recordCount; ++y) + { + for (uint32 x = 0; x < fieldCount; ++x) + { + switch (format[x]) + { + case FT_FLOAT: + offset += sizeof(float); + break; + case FT_IND: + case FT_INT: + offset += sizeof(uint32); + break; + case FT_BYTE: + offset += sizeof(uint8); + break; + case FT_STRING: + { + // fill only not filled entries + char** slot = (char**)(&dataTable[offset]); + if (!*slot || !**slot) + { + const char * st = getRecord(y).getString(x); + *slot = stringPool + (st - (char const*)stringTable); + } + offset += sizeof(char*); + break; + } + case FT_LOGIC: + ASSERT(false && "Attempted to load DBC files that does not have field types that match what is in the core. Check DBCfmt.h or your DBC files."); + break; + case FT_NA: + case FT_NA_BYTE: + case FT_SORT: + break; + default: + ASSERT(false && "Unknown field format character in DBCfmt.h"); + break; + } + } + } + + return stringPool; +} diff --git a/src/common/DataStores/DBCFileLoader.h b/src/common/DataStores/DBCFileLoader.h new file mode 100644 index 00000000000..85cad0d9e7b --- /dev/null +++ b/src/common/DataStores/DBCFileLoader.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef DBC_FILE_LOADER_H +#define DBC_FILE_LOADER_H + +#include "Define.h" +#include "Utilities/ByteConverter.h" +#include + +enum DbcFieldFormat +{ + FT_NA='x', //not used or unknown, 4 byte size + FT_NA_BYTE='X', //not used or unknown, byte + FT_STRING='s', //char* + FT_FLOAT='f', //float + FT_INT='i', //uint32 + FT_BYTE='b', //uint8 + FT_SORT='d', //sorted by this field, field is not included + FT_IND='n', //the same, but parsed to data + FT_LOGIC='l', //Logical (boolean) + FT_SQL_PRESENT='p', //Used in sql format to mark column present in sql dbc + FT_SQL_ABSENT='a' //Used in sql format to mark column absent in sql dbc +}; + +class TC_COMMON_API DBCFileLoader +{ + public: + DBCFileLoader(); + ~DBCFileLoader(); + + bool Load(const char *filename, const char *fmt); + + class Record + { + public: + float getFloat(size_t field) const + { + assert(field < file.fieldCount); + float val = *reinterpret_cast(offset+file.GetOffset(field)); + EndianConvert(val); + return val; + } + uint32 getUInt(size_t field) const + { + assert(field < file.fieldCount); + uint32 val = *reinterpret_cast(offset+file.GetOffset(field)); + EndianConvert(val); + return val; + } + uint8 getUInt8(size_t field) const + { + assert(field < file.fieldCount); + return *reinterpret_cast(offset+file.GetOffset(field)); + } + + const char *getString(size_t field) const + { + assert(field < file.fieldCount); + size_t stringOffset = getUInt(field); + assert(stringOffset < file.stringSize); + return reinterpret_cast(file.stringTable + stringOffset); + } + + private: + Record(DBCFileLoader &file_, unsigned char *offset_): offset(offset_), file(file_) { } + unsigned char *offset; + DBCFileLoader &file; + + friend class DBCFileLoader; + + }; + + // Get record by id + Record getRecord(size_t id); + /// Get begin iterator over records + + uint32 GetNumRows() const { return recordCount; } + uint32 GetRowSize() const { return recordSize; } + uint32 GetCols() const { return fieldCount; } + uint32 GetOffset(size_t id) const { return (fieldsOffset != nullptr && id < fieldCount) ? fieldsOffset[id] : 0; } + bool IsLoaded() const { return data != nullptr; } + char* AutoProduceData(char const* fmt, uint32& count, char**& indexTable); + char* AutoProduceStrings(char const* fmt, char* dataTable); + static uint32 GetFormatRecordSize(const char * format, int32 * index_pos = nullptr); + private: + + uint32 recordSize; + uint32 recordCount; + uint32 fieldCount; + uint32 stringSize; + uint32 *fieldsOffset; + unsigned char *data; + unsigned char *stringTable; + + DBCFileLoader(DBCFileLoader const& right) = delete; + DBCFileLoader& operator=(DBCFileLoader const& right) = delete; +}; +#endif diff --git a/src/common/Debugging/Errors.cpp b/src/common/Debugging/Errors.cpp index 2e67f3bf539..4b56f43b067 100644 --- a/src/common/Debugging/Errors.cpp +++ b/src/common/Debugging/Errors.cpp @@ -40,7 +40,7 @@ void Assert(char const* file, int line, char const* function, char const* messag { fprintf(stderr, "\n%s:%i in %s ASSERTION FAILED:\n %s\n", file, line, function, message); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -55,7 +55,7 @@ void Assert(char const* file, int line, char const* function, char const* messag fflush(stderr); va_end(args); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -70,7 +70,7 @@ void Fatal(char const* file, int line, char const* function, char const* message fflush(stderr); std::this_thread::sleep_for(std::chrono::seconds(10)); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -78,7 +78,7 @@ void Error(char const* file, int line, char const* function, char const* message { fprintf(stderr, "\n%s:%i in %s ERROR:\n %s\n", file, line, function, message); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -92,14 +92,14 @@ void Abort(char const* file, int line, char const* function) { fprintf(stderr, "\n%s:%i in %s ABORTED.\n", file, line, function); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } void AbortHandler(int /*sigval*/) { // nothing useful to log here, no way to pass args - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } diff --git a/src/common/Debugging/WheatyExceptionReport.cpp b/src/common/Debugging/WheatyExceptionReport.cpp index 5585dd25c13..5b6e9e76ebc 100644 --- a/src/common/Debugging/WheatyExceptionReport.cpp +++ b/src/common/Debugging/WheatyExceptionReport.cpp @@ -6,7 +6,9 @@ #include "CompilerDefs.h" #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS && !defined(__MINGW32__) +#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN +#endif #pragma warning(disable:4996) #pragma warning(disable:4312) #pragma warning(disable:4311) @@ -21,6 +23,7 @@ #include "Common.h" #include "GitRevision.h" +#include #define CrashFolder _T("Crashes") #pragma comment(linker, "/DEFAULTLIB:dbghelp.lib") @@ -915,7 +918,7 @@ DWORD64 modBase, DWORD dwTypeIndex, DWORD_PTR offset, bool & bHandled, -const char* Name, +char const* Name, char* /*suffix*/, bool newSymbol, bool logChildren) diff --git a/src/common/Debugging/WheatyExceptionReport.h b/src/common/Debugging/WheatyExceptionReport.h index 91c2ae93179..2fee14708f2 100644 --- a/src/common/Debugging/WheatyExceptionReport.h +++ b/src/common/Debugging/WheatyExceptionReport.h @@ -56,7 +56,7 @@ enum DataKind // Stolen from CVCONS DataIsConstant }; -const char* const rgBaseType[] = +char const* const rgBaseType[] = { "", // btNoType = 0, "void", // btVoid = 1, @@ -100,7 +100,7 @@ struct SymbolPair _offset = offset; } - bool operator<(const SymbolPair& other) const + bool operator<(SymbolPair const& other) const { return _offset < other._offset || (_offset == other._offset && _type < other._type); @@ -174,7 +174,7 @@ class WheatyExceptionReport static bool FormatSymbolValue(PSYMBOL_INFO, STACKFRAME64 *); - static void DumpTypeIndex(DWORD64, DWORD, DWORD_PTR, bool &, const char*, char*, bool, bool); + static void DumpTypeIndex(DWORD64, DWORD, DWORD_PTR, bool &, char const*, char*, bool, bool); static void FormatOutputValue(char * pszCurrBuffer, BasicType basicType, DWORD64 length, PVOID pAddress, size_t bufferSize, size_t countOverride = 0); diff --git a/src/common/Define.h b/src/common/Define.h index e34ee8bfa18..2e991610d45 100644 --- a/src/common/Define.h +++ b/src/common/Define.h @@ -56,7 +56,7 @@ #endif #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS -# define TRINITY_PATH_MAX MAX_PATH +# define TRINITY_PATH_MAX 260 # define _USE_MATH_DEFINES # ifndef DECLSPEC_NORETURN # define DECLSPEC_NORETURN __declspec(noreturn) diff --git a/src/common/GitRevision.cpp b/src/common/GitRevision.cpp index 3e578cf1ee8..86362955792 100644 --- a/src/common/GitRevision.cpp +++ b/src/common/GitRevision.cpp @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "GitRevision.h" #include "revision_data.h" diff --git a/src/common/GitRevision.h b/src/common/GitRevision.h index 9a31b3f1a66..d6a290ad0d5 100644 --- a/src/common/GitRevision.h +++ b/src/common/GitRevision.h @@ -18,7 +18,6 @@ #ifndef __GITREVISION_H__ #define __GITREVISION_H__ -#include #include "Define.h" namespace GitRevision diff --git a/src/common/Logging/Appender.cpp b/src/common/Logging/Appender.cpp index ec88d5fd4c1..616e3a2137f 100644 --- a/src/common/Logging/Appender.cpp +++ b/src/common/Logging/Appender.cpp @@ -16,27 +16,11 @@ */ #include "Appender.h" -#include "Common.h" -#include "Util.h" +#include "LogMessage.h" #include "StringFormat.h" -#include #include -std::string LogMessage::getTimeStr(time_t time) -{ - tm aTm; - localtime_r(&time, &aTm); - char buf[20]; - snprintf(buf, 20, "%04d-%02d-%02d_%02d:%02d:%02d", aTm.tm_year+1900, aTm.tm_mon+1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); - return std::string(buf); -} - -std::string LogMessage::getTimeStr() -{ - return getTimeStr(mtime); -} - Appender::Appender(uint8 _id, std::string const& _name, LogLevel _level /* = LOG_LEVEL_DISABLED */, AppenderFlags _flags /* = APPENDER_FLAGS_NONE */): id(_id), name(_name), level(_level), flags(_flags) { } @@ -87,7 +71,7 @@ void Appender::write(LogMessage* message) _write(message); } -const char* Appender::getLogLevelString(LogLevel level) +char const* Appender::getLogLevelString(LogLevel level) { switch (level) { diff --git a/src/common/Logging/Appender.h b/src/common/Logging/Appender.h index 6a9932b7935..fd17ad71fdd 100644 --- a/src/common/Logging/Appender.h +++ b/src/common/Logging/Appender.h @@ -18,72 +18,13 @@ #ifndef APPENDER_H #define APPENDER_H -#include +#include "Define.h" +#include "LogCommon.h" #include #include -#include -#include #include -#include -#include "Define.h" - -// Values assigned have their equivalent in enum ACE_Log_Priority -enum LogLevel -{ - LOG_LEVEL_DISABLED = 0, - LOG_LEVEL_TRACE = 1, - LOG_LEVEL_DEBUG = 2, - LOG_LEVEL_INFO = 3, - LOG_LEVEL_WARN = 4, - LOG_LEVEL_ERROR = 5, - LOG_LEVEL_FATAL = 6 -}; - -const uint8 MaxLogLevels = 6; - -enum AppenderType : uint8 -{ - APPENDER_NONE, - APPENDER_CONSOLE, - APPENDER_FILE, - APPENDER_DB -}; - -enum AppenderFlags -{ - APPENDER_FLAGS_NONE = 0x00, - APPENDER_FLAGS_PREFIX_TIMESTAMP = 0x01, - APPENDER_FLAGS_PREFIX_LOGLEVEL = 0x02, - APPENDER_FLAGS_PREFIX_LOGFILTERTYPE = 0x04, - APPENDER_FLAGS_USE_TIMESTAMP = 0x08, // only used by FileAppender - APPENDER_FLAGS_MAKE_FILE_BACKUP = 0x10 // only used by FileAppender -}; - -struct TC_COMMON_API LogMessage -{ - LogMessage(LogLevel _level, std::string const& _type, std::string&& _text) - : level(_level), type(_type), text(std::forward(_text)), mtime(time(NULL)) - { } - LogMessage(LogMessage const& /*other*/) = delete; - LogMessage& operator=(LogMessage const& /*other*/) = delete; - - static std::string getTimeStr(time_t time); - std::string getTimeStr(); - - LogLevel const level; - std::string const type; - std::string const text; - std::string prefix; - std::string param1; - time_t mtime; - - ///@ Returns size of the log message content in bytes - uint32 Size() const - { - return static_cast(prefix.size() + text.size()); - } -}; +struct LogMessage; class TC_COMMON_API Appender { @@ -99,7 +40,7 @@ class TC_COMMON_API Appender void setLogLevel(LogLevel); void write(LogMessage* message); - static const char* getLogLevelString(LogLevel level); + static char const* getLogLevelString(LogLevel level); virtual void setRealmId(uint32 /*realmId*/) { } private: @@ -111,18 +52,6 @@ class TC_COMMON_API Appender AppenderFlags flags; }; -typedef std::unordered_map AppenderMap; - -typedef std::vector ExtraAppenderArgs; -typedef Appender*(*AppenderCreatorFn)(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); -typedef std::unordered_map AppenderCreatorMap; - -template -Appender* CreateAppender(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs) -{ - return new AppenderImpl(id, name, level, flags, std::forward(extraArgs)); -} - class TC_COMMON_API InvalidAppenderArgsException : public std::length_error { public: diff --git a/src/common/Logging/AppenderConsole.cpp b/src/common/Logging/AppenderConsole.cpp index 3378c185cc5..7ae1987162e 100644 --- a/src/common/Logging/AppenderConsole.cpp +++ b/src/common/Logging/AppenderConsole.cpp @@ -15,20 +15,19 @@ * with this program. If not, see . */ -#include - #include "AppenderConsole.h" -#include "Config.h" +#include "LogMessage.h" #include "Util.h" +#include #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS #include #endif -AppenderConsole::AppenderConsole(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs) +AppenderConsole::AppenderConsole(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs) : Appender(id, name, level, flags), _colored(false) { - for (uint8 i = 0; i < MaxLogLevels; ++i) + for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) _colors[i] = ColorTypes(MaxColors); if (!extraArgs.empty()) @@ -43,11 +42,11 @@ void AppenderConsole::InitColors(std::string const& str) return; } - int color[MaxLogLevels]; + int color[NUM_ENABLED_LOG_LEVELS]; std::istringstream ss(str); - for (uint8 i = 0; i < MaxLogLevels; ++i) + for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) { ss >> color[i]; @@ -58,7 +57,7 @@ void AppenderConsole::InitColors(std::string const& str) return; } - for (uint8 i = 0; i < MaxLogLevels; ++i) + for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) _colors[i] = ColorTypes(color[i]); _colored = true; diff --git a/src/common/Logging/AppenderConsole.h b/src/common/Logging/AppenderConsole.h index c56a745bfba..9fd57c99f8a 100644 --- a/src/common/Logging/AppenderConsole.h +++ b/src/common/Logging/AppenderConsole.h @@ -18,7 +18,6 @@ #ifndef APPENDERCONSOLE_H #define APPENDERCONSOLE_H -#include #include "Appender.h" enum ColorTypes @@ -47,7 +46,7 @@ class TC_COMMON_API AppenderConsole : public Appender public: typedef std::integral_constant::type TypeIndex; - AppenderConsole(uint8 _id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); + AppenderConsole(uint8 _id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs); void InitColors(const std::string& init_str); AppenderType getType() const override { return TypeIndex::value; } @@ -56,7 +55,7 @@ class TC_COMMON_API AppenderConsole : public Appender void ResetColor(bool stdout_stream); void _write(LogMessage const* message) override; bool _colored; - ColorTypes _colors[MaxLogLevels]; + ColorTypes _colors[NUM_ENABLED_LOG_LEVELS]; }; #endif diff --git a/src/common/Logging/AppenderFile.cpp b/src/common/Logging/AppenderFile.cpp index 6c68406667d..d2109936e65 100644 --- a/src/common/Logging/AppenderFile.cpp +++ b/src/common/Logging/AppenderFile.cpp @@ -16,17 +16,13 @@ */ #include "AppenderFile.h" -#include "Common.h" -#include "StringFormat.h" #include "Log.h" +#include "LogMessage.h" +#include -#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS -# include -#endif - -AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs) : +AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs) : Appender(id, name, level, flags), - logfile(NULL), + logfile(nullptr), _logDir(sLog->GetLogsDir()), _maxFileSize(0), _fileSize(0) @@ -101,7 +97,7 @@ FILE* AppenderFile::OpenFile(std::string const& filename, std::string const& mod CloseFile(); std::string newName(fullName); newName.push_back('.'); - newName.append(LogMessage::getTimeStr(time(NULL))); + newName.append(LogMessage::getTimeStr(time(nullptr))); std::replace(newName.begin(), newName.end(), ':', '-'); rename(fullName.c_str(), newName.c_str()); // no error handling... if we couldn't make a backup, just ignore } @@ -112,7 +108,7 @@ FILE* AppenderFile::OpenFile(std::string const& filename, std::string const& mod return ret; } - return NULL; + return nullptr; } void AppenderFile::CloseFile() @@ -120,6 +116,6 @@ void AppenderFile::CloseFile() if (logfile) { fclose(logfile); - logfile = NULL; + logfile = nullptr; } } diff --git a/src/common/Logging/AppenderFile.h b/src/common/Logging/AppenderFile.h index aeb1c2d8001..8e728cbdf4d 100644 --- a/src/common/Logging/AppenderFile.h +++ b/src/common/Logging/AppenderFile.h @@ -18,15 +18,15 @@ #ifndef APPENDERFILE_H #define APPENDERFILE_H -#include #include "Appender.h" +#include class TC_COMMON_API AppenderFile : public Appender { public: typedef std::integral_constant::type TypeIndex; - AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); + AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs); ~AppenderFile(); FILE* OpenFile(std::string const& name, std::string const& mode, bool backup); AppenderType getType() const override { return TypeIndex::value; } diff --git a/src/common/Logging/Log.cpp b/src/common/Logging/Log.cpp index a2e3ee99471..d0ba17b52a7 100644 --- a/src/common/Logging/Log.cpp +++ b/src/common/Logging/Log.cpp @@ -17,14 +17,17 @@ */ #include "Log.h" -#include "Common.h" -#include "Config.h" -#include "Util.h" #include "AppenderConsole.h" #include "AppenderFile.h" +#include "AsioHacksImpl.h" +#include "Common.h" +#include "Config.h" +#include "Errors.h" +#include "Logger.h" +#include "LogMessage.h" #include "LogOperation.h" - -#include +#include "Util.h" +#include #include Log::Log() : AppenderId(0), lowestLogLevel(LOG_LEVEL_FATAL), _ioService(nullptr), _strand(nullptr) @@ -45,25 +48,13 @@ uint8 Log::NextAppenderId() return AppenderId++; } -int32 GetConfigIntDefault(std::string base, const char* name, int32 value) -{ - base.append(name); - return sConfigMgr->GetIntDefault(base.c_str(), value); -} - -std::string GetConfigStringDefault(std::string base, const char* name, const char* value) -{ - base.append(name); - return sConfigMgr->GetStringDefault(base.c_str(), value); -} - Appender* Log::GetAppenderByName(std::string const& name) { - AppenderMap::iterator it = appenders.begin(); + auto it = appenders.begin(); while (it != appenders.end() && it->second && it->second->getName() != name) ++it; - return it == appenders.end() ? NULL : it->second; + return it == appenders.end() ? nullptr : it->second.get(); } void Log::CreateAppenderFromConfig(std::string const& appenderName) @@ -71,13 +62,13 @@ void Log::CreateAppenderFromConfig(std::string const& appenderName) if (appenderName.empty()) return; - // Format=type, level, flags, optional1, optional2 + // Format = type, level, flags, optional1, optional2 // if type = File. optional1 = file and option2 = mode // if type = Console. optional1 = Color std::string options = sConfigMgr->GetStringDefault(appenderName.c_str(), ""); Tokenizer tokens(options, ','); - Tokenizer::const_iterator iter = tokens.begin(); + auto iter = tokens.begin(); size_t size = tokens.size(); std::string name = appenderName.substr(9); @@ -110,8 +101,8 @@ void Log::CreateAppenderFromConfig(std::string const& appenderName) try { - Appender* appender = factoryFunction->second(NextAppenderId(), name, level, flags, ExtraAppenderArgs(iter, tokens.end())); - appenders[appender->getId()] = appender; + Appender* appender = factoryFunction->second(NextAppenderId(), name, level, flags, std::vector(iter, tokens.end())); + appenders[appender->getId()].reset(appender); } catch (InvalidAppenderArgsException const& iaae) { @@ -145,8 +136,8 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) return; } - Logger& logger = loggers[name]; - if (!logger.getName().empty()) + std::unique_ptr& logger = loggers[name]; + if (logger) { fprintf(stderr, "Error while configuring Logger %s. Already defined\n", name.c_str()); return; @@ -162,7 +153,7 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) if (level < lowestLogLevel) lowestLogLevel = level; - logger.Create(name, level); + logger = Trinity::make_unique(name, level); //fprintf(stdout, "Log::CreateLoggerFromConfig: Created Logger %s, Level %u\n", name.c_str(), level); std::istringstream ss(*iter); @@ -173,7 +164,7 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) { if (Appender* appender = GetAppenderByName(str)) { - logger.addAppender(appender->getId(), appender); + logger->addAppender(appender->getId(), appender); //fprintf(stdout, "Log::CreateLoggerFromConfig: Added Appender %s to Logger %s\n", appender->getName().c_str(), name.c_str()); } else @@ -184,24 +175,16 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) void Log::ReadAppendersFromConfig() { - std::list keys = sConfigMgr->GetKeysByString("Appender."); - - while (!keys.empty()) - { - CreateAppenderFromConfig(keys.front()); - keys.pop_front(); - } + std::vector keys = sConfigMgr->GetKeysByString("Appender."); + for (std::string const& appenderName : keys) + CreateAppenderFromConfig(appenderName); } void Log::ReadLoggersFromConfig() { - std::list keys = sConfigMgr->GetKeysByString("Logger."); - - while (!keys.empty()) - { - CreateLoggerFromConfig(keys.front()); - keys.pop_front(); - } + std::vector keys = sConfigMgr->GetKeysByString("Logger."); + for (std::string const& loggerName : keys) + CreateLoggerFromConfig(loggerName); // Bad config configuration, creating default config if (loggers.find(LOGGER_ROOT) == loggers.end()) @@ -211,26 +194,43 @@ void Log::ReadLoggersFromConfig() Close(); // Clean any Logger or Appender created - AppenderConsole* appender = new AppenderConsole(NextAppenderId(), "Console", LOG_LEVEL_DEBUG, APPENDER_FLAGS_NONE, ExtraAppenderArgs()); - appenders[appender->getId()] = appender; + AppenderConsole* appender = new AppenderConsole(NextAppenderId(), "Console", LOG_LEVEL_DEBUG, APPENDER_FLAGS_NONE, std::vector()); + appenders[appender->getId()].reset(appender); - Logger& rootLogger = loggers[LOGGER_ROOT]; - rootLogger.Create(LOGGER_ROOT, LOG_LEVEL_ERROR); - rootLogger.addAppender(appender->getId(), appender); + Logger* rootLogger = new Logger(LOGGER_ROOT, LOG_LEVEL_ERROR); + rootLogger->addAppender(appender->getId(), appender); + loggers[LOGGER_ROOT].reset(rootLogger); - Logger& serverLogger = loggers["server"]; - serverLogger.Create("server", LOG_LEVEL_INFO); - serverLogger.addAppender(appender->getId(), appender); + Logger* serverLogger = new Logger("server", LOG_LEVEL_INFO); + serverLogger->addAppender(appender->getId(), appender); + loggers["server"].reset(serverLogger); } } +void Log::RegisterAppender(uint8 index, AppenderCreatorFn appenderCreateFn) +{ + auto itr = appenderFactory.find(index); + ASSERT(itr == appenderFactory.end()); + appenderFactory[index] = appenderCreateFn; +} + +void Log::outMessage(std::string const& filter, LogLevel level, std::string&& message) +{ + write(Trinity::make_unique(level, filter, std::move(message))); +} + +void Log::outCommand(std::string&& message, std::string&& param1) +{ + write(Trinity::make_unique(LOG_LEVEL_INFO, "commands.gm", std::move(message), std::move(param1))); +} + void Log::write(std::unique_ptr&& msg) const { Logger const* logger = GetLoggerByType(msg->type); if (_ioService) { - auto logOperation = std::shared_ptr(new LogOperation(logger, std::move(msg))); + auto logOperation = std::make_shared(logger, std::move(msg)); _ioService->post(_strand->wrap([logOperation](){ logOperation->call(); })); } @@ -238,6 +238,23 @@ void Log::write(std::unique_ptr&& msg) const logger->write(msg.get()); } +Logger const* Log::GetLoggerByType(std::string const& type) const +{ + auto it = loggers.find(type); + if (it != loggers.end()) + return it->second.get(); + + if (type == LOGGER_ROOT) + return nullptr; + + std::string parentLogger = LOGGER_ROOT; + size_t found = type.find_last_of('.'); + if (found != std::string::npos) + parentLogger = type.substr(0, found); + + return GetLoggerByType(parentLogger); +} + std::string Log::GetTimestampStr() { time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); @@ -255,7 +272,7 @@ std::string Log::GetTimestampStr() aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); } -bool Log::SetLogLevel(std::string const& name, const char* newLevelc, bool isLogger /* = true */) +bool Log::SetLogLevel(std::string const& name, char const* newLevelc, bool isLogger /* = true */) { LogLevel newLevel = LogLevel(atoi(newLevelc)); if (newLevel < 0) @@ -263,14 +280,14 @@ bool Log::SetLogLevel(std::string const& name, const char* newLevelc, bool isLog if (isLogger) { - LoggerMap::iterator it = loggers.begin(); - while (it != loggers.end() && it->second.getName() != name) + auto it = loggers.begin(); + while (it != loggers.end() && it->second->getName() != name) ++it; if (it == loggers.end()) return false; - it->second.setLogLevel(newLevel); + it->second->setLogLevel(newLevel); if (newLevel != LOG_LEVEL_DISABLED && newLevel < lowestLogLevel) lowestLogLevel = newLevel; @@ -307,19 +324,34 @@ void Log::outCharDump(char const* str, uint32 accountId, uint64 guid, char const void Log::SetRealmId(uint32 id) { - for (AppenderMap::iterator it = appenders.begin(); it != appenders.end(); ++it) + for (auto it = appenders.begin(); it != appenders.end(); ++it) it->second->setRealmId(id); } void Log::Close() { loggers.clear(); - for (AppenderMap::iterator it = appenders.begin(); it != appenders.end(); ++it) - delete it->second; - appenders.clear(); } +bool Log::ShouldLog(std::string const& type, LogLevel level) const +{ + // TODO: Use cache to store "Type.sub1.sub2": "Type" equivalence, should + // Speed up in cases where requesting "Type.sub1.sub2" but only configured + // Logger "Type" + + // Don't even look for a logger if the LogLevel is lower than lowest log levels across all loggers + if (level < lowestLogLevel) + return false; + + Logger const* logger = GetLoggerByType(type); + if (!logger) + return false; + + LogLevel logLevel = logger->getLogLevel(); + return logLevel != LOG_LEVEL_DISABLED && logLevel <= level; +} + Log* Log::instance() { static Log instance; @@ -331,7 +363,7 @@ void Log::Initialize(boost::asio::io_service* ioService) if (ioService) { _ioService = ioService; - _strand = new boost::asio::strand(*ioService); + _strand = new Trinity::AsioStrand(*ioService); } LoadFromConfig(); diff --git a/src/common/Logging/Log.h b/src/common/Logging/Log.h index fa67a8ea648..5065d8bb5b8 100644 --- a/src/common/Logging/Log.h +++ b/src/common/Logging/Log.h @@ -20,20 +20,36 @@ #define TRINITYCORE_LOG_H #include "Define.h" -#include "Appender.h" -#include "Logger.h" +#include "AsioHacksFwd.h" +#include "LogCommon.h" #include "StringFormat.h" -#include "Common.h" -#include -#include -#include -#include -#include #include +#include +#include + +class Appender; +class Logger; +struct LogMessage; + +namespace boost +{ + namespace asio + { + class io_service; + } +} #define LOGGER_ROOT "root" +typedef Appender*(*AppenderCreatorFn)(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector&& extraArgs); + +template +Appender* CreateAppender(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector&& extraArgs) +{ + return new AppenderImpl(id, name, level, flags, std::forward>(extraArgs)); +} + class TC_COMMON_API Log { typedef std::unordered_map LoggerMap; @@ -41,9 +57,12 @@ class TC_COMMON_API Log private: Log(); ~Log(); + Log(Log const&) = delete; + Log(Log&&) = delete; + Log& operator=(Log const&) = delete; + Log& operator=(Log&&) = delete; public: - static Log* instance(); void Initialize(boost::asio::io_service* ioService); @@ -56,8 +75,7 @@ class TC_COMMON_API Log template inline void outMessage(std::string const& filter, LogLevel const level, Format&& fmt, Args&&... args) { - write(Trinity::make_unique(level, filter, - Trinity::StringFormat(std::forward(fmt), std::forward(args)...))); + outMessage(filter, level, Trinity::StringFormat(std::forward(fmt), std::forward(args)...)); } template @@ -66,13 +84,7 @@ class TC_COMMON_API Log if (!ShouldLog("commands.gm", LOG_LEVEL_INFO)) return; - std::unique_ptr msg = - Trinity::make_unique(LOG_LEVEL_INFO, "commands.gm", - Trinity::StringFormat(std::forward(fmt), std::forward(args)...)); - - msg->param1 = std::to_string(account); - - write(std::move(msg)); + outCommand(Trinity::StringFormat(std::forward(fmt), std::forward(args)...), std::to_string(account)); } void outCharDump(char const* str, uint32 account_id, uint64 guid, char const* name); @@ -83,9 +95,7 @@ class TC_COMMON_API Log void RegisterAppender() { using Index = typename AppenderImpl::TypeIndex; - auto itr = appenderFactory.find(Index::value); - ASSERT(itr == appenderFactory.end()); - appenderFactory[Index::value] = &CreateAppender; + RegisterAppender(Index::value, &CreateAppender); } std::string const& GetLogsDir() const { return m_logsDir; } @@ -102,10 +112,13 @@ class TC_COMMON_API Log void CreateLoggerFromConfig(std::string const& name); void ReadAppendersFromConfig(); void ReadLoggersFromConfig(); + void RegisterAppender(uint8 index, AppenderCreatorFn appenderCreateFn); + void outMessage(std::string const& filter, LogLevel level, std::string&& message); + void outCommand(std::string&& message, std::string&& param1); - AppenderCreatorMap appenderFactory; - AppenderMap appenders; - LoggerMap loggers; + std::unordered_map appenderFactory; + std::unordered_map> appenders; + std::unordered_map> loggers; uint8 AppenderId; LogLevel lowestLogLevel; @@ -113,44 +126,9 @@ class TC_COMMON_API Log std::string m_logsTimestamp; boost::asio::io_service* _ioService; - boost::asio::strand* _strand; + Trinity::AsioStrand* _strand; }; -inline Logger const* Log::GetLoggerByType(std::string const& type) const -{ - LoggerMap::const_iterator it = loggers.find(type); - if (it != loggers.end()) - return &(it->second); - - if (type == LOGGER_ROOT) - return NULL; - - std::string parentLogger = LOGGER_ROOT; - size_t found = type.find_last_of('.'); - if (found != std::string::npos) - parentLogger = type.substr(0,found); - - return GetLoggerByType(parentLogger); -} - -inline bool Log::ShouldLog(std::string const& type, LogLevel level) const -{ - // TODO: Use cache to store "Type.sub1.sub2": "Type" equivalence, should - // Speed up in cases where requesting "Type.sub1.sub2" but only configured - // Logger "Type" - - // Don't even look for a logger if the LogLevel is lower than lowest log levels across all loggers - if (level < lowestLogLevel) - return false; - - Logger const* logger = GetLoggerByType(type); - if (!logger) - return false; - - LogLevel logLevel = logger->getLogLevel(); - return logLevel != LOG_LEVEL_DISABLED && logLevel <= level; -} - #define sLog Log::instance() #define LOG_EXCEPTION_FREE(filterType__, level__, ...) \ @@ -167,7 +145,7 @@ inline bool Log::ShouldLog(std::string const& type, LogLevel level) const } #if TRINITY_PLATFORM != TRINITY_PLATFORM_WINDOWS -void check_args(const char*, ...) ATTR_PRINTF(1, 2); +void check_args(char const*, ...) ATTR_PRINTF(1, 2); void check_args(std::string const&, ...); // This will catch format errors on build time diff --git a/src/common/Logging/LogCommon.h b/src/common/Logging/LogCommon.h new file mode 100644 index 00000000000..50ab6131a73 --- /dev/null +++ b/src/common/Logging/LogCommon.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef LogCommon_h__ +#define LogCommon_h__ + +enum LogLevel +{ + LOG_LEVEL_DISABLED = 0, + LOG_LEVEL_TRACE = 1, + LOG_LEVEL_DEBUG = 2, + LOG_LEVEL_INFO = 3, + LOG_LEVEL_WARN = 4, + LOG_LEVEL_ERROR = 5, + LOG_LEVEL_FATAL = 6, + + NUM_ENABLED_LOG_LEVELS = 6 +}; + +enum AppenderType : uint8 +{ + APPENDER_NONE, + APPENDER_CONSOLE, + APPENDER_FILE, + APPENDER_DB +}; + +enum AppenderFlags +{ + APPENDER_FLAGS_NONE = 0x00, + APPENDER_FLAGS_PREFIX_TIMESTAMP = 0x01, + APPENDER_FLAGS_PREFIX_LOGLEVEL = 0x02, + APPENDER_FLAGS_PREFIX_LOGFILTERTYPE = 0x04, + APPENDER_FLAGS_USE_TIMESTAMP = 0x08, + APPENDER_FLAGS_MAKE_FILE_BACKUP = 0x10 +}; + +#endif // LogCommon_h__ diff --git a/src/common/Logging/LogMessage.cpp b/src/common/Logging/LogMessage.cpp new file mode 100644 index 00000000000..d907fbc12a2 --- /dev/null +++ b/src/common/Logging/LogMessage.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "LogMessage.h" +#include "Util.h" + +LogMessage::LogMessage(LogLevel _level, std::string const& _type, std::string&& _text) + : level(_level), type(_type), text(std::forward(_text)), mtime(time(nullptr)) +{ +} + +LogMessage::LogMessage(LogLevel _level, std::string const& _type, std::string&& _text, std::string&& _param1) + : level(_level), type(_type), text(std::forward(_text)), param1(std::forward(_param1)), mtime(time(nullptr)) +{ +} + +std::string LogMessage::getTimeStr(time_t time) +{ + tm aTm; + localtime_r(&time, &aTm); + char buf[20]; + snprintf(buf, 20, "%04d-%02d-%02d_%02d:%02d:%02d", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); + return std::string(buf); +} + +std::string LogMessage::getTimeStr() const +{ + return getTimeStr(mtime); +} diff --git a/src/common/Logging/LogMessage.h b/src/common/Logging/LogMessage.h new file mode 100644 index 00000000000..ed9c51cec2f --- /dev/null +++ b/src/common/Logging/LogMessage.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef LogMessage_h__ +#define LogMessage_h__ + +#include "Define.h" +#include "LogCommon.h" +#include +#include + +struct TC_COMMON_API LogMessage +{ + LogMessage(LogLevel _level, std::string const& _type, std::string&& _text); + LogMessage(LogLevel _level, std::string const& _type, std::string&& _text, std::string&& _param1); + + LogMessage(LogMessage const& /*other*/) = delete; + LogMessage& operator=(LogMessage const& /*other*/) = delete; + + static std::string getTimeStr(time_t time); + std::string getTimeStr() const; + + LogLevel const level; + std::string const type; + std::string const text; + std::string prefix; + std::string param1; + time_t mtime; + + ///@ Returns size of the log message content in bytes + uint32 Size() const + { + return static_cast(prefix.size() + text.size()); + } +}; + +#endif // LogMessage_h__ diff --git a/src/common/Logging/LogOperation.cpp b/src/common/Logging/LogOperation.cpp index 81bb98b9cce..c3a3711cc49 100644 --- a/src/common/Logging/LogOperation.cpp +++ b/src/common/Logging/LogOperation.cpp @@ -17,6 +17,15 @@ #include "LogOperation.h" #include "Logger.h" +#include "LogMessage.h" + +LogOperation::LogOperation(Logger const* _logger, std::unique_ptr&& _msg) : logger(_logger), msg(std::forward>(_msg)) +{ +} + +LogOperation::~LogOperation() +{ +} int LogOperation::call() { diff --git a/src/common/Logging/LogOperation.h b/src/common/Logging/LogOperation.h index a7230d1749d..ddf5ef1debc 100644 --- a/src/common/Logging/LogOperation.h +++ b/src/common/Logging/LogOperation.h @@ -18,8 +18,8 @@ #ifndef LOGOPERATION_H #define LOGOPERATION_H -#include #include "Define.h" +#include class Logger; struct LogMessage; @@ -27,11 +27,9 @@ struct LogMessage; class TC_COMMON_API LogOperation { public: - LogOperation(Logger const* _logger, std::unique_ptr&& _msg) - : logger(_logger), msg(std::forward>(_msg)) - { } + LogOperation(Logger const* _logger, std::unique_ptr&& _msg); - ~LogOperation() { } + ~LogOperation(); int call(); diff --git a/src/common/Logging/Logger.cpp b/src/common/Logging/Logger.cpp index 8e1f9c7ef9d..a3a72f15642 100644 --- a/src/common/Logging/Logger.cpp +++ b/src/common/Logging/Logger.cpp @@ -16,14 +16,10 @@ */ #include "Logger.h" +#include "Appender.h" +#include "LogMessage.h" -Logger::Logger(): name(""), level(LOG_LEVEL_DISABLED) { } - -void Logger::Create(std::string const& _name, LogLevel _level) -{ - name = _name; - level = _level; -} +Logger::Logger(std::string const& _name, LogLevel _level): name(_name), level(_level) { } std::string const& Logger::getName() const { @@ -58,7 +54,7 @@ void Logger::write(LogMessage* message) const return; } - for (AppenderMap::const_iterator it = appenders.begin(); it != appenders.end(); ++it) + for (auto it = appenders.begin(); it != appenders.end(); ++it) if (it->second) it->second->write(message); } diff --git a/src/common/Logging/Logger.h b/src/common/Logging/Logger.h index 1446062c22b..7aac15396f3 100644 --- a/src/common/Logging/Logger.h +++ b/src/common/Logging/Logger.h @@ -18,15 +18,20 @@ #ifndef LOGGER_H #define LOGGER_H -#include "Appender.h" +#include "Define.h" +#include "LogCommon.h" +#include +#include + +class Appender; +struct LogMessage; class TC_COMMON_API Logger { public: - Logger(); + Logger(std::string const& name, LogLevel level); - void Create(std::string const& name, LogLevel level); - void addAppender(uint8 type, Appender *); + void addAppender(uint8 type, Appender* appender); void delAppender(uint8 type); std::string const& getName() const; @@ -37,7 +42,7 @@ class TC_COMMON_API Logger private: std::string name; LogLevel level; - AppenderMap appenders; + std::unordered_map appenders; }; #endif diff --git a/src/common/Metric/Metric.cpp b/src/common/Metric/Metric.cpp index fbd8695429b..10f0d13b688 100644 --- a/src/common/Metric/Metric.cpp +++ b/src/common/Metric/Metric.cpp @@ -16,12 +16,18 @@ */ #include "Metric.h" -#include "Log.h" +#include "AsioHacksImpl.h" +#include "Common.h" #include "Config.h" +#include "Log.h" #include "Util.h" +#include +#include +#include void Metric::Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function overallStatusLogger) { + _dataStream = Trinity::make_unique(); _realmName = FormatInfluxDBTagValue(realmName); _batchTimer = Trinity::make_unique(ioService); _overallStatusTimer = Trinity::make_unique(ioService); @@ -31,8 +37,9 @@ void Metric::Initialize(std::string const& realmName, boost::asio::io_service& i bool Metric::Connect() { - _dataStream.connect(_hostname, _port); - auto error = _dataStream.error(); + auto& stream = static_cast(GetDataStream()); + stream.connect(_hostname, _port); + auto error = stream.error(); if (error) { TC_LOG_ERROR("metric", "Error connecting to '%s:%s', disabling Metric. Error message : %s", @@ -40,7 +47,7 @@ bool Metric::Connect() _enabled = false; return false; } - _dataStream.clear(); + stream.clear(); return true; } @@ -156,22 +163,22 @@ void Metric::SendBatch() return; } - if (!_dataStream.good() && !Connect()) + if (!GetDataStream().good() && !Connect()) return; - _dataStream << "POST " << "/write?db=" << _databaseName << " HTTP/1.1\r\n"; - _dataStream << "Host: " << _hostname << ":" << _port << "\r\n"; - _dataStream << "Accept: */*\r\n"; - _dataStream << "Content-Type: application/octet-stream\r\n"; - _dataStream << "Content-Transfer-Encoding: binary\r\n"; + GetDataStream() << "POST " << "/write?db=" << _databaseName << " HTTP/1.1\r\n"; + GetDataStream() << "Host: " << _hostname << ":" << _port << "\r\n"; + GetDataStream() << "Accept: */*\r\n"; + GetDataStream() << "Content-Type: application/octet-stream\r\n"; + GetDataStream() << "Content-Transfer-Encoding: binary\r\n"; - _dataStream << "Content-Length: " << std::to_string(batchedData.tellp()) << "\r\n\r\n"; - _dataStream << batchedData.rdbuf(); + GetDataStream() << "Content-Length: " << std::to_string(batchedData.tellp()) << "\r\n\r\n"; + GetDataStream() << batchedData.rdbuf(); std::string http_version; - _dataStream >> http_version; + GetDataStream() >> http_version; unsigned int status_code = 0; - _dataStream >> status_code; + GetDataStream() >> status_code; if (status_code != 204) { TC_LOG_ERROR("metric", "Error sending data, returned HTTP code: %u", status_code); @@ -179,14 +186,12 @@ void Metric::SendBatch() // Read and ignore the status description std::string status_description; - std::getline(_dataStream, status_description); + std::getline(GetDataStream(), status_description); // Read headers std::string header; - while (std::getline(_dataStream, header) && header != "\r") - { + while (std::getline(GetDataStream(), header) && header != "\r") if (header == "Connection: close\r") - _dataStream.close(); - } + static_cast(GetDataStream()).close(); ScheduleSend(); } @@ -200,7 +205,7 @@ void Metric::ScheduleSend() } else { - _dataStream.close(); + static_cast(GetDataStream()).close(); MetricData* data; // Clear the queue while (_queuedData.Dequeue(data)) @@ -228,8 +233,62 @@ void Metric::ScheduleOverallStatusLog() } } +std::string Metric::FormatInfluxDBValue(bool value) +{ + return value ? "t" : "f"; +} + +template +std::string Metric::FormatInfluxDBValue(T value) +{ + return std::to_string(value) + 'i'; +} + +std::string Metric::FormatInfluxDBValue(std::string const& value) +{ + return '"' + boost::replace_all_copy(value, "\"", "\\\"") + '"'; +} + +std::string Metric::FormatInfluxDBValue(char const* value) +{ + return FormatInfluxDBValue(std::string(value)); +} + +std::string Metric::FormatInfluxDBValue(double value) +{ + return std::to_string(value); +} + +std::string Metric::FormatInfluxDBValue(float value) +{ + return FormatInfluxDBValue(double(value)); +} + +std::string Metric::FormatInfluxDBTagValue(std::string const& value) +{ + // ToDo: should handle '=' and ',' characters too + return boost::replace_all_copy(value, " ", "\\ "); +} + +Metric::Metric() +{ +} + +Metric::~Metric() +{ +} + Metric* Metric::instance() { static Metric instance; return &instance; } + +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int8); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint8); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int16); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint16); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int32); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint32); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int64); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint64); diff --git a/src/common/Metric/Metric.h b/src/common/Metric/Metric.h index a5d8e5f589a..49347ffe1b7 100644 --- a/src/common/Metric/Metric.h +++ b/src/common/Metric/Metric.h @@ -18,11 +18,22 @@ #ifndef METRIC_H__ #define METRIC_H__ -#include "Common.h" -#include "Threading/MPSCQueue.h" -#include -#include -#include +#include "Define.h" +#include "AsioHacksFwd.h" +#include "MPSCQueue.h" +#include +#include +#include +#include +#include + +namespace boost +{ + namespace asio + { + class io_service; + } +} enum MetricDataType { @@ -33,7 +44,7 @@ enum MetricDataType struct MetricData { std::string Category; - std::chrono::time_point Timestamp; + std::chrono::system_clock::time_point Timestamp; MetricDataType Type; // LogValue-specific fields @@ -47,7 +58,8 @@ struct MetricData class TC_COMMON_API Metric { private: - boost::asio::ip::tcp::iostream _dataStream; + std::iostream& GetDataStream() { return *_dataStream; } + std::unique_ptr _dataStream; MPSCQueue _queuedData; std::unique_ptr _batchTimer; std::unique_ptr _overallStatusTimer; @@ -66,31 +78,24 @@ private: void ScheduleSend(); void ScheduleOverallStatusLog(); - template::value>::type* = nullptr> - static std::string FormatInfluxDBValue(T value) { return std::to_string(value) + 'i'; } + static std::string FormatInfluxDBValue(bool value); + template + static std::string FormatInfluxDBValue(T value); + static std::string FormatInfluxDBValue(std::string const& value); + static std::string FormatInfluxDBValue(char const* value); + static std::string FormatInfluxDBValue(double value); + static std::string FormatInfluxDBValue(float value); - static std::string FormatInfluxDBValue(std::string const& value) - { - return '"' + boost::replace_all_copy(value, "\"", "\\\"") + '"'; - } - - static std::string FormatInfluxDBValue(bool value) { return value ? "t" : "f"; } - static std::string FormatInfluxDBValue(const char* value) { return FormatInfluxDBValue(std::string(value)); } - static std::string FormatInfluxDBValue(double value) { return std::to_string(value); } - static std::string FormatInfluxDBValue(float value) { return FormatInfluxDBValue(double(value)); } - - static std::string FormatInfluxDBTagValue(std::string const& value) - { - // ToDo: should handle '=' and ',' characters too - return boost::replace_all_copy(value, " ", "\\ "); - } + static std::string FormatInfluxDBTagValue(std::string const& value); // ToDo: should format TagKey and FieldKey too in the same way as TagValue public: + Metric(); + ~Metric(); static Metric* instance(); - void Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function overallStatusLogger = [](){}); + void Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function overallStatusLogger); void LoadFromConfigs(); void Update(); diff --git a/src/common/PrecompiledHeaders/commonPCH.cpp b/src/common/PrecompiledHeaders/commonPCH.cpp index 52c623ca64a..eccfda05b32 100644 --- a/src/common/PrecompiledHeaders/commonPCH.cpp +++ b/src/common/PrecompiledHeaders/commonPCH.cpp @@ -1 +1,18 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "PrecompiledHeaders/commonPCH.h" diff --git a/src/common/PrecompiledHeaders/commonPCH.h b/src/common/PrecompiledHeaders/commonPCH.h index 2d4f1ff4694..4071ee22c63 100644 --- a/src/common/PrecompiledHeaders/commonPCH.h +++ b/src/common/PrecompiledHeaders/commonPCH.h @@ -1,13 +1,41 @@ -#include "Define.h" -#include "Common.h" +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "BoundingIntervalHierarchy.h" -#include "BoundingIntervalHierarchyWrapper.h" -#include "RegularGrid.h" -#include "Collision/VMapDefinitions.h" -#include "Collision/Maps/MapTree.h" -#include "Collision/Models/WorldModel.h" -#include "Collision/Models/ModelInstance.h" -#include "Collision/Models/GameObjectModel.h" -#include "Threading/ProducerConsumerQueue.h" -#include "Utilities/TaskScheduler.h" -#include "Utilities/EventMap.h" +#include "Common.h" +#include "Config.h" +#include "Define.h" +#include "Errors.h" +#include "GitRevision.h" +#include "Log.h" +#include "LogMessage.h" +#include "MapTree.h" +#include "ModelInstance.h" +#include "Util.h" +#include "VMapDefinitions.h" +#include "WorldModel.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/src/common/Threading/ProcessPriority.cpp b/src/common/Threading/ProcessPriority.cpp new file mode 100644 index 00000000000..83d7164a0f5 --- /dev/null +++ b/src/common/Threading/ProcessPriority.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ProcessPriority.h" +#include "Log.h" + +#ifdef _WIN32 // Windows +#include +#elif defined(__linux__) +#include +#include +#define PROCESS_HIGH_PRIORITY -15 // [-20, 19], default is 0 +#endif + +void SetProcessPriority(std::string const& logChannel, uint32 affinity, bool highPriority) +{ + ///- Handle affinity for multiple processors and process priority +#ifdef _WIN32 // Windows + + HANDLE hProcess = GetCurrentProcess(); + if (affinity > 0) + { + ULONG_PTR appAff; + ULONG_PTR sysAff; + + if (GetProcessAffinityMask(hProcess, &appAff, &sysAff)) + { + // remove non accessible processors + ULONG_PTR currentAffinity = affinity & appAff; + + if (!currentAffinity) + TC_LOG_ERROR(logChannel, "Processors marked in UseProcessors bitmask (hex) %x are not accessible. Accessible processors bitmask (hex): %x", affinity, appAff); + else if (SetProcessAffinityMask(hProcess, currentAffinity)) + TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %x", currentAffinity); + else + TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x", currentAffinity); + } + } + + if (highPriority) + { + if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS)) + TC_LOG_INFO(logChannel, "Process priority class set to HIGH"); + else + TC_LOG_ERROR(logChannel, "Can't set process priority class."); + } + +#elif defined(__linux__) // Linux + + if (affinity > 0) + { + cpu_set_t mask; + CPU_ZERO(&mask); + + for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i) + if (affinity & (1 << i)) + CPU_SET(i, &mask); + + if (sched_setaffinity(0, sizeof(mask), &mask)) + TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno)); + else + { + CPU_ZERO(&mask); + sched_getaffinity(0, sizeof(mask), &mask); + TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask)); + } + } + + if (highPriority) + { + if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY)) + TC_LOG_ERROR(logChannel, "Can't set process priority class, error: %s", strerror(errno)); + else + TC_LOG_INFO(logChannel, "Process priority class set to %i", getpriority(PRIO_PROCESS, 0)); + } + +#else + // Suppresses unused argument warning for all other platforms + (void)logChannel; + (void)affinity; + (void)highPriority; +#endif +} diff --git a/src/common/Threading/ProcessPriority.h b/src/common/Threading/ProcessPriority.h index b4ff3f5ecf6..3cb866c7de1 100644 --- a/src/common/Threading/ProcessPriority.h +++ b/src/common/Threading/ProcessPriority.h @@ -18,86 +18,12 @@ #ifndef _PROCESSPRIO_H #define _PROCESSPRIO_H -#include "Configuration/Config.h" +#include "Define.h" +#include -#ifdef __linux__ -#include -#include -#define PROCESS_HIGH_PRIORITY -15 // [-20, 19], default is 0 -#endif - -void SetProcessPriority(const std::string& logChannel) -{ -#if defined(_WIN32) || defined(__linux__) - - ///- Handle affinity for multiple processors and process priority - uint32 affinity = sConfigMgr->GetIntDefault("UseProcessors", 0); - bool highPriority = sConfigMgr->GetBoolDefault("ProcessPriority", false); - -#ifdef _WIN32 // Windows - - HANDLE hProcess = GetCurrentProcess(); - if (affinity > 0) - { - ULONG_PTR appAff; - ULONG_PTR sysAff; - - if (GetProcessAffinityMask(hProcess, &appAff, &sysAff)) - { - // remove non accessible processors - ULONG_PTR currentAffinity = affinity & appAff; - - if (!currentAffinity) - TC_LOG_ERROR(logChannel, "Processors marked in UseProcessors bitmask (hex) %x are not accessible. Accessible processors bitmask (hex): %x", affinity, appAff); - else if (SetProcessAffinityMask(hProcess, currentAffinity)) - TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %x", currentAffinity); - else - TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x", currentAffinity); - } - } - - if (highPriority) - { - if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS)) - TC_LOG_INFO(logChannel, "Process priority class set to HIGH"); - else - TC_LOG_ERROR(logChannel, "Can't set process priority class."); - } +#define CONFIG_PROCESSOR_AFFINITY "UseProcessors" +#define CONFIG_HIGH_PRIORITY "ProcessPriority" -#else // Linux - - if (affinity > 0) - { - cpu_set_t mask; - CPU_ZERO(&mask); - - for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i) - if (affinity & (1 << i)) - CPU_SET(i, &mask); - - if (sched_setaffinity(0, sizeof(mask), &mask)) - TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno)); - else - { - CPU_ZERO(&mask); - sched_getaffinity(0, sizeof(mask), &mask); - TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask)); - } - } - - if (highPriority) - { - if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY)) - TC_LOG_ERROR(logChannel, "Can't set process priority class, error: %s", strerror(errno)); - else - TC_LOG_INFO(logChannel, "Process priority class set to %i", getpriority(PRIO_PROCESS, 0)); - } - -#endif -#else - // Suppresses unused argument warning for all other platforms - (void)logChannel; -#endif -} +void TC_COMMON_API SetProcessPriority(std::string const& logChannel, uint32 affinity, bool highPriority); #endif diff --git a/src/common/Utilities/AsioHacksFwd.h b/src/common/Utilities/AsioHacksFwd.h new file mode 100644 index 00000000000..402c390f4f0 --- /dev/null +++ b/src/common/Utilities/AsioHacksFwd.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef AsioHacksFwd_h__ +#define AsioHacksFwd_h__ + +namespace boost +{ + namespace posix_time + { + class ptime; + } + + namespace asio + { + namespace ip + { + class address; + + class tcp; + + template + class basic_endpoint; + + typedef basic_endpoint tcp_endpoint; + + template + class resolver_service; + + template + class basic_resolver; + + typedef basic_resolver> tcp_resolver; + } + + template + struct time_traits; + + template + class deadline_timer_service; + + template + class basic_deadline_timer; + + typedef basic_deadline_timer, deadline_timer_service>> deadline_timer; + } +} + +namespace Trinity +{ + class AsioStrand; +} + +#endif // AsioHacksFwd_h__ diff --git a/src/common/Utilities/AsioHacksImpl.h b/src/common/Utilities/AsioHacksImpl.h new file mode 100644 index 00000000000..86888927a72 --- /dev/null +++ b/src/common/Utilities/AsioHacksImpl.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef AsioHacksImpl_h__ +#define AsioHacksImpl_h__ + +#include + +namespace Trinity +{ + class AsioStrand : public boost::asio::io_service::strand + { + public: + AsioStrand(boost::asio::io_service& io_service) : boost::asio::io_service::strand(io_service) { } + }; +} + +#endif // AsioHacksImpl_h__ diff --git a/src/common/Utilities/EventMap.cpp b/src/common/Utilities/EventMap.cpp index d4ea70174c4..e1c46d0ae65 100644 --- a/src/common/Utilities/EventMap.cpp +++ b/src/common/Utilities/EventMap.cpp @@ -16,6 +16,7 @@ */ #include "EventMap.h" +#include "Random.h" void EventMap::Reset() { @@ -32,6 +33,11 @@ void EventMap::SetPhase(uint8 phase) _phase = uint8(1 << (phase - 1)); } +void EventMap::ScheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group /*= 0*/, uint32 phase /*= 0*/) +{ + ScheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); +} + void EventMap::ScheduleEvent(uint32 eventId, uint32 time, uint32 group /*= 0*/, uint8 phase /*= 0*/) { if (group && group <= 8) @@ -43,6 +49,16 @@ void EventMap::ScheduleEvent(uint32 eventId, uint32 time, uint32 group /*= 0*/, _eventMap.insert(EventStore::value_type(_time + time, eventId)); } +void EventMap::RescheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group /*= 0*/, uint32 phase /*= 0*/) +{ + RescheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); +} + +void EventMap::Repeat(uint32 minTime, uint32 maxTime) +{ + Repeat(urand(minTime, maxTime)); +} + uint32 EventMap::ExecuteEvent() { while (!Empty()) diff --git a/src/common/Utilities/EventMap.h b/src/common/Utilities/EventMap.h index edcc7a64455..22899ea6b60 100644 --- a/src/common/Utilities/EventMap.h +++ b/src/common/Utilities/EventMap.h @@ -18,9 +18,9 @@ #ifndef _EVENT_MAP_H_ #define _EVENT_MAP_H_ -#include "Common.h" +#include "Define.h" #include "Duration.h" -#include "Util.h" +#include class TC_COMMON_API EventMap { @@ -134,10 +134,7 @@ public: * @param group The group which the event is associated to. Has to be between 1 and 8. 0 means it has no group. * @param phase The phase in which the event can occur. Has to be between 1 and 8. 0 means it can occur in all phases. */ - void ScheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0) - { - ScheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); - } + void ScheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0); /** * @name ScheduleEvent @@ -171,10 +168,7 @@ public: * @param group The group which the event is associated to. Has to be between 1 and 8. 0 means it has no group. * @param phase The phase in which the event can occur. Has to be between 1 and 8. 0 means it can occur in all phases. */ - void RescheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0) - { - RescheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); - } + void RescheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0); /** * @name RescheduleEvent @@ -227,10 +221,7 @@ public: * @param minTime Minimum time until the event occurs. * @param maxTime Maximum time until the event occurs. */ - void Repeat(uint32 minTime, uint32 maxTime) - { - Repeat(urand(minTime, maxTime)); - } + void Repeat(uint32 minTime, uint32 maxTime); /** * @name ExecuteEvent diff --git a/src/common/Utilities/EventProcessor.cpp b/src/common/Utilities/EventProcessor.cpp index 039ca37b9d7..0149f222da8 100644 --- a/src/common/Utilities/EventProcessor.cpp +++ b/src/common/Utilities/EventProcessor.cpp @@ -44,7 +44,7 @@ void EventProcessor::Update(uint32 p_time) m_time += p_time; // main event loop - EventList::iterator i; + std::multimap::iterator i; while (((i = m_events.begin()) != m_events.end()) && i->first <= m_time) { // get and remove event from queue diff --git a/src/common/Utilities/EventProcessor.h b/src/common/Utilities/EventProcessor.h index 2f65957581c..9a356b0e3f5 100644 --- a/src/common/Utilities/EventProcessor.h +++ b/src/common/Utilities/EventProcessor.h @@ -68,8 +68,6 @@ class TC_COMMON_API BasicEvent uint64 m_execTime; // planned time of next execution, filled by event handler }; -typedef std::multimap EventList; - class TC_COMMON_API EventProcessor { public: @@ -84,7 +82,7 @@ class TC_COMMON_API EventProcessor protected: uint64 m_time; - EventList m_events; + std::multimap m_events; }; #endif diff --git a/src/common/Utilities/Hash.h b/src/common/Utilities/Hash.h new file mode 100644 index 00000000000..fe2047f7024 --- /dev/null +++ b/src/common/Utilities/Hash.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef TrinityCore_Hash_h__ +#define TrinityCore_Hash_h__ + +#include +#include + +namespace Trinity +{ + template + inline void hash_combine(std::size_t& seed, T const& val) + { + seed ^= std::hash()(val) + 0x9E3779B9 + (seed << 6) + (seed >> 2); + } +} + + //! Hash implementation for std::pair to allow using pairs in unordered_set or as key for unordered_map + //! Individual types used in pair must be hashable by std::hash +namespace std +{ + template + struct hash> + { + public: + size_t operator()(std::pair const& p) const + { + size_t hashVal = 0; + Trinity::hash_combine(hashVal, p.first); + Trinity::hash_combine(hashVal, p.second); + return hashVal; + } + }; +} + +#endif // TrinityCore_Hash_h__ diff --git a/src/common/Utilities/Optional.h b/src/common/Utilities/Optional.h new file mode 100644 index 00000000000..b46f5cba5b5 --- /dev/null +++ b/src/common/Utilities/Optional.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef TrinityCore_Optional_h__ +#define TrinityCore_Optional_h__ + +#include "OptionalFwd.h" +#include +#include + +#endif // TrinityCore_Optional_h__ diff --git a/src/common/Utilities/OptionalFwd.h b/src/common/Utilities/OptionalFwd.h new file mode 100644 index 00000000000..d6b7a48f66e --- /dev/null +++ b/src/common/Utilities/OptionalFwd.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef OptionalFwd_h__ +#define OptionalFwd_h__ + +namespace boost +{ + template + class optional; +} + +//! Optional helper class to wrap optional values within. +template +using Optional = boost::optional; + +#endif // OptionalFwd_h__ diff --git a/src/common/Utilities/Random.cpp b/src/common/Utilities/Random.cpp index 3a0cdedcf4b..890ba1b8fce 100644 --- a/src/common/Utilities/Random.cpp +++ b/src/common/Utilities/Random.cpp @@ -16,7 +16,6 @@ */ #include "Random.h" -#include "Common.h" #include "Errors.h" #include "SFMT.h" #include @@ -53,8 +52,8 @@ uint32 urand(uint32 min, uint32 max) uint32 urandms(uint32 min, uint32 max) { ASSERT(max >= min); - ASSERT(INT_MAX / IN_MILLISECONDS >= max); - return GetRng()->URandom(min * IN_MILLISECONDS, max * IN_MILLISECONDS); + ASSERT(std::numeric_limits::max() / Milliseconds::period::den >= max); + return GetRng()->URandom(min * Milliseconds::period::den, max * Milliseconds::period::den); } float frand(float min, float max) diff --git a/src/common/Utilities/Random.h b/src/common/Utilities/Random.h index ded0a6c6e5c..d200282093a 100644 --- a/src/common/Utilities/Random.h +++ b/src/common/Utilities/Random.h @@ -21,7 +21,6 @@ #include "Define.h" #include "Duration.h" #include -#include /* Return a random number in the range min..max. */ TC_COMMON_API int32 irand(int32 min, int32 max); diff --git a/src/common/Utilities/StartProcess.cpp b/src/common/Utilities/StartProcess.cpp index 6f4676232ca..dc25cde3767 100644 --- a/src/common/Utilities/StartProcess.cpp +++ b/src/common/Utilities/StartProcess.cpp @@ -16,27 +16,20 @@ */ #include "StartProcess.h" - -#include -#include -#include +#include "Errors.h" +#include "Log.h" +#include "Optional.h" #include -#include #include -#include -#include #include -#include - -#include "Common.h" -#include "Log.h" using namespace boost::process; using namespace boost::process::initializers; using namespace boost::iostreams; -namespace Trinity { +namespace Trinity +{ template class TCLogSink @@ -51,7 +44,7 @@ public: TCLogSink(T callback) : callback_(std::move(callback)) { } - std::streamsize write(const char* str, std::streamsize size) + std::streamsize write(char const* str, std::streamsize size) { callback_(std::string(str, size)); return size; @@ -250,19 +243,15 @@ std::shared_ptr return handle; } -Optional SearchExecutableInPath(std::string const& filename) +std::string SearchExecutableInPath(std::string const& filename) { try { - auto result = search_path(filename); - if (result.empty()) - return boost::none; - else - return result; + return search_path(filename); } catch (...) { - return boost::none; + return ""; } } diff --git a/src/common/Utilities/StartProcess.h b/src/common/Utilities/StartProcess.h index 120c4f26ea6..2f8f6ffdec5 100644 --- a/src/common/Utilities/StartProcess.h +++ b/src/common/Utilities/StartProcess.h @@ -18,11 +18,14 @@ #ifndef Process_h__ #define Process_h__ +#include "Define.h" #include #include -#include "Common.h" +#include +#include -namespace Trinity { +namespace Trinity +{ /// Starts a process with the given arguments and parameters and will block /// until the process is finished. @@ -59,8 +62,8 @@ TC_COMMON_API std::shared_ptr bool secure = false); /// Searches for the given executable in the PATH variable -/// and returns a present optional when it was found. -TC_COMMON_API Optional SearchExecutableInPath(std::string const& filename); +/// and returns a non-empty string when it was found. +TC_COMMON_API std::string SearchExecutableInPath(std::string const& filename); } // namespace Trinity diff --git a/src/common/Utilities/StringFormat.h b/src/common/Utilities/StringFormat.h index acda4b41c9f..12eeb2a6d14 100644 --- a/src/common/Utilities/StringFormat.h +++ b/src/common/Utilities/StringFormat.h @@ -31,7 +31,7 @@ namespace Trinity } /// Returns true if the given char pointer is null. - inline bool IsFormatEmptyOrNull(const char* fmt) + inline bool IsFormatEmptyOrNull(char const* fmt) { return fmt == nullptr; } diff --git a/src/common/Utilities/TaskScheduler.cpp b/src/common/Utilities/TaskScheduler.cpp index 730ef8d4b89..a9dcf5dc09b 100644 --- a/src/common/Utilities/TaskScheduler.cpp +++ b/src/common/Utilities/TaskScheduler.cpp @@ -16,6 +16,7 @@ */ #include "TaskScheduler.h" +#include "Errors.h" TaskScheduler& TaskScheduler::ClearValidator() { diff --git a/src/common/Utilities/TaskScheduler.h b/src/common/Utilities/TaskScheduler.h index d6c399639bc..0213fb90f9b 100644 --- a/src/common/Utilities/TaskScheduler.h +++ b/src/common/Utilities/TaskScheduler.h @@ -18,6 +18,9 @@ #ifndef _TASK_SCHEDULER_H_ #define _TASK_SCHEDULER_H_ +#include "Duration.h" +#include "Optional.h" +#include "Random.h" #include #include #include @@ -26,11 +29,6 @@ #include #include -#include - -#include "Util.h" -#include "Duration.h" - class TaskContext; /// The TaskScheduler class provides the ability to schedule std::function's in the near future. @@ -73,13 +71,13 @@ class TC_COMMON_API TaskScheduler timepoint_t _end; duration_t _duration; - boost::optional _group; + Optional _group; repeated_t _repeated; task_handler_t _task; public: // All Argument construct - Task(timepoint_t const& end, duration_t const& duration, boost::optional const& group, + Task(timepoint_t const& end, duration_t const& duration, Optional const& group, repeated_t const repeated, task_handler_t const& task) : _end(end), _duration(duration), _group(group), _repeated(repeated), _task(task) { } diff --git a/src/common/Utilities/Timer.h b/src/common/Utilities/Timer.h index e774808bcb0..30a8873102c 100644 --- a/src/common/Utilities/Timer.h +++ b/src/common/Utilities/Timer.h @@ -19,6 +19,7 @@ #ifndef TRINITY_TIMER_H #define TRINITY_TIMER_H +#include "Define.h" #include inline uint32 getMSTime() diff --git a/src/common/Utilities/Util.cpp b/src/common/Utilities/Util.cpp index 58b02addc37..01df50a03de 100644 --- a/src/common/Utilities/Util.cpp +++ b/src/common/Utilities/Util.cpp @@ -18,11 +18,12 @@ #include "Util.h" #include "Common.h" -#include "CompilerDefs.h" -#include "utf8.h" -#include "Errors.h" // for ASSERT -#include -#include +#include +#include +#include +#include +#include +#include #if TRINITY_COMPILER == TRINITY_COMPILER_GNU #include @@ -100,7 +101,7 @@ void stripLineInvisibleChars(std::string &str) } #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) -struct tm* localtime_r(const time_t* time, struct tm *result) +struct tm* localtime_r(time_t const* time, struct tm *result) { localtime_s(result, time); return result; @@ -130,7 +131,7 @@ std::string secsToTimeString(uint64 timeInSecs, bool shortText, bool hoursOnly) return ss.str(); } -int32 MoneyStringToMoney(const std::string& moneyString) +int32 MoneyStringToMoney(std::string const& moneyString) { int32 money = 0; @@ -149,7 +150,7 @@ int32 MoneyStringToMoney(const std::string& moneyString) if (gCount + sCount + cCount != 1) return 0; - uint32 amount = atoi(*itr); + uint32 amount = strtoul(*itr, nullptr, 10); if (gCount == 1) money += amount * 100 * 100; else if (sCount == 1) @@ -161,7 +162,7 @@ int32 MoneyStringToMoney(const std::string& moneyString) return money; } -uint32 TimeStringToSecs(const std::string& timestring) +uint32 TimeStringToSecs(std::string const& timestring) { uint32 secs = 0; uint32 buffer = 0; @@ -171,8 +172,8 @@ uint32 TimeStringToSecs(const std::string& timestring) { if (isdigit(*itr)) { - buffer*=10; - buffer+= (*itr)-'0'; + buffer *= 10; + buffer += (*itr) - '0'; } else { @@ -184,9 +185,9 @@ uint32 TimeStringToSecs(const std::string& timestring) case 's': multiplier = 1; break; default : return 0; //bad format } - buffer*=multiplier; - secs+=buffer; - buffer=0; + buffer *= multiplier; + secs += buffer; + buffer = 0; } } @@ -214,16 +215,16 @@ bool IsIPAddress(char const* ipaddress) if (!ipaddress) return false; - // Let the big boys do it. - // Drawback: all valid ip address formats are recognized e.g.: 12.23, 121234, 0xABCD) - return inet_addr(ipaddress) != INADDR_NONE; + boost::system::error_code error; + boost::asio::ip::address::from_string(ipaddress, error); + return !error; } /// create PID file uint32 CreatePIDFile(std::string const& filename) { FILE* pid_file = fopen(filename.c_str(), "w"); - if (pid_file == NULL) + if (pid_file == nullptr) return 0; uint32 pid = GetPID(); @@ -374,6 +375,16 @@ bool WStrToUtf8(std::wstring const& wstr, std::string& utf8str) typedef wchar_t const* const* wstrlist; +void wstrToUpper(std::wstring& str) +{ + std::transform(str.begin(), str.end(), str.begin(), wcharToUpper); +} + +void wstrToLower(std::wstring& str) +{ + std::transform(str.begin(), str.end(), str.begin(), wcharToLower); +} + std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension) { // supported only Cyrillic cases @@ -400,12 +411,12 @@ std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension) static wchar_t const j_End[] = { wchar_t(1), wchar_t(0x0439), wchar_t(0x0000)}; static wchar_t const* const dropEnds[6][8] = { - { &a_End[1], &o_End[1], &ya_End[1], &ie_End[1], &soft_End[1], &j_End[1], NULL, NULL }, - { &a_End[1], &ya_End[1], &yeru_End[1], &i_End[1], NULL, NULL, NULL, NULL }, - { &ie_End[1], &u_End[1], &yu_End[1], &i_End[1], NULL, NULL, NULL, NULL }, - { &u_End[1], &yu_End[1], &o_End[1], &ie_End[1], &soft_End[1], &ya_End[1], &a_End[1], NULL }, - { &oj_End[1], &io_j_End[1], &ie_j_End[1], &o_m_End[1], &io_m_End[1], &ie_m_End[1], &yu_End[1], NULL }, - { &ie_End[1], &i_End[1], NULL, NULL, NULL, NULL, NULL, NULL } + { &a_End[1], &o_End[1], &ya_End[1], &ie_End[1], &soft_End[1], &j_End[1], nullptr, nullptr }, + { &a_End[1], &ya_End[1], &yeru_End[1], &i_End[1], nullptr, nullptr, nullptr, nullptr }, + { &ie_End[1], &u_End[1], &yu_End[1], &i_End[1], nullptr, nullptr, nullptr, nullptr }, + { &u_End[1], &yu_End[1], &o_End[1], &ie_End[1], &soft_End[1], &ya_End[1], &a_End[1], nullptr }, + { &oj_End[1], &io_j_End[1], &ie_j_End[1], &o_m_End[1], &io_m_End[1], &ie_m_End[1], &yu_End[1], nullptr }, + { &ie_End[1], &i_End[1], nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } }; for (wchar_t const* const* itr = &dropEnds[declension][0]; *itr; ++itr) @@ -552,12 +563,13 @@ void HexStrToByteArray(std::string const& str, uint8* out, bool reverse /*= fals for (int32 i = init; i != end; i += 2 * op) { char buffer[3] = { str[i], str[i + 1], '\0' }; - out[j++] = uint8(strtoul(buffer, NULL, 16)); + out[j++] = uint8(strtoul(buffer, nullptr, 16)); } } bool StringToBool(std::string const& str) { - std::string lowerStr = boost::algorithm::to_lower_copy(str); + std::string lowerStr = str; + std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower); return lowerStr == "1" || lowerStr == "true" || lowerStr == "yes"; } diff --git a/src/common/Utilities/Util.h b/src/common/Utilities/Util.h index 92a2f601c3f..458c783152c 100644 --- a/src/common/Utilities/Util.h +++ b/src/common/Utilities/Util.h @@ -21,24 +21,10 @@ #include "Define.h" #include "Errors.h" -#include "Random.h" -#include #include +#include #include -#include -#include -#include - -// Searcher for map of structs -template struct Finder -{ - T val_; - T S::* idMember_; - - Finder(T val, T S::* idMember) : val_(val), idMember_(idMember) {} - bool operator()(const std::pair &obj) { return obj.second.*idMember_ == val_; } -}; class TC_COMMON_API Tokenizer { @@ -70,12 +56,12 @@ private: TC_COMMON_API void stripLineInvisibleChars(std::string &src); -TC_COMMON_API int32 MoneyStringToMoney(const std::string& moneyString); +TC_COMMON_API int32 MoneyStringToMoney(std::string const& moneyString); -TC_COMMON_API struct tm* localtime_r(const time_t* time, struct tm *result); +TC_COMMON_API struct tm* localtime_r(time_t const* time, struct tm *result); TC_COMMON_API std::string secsToTimeString(uint64 timeInSecs, bool shortText = false, bool hoursOnly = false); -TC_COMMON_API uint32 TimeStringToSecs(const std::string& timestring); +TC_COMMON_API uint32 TimeStringToSecs(std::string const& timestring); TC_COMMON_API std::string TimeToTimestampStr(time_t t); // Percentage calculation @@ -289,15 +275,8 @@ inline wchar_t wcharToLower(wchar_t wchar) return wchar; } -inline void wstrToUpper(std::wstring& str) -{ - std::transform( str.begin(), str.end(), str.begin(), wcharToUpper ); -} - -inline void wstrToLower(std::wstring& str) -{ - std::transform( str.begin(), str.end(), str.begin(), wcharToLower ); -} +TC_COMMON_API void wstrToUpper(std::wstring& str); +TC_COMMON_API void wstrToLower(std::wstring& str); TC_COMMON_API std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension); @@ -382,7 +361,7 @@ public: part[2] = p3; } - inline bool operator <(const flag96 &right) const + inline bool operator<(flag96 const& right) const { for (uint8 i = 3; i > 0; --i) { @@ -394,7 +373,7 @@ public: return false; } - inline bool operator ==(const flag96 &right) const + inline bool operator==(flag96 const& right) const { return ( @@ -404,12 +383,12 @@ public: ); } - inline bool operator !=(const flag96 &right) const + inline bool operator!=(flag96 const& right) const { - return !this->operator ==(right); + return !(*this == right); } - inline flag96 & operator =(const flag96 &right) + inline flag96& operator=(flag96 const& right) { part[0] = right.part[0]; part[1] = right.part[1]; @@ -417,13 +396,12 @@ public: return *this; } - inline flag96 operator &(const flag96 &right) const + inline flag96 operator&(flag96 const& right) const { - return flag96(part[0] & right.part[0], part[1] & right.part[1], - part[2] & right.part[2]); + return flag96(part[0] & right.part[0], part[1] & right.part[1], part[2] & right.part[2]); } - inline flag96 & operator &=(const flag96 &right) + inline flag96& operator&=(flag96 const& right) { part[0] &= right.part[0]; part[1] &= right.part[1]; @@ -431,13 +409,12 @@ public: return *this; } - inline flag96 operator |(const flag96 &right) const + inline flag96 operator|(flag96 const& right) const { - return flag96(part[0] | right.part[0], part[1] | right.part[1], - part[2] | right.part[2]); + return flag96(part[0] | right.part[0], part[1] | right.part[1], part[2] | right.part[2]); } - inline flag96 & operator |=(const flag96 &right) + inline flag96& operator |=(flag96 const& right) { part[0] |= right.part[0]; part[1] |= right.part[1]; @@ -445,18 +422,17 @@ public: return *this; } - inline flag96 operator ~() const + inline flag96 operator~() const { return flag96(~part[0], ~part[1], ~part[2]); } - inline flag96 operator ^(const flag96 &right) const + inline flag96 operator^(flag96 const& right) const { - return flag96(part[0] ^ right.part[0], part[1] ^ right.part[1], - part[2] ^ right.part[2]); + return flag96(part[0] ^ right.part[0], part[1] ^ right.part[1], part[2] ^ right.part[2]); } - inline flag96 & operator ^=(const flag96 &right) + inline flag96& operator^=(flag96 const& right) { part[0] ^= right.part[0]; part[1] ^= right.part[1]; @@ -471,15 +447,15 @@ public: inline bool operator !() const { - return !this->operator bool(); + return !(bool(*this)); } - inline uint32 & operator [](uint8 el) + inline uint32& operator[](uint8 el) { return part[el]; } - inline const uint32 & operator [](uint8 el) const + inline uint32 const& operator [](uint8 el) const { return part[el]; } diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index 742fc6dada0..8256b976f89 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -17,9 +17,7 @@ if(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW) endif() if(WIN32) - set(sources_windows - ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.cpp - ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.h + list(APPEND sources_windows ${CMAKE_SOURCE_DIR}/src/common/Platform/ServiceWin32.cpp ${CMAKE_SOURCE_DIR}/src/common/Platform/ServiceWin32.h ) diff --git a/src/server/authserver/Authentication/AuthCodes.cpp b/src/server/authserver/Authentication/AuthCodes.cpp index d0c41258130..4b6e78a72a3 100644 --- a/src/server/authserver/Authentication/AuthCodes.cpp +++ b/src/server/authserver/Authentication/AuthCodes.cpp @@ -77,6 +77,6 @@ namespace AuthHelper if (PreBcAcceptedClientBuilds[i].Build == build) return &PreBcAcceptedClientBuilds[i]; - return NULL; + return nullptr; } } diff --git a/src/server/authserver/Authentication/TOTP.cpp b/src/server/authserver/Authentication/TOTP.cpp index e26fd47e167..0566adea23a 100644 --- a/src/server/authserver/Authentication/TOTP.cpp +++ b/src/server/authserver/Authentication/TOTP.cpp @@ -18,7 +18,7 @@ #include "TOTP.h" #include -int base32_decode(const char* encoded, char* result, int bufSize) +int base32_decode(char const* encoded, char* result, int bufSize) { // Base32 implementation // Copyright 2010 Google Inc. @@ -68,7 +68,7 @@ int base32_decode(const char* encoded, char* result, int bufSize) namespace TOTP { - unsigned int GenerateToken(const char* b32key) + unsigned int GenerateToken(char const* b32key) { size_t keySize = strlen(b32key); int bufsize = (keySize + 7)/8*5; @@ -76,7 +76,7 @@ namespace TOTP memset(encoded, 0, bufsize); unsigned int hmacResSize = HMAC_RES_SIZE; unsigned char hmacRes[HMAC_RES_SIZE]; - unsigned long timestamp = time(NULL)/30; + unsigned long timestamp = time(nullptr)/30; unsigned char challenge[8]; for (int i = 8; i--;timestamp >>= 8) diff --git a/src/server/authserver/Authentication/TOTP.h b/src/server/authserver/Authentication/TOTP.h index 94a3383e831..7137bb0e662 100644 --- a/src/server/authserver/Authentication/TOTP.h +++ b/src/server/authserver/Authentication/TOTP.h @@ -23,7 +23,7 @@ namespace TOTP { - unsigned int GenerateToken(const char* b32key); + unsigned int GenerateToken(char const* b32key); } #endif diff --git a/src/server/authserver/Main.cpp b/src/server/authserver/Main.cpp index 6e67a950343..072810867b1 100644 --- a/src/server/authserver/Main.cpp +++ b/src/server/authserver/Main.cpp @@ -24,22 +24,24 @@ * authentication server */ +#include "AppenderDB.h" #include "AuthSocketMgr.h" -#include "Common.h" +#include "Banner.h" #include "Config.h" #include "DatabaseEnv.h" #include "DatabaseLoader.h" -#include "Log.h" -#include "AppenderDB.h" +#include "GitRevision.h" +#include "MySQLThreading.h" #include "ProcessPriority.h" #include "RealmList.h" -#include "GitRevision.h" #include "Util.h" -#include -#include +#include #include -#include +#include #include +#include +#include +#include using boost::asio::ip::tcp; using namespace boost::program_options; @@ -104,11 +106,18 @@ int main(int argc, char** argv) sLog->RegisterAppender(); sLog->Initialize(nullptr); - TC_LOG_INFO("server.authserver", "%s (authserver)", GitRevision::GetFullVersion()); - TC_LOG_INFO("server.authserver", " to stop.\n"); - TC_LOG_INFO("server.authserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); - TC_LOG_INFO("server.authserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); - TC_LOG_INFO("server.authserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + Trinity::Banner::Show("authserver", + [](char const* text) + { + TC_LOG_INFO("server.authserver", "%s", text); + }, + []() + { + TC_LOG_INFO("server.authserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); + TC_LOG_INFO("server.authserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); + TC_LOG_INFO("server.authserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + } + ); // authserver PID file creation std::string pidFile = sConfigMgr->GetStringDefault("PidFile", ""); @@ -168,7 +177,7 @@ int main(int argc, char** argv) signals.async_wait(std::bind(&SignalHandler, std::weak_ptr(ioService), std::placeholders::_1, std::placeholders::_2)); // Set process priority according to configuration settings - SetProcessPriority("server.authserver"); + SetProcessPriority("server.authserver", sConfigMgr->GetIntDefault(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetBoolDefault(CONFIG_HIGH_PRIORITY, false)); // Enabled a timed callback for handling the database keep alive ping int32 dbPingInterval = sConfigMgr->GetIntDefault("MaxPingTime", 30); diff --git a/src/server/authserver/PrecompiledHeaders/authPCH.cpp b/src/server/authserver/PrecompiledHeaders/authPCH.cpp index eed50cb2c0b..76ee97ee0e7 100644 --- a/src/server/authserver/PrecompiledHeaders/authPCH.cpp +++ b/src/server/authserver/PrecompiledHeaders/authPCH.cpp @@ -1 +1,18 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "authPCH.h" diff --git a/src/server/authserver/PrecompiledHeaders/authPCH.h b/src/server/authserver/PrecompiledHeaders/authPCH.h index ef757a656d5..26a070fba64 100644 --- a/src/server/authserver/PrecompiledHeaders/authPCH.h +++ b/src/server/authserver/PrecompiledHeaders/authPCH.h @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "Common.h" #include "Configuration/Config.h" #include "Database/DatabaseEnv.h" diff --git a/src/server/authserver/Server/AuthSession.cpp b/src/server/authserver/Server/AuthSession.cpp index dfd77c39cb5..8e6ec882636 100644 --- a/src/server/authserver/Server/AuthSession.cpp +++ b/src/server/authserver/Server/AuthSession.cpp @@ -17,16 +17,17 @@ */ #include "AuthSession.h" -#include "Log.h" #include "AuthCodes.h" -#include "Database/DatabaseEnv.h" -#include "QueryCallback.h" +#include "Config.h" +#include "Errors.h" +#include "Log.h" +#include "DatabaseEnv.h" +#include "RealmList.h" #include "SHA1.h" #include "TOTP.h" -#include "openssl/crypto.h" -#include "Configuration/Config.h" -#include "RealmList.h" +#include "Util.h" #include +#include using boost::asio::ip::tcp; @@ -285,7 +286,7 @@ bool AuthSession::HandleLogonChallenge() if (challenge->size - (sizeof(sAuthLogonChallenge_C) - AUTH_LOGON_CHALLENGE_INITIAL_SIZE - 1) != challenge->I_len) return false; - std::string login((const char*)challenge->I, challenge->I_len); + std::string login((char const*)challenge->I, challenge->I_len); TC_LOG_DEBUG("server.authserver", "[AuthChallenge] '%s'", login.c_str()); _build = challenge->build; @@ -481,7 +482,7 @@ bool AuthSession::HandleLogonProof() return false; SHA1Hash sha; - sha.UpdateBigNumbers(&A, &B, NULL); + sha.UpdateBigNumbers(&A, &B, nullptr); sha.Finalize(); BigNumber u; u.SetBinary(sha.GetDigest(), 20); @@ -517,11 +518,11 @@ bool AuthSession::HandleLogonProof() uint8 hash[20]; sha.Initialize(); - sha.UpdateBigNumbers(&N, NULL); + sha.UpdateBigNumbers(&N, nullptr); sha.Finalize(); memcpy(hash, sha.GetDigest(), 20); sha.Initialize(); - sha.UpdateBigNumbers(&g, NULL); + sha.UpdateBigNumbers(&g, nullptr); sha.Finalize(); for (int i = 0; i < 20; ++i) @@ -537,9 +538,9 @@ bool AuthSession::HandleLogonProof() memcpy(t4, sha.GetDigest(), SHA_DIGEST_LENGTH); sha.Initialize(); - sha.UpdateBigNumbers(&t3, NULL); + sha.UpdateBigNumbers(&t3, nullptr); sha.UpdateData(t4, SHA_DIGEST_LENGTH); - sha.UpdateBigNumbers(&s, &A, &B, &K, NULL); + sha.UpdateBigNumbers(&s, &A, &B, &K, nullptr); sha.Finalize(); BigNumber M; M.SetBinary(sha.GetDigest(), sha.GetLength()); @@ -583,7 +584,7 @@ bool AuthSession::HandleLogonProof() // Finish SRP6 and send the final result to the client sha.Initialize(); - sha.UpdateBigNumbers(&A, &M, &K, NULL); + sha.UpdateBigNumbers(&A, &M, &K, nullptr); sha.Finalize(); ByteBuffer packet; @@ -687,7 +688,7 @@ bool AuthSession::HandleReconnectChallenge() if (challenge->size - (sizeof(sAuthLogonChallenge_C) - AUTH_LOGON_CHALLENGE_INITIAL_SIZE - 1) != challenge->I_len) return false; - std::string login((const char*)challenge->I, challenge->I_len); + std::string login((char const*)challenge->I, challenge->I_len); TC_LOG_DEBUG("server.authserver", "[ReconnectChallenge] '%s'", login.c_str()); _build = challenge->build; @@ -754,7 +755,7 @@ bool AuthSession::HandleReconnectProof() SHA1Hash sha; sha.Initialize(); sha.UpdateData(_accountInfo.Login); - sha.UpdateBigNumbers(&t1, &_reconnectProof, &K, NULL); + sha.UpdateBigNumbers(&t1, &_reconnectProof, &K, nullptr); sha.Finalize(); if (!memcmp(sha.GetDigest(), reconnectProof->R2, SHA_DIGEST_LENGTH)) @@ -805,7 +806,7 @@ void AuthSession::RealmListCallback(PreparedQueryResult result) size_t RealmListSize = 0; for (RealmList::RealmMap::value_type const& i : sRealmList->GetRealms()) { - const Realm &realm = i.second; + Realm const& realm = i.second; // don't work with realms which not compatible with the client bool okBuild = ((_expversion & POST_BC_EXP_FLAG) && realm.Build == _build) || ((_expversion & PRE_BC_EXP_FLAG) && !AuthHelper::IsPreBCAcceptedClientBuild(realm.Build)); diff --git a/src/server/database/Database/AdhocStatement.cpp b/src/server/database/Database/AdhocStatement.cpp index 644af01787b..90ddc1630f4 100644 --- a/src/server/database/Database/AdhocStatement.cpp +++ b/src/server/database/Database/AdhocStatement.cpp @@ -16,10 +16,14 @@ */ #include "AdhocStatement.h" +#include "Errors.h" #include "MySQLConnection.h" +#include "QueryResult.h" +#include +#include /*! Basic, ad-hoc queries. */ -BasicStatementTask::BasicStatementTask(const char* sql, bool async) : +BasicStatementTask::BasicStatementTask(char const* sql, bool async) : m_result(nullptr) { m_sql = strdup(sql); @@ -43,7 +47,7 @@ bool BasicStatementTask::Execute() if (!result || !result->GetRowCount() || !result->NextRow()) { delete result; - m_result->set_value(QueryResult(NULL)); + m_result->set_value(QueryResult(nullptr)); return false; } diff --git a/src/server/database/Database/AdhocStatement.h b/src/server/database/Database/AdhocStatement.h index e419908d175..e42e3474df3 100644 --- a/src/server/database/Database/AdhocStatement.h +++ b/src/server/database/Database/AdhocStatement.h @@ -18,24 +18,22 @@ #ifndef _ADHOCSTATEMENT_H #define _ADHOCSTATEMENT_H -#include +#include "Define.h" +#include "DatabaseEnvFwd.h" #include "SQLOperation.h" -typedef std::future QueryResultFuture; -typedef std::promise QueryResultPromise; - /*! Raw, ad-hoc query. */ class TC_DATABASE_API BasicStatementTask : public SQLOperation { public: - BasicStatementTask(const char* sql, bool async = false); + BasicStatementTask(char const* sql, bool async = false); ~BasicStatementTask(); bool Execute() override; QueryResultFuture GetFuture() const { return m_result->get_future(); } private: - const char* m_sql; //- Raw query to be executed + char const* m_sql; //- Raw query to be executed bool m_has_result; QueryResultPromise* m_result; }; diff --git a/src/server/database/Database/DatabaseEnv.cpp b/src/server/database/Database/DatabaseEnv.cpp index 21b937d3c76..c7419f95de8 100644 --- a/src/server/database/Database/DatabaseEnv.cpp +++ b/src/server/database/Database/DatabaseEnv.cpp @@ -17,6 +17,6 @@ #include "DatabaseEnv.h" -WorldDatabaseWorkerPool WorldDatabase; -CharacterDatabaseWorkerPool CharacterDatabase; -LoginDatabaseWorkerPool LoginDatabase; +DatabaseWorkerPool WorldDatabase; +DatabaseWorkerPool CharacterDatabase; +DatabaseWorkerPool LoginDatabase; diff --git a/src/server/database/Database/DatabaseEnv.h b/src/server/database/Database/DatabaseEnv.h index dde0d5f1847..301b94567ce 100644 --- a/src/server/database/Database/DatabaseEnv.h +++ b/src/server/database/Database/DatabaseEnv.h @@ -19,30 +19,24 @@ #ifndef DATABASEENV_H #define DATABASEENV_H -#include "Common.h" -#include "Errors.h" -#include "Log.h" - -#include "Field.h" -#include "QueryResult.h" - -#include "MySQLThreading.h" -#include "Transaction.h" - -#define _LIKE_ "LIKE" -#define _TABLE_SIM_ '`' -#define _CONCAT3_(A, B, C) "CONCAT( " A ", " B ", " C " )" -#define _OFFSET_ "LIMIT %d, 1" +#include "Define.h" +#include "DatabaseWorkerPool.h" #include "Implementation/LoginDatabase.h" #include "Implementation/CharacterDatabase.h" #include "Implementation/WorldDatabase.h" +#include "Field.h" +#include "PreparedStatement.h" +#include "QueryCallback.h" +#include "QueryResult.h" +#include "Transaction.h" + /// Accessor to the world database -TC_DATABASE_API extern WorldDatabaseWorkerPool WorldDatabase; +TC_DATABASE_API extern DatabaseWorkerPool WorldDatabase; /// Accessor to the character database -TC_DATABASE_API extern CharacterDatabaseWorkerPool CharacterDatabase; +TC_DATABASE_API extern DatabaseWorkerPool CharacterDatabase; /// Accessor to the realm/login database -TC_DATABASE_API extern LoginDatabaseWorkerPool LoginDatabase; +TC_DATABASE_API extern DatabaseWorkerPool LoginDatabase; #endif diff --git a/src/server/database/Database/DatabaseEnvFwd.h b/src/server/database/Database/DatabaseEnvFwd.h new file mode 100644 index 00000000000..893dffaaace --- /dev/null +++ b/src/server/database/Database/DatabaseEnvFwd.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef DatabaseEnvFwd_h__ +#define DatabaseEnvFwd_h__ + +#include +#include + +class Field; + +class ResultSet; +typedef std::shared_ptr QueryResult; +typedef std::future QueryResultFuture; +typedef std::promise QueryResultPromise; + +class PreparedStatement; + +class PreparedResultSet; +typedef std::shared_ptr PreparedQueryResult; +typedef std::future PreparedQueryResultFuture; +typedef std::promise PreparedQueryResultPromise; + +class QueryCallback; + +class Transaction; +typedef std::shared_ptr SQLTransaction; + +class SQLQueryHolder; +typedef std::future QueryResultHolderFuture; +typedef std::promise QueryResultHolderPromise; + +// mysql +typedef struct st_mysql MYSQL; +typedef struct st_mysql_res MYSQL_RES; +typedef struct st_mysql_field MYSQL_FIELD; +typedef struct st_mysql_bind MYSQL_BIND; +typedef struct st_mysql_stmt MYSQL_STMT; + +#endif // DatabaseEnvFwd_h__ diff --git a/src/server/database/Database/DatabaseLoader.cpp b/src/server/database/Database/DatabaseLoader.cpp index 31e4b63f46c..6dd5003cc4b 100644 --- a/src/server/database/Database/DatabaseLoader.cpp +++ b/src/server/database/Database/DatabaseLoader.cpp @@ -16,8 +16,10 @@ */ #include "DatabaseLoader.h" -#include "DBUpdater.h" #include "Config.h" +#include "DatabaseEnv.h" +#include "DBUpdater.h" +#include "Log.h" #include @@ -178,8 +180,8 @@ bool DatabaseLoader::Process(std::queue& queue) } template TC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(LoginDatabaseWorkerPool&, std::string const&); +DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); template TC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(CharacterDatabaseWorkerPool&, std::string const&); +DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); template TC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(WorldDatabaseWorkerPool&, std::string const&); +DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); diff --git a/src/server/database/Database/DatabaseLoader.h b/src/server/database/Database/DatabaseLoader.h index 472a6811f31..78125b9ac7e 100644 --- a/src/server/database/Database/DatabaseLoader.h +++ b/src/server/database/Database/DatabaseLoader.h @@ -18,12 +18,15 @@ #ifndef DatabaseLoader_h__ #define DatabaseLoader_h__ -#include "DatabaseWorkerPool.h" -#include "DBUpdater.h" +#include "Define.h" #include -#include #include +#include +#include + +template +class DatabaseWorkerPool; // A helper class to initiate all database worker pools, // handles updating, delays preparing of statements and cleans up on failure. diff --git a/src/server/database/Database/DatabaseWorker.cpp b/src/server/database/Database/DatabaseWorker.cpp index 54980863861..c26562b4ff1 100644 --- a/src/server/database/Database/DatabaseWorker.cpp +++ b/src/server/database/Database/DatabaseWorker.cpp @@ -15,7 +15,6 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "DatabaseWorker.h" #include "SQLOperation.h" #include "ProducerConsumerQueue.h" diff --git a/src/server/database/Database/DatabaseWorker.h b/src/server/database/Database/DatabaseWorker.h index 38444706656..1476a2b9e99 100644 --- a/src/server/database/Database/DatabaseWorker.h +++ b/src/server/database/Database/DatabaseWorker.h @@ -18,8 +18,12 @@ #ifndef _WORKERTHREAD_H #define _WORKERTHREAD_H +#include "Define.h" +#include #include -#include "ProducerConsumerQueue.h" + +template +class ProducerConsumerQueue; class MySQLConnection; class SQLOperation; @@ -37,7 +41,7 @@ class TC_DATABASE_API DatabaseWorker void WorkerThread(); std::thread _workerThread; - std::atomic_bool _cancelationToken; + std::atomic _cancelationToken; DatabaseWorker(DatabaseWorker const& right) = delete; DatabaseWorker& operator=(DatabaseWorker const& right) = delete; diff --git a/src/server/database/Database/DatabaseWorkerPool.cpp b/src/server/database/Database/DatabaseWorkerPool.cpp index fca4f666310..2d8c22e4d6f 100644 --- a/src/server/database/Database/DatabaseWorkerPool.cpp +++ b/src/server/database/Database/DatabaseWorkerPool.cpp @@ -16,12 +16,39 @@ */ #include "DatabaseWorkerPool.h" -#include "DatabaseEnv.h" +#include "AdhocStatement.h" +#include "Common.h" +#include "Errors.h" +#include "Implementation/LoginDatabase.h" +#include "Implementation/WorldDatabase.h" +#include "Implementation/CharacterDatabase.h" +#include "Log.h" +#include "PreparedStatement.h" +#include "ProducerConsumerQueue.h" #include "QueryCallback.h" +#include "QueryHolder.h" +#include "QueryResult.h" +#include "SQLOperation.h" +#include "Transaction.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include +#include #define MIN_MYSQL_SERVER_VERSION 50100u #define MIN_MYSQL_CLIENT_VERSION 50100u +class PingOperation : public SQLOperation +{ + //! Operation for idle delaythreads + bool Execute() override + { + m_conn->Ping(); + return true; + } +}; + template DatabaseWorkerPool::DatabaseWorkerPool() : _queue(new ProducerConsumerQueue()), @@ -33,6 +60,12 @@ DatabaseWorkerPool::DatabaseWorkerPool() mysql_get_client_info(), MYSQL_SERVER_VERSION); } +template +DatabaseWorkerPool::~DatabaseWorkerPool() +{ + _queue->Cancel(); +} + template void DatabaseWorkerPool::SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads) @@ -135,7 +168,7 @@ bool DatabaseWorkerPool::PrepareStatements() } template -QueryResult DatabaseWorkerPool::Query(const char* sql, T* connection /*= nullptr*/) +QueryResult DatabaseWorkerPool::Query(char const* sql, T* connection /*= nullptr*/) { if (!connection) connection = GetFreeConnection(); @@ -145,7 +178,7 @@ QueryResult DatabaseWorkerPool::Query(const char* sql, T* connection /*= null if (!result || !result->GetRowCount() || !result->NextRow()) { delete result; - return QueryResult(NULL); + return QueryResult(nullptr); } return QueryResult(result); @@ -164,14 +197,14 @@ PreparedQueryResult DatabaseWorkerPool::Query(PreparedStatement* stmt) if (!ret || !ret->GetRowCount()) { delete ret; - return PreparedQueryResult(NULL); + return PreparedQueryResult(nullptr); } return PreparedQueryResult(ret); } template -QueryCallback DatabaseWorkerPool::AsyncQuery(const char* sql) +QueryCallback DatabaseWorkerPool::AsyncQuery(char const* sql) { BasicStatementTask* task = new BasicStatementTask(sql, true); // Store future result before enqueueing - task might get already processed and deleted before returning from this method @@ -200,6 +233,12 @@ QueryResultHolderFuture DatabaseWorkerPool::DelayQueryHolder(SQLQueryHolder* return result; } +template +SQLTransaction DatabaseWorkerPool::BeginTransaction() +{ + return std::make_shared(); +} + template void DatabaseWorkerPool::CommitTransaction(SQLTransaction transaction) { @@ -252,6 +291,12 @@ void DatabaseWorkerPool::DirectCommitTransaction(SQLTransaction& transaction) connection->Unlock(); } +template +PreparedStatement* DatabaseWorkerPool::GetPreparedStatement(PreparedStatementIndex index) +{ + return new PreparedStatement(index, _preparedStatementSize[index]); +} + template void DatabaseWorkerPool::EscapeString(std::string& str) { @@ -324,6 +369,22 @@ uint32 DatabaseWorkerPool::OpenConnections(InternalIndex type, uint8 numConne return 0; } +template +unsigned long DatabaseWorkerPool::EscapeString(char* to, char const* from, unsigned long length) +{ + if (!to || !from || !length) + return 0; + + return mysql_real_escape_string( + _connections[IDX_SYNCH].front()->GetHandle(), to, from, length); +} + +template +void DatabaseWorkerPool::Enqueue(SQLOperation* op) +{ + _queue->Push(op); +} + template T* DatabaseWorkerPool::GetFreeConnection() { @@ -342,6 +403,69 @@ T* DatabaseWorkerPool::GetFreeConnection() return connection; } +template +char const* DatabaseWorkerPool::GetDatabaseName() const +{ + return _connectionInfo->database.c_str(); +} + +template +void DatabaseWorkerPool::Execute(char const* sql) +{ + if (Trinity::IsFormatEmptyOrNull(sql)) + return; + + BasicStatementTask* task = new BasicStatementTask(sql); + Enqueue(task); +} + +template +void DatabaseWorkerPool::Execute(PreparedStatement* stmt) +{ + PreparedStatementTask* task = new PreparedStatementTask(stmt); + Enqueue(task); +} + +template +void DatabaseWorkerPool::DirectExecute(char const* sql) +{ + if (Trinity::IsFormatEmptyOrNull(sql)) + return; + + T* connection = GetFreeConnection(); + connection->Execute(sql); + connection->Unlock(); +} + +template +void DatabaseWorkerPool::DirectExecute(PreparedStatement* stmt) +{ + T* connection = GetFreeConnection(); + connection->Execute(stmt); + connection->Unlock(); + + //! Delete proxy-class. Not needed anymore + delete stmt; +} + +template +void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction& trans, char const* sql) +{ + if (!trans) + Execute(sql); + else + trans->Append(sql); +} + +template +void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt) +{ + if (!trans) + Execute(stmt); + else + trans->Append(stmt); +} + template class TC_DATABASE_API DatabaseWorkerPool; template class TC_DATABASE_API DatabaseWorkerPool; template class TC_DATABASE_API DatabaseWorkerPool; diff --git a/src/server/database/Database/DatabaseWorkerPool.h b/src/server/database/Database/DatabaseWorkerPool.h index b1be44adf32..7b4698a5bce 100644 --- a/src/server/database/Database/DatabaseWorkerPool.h +++ b/src/server/database/Database/DatabaseWorkerPool.h @@ -18,32 +18,18 @@ #ifndef _DATABASEWORKERPOOL_H #define _DATABASEWORKERPOOL_H -#include "Common.h" -#include "MySQLConnection.h" -#include "Transaction.h" -#include "DatabaseWorker.h" -#include "PreparedStatement.h" -#include "Log.h" -#include "QueryResult.h" -#include "QueryHolder.h" -#include "AdhocStatement.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" #include "StringFormat.h" - -#include -#include #include +#include +#include -class QueryCallback; +template +class ProducerConsumerQueue; -class PingOperation : public SQLOperation -{ - //! Operation for idle delaythreads - bool Execute() override - { - m_conn->Ping(); - return true; - } -}; +class SQLOperation; +struct MySQLConnectionInfo; template class DatabaseWorkerPool @@ -60,10 +46,7 @@ class DatabaseWorkerPool /* Activity state */ DatabaseWorkerPool(); - ~DatabaseWorkerPool() - { - _queue->Cancel(); - } + ~DatabaseWorkerPool(); void SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads); @@ -85,14 +68,7 @@ class DatabaseWorkerPool //! Enqueues a one-way SQL operation in string format that will be executed asynchronously. //! This method should only be used for queries that are only executed once, e.g during startup. - void Execute(const char* sql) - { - if (Trinity::IsFormatEmptyOrNull(sql)) - return; - - BasicStatementTask* task = new BasicStatementTask(sql); - Enqueue(task); - } + void Execute(char const* sql); //! Enqueues a one-way SQL operation in string format -with variable args- that will be executed asynchronously. //! This method should only be used for queries that are only executed once, e.g during startup. @@ -107,11 +83,7 @@ class DatabaseWorkerPool //! Enqueues a one-way SQL operation in prepared statement format that will be executed asynchronously. //! Statement must be prepared with CONNECTION_ASYNC flag. - void Execute(PreparedStatement* stmt) - { - PreparedStatementTask* task = new PreparedStatementTask(stmt); - Enqueue(task); - } + void Execute(PreparedStatement* stmt); /** Direct synchronous one-way statement methods. @@ -119,15 +91,7 @@ class DatabaseWorkerPool //! Directly executes a one-way SQL operation in string format, that will block the calling thread until finished. //! This method should only be used for queries that are only executed once, e.g during startup. - void DirectExecute(const char* sql) - { - if (Trinity::IsFormatEmptyOrNull(sql)) - return; - - T* connection = GetFreeConnection(); - connection->Execute(sql); - connection->Unlock(); - } + void DirectExecute(char const* sql); //! Directly executes a one-way SQL operation in string format -with variable args-, that will block the calling thread until finished. //! This method should only be used for queries that are only executed once, e.g during startup. @@ -142,15 +106,7 @@ class DatabaseWorkerPool //! Directly executes a one-way SQL operation in prepared statement format, that will block the calling thread until finished. //! Statement must be prepared with the CONNECTION_SYNCH flag. - void DirectExecute(PreparedStatement* stmt) - { - T* connection = GetFreeConnection(); - connection->Execute(stmt); - connection->Unlock(); - - //! Delete proxy-class. Not needed anymore - delete stmt; - } + void DirectExecute(PreparedStatement* stmt); /** Synchronous query (with resultset) methods. @@ -158,7 +114,7 @@ class DatabaseWorkerPool //! Directly executes an SQL query in string format that will block the calling thread until finished. //! Returns reference counted auto pointer, no need for manual memory management in upper level code. - QueryResult Query(const char* sql, T* connection = nullptr); + QueryResult Query(char const* sql, T* connection = nullptr); //! Directly executes an SQL query in string format -with variable args- that will block the calling thread until finished. //! Returns reference counted auto pointer, no need for manual memory management in upper level code. @@ -193,7 +149,7 @@ class DatabaseWorkerPool //! Enqueues a query in string format that will set the value of the QueryResultFuture return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. - QueryCallback AsyncQuery(const char* sql); + QueryCallback AsyncQuery(char const* sql); //! Enqueues a query in prepared format that will set the value of the PreparedQueryResultFuture return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. @@ -211,10 +167,7 @@ class DatabaseWorkerPool */ //! Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0) - SQLTransaction BeginTransaction() - { - return SQLTransaction(new Transaction); - } + SQLTransaction BeginTransaction(); //! Enqueues a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations //! were appended to the transaction will be respected during execution. @@ -224,25 +177,13 @@ class DatabaseWorkerPool //! were appended to the transaction will be respected during execution. void DirectCommitTransaction(SQLTransaction& transaction); - //! Method used to execute prepared statements in a diverse context. + //! Method used to execute ad-hoc statements in a diverse context. //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. - void ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt) - { - if (!trans) - Execute(stmt); - else - trans->Append(stmt); - } + void ExecuteOrAppend(SQLTransaction& trans, char const* sql); - //! Method used to execute ad-hoc statements in a diverse context. + //! Method used to execute prepared statements in a diverse context. //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. - void ExecuteOrAppend(SQLTransaction& trans, const char* sql) - { - if (!trans) - Execute(sql); - else - trans->Append(sql); - } + void ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt); /** Other @@ -253,10 +194,7 @@ class DatabaseWorkerPool //! Automanaged (internally) pointer to a prepared statement object for usage in upper level code. //! Pointer is deleted in this->DirectExecute(PreparedStatement*), this->Query(PreparedStatement*) or PreparedStatementTask::~PreparedStatementTask. //! This object is not tied to the prepared statement on the MySQL context yet until execution. - PreparedStatement* GetPreparedStatement(PreparedStatementIndex index) - { - return new PreparedStatement(index, _preparedStatementSize[index]); - } + PreparedStatement* GetPreparedStatement(PreparedStatementIndex index); //! Apply escape string'ing for current collation. (utf8) void EscapeString(std::string& str); @@ -267,28 +205,15 @@ class DatabaseWorkerPool private: uint32 OpenConnections(InternalIndex type, uint8 numConnections); - unsigned long EscapeString(char *to, const char *from, unsigned long length) - { - if (!to || !from || !length) - return 0; + unsigned long EscapeString(char* to, char const* from, unsigned long length); - return mysql_real_escape_string( - _connections[IDX_SYNCH].front()->GetHandle(), to, from, length); - } - - void Enqueue(SQLOperation* op) - { - _queue->Push(op); - } + void Enqueue(SQLOperation* op); //! Gets a free connection in the synchronous connection pool. //! Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks. T* GetFreeConnection(); - char const* GetDatabaseName() const - { - return _connectionInfo->database.c_str(); - } + char const* GetDatabaseName() const; //! Queue shared by async worker threads. std::unique_ptr> _queue; diff --git a/src/server/database/Database/Field.cpp b/src/server/database/Database/Field.cpp index 29326287e63..fee9ff6467d 100644 --- a/src/server/database/Database/Field.cpp +++ b/src/server/database/Database/Field.cpp @@ -16,11 +16,12 @@ */ #include "Field.h" +#include "Log.h" Field::Field() { - data.value = NULL; - data.type = MYSQL_TYPE_NULL; + data.value = nullptr; + data.type = DatabaseFieldTypes::Null; data.length = 0; data.raw = false; } @@ -30,7 +31,236 @@ Field::~Field() CleanUp(); } -void Field::SetByteValue(void* newValue, enum_field_types newType, uint32 length) +uint8 Field::GetUInt8() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int8)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoul((char*)data.value, nullptr, 10)); +} + +int8 Field::GetInt8() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int8)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtol((char*)data.value, nullptr, 10)); +} + +uint16 Field::GetUInt16() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int16)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoul((char*)data.value, nullptr, 10)); +} + +int16 Field::GetInt16() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int16)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtol((char*)data.value, nullptr, 10)); +} + +uint32 Field::GetUInt32() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int32)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoul((char*)data.value, nullptr, 10)); +} + +int32 Field::GetInt32() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int32)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtol((char*)data.value, nullptr, 10)); +} + +uint64 Field::GetUInt64() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int64)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoull((char*)data.value, nullptr, 10)); +} + +int64 Field::GetInt64() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int64)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoll((char*)data.value, nullptr, 10)); +} + +float Field::GetFloat() const +{ + if (!data.value) + return 0.0f; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Float)) + { + TC_LOG_WARN("sql.sql", "Warning: GetFloat() on non-float field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0.0f; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(atof((char*)data.value)); +} + +double Field::GetDouble() const +{ + if (!data.value) + return 0.0f; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Double) && !IsType(DatabaseFieldTypes::Decimal)) + { + TC_LOG_WARN("sql.sql", "Warning: GetDouble() on non-double/non-decimal field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0.0f; + } +#endif + + if (data.raw && !IsType(DatabaseFieldTypes::Decimal)) + return *reinterpret_cast(data.value); + return static_cast(atof((char*)data.value)); +} + +char const* Field::GetCString() const +{ + if (!data.value) + return nullptr; + +#ifdef TRINITY_DEBUG + if (IsNumeric() && data.raw) + { + TC_LOG_WARN("sql.sql", "Error: GetCString() on numeric field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return nullptr; + } +#endif + return static_cast(data.value); +} + +std::string Field::GetString() const +{ + if (!data.value) + return ""; + + char const* string = GetCString(); + if (!string) + return ""; + + return std::string(string, data.length); +} + +std::vector Field::GetBinary() const +{ + std::vector result; + if (!data.value || !data.length) + return result; + + result.resize(data.length); + memcpy(result.data(), data.value, data.length); + return result; +} + +void Field::SetByteValue(void* newValue, DatabaseFieldTypes newType, uint32 length) { // This value stores raw bytes that have to be explicitly cast later data.value = newValue; @@ -39,7 +269,7 @@ void Field::SetByteValue(void* newValue, enum_field_types newType, uint32 length data.raw = true; } -void Field::SetStructuredValue(char* newValue, enum_field_types newType, uint32 length) +void Field::SetStructuredValue(char* newValue, DatabaseFieldTypes newType, uint32 length) { if (data.value) CleanUp(); @@ -56,3 +286,70 @@ void Field::SetStructuredValue(char* newValue, enum_field_types newType, uint32 data.type = newType; data.raw = false; } + +bool Field::IsType(DatabaseFieldTypes type) const +{ + return data.type == type; +} + +bool Field::IsNumeric() const +{ + return (data.type == DatabaseFieldTypes::Int8 || + data.type == DatabaseFieldTypes::Int16 || + data.type == DatabaseFieldTypes::Int32 || + data.type == DatabaseFieldTypes::Int64 || + data.type == DatabaseFieldTypes::Float || + data.type == DatabaseFieldTypes::Double); +} + +#ifdef TRINITY_DEBUG + +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include + +static char const* FieldTypeToString(enum_field_types type) +{ + switch (type) + { + case MYSQL_TYPE_BIT: return "BIT"; + case MYSQL_TYPE_BLOB: return "BLOB"; + case MYSQL_TYPE_DATE: return "DATE"; + case MYSQL_TYPE_DATETIME: return "DATETIME"; + case MYSQL_TYPE_NEWDECIMAL: return "NEWDECIMAL"; + case MYSQL_TYPE_DECIMAL: return "DECIMAL"; + case MYSQL_TYPE_DOUBLE: return "DOUBLE"; + case MYSQL_TYPE_ENUM: return "ENUM"; + case MYSQL_TYPE_FLOAT: return "FLOAT"; + case MYSQL_TYPE_GEOMETRY: return "GEOMETRY"; + case MYSQL_TYPE_INT24: return "INT24"; + case MYSQL_TYPE_LONG: return "LONG"; + case MYSQL_TYPE_LONGLONG: return "LONGLONG"; + case MYSQL_TYPE_LONG_BLOB: return "LONG_BLOB"; + case MYSQL_TYPE_MEDIUM_BLOB: return "MEDIUM_BLOB"; + case MYSQL_TYPE_NEWDATE: return "NEWDATE"; + case MYSQL_TYPE_NULL: return "NULL"; + case MYSQL_TYPE_SET: return "SET"; + case MYSQL_TYPE_SHORT: return "SHORT"; + case MYSQL_TYPE_STRING: return "STRING"; + case MYSQL_TYPE_TIME: return "TIME"; + case MYSQL_TYPE_TIMESTAMP: return "TIMESTAMP"; + case MYSQL_TYPE_TINY: return "TINY"; + case MYSQL_TYPE_TINY_BLOB: return "TINY_BLOB"; + case MYSQL_TYPE_VAR_STRING: return "VAR_STRING"; + case MYSQL_TYPE_YEAR: return "YEAR"; + default: return "-Unknown-"; + } +} + +void Field::SetMetadata(MYSQL_FIELD* field, uint32 fieldIndex) +{ + meta.TableName = field->org_table; + meta.TableAlias = field->table; + meta.Name = field->org_name; + meta.Alias = field->name; + meta.Type = FieldTypeToString(field->type); + meta.Index = fieldIndex; +} +#endif diff --git a/src/server/database/Database/Field.h b/src/server/database/Database/Field.h index 4daa447e481..f7f8397b761 100644 --- a/src/server/database/Database/Field.h +++ b/src/server/database/Database/Field.h @@ -18,10 +18,23 @@ #ifndef _FIELD_H #define _FIELD_H -#include "Common.h" -#include "Log.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include -#include +enum class DatabaseFieldTypes : uint8 +{ + Null, + Int8, + Int16, + Int32, + Int64, + Float, + Double, + Decimal, + Date, + Binary +}; /** @class Field @@ -67,238 +80,23 @@ class TC_DATABASE_API Field return GetUInt8() == 1 ? true : false; } - uint8 GetUInt8() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_TINY)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoul((char*)data.value, nullptr, 10)); - } - - int8 GetInt8() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_TINY)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtol((char*)data.value, NULL, 10)); - } - - uint16 GetUInt16() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_SHORT) && !IsType(MYSQL_TYPE_YEAR)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoul((char*)data.value, nullptr, 10)); - } - - int16 GetInt16() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_SHORT) && !IsType(MYSQL_TYPE_YEAR)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtol((char*)data.value, NULL, 10)); - } - - uint32 GetUInt32() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_INT24) && !IsType(MYSQL_TYPE_LONG)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoul((char*)data.value, nullptr, 10)); - } - - int32 GetInt32() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_INT24) && !IsType(MYSQL_TYPE_LONG)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtol((char*)data.value, NULL, 10)); - } - - uint64 GetUInt64() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_LONGLONG) && !IsType(MYSQL_TYPE_BIT)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoull((char*)data.value, nullptr, 10)); - } - - int64 GetInt64() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_LONGLONG) && !IsType(MYSQL_TYPE_BIT)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoll((char*)data.value, NULL, 10)); - } - - float GetFloat() const - { - if (!data.value) - return 0.0f; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_FLOAT)) - { - TC_LOG_WARN("sql.sql", "Warning: GetFloat() on non-float field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0.0f; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(atof((char*)data.value)); - } - - double GetDouble() const - { - if (!data.value) - return 0.0f; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_DOUBLE) && !IsType(MYSQL_TYPE_NEWDECIMAL)) - { - TC_LOG_WARN("sql.sql", "Warning: GetDouble() on non-double/non-decimal field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0.0f; - } - #endif - - if (data.raw && !IsType(MYSQL_TYPE_NEWDECIMAL)) - return *reinterpret_cast(data.value); - return static_cast(atof((char*)data.value)); - } - - char const* GetCString() const - { - if (!data.value) - return NULL; - - #ifdef TRINITY_DEBUG - if (IsNumeric()) - { - TC_LOG_WARN("sql.sql", "Error: GetCString() on numeric field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return NULL; - } - #endif - return static_cast(data.value); - } - - std::string GetString() const - { - if (!data.value) - return ""; - - char const* string = GetCString(); - if (!string) - return ""; - - return std::string(string, data.length); - } - - std::vector GetBinary() const - { - std::vector result; - if (!data.value || !data.length) - return result; - - result.resize(data.length); - memcpy(result.data(), data.value, data.length); - return result; - } + uint8 GetUInt8() const; + int8 GetInt8() const; + uint16 GetUInt16() const; + int16 GetInt16() const; + uint32 GetUInt32() const; + int32 GetInt32() const; + uint64 GetUInt64() const; + int64 GetInt64() const; + float GetFloat() const; + double GetDouble() const; + char const* GetCString() const; + std::string GetString() const; + std::vector GetBinary() const; bool IsNull() const { - return data.value == NULL; + return data.value == nullptr; } struct Metadata @@ -315,138 +113,32 @@ class TC_DATABASE_API Field #pragma pack(push, 1) struct { - uint32 length; // Length (prepared strings only) - void* value; // Actual data in memory - enum_field_types type; // Field type - bool raw; // Raw bytes? (Prepared statement or ad hoc) + uint32 length; // Length (prepared strings only) + void* value; // Actual data in memory + DatabaseFieldTypes type; // Field type + bool raw; // Raw bytes? (Prepared statement or ad hoc) } data; #pragma pack(pop) - void SetByteValue(void* newValue, enum_field_types newType, uint32 length); - void SetStructuredValue(char* newValue, enum_field_types newType, uint32 length); + void SetByteValue(void* newValue, DatabaseFieldTypes newType, uint32 length); + void SetStructuredValue(char* newValue, DatabaseFieldTypes newType, uint32 length); void CleanUp() { // Field does not own the data if fetched with prepared statement if (!data.raw) delete[] ((char*)data.value); - data.value = NULL; - } - - static uint32 SizeForType(MYSQL_FIELD* field) - { - switch (field->type) - { - case MYSQL_TYPE_NULL: - return 0; - case MYSQL_TYPE_TINY: - return 1; - case MYSQL_TYPE_YEAR: - case MYSQL_TYPE_SHORT: - return 2; - case MYSQL_TYPE_INT24: - case MYSQL_TYPE_LONG: - case MYSQL_TYPE_FLOAT: - return 4; - case MYSQL_TYPE_DOUBLE: - case MYSQL_TYPE_LONGLONG: - case MYSQL_TYPE_BIT: - return 8; - - case MYSQL_TYPE_TIMESTAMP: - case MYSQL_TYPE_DATE: - case MYSQL_TYPE_TIME: - case MYSQL_TYPE_DATETIME: - return sizeof(MYSQL_TIME); - - case MYSQL_TYPE_TINY_BLOB: - case MYSQL_TYPE_MEDIUM_BLOB: - case MYSQL_TYPE_LONG_BLOB: - case MYSQL_TYPE_BLOB: - case MYSQL_TYPE_STRING: - case MYSQL_TYPE_VAR_STRING: - return field->max_length + 1; - - case MYSQL_TYPE_DECIMAL: - case MYSQL_TYPE_NEWDECIMAL: - return 64; - - case MYSQL_TYPE_GEOMETRY: - /* - Following types are not sent over the wire: - MYSQL_TYPE_ENUM: - MYSQL_TYPE_SET: - */ - default: - TC_LOG_WARN("sql.sql", "SQL::SizeForType(): invalid field type %u", uint32(field->type)); - return 0; - } + data.value = nullptr; } - bool IsType(enum_field_types type) const - { - return data.type == type; - } + bool IsType(DatabaseFieldTypes type) const; - bool IsNumeric() const - { - return (data.type == MYSQL_TYPE_TINY || - data.type == MYSQL_TYPE_SHORT || - data.type == MYSQL_TYPE_INT24 || - data.type == MYSQL_TYPE_LONG || - data.type == MYSQL_TYPE_FLOAT || - data.type == MYSQL_TYPE_DOUBLE || - data.type == MYSQL_TYPE_LONGLONG ); - } + bool IsNumeric() const; private: #ifdef TRINITY_DEBUG - static char const* FieldTypeToString(enum_field_types type) - { - switch (type) - { - case MYSQL_TYPE_BIT: return "BIT"; - case MYSQL_TYPE_BLOB: return "BLOB"; - case MYSQL_TYPE_DATE: return "DATE"; - case MYSQL_TYPE_DATETIME: return "DATETIME"; - case MYSQL_TYPE_NEWDECIMAL: return "NEWDECIMAL"; - case MYSQL_TYPE_DECIMAL: return "DECIMAL"; - case MYSQL_TYPE_DOUBLE: return "DOUBLE"; - case MYSQL_TYPE_ENUM: return "ENUM"; - case MYSQL_TYPE_FLOAT: return "FLOAT"; - case MYSQL_TYPE_GEOMETRY: return "GEOMETRY"; - case MYSQL_TYPE_INT24: return "INT24"; - case MYSQL_TYPE_LONG: return "LONG"; - case MYSQL_TYPE_LONGLONG: return "LONGLONG"; - case MYSQL_TYPE_LONG_BLOB: return "LONG_BLOB"; - case MYSQL_TYPE_MEDIUM_BLOB: return "MEDIUM_BLOB"; - case MYSQL_TYPE_NEWDATE: return "NEWDATE"; - case MYSQL_TYPE_NULL: return "NULL"; - case MYSQL_TYPE_SET: return "SET"; - case MYSQL_TYPE_SHORT: return "SHORT"; - case MYSQL_TYPE_STRING: return "STRING"; - case MYSQL_TYPE_TIME: return "TIME"; - case MYSQL_TYPE_TIMESTAMP: return "TIMESTAMP"; - case MYSQL_TYPE_TINY: return "TINY"; - case MYSQL_TYPE_TINY_BLOB: return "TINY_BLOB"; - case MYSQL_TYPE_VAR_STRING: return "VAR_STRING"; - case MYSQL_TYPE_YEAR: return "YEAR"; - default: return "-Unknown-"; - } - } - - void SetMetadata(MYSQL_FIELD* field, uint32 fieldIndex) - { - meta.TableName = field->org_table; - meta.TableAlias = field->table; - meta.Name = field->org_name; - meta.Alias = field->name; - meta.Type = FieldTypeToString(field->type); - meta.Index = fieldIndex; - } - + void SetMetadata(MYSQL_FIELD* field, uint32 fieldIndex); Metadata meta; - #endif }; diff --git a/src/server/database/Database/Implementation/CharacterDatabase.cpp b/src/server/database/Database/Implementation/CharacterDatabase.cpp index ca845ccd5a9..398973a7e85 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.cpp +++ b/src/server/database/Database/Implementation/CharacterDatabase.cpp @@ -16,6 +16,7 @@ */ #include "CharacterDatabase.h" +#include "PreparedStatement.h" void CharacterDatabaseConnection::DoPrepareStatements() { @@ -610,3 +611,15 @@ void CharacterDatabaseConnection::DoPrepareStatements() // DeserterTracker PrepareStatement(CHAR_INS_DESERTER_TRACK, "INSERT INTO battleground_deserters (guid, type, datetime) VALUES (?, ?, NOW())", CONNECTION_ASYNC); } + +CharacterDatabaseConnection::CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +{ +} + +CharacterDatabaseConnection::CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) +{ +} + +CharacterDatabaseConnection::~CharacterDatabaseConnection() +{ +} diff --git a/src/server/database/Database/Implementation/CharacterDatabase.h b/src/server/database/Database/Implementation/CharacterDatabase.h index 28408886a8e..8f59059abc0 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.h +++ b/src/server/database/Database/Implementation/CharacterDatabase.h @@ -18,10 +18,9 @@ #ifndef _CHARACTERDATABASE_H #define _CHARACTERDATABASE_H -#include "DatabaseWorkerPool.h" #include "MySQLConnection.h" -enum CharacterDatabaseStatements +enum CharacterDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} @@ -536,13 +535,12 @@ public: typedef CharacterDatabaseStatements Statements; //- Constructors for sync and async connections - CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) { } - CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) { } + CharacterDatabaseConnection(MySQLConnectionInfo& connInfo); + CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); + ~CharacterDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; -typedef DatabaseWorkerPool CharacterDatabaseWorkerPool; - #endif diff --git a/src/server/database/Database/Implementation/LoginDatabase.cpp b/src/server/database/Database/Implementation/LoginDatabase.cpp index 360f0648254..3001e4c6df7 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.cpp +++ b/src/server/database/Database/Implementation/LoginDatabase.cpp @@ -16,6 +16,7 @@ */ #include "LoginDatabase.h" +#include "PreparedStatement.h" void LoginDatabaseConnection::DoPrepareStatements() { @@ -63,7 +64,7 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_INS_REALM_CHARACTERS, "INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (?, ?, ?)", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_SUM_REALM_CHARACTERS, "SELECT SUM(numchars) FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_INS_ACCOUNT, "INSERT INTO account(username, sha_pass_hash, reg_mail, email, joindate) VALUES(?, ?, ?, ?, NOW())", CONNECTION_SYNCH); - PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "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", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "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", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_EXPANSION, "UPDATE account SET expansion = ? WHERE id = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK, "UPDATE account SET locked = ? WHERE id = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK_CONTRY, "UPDATE account SET lock_country = ? WHERE id = ?", CONNECTION_ASYNC); @@ -90,7 +91,7 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME, "SELECT 1 FROM account WHERE username = ? AND sha_pass_hash = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_PINFO, "SELECT a.username, aa.gmlevel, a.email, a.reg_mail, a.last_ip, DATE_FORMAT(a.last_login, '%Y-%m-%d %T'), a.mutetime, a.mutereason, a.muteby, a.failed_logins, a.locked, a.OS FROM account a LEFT JOIN account_access aa ON (a.id = aa.id AND (aa.RealmID = ? OR aa.RealmID = -1)) WHERE a.id = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned WHERE id = ? AND active ORDER BY bandate ASC LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", CONNECTION_SYNCH); + PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id = aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_INFO, "SELECT a.username, a.last_ip, aa.gmlevel, a.expansion FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.id = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST, "SELECT 1 FROM account_access WHERE id = ? AND gmlevel > ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS, "SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", CONNECTION_SYNCH); @@ -119,3 +120,15 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_SEL_ACCOUNT_MUTE_INFO, "SELECT mutedate, mutetime, mutereason, mutedby FROM account_muted WHERE guid = ? ORDER BY mutedate ASC", CONNECTION_SYNCH); PrepareStatement(LOGIN_DEL_ACCOUNT_MUTED, "DELETE FROM account_muted WHERE guid = ?", CONNECTION_ASYNC); } + +LoginDatabaseConnection::LoginDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +{ +} + +LoginDatabaseConnection::LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) +{ +} + +LoginDatabaseConnection::~LoginDatabaseConnection() +{ +} diff --git a/src/server/database/Database/Implementation/LoginDatabase.h b/src/server/database/Database/Implementation/LoginDatabase.h index dcb77394b42..f199d81f55c 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.h +++ b/src/server/database/Database/Implementation/LoginDatabase.h @@ -18,10 +18,9 @@ #ifndef _LOGINDATABASE_H #define _LOGINDATABASE_H -#include "DatabaseWorkerPool.h" #include "MySQLConnection.h" -enum LoginDatabaseStatements +enum LoginDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} @@ -123,13 +122,12 @@ public: typedef LoginDatabaseStatements Statements; //- Constructors for sync and async connections - LoginDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) { } - LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) { } + LoginDatabaseConnection(MySQLConnectionInfo& connInfo); + LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); + ~LoginDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; -typedef DatabaseWorkerPool LoginDatabaseWorkerPool; - #endif diff --git a/src/server/database/Database/Implementation/WorldDatabase.cpp b/src/server/database/Database/Implementation/WorldDatabase.cpp index c4550144908..c64e7a9c2fc 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.cpp +++ b/src/server/database/Database/Implementation/WorldDatabase.cpp @@ -16,6 +16,7 @@ */ #include "WorldDatabase.h" +#include "PreparedStatement.h" void WorldDatabaseConnection::DoPrepareStatements() { @@ -92,3 +93,15 @@ void WorldDatabaseConnection::DoPrepareStatements() PrepareStatement(WORLD_UPD_CREATURE_ZONE_AREA_DATA, "UPDATE creature SET zoneId = ?, areaId = ? WHERE guid = ?", CONNECTION_ASYNC); PrepareStatement(WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA, "UPDATE gameobject SET zoneId = ?, areaId = ? WHERE guid = ?", CONNECTION_ASYNC); } + +WorldDatabaseConnection::WorldDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +{ +} + +WorldDatabaseConnection::WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) +{ +} + +WorldDatabaseConnection::~WorldDatabaseConnection() +{ +} diff --git a/src/server/database/Database/Implementation/WorldDatabase.h b/src/server/database/Database/Implementation/WorldDatabase.h index 069f5fe0555..b68f53bb173 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.h +++ b/src/server/database/Database/Implementation/WorldDatabase.h @@ -18,10 +18,9 @@ #ifndef _WORLDDATABASE_H #define _WORLDDATABASE_H -#include "DatabaseWorkerPool.h" #include "MySQLConnection.h" -enum WorldDatabaseStatements +enum WorldDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} @@ -109,13 +108,12 @@ public: typedef WorldDatabaseStatements Statements; //- Constructors for sync and async connections - WorldDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) { } - WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) { } + WorldDatabaseConnection(MySQLConnectionInfo& connInfo); + WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); + ~WorldDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; -typedef DatabaseWorkerPool WorldDatabaseWorkerPool; - #endif diff --git a/src/server/database/Database/MySQLConnection.cpp b/src/server/database/Database/MySQLConnection.cpp index 6e862ae6abe..75e6362f87f 100644 --- a/src/server/database/Database/MySQLConnection.cpp +++ b/src/server/database/Database/MySQLConnection.cpp @@ -15,29 +15,43 @@ * with this program. If not, see . */ - +#include "MySQLConnection.h" #include "Common.h" - -#ifdef _WIN32 - #include +#include "DatabaseWorker.h" +#include "Log.h" +#include "PreparedStatement.h" +#include "QueryResult.h" +#include "Timer.h" +#include "Transaction.h" +#include "Util.h" +#include +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include #endif #include -#include +#include -#include "MySQLConnection.h" -#include "QueryResult.h" -#include "SQLOperation.h" -#include "PreparedStatement.h" -#include "DatabaseWorker.h" -#include "Timer.h" -#include "Log.h" -#include "ProducerConsumerQueue.h" +MySQLConnectionInfo::MySQLConnectionInfo(std::string const& infoString) +{ + Tokenizer tokens(infoString, ';'); + + if (tokens.size() != 5) + return; + + uint8 i = 0; + + host.assign(tokens[i++]); + port_or_socket.assign(tokens[i++]); + user.assign(tokens[i++]); + password.assign(tokens[i++]); + database.assign(tokens[i++]); +} MySQLConnection::MySQLConnection(MySQLConnectionInfo& connInfo) : m_reconnecting(false), m_prepareError(false), -m_queue(NULL), -m_Mysql(NULL), +m_queue(nullptr), +m_Mysql(nullptr), m_connectionInfo(connInfo), m_connectionFlags(CONNECTION_SYNCH) { } @@ -45,7 +59,7 @@ MySQLConnection::MySQLConnection(ProducerConsumerQueue* queue, My m_reconnecting(false), m_prepareError(false), m_queue(queue), -m_Mysql(NULL), +m_Mysql(nullptr), m_connectionInfo(connInfo), m_connectionFlags(CONNECTION_ASYNC) { @@ -74,7 +88,7 @@ void MySQLConnection::Close() uint32 MySQLConnection::Open() { MYSQL *mysqlInit; - mysqlInit = mysql_init(NULL); + mysqlInit = mysql_init(nullptr); if (!mysqlInit) { TC_LOG_ERROR("sql.sql", "Could not initialize Mysql connection to database `%s`", m_connectionInfo.database.c_str()); @@ -152,7 +166,7 @@ bool MySQLConnection::PrepareStatements() return !m_prepareError; } -bool MySQLConnection::Execute(const char* sql) +bool MySQLConnection::Execute(char const* sql) { if (!m_Mysql) return false; @@ -281,18 +295,18 @@ bool MySQLConnection::_Query(PreparedStatement* stmt, MYSQL_RES **pResult, uint6 return true; } -ResultSet* MySQLConnection::Query(const char* sql) +ResultSet* MySQLConnection::Query(char const* sql) { if (!sql) - return NULL; + return nullptr; - MYSQL_RES *result = NULL; - MYSQL_FIELD *fields = NULL; + MYSQL_RES *result = nullptr; + MYSQL_FIELD *fields = nullptr; uint64 rowCount = 0; uint32 fieldCount = 0; if (!_Query(sql, &result, &fields, &rowCount, &fieldCount)) - return NULL; + return nullptr; return new ResultSet(result, fields, rowCount, fieldCount); } @@ -355,14 +369,13 @@ void MySQLConnection::CommitTransaction() int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) { - std::list const& queries = transaction->m_queries; + std::vector const& queries = transaction->m_queries; if (queries.empty()) return -1; BeginTransaction(); - std::list::const_iterator itr; - for (itr = queries.begin(); itr != queries.end(); ++itr) + for (auto itr = queries.begin(); itr != queries.end(); ++itr) { SQLElementData const& data = *itr; switch (itr->type) @@ -382,7 +395,7 @@ int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) break; case SQL_ELEMENT_RAW: { - const char* sql = data.element.query; + char const* sql = data.element.query; ASSERT(sql); if (!Execute(sql)) { @@ -405,6 +418,26 @@ int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) return 0; } +void MySQLConnection::Ping() +{ + mysql_ping(m_Mysql); +} + +uint32 MySQLConnection::GetLastError() +{ + return mysql_errno(m_Mysql); +} + +bool MySQLConnection::LockIfReady() +{ + return m_Mutex.try_lock(); +} + +void MySQLConnection::Unlock() +{ + m_Mutex.unlock(); +} + MySQLPreparedStatement* MySQLConnection::GetPreparedStatement(uint32 index) { ASSERT(index < m_stmts.size()); @@ -450,12 +483,12 @@ void MySQLConnection::PrepareStatement(uint32 index, std::string const& sql, Con PreparedResultSet* MySQLConnection::Query(PreparedStatement* stmt) { - MYSQL_RES *result = NULL; + MYSQL_RES *result = nullptr; uint64 rowCount = 0; uint32 fieldCount = 0; if (!_Query(stmt, &result, &rowCount, &fieldCount)) - return NULL; + return nullptr; if (mysql_more_results(m_Mysql)) { diff --git a/src/server/database/Database/MySQLConnection.h b/src/server/database/Database/MySQLConnection.h index 81b57261899..e8f42d49b34 100644 --- a/src/server/database/Database/MySQLConnection.h +++ b/src/server/database/Database/MySQLConnection.h @@ -15,18 +15,23 @@ * with this program. If not, see . */ -#include "DatabaseWorkerPool.h" -#include "Transaction.h" -#include "Util.h" -#include "ProducerConsumerQueue.h" - #ifndef _MYSQLCONNECTION_H #define _MYSQLCONNECTION_H +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include +#include +#include +#include +#include + +template +class ProducerConsumerQueue; + class DatabaseWorker; -class PreparedStatement; class MySQLPreparedStatement; -class PingOperation; +class SQLOperation; enum ConnectionFlags { @@ -37,21 +42,7 @@ enum ConnectionFlags struct TC_DATABASE_API MySQLConnectionInfo { - explicit MySQLConnectionInfo(std::string const& infoString) - { - Tokenizer tokens(infoString, ';'); - - if (tokens.size() != 5) - return; - - uint8 i = 0; - - host.assign(tokens[i++]); - port_or_socket.assign(tokens[i++]); - user.assign(tokens[i++]); - password.assign(tokens[i++]); - database.assign(tokens[i++]); - } + explicit MySQLConnectionInfo(std::string const& infoString); std::string user; std::string password; @@ -76,36 +67,29 @@ class TC_DATABASE_API MySQLConnection bool PrepareStatements(); public: - bool Execute(const char* sql); + bool Execute(char const* sql); bool Execute(PreparedStatement* stmt); - ResultSet* Query(const char* sql); + ResultSet* Query(char const* sql); PreparedResultSet* Query(PreparedStatement* stmt); - bool _Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount); - bool _Query(PreparedStatement* stmt, MYSQL_RES **pResult, uint64* pRowCount, uint32* pFieldCount); + bool _Query(char const* sql, MYSQL_RES** pResult, MYSQL_FIELD** pFields, uint64* pRowCount, uint32* pFieldCount); + bool _Query(PreparedStatement* stmt, MYSQL_RES** pResult, uint64* pRowCount, uint32* pFieldCount); void BeginTransaction(); void RollbackTransaction(); void CommitTransaction(); int ExecuteTransaction(SQLTransaction& transaction); - operator bool () const { return m_Mysql != NULL; } - void Ping() { mysql_ping(m_Mysql); } + void Ping(); - uint32 GetLastError() { return mysql_errno(m_Mysql); } + uint32 GetLastError(); protected: - bool LockIfReady() - { - /// Tries to acquire lock. If lock is acquired by another thread - /// the calling parent will just try another connection - return m_Mutex.try_lock(); - } - - void Unlock() - { - /// Called by parent databasepool. Will let other threads access this connection - m_Mutex.unlock(); - } + /// Tries to acquire lock. If lock is acquired by another thread + /// the calling parent will just try another connection + bool LockIfReady(); + + /// Called by parent databasepool. Will let other threads access this connection + void Unlock(); MYSQL* GetHandle() { return m_Mysql; } MySQLPreparedStatement* GetPreparedStatement(uint32 index); diff --git a/src/server/database/Database/MySQLThreading.cpp b/src/server/database/Database/MySQLThreading.cpp new file mode 100644 index 00000000000..3baa7877fe8 --- /dev/null +++ b/src/server/database/Database/MySQLThreading.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "MySQLThreading.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include + +void MySQL::Library_Init() +{ + mysql_library_init(-1, nullptr, nullptr); +} + +void MySQL::Library_End() +{ + mysql_library_end(); +} diff --git a/src/server/database/Database/MySQLThreading.h b/src/server/database/Database/MySQLThreading.h index 68a8c3ea7ed..4f8030f6555 100644 --- a/src/server/database/Database/MySQLThreading.h +++ b/src/server/database/Database/MySQLThreading.h @@ -18,20 +18,12 @@ #ifndef _MYSQLTHREADING_H #define _MYSQLTHREADING_H -#include "Log.h" +#include "Define.h" -class TC_DATABASE_API MySQL +namespace MySQL { - public: - static void Library_Init() - { - mysql_library_init(-1, NULL, NULL); - } - - static void Library_End() - { - mysql_library_end(); - } -}; + void TC_DATABASE_API Library_Init(); + void TC_DATABASE_API Library_End(); +} #endif diff --git a/src/server/database/Database/PreparedStatement.cpp b/src/server/database/Database/PreparedStatement.cpp index a46a022df48..137e9c05096 100644 --- a/src/server/database/Database/PreparedStatement.cpp +++ b/src/server/database/Database/PreparedStatement.cpp @@ -16,8 +16,15 @@ */ #include "PreparedStatement.h" +#include "Errors.h" #include "MySQLConnection.h" +#include "QueryResult.h" #include "Log.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include +#include PreparedStatement::PreparedStatement(uint32 index, uint8 capacity) : m_stmt(nullptr), m_index(index), statement_data(capacity) { } @@ -214,9 +221,9 @@ void MySQLPreparedStatement::ClearParameters() for (uint32 i=0; i < m_paramCount; ++i) { delete m_bind[i].length; - m_bind[i].length = NULL; + m_bind[i].length = nullptr; delete[] (char*) m_bind[i].buffer; - m_bind[i].buffer = NULL; + m_bind[i].buffer = nullptr; m_paramsSet[i] = false; } } @@ -227,6 +234,19 @@ static bool ParamenterIndexAssertFail(uint32 stmtIndex, uint8 index, uint32 para return false; } +static void SetParameterValue(MYSQL_BIND* param, enum_field_types type, void const* value, uint32 len, bool isUnsigned) +{ + param->buffer_type = type; + delete[] static_cast(param->buffer); + param->buffer = new char[len]; + param->buffer_length = 0; + param->is_null_value = 0; + param->length = nullptr; // Only != NULL for strings + param->is_unsigned = isUnsigned; + + memcpy(param->buffer, value, len); +} + //- Bind on mysql level void MySQLPreparedStatement::AssertValidIndex(uint8 index) { @@ -236,6 +256,20 @@ void MySQLPreparedStatement::AssertValidIndex(uint8 index) TC_LOG_ERROR("sql.sql", "[ERROR] Prepared Statement (id: %u) trying to bind value on already bound index (%u).", m_stmt->m_index, index); } +void MySQLPreparedStatement::setNull(const uint8 index) +{ + AssertValidIndex(index); + m_paramsSet[index] = true; + MYSQL_BIND* param = &m_bind[index]; + param->buffer_type = MYSQL_TYPE_NULL; + delete[] static_cast(param->buffer); + param->buffer = nullptr; + param->buffer_length = 0; + param->is_null_value = 1; + delete param->length; + param->length = nullptr; +} + void MySQLPreparedStatement::setBool(const uint8 index, const bool value) { setUInt8(index, value ? 1 : 0); @@ -246,7 +280,7 @@ void MySQLPreparedStatement::setUInt8(const uint8 index, const uint8 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_TINY, &value, sizeof(uint8), true); + SetParameterValue(param, MYSQL_TYPE_TINY, &value, sizeof(uint8), true); } void MySQLPreparedStatement::setUInt16(const uint8 index, const uint16 value) @@ -254,7 +288,7 @@ void MySQLPreparedStatement::setUInt16(const uint8 index, const uint16 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_SHORT, &value, sizeof(uint16), true); + SetParameterValue(param, MYSQL_TYPE_SHORT, &value, sizeof(uint16), true); } void MySQLPreparedStatement::setUInt32(const uint8 index, const uint32 value) @@ -262,7 +296,7 @@ void MySQLPreparedStatement::setUInt32(const uint8 index, const uint32 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONG, &value, sizeof(uint32), true); + SetParameterValue(param, MYSQL_TYPE_LONG, &value, sizeof(uint32), true); } void MySQLPreparedStatement::setUInt64(const uint8 index, const uint64 value) @@ -270,7 +304,7 @@ void MySQLPreparedStatement::setUInt64(const uint8 index, const uint64 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(uint64), true); + SetParameterValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(uint64), true); } void MySQLPreparedStatement::setInt8(const uint8 index, const int8 value) @@ -278,7 +312,7 @@ void MySQLPreparedStatement::setInt8(const uint8 index, const int8 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_TINY, &value, sizeof(int8), false); + SetParameterValue(param, MYSQL_TYPE_TINY, &value, sizeof(int8), false); } void MySQLPreparedStatement::setInt16(const uint8 index, const int16 value) @@ -286,7 +320,7 @@ void MySQLPreparedStatement::setInt16(const uint8 index, const int16 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_SHORT, &value, sizeof(int16), false); + SetParameterValue(param, MYSQL_TYPE_SHORT, &value, sizeof(int16), false); } void MySQLPreparedStatement::setInt32(const uint8 index, const int32 value) @@ -294,7 +328,7 @@ void MySQLPreparedStatement::setInt32(const uint8 index, const int32 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONG, &value, sizeof(int32), false); + SetParameterValue(param, MYSQL_TYPE_LONG, &value, sizeof(int32), false); } void MySQLPreparedStatement::setInt64(const uint8 index, const int64 value) @@ -302,7 +336,7 @@ void MySQLPreparedStatement::setInt64(const uint8 index, const int64 value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(int64), false); + SetParameterValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(int64), false); } void MySQLPreparedStatement::setFloat(const uint8 index, const float value) @@ -310,7 +344,7 @@ void MySQLPreparedStatement::setFloat(const uint8 index, const float value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_FLOAT, &value, sizeof(float), (value > 0.0f)); + SetParameterValue(param, MYSQL_TYPE_FLOAT, &value, sizeof(float), (value > 0.0f)); } void MySQLPreparedStatement::setDouble(const uint8 index, const double value) @@ -318,7 +352,7 @@ void MySQLPreparedStatement::setDouble(const uint8 index, const double value) AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_DOUBLE, &value, sizeof(double), (value > 0.0f)); + SetParameterValue(param, MYSQL_TYPE_DOUBLE, &value, sizeof(double), (value > 0.0f)); } void MySQLPreparedStatement::setBinary(const uint8 index, const std::vector& value, bool isString) @@ -328,7 +362,7 @@ void MySQLPreparedStatement::setBinary(const uint8 index, const std::vectorbuffer_type = MYSQL_TYPE_BLOB; - delete [] static_cast(param->buffer); + delete [] static_cast(param->buffer); param->buffer = new char[len]; param->buffer_length = len; param->is_null_value = 0; @@ -343,33 +377,6 @@ void MySQLPreparedStatement::setBinary(const uint8 index, const std::vectorbuffer, value.data(), len); } -void MySQLPreparedStatement::setNull(const uint8 index) -{ - AssertValidIndex(index); - m_paramsSet[index] = true; - MYSQL_BIND* param = &m_bind[index]; - param->buffer_type = MYSQL_TYPE_NULL; - delete [] static_cast(param->buffer); - param->buffer = NULL; - param->buffer_length = 0; - param->is_null_value = 1; - delete param->length; - param->length = NULL; -} - -void MySQLPreparedStatement::setValue(MYSQL_BIND* param, enum_field_types type, const void* value, uint32 len, bool isUnsigned) -{ - param->buffer_type = type; - delete [] static_cast(param->buffer); - param->buffer = new char[len]; - param->buffer_length = 0; - param->is_null_value = 0; - param->length = NULL; // Only != NULL for strings - param->is_unsigned = isUnsigned; - - memcpy(param->buffer, value, len); -} - std::string MySQLPreparedStatement::getQueryString() const { std::string queryString(m_queryString); @@ -458,7 +465,7 @@ bool PreparedStatementTask::Execute() if (!result || !result->GetRowCount()) { delete result; - m_result->set_value(PreparedQueryResult(NULL)); + m_result->set_value(PreparedQueryResult(nullptr)); return false; } m_result->set_value(PreparedQueryResult(result)); diff --git a/src/server/database/Database/PreparedStatement.h b/src/server/database/Database/PreparedStatement.h index 33ef04287cd..7d13e81c395 100644 --- a/src/server/database/Database/PreparedStatement.h +++ b/src/server/database/Database/PreparedStatement.h @@ -18,8 +18,10 @@ #ifndef _PREPAREDSTATEMENT_H #define _PREPAREDSTATEMENT_H -#include +#include "Define.h" #include "SQLOperation.h" +#include +#include #ifdef __APPLE__ #undef TYPE_BOOL @@ -81,6 +83,7 @@ class TC_DATABASE_API PreparedStatement PreparedStatement(uint32 index, uint8 capacity); ~PreparedStatement(); + void setNull(const uint8 index); void setBool(const uint8 index, const bool value); void setUInt8(const uint8 index, const uint8 value); void setUInt16(const uint8 index, const uint16 value); @@ -94,7 +97,6 @@ class TC_DATABASE_API PreparedStatement void setDouble(const uint8 index, const double value); void setString(const uint8 index, const std::string& value); void setBinary(const uint8 index, const std::vector& value); - void setNull(const uint8 index); protected: void BindParameters(MySQLPreparedStatement* stmt); @@ -146,9 +148,6 @@ class TC_DATABASE_API MySQLPreparedStatement void AssertValidIndex(uint8 index); std::string getQueryString() const; - private: - void setValue(MYSQL_BIND* param, enum_field_types type, const void* value, uint32 len, bool isUnsigned); - private: MYSQL_STMT* m_Mstmt; uint32 m_paramCount; @@ -160,9 +159,6 @@ class TC_DATABASE_API MySQLPreparedStatement MySQLPreparedStatement& operator=(MySQLPreparedStatement const& right) = delete; }; -typedef std::future PreparedQueryResultFuture; -typedef std::promise PreparedQueryResultPromise; - //- Lower-level class, enqueuable operation class TC_DATABASE_API PreparedStatementTask : public SQLOperation { diff --git a/src/server/database/Database/QueryCallback.cpp b/src/server/database/Database/QueryCallback.cpp index 2d89e08a956..18f72975935 100644 --- a/src/server/database/Database/QueryCallback.cpp +++ b/src/server/database/Database/QueryCallback.cpp @@ -16,6 +16,7 @@ */ #include "QueryCallback.h" +#include "Errors.h" template inline void Construct(T& t, Args&&... args) @@ -30,7 +31,7 @@ inline void Destroy(T& t) } template -void ConstructActiveMember(T* obj) +inline void ConstructActiveMember(T* obj) { if (!obj->_isPrepared) Construct(obj->_string); @@ -39,7 +40,7 @@ void ConstructActiveMember(T* obj) } template -void DestroyActiveMember(T* obj) +inline void DestroyActiveMember(T* obj) { if (!obj->_isPrepared) Destroy(obj->_string); @@ -48,7 +49,7 @@ void DestroyActiveMember(T* obj) } template -void MoveFrom(T* to, T&& from) +inline void MoveFrom(T* to, T&& from) { ASSERT(to->_isPrepared == from._isPrepared); @@ -199,7 +200,7 @@ QueryCallback::Status QueryCallback::InvokeIfReady() { if (_string.valid() && _string.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - std::future f(std::move(_string)); + QueryResultFuture f(std::move(_string)); std::function cb(std::move(callback._string)); cb(*this, f.get()); return checkStateAndReturnCompletion(); @@ -209,7 +210,7 @@ QueryCallback::Status QueryCallback::InvokeIfReady() { if (_prepared.valid() && _prepared.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - std::future f(std::move(_prepared)); + PreparedQueryResultFuture f(std::move(_prepared)); std::function cb(std::move(callback._prepared)); cb(*this, f.get()); return checkStateAndReturnCompletion(); diff --git a/src/server/database/Database/QueryCallback.h b/src/server/database/Database/QueryCallback.h index f9c93000da7..ebc1538b5e9 100644 --- a/src/server/database/Database/QueryCallback.h +++ b/src/server/database/Database/QueryCallback.h @@ -18,14 +18,19 @@ #ifndef _QUERY_CALLBACK_H #define _QUERY_CALLBACK_H -#include "QueryResult.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include #include +#include +#include +#include class TC_DATABASE_API QueryCallback { public: - explicit QueryCallback(std::future&& result); - explicit QueryCallback(std::future&& result); + explicit QueryCallback(QueryResultFuture&& result); + explicit QueryCallback(PreparedQueryResultFuture&& result); QueryCallback(QueryCallback&& right); QueryCallback& operator=(QueryCallback&& right); ~QueryCallback(); @@ -58,8 +63,8 @@ private: union { - std::future _string; - std::future _prepared; + QueryResultFuture _string; + PreparedQueryResultFuture _prepared; }; bool _isPrepared; diff --git a/src/server/database/Database/QueryHolder.cpp b/src/server/database/Database/QueryHolder.cpp index 6a8bb701a1f..7143671db75 100644 --- a/src/server/database/Database/QueryHolder.cpp +++ b/src/server/database/Database/QueryHolder.cpp @@ -19,26 +19,7 @@ #include "QueryHolder.h" #include "PreparedStatement.h" #include "Log.h" - -bool SQLQueryHolder::SetQuery(size_t index, const char *sql) -{ - if (m_queries.size() <= index) - { - TC_LOG_ERROR("sql.sql", "Query index (%u) out of range (size: %u) for query: %s", uint32(index), (uint32)m_queries.size(), sql); - return false; - } - - /// not executed yet, just stored (it's not called a holder for nothing) - SQLElementData element; - element.type = SQL_ELEMENT_RAW; - element.element.query = strdup(sql); - - SQLResultSetUnion result; - result.qresult = NULL; - - m_queries[index] = SQLResultPair(element, result); - return true; -} +#include "QueryResult.h" bool SQLQueryHolder::SetPreparedQuery(size_t index, PreparedStatement* stmt) { @@ -48,59 +29,17 @@ bool SQLQueryHolder::SetPreparedQuery(size_t index, PreparedStatement* stmt) return false; } - /// not executed yet, just stored (it's not called a holder for nothing) - SQLElementData element; - element.type = SQL_ELEMENT_PREPARED; - element.element.stmt = stmt; - - SQLResultSetUnion result; - result.presult = NULL; - - m_queries[index] = SQLResultPair(element, result); + m_queries[index].first = stmt; return true; } -QueryResult SQLQueryHolder::GetResult(size_t index) -{ - // Don't call to this function if the index is of an ad-hoc statement - if (index < m_queries.size()) - { - ResultSet* result = m_queries[index].second.qresult; - if (!result || !result->GetRowCount() || !result->NextRow()) - return QueryResult(NULL); - - return QueryResult(result); - } - else - return QueryResult(NULL); -} - PreparedQueryResult SQLQueryHolder::GetPreparedResult(size_t index) { // Don't call to this function if the index is of a prepared statement if (index < m_queries.size()) - { - PreparedResultSet* result = m_queries[index].second.presult; - if (!result || !result->GetRowCount()) - return PreparedQueryResult(NULL); - - return PreparedQueryResult(result); - } + return m_queries[index].second; else - return PreparedQueryResult(NULL); -} - -void SQLQueryHolder::SetResult(size_t index, ResultSet* result) -{ - if (result && !result->GetRowCount()) - { - delete result; - result = NULL; - } - - /// store the result in the holder - if (index < m_queries.size()) - m_queries[index].second.qresult = result; + return PreparedQueryResult(nullptr); } void SQLQueryHolder::SetPreparedResult(size_t index, PreparedResultSet* result) @@ -108,12 +47,12 @@ void SQLQueryHolder::SetPreparedResult(size_t index, PreparedResultSet* result) if (result && !result->GetRowCount()) { delete result; - result = NULL; + result = nullptr; } /// store the result in the holder if (index < m_queries.size()) - m_queries[index].second.presult = result; + m_queries[index].second = PreparedQueryResult(result); } SQLQueryHolder::~SQLQueryHolder() @@ -122,18 +61,7 @@ SQLQueryHolder::~SQLQueryHolder() { /// if the result was never used, free the resources /// results used already (getresult called) are expected to be deleted - if (SQLElementData* data = &m_queries[i].first) - { - switch (data->type) - { - case SQL_ELEMENT_RAW: - free((void*)(const_cast(data->element.query))); - break; - case SQL_ELEMENT_PREPARED: - delete data->element.stmt; - break; - } - } + delete m_queries[i].first; } } @@ -156,33 +84,10 @@ bool SQLQueryHolderTask::Execute() if (!m_holder) return false; - /// we can do this, we are friends - std::vector &queries = m_holder->m_queries; - - for (size_t i = 0; i < queries.size(); i++) - { - /// execute all queries in the holder and pass the results - if (SQLElementData* data = &queries[i].first) - { - switch (data->type) - { - case SQL_ELEMENT_RAW: - { - char const* sql = data->element.query; - if (sql) - m_holder->SetResult(i, m_conn->Query(sql)); - break; - } - case SQL_ELEMENT_PREPARED: - { - PreparedStatement* stmt = data->element.stmt; - if (stmt) - m_holder->SetPreparedResult(i, m_conn->Query(stmt)); - break; - } - } - } - } + /// execute all queries in the holder and pass the results + for (size_t i = 0; i < m_holder->m_queries.size(); ++i) + if (PreparedStatement* stmt = m_holder->m_queries[i].first) + m_holder->SetPreparedResult(i, m_conn->Query(stmt)); m_result.set_value(m_holder); return true; diff --git a/src/server/database/Database/QueryHolder.h b/src/server/database/Database/QueryHolder.h index c3ebb33068c..123765b01a5 100644 --- a/src/server/database/Database/QueryHolder.h +++ b/src/server/database/Database/QueryHolder.h @@ -18,34 +18,22 @@ #ifndef _QUERYHOLDER_H #define _QUERYHOLDER_H -#include +#include "SQLOperation.h" class TC_DATABASE_API SQLQueryHolder { friend class SQLQueryHolderTask; private: - typedef std::pair SQLResultPair; - std::vector m_queries; + std::vector> m_queries; public: SQLQueryHolder() { } virtual ~SQLQueryHolder(); - bool SetQuery(size_t index, const char* sql); - template - bool SetPQuery(size_t index, Format&& sql, Args&&... args) - { - return SetQuery(index, Trinity::StringFormat(std::forward(sql), std::forward(args)...).c_str()); - } bool SetPreparedQuery(size_t index, PreparedStatement* stmt); void SetSize(size_t size); - QueryResult GetResult(size_t index); PreparedQueryResult GetPreparedResult(size_t index); - void SetResult(size_t index, ResultSet* result); void SetPreparedResult(size_t index, PreparedResultSet* result); }; -typedef std::future QueryResultHolderFuture; -typedef std::promise QueryResultHolderPromise; - class TC_DATABASE_API SQLQueryHolderTask : public SQLOperation { private: diff --git a/src/server/database/Database/QueryResult.cpp b/src/server/database/Database/QueryResult.cpp index 7b6937e50b7..c2c05730ff1 100644 --- a/src/server/database/Database/QueryResult.cpp +++ b/src/server/database/Database/QueryResult.cpp @@ -16,8 +16,108 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" +#include "QueryResult.h" +#include "Errors.h" +#include "Field.h" #include "Log.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include + +static uint32 SizeForType(MYSQL_FIELD* field) +{ + switch (field->type) + { + case MYSQL_TYPE_NULL: + return 0; + case MYSQL_TYPE_TINY: + return 1; + case MYSQL_TYPE_YEAR: + case MYSQL_TYPE_SHORT: + return 2; + case MYSQL_TYPE_INT24: + case MYSQL_TYPE_LONG: + case MYSQL_TYPE_FLOAT: + return 4; + case MYSQL_TYPE_DOUBLE: + case MYSQL_TYPE_LONGLONG: + case MYSQL_TYPE_BIT: + return 8; + + case MYSQL_TYPE_TIMESTAMP: + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_TIME: + case MYSQL_TYPE_DATETIME: + return sizeof(MYSQL_TIME); + + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_VAR_STRING: + return field->max_length + 1; + + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_NEWDECIMAL: + return 64; + + case MYSQL_TYPE_GEOMETRY: + /* + Following types are not sent over the wire: + MYSQL_TYPE_ENUM: + MYSQL_TYPE_SET: + */ + default: + TC_LOG_WARN("sql.sql", "SQL::SizeForType(): invalid field type %u", uint32(field->type)); + return 0; + } +} + +DatabaseFieldTypes MysqlTypeToFieldType(enum_field_types type) +{ + switch (type) + { + case MYSQL_TYPE_NULL: + return DatabaseFieldTypes::Null; + case MYSQL_TYPE_TINY: + return DatabaseFieldTypes::Int8; + case MYSQL_TYPE_YEAR: + case MYSQL_TYPE_SHORT: + return DatabaseFieldTypes::Int16; + case MYSQL_TYPE_INT24: + case MYSQL_TYPE_LONG: + return DatabaseFieldTypes::Int32; + case MYSQL_TYPE_LONGLONG: + case MYSQL_TYPE_BIT: + return DatabaseFieldTypes::Int64; + case MYSQL_TYPE_FLOAT: + return DatabaseFieldTypes::Float; + case MYSQL_TYPE_DOUBLE: + return DatabaseFieldTypes::Double; + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_NEWDECIMAL: + return DatabaseFieldTypes::Decimal; + case MYSQL_TYPE_TIMESTAMP: + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_TIME: + case MYSQL_TYPE_DATETIME: + return DatabaseFieldTypes::Date; + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_VAR_STRING: + return DatabaseFieldTypes::Binary; + default: + TC_LOG_WARN("sql.sql", "MysqlTypeToFieldType(): invalid field type %u", uint32(type)); + break; + } + + return DatabaseFieldTypes::Null; +} ResultSet::ResultSet(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) : _rowCount(rowCount), @@ -36,11 +136,9 @@ PreparedResultSet::PreparedResultSet(MYSQL_STMT* stmt, MYSQL_RES *result, uint64 m_rowCount(rowCount), m_rowPosition(0), m_fieldCount(fieldCount), -m_rBind(NULL), +m_rBind(nullptr), m_stmt(stmt), -m_metadataResult(result), -m_isNull(NULL), -m_length(NULL) +m_metadataResult(result) { if (!m_metadataResult) return; @@ -52,8 +150,12 @@ m_length(NULL) } m_rBind = new MYSQL_BIND[m_fieldCount]; - m_isNull = new my_bool[m_fieldCount]; - m_length = new unsigned long[m_fieldCount]; + + //- for future readers wondering where the fuck this is freed - mysql_stmt_bind_result moves pointers to these + // from m_rBind to m_stmt->bind and it is later freed by the `if (m_stmt->bind_result_done)` block just above here + // MYSQL_STMT lifetime is equal to connection lifetime + my_bool* m_isNull = new my_bool[m_fieldCount]; + unsigned long* m_length = new unsigned long[m_fieldCount]; memset(m_isNull, 0, sizeof(my_bool) * m_fieldCount); memset(m_rBind, 0, sizeof(MYSQL_BIND) * m_fieldCount); @@ -76,14 +178,14 @@ m_length(NULL) std::size_t rowSize = 0; for (uint32 i = 0; i < m_fieldCount; ++i) { - uint32 size = Field::SizeForType(&field[i]); + uint32 size = SizeForType(&field[i]); rowSize += size; m_rBind[i].buffer_type = field[i].type; m_rBind[i].buffer_length = size; m_rBind[i].length = &m_length[i]; m_rBind[i].is_null = &m_isNull[i]; - m_rBind[i].error = NULL; + m_rBind[i].error = nullptr; m_rBind[i].is_unsigned = field[i].flags & UNSIGNED_FLAG; } @@ -137,7 +239,7 @@ m_length(NULL) m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetByteValue( buffer, - m_rBind[fIndex].buffer_type, + MysqlTypeToFieldType(m_rBind[fIndex].buffer_type), fetched_length); // move buffer pointer to next part @@ -147,7 +249,7 @@ m_length(NULL) { m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetByteValue( nullptr, - m_rBind[fIndex].buffer_type, + MysqlTypeToFieldType(m_rBind[fIndex].buffer_type), *m_rBind[fIndex].length); } @@ -196,7 +298,7 @@ bool ResultSet::NextRow() } for (uint32 i = 0; i < _fieldCount; i++) - _currentRow[i].SetStructuredValue(row[i], _fields[i].type, lengths[i]); + _currentRow[i].SetStructuredValue(row[i], MysqlTypeToFieldType(_fields[i].type), lengths[i]); return true; } @@ -227,16 +329,35 @@ void ResultSet::CleanUp() if (_currentRow) { delete [] _currentRow; - _currentRow = NULL; + _currentRow = nullptr; } if (_result) { mysql_free_result(_result); - _result = NULL; + _result = nullptr; } } +Field const& ResultSet::operator[](std::size_t index) const +{ + ASSERT(index < _fieldCount); + return _currentRow[index]; +} + +Field* PreparedResultSet::Fetch() const +{ + ASSERT(m_rowPosition < m_rowCount); + return const_cast(&m_rows[uint32(m_rowPosition) * m_fieldCount]); +} + +Field const& PreparedResultSet::operator[](std::size_t index) const +{ + ASSERT(m_rowPosition < m_rowCount); + ASSERT(index < m_fieldCount); + return m_rows[uint32(m_rowPosition) * m_fieldCount + index]; +} + void PreparedResultSet::CleanUp() { if (m_metadataResult) diff --git a/src/server/database/Database/QueryResult.h b/src/server/database/Database/QueryResult.h index 2df5d3a4f70..dcfe18765fc 100644 --- a/src/server/database/Database/QueryResult.h +++ b/src/server/database/Database/QueryResult.h @@ -19,13 +19,9 @@ #ifndef QUERYRESULT_H #define QUERYRESULT_H -#include -#include "Field.h" - -#ifdef _WIN32 - #include -#endif -#include +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include class TC_DATABASE_API ResultSet { @@ -38,11 +34,7 @@ class TC_DATABASE_API ResultSet uint32 GetFieldCount() const { return _fieldCount; } Field* Fetch() const { return _currentRow; } - const Field & operator [] (uint32 index) const - { - ASSERT(index < _fieldCount); - return _currentRow[index]; - } + Field const& operator[](std::size_t index) const; protected: uint64 _rowCount; @@ -58,8 +50,6 @@ class TC_DATABASE_API ResultSet ResultSet& operator=(ResultSet const& right) = delete; }; -typedef std::shared_ptr QueryResult; - class TC_DATABASE_API PreparedResultSet { public: @@ -70,18 +60,8 @@ class TC_DATABASE_API PreparedResultSet uint64 GetRowCount() const { return m_rowCount; } uint32 GetFieldCount() const { return m_fieldCount; } - Field* Fetch() const - { - ASSERT(m_rowPosition < m_rowCount); - return const_cast(&m_rows[uint32(m_rowPosition) * m_fieldCount]); - } - - Field const& operator[](uint32 index) const - { - ASSERT(m_rowPosition < m_rowCount); - ASSERT(index < m_fieldCount); - return m_rows[uint32(m_rowPosition) * m_fieldCount + index]; - } + Field* Fetch() const; + Field const& operator[](std::size_t index) const; protected: std::vector m_rows; @@ -94,9 +74,6 @@ class TC_DATABASE_API PreparedResultSet MYSQL_STMT* m_stmt; MYSQL_RES* m_metadataResult; ///< Field metadata, returned by mysql_stmt_result_metadata - my_bool* m_isNull; - unsigned long* m_length; - void CleanUp(); bool _NextRow(); @@ -104,7 +81,4 @@ class TC_DATABASE_API PreparedResultSet PreparedResultSet& operator=(PreparedResultSet const& right) = delete; }; -typedef std::shared_ptr PreparedQueryResult; - #endif - diff --git a/src/server/database/Database/SQLOperation.h b/src/server/database/Database/SQLOperation.h index 1e3000600c5..4e7e4c8eba5 100644 --- a/src/server/database/Database/SQLOperation.h +++ b/src/server/database/Database/SQLOperation.h @@ -18,16 +18,14 @@ #ifndef _SQLOPERATION_H #define _SQLOPERATION_H -#include "QueryResult.h" - -//- Forward declare (don't include header to prevent circular includes) -class PreparedStatement; +#include "Define.h" +#include "DatabaseEnvFwd.h" //- Union that holds element data union SQLElementUnion { PreparedStatement* stmt; - const char* query; + char const* query; }; //- Type specifier of our element data @@ -56,7 +54,7 @@ class MySQLConnection; class TC_DATABASE_API SQLOperation { public: - SQLOperation(): m_conn(NULL) { } + SQLOperation(): m_conn(nullptr) { } virtual ~SQLOperation() { } virtual int call() diff --git a/src/server/database/Database/Transaction.cpp b/src/server/database/Database/Transaction.cpp index 52f7062c78a..740e0455881 100644 --- a/src/server/database/Database/Transaction.cpp +++ b/src/server/database/Database/Transaction.cpp @@ -15,14 +15,15 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "Transaction.h" +#include "MySQLConnection.h" +#include "PreparedStatement.h" #include std::mutex TransactionTask::_deadlockLock; //- Append a raw ad-hoc query to the transaction -void Transaction::Append(const char* sql) +void Transaction::Append(char const* sql) { SQLElementData data; data.type = SQL_ELEMENT_RAW; @@ -45,9 +46,8 @@ void Transaction::Cleanup() if (_cleanedUp) return; - while (!m_queries.empty()) + for (SQLElementData const& data : m_queries) { - SQLElementData const &data = m_queries.front(); switch (data.type) { case SQL_ELEMENT_PREPARED: @@ -57,10 +57,9 @@ void Transaction::Cleanup() free((void*)(data.element.query)); break; } - - m_queries.pop_front(); } + m_queries.clear(); _cleanedUp = true; } diff --git a/src/server/database/Database/Transaction.h b/src/server/database/Database/Transaction.h index 6e6d68302f5..33e19531889 100644 --- a/src/server/database/Database/Transaction.h +++ b/src/server/database/Database/Transaction.h @@ -18,11 +18,12 @@ #ifndef _TRANSACTION_H #define _TRANSACTION_H +#include "Define.h" +#include "DatabaseEnvFwd.h" #include "SQLOperation.h" #include "StringFormat.h" - -//- Forward declare (don't include header to prevent circular includes) -class PreparedStatement; +#include +#include /*! Transactions, high level class. */ class TC_DATABASE_API Transaction @@ -38,24 +39,23 @@ class TC_DATABASE_API Transaction ~Transaction() { Cleanup(); } void Append(PreparedStatement* statement); - void Append(const char* sql); + void Append(char const* sql); template void PAppend(Format&& sql, Args&&... args) { Append(Trinity::StringFormat(std::forward(sql), std::forward(args)...).c_str()); } - size_t GetSize() const { return m_queries.size(); } + std::size_t GetSize() const { return m_queries.size(); } protected: void Cleanup(); - std::list m_queries; + std::vector m_queries; private: bool _cleanedUp; }; -typedef std::shared_ptr SQLTransaction; /*! Low level class*/ class TC_DATABASE_API TransactionTask : public SQLOperation diff --git a/src/server/database/Logging/AppenderDB.cpp b/src/server/database/Logging/AppenderDB.cpp index 1a6e11209e9..6420c42a8be 100644 --- a/src/server/database/Logging/AppenderDB.cpp +++ b/src/server/database/Logging/AppenderDB.cpp @@ -16,9 +16,11 @@ */ #include "AppenderDB.h" -#include "Database/DatabaseEnv.h" +#include "DatabaseEnv.h" +#include "LogMessage.h" +#include "PreparedStatement.h" -AppenderDB::AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags /*flags*/, ExtraAppenderArgs /*extraArgs*/) +AppenderDB::AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags /*flags*/, std::vector /*extraArgs*/) : Appender(id, name, level), realmId(0), enabled(false) { } AppenderDB::~AppenderDB() { } diff --git a/src/server/database/Logging/AppenderDB.h b/src/server/database/Logging/AppenderDB.h index 56f5fc13b94..3f53a33210a 100644 --- a/src/server/database/Logging/AppenderDB.h +++ b/src/server/database/Logging/AppenderDB.h @@ -25,7 +25,7 @@ class TC_DATABASE_API AppenderDB: public Appender public: typedef std::integral_constant::type TypeIndex; - AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); + AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs); ~AppenderDB(); void setRealmId(uint32 realmId) override; diff --git a/src/server/database/PrecompiledHeaders/databasePCH.cpp b/src/server/database/PrecompiledHeaders/databasePCH.cpp index f84a52be82a..8ac9a9d0bd3 100644 --- a/src/server/database/PrecompiledHeaders/databasePCH.cpp +++ b/src/server/database/PrecompiledHeaders/databasePCH.cpp @@ -1 +1,18 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "PrecompiledHeaders/databasePCH.h" diff --git a/src/server/database/PrecompiledHeaders/databasePCH.h b/src/server/database/PrecompiledHeaders/databasePCH.h index d524d52ade0..ee6a852f6e0 100644 --- a/src/server/database/PrecompiledHeaders/databasePCH.h +++ b/src/server/database/PrecompiledHeaders/databasePCH.h @@ -1,23 +1,32 @@ -#include "Config.h" -#include "Database/AdhocStatement.h" -#include "Database/DatabaseEnv.h" -#include "Database/DatabaseLoader.h" -#include "Database/DatabaseWorker.h" -#include "Database/DatabaseWorkerPool.h" -#include "Database/Field.h" -#include "Database/MySQLConnection.h" -#include "Database/MySQLThreading.h" -#include "Database/PreparedStatement.h" -#include "Database/QueryHolder.h" -#include "Database/QueryResult.h" -#include "Database/SQLOperation.h" -#include "Database/Transaction.h" -#include "Logging/Appender.h" -#include "Logging/AppenderConsole.h" -#include "Logging/AppenderDB.h" -#include "Logging/AppenderFile.h" -#include "Logging/Log.h" -#include "Logging/LogOperation.h" -#include "Logging/Logger.h" -#include "Updater/DBUpdater.h" -#include "Updater/UpdateFetcher.h" +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "Define.h" +#include "Errors.h" +#include "Field.h" +#include "Log.h" +#include "MySQLConnection.h" +#include "PreparedStatement.h" +#include "QueryResult.h" +#include "SQLOperation.h" +#include "Transaction.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include +#include +#include diff --git a/src/server/database/Updater/DBUpdater.cpp b/src/server/database/Updater/DBUpdater.cpp index 104533c1573..b82e0919dab 100644 --- a/src/server/database/Updater/DBUpdater.cpp +++ b/src/server/database/Updater/DBUpdater.cpp @@ -16,17 +16,18 @@ */ #include "DBUpdater.h" -#include "Log.h" -#include "GitRevision.h" -#include "UpdateFetcher.h" -#include "DatabaseLoader.h" -#include "Config.h" #include "BuiltInConfig.h" +#include "Config.h" +#include "DatabaseEnv.h" +#include "DatabaseLoader.h" +#include "GitRevision.h" +#include "Log.h" +#include "QueryResult.h" #include "StartProcess.h" - +#include "UpdateFetcher.h" +#include #include #include -#include std::string DBUpdaterUtil::GetCorrectedMySQLExecutable() { @@ -41,18 +42,12 @@ bool DBUpdaterUtil::CheckExecutable() boost::filesystem::path exe(GetCorrectedMySQLExecutable()); if (!exists(exe)) { - exe.clear(); - - if (auto path = Trinity::SearchExecutableInPath("mysql")) + exe = Trinity::SearchExecutableInPath("mysql"); + if (!exe.empty() && exists(exe)) { - exe = std::move(*path); - - if (!exe.empty() && exists(exe)) - { - // Correct the path to the cli - corrected_path() = absolute(exe).generic_string(); - return true; - } + // Correct the path to the cli + corrected_path() = absolute(exe).generic_string(); + return true; } TC_LOG_FATAL("sql.updates", "Didn't find any executable MySQL binary at \'%s\' or in path, correct the path in the *.conf (\"MySQLExecutable\").", @@ -313,7 +308,7 @@ bool DBUpdater::Populate(DatabaseWorkerPool& pool) template QueryResult DBUpdater::Retrieve(DatabaseWorkerPool& pool, std::string const& query) { - return pool.PQuery(query.c_str()); + return pool.Query(query.c_str()); } template diff --git a/src/server/database/Updater/DBUpdater.h b/src/server/database/Updater/DBUpdater.h index fdc00c9d6b6..8cea468e3cd 100644 --- a/src/server/database/Updater/DBUpdater.h +++ b/src/server/database/Updater/DBUpdater.h @@ -18,10 +18,20 @@ #ifndef DBUpdater_h__ #define DBUpdater_h__ -#include "DatabaseEnv.h" - +#include "Define.h" +#include "DatabaseEnvFwd.h" #include -#include + +template +class DatabaseWorkerPool; + +namespace boost +{ + namespace filesystem + { + class path; + } +} class TC_DATABASE_API UpdateException : public std::exception { @@ -41,19 +51,6 @@ enum BaseLocation LOCATION_DOWNLOAD }; -struct TC_DATABASE_API UpdateResult -{ - UpdateResult() - : updated(0), recent(0), archived(0) { } - - UpdateResult(size_t const updated_, size_t const recent_, size_t const archived_) - : updated(updated_), recent(recent_), archived(archived_) { } - - size_t updated; - size_t recent; - size_t archived; -}; - class DBUpdaterUtil { public: diff --git a/src/server/database/Updater/UpdateFetcher.cpp b/src/server/database/Updater/UpdateFetcher.cpp index 1da370ee7b9..4f12f6c09cd 100644 --- a/src/server/database/Updater/UpdateFetcher.cpp +++ b/src/server/database/Updater/UpdateFetcher.cpp @@ -16,28 +16,40 @@ */ #include "UpdateFetcher.h" +#include "Common.h" +#include "DBUpdater.h" +#include "Field.h" #include "Log.h" +#include "QueryResult.h" #include "Util.h" #include "SHA1.h" - +#include #include -#include -#include #include -#include -#include using namespace boost::filesystem; +struct UpdateFetcher::DirectoryEntry +{ + DirectoryEntry(Path const& path_, State state_) : path(path_), state(state_) { } + + Path const path; + State const state; +}; + UpdateFetcher::UpdateFetcher(Path const& sourceDirectory, std::function const& apply, std::function const& applyFile, std::function const& retrieve) : - _sourceDirectory(sourceDirectory), _apply(apply), _applyFile(applyFile), + _sourceDirectory(Trinity::make_unique(sourceDirectory)), _apply(apply), _applyFile(applyFile), _retrieve(retrieve) { } +UpdateFetcher::~UpdateFetcher() +{ +} + UpdateFetcher::LocaleFileStorage UpdateFetcher::GetFileList() const { LocaleFileStorage files; @@ -95,7 +107,7 @@ UpdateFetcher::DirectoryStorage UpdateFetcher::ReceiveIncludedDirectories() cons std::string path = fields[0].GetString(); if (path.substr(0, 1) == "$") - path = _sourceDirectory.generic_string() + path.substr(1); + path = _sourceDirectory->generic_string() + path.substr(1); Path const p(path); @@ -405,3 +417,8 @@ void UpdateFetcher::UpdateState(std::string const& name, State const state) cons // Update database _apply(update); } + +bool UpdateFetcher::PathCompare::operator()(LocaleFileEntry const& left, LocaleFileEntry const& right) const +{ + return left.first.filename().string() < right.first.filename().string(); +} diff --git a/src/server/database/Updater/UpdateFetcher.h b/src/server/database/Updater/UpdateFetcher.h index 51f735e797f..a905e21dcd3 100644 --- a/src/server/database/Updater/UpdateFetcher.h +++ b/src/server/database/Updater/UpdateFetcher.h @@ -18,13 +18,34 @@ #ifndef UpdateFetcher_h__ #define UpdateFetcher_h__ -#include - -#include +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include #include -#include +#include #include +namespace boost +{ + namespace filesystem + { + class path; + } +} + +struct TC_DATABASE_API UpdateResult +{ + UpdateResult() + : updated(0), recent(0), archived(0) { } + + UpdateResult(size_t const updated_, size_t const recent_, size_t const archived_) + : updated(updated_), recent(recent_), archived(archived_) { } + + size_t updated; + size_t recent; + size_t archived; +}; + class TC_DATABASE_API UpdateFetcher { typedef boost::filesystem::path Path; @@ -34,6 +55,7 @@ public: std::function const& apply, std::function const& applyFile, std::function const& retrieve); + ~UpdateFetcher(); UpdateResult Update(bool const redundancyChecks, bool const allowRehash, bool const archivedRedundancy, int32 const cleanDeadReferencesMaxCount) const; @@ -80,23 +102,13 @@ private: } }; - struct DirectoryEntry - { - DirectoryEntry(Path const& path_, State state_) : path(path_), state(state_) { } - - Path const path; - - State const state; - }; + struct DirectoryEntry; typedef std::pair LocaleFileEntry; struct PathCompare { - inline bool operator() (LocaleFileEntry const& left, LocaleFileEntry const& right) const - { - return left.first.filename().string() < right.first.filename().string(); - } + bool operator()(LocaleFileEntry const& left, LocaleFileEntry const& right) const; }; typedef std::set LocaleFileStorage; @@ -121,7 +133,7 @@ private: void UpdateState(std::string const& name, State const state) const; - Path const _sourceDirectory; + std::unique_ptr const _sourceDirectory; std::function const _apply; std::function const _applyFile; diff --git a/src/server/game/AI/CoreAI/CombatAI.cpp b/src/server/game/AI/CoreAI/CombatAI.cpp index 86858de04dd..f7143591060 100644 --- a/src/server/game/AI/CoreAI/CombatAI.cpp +++ b/src/server/game/AI/CoreAI/CombatAI.cpp @@ -17,11 +17,16 @@ */ #include "CombatAI.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "Vehicle.h" +#include "ConditionMgr.h" +#include "Creature.h" +#include "CreatureAIImpl.h" +#include "Log.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" #include "Player.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "Vehicle.h" ///////////////// // AggressorAI @@ -232,7 +237,7 @@ TurretAI::TurretAI(Creature* c) : CreatureAI(c) me->m_SightDistance = me->m_CombatDistance; } -bool TurretAI::CanAIAttack(const Unit* /*who*/) const +bool TurretAI::CanAIAttack(Unit const* /*who*/) const { /// @todo use one function to replace it if (!me->IsWithinCombatRange(me->GetVictim(), me->m_CombatDistance) diff --git a/src/server/game/AI/CoreAI/CombatAI.h b/src/server/game/AI/CoreAI/CombatAI.h index 86e95e0b209..872d02b1531 100644 --- a/src/server/game/AI/CoreAI/CombatAI.h +++ b/src/server/game/AI/CoreAI/CombatAI.h @@ -20,8 +20,6 @@ #define TRINITY_COMBATAI_H #include "CreatureAI.h" -#include "CreatureAIImpl.h" -#include "ConditionMgr.h" class Creature; diff --git a/src/server/game/AI/CoreAI/GameObjectAI.cpp b/src/server/game/AI/CoreAI/GameObjectAI.cpp index 204f4c16275..4d511cdc353 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.cpp +++ b/src/server/game/AI/CoreAI/GameObjectAI.cpp @@ -17,5 +17,16 @@ */ #include "GameObjectAI.h" +#include "CreatureAI.h" + +int32 GameObjectAI::Permissible(GameObject const* /*go*/) +{ + return PERMIT_BASE_NO; +} NullGameObjectAI::NullGameObjectAI(GameObject* g) : GameObjectAI(g) { } + +int32 NullGameObjectAI::Permissible(GameObject const* /*go*/) +{ + return PERMIT_BASE_IDLE; +} diff --git a/src/server/game/AI/CoreAI/GameObjectAI.h b/src/server/game/AI/CoreAI/GameObjectAI.h index 84ead51cc91..80ab11d6792 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.h +++ b/src/server/game/AI/CoreAI/GameObjectAI.h @@ -20,11 +20,11 @@ #define TRINITY_GAMEOBJECTAI_H #include "Define.h" -#include -#include "Object.h" #include "QuestDef.h" -#include "GameObject.h" -#include "CreatureAI.h" + +class GameObject; +class Unit; +class SpellInfo; class TC_GAME_API GameObjectAI { @@ -45,7 +45,7 @@ class TC_GAME_API GameObjectAI virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) { } virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; } - static int32 Permissible(GameObject const* /*go*/) { return PERMIT_BASE_NO; } + static int32 Permissible(GameObject const* go); // Called when a player opens a gossip dialog with the gameobject. virtual bool GossipHello(Player* /*player*/) { return false; } @@ -81,7 +81,7 @@ class TC_GAME_API GameObjectAI virtual void OnLootStateChanged(uint32 /*state*/, Unit* /*unit*/) { } virtual void OnStateChanged(uint32 /*state*/) { } virtual void EventInform(uint32 /*eventId*/) { } - virtual void SpellHit(Unit* /*unit*/, const SpellInfo* /*spellInfo*/) { } + virtual void SpellHit(Unit* /*unit*/, SpellInfo const* /*spellInfo*/) { } }; class TC_GAME_API NullGameObjectAI : public GameObjectAI @@ -91,6 +91,6 @@ class TC_GAME_API NullGameObjectAI : public GameObjectAI void UpdateAI(uint32 /*diff*/) override { } - static int32 Permissible(GameObject const* /*go*/) { return PERMIT_BASE_IDLE; } + static int32 Permissible(GameObject const* go); }; #endif diff --git a/src/server/game/AI/CoreAI/GuardAI.cpp b/src/server/game/AI/CoreAI/GuardAI.cpp index 1da03952dc9..f216059e492 100644 --- a/src/server/game/AI/CoreAI/GuardAI.cpp +++ b/src/server/game/AI/CoreAI/GuardAI.cpp @@ -17,9 +17,16 @@ */ #include "GuardAI.h" +#include "Creature.h" #include "Errors.h" +#include "Log.h" +#include "MotionMaster.h" #include "Player.h" +GuardAI::GuardAI(Creature* creature) : ScriptedAI(creature) +{ +} + int32 GuardAI::Permissible(Creature const* creature) { if (creature->IsGuard()) @@ -28,7 +35,13 @@ int32 GuardAI::Permissible(Creature const* creature) return PERMIT_BASE_NO; } -GuardAI::GuardAI(Creature* creature) : ScriptedAI(creature) { } +void GuardAI::UpdateAI(uint32 /*diff*/) +{ + if (!UpdateVictim()) + return; + + DoMeleeAttackIfReady(); +} bool GuardAI::CanSeeAlways(WorldObject const* obj) { diff --git a/src/server/game/AI/CoreAI/GuardAI.h b/src/server/game/AI/CoreAI/GuardAI.h index 0b0ac1f0983..77b83340c91 100644 --- a/src/server/game/AI/CoreAI/GuardAI.h +++ b/src/server/game/AI/CoreAI/GuardAI.h @@ -29,6 +29,7 @@ class TC_GAME_API GuardAI : public ScriptedAI explicit GuardAI(Creature* creature); static int32 Permissible(Creature const* creature); + void UpdateAI(uint32 diff) override; bool CanSeeAlways(WorldObject const* obj) override; void EnterEvadeMode(EvadeReason /*why*/) override; diff --git a/src/server/game/AI/CoreAI/PetAI.cpp b/src/server/game/AI/CoreAI/PetAI.cpp index f27f9a0adb9..1fad18a2713 100644 --- a/src/server/game/AI/CoreAI/PetAI.cpp +++ b/src/server/game/AI/CoreAI/PetAI.cpp @@ -17,17 +17,19 @@ */ #include "PetAI.h" +#include "Creature.h" #include "Errors.h" +#include "Group.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Pet.h" #include "Player.h" #include "Spell.h" -#include "ObjectAccessor.h" #include "SpellHistory.h" +#include "SpellInfo.h" #include "SpellMgr.h" -#include "Creature.h" #include "Util.h" -#include "Group.h" -#include "SpellInfo.h" int32 PetAI::Permissible(Creature const* creature) { @@ -264,7 +266,7 @@ void PetAI::UpdateAllies() if (!owner) return; - Group* group = NULL; + Group* group = nullptr; if (Player* player = owner->ToPlayer()) group = player->GetGroup(); @@ -280,7 +282,7 @@ void PetAI::UpdateAllies() m_AllySet.insert(me->GetGUID()); if (group) //add group { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* Target = itr->GetSource(); if (!Target || !Target->IsInMap(owner) || !group->SameSubGroup(owner->ToPlayer(), Target)) @@ -389,7 +391,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const // Passive pets don't do next target selection if (me->HasReactState(REACT_PASSIVE)) - return NULL; + return nullptr; // Check pet attackers first so we don't drag a bunch of targets to the owner if (Unit* myAttacker = me->getAttackerForHelper()) @@ -398,7 +400,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const // Not sure why we wouldn't have an owner but just in case... if (!me->GetCharmerOrOwner()) - return NULL; + return nullptr; // Check owner attackers if (Unit* ownerAttacker = me->GetCharmerOrOwner()->getAttackerForHelper()) @@ -421,7 +423,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const } // Default - no valid targets - return NULL; + return nullptr; } void PetAI::HandleReturnMovement() @@ -568,7 +570,7 @@ bool PetAI::CanAttack(Unit* target) if (me->GetVictim() && me->GetVictim() != target) { // Check if our owner selected this target and clicked "attack" - Unit* ownerTarget = NULL; + Unit* ownerTarget = nullptr; if (Player* owner = me->GetCharmerOrOwner()->ToPlayer()) ownerTarget = owner->GetSelectedUnit(); else diff --git a/src/server/game/AI/CoreAI/ReactorAI.cpp b/src/server/game/AI/CoreAI/ReactorAI.cpp index 8ad251776b6..0f2e7437104 100644 --- a/src/server/game/AI/CoreAI/ReactorAI.cpp +++ b/src/server/game/AI/CoreAI/ReactorAI.cpp @@ -16,8 +16,8 @@ * with this program. If not, see . */ -#include "ByteBuffer.h" #include "ReactorAI.h" +#include "Creature.h" int32 ReactorAI::Permissible(Creature const* creature) { diff --git a/src/server/game/AI/CoreAI/ReactorAI.h b/src/server/game/AI/CoreAI/ReactorAI.h index 412849a955b..db1f60fc263 100644 --- a/src/server/game/AI/CoreAI/ReactorAI.h +++ b/src/server/game/AI/CoreAI/ReactorAI.h @@ -21,8 +21,6 @@ #include "CreatureAI.h" -class Unit; - class TC_GAME_API ReactorAI : public CreatureAI { public: diff --git a/src/server/game/AI/CoreAI/TotemAI.cpp b/src/server/game/AI/CoreAI/TotemAI.cpp index a44c4532e60..da484e20983 100644 --- a/src/server/game/AI/CoreAI/TotemAI.cpp +++ b/src/server/game/AI/CoreAI/TotemAI.cpp @@ -64,14 +64,14 @@ void TotemAI::UpdateAI(uint32 /*diff*/) // SPELLMOD_RANGE not applied in this place just because not existence range mods for attacking totems // pointer to appropriate target if found any - Unit* victim = i_victimGuid ? ObjectAccessor::GetUnit(*me, i_victimGuid) : NULL; + Unit* victim = i_victimGuid ? ObjectAccessor::GetUnit(*me, i_victimGuid) : nullptr; // Search victim if no, not attackable, or out of range, or friendly (possible in case duel end) if (!victim || !victim->isTargetableForAttack() || !me->IsWithinDistInMap(victim, max_range) || me->IsFriendlyTo(victim) || !me->CanSeeOrDetect(victim)) { - victim = NULL; + victim = nullptr; Trinity::NearestAttackableUnitInObjectRangeCheck u_check(me, me, max_range); Trinity::UnitLastSearcher checker(me, victim, u_check); Cell::VisitAllObjects(me, checker, max_range); diff --git a/src/server/game/AI/CoreAI/UnitAI.cpp b/src/server/game/AI/CoreAI/UnitAI.cpp index 055abc99d96..9f13f7901bc 100644 --- a/src/server/game/AI/CoreAI/UnitAI.cpp +++ b/src/server/game/AI/CoreAI/UnitAI.cpp @@ -17,14 +17,15 @@ */ #include "UnitAI.h" -#include "Player.h" #include "Creature.h" -#include "SpellAuras.h" +#include "CreatureAIImpl.h" +#include "MotionMaster.h" +#include "Player.h" +#include "Spell.h" #include "SpellAuraEffects.h" -#include "SpellMgr.h" +#include "SpellAuras.h" #include "SpellInfo.h" -#include "Spell.h" -#include "CreatureAIImpl.h" +#include "SpellMgr.h" void UnitAI::AttackStart(Unit* victim) { @@ -40,6 +41,12 @@ void UnitAI::AttackStart(Unit* victim) } } +void UnitAI::InitializeAI() +{ + if (!me->isDead()) + Reset(); +} + void UnitAI::AttackStartCaster(Unit* victim, float dist) { if (victim && me->Attack(victim, false)) @@ -112,37 +119,9 @@ float UnitAI::DoGetSpellMaxRange(uint32 spellId, bool positive) return spellInfo ? spellInfo->GetMaxRange(positive) : 0; } -void UnitAI::DoAddAuraToAllHostilePlayers(uint32 spellid) -{ - if (me->IsInCombat()) - { - ThreatContainer::StorageType threatlist = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - { - if (Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid())) - if (unit->GetTypeId() == TYPEID_PLAYER) - me->AddAura(spellid, unit); - } - } -} - -void UnitAI::DoCastToAllHostilePlayers(uint32 spellid, bool triggered) -{ - if (me->IsInCombat()) - { - ThreatContainer::StorageType threatlist = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - { - if (Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid())) - if (unit->GetTypeId() == TYPEID_PLAYER) - me->CastSpell(unit, spellid, triggered); - } - } -} - void UnitAI::DoCast(uint32 spellId) { - Unit* target = NULL; + Unit* target = nullptr; switch (AISpellInfo[spellId].target) { @@ -211,7 +190,12 @@ void UnitAI::DoCastAOE(uint32 spellId, bool triggered) if (!triggered && me->HasUnitState(UNIT_STATE_CASTING)) return; - me->CastSpell((Unit*)NULL, spellId, triggered); + me->CastSpell((Unit*)nullptr, spellId, triggered); +} + +uint32 UnitAI::GetDialogStatus(Player* /*player*/) +{ + return DIALOG_STATUS_SCRIPTED_NO_STATUS; } #define UPDATE_TARGET(a) {if (AIInfo->targettarget=a;} @@ -221,11 +205,9 @@ void UnitAI::FillAISpellInfo() AISpellInfo = new AISpellInfoType[sSpellMgr->GetSpellInfoStoreSize()]; AISpellInfoType* AIInfo = AISpellInfo; - const SpellInfo* spellInfo; - for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i, ++AIInfo) { - spellInfo = sSpellMgr->GetSpellInfo(i); + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(i); if (!spellInfo) continue; @@ -267,6 +249,45 @@ void UnitAI::FillAISpellInfo() } } +ThreatManager& UnitAI::GetThreatManager() +{ + return me->getThreatManager(); +} + +bool DefaultTargetSelector::operator()(Unit const* target) const +{ + if (!me) + return false; + + if (!target) + return false; + + if (m_playerOnly && (target->GetTypeId() != TYPEID_PLAYER)) + return false; + + if (m_dist > 0.0f && !me->IsWithinCombatRange(target, m_dist)) + return false; + + if (m_dist < 0.0f && me->IsWithinCombatRange(target, -m_dist)) + return false; + + if (m_aura) + { + if (m_aura > 0) + { + if (!target->HasAura(m_aura)) + return false; + } + else + { + if (target->HasAura(-m_aura)) + return false; + } + } + + return true; +} + SpellTargetSelector::SpellTargetSelector(Unit* caster, uint32 spellId) : _caster(caster), _spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(spellId), caster)) { @@ -384,3 +405,8 @@ bool FarthestTargetSelector::operator()(Unit const* target) const return true; } + +void SortByDistanceTo(Unit* reference, std::list& targets) +{ + targets.sort(Trinity::ObjectDistanceOrderPred(reference)); +} diff --git a/src/server/game/AI/CoreAI/UnitAI.h b/src/server/game/AI/CoreAI/UnitAI.h index 0e0d2200280..d164b9fe6d5 100644 --- a/src/server/game/AI/CoreAI/UnitAI.h +++ b/src/server/game/AI/CoreAI/UnitAI.h @@ -19,16 +19,29 @@ #ifndef TRINITY_UNITAI_H #define TRINITY_UNITAI_H -#include "Define.h" -#include "Unit.h" #include "Containers.h" #include "EventMap.h" -#include "QuestDef.h" -#include +#include "ObjectGuid.h" +#include "ThreatManager.h" + +#define CAST_AI(a, b) (dynamic_cast(b)) +#define ENSURE_AI(a,b) (EnsureAI(b)) + +template +T* EnsureAI(U* ai) +{ + T* cast_ai = dynamic_cast(ai); + ASSERT(cast_ai); + return cast_ai; +}; class Player; class Quest; +class SpellInfo; +class Unit; struct AISpellInfoType; +enum DamageEffectType : uint8; +enum SpellEffIndex : uint8; //Selection method used by SelectTarget enum SelectAggroTarget @@ -41,9 +54,9 @@ enum SelectAggroTarget }; // default predicate function to select target based on distance, player and/or aura criteria -struct TC_GAME_API DefaultTargetSelector : public std::unary_function +struct TC_GAME_API DefaultTargetSelector { - const Unit* me; + Unit const* me; float m_dist; bool m_playerOnly; int32 m_aura; @@ -54,44 +67,12 @@ struct TC_GAME_API DefaultTargetSelector : public std::unary_function 0: the target shall have the aura, if < 0, the target shall NOT have the aura DefaultTargetSelector(Unit const* unit, float dist, bool playerOnly, int32 aura) : me(unit), m_dist(dist), m_playerOnly(playerOnly), m_aura(aura) { } - bool operator()(Unit const* target) const - { - if (!me) - return false; - - if (!target) - return false; - - if (m_playerOnly && (target->GetTypeId() != TYPEID_PLAYER)) - return false; - - if (m_dist > 0.0f && !me->IsWithinCombatRange(target, m_dist)) - return false; - - if (m_dist < 0.0f && me->IsWithinCombatRange(target, -m_dist)) - return false; - - if (m_aura) - { - if (m_aura > 0) - { - if (!target->HasAura(m_aura)) - return false; - } - else - { - if (target->HasAura(-m_aura)) - return false; - } - } - - return true; - } + bool operator()(Unit const* target) const; }; // Target selector for spell casts checking range, auras and attributes /// @todo Add more checks from Spell::CheckCast -struct TC_GAME_API SpellTargetSelector : public std::unary_function +struct TC_GAME_API SpellTargetSelector { public: SpellTargetSelector(Unit* caster, uint32 spellId); @@ -105,7 +86,7 @@ struct TC_GAME_API SpellTargetSelector : public std::unary_function // Very simple target selector, will just skip main target // NOTE: When passing to UnitAI::SelectTarget remember to use 0 as position for random selection // because tank will not be in the temporary list -struct TC_GAME_API NonTankTargetSelector : public std::unary_function +struct TC_GAME_API NonTankTargetSelector { public: NonTankTargetSelector(Unit* source, bool playerOnly = true) : _source(source), _playerOnly(playerOnly) { } @@ -137,12 +118,14 @@ struct TC_GAME_API FarthestTargetSelector bool operator()(Unit const* target) const; private: - const Unit* _me; + Unit const* _me; float _dist; bool _playerOnly; bool _inLos; }; +TC_GAME_API void SortByDistanceTo(Unit* reference, std::list& targets); + class TC_GAME_API UnitAI { protected: @@ -155,7 +138,7 @@ class TC_GAME_API UnitAI virtual void AttackStart(Unit* /*target*/); virtual void UpdateAI(uint32 diff) = 0; - virtual void InitializeAI() { if (!me->isDead()) Reset(); } + virtual void InitializeAI(); virtual void Reset() { } @@ -172,15 +155,16 @@ class TC_GAME_API UnitAI Unit* SelectTarget(SelectAggroTarget targetType, uint32 position = 0, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); // Select the targets satisfying the predicate. // predicate shall extend std::unary_function - template Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) + template + Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) { - ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = GetThreatManager().getThreatList(); if (position >= threatlist.size()) return nullptr; std::list targetList; Unit* currentVictim = nullptr; - if (auto currentVictimReference = me->getThreatManager().getCurrentVictim()) + if (auto currentVictimReference = GetThreatManager().getCurrentVictim()) { currentVictim = currentVictimReference->getTarget(); @@ -189,42 +173,38 @@ class TC_GAME_API UnitAI targetList.push_back(currentVictim); } - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) + for (HostileReference* hostileRef : threatlist) { - if (currentVictim != nullptr && (*itr)->getTarget() != currentVictim && predicate((*itr)->getTarget())) - targetList.push_back((*itr)->getTarget()); - else if (currentVictim == nullptr && predicate((*itr)->getTarget())) - targetList.push_back((*itr)->getTarget()); + if (currentVictim != nullptr && hostileRef->getTarget() != currentVictim && predicate(hostileRef->getTarget())) + targetList.push_back(hostileRef->getTarget()); + else if (currentVictim == nullptr && predicate(hostileRef->getTarget())) + targetList.push_back(hostileRef->getTarget()); } if (position >= targetList.size()) return nullptr; if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - targetList.sort(Trinity::ObjectDistanceOrderPred(me)); + SortByDistanceTo(me, targetList); switch (targetType) { case SELECT_TARGET_NEAREST: case SELECT_TARGET_TOPAGGRO: { - std::list::iterator itr = targetList.begin(); + auto itr = targetList.begin(); std::advance(itr, position); return *itr; } case SELECT_TARGET_FARTHEST: case SELECT_TARGET_BOTTOMAGGRO: { - std::list::reverse_iterator ritr = targetList.rbegin(); + auto ritr = targetList.rbegin(); std::advance(ritr, position); return *ritr; } case SELECT_TARGET_RANDOM: - { - std::list::iterator itr = targetList.begin(); - std::advance(itr, urand(position, targetList.size() - 1)); - return *itr; - } + return Trinity::Containers::SelectRandomContainerElement(targetList); default: break; } @@ -236,21 +216,22 @@ class TC_GAME_API UnitAI // Select the targets satifying the predicate. // predicate shall extend std::unary_function - template void SelectTargetList(std::list& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) + template + void SelectTargetList(std::list& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) { - ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = GetThreatManager().getThreatList(); if (threatlist.empty()) return; - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - if (predicate((*itr)->getTarget())) - targetList.push_back((*itr)->getTarget()); + for (HostileReference* hostileRef : threatlist) + if (predicate(hostileRef->getTarget())) + targetList.push_back(hostileRef->getTarget()); if (targetList.size() < maxTargets) return; if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - targetList.sort(Trinity::ObjectDistanceOrderPred(me)); + SortByDistanceTo(me, targetList); if (targetType == SELECT_TARGET_FARTHEST || targetType == SELECT_TARGET_BOTTOMAGGRO) targetList.reverse(); @@ -280,11 +261,9 @@ class TC_GAME_API UnitAI void AttackStartCaster(Unit* victim, float dist); - void DoAddAuraToAllHostilePlayers(uint32 spellid); void DoCast(uint32 spellId); void DoCast(Unit* victim, uint32 spellId, bool triggered = false); void DoCastSelf(uint32 spellId, bool triggered = false) { DoCast(me, spellId, triggered); } - void DoCastToAllHostilePlayers(uint32 spellid, bool triggered = false); void DoCastVictim(uint32 spellId, bool triggered = false); void DoCastAOE(uint32 spellId, bool triggered = false); @@ -305,7 +284,7 @@ class TC_GAME_API UnitAI virtual bool GossipSelect(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/) { return false; } // Called when a player selects a gossip with a code in the creature's gossip menu. - virtual bool GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, const char* /*code*/) { return false; } + virtual bool GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; } // Called when a player accepts a quest from the creature. virtual void QuestAccept(Player* /*player*/, Quest const* /*quest*/) { } @@ -317,12 +296,13 @@ class TC_GAME_API UnitAI virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) { } // Called when the dialog status between a player and the creature is requested. - virtual uint32 GetDialogStatus(Player* /*player*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } - + virtual uint32 GetDialogStatus(Player* /*player*/); private: UnitAI(UnitAI const& right) = delete; UnitAI& operator=(UnitAI const& right) = delete; + + ThreatManager& GetThreatManager(); }; #endif diff --git a/src/server/game/AI/CreatureAI.cpp b/src/server/game/AI/CreatureAI.cpp index 281795c0ed1..7ecee7cc14c 100644 --- a/src/server/game/AI/CreatureAI.cpp +++ b/src/server/game/AI/CreatureAI.cpp @@ -17,16 +17,20 @@ */ #include "CreatureAI.h" -#include "CreatureAIImpl.h" +#include "AreaBoundary.h" #include "Creature.h" -#include "World.h" -#include "SpellMgr.h" -#include "Vehicle.h" +#include "CreatureAIImpl.h" +#include "CreatureTextMgr.h" +#include "Language.h" #include "Log.h" +#include "Map.h" #include "MapReference.h" +#include "MotionMaster.h" #include "Player.h" -#include "CreatureTextMgr.h" -#include "Language.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" +#include "Vehicle.h" +#include "World.h" //Disable CreatureAI when charmed void CreatureAI::OnCharmed(bool apply) @@ -39,7 +43,15 @@ void CreatureAI::OnCharmed(bool apply) } AISpellInfoType* UnitAI::AISpellInfo; -AISpellInfoType* GetAISpellInfo(uint32 i) { return &CreatureAI::AISpellInfo[i]; } +AISpellInfoType* GetAISpellInfo(uint32 i) { return &UnitAI::AISpellInfo[i]; } + +CreatureAI::CreatureAI(Creature* creature) : UnitAI(creature), me(creature), _boundary(nullptr), _negateBoundary(false), m_MoveInLineOfSight_locked(false) +{ +} + +CreatureAI::~CreatureAI() +{ +} void CreatureAI::Talk(uint8 id, WorldObject const* whisperTarget /*= nullptr*/) { @@ -391,7 +403,7 @@ void CreatureAI::SetBoundary(CreatureBoundary const* boundary, bool negateBounda me->DoImmediateBoundaryCheck(); } -Creature* CreatureAI::DoSummon(uint32 entry, const Position& pos, uint32 despawnTime, TempSummonType summonType) +Creature* CreatureAI::DoSummon(uint32 entry, Position const& pos, uint32 despawnTime, TempSummonType summonType) { return me->SummonCreature(entry, pos, summonType, despawnTime); } diff --git a/src/server/game/AI/CreatureAI.h b/src/server/game/AI/CreatureAI.h index 79bcefb3946..a787082bf9d 100644 --- a/src/server/game/AI/CreatureAI.h +++ b/src/server/game/AI/CreatureAI.h @@ -19,17 +19,19 @@ #ifndef TRINITY_CREATUREAI_H #define TRINITY_CREATUREAI_H -#include "Creature.h" #include "UnitAI.h" -#include "AreaBoundary.h" #include "Common.h" +#include "ObjectDefines.h" -class WorldObject; -class Unit; +class AreaBoundary; class Creature; -class Player; +class DynamicObject; +class GameObject; class PlayerAI; -class SpellInfo; +class WorldObject; +struct Position; + +typedef std::vector CreatureBoundary; #define TIME_INTERVAL_LOOK 5000 #define VISIBILITY_RANGE 10000 @@ -65,7 +67,6 @@ enum SCEquip EQUIP_UNEQUIP = 0 }; -typedef std::vector CreatureBoundary; class TC_GAME_API CreatureAI : public UnitAI { protected: @@ -92,11 +93,11 @@ class TC_GAME_API CreatureAI : public UnitAI EVADE_REASON_OTHER }; - void Talk(uint8 id, WorldObject const* whisperTarget = nullptr); + explicit CreatureAI(Creature* creature); - explicit CreatureAI(Creature* creature) : UnitAI(creature), me(creature), _boundary(nullptr), _negateBoundary(false), m_MoveInLineOfSight_locked(false) { } + virtual ~CreatureAI(); - virtual ~CreatureAI() { } + void Talk(uint8 id, WorldObject const* whisperTarget = nullptr); /// == Reactions At ================================= diff --git a/src/server/game/AI/CreatureAIFactory.h b/src/server/game/AI/CreatureAIFactory.h index 6681ba8bc89..feb73ce11de 100644 --- a/src/server/game/AI/CreatureAIFactory.h +++ b/src/server/game/AI/CreatureAIFactory.h @@ -22,6 +22,9 @@ #include "ObjectRegistry.h" #include "FactoryHolder.h" +class Creature; +class CreatureAI; + typedef FactoryHolder CreatureAICreator; struct SelectableAI : public CreatureAICreator, public Permissible diff --git a/src/server/game/AI/CreatureAIImpl.h b/src/server/game/AI/CreatureAIImpl.h index e0346eac10a..b2036d815bd 100644 --- a/src/server/game/AI/CreatureAIImpl.h +++ b/src/server/game/AI/CreatureAIImpl.h @@ -17,17 +17,13 @@ #ifndef CREATUREAIIMPL_H #define CREATUREAIIMPL_H -#include "Common.h" -#include "Define.h" -#include "TemporarySummon.h" -#include "CreatureAI.h" -#include "SpellMgr.h" - -#include +#include "Random.h" #include +class WorldObject; + template -static inline First const& RAND(First const& first, Second const& second, Rest const&... rest) +inline First const& RAND(First const& first, Second const& second, Rest const&... rest) { std::reference_wrapper::type> const pack[] = { first, second, rest... }; return pack[urand(0, sizeof...(rest) + 1)].get(); @@ -65,5 +61,15 @@ struct AISpellInfoType AISpellInfoType* GetAISpellInfo(uint32 i); -#endif +TC_GAME_API bool InstanceHasScript(WorldObject const* obj, char const* scriptName); + +template +AI* GetInstanceAI(T* obj, char const* scriptName) +{ + if (InstanceHasScript(obj, scriptName)) + return new AI(obj); + + return nullptr; +} +#endif diff --git a/src/server/game/AI/CreatureAIRegistry.cpp b/src/server/game/AI/CreatureAIRegistry.cpp index 25dcd98c5db..a89c410a93b 100644 --- a/src/server/game/AI/CreatureAIRegistry.cpp +++ b/src/server/game/AI/CreatureAIRegistry.cpp @@ -16,19 +16,20 @@ * with this program. If not, see . */ -#include "PassiveAI.h" -#include "ReactorAI.h" +#include "CreatureAIFactory.h" +#include "GameObjectAIFactory.h" + #include "CombatAI.h" #include "GuardAI.h" +#include "PassiveAI.h" #include "PetAI.h" +#include "ReactorAI.h" +#include "SmartAI.h" #include "TotemAI.h" -#include "RandomMovementGenerator.h" + #include "MovementGenerator.h" -#include "CreatureAIRegistry.h" +#include "RandomMovementGenerator.h" #include "WaypointMovementGenerator.h" -#include "CreatureAIFactory.h" -#include "GameObjectAIFactory.h" -#include "SmartAI.h" namespace AIRegistry { diff --git a/src/server/game/AI/GameObjectAIFactory.h b/src/server/game/AI/GameObjectAIFactory.h index 2ff799ab7ea..a52f4279223 100644 --- a/src/server/game/AI/GameObjectAIFactory.h +++ b/src/server/game/AI/GameObjectAIFactory.h @@ -21,6 +21,9 @@ #include "ObjectRegistry.h" #include "FactoryHolder.h" +class GameObject; +class GameObjectAI; + typedef FactoryHolder GameObjectAICreator; struct SelectableGameObjectAI : public GameObjectAICreator, public Permissible diff --git a/src/server/game/AI/PlayerAI/PlayerAI.cpp b/src/server/game/AI/PlayerAI/PlayerAI.cpp index 0edd6097026..589b7162c3f 100644 --- a/src/server/game/AI/PlayerAI/PlayerAI.cpp +++ b/src/server/game/AI/PlayerAI/PlayerAI.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016-2017 TrinityCore + * Copyright (C) 2008-2017 TrinityCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -16,8 +16,16 @@ */ #include "PlayerAI.h" +#include "Creature.h" +#include "Item.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "Spell.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" static const uint8 NUM_TALENT_TREES = 3; static const uint8 NUM_SPEC_ICONICS = 3; @@ -496,6 +504,20 @@ static const uint32 SPEC_ICONICS[MAX_CLASSES][NUM_TALENT_TREES][NUM_SPEC_ICONICS } }; +PlayerAI::PlayerAI(Player* player) : UnitAI(player), me(player), + _selfSpec(PlayerAI::GetPlayerSpec(player)), + _isSelfHealer(PlayerAI::IsPlayerHealer(player)), + _isSelfRangedAttacker(PlayerAI::IsPlayerRangedAttacker(player)) +{ +} + +Creature* PlayerAI::GetCharmer() const +{ + if (me->GetCharmerGUID().IsCreature()) + return ObjectAccessor::GetCreature(*me, me->GetCharmerGUID()); + return nullptr; +} + uint8 PlayerAI::GetPlayerSpec(Player const* who) { if (!who) @@ -664,6 +686,13 @@ PlayerAI::TargetedSpell PlayerAI::SelectSpellCast(PossibleSpellVector& spells) return selected; } +void PlayerAI::DoCastAtTarget(TargetedSpell spell) +{ + SpellCastTargets targets; + targets.SetUnitTarget(spell.second); + spell.first->prepare(&targets); +} + void PlayerAI::DoRangedAttackIfReady() { if (me->HasUnitState(UNIT_STATE_CASTING)) @@ -735,13 +764,19 @@ void PlayerAI::CancelAllShapeshifts() me->RemoveOwnedAura(aura, AURA_REMOVE_BY_CANCEL); } -struct UncontrolledTargetSelectPredicate : public std::unary_function +Unit* PlayerAI::SelectAttackTarget() const +{ + return me->GetCharmer() ? me->GetCharmer()->GetVictim() : nullptr; +} + +struct UncontrolledTargetSelectPredicate { bool operator()(Unit const* target) const { return !target->HasBreakableByDamageCrowdControlAura(); } }; + Unit* SimpleCharmedPlayerAI::SelectAttackTarget() const { if (Unit* charmer = me->GetCharmer()) diff --git a/src/server/game/AI/PlayerAI/PlayerAI.h b/src/server/game/AI/PlayerAI/PlayerAI.h index fce24b2dc0e..8afc5ab3ce9 100644 --- a/src/server/game/AI/PlayerAI/PlayerAI.h +++ b/src/server/game/AI/PlayerAI/PlayerAI.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016-2017 TrinityCore + * Copyright (C) 2008-2017 TrinityCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the @@ -19,24 +19,18 @@ #define TRINITY_PLAYERAI_H #include "UnitAI.h" -#include "Player.h" -#include "Spell.h" -#include "Creature.h" + +class Spell; class TC_GAME_API PlayerAI : public UnitAI { public: - explicit PlayerAI(Player* player) : UnitAI(static_cast(player)), me(player), _selfSpec(PlayerAI::GetPlayerSpec(player)), _isSelfHealer(PlayerAI::IsPlayerHealer(player)), _isSelfRangedAttacker(PlayerAI::IsPlayerRangedAttacker(player)) { } + explicit PlayerAI(Player* player); void OnCharmed(bool /*apply*/) override { } // charm AI application for players is handled by Unit::SetCharmedBy / Unit::RemoveCharmedBy - Creature* GetCharmer() const - { - if (ObjectGuid charmerGUID = me->GetCharmerGUID()) - if (charmerGUID.IsCreature()) - return ObjectAccessor::GetCreature(*me, charmerGUID); - return nullptr; - } + Creature* GetCharmer() const; + // helper functions to determine player info // Return values range from 0 (left-most spec) to 2 (right-most spec). If two specs have the same number of talent points, the left-most of those specs is returned. static uint8 GetPlayerSpec(Player const* who); @@ -85,14 +79,9 @@ class TC_GAME_API PlayerAI : public UnitAI This invalidates the vector, and empties it to prevent accidental misuse. */ TargetedSpell SelectSpellCast(PossibleSpellVector& spells); /* Helper method - casts the included spell at the included target */ - inline void DoCastAtTarget(TargetedSpell spell) - { - SpellCastTargets targets; - targets.SetUnitTarget(spell.second); - spell.first->prepare(&targets); - } + void DoCastAtTarget(TargetedSpell spell); - virtual Unit* SelectAttackTarget() const { return me->GetCharmer() ? me->GetCharmer()->GetVictim() : nullptr; } + virtual Unit* SelectAttackTarget() const; void DoRangedAttackIfReady(); void DoAutoAttackIfReady(); diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp index 5464b99f8c9..d32ac53cb9f 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp @@ -17,13 +17,19 @@ */ #include "ScriptedCreature.h" -#include "Spell.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "AreaBoundary.h" #include "Cell.h" #include "CellImpl.h" -#include "ObjectMgr.h" -#include "AreaBoundary.h" +#include "DBCStores.h" +#include "GridNotifiers.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Spell.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" // Spell summary for ScriptedAI::SelectSpell struct TSpellSummary @@ -32,6 +38,16 @@ struct TSpellSummary uint8 Effects; // set of enum SelectEffect } extern* SpellSummary; +void SummonList::Summon(Creature const* summon) +{ + storage_.push_back(summon->GetGUID()); +} + +void SummonList::Despawn(Creature const* summon) +{ + storage_.remove(summon->GetGUID()); +} + void SummonList::DoZoneInCombat(uint32 entry, float maxRangeToNearestTarget) { for (StorageType::iterator i = storage_.begin(); i != storage_.end();) @@ -97,6 +113,16 @@ bool SummonList::HasEntry(uint32 entry) const return false; } +void SummonList::DoActionImpl(int32 action, StorageType const& summons) +{ + for (auto const& guid : summons) + { + Creature* summon = ObjectAccessor::GetCreature(*me, guid); + if (summon && summon->IsAIEnabled) + summon->AI()->DoAction(action); + } +} + ScriptedAI::ScriptedAI(Creature* creature) : CreatureAI(creature), IsFleeing(false), _isCombatMovementAllowed(true) @@ -179,6 +205,16 @@ Creature* ScriptedAI::DoSpawnCreature(uint32 entry, float offsetX, float offsetY return me->SummonCreature(entry, me->GetPositionX() + offsetX, me->GetPositionY() + offsetY, me->GetPositionZ() + offsetZ, angle, TempSummonType(type), despawntime); } +bool ScriptedAI::HealthBelowPct(uint32 pct) const +{ + return me->HealthBelowPct(pct); +} + +bool ScriptedAI::HealthAbovePct(uint32 pct) const +{ + return me->HealthAbovePct(pct); +} + SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mechanic, SelectTargetType targets, uint32 powerCostMin, uint32 powerCostMax, float rangeMin, float rangeMax, SelectEffect effects) { //No target so we can't cast @@ -444,6 +480,11 @@ void BossAI::_JustDied() instance->SetBossState(_bossId, DONE); } +void BossAI::_JustReachedHome() +{ + me->setActive(false); +} + void BossAI::_EnterCombat() { if (instance) @@ -507,6 +548,11 @@ void BossAI::UpdateAI(uint32 diff) DoMeleeAttackIfReady(); } +bool BossAI::CanAIAttack(Unit const* target) const +{ + return CheckBoundary(target); +} + void BossAI::_DespawnAtEvade(uint32 delayToRespawn /*= 30*/, Creature* who /*= nullptr*/) { if (delayToRespawn < 2) diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index b4db664a980..3b24203a146 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -19,23 +19,11 @@ #ifndef SCRIPTEDCREATURE_H_ #define SCRIPTEDCREATURE_H_ -#include "Creature.h" #include "CreatureAI.h" -#include "CreatureAIImpl.h" -#include "InstanceScript.h" +#include "Creature.h" // convenience include for scripts, all uses of ScriptedCreature also need Creature (except ScriptedCreature itself doesn't need Creature) +#include "DBCEnums.h" #include "TaskScheduler.h" -#define CAST_AI(a, b) (dynamic_cast(b)) -#define ENSURE_AI(a,b) (EnsureAI(b)) - -template -T* EnsureAI(U* ai) -{ - T* cast_ai = dynamic_cast(ai); - ASSERT(cast_ai); - return cast_ai; -}; - class InstanceScript; class TC_GAME_API SummonList @@ -95,13 +83,13 @@ public: storage_.clear(); } - void Summon(Creature const* summon) { storage_.push_back(summon->GetGUID()); } - void Despawn(Creature const* summon) { storage_.remove(summon->GetGUID()); } + void Summon(Creature const* summon); + void Despawn(Creature const* summon); void DespawnEntry(uint32 entry); void DespawnAll(); template - void DespawnIf(T const &predicate) + void DespawnIf(T const& predicate) { storage_.remove_if(predicate); } @@ -112,12 +100,7 @@ public: // We need to use a copy of SummonList here, otherwise original SummonList would be modified StorageType listCopy = storage_; Trinity::Containers::RandomResize(listCopy, std::forward(predicate), max); - for (StorageType::iterator i = listCopy.begin(); i != listCopy.end(); ) - { - Creature* summon = ObjectAccessor::GetCreature(*me, *i++); - if (summon && summon->IsAIEnabled) - summon->AI()->DoAction(info); - } + DoActionImpl(info, listCopy); } void DoZoneInCombat(uint32 entry = 0, float maxRangeToNearestTarget = 250.0f); @@ -125,6 +108,8 @@ public: bool HasEntry(uint32 entry) const; private: + void DoActionImpl(int32 action, StorageType const& summons); + Creature* me; StorageType storage_; }; @@ -256,8 +241,8 @@ struct TC_GAME_API ScriptedAI : public CreatureAI //Spawns a creature relative to me Creature* DoSpawnCreature(uint32 entry, float offsetX, float offsetY, float offsetZ, float angle, uint32 type, uint32 despawntime); - bool HealthBelowPct(uint32 pct) const { return me->HealthBelowPct(pct); } - bool HealthAbovePct(uint32 pct) const { return me->HealthAbovePct(pct); } + bool HealthBelowPct(uint32 pct) const; + bool HealthAbovePct(uint32 pct) const; //Returns spells that meet the specified criteria from the creatures spell list SpellInfo const* SelectSpell(Unit* target, uint32 school, uint32 mechanic, SelectTargetType targets, uint32 powerCostMin, uint32 powerCostMax, float rangeMin, float rangeMax, SelectEffect effect); @@ -369,13 +354,13 @@ class TC_GAME_API BossAI : public ScriptedAI void JustDied(Unit* /*killer*/) override { _JustDied(); } void JustReachedHome() override { _JustReachedHome(); } - bool CanAIAttack(Unit const* target) const override { return CheckBoundary(target); } + bool CanAIAttack(Unit const* target) const override; protected: void _Reset(); void _EnterCombat(); void _JustDied(); - void _JustReachedHome() { me->setActive(false); } + void _JustReachedHome(); void _DespawnAtEvade(uint32 delayToRespawn = 30, Creature* who = nullptr); void _DespawnAtEvade(Seconds const& time, Creature* who = nullptr) { _DespawnAtEvade(uint32(time.count()), who); } diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp index 085ef9c4047..6f5b7f1aa71 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp @@ -23,10 +23,14 @@ SDComment: SDCategory: Npc EndScriptData */ -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptedEscortAI.h" +#include "Creature.h" #include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" enum Points { @@ -39,7 +43,7 @@ npc_escortAI::npc_escortAI(Creature* creature) : ScriptedAI(creature), m_uiPlayerCheckTimer(1000), m_uiEscortState(STATE_ESCORT_NONE), MaxPlayerDistance(DEFAULT_MAX_PLAYER_DISTANCE), - m_pQuestForEscort(NULL), + m_pQuestForEscort(nullptr), m_bIsActiveAttacker(true), m_bIsRunning(false), m_bCanInstantRespawn(false), @@ -65,6 +69,11 @@ void npc_escortAI::AttackStart(Unit* who) } } +Player* npc_escortAI::GetPlayerForEscort() +{ + return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); +} + //see followerAI bool npc_escortAI::AssistPlayerInCombatAgainst(Unit* who) { @@ -148,7 +157,7 @@ void npc_escortAI::JustDied(Unit* /*killer*/) { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (member->IsInMap(player)) member->FailQuest(m_pQuestForEscort->GetQuestId()); @@ -186,7 +195,7 @@ void npc_escortAI::EnterEvadeMode(EvadeReason /*why*/) me->RemoveAllAuras(); me->DeleteThreatList(); me->CombatStop(true); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); if (HasEscortState(STATE_ESCORT_ESCORTING)) { @@ -209,7 +218,7 @@ bool npc_escortAI::IsPlayerOrGroupInRange() { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (me->IsWithinDistInMap(member, GetMaxPlayerDistance())) return true; @@ -431,7 +440,7 @@ void npc_escortAI::SetRun(bool on) } /// @todo get rid of this many variables passed in function. -void npc_escortAI::Start(bool isActiveAttacker /* = true*/, bool run /* = false */, ObjectGuid playerGUID /* = 0 */, Quest const* quest /* = NULL */, bool instantRespawn /* = false */, bool canLoopPath /* = false */, bool resetWaypoints /* = true */) +void npc_escortAI::Start(bool isActiveAttacker /* = true*/, bool run /* = false */, ObjectGuid playerGUID /* = 0 */, Quest const* quest /* = nullptr */, bool instantRespawn /* = false */, bool canLoopPath /* = false */, bool resetWaypoints /* = true */) { if (me->GetVictim()) { diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h index e1bf3af5343..754d96dced9 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h @@ -19,8 +19,11 @@ #ifndef SC_ESCORTAI_H #define SC_ESCORTAI_H +#include "ScriptedCreature.h" #include "ScriptSystem.h" +class Quest; + #define DEFAULT_MAX_PLAYER_DISTANCE 50 struct Escort_Waypoint @@ -88,7 +91,7 @@ struct TC_GAME_API npc_escortAI : public ScriptedAI virtual void WaypointReached(uint32 pointId) = 0; virtual void WaypointStart(uint32 /*pointId*/) { } - void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = ObjectGuid::Empty, Quest const* quest = NULL, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); + void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = ObjectGuid::Empty, Quest const* quest = nullptr, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); void SetRun(bool on = true); void SetEscortPaused(bool on); @@ -106,7 +109,7 @@ struct TC_GAME_API npc_escortAI : public ScriptedAI ObjectGuid GetEventStarterGUID() const { return m_uiPlayerGUID; } protected: - Player* GetPlayerForEscort() { return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); } + Player* GetPlayerForEscort(); private: bool AssistPlayerInCombatAgainst(Unit* who); diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp index 79c3c17d610..d18876fc439 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp @@ -23,10 +23,14 @@ SDComment: This AI is under development SDCategory: Npc EndScriptData */ -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptedFollowerAI.h" +#include "Creature.h" #include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" const float MAX_PLAYER_DISTANCE = 100.0f; @@ -38,7 +42,7 @@ enum Points FollowerAI::FollowerAI(Creature* creature) : ScriptedAI(creature), m_uiUpdateFollowTimer(2500), m_uiFollowState(STATE_FOLLOW_NONE), - m_pQuestForFollow(NULL) + m_pQuestForFollow(nullptr) { } void FollowerAI::AttackStart(Unit* who) @@ -146,7 +150,7 @@ void FollowerAI::JustDied(Unit* /*killer*/) { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (member->IsInMap(player)) member->FailQuest(m_pQuestForFollow->GetQuestId()); @@ -174,7 +178,7 @@ void FollowerAI::EnterEvadeMode(EvadeReason /*why*/) me->RemoveAllAuras(); me->DeleteThreatList(); me->CombatStop(true); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); if (HasFollowState(STATE_FOLLOW_INPROGRESS)) { @@ -224,7 +228,7 @@ void FollowerAI::UpdateAI(uint32 uiDiff) if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) { Player* member = groupRef->GetSource(); if (member && me->IsWithinDistInMap(member, MAX_PLAYER_DISTANCE)) @@ -282,7 +286,7 @@ void FollowerAI::MovementInform(uint32 motionType, uint32 pointId) } } -void FollowerAI::StartFollow(Player* player, uint32 factionForFollower, const Quest* quest) +void FollowerAI::StartFollow(Player* player, uint32 factionForFollower, Quest const* quest) { if (me->GetVictim()) { @@ -330,7 +334,7 @@ Player* FollowerAI::GetLeaderForFollower() { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) { Player* member = groupRef->GetSource(); if (member && me->IsWithinDistInMap(member, MAX_PLAYER_DISTANCE) && member->IsAlive()) @@ -345,7 +349,7 @@ Player* FollowerAI::GetLeaderForFollower() } TC_LOG_DEBUG("scripts", "FollowerAI GetLeader can not find suitable leader."); - return NULL; + return nullptr; } void FollowerAI::SetFollowComplete(bool bWithEndEvent) diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h index 6b5b06490f0..7fe877a7589 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h @@ -19,8 +19,11 @@ #ifndef SC_FOLLOWERAI_H #define SC_FOLLOWERAI_H +#include "ScriptedCreature.h" #include "ScriptSystem.h" +class Quest; + enum eFollowState { STATE_FOLLOW_NONE = 0x000, @@ -55,7 +58,7 @@ class TC_GAME_API FollowerAI : public ScriptedAI void UpdateAI(uint32) override; //the "internal" update, calls UpdateFollowerAI() virtual void UpdateFollowerAI(uint32); //used when it's needed to add code in update (abilities, scripted events, etc) - void StartFollow(Player* player, uint32 factionForFollower = 0, const Quest* quest = NULL); + void StartFollow(Player* player, uint32 factionForFollower = 0, Quest const* quest = nullptr); void SetFollowPaused(bool bPaused); //if special event require follow mode to hold/resume during the follow void SetFollowComplete(bool bWithEndEvent = false); @@ -75,7 +78,7 @@ class TC_GAME_API FollowerAI : public ScriptedAI uint32 m_uiUpdateFollowTimer; uint32 m_uiFollowState; - const Quest* m_pQuestForFollow; //normally we have a quest + Quest const* m_pQuestForFollow; //normally we have a quest }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index df5fe1d6b7b..682f92f1ee6 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -15,15 +15,16 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" -#include "ObjectMgr.h" -#include "ObjectDefines.h" -#include "GridDefines.h" -#include "GridNotifiers.h" -#include "SpellMgr.h" -#include "Cell.h" -#include "Group.h" #include "SmartAI.h" +#include "Creature.h" +#include "DBCStructure.h" +#include "GameObject.h" +#include "Group.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PetDefines.h" +#include "Player.h" #include "ScriptMgr.h" #include "Vehicle.h" @@ -530,7 +531,7 @@ void SmartAI::MoveInLineOfSight(Unit* who) CreatureAI::MoveInLineOfSight(who); } -bool SmartAI::CanAIAttack(const Unit* /*who*/) const +bool SmartAI::CanAIAttack(Unit const* /*who*/) const { return !(me->HasReactState(REACT_PASSIVE)); } @@ -663,12 +664,12 @@ void SmartAI::AttackStart(Unit* who) } } -void SmartAI::SpellHit(Unit* unit, const SpellInfo* spellInfo) +void SmartAI::SpellHit(Unit* unit, SpellInfo const* spellInfo) { GetScript()->ProcessEventsFor(SMART_EVENT_SPELLHIT, unit, 0, 0, false, spellInfo); } -void SmartAI::SpellHitTarget(Unit* target, const SpellInfo* spellInfo) +void SmartAI::SpellHitTarget(Unit* target, SpellInfo const* spellInfo) { GetScript()->ProcessEventsFor(SMART_EVENT_SPELLHIT_TARGET, target, 0, 0, false, spellInfo); } @@ -816,7 +817,7 @@ bool SmartAI::GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) return _gossipReturn; } -bool SmartAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, const char* /*code*/) +bool SmartAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; } @@ -1005,7 +1006,7 @@ bool SmartGameObjectAI::GossipSelect(Player* player, uint32 sender, uint32 actio } // Called when a player selects a gossip with a code in the gameobject's gossip menu. -bool SmartGameObjectAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, const char* /*code*/) +bool SmartGameObjectAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; } @@ -1055,7 +1056,7 @@ void SmartGameObjectAI::EventInform(uint32 eventId) GetScript()->ProcessEventsFor(SMART_EVENT_GO_EVENT_INFORM, nullptr, eventId); } -void SmartGameObjectAI::SpellHit(Unit* unit, const SpellInfo* spellInfo) +void SmartGameObjectAI::SpellHit(Unit* unit, SpellInfo const* spellInfo) { GetScript()->ProcessEventsFor(SMART_EVENT_SPELLHIT, unit, 0, 0, false, spellInfo); } diff --git a/src/server/game/AI/SmartScripts/SmartAI.h b/src/server/game/AI/SmartScripts/SmartAI.h index e295f1bc7c4..b5ed74c4edb 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.h +++ b/src/server/game/AI/SmartScripts/SmartAI.h @@ -18,15 +18,13 @@ #ifndef TRINITY_SMARTAI_H #define TRINITY_SMARTAI_H -#include "Common.h" -#include "Creature.h" +#include "Define.h" #include "CreatureAI.h" -#include "Unit.h" -#include "Spell.h" - -#include "SmartScript.h" -#include "SmartScriptMgr.h" #include "GameObjectAI.h" +#include "Position.h" +#include "SmartScript.h" + +struct WayPoint; enum SmartEscortState { @@ -100,10 +98,10 @@ class TC_GAME_API SmartAI : public CreatureAI void MoveInLineOfSight(Unit* who) override; // Called when hit by a spell - void SpellHit(Unit* unit, const SpellInfo* spellInfo) override; + void SpellHit(Unit* unit, SpellInfo const* spellInfo) override; // Called when spell hits a target - void SpellHitTarget(Unit* target, const SpellInfo* spellInfo) override; + void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override; // Called at any Damage from any attacker (before damage apply) void DamageTaken(Unit* doneBy, uint32& damage) override; @@ -142,7 +140,7 @@ class TC_GAME_API SmartAI : public CreatureAI void OnCharmed(bool apply) override; // Called when victim is in line of sight - bool CanAIAttack(const Unit* who) const override; + bool CanAIAttack(Unit const* who) const override; // Used in scripts to share variables void DoAction(int32 param = 0) override; @@ -180,7 +178,7 @@ class TC_GAME_API SmartAI : public CreatureAI bool GossipHello(Player* player) override; bool GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override; - bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, const char* code) override; + bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, char const* code) override; void QuestAccept(Player* player, Quest const* quest) override; void QuestReward(Player* player, Quest const* quest, uint32 opt) override; void OnGameEvent(bool start, uint16 eventId) override; @@ -262,7 +260,7 @@ class TC_GAME_API SmartGameObjectAI : public GameObjectAI bool GossipHello(Player* player) override; bool OnReportUse(Player* player) override; bool GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override; - bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, const char* code) override; + bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, char const* code) override; void QuestAccept(Player* player, Quest const* quest) override; void QuestReward(Player* player, Quest const* quest, uint32 opt) override; void Destroyed(Player* player, uint32 eventId) override; @@ -271,7 +269,7 @@ class TC_GAME_API SmartGameObjectAI : public GameObjectAI void OnGameEvent(bool start, uint16 eventId) override; void OnLootStateChanged(uint32 state, Unit* unit) override; void EventInform(uint32 eventId) override; - void SpellHit(Unit* unit, const SpellInfo* spellInfo) override; + void SpellHit(Unit* unit, SpellInfo const* spellInfo) override; void SetGossipReturn(bool val) { _gossipReturn = val; } diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index 6dc0bd62256..fe86978b0db 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -15,27 +15,31 @@ * with this program. If not, see . */ -#include "Cell.h" +#include "SmartScript.h" #include "CellImpl.h" #include "ChatTextBuilder.h" +#include "Creature.h" #include "CreatureTextMgr.h" -#include "DatabaseEnv.h" +#include "CreatureTextMgrImpl.h" +#include "GameEventMgr.h" +#include "GameObject.h" #include "GossipDef.h" -#include "GridDefines.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceScript.h" #include "Language.h" -#include "ObjectDefines.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "Random.h" #include "SmartAI.h" -#include "SmartScript.h" +#include "SpellAuras.h" #include "SpellMgr.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "GameEventMgr.h" +#include SmartScript::SmartScript() { @@ -57,6 +61,97 @@ SmartScript::~SmartScript() { } +bool SmartScript::IsSmart(Creature* c /*= nullptr*/) +{ + bool smart = true; + if (c && c->GetAIName() != "SmartAI") + smart = false; + + if (!me || me->GetAIName() != "SmartAI") + smart = false; + + if (!smart) + TC_LOG_ERROR("sql.sql", "SmartScript: Action target Creature (GUID: %u Entry: %u) is not using SmartAI, action called by Creature (GUID: %u Entry: %u) skipped to prevent crash.", c ? c->GetSpawnId() : 0, c ? c->GetEntry() : 0, me ? me->GetSpawnId() : 0, me ? me->GetEntry() : 0); + + return smart; +} + +bool SmartScript::IsSmartGO(GameObject* g /*= nullptr*/) +{ + bool smart = true; + if (g && g->GetAIName() != "SmartGameObjectAI") + smart = false; + + if (!go || go->GetAIName() != "SmartGameObjectAI") + smart = false; + if (!smart) + TC_LOG_ERROR("sql.sql", "SmartScript: Action target GameObject (GUID: %u Entry: %u) is not using SmartGameObjectAI, action called by GameObject (GUID: %u Entry: %u) skipped to prevent crash.", g ? g->GetSpawnId() : 0, g ? g->GetEntry() : 0, go ? go->GetSpawnId() : 0, go ? go->GetEntry() : 0); + + return smart; +} + +void SmartScript::StoreTargetList(ObjectVector const& targets, uint32 id) +{ + // insert or replace + _storedTargets.erase(id); + _storedTargets.emplace(id, ObjectGuidVector(targets)); +} + +ObjectVector const* SmartScript::GetStoredTargetVector(uint32 id, WorldObject const& ref) const +{ + auto itr = _storedTargets.find(id); + if (itr != _storedTargets.end()) + return itr->second.GetObjectVector(ref); + return nullptr; +} + +void SmartScript::StoreCounter(uint32 id, uint32 value, uint32 reset) +{ + CounterMap::iterator itr = mCounterList.find(id); + if (itr != mCounterList.end()) + { + if (reset == 0) + itr->second += value; + else + itr->second = value; + } + else + mCounterList.insert(std::make_pair(id, value)); + + ProcessEventsFor(SMART_EVENT_COUNTER_SET, nullptr, id); +} + +uint32 SmartScript::GetCounterValue(uint32 id) const +{ + CounterMap::const_iterator itr = mCounterList.find(id); + if (itr != mCounterList.end()) + return itr->second; + return 0; +} + +GameObject* SmartScript::FindGameObjectNear(WorldObject* searchObject, ObjectGuid::LowType guid) const +{ + auto bounds = searchObject->GetMap()->GetGameObjectBySpawnIdStore().equal_range(guid); + if (bounds.first == bounds.second) + return nullptr; + + return bounds.first->second; +} + +Creature* SmartScript::FindCreatureNear(WorldObject* searchObject, ObjectGuid::LowType guid) const +{ + auto bounds = searchObject->GetMap()->GetCreatureBySpawnIdStore().equal_range(guid); + if (bounds.first == bounds.second) + return nullptr; + + auto creatureItr = std::find_if(bounds.first, bounds.second, [](Map::CreatureBySpawnIdContainer::value_type const& pair) + { + return pair.second->IsAlive(); + }); + + return creatureItr != bounds.second ? creatureItr->second : bounds.first->second; +} + void SmartScript::OnReset() { ResetBaseObject(); @@ -73,7 +168,37 @@ void SmartScript::OnReset() mCounterList.clear(); } -void SmartScript::ProcessEventsFor(SMART_EVENT e, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ResetBaseObject() +{ + WorldObject* lookupRoot = me; + if (!lookupRoot) + lookupRoot = go; + + if (lookupRoot) + { + if (!meOrigGUID.IsEmpty()) + { + if (Creature* m = ObjectAccessor::GetCreature(*lookupRoot, meOrigGUID)) + { + me = m; + go = nullptr; + } + } + + if (!goOrigGUID.IsEmpty()) + { + if (GameObject* o = ObjectAccessor::GetGameObject(*lookupRoot, goOrigGUID)) + { + me = nullptr; + go = o; + } + } + } + goOrigGUID.Clear(); + meOrigGUID.Clear(); +} + +void SmartScript::ProcessEventsFor(SMART_EVENT e, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { for (SmartAIEventList::iterator i = mEvents.begin(); i != mEvents.end(); ++i) { @@ -87,7 +212,7 @@ void SmartScript::ProcessEventsFor(SMART_EVENT e, Unit* unit, uint32 var0, uint3 } } -void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { // calc random if (e.GetEventType() != SMART_EVENT_LINK && e.event.event_chance < 100 && e.event.event_chance) @@ -314,7 +439,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u case SMART_ACTION_RANDOM_EMOTE: { std::vector emotes; - std::copy_if(e.action.randomEmote.emotes.begin(), e.action.randomEmote.emotes.end(), + std::copy_if(std::begin(e.action.randomEmote.emotes), std::end(e.action.randomEmote.emotes), std::back_inserter(emotes), [](uint32 emote) { return emote != 0; }); for (WorldObject* target : targets) @@ -736,7 +861,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; std::vector phases; - std::copy_if(e.action.randomPhase.phases.begin(), e.action.randomPhase.phases.end(), + std::copy_if(std::begin(e.action.randomPhase.phases), std::end(e.action.randomPhase.phases), std::back_inserter(phases), [](uint32 phase) { return phase != 0; }); uint32 phase = Trinity::Containers::SelectRandomContainerElement(phases); @@ -1064,14 +1189,14 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u for (WorldObject* target : targets) { Position pos = target->GetPositionWithOffset(Position(e.target.x, e.target.y, e.target.z, e.target.o)); - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f); GetBaseObject()->SummonGameObject(e.action.summonGO.entry, pos, rot, e.action.summonGO.despawnTime); } if (e.GetTargetType() != SMART_TARGET_POSITION) break; - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(e.target.o, 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(e.target.o, 0.f, 0.f); GetBaseObject()->SummonGameObject(e.action.summonGO.entry, Position(e.target.x, e.target.y, e.target.z, e.target.o), rot, e.action.summonGO.despawnTime); break; } @@ -1350,7 +1475,11 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u std::copy(std::begin(eInfo->ItemEntry), std::end(eInfo->ItemEntry), std::begin(slot)); } else - std::copy(std::begin(e.action.equip.slots), std::end(e.action.equip.slots), std::begin(slot)); + { + slot[0] = e.action.equip.slot1; + slot[1] = e.action.equip.slot2; + slot[2] = e.action.equip.slot3; + } for (uint32 i = 0; i < MAX_EQUIPMENT_ITEMS; ++i) if (!e.action.equip.mask || (e.action.equip.mask & (1 << i))) @@ -1498,7 +1627,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; ObjectVector casters; - GetTargets(casters, CreateEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.crossCast.targetType, e.action.crossCast.targetParam1, e.action.crossCast.targetParam2, e.action.crossCast.targetParam3, 0), unit); + GetTargets(casters, CreateSmartEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.crossCast.targetType, e.action.crossCast.targetParam1, e.action.crossCast.targetParam2, e.action.crossCast.targetParam3, 0), unit); for (WorldObject* caster : casters) { @@ -1533,7 +1662,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u case SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST: { std::vector actionLists; - std::copy_if(e.action.randTimedActionList.actionLists.begin(), e.action.randTimedActionList.actionLists.end(), + std::copy_if(std::begin(e.action.randTimedActionList.actionLists), std::end(e.action.randTimedActionList.actionLists), std::back_inserter(actionLists), [](uint32 actionList) { return actionList != 0; }); uint32 id = Trinity::Containers::SelectRandomContainerElement(actionLists); @@ -1738,9 +1867,9 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (e.action.sendGossipMenu.gossipMenuId) player->PrepareGossipMenu(GetBaseObject(), e.action.sendGossipMenu.gossipMenuId, true); else - ClearGossipMenuFor(player); + player->PlayerTalkClass->ClearMenus(); - SendGossipMenuFor(player, e.action.sendGossipMenu.gossipNpcTextId, GetBaseObject()->GetGUID()); + player->PlayerTalkClass->SendGossipMenu(e.action.sendGossipMenu.gossipNpcTextId, GetBaseObject()->GetGUID()); } } break; @@ -1861,7 +1990,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u case SMART_ACTION_START_CLOSEST_WAYPOINT: { std::vector waypoints; - std::copy_if(e.action.closestWaypointFromList.wps.begin(), e.action.closestWaypointFromList.wps.end(), + std::copy_if(std::begin(e.action.closestWaypointFromList.wps), std::end(e.action.closestWaypointFromList.wps), std::back_inserter(waypoints), [](uint32 wp) { return wp != 0; }); float distanceToClosest = std::numeric_limits::max(); @@ -1904,7 +2033,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u case SMART_ACTION_RANDOM_SOUND: { std::vector sounds; - std::copy_if(e.action.randomSound.sounds.begin(), e.action.randomSound.sounds.end(), + std::copy_if(std::begin(e.action.randomSound.sounds), std::end(e.action.randomSound.sounds), std::back_inserter(sounds), [](uint32 sound) { return sound != 0; }); bool onlySelf = e.action.randomSound.onlySelf != 0; @@ -1975,7 +2104,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u case SMART_ACTION_TRIGGER_RANDOM_TIMED_EVENT: { uint32 eventId = urand(e.action.randomTimedEvent.minId, e.action.randomTimedEvent.maxId); - ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, NULL, eventId); + ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, nullptr, eventId); break; } @@ -2015,7 +2144,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } } -void SmartScript::ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { // We may want to execute action rarely and because of this if condition is not fulfilled the action will be rechecked in a long time if (sConditionMgr->IsObjectMeetingSmartEventConditions(e.entryOrGuid, e.event_id, e.source_type, unit, GetBaseObject())) @@ -2105,10 +2234,10 @@ void SmartScript::InstallTemplate(SmartScriptHolder const& e) void SmartScript::AddEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask) { - mInstallEvents.push_back(CreateEvent(e, event_flags, event_param1, event_param2, event_param3, event_param4, action, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, t, target_param1, target_param2, target_param3, phaseMask)); + mInstallEvents.push_back(CreateSmartEvent(e, event_flags, event_param1, event_param2, event_param3, event_param4, action, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, t, target_param1, target_param2, target_param3, phaseMask)); } -SmartScriptHolder SmartScript::CreateEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask) +SmartScriptHolder SmartScript::CreateSmartEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask) { SmartScriptHolder script; script.event.type = e; @@ -2373,13 +2502,13 @@ void SmartScript::GetTargets(ObjectVector& targets, SmartScriptHolder const& e, } case SMART_TARGET_CLOSEST_CREATURE: { - if (Creature* target = GetClosestCreatureWithEntry(baseObject, e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100), !e.target.closest.dead)) + if (Creature* target = baseObject->FindNearestCreature(e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100), !e.target.closest.dead)) targets.push_back(target); break; } case SMART_TARGET_CLOSEST_GAMEOBJECT: { - if (GameObject* target = GetClosestGameObjectWithEntry(baseObject, e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100))) + if (GameObject* target = baseObject->FindNearestGameObject(e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100))) targets.push_back(target); break; } @@ -2496,7 +2625,7 @@ void SmartScript::GetWorldObjectsInDist(ObjectVector& targets, float dist) const Cell::VisitAllObjects(obj, searcher, dist); } -void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { if (!e.active && e.GetEventType() != SMART_EVENT_LINK) return; @@ -3182,6 +3311,62 @@ void SmartScript::InstallEvents() } } +void SmartScript::RemoveStoredEvent(uint32 id) +{ + if (!mStoredEvents.empty()) + { + for (auto i = mStoredEvents.begin(); i != mStoredEvents.end(); ++i) + { + if (i->event_id == id) + { + mStoredEvents.erase(i); + return; + } + } + } +} + +WorldObject* SmartScript::GetBaseObject() const +{ + WorldObject* obj = nullptr; + if (me) + obj = me; + else if (go) + obj = go; + return obj; +} + +bool SmartScript::IsUnit(WorldObject* obj) +{ + return obj && (obj->GetTypeId() == TYPEID_UNIT || obj->GetTypeId() == TYPEID_PLAYER); +} + +bool SmartScript::IsPlayer(WorldObject* obj) +{ + return obj && obj->GetTypeId() == TYPEID_PLAYER; +} + +bool SmartScript::IsCreature(WorldObject* obj) +{ + return obj && obj->GetTypeId() == TYPEID_UNIT; +} + +bool SmartScript::IsCharmedCreature(WorldObject* obj) +{ + if (!obj) + return false; + + if (Creature* creatureObj = obj->ToCreature()) + return creatureObj->IsCharmed(); + + return false; +} + +bool SmartScript::IsGameObject(WorldObject* obj) +{ + return obj && obj->GetTypeId() == TYPEID_GAMEOBJECT; +} + void SmartScript::OnUpdate(uint32 const diff) { if ((mScriptType == SMART_SCRIPT_TYPE_CREATURE || mScriptType == SMART_SCRIPT_TYPE_GAMEOBJECT) && !GetBaseObject()) diff --git a/src/server/game/AI/SmartScripts/SmartScript.h b/src/server/game/AI/SmartScripts/SmartScript.h index cf10f7d15f4..b0269bc45c2 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.h +++ b/src/server/game/AI/SmartScripts/SmartScript.h @@ -18,15 +18,16 @@ #ifndef TRINITY_SMARTSCRIPT_H #define TRINITY_SMARTSCRIPT_H -#include "Common.h" -#include "Creature.h" -#include "CreatureAI.h" -#include "Unit.h" -#include "Spell.h" -#include "GridNotifiers.h" - +#include "Define.h" #include "SmartScriptMgr.h" -//#include "SmartAI.h" + +class Creature; +class GameObject; +class Player; +class SpellInfo; +class Unit; +class WorldObject; +struct AreaTriggerEntry; class TC_GAME_API SmartScript { @@ -38,61 +39,27 @@ class TC_GAME_API SmartScript void GetScript(); void FillScript(SmartAIEventList e, WorldObject* obj, AreaTriggerEntry const* at); - void ProcessEventsFor(SMART_EVENT e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); - void ProcessEvent(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); + void ProcessEventsFor(SMART_EVENT e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); + void ProcessEvent(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); bool CheckTimer(SmartScriptHolder const& e) const; static void RecalcTimer(SmartScriptHolder& e, uint32 min, uint32 max); void UpdateTimer(SmartScriptHolder& e, uint32 const diff); static void InitTimer(SmartScriptHolder& e); - void ProcessAction(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); - void ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); + void ProcessAction(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); + void ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); void GetTargets(ObjectVector& targets, SmartScriptHolder const& e, Unit* invoker = nullptr) const; void GetWorldObjectsInDist(ObjectVector& objects, float dist) const; void InstallTemplate(SmartScriptHolder const& e); - static SmartScriptHolder CreateEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask = 0); + static SmartScriptHolder CreateSmartEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask = 0); void AddEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask = 0); void SetPathId(uint32 id) { mPathId = id; } uint32 GetPathId() const { return mPathId; } - WorldObject* GetBaseObject() const - { - WorldObject* obj = nullptr; - if (me) - obj = me; - else if (go) - obj = go; - return obj; - } - - static bool IsUnit(WorldObject* obj) - { - return obj && (obj->GetTypeId() == TYPEID_UNIT || obj->GetTypeId() == TYPEID_PLAYER); - } - - static bool IsPlayer(WorldObject* obj) - { - return obj && obj->GetTypeId() == TYPEID_PLAYER; - } - - static bool IsCreature(WorldObject* obj) - { - return obj && obj->GetTypeId() == TYPEID_UNIT; - } - - static bool IsCharmedCreature(WorldObject* obj) - { - if (!obj) - return false; - - if (Creature* creatureObj = obj->ToCreature()) - return creatureObj->IsCharmed(); - - return false; - } - - static bool IsGameObject(WorldObject* obj) - { - return obj && obj->GetTypeId() == TYPEID_GAMEOBJECT; - } + WorldObject* GetBaseObject() const; + static bool IsUnit(WorldObject* obj); + static bool IsPlayer(WorldObject* obj); + static bool IsCreature(WorldObject* obj); + static bool IsCharmedCreature(WorldObject* obj); + static bool IsGameObject(WorldObject* obj); void OnUpdate(const uint32 diff); void OnMoveInLineOfSight(Unit* who); @@ -102,127 +69,20 @@ class TC_GAME_API SmartScript void DoFindFriendlyMissingBuff(std::vector& creatures, float range, uint32 spellid) const; Unit* DoFindClosestFriendlyInRange(float range, bool playerOnly) const; - void StoreTargetList(ObjectVector const& targets, uint32 id) - { - // insert or replace - _storedTargets.erase(id); - _storedTargets.emplace(id, ObjectGuidVector(targets)); - } - - bool IsSmart(Creature* c = nullptr) - { - bool smart = true; - if (c && c->GetAIName() != "SmartAI") - smart = false; - - if (!me || me->GetAIName() != "SmartAI") - smart = false; - - if (!smart) - TC_LOG_ERROR("sql.sql", "SmartScript: Action target Creature (GUID: %u Entry: %u) is not using SmartAI, action called by Creature (GUID: %u Entry: %u) skipped to prevent crash.", c ? c->GetSpawnId() : 0, c ? c->GetEntry() : 0, me ? me->GetSpawnId() : 0, me ? me->GetEntry() : 0); + bool IsSmart(Creature* c = nullptr); + bool IsSmartGO(GameObject* g = nullptr); - return smart; - } + void StoreTargetList(ObjectVector const& targets, uint32 id); + ObjectVector const* GetStoredTargetVector(uint32 id, WorldObject const& ref) const; - bool IsSmartGO(GameObject* g = nullptr) - { - bool smart = true; - if (g && g->GetAIName() != "SmartGameObjectAI") - smart = false; + void StoreCounter(uint32 id, uint32 value, uint32 reset); + uint32 GetCounterValue(uint32 id) const; - if (!go || go->GetAIName() != "SmartGameObjectAI") - smart = false; - if (!smart) - TC_LOG_ERROR("sql.sql", "SmartScript: Action target GameObject (GUID: %u Entry: %u) is not using SmartGameObjectAI, action called by GameObject (GUID: %u Entry: %u) skipped to prevent crash.", g ? g->GetSpawnId() : 0, g ? g->GetEntry() : 0, go ? go->GetSpawnId() : 0, go ? go->GetEntry() : 0); - - return smart; - } - - ObjectVector const* GetStoredTargetVector(uint32 id, WorldObject const& ref) const - { - auto itr = _storedTargets.find(id); - if (itr != _storedTargets.end()) - return itr->second.GetObjectVector(ref); - return nullptr; - } - - void StoreCounter(uint32 id, uint32 value, uint32 reset) - { - CounterMap::iterator itr = mCounterList.find(id); - if (itr != mCounterList.end()) - { - if (reset == 0) - itr->second += value; - else - itr->second = value; - } - else - mCounterList.insert(std::make_pair(id, value)); - - ProcessEventsFor(SMART_EVENT_COUNTER_SET, nullptr, id); - } - - uint32 GetCounterValue(uint32 id) const - { - CounterMap::const_iterator itr = mCounterList.find(id); - if (itr != mCounterList.end()) - return itr->second; - return 0; - } - - GameObject* FindGameObjectNear(WorldObject* searchObject, ObjectGuid::LowType guid) const - { - auto bounds = searchObject->GetMap()->GetGameObjectBySpawnIdStore().equal_range(guid); - if (bounds.first == bounds.second) - return nullptr; - - return bounds.first->second; - } - - Creature* FindCreatureNear(WorldObject* searchObject, ObjectGuid::LowType guid) const - { - auto bounds = searchObject->GetMap()->GetCreatureBySpawnIdStore().equal_range(guid); - if (bounds.first == bounds.second) - return nullptr; - - auto creatureItr = std::find_if(bounds.first, bounds.second, [](Map::CreatureBySpawnIdContainer::value_type const& pair) - { - return pair.second->IsAlive(); - }); - - return creatureItr != bounds.second ? creatureItr->second : bounds.first->second; - } + GameObject* FindGameObjectNear(WorldObject* searchObject, ObjectGuid::LowType guid) const; + Creature* FindCreatureNear(WorldObject* searchObject, ObjectGuid::LowType guid) const; void OnReset(); - void ResetBaseObject() - { - WorldObject* lookupRoot = me; - if (!lookupRoot) - lookupRoot = go; - - if (lookupRoot) - { - if (!meOrigGUID.IsEmpty()) - { - if (Creature* m = ObjectAccessor::GetCreature(*lookupRoot, meOrigGUID)) - { - me = m; - go = nullptr; - } - } - - if (!goOrigGUID.IsEmpty()) - { - if (GameObject* o = ObjectAccessor::GetGameObject(*lookupRoot, goOrigGUID)) - { - me = nullptr; - go = o; - } - } - } - goOrigGUID.Clear(); - meOrigGUID.Clear(); - } + void ResetBaseObject(); //TIMED_ACTIONLIST (script type 9 aka script9) void SetScript9(SmartScriptHolder& e, uint32 entry); @@ -265,20 +125,7 @@ class TC_GAME_API SmartScript SMARTAI_TEMPLATE mTemplate; void InstallEvents(); - void RemoveStoredEvent(uint32 id) - { - if (!mStoredEvents.empty()) - { - for (auto i = mStoredEvents.begin(); i != mStoredEvents.end(); ++i) - { - if (i->event_id == id) - { - mStoredEvents.erase(i); - return; - } - } - } - } + void RemoveStoredEvent(uint32 id); }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp index d2910208155..31282a934ac 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp @@ -15,18 +15,20 @@ * with this program. If not, see . */ +#include "SmartScriptMgr.h" +#include "CreatureTextMgr.h" #include "DatabaseEnv.h" -#include "ObjectMgr.h" -#include "GridDefines.h" -#include "GridNotifiers.h" -#include "InstanceScript.h" -#include "SpellMgr.h" -#include "Cell.h" +#include "DBCStores.h" #include "GameEventMgr.h" -#include "CreatureTextMgr.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "SpellInfo.h" - -#include "SmartScriptMgr.h" +#include "SpellMgr.h" +#include "Timer.h" +#include "UnitDefines.h" SmartWaypointMgr* SmartWaypointMgr::instance() { @@ -380,6 +382,43 @@ void SmartAIMgr::LoadSmartAIFromDB() UnLoadHelperStores(); } +SmartAIEventList SmartAIMgr::GetScript(int32 entry, SmartScriptType type) +{ + SmartAIEventList temp; + if (mEventMap[uint32(type)].find(entry) != mEventMap[uint32(type)].end()) + return mEventMap[uint32(type)][entry]; + else + { + if (entry > 0)//first search is for guid (negative), do not drop error if not found + TC_LOG_DEBUG("scripts.ai", "SmartAIMgr::GetScript: Could not load Script for Entry %d ScriptType %u.", entry, uint32(type)); + return temp; + } +} + +SmartScriptHolder& SmartAIMgr::FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId) +{ + SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), + [eventId](SmartScriptHolder& source) { return source.link == eventId; }); + + if (itr != list.end()) + return *itr; + + static SmartScriptHolder SmartScriptHolderDummy; + return SmartScriptHolderDummy; +} + +SmartScriptHolder& SmartAIMgr::FindLinkedEvent(SmartAIEventList& list, uint32 link) +{ + SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), + [link](SmartScriptHolder& linked) { return linked.event_id == link && linked.GetEventType() == SMART_EVENT_LINK; }); + + if (itr != list.end()) + return *itr; + + static SmartScriptHolder SmartScriptHolderDummy; + return SmartScriptHolderDummy; +} + bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { if (std::abs(e.target.o) > 2 * float(M_PI)) @@ -463,6 +502,116 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) return true; } +bool SmartAIMgr::IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max) +{ + if (max < min) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses min/max params wrong (%u/%u), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); + return false; + } + return true; +} + +bool SmartAIMgr::NotNULL(SmartScriptHolder const& e, uint32 data) +{ + if (!data) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Parameter can not be NULL, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + return false; + } + return true; +} + +bool SmartAIMgr::IsCreatureValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sObjectMgr->GetCreatureTemplate(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsQuestValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sObjectMgr->GetQuestTemplate(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsGameObjectValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sObjectMgr->GetGameObjectTemplate(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsSpellValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sSpellMgr->GetSpellInfo(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsItemValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sItemStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Item entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sEmotesTextStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Text Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsEmoteValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sEmotesStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sAreaTriggerStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent AreaTrigger entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsSoundValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sSoundEntriesStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Sound entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.event.type >= SMART_EVENT_END) @@ -916,7 +1065,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } case SMART_ACTION_RANDOM_EMOTE: { - if (std::all_of(e.action.randomEmote.emotes.begin(), e.action.randomEmote.emotes.end(), [](uint32 emote) { return emote == 0; })) + if (std::all_of(std::begin(e.action.randomEmote.emotes), std::end(e.action.randomEmote.emotes), [](uint32 emote) { return emote == 0; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero emote", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); @@ -930,7 +1079,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } case SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST: { - if (std::all_of(e.action.randTimedActionList.actionLists.begin(), e.action.randTimedActionList.actionLists.end(), [](uint32 actionList) { return actionList == 0; })) + if (std::all_of(std::begin(e.action.randTimedActionList.actionLists), std::end(e.action.randTimedActionList.actionLists), [](uint32 actionList) { return actionList == 0; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero action list", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); @@ -940,7 +1089,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } case SMART_ACTION_START_CLOSEST_WAYPOINT: { - if (std::all_of(e.action.closestWaypointFromList.wps.begin(), e.action.closestWaypointFromList.wps.end(), [](uint32 wp) { return wp == 0; })) + if (std::all_of(std::begin(e.action.closestWaypointFromList.wps), std::end(e.action.closestWaypointFromList.wps), [](uint32 wp) { return wp == 0; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero waypoint id", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); @@ -950,7 +1099,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } case SMART_ACTION_RANDOM_SOUND: { - if (std::all_of(e.action.randomSound.sounds.begin(), e.action.randomSound.sounds.end(), [](uint32 sound) { return sound == 0; })) + if (std::all_of(std::begin(e.action.randomSound.sounds), std::end(e.action.randomSound.sounds), [](uint32 sound) { return sound == 0; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero sound", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); @@ -1032,14 +1181,14 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) break; case SMART_ACTION_RANDOM_PHASE: { - if (std::all_of(e.action.randomPhase.phases.begin(), e.action.randomPhase.phases.end(), [](uint32 phase) { return phase == 0; })) + if (std::all_of(std::begin(e.action.randomPhase.phases), std::end(e.action.randomPhase.phases), [](uint32 phase) { return phase == 0; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero phase", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } - if (std::any_of(e.action.randomPhase.phases.begin(), e.action.randomPhase.phases.end(), [](uint32 phase) { return phase >= SMART_EVENT_PHASE_MAX; })) + if (std::any_of(std::begin(e.action.randomPhase.phases), std::end(e.action.randomPhase.phases), [](uint32 phase) { return phase >= SMART_EVENT_PHASE_MAX; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; @@ -1164,21 +1313,21 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return false; break; case SMART_ACTION_WP_START: + { + if (!sSmartWaypointMgr->GetPath(e.action.wpStart.pathID)) { - if (!sSmartWaypointMgr->GetPath(e.action.wpStart.pathID)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses non-existent WaypointPath id %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.pathID); - return false; - } - if (e.action.wpStart.quest && !IsQuestValid(e, e.action.wpStart.quest)) - return false; - if (e.action.wpStart.reactState > REACT_AGGRESSIVE) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses invalid React State %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.reactState); - return false; - } - break; + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses non-existent WaypointPath id %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.pathID); + return false; + } + if (e.action.wpStart.quest && !IsQuestValid(e, e.action.wpStart.quest)) + return false; + if (e.action.wpStart.reactState > REACT_AGGRESSIVE) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Creature %d Event %u Action %u uses invalid React State %u, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.reactState); + return false; } + break; + } case SMART_ACTION_CREATE_TIMED_EVENT: { if (!IsMinMaxValid(e, e.action.timeEvent.min, e.action.timeEvent.max)) @@ -1419,7 +1568,7 @@ void SmartAIMgr::LoadHelperStores() { uint32 oldMSTime = getMSTime(); - SpellInfo const* spellInfo = NULL; + SpellInfo const* spellInfo = nullptr; for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i) { spellInfo = sSpellMgr->GetSpellInfo(i); @@ -1473,3 +1622,18 @@ CacheSpellContainerBounds SmartAIMgr::GetCreateItemSpellContainerBounds(uint32 i return CreateItemSpellStore.equal_range(itemId); } +ObjectGuidVector::ObjectGuidVector(ObjectVector const& objectVector) : _objectVector(objectVector) +{ + _guidVector.reserve(_objectVector.size()); + for (WorldObject* obj : _objectVector) + _guidVector.push_back(obj->GetGUID()); +} + +void ObjectGuidVector::UpdateObjects(WorldObject const& ref) const +{ + _objectVector.clear(); + + for (ObjectGuid const& guid : _guidVector) + if (WorldObject* obj = ObjectAccessor::GetWorldObject(ref, guid)) + _objectVector.push_back(obj); +} diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index 29b76ae0dd9..7a1433bc7fb 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -18,14 +18,14 @@ #ifndef TRINITY_SMARTSCRIPTMGR_H #define TRINITY_SMARTSCRIPTMGR_H -#include "Common.h" -#include "Creature.h" -#include "CreatureAI.h" -#include "Unit.h" -#include "Spell.h" +#include "Define.h" +#include "ObjectGuid.h" +#include +#include +#include -//#include "SmartScript.h" -//#include "SmartAI.h" +class WorldObject; +enum SpellEffIndex : uint8; struct WayPoint { @@ -646,7 +646,7 @@ struct SmartAction struct { - std::array emotes; + uint32 emotes[SMART_ACTION_PARAM_COUNT]; } randomEmote; struct @@ -739,7 +739,7 @@ struct SmartAction struct { - std::array phases; + uint32 phases[SMART_ACTION_PARAM_COUNT]; } randomPhase; struct @@ -930,7 +930,9 @@ struct SmartAction { uint32 entry; uint32 mask; - std::array slots; + uint32 slot1; + uint32 slot2; + uint32 slot3; } equip; struct @@ -964,7 +966,7 @@ struct SmartAction struct { - std::array actionLists; + uint32 actionLists[SMART_ACTION_PARAM_COUNT]; } randTimedActionList; struct @@ -1074,12 +1076,12 @@ struct SmartAction struct { - std::array wps; + uint32 wps[SMART_ACTION_PARAM_COUNT]; } closestWaypointFromList; struct { - std::array sounds; + uint32 sounds[SMART_ACTION_PARAM_COUNT - 1]; uint32 onlySelf; } randomSound; @@ -1500,12 +1502,7 @@ typedef std::vector ObjectVector; class ObjectGuidVector { public: - explicit ObjectGuidVector(ObjectVector const& objectVector) : _objectVector(objectVector) - { - _guidVector.reserve(_objectVector.size()); - for (WorldObject* obj : _objectVector) - _guidVector.push_back(obj->GetGUID()); - } + explicit ObjectGuidVector(ObjectVector const& objectVector); ObjectVector const* GetObjectVector(WorldObject const& ref) const { @@ -1520,14 +1517,7 @@ class ObjectGuidVector mutable ObjectVector _objectVector; //sanitize vector using _guidVector - void UpdateObjects(WorldObject const& ref) const - { - _objectVector.clear(); - - for (ObjectGuid const& guid : _guidVector) - if (WorldObject* obj = ObjectAccessor::GetWorldObject(ref, guid)) - _objectVector.push_back(obj); - } + void UpdateObjects(WorldObject const& ref) const; }; typedef std::unordered_map ObjectVectorMap; @@ -1575,42 +1565,11 @@ class TC_GAME_API SmartAIMgr void LoadSmartAIFromDB(); - SmartAIEventList GetScript(int32 entry, SmartScriptType type) - { - SmartAIEventList temp; - if (mEventMap[uint32(type)].find(entry) != mEventMap[uint32(type)].end()) - return mEventMap[uint32(type)][entry]; - else - { - if (entry > 0)//first search is for guid (negative), do not drop error if not found - TC_LOG_DEBUG("scripts.ai", "SmartAIMgr::GetScript: Could not load Script for Entry %d ScriptType %u.", entry, uint32(type)); - return temp; - } - } + SmartAIEventList GetScript(int32 entry, SmartScriptType type); - static SmartScriptHolder& FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId) - { - SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), - [eventId](SmartScriptHolder& source) { return source.link == eventId; }); + static SmartScriptHolder& FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId); - if (itr != list.end()) - return *itr; - - static SmartScriptHolder SmartScriptHolderDummy; - return SmartScriptHolderDummy; - } - - static SmartScriptHolder& FindLinkedEvent(SmartAIEventList& list, uint32 link) - { - SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), - [link](SmartScriptHolder& linked) { return linked.event_id == link && linked.GetEventType() == SMART_EVENT_LINK; }); - - if (itr != list.end()) - return *itr; - - static SmartScriptHolder SmartScriptHolderDummy; - return SmartScriptHolderDummy; - } + static SmartScriptHolder& FindLinkedEvent(SmartAIEventList& list, uint32 link); private: //event stores @@ -1619,127 +1578,19 @@ class TC_GAME_API SmartAIMgr bool IsEventValid(SmartScriptHolder& e); bool IsTargetValid(SmartScriptHolder const& e); - bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max) - { - if (max < min) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses min/max params wrong (%u/%u), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); - return false; - } - return true; - } - - /*inline bool IsPercentValid(SmartScriptHolder e, int32 pct) - { - if (pct < -100 || pct > 100) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u has invalid Percent set (%d), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), pct); - return false; - } - return true; - }*/ - - bool NotNULL(SmartScriptHolder const& e, uint32 data) - { - if (!data) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Parameter can not be NULL, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); - return false; - } - return true; - } - - bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sObjectMgr->GetCreatureTemplate(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsQuestValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sObjectMgr->GetQuestTemplate(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sObjectMgr->GetGameObjectTemplate(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsSpellValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sSpellMgr->GetSpellInfo(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsItemValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sItemStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Item entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sEmotesTextStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Text Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sEmotesStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sAreaTriggerStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent AreaTrigger entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsSoundValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sSoundEntriesStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Sound entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsTextValid(SmartScriptHolder const& e, uint32 id); + static bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max); + + static bool NotNULL(SmartScriptHolder const& e, uint32 data); + static bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry); + static bool IsQuestValid(SmartScriptHolder const& e, uint32 entry); + static bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry); + static bool IsSpellValid(SmartScriptHolder const& e, uint32 entry); + static bool IsItemValid(SmartScriptHolder const& e, uint32 entry); + static bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry); + static bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry); + static bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry); + static bool IsSoundValid(SmartScriptHolder const& e, uint32 entry); + static bool IsTextValid(SmartScriptHolder const& e, uint32 id); // Helpers void LoadHelperStores(); diff --git a/src/server/game/Accounts/AccountMgr.cpp b/src/server/game/Accounts/AccountMgr.cpp index 14b04856ce1..b7aebd74f0c 100644 --- a/src/server/game/Accounts/AccountMgr.cpp +++ b/src/server/game/Accounts/AccountMgr.cpp @@ -19,11 +19,14 @@ #include "AccountMgr.h" #include "Config.h" #include "DatabaseEnv.h" +#include "Log.h" #include "ObjectAccessor.h" #include "Player.h" +#include "Realm.h" #include "ScriptMgr.h" -#include "Util.h" #include "SHA1.h" +#include "Util.h" +#include "World.h" #include "WorldSession.h" AccountMgr::AccountMgr() { } @@ -438,7 +441,7 @@ void AccountMgr::LoadRBAC() } uint32 permissionId = 0; - rbac::RBACPermission* permission = NULL; + rbac::RBACPermission* permission = nullptr; do { @@ -470,12 +473,12 @@ void AccountMgr::LoadRBAC() } uint8 secId = 255; - rbac::RBACPermissionContainer* permissions = NULL; + rbac::RBACPermissionContainer* permissions = nullptr; do { Field* field = result->Fetch(); uint32 newId = field[0].GetUInt32(); - if (secId != newId || permissions == NULL) + if (secId != newId || permissions == nullptr) { secId = newId; permissions = &_defaultPermissions[secId]; @@ -530,7 +533,7 @@ rbac::RBACPermission const* AccountMgr::GetRBACPermission(uint32 permissionId) c if (it != _permissions.end()) return it->second; - return NULL; + return nullptr; } bool AccountMgr::HasPermission(uint32 accountId, uint32 permissionId, uint32 realmId) diff --git a/src/server/game/Accounts/RBAC.cpp b/src/server/game/Accounts/RBAC.cpp index 951223a9257..bef26f25039 100644 --- a/src/server/game/Accounts/RBAC.cpp +++ b/src/server/game/Accounts/RBAC.cpp @@ -17,8 +17,9 @@ #include "RBAC.h" #include "AccountMgr.h" +#include "DatabaseEnv.h" #include "Log.h" -#include "QueryCallback.h" +#include namespace rbac { diff --git a/src/server/game/Accounts/RBAC.h b/src/server/game/Accounts/RBAC.h index c7096ecd628..cb547216841 100644 --- a/src/server/game/Accounts/RBAC.h +++ b/src/server/game/Accounts/RBAC.h @@ -40,7 +40,8 @@ #ifndef _RBAC_H #define _RBAC_H -#include "DatabaseEnv.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" #include #include #include diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index bc8400f4a73..4e6ed998687 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -17,12 +17,9 @@ */ #include "AchievementMgr.h" -#include "ArenaTeam.h" #include "ArenaTeamMgr.h" #include "Battleground.h" -#include "CellImpl.h" #include "ChatTextBuilder.h" -#include "Common.h" #include "DatabaseEnv.h" #include "DBCEnums.h" #include "DisableMgr.h" @@ -32,16 +29,20 @@ #include "Guild.h" #include "GuildMgr.h" #include "InstanceScript.h" +#include "Item.h" #include "Language.h" +#include "Log.h" +#include "Mail.h" #include "Map.h" #include "MapManager.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" #include "ScriptMgr.h" +#include "SpellInfo.h" #include "SpellMgr.h" #include "World.h" -#include "WorldPacket.h" +#include "WorldSession.h" bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) { @@ -323,7 +324,7 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un return !target->HealthAbovePct(health.percent); case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD: if (target && !target->IsAlive()) - if (const Player* player = target->ToPlayer()) + if (Player const* player = target->ToPlayer()) if (player->GetDeathTimer() != 0) // flag set == must be same team, not set == different team return (player->GetTeam() == source->GetTeam()) == (player_dead.own_team_flag != 0); @@ -622,7 +623,7 @@ void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult, PreparedQ continue; } - if (criteria->StartTimer && time_t(date + criteria->StartTimer) < time(NULL)) + if (criteria->StartTimer && time_t(date + criteria->StartTimer) < time(nullptr)) continue; CriteriaProgress& progress = m_criteriaProgress[id]; @@ -682,7 +683,7 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievement) WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8+4+8); data << GetPlayer()->GetPackGUID(); data << uint32(achievement->ID); - data.AppendPackedTime(time(NULL)); + data.AppendPackedTime(time(nullptr)); data << uint32(0); GetPlayer()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true); } @@ -721,7 +722,7 @@ static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = { 1057, 1107, 1108 }; /** * this function will be called whenever the user might have done a criteria relevant action */ -void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) +void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= nullptr*/) { if (type >= ACHIEVEMENT_CRITERIA_TYPE_TOTAL) { @@ -903,7 +904,7 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, ui { uint32 counter = 0; - const RewardedQuestSet &rewQuests = GetPlayer()->getRewardedQuests(); + RewardedQuestSet const& rewQuests = GetPlayer()->getRewardedQuests(); for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) { Quest const* quest = sObjectMgr->GetQuestTemplate(*itr); @@ -1325,7 +1326,7 @@ CriteriaProgress* AchievementMgr::GetCriteriaProgress(AchievementCriteriaEntry c CriteriaProgressMap::iterator iter = m_criteriaProgress.find(entry->ID); if (iter == m_criteriaProgress.end()) - return NULL; + return nullptr; return &(iter->second); } @@ -1378,7 +1379,7 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entry, } progress->changed = true; - progress->date = time(NULL); // set the date to the latest update. + progress->date = time(nullptr); // set the date to the latest update. uint32 timeElapsed = 0; bool timedCompleted = false; @@ -1494,7 +1495,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) SendAchievementEarned(achievement); CompletedAchievementData& ca = m_completedAchievements[achievement->ID]; - ca.date = time(NULL); + ca.date = time(nullptr); ca.changed = true; if (achievement->Flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) @@ -1531,7 +1532,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) std::string text = reward->Text; LocaleConstant localeConstant = GetPlayer()->GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement)) { @@ -1545,7 +1546,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achievement) SQLTransaction trans = CharacterDatabase.BeginTransaction(); - Item* item = reward->ItemID ? Item::CreateItem(reward->ItemID, 1, GetPlayer()) : NULL; + Item* item = reward->ItemID ? Item::CreateItem(reward->ItemID, 1, GetPlayer()) : nullptr; if (item) { // save new item before send @@ -1564,7 +1565,7 @@ void AchievementMgr::SendAllAchievementData() const { WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA, m_completedAchievements.size()*8+4+m_criteriaProgress.size()*38+4); BuildAllDataPacket(&data); - GetPlayer()->GetSession()->SendPacket(&data); + GetPlayer()->SendDirectMessage(&data); } void AchievementMgr::SendRespondInspectAchievements(Player* player) const @@ -1572,7 +1573,7 @@ void AchievementMgr::SendRespondInspectAchievements(Player* player) const WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS, 9+m_completedAchievements.size()*8+4+m_criteriaProgress.size()*38+4); data << GetPlayer()->GetPackGUID(); BuildAllDataPacket(&data); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } /** @@ -2510,7 +2511,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() continue; } - if (!GetCriteriaDataSet(criteria) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, entryId, NULL)) + if (!GetCriteriaDataSet(criteria) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, entryId, nullptr)) TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` does not contain expected data for criteria (Entry: %u Type: %u) for achievement %u.", criteria->ID, criteria->Type, criteria->ReferredAchievement); } @@ -2542,7 +2543,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() Field* fields = result->Fetch(); uint16 achievementId = fields[0].GetUInt16(); - const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementId); if (!achievement) { // Remove non-existing achievements from all characters diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index e4b994fcb5f..2f0f30b2408 100644 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -19,14 +19,13 @@ #ifndef __TRINITY_ACHIEVEMENTMGR_H #define __TRINITY_ACHIEVEMENTMGR_H -#include -#include - -#include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "DBCEnums.h" #include "DBCStores.h" #include "ObjectGuid.h" +#include +#include +#include class Unit; class Player; @@ -282,7 +281,7 @@ class TC_GAME_API AchievementMgr void LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult); void SaveToDB(SQLTransaction& trans); void ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = NULL); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); void CompletedAchievement(AchievementEntry const* entry); void CheckAllAchievementCriteria(); void SendAllAchievementData() const; @@ -342,31 +341,31 @@ class TC_GAME_API AchievementGlobalMgr AchievementCriteriaEntryList const* GetAchievementCriteriaByAchievement(uint32 id) const { AchievementCriteriaListByAchievement::const_iterator itr = m_AchievementCriteriaListByAchievement.find(id); - return itr != m_AchievementCriteriaListByAchievement.end() ? &itr->second : NULL; + return itr != m_AchievementCriteriaListByAchievement.end() ? &itr->second : nullptr; } AchievementEntryList const* GetAchievementByReferencedId(uint32 id) const { AchievementListByReferencedId::const_iterator itr = m_AchievementListByReferencedId.find(id); - return itr != m_AchievementListByReferencedId.end() ? &itr->second : NULL; + return itr != m_AchievementListByReferencedId.end() ? &itr->second : nullptr; } AchievementReward const* GetAchievementReward(AchievementEntry const* achievement) const { AchievementRewards::const_iterator iter = m_achievementRewards.find(achievement->ID); - return iter != m_achievementRewards.end() ? &iter->second : NULL; + return iter != m_achievementRewards.end() ? &iter->second : nullptr; } AchievementRewardLocale const* GetAchievementRewardLocale(AchievementEntry const* achievement) const { AchievementRewardLocales::const_iterator iter = m_achievementRewardLocales.find(achievement->ID); - return iter != m_achievementRewardLocales.end() ? &iter->second : NULL; + return iter != m_achievementRewardLocales.end() ? &iter->second : nullptr; } AchievementCriteriaDataSet const* GetCriteriaDataSet(AchievementCriteriaEntry const* achievementCriteria) const { AchievementCriteriaDataMap::const_iterator iter = m_criteriaDataMap.find(achievementCriteria->ID); - return iter != m_criteriaDataMap.end() ? &iter->second : NULL; + return iter != m_criteriaDataMap.end() ? &iter->second : nullptr; } bool IsRealmCompleted(AchievementEntry const* achievement) const; diff --git a/src/server/game/Addons/AddonMgr.cpp b/src/server/game/Addons/AddonMgr.cpp index 7371cfb5f4f..075daabce78 100644 --- a/src/server/game/Addons/AddonMgr.cpp +++ b/src/server/game/Addons/AddonMgr.cpp @@ -119,7 +119,7 @@ SavedAddon const* GetAddonInfo(const std::string& name) return &addon; } - return NULL; + return nullptr; } BannedAddonList const* GetBannedAddons() diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index a6ff7f558a7..1dabff8a76e 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -16,23 +16,27 @@ * with this program. If not, see . */ +#include "AuctionHouseMgr.h" +#include "AuctionHouseBot.h" +#include "AccountMgr.h" +#include "Bag.h" #include "Common.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "World.h" -#include "WorldPacket.h" -#include "WorldSession.h" +#include "CharacterCache.h" #include "DatabaseEnv.h" #include "DBCStores.h" -#include "ScriptMgr.h" -#include "AccountMgr.h" -#include "AuctionHouseMgr.h" -#include "AuctionHouseBot.h" +#include "GameTime.h" #include "Item.h" #include "Language.h" #include "Log.h" -#include "CharacterCache.h" -#include "GameTime.h" +#include "Mail.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Realm.h" +#include "ScriptMgr.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" enum eAuctionHouse { @@ -437,7 +441,7 @@ bool AuctionHouseMgr::PendingAuctionAdd(Player* player, AuctionEntry* aEntry, It return true; } -uint32 AuctionHouseMgr::PendingAuctionCount(const Player* player) const +uint32 AuctionHouseMgr::PendingAuctionCount(Player const* player) const { auto const itr = pendingAuctionMap.find(player->GetGUID()); if (itr != pendingAuctionMap.end()) @@ -523,7 +527,7 @@ void AuctionHouseMgr::UpdatePendingAuctions() { AuctionEntry* AH = (*AHitr); ++AHitr; - AH->expire_time = time(NULL); + AH->expire_time = time(nullptr); AH->DeleteFromDB(trans); AH->SaveToDB(trans); } @@ -754,7 +758,7 @@ void AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player continue; // local name - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (ItemLocale const* il = sObjectMgr->GetItemLocale(proto->ItemId)) ObjectMgr::GetLocaleString(il->Name, localeConstant, name); @@ -773,13 +777,13 @@ void AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player if (propRefID < 0) { - const ItemRandomSuffixEntry* itemRandSuffix = sItemRandomSuffixStore.LookupEntry(-propRefID); + ItemRandomSuffixEntry const* itemRandSuffix = sItemRandomSuffixStore.LookupEntry(-propRefID); if (itemRandSuffix) suffix = itemRandSuffix->nameSuffix; } else { - const ItemRandomPropertiesEntry* itemRandProp = sItemRandomPropertiesStore.LookupEntry(propRefID); + ItemRandomPropertiesEntry const* itemRandProp = sItemRandomPropertiesStore.LookupEntry(propRefID); if (itemRandProp) suffix = itemRandProp->nameSuffix; } @@ -838,7 +842,7 @@ bool AuctionEntry::BuildAuctionInfo(WorldPacket& data, Item* sourceItem) const data << uint32(bid ? GetAuctionOutBid() : 0); // Minimal outbid data << uint32(buyout); // Auction->buyout - data << uint32((expire_time - time(NULL)) * IN_MILLISECONDS); // time left + data << uint32((expire_time - time(nullptr)) * IN_MILLISECONDS); // time left data << uint64(bidder); // auction->bidder current data << uint32(bid); // current bid return true; diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.h b/src/server/game/AuctionHouse/AuctionHouseMgr.h index fb3f11052bc..2fad4264d15 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.h +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.h @@ -19,14 +19,17 @@ #ifndef _AUCTION_HOUSE_MGR_H #define _AUCTION_HOUSE_MGR_H -#include "Common.h" -#include "DatabaseEnv.h" -#include "DBCStructure.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include "ObjectGuid.h" +#include #include +#include class Item; class Player; class WorldPacket; +struct AuctionHouseEntry; #define MIN_AUCTION_TIME (12*HOUR) #define MAX_AUCTION_ITEMS 160 @@ -121,7 +124,7 @@ class TC_GAME_API AuctionHouseObject AuctionEntry* GetAuction(uint32 id) const { AuctionEntryMap::const_iterator itr = AuctionsMap.find(id); - return itr != AuctionsMap.end() ? itr->second : NULL; + return itr != AuctionsMap.end() ? itr->second : nullptr; } void AddAuction(AuctionEntry* auction); @@ -169,7 +172,7 @@ class TC_GAME_API AuctionHouseMgr if (itr != mAitems.end()) return itr->second; - return NULL; + return nullptr; } //auction messages @@ -192,7 +195,7 @@ class TC_GAME_API AuctionHouseMgr void AddAItem(Item* it); bool RemoveAItem(ObjectGuid::LowType id, bool deleteItem = false, SQLTransaction* trans = nullptr); bool PendingAuctionAdd(Player* player, AuctionEntry* aEntry, Item* item); - uint32 PendingAuctionCount(const Player* player) const; + uint32 PendingAuctionCount(Player const* player) const; void PendingAuctionProcess(Player* player); void UpdatePendingAuctions(); void Update(); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp index c7724fa144a..4b433930e93 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp @@ -15,17 +15,18 @@ * with this program. If not, see . */ -#include "Containers.h" -#include "Log.h" -#include "Item.h" -#include "World.h" -#include "Config.h" -#include "AccountMgr.h" -#include "AuctionHouseMgr.h" #include "AuctionHouseBot.h" +#include "AccountMgr.h" #include "AuctionHouseBotBuyer.h" #include "AuctionHouseBotSeller.h" +#include "AuctionHouseMgr.h" +#include "Config.h" +#include "Containers.h" +#include "DatabaseEnv.h" #include "GameTime.h" +#include "Item.h" +#include "Log.h" +#include "World.h" AuctionBotConfig* AuctionBotConfig::instance() { diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBot.h b/src/server/game/AuctionHouseBot/AuctionHouseBot.h index 73cfd764946..162647c58bc 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBot.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBot.h @@ -19,6 +19,9 @@ #define AUCTION_HOUSE_BOT_H #include "Define.h" +#include "SharedDefines.h" +#include +#include class AuctionBotSeller; class AuctionBotBuyer; @@ -211,8 +214,8 @@ public: static AuctionBotConfig* instance(); bool Initialize(); - const std::string& GetAHBotIncludes() const { return _AHBotIncludes; } - const std::string& GetAHBotExcludes() const { return _AHBotExcludes; } + std::string const& GetAHBotIncludes() const { return _AHBotIncludes; } + std::string const& GetAHBotExcludes() const { return _AHBotExcludes; } uint32 GetConfig(AuctionBotConfigUInt32Values index) const { return _configUint32Values[index]; } bool GetConfig(AuctionBotConfigBoolValues index) const { return _configBoolValues[index]; } diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp index 8396ab94622..4d7ad22eef5 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp @@ -15,10 +15,12 @@ * with this program. If not, see . */ -#include "Log.h" +#include "AuctionHouseBotBuyer.h" +#include "DatabaseEnv.h" #include "Item.h" #include "ItemTemplate.h" -#include "AuctionHouseBotBuyer.h" +#include "Log.h" +#include "Random.h" AuctionBotBuyer::AuctionBotBuyer() : _checkInterval(20 * MINUTE) { @@ -156,7 +158,7 @@ uint32 AuctionBotBuyer::GetItemInformation(BuyerConfiguration& config) } // ahInfo can be NULL -bool AuctionBotBuyer::RollBuyChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 /*bidPrice*/) +bool AuctionBotBuyer::RollBuyChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 /*bidPrice*/) { if (!auction->buyout) return false; @@ -195,7 +197,7 @@ bool AuctionBotBuyer::RollBuyChance(const BuyerItemInfo* ahInfo, const Item* ite } // ahInfo can be NULL -bool AuctionBotBuyer::RollBidChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 bidPrice) +bool AuctionBotBuyer::RollBidChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 bidPrice) { float itemBidPrice = float(bidPrice / item->GetCount()); float itemPrice = float(item->GetTemplate()->SellPrice ? item->GetTemplate()->SellPrice : GetVendorPrice(item->GetTemplate()->Quality)); @@ -306,7 +308,7 @@ void AuctionBotBuyer::BuyAndBidItems(BuyerConfiguration& config) bidPrice = auction->startbid; } - const BuyerItemInfo* ahInfo = nullptr; + BuyerItemInfo const* ahInfo = nullptr; BuyerItemInfoMap::const_iterator sameItemItr = config.SameItemInfo.find(item->GetEntry()); if (sameItemItr != config.SameItemInfo.end()) ahInfo = &sameItemItr->second; @@ -392,7 +394,7 @@ void AuctionBotBuyer::BuyEntry(AuctionEntry* auction, AuctionHouseObject* auctio // Send mail to previous bidder if any if (auction->bidder && !sAuctionBotConfig->IsBotChar(auction->bidder)) - sAuctionMgr->SendAuctionOutbiddedMail(auction, auction->buyout, NULL, trans); + sAuctionMgr->SendAuctionOutbiddedMail(auction, auction->buyout, nullptr, trans); // Set bot as bidder and set new bid amount auction->bidder = sAuctionBotConfig->GetRandCharExclude(auction->owner); @@ -423,7 +425,7 @@ void AuctionBotBuyer::PlaceBidToEntry(AuctionEntry* auction, uint32 bidPrice) // Send mail to previous bidder if any if (auction->bidder && !sAuctionBotConfig->IsBotChar(auction->bidder)) - sAuctionMgr->SendAuctionOutbiddedMail(auction, bidPrice, NULL, trans); + sAuctionMgr->SendAuctionOutbiddedMail(auction, bidPrice, nullptr, trans); // Set bot as bidder and set new bid amount auction->bidder = sAuctionBotConfig->GetRandCharExclude(auction->owner); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h index ba4326ffabf..1770451f323 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h @@ -86,8 +86,8 @@ private: void LoadBuyerValues(BuyerConfiguration& config); // ahInfo can be NULL - bool RollBuyChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 bidPrice); - bool RollBidChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 bidPrice); + bool RollBuyChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 bidPrice); + bool RollBidChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 bidPrice); void PlaceBidToEntry(AuctionEntry* auction, uint32 bidPrice); void BuyEntry(AuctionEntry* auction, AuctionHouseObject* auctionHouse); void PrepareListOfEntry(BuyerConfiguration& config); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp index 6fd11aa6406..7c1ba67d547 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp @@ -15,12 +15,16 @@ * with this program. If not, see . */ -#include "Log.h" +#include "AuctionHouseBotSeller.h" +#include "AuctionHouseMgr.h" #include "Containers.h" +#include "DatabaseEnv.h" #include "DBCStores.h" +#include "Item.h" +#include "Log.h" #include "ObjectMgr.h" -#include "AuctionHouseMgr.h" -#include "AuctionHouseBotSeller.h" +#include "Random.h" +#include AuctionBotSeller::AuctionBotSeller() { @@ -62,13 +66,9 @@ bool AuctionBotSeller::Initialize() TC_LOG_DEBUG("ahbot", "Loading npc vendor items for filter.."); CreatureTemplateContainer const* creatures = sObjectMgr->GetCreatureTemplates(); for (CreatureTemplateContainer::const_iterator it = creatures->begin(); it != creatures->end(); ++it) - { if (VendorItemData const* data = sObjectMgr->GetNpcVendorItemList(it->first)) - { - for (VendorItemList::const_iterator it2 = data->m_items.begin(); it2 != data->m_items.end(); ++it2) - npcItems.insert((*it2)->item); - } - } + for (VendorItem const& it2 : data->m_items) + npcItems.insert(it2.item); TC_LOG_DEBUG("ahbot", "Npc vendor filter has %u items", (uint32)npcItems.size()); @@ -108,7 +108,6 @@ bool AuctionBotSeller::Initialize() for (uint32 itemId = 0; itemId < sItemStore.GetNumRows(); ++itemId) { ItemTemplate const* prototype = sObjectMgr->GetItemTemplate(itemId); - if (!prototype) continue; @@ -890,7 +889,7 @@ void AuctionBotSeller::AddNewAuctions(SellerConfiguration& config) // Update the just created item so that if it needs random properties it has them. // Ex: Notched Shortsword of Stamina will only generate as a Notched Shortsword without this. - if (int32 randomPropertyId = Item::GenerateItemRandomPropertyId(itemId)) + if (int32 randomPropertyId = GenerateItemRandomPropertyId(itemId)) item->SetItemRandomProperties(randomPropertyId); uint32 buyoutPrice; @@ -927,7 +926,7 @@ void AuctionBotSeller::AddNewAuctions(SellerConfiguration& config) auctionEntry->bid = 0; auctionEntry->deposit = sAuctionMgr->GetAuctionDeposit(ahEntry, etime, item, stackCount); auctionEntry->auctionHouseEntry = ahEntry; - auctionEntry->expire_time = time(NULL) + urand(config.GetMinTime(), config.GetMaxTime()) * HOUR; + auctionEntry->expire_time = time(nullptr) + urand(config.GetMinTime(), config.GetMaxTime()) * HOUR; item->SaveToDB(trans); sAuctionMgr->AddAItem(item); diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index 2c75d75f0b4..27e83185e27 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -20,15 +20,18 @@ #include "Battleground.h" #include "CellImpl.h" #include "CreatureTextMgr.h" +#include "DBCStores.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "GroupMgr.h" +#include "Log.h" #include "Map.h" #include "MapManager.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "WorldPacket.h" +#include Battlefield::Battlefield() { @@ -563,7 +566,7 @@ BfGraveyard* Battlefield::GetGraveyardById(uint32 id) const return nullptr; } -WorldSafeLocsEntry const* Battlefield::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* Battlefield::GetClosestGraveyard(Player* player) { BfGraveyard* closestGY = nullptr; float maxdist = -1; @@ -738,7 +741,7 @@ void BfGraveyard::RelocateDeadPlayers() player->TeleportTo(player->GetMapId(), closestGrave->x, closestGrave->y, closestGrave->z, player->GetOrientation()); else { - closestGrave = m_Bf->GetClosestGraveYard(player); + closestGrave = m_Bf->GetClosestGraveyard(player); if (closestGrave) player->TeleportTo(player->GetMapId(), closestGrave->x, closestGrave->y, closestGrave->z, player->GetOrientation()); } @@ -794,7 +797,7 @@ Creature* Battlefield::SpawnCreature(uint32 entry, Position const& pos) } // Method for spawning gameobject on map -GameObject* Battlefield::SpawnGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot) +GameObject* Battlefield::SpawnGameObject(uint32 entry, Position const& pos, QuaternionData const& rot) { // Get map object Map* map = sMapMgr->CreateBaseMap(m_MapId); diff --git a/src/server/game/Battlefield/Battlefield.h b/src/server/game/Battlefield/Battlefield.h index 2889a53a3be..0ede10657e6 100644 --- a/src/server/game/Battlefield/Battlefield.h +++ b/src/server/game/Battlefield/Battlefield.h @@ -18,8 +18,10 @@ #ifndef BATTLEFIELD_H_ #define BATTLEFIELD_H_ +#include "Position.h" #include "SharedDefines.h" #include "ZoneScript.h" +#include enum BattlefieldTypes { @@ -55,14 +57,17 @@ enum BattlefieldTimers }; // some class predefs -class Player; -class GameObject; -class WorldPacket; -class Creature; -class Unit; - class Battlefield; class BfGraveyard; +class Creature; +class GameObject; +class Group; +class Map; +class Player; +class Unit; +class WorldPacket; +struct QuaternionData; +struct WorldSafeLocsEntry; typedef std::vector GraveyardVect; typedef std::map PlayerTimerMap; @@ -272,7 +277,7 @@ class TC_GAME_API Battlefield : public ZoneScript // Graveyard methods // Find which graveyard the player must be teleported to to be resurrected by spiritguide - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player); + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player); virtual void AddPlayerToResurrectQueue(ObjectGuid npc_guid, ObjectGuid player_guid); void RemovePlayerFromResurrectQueue(ObjectGuid player_guid); @@ -281,7 +286,7 @@ class TC_GAME_API Battlefield : public ZoneScript // Misc methods Creature* SpawnCreature(uint32 entry, Position const& pos); - GameObject* SpawnGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot); + GameObject* SpawnGameObject(uint32 entry, Position const& pos, QuaternionData const& rot); Creature* GetCreature(ObjectGuid guid); GameObject* GetGameObject(ObjectGuid guid); @@ -405,7 +410,7 @@ class TC_GAME_API Battlefield : public ZoneScript Battlefield::BfCapturePointMap::const_iterator itr = m_capturePoints.find(lowguid); if (itr != m_capturePoints.end()) return itr->second; - return NULL; + return nullptr; } void RegisterZone(uint32 zoneid); diff --git a/src/server/game/Battlefield/BattlefieldMgr.cpp b/src/server/game/Battlefield/BattlefieldMgr.cpp index 5130dafa254..fde19810bfd 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.cpp +++ b/src/server/game/Battlefield/BattlefieldMgr.cpp @@ -17,6 +17,7 @@ #include "BattlefieldMgr.h" #include "BattlefieldWG.h" +#include "Log.h" #include "Player.h" BattlefieldMgr::BattlefieldMgr() diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp index edb1753b01f..bd5f47f67c9 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp @@ -21,14 +21,19 @@ #include "BattlefieldWG.h" #include "AchievementMgr.h" -#include "CreatureTextMgr.h" #include "Battleground.h" +#include "CreatureTextMgr.h" +#include "GameObject.h" +#include "Log.h" #include "MapManager.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "Random.h" #include "SpellAuras.h" #include "TemporarySummon.h" +#include "World.h" #include "WorldSession.h" struct BfWGCoordGY @@ -40,7 +45,7 @@ struct BfWGCoordGY }; // 7 in sql, 7 in header -BfWGCoordGY const WGGraveYard[BATTLEFIELD_WG_GRAVEYARD_MAX] = +BfWGCoordGY const WGGraveyard[BATTLEFIELD_WG_GRAVEYARD_MAX] = { { { 5104.750f, 2300.940f, 368.579f, 0.733038f }, 1329, BATTLEFIELD_WG_GOSSIPTEXT_GY_NE, TEAM_NEUTRAL }, { { 5099.120f, 3466.036f, 368.484f, 5.317802f }, 1330, BATTLEFIELD_WG_GOSSIPTEXT_GY_NW, TEAM_NEUTRAL }, @@ -57,7 +62,7 @@ uint32 const WintergraspFaction[] = { FACTION_ALLIANCE_GENERIC_WG, FACTION_ Position const WintergraspStalkerPos = { 4948.985f, 2937.789f, 550.5172f, 1.815142f }; Position const WintergraspRelicPos = { 5440.379f, 2840.493f, 430.2816f, -1.832595f }; -G3D::Quat const WintergraspRelicRot = { 0.f, 0.f, -0.7933531f, 0.6087617f }; +QuaternionData const WintergraspRelicRot = { 0.f, 0.f, -0.7933531f, 0.6087617f }; uint8 const WG_MAX_OBJ = 32; uint8 const WG_MAX_TURRET = 15; @@ -74,7 +79,7 @@ struct WintergraspBuildingSpawnData uint32 entry; uint32 WorldState; Position pos; - G3D::Quat rot; + QuaternionData rot; WintergraspGameObjectBuildingType type; }; @@ -177,7 +182,7 @@ struct WintergraspObjectPositionData struct WintergraspGameObjectData { Position Pos; - G3D::Quat Rot; + QuaternionData Rot; uint32 HordeEntry; uint32 AllianceEntry; }; @@ -431,7 +436,7 @@ bool BattlefieldWG::SetupBattlefield() m_saveTimer = 60000; - // Init GraveYards + // Init Graveyards SetGraveyardNumber(BATTLEFIELD_WG_GRAVEYARD_MAX); // Load from db @@ -463,12 +468,12 @@ bool BattlefieldWG::SetupBattlefield() BfGraveyardWG* graveyard = new BfGraveyardWG(this); // When between games, the graveyard is controlled by the defending team - if (WGGraveYard[i].StartControl == TEAM_NEUTRAL) - graveyard->Initialize(m_DefenderTeam, WGGraveYard[i].GraveyardID); + if (WGGraveyard[i].StartControl == TEAM_NEUTRAL) + graveyard->Initialize(m_DefenderTeam, WGGraveyard[i].GraveyardID); else - graveyard->Initialize(WGGraveYard[i].StartControl, WGGraveYard[i].GraveyardID); + graveyard->Initialize(WGGraveyard[i].StartControl, WGGraveyard[i].GraveyardID); - graveyard->SetTextId(WGGraveYard[i].TextID); + graveyard->SetTextId(WGGraveyard[i].TextID); m_GraveyardList[i] = graveyard; } diff --git a/src/server/game/Battlegrounds/Arena.cpp b/src/server/game/Battlegrounds/Arena.cpp index fb4f6b965ca..b9ec40c7f13 100644 --- a/src/server/game/Battlegrounds/Arena.cpp +++ b/src/server/game/Battlegrounds/Arena.cpp @@ -19,11 +19,45 @@ #include "ArenaScore.h" #include "ArenaTeamMgr.h" #include "Language.h" +#include "Log.h" #include "ObjectAccessor.h" #include "Player.h" #include "World.h" #include "WorldSession.h" +void ArenaScore::AppendToPacket(WorldPacket& data) +{ + data << uint64(PlayerGuid); + + data << uint32(KillingBlows); + data << uint8(TeamId); + data << uint32(DamageDone); + data << uint32(HealingDone); + + BuildObjectivesBlock(data); +} + +void ArenaScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(0); // Objectives Count +} + +void ArenaTeamScore::BuildRatingInfoBlock(WorldPacket& data) +{ + uint32 ratingLost = std::abs(std::min(RatingChange, 0)); + uint32 ratingWon = std::max(RatingChange, 0); + + // should be old rating, new rating, and client will calculate rating change itself + data << uint32(ratingLost); + data << uint32(ratingWon); + data << uint32(MatchmakerRating); +} + +void ArenaTeamScore::BuildTeamInfoBlock(WorldPacket& data) +{ + data << TeamName; +} + Arena::Arena() { StartDelayTimes[BG_STARTING_EVENT_FIRST] = BG_START_DELAY_1M; @@ -144,17 +178,17 @@ void Arena::EndBattleground(uint32 winner) // In case of arena draw, follow this logic: // winnerArenaTeam => ALLIANCE, loserArenaTeam => HORDE - ArenaTeam* winnerArenaTeam = sArenaTeamMgr->GetArenaTeamById(GetArenaTeamIdForTeam(winner == 0 ? ALLIANCE : winner)); - ArenaTeam* loserArenaTeam = sArenaTeamMgr->GetArenaTeamById(GetArenaTeamIdForTeam(winner == 0 ? HORDE : GetOtherTeam(winner))); + ArenaTeam* winnerArenaTeam = sArenaTeamMgr->GetArenaTeamById(GetArenaTeamIdForTeam(winner == 0 ? uint32(ALLIANCE) : winner)); + ArenaTeam* loserArenaTeam = sArenaTeamMgr->GetArenaTeamById(GetArenaTeamIdForTeam(winner == 0 ? uint32(HORDE) : GetOtherTeam(winner))); if (winnerArenaTeam && loserArenaTeam && winnerArenaTeam != loserArenaTeam) { // In case of arena draw, follow this logic: // winnerMatchmakerRating => ALLIANCE, loserMatchmakerRating => HORDE loserTeamRating = loserArenaTeam->GetRating(); - loserMatchmakerRating = GetArenaMatchmakerRating(winner == 0 ? HORDE : GetOtherTeam(winner)); + loserMatchmakerRating = GetArenaMatchmakerRating(winner == 0 ? uint32(HORDE) : GetOtherTeam(winner)); winnerTeamRating = winnerArenaTeam->GetRating(); - winnerMatchmakerRating = GetArenaMatchmakerRating(winner == 0 ? ALLIANCE : winner); + winnerMatchmakerRating = GetArenaMatchmakerRating(winner == 0 ? uint32(ALLIANCE) : winner); if (winner != 0) { diff --git a/src/server/game/Battlegrounds/ArenaScore.h b/src/server/game/Battlegrounds/ArenaScore.h index a2914337322..f4ab82034cf 100644 --- a/src/server/game/Battlegrounds/ArenaScore.h +++ b/src/server/game/Battlegrounds/ArenaScore.h @@ -19,7 +19,7 @@ #define TRINITY_ARENA_SCORE_H #include "BattlegroundScore.h" -#include "SharedDefines.h" +#include struct TC_GAME_API ArenaScore : public BattlegroundScore { @@ -28,22 +28,8 @@ struct TC_GAME_API ArenaScore : public BattlegroundScore protected: ArenaScore(ObjectGuid playerGuid, uint32 team) : BattlegroundScore(playerGuid), TeamId(team == ALLIANCE ? BG_TEAM_ALLIANCE : BG_TEAM_HORDE) { } - void AppendToPacket(WorldPacket& data) final override - { - data << uint64(PlayerGuid); - - data << uint32(KillingBlows); - data << uint8(TeamId); - data << uint32(DamageDone); - data << uint32(HealingDone); - - BuildObjectivesBlock(data); - } - - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(0); // Objectives Count - } + void AppendToPacket(WorldPacket& data) final override; + void BuildObjectivesBlock(WorldPacket& data) final override; // For Logging purpose std::string ToString() const override @@ -80,21 +66,8 @@ struct TC_GAME_API ArenaTeamScore TeamName = teamName; } - void BuildRatingInfoBlock(WorldPacket& data) - { - uint32 ratingLost = std::abs(std::min(RatingChange, 0)); - uint32 ratingWon = std::max(RatingChange, 0); - - // should be old rating, new rating, and client will calculate rating change itself - data << uint32(ratingLost); - data << uint32(ratingWon); - data << uint32(MatchmakerRating); - } - - void BuildTeamInfoBlock(WorldPacket& data) - { - data << TeamName; - } + void BuildRatingInfoBlock(WorldPacket& data); + void BuildTeamInfoBlock(WorldPacket& data); int32 RatingChange; uint32 MatchmakerRating; diff --git a/src/server/game/Battlegrounds/ArenaTeam.cpp b/src/server/game/Battlegrounds/ArenaTeam.cpp index 1c5a2dac3eb..cda870fdba8 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.cpp +++ b/src/server/game/Battlegrounds/ArenaTeam.cpp @@ -16,16 +16,19 @@ * with this program. If not, see . */ +#include "ArenaTeam.h" +#include "ArenaTeamMgr.h" +#include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "Group.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "WorldPacket.h" -#include "ArenaTeam.h" #include "World.h" -#include "Group.h" -#include "ArenaTeamMgr.h" +#include "WorldPacket.h" #include "WorldSession.h" -#include "Opcodes.h" -#include "CharacterCache.h" ArenaTeam::ArenaTeam() : TeamId(0), Type(0), TeamName(), CaptainGuid(), BackgroundColor(0), EmblemStyle(0), EmblemColor(0), @@ -399,7 +402,7 @@ void ArenaTeam::Disband() void ArenaTeam::Roster(WorldSession* session) { - Player* player = NULL; + Player* player = nullptr; uint8 unk308 = 0; @@ -516,7 +519,7 @@ void ArenaTeam::BroadcastPacket(WorldPacket* packet) { for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) if (Player* player = ObjectAccessor::FindConnectedPlayer(itr->Guid)) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, ObjectGuid guid, uint8 strCount, std::string const& str1, std::string const& str2, std::string const& str3) @@ -811,7 +814,7 @@ void ArenaTeam::OfflineMemberLost(ObjectGuid guid, uint32 againstMatchmakerRatin { // update personal rating int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, false); - itr->ModifyPersonalRating(NULL, mod, GetType()); + itr->ModifyPersonalRating(nullptr, mod, GetType()); // update matchmaker rating itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot()); @@ -960,7 +963,7 @@ ArenaTeamMember* ArenaTeam::GetMember(const std::string& name) if (itr->Name == name) return &(*itr); - return NULL; + return nullptr; } ArenaTeamMember* ArenaTeam::GetMember(ObjectGuid guid) @@ -969,5 +972,5 @@ ArenaTeamMember* ArenaTeam::GetMember(ObjectGuid guid) if (itr->Guid == guid) return &(*itr); - return NULL; + return nullptr; } diff --git a/src/server/game/Battlegrounds/ArenaTeam.h b/src/server/game/Battlegrounds/ArenaTeam.h index c88afc8c65e..38f2b7daaaa 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.h +++ b/src/server/game/Battlegrounds/ArenaTeam.h @@ -131,7 +131,7 @@ class TC_GAME_API ArenaTeam static uint8 GetSlotByType(uint32 type); ObjectGuid GetCaptain() const { return CaptainGuid; } std::string const& GetName() const { return TeamName; } - const ArenaTeamStats& GetStats() const { return Stats; } + ArenaTeamStats const& GetStats() const { return Stats; } uint32 GetRating() const { return Stats.Rating; } uint32 GetAverageMMR(Group* group) const; diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp index 3e991c1a1b7..56749e0bf4f 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp @@ -48,7 +48,7 @@ ArenaTeam* ArenaTeamMgr::GetArenaTeamById(uint32 arenaTeamId) const if (itr != ArenaTeamStore.end()) return itr->second; - return NULL; + return nullptr; } ArenaTeam* ArenaTeamMgr::GetArenaTeamByName(const std::string& arenaTeamName) const @@ -62,7 +62,7 @@ ArenaTeam* ArenaTeamMgr::GetArenaTeamByName(const std::string& arenaTeamName) co if (search == teamName) return itr->second; } - return NULL; + return nullptr; } ArenaTeam* ArenaTeamMgr::GetArenaTeamByCaptain(ObjectGuid guid) const @@ -71,7 +71,7 @@ ArenaTeam* ArenaTeamMgr::GetArenaTeamByCaptain(ObjectGuid guid) const if (itr->second->GetCaptain() == guid) return itr->second; - return NULL; + return nullptr; } void ArenaTeamMgr::AddArenaTeam(ArenaTeam* arenaTeam) @@ -127,7 +127,7 @@ void ArenaTeamMgr::LoadArenaTeams() if (!newArenaTeam->LoadArenaTeamFromDB(result) || !newArenaTeam->LoadMembersFromDB(result2)) { - newArenaTeam->Disband(NULL); + newArenaTeam->Disband(nullptr); delete newArenaTeam; continue; } diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.h b/src/server/game/Battlegrounds/ArenaTeamMgr.h index b5769c0c536..1663ee54711 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.h +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.h @@ -19,6 +19,7 @@ #define _ARENATEAMMGR_H #include "ArenaTeam.h" +#include class TC_GAME_API ArenaTeamMgr { diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index 6a2275ed415..41591c419e9 100644 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -16,32 +16,50 @@ * with this program. If not, see . */ -#include "ArenaScore.h" #include "Battleground.h" +#include "ArenaScore.h" #include "BattlegroundMgr.h" #include "BattlegroundScore.h" +#include "Chat.h" #include "Creature.h" #include "CreatureTextMgr.h" -#include "Chat.h" +#include "DatabaseEnv.h" #include "Formulas.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "Object.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" #include "SpellAuras.h" +#include "TemporarySummon.h" +#include "Transport.h" #include "Util.h" #include "WorldPacket.h" -#include "Transport.h" -#include "GameTime.h" +#include + +void BattlegroundScore::AppendToPacket(WorldPacket& data) +{ + data << uint64(PlayerGuid); + + data << uint32(KillingBlows); + data << uint32(HonorableKills); + data << uint32(Deaths); + data << uint32(BonusHonor); + data << uint32(DamageDone); + data << uint32(HealingDone); + + BuildObjectivesBlock(data); +} namespace Trinity { class BattlegroundChatBuilder { public: - BattlegroundChatBuilder(ChatMsg msgtype, uint32 textId, Player const* source, va_list* args = NULL) + BattlegroundChatBuilder(ChatMsg msgtype, uint32 textId, Player const* source, va_list* args = nullptr) : _msgtype(msgtype), _textId(textId), _source(source), _args(args) { } void operator()(WorldPacket& data, LocaleConstant loc_idx) @@ -144,7 +162,7 @@ Battleground::Battleground() m_MinPlayers = 0; m_MapId = 0; - m_Map = NULL; + m_Map = nullptr; m_StartMaxDist = 0.0f; ScriptId = 0; @@ -154,8 +172,8 @@ Battleground::Battleground() m_ArenaTeamMMR[TEAM_ALLIANCE] = 0; m_ArenaTeamMMR[TEAM_HORDE] = 0; - m_BgRaids[TEAM_ALLIANCE] = NULL; - m_BgRaids[TEAM_HORDE] = NULL; + m_BgRaids[TEAM_ALLIANCE] = nullptr; + m_BgRaids[TEAM_HORDE] = nullptr; m_PlayersCount[TEAM_ALLIANCE] = 0; m_PlayersCount[TEAM_HORDE] = 0; @@ -197,8 +215,8 @@ Battleground::~Battleground() { m_Map->SetUnload(); //unlink to prevent crash, always unlink all pointer reference before destruction - m_Map->SetBG(NULL); - m_Map = NULL; + m_Map->SetBG(nullptr); + m_Map = nullptr; } // remove from bg free slot queue RemoveFromBGFreeSlotQueue(); @@ -220,7 +238,7 @@ void Battleground::Update(uint32 diff) // [[ but if you use battleground object again (more battles possible to be played on 1 instance) // then this condition should be removed and code: // if (!GetInvitedCount(HORDE) && !GetInvitedCount(ALLIANCE)) - // this->AddToFreeBGObjectsQueue(); // not yet implemented + // AddToFreeBGObjectsQueue(); // not yet implemented // should be used instead of current // ]] // Battleground Template instance cannot be updated, because it would be deleted @@ -342,7 +360,7 @@ inline void Battleground::_ProcessResurrect(uint32 diff) { for (std::map::iterator itr = m_ReviveQueue.begin(); itr != m_ReviveQueue.end(); ++itr) { - Creature* sh = NULL; + Creature* sh = nullptr; for (GuidVector::const_iterator itr2 = (itr->second).begin(); itr2 != (itr->second).end(); ++itr2) { Player* player = ObjectAccessor::FindPlayer(*itr2); @@ -423,13 +441,13 @@ inline void Battleground::_ProcessProgress(uint32 diff) if (newtime > (MINUTE * IN_MILLISECONDS)) { if (newtime / (MINUTE * IN_MILLISECONDS) != m_PrematureCountDownTimer / (MINUTE * IN_MILLISECONDS)) - PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING, CHAT_MSG_SYSTEM, NULL, (uint32)(m_PrematureCountDownTimer / (MINUTE * IN_MILLISECONDS))); + PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING, CHAT_MSG_SYSTEM, nullptr, (uint32)(m_PrematureCountDownTimer / (MINUTE * IN_MILLISECONDS))); } else { //announce every 15 seconds if (newtime / (15 * IN_MILLISECONDS) != m_PrematureCountDownTimer / (15 * IN_MILLISECONDS)) - PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING_SECS, CHAT_MSG_SYSTEM, NULL, (uint32)(m_PrematureCountDownTimer / IN_MILLISECONDS)); + PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING_SECS, CHAT_MSG_SYSTEM, nullptr, (uint32)(m_PrematureCountDownTimer / IN_MILLISECONDS)); } m_PrematureCountDownTimer = newtime; } @@ -570,7 +588,7 @@ inline void Battleground::_ProcessLeave(uint32 diff) Player* Battleground::_GetPlayer(ObjectGuid guid, bool offlineRemove, char const* context) const { - Player* player = NULL; + Player* player = nullptr; if (!offlineRemove) { // should this be ObjectAccessor::FindConnectedPlayer() to return players teleporting ? @@ -591,7 +609,7 @@ Player* Battleground::_GetPlayerForTeam(uint32 teamId, BattlegroundPlayerMap::co if (!team) team = player->GetTeam(); if (team != teamId) - player = NULL; + player = nullptr; } return player; } @@ -627,7 +645,7 @@ void Battleground::SendPacketToTeam(uint32 TeamID, WorldPacket* packet, Player* } } -void Battleground::SendChatMessage(Creature* source, uint8 textId, WorldObject* target /*= NULL*/) +void Battleground::SendChatMessage(Creature* source, uint8 textId, WorldObject* target /*= nullptr*/) { sCreatureTextMgr->SendChat(source, textId, target); } @@ -922,7 +940,7 @@ void Battleground::RemovePlayerAtLeave(ObjectGuid guid, bool Transport, bool Sen bgTypeId = BATTLEGROUND_AA; // set the bg type to all arenas (it will be used for queue refreshing) // unsummon current and summon old pet if there was one and there isn't a current pet - player->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT); + player->RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT); player->ResummonPetTemporaryUnSummonedIfAny(); } @@ -941,7 +959,7 @@ void Battleground::RemovePlayerAtLeave(ObjectGuid guid, bool Transport, bool Sen if (Group* group = GetBgRaid(team)) { if (!group->RemoveMember(guid)) // group was disbanded - SetBgRaid(team, NULL); + SetBgRaid(team, nullptr); } DecreaseInvitedCount(team); //we should update battleground queue, but only if bg isn't ending @@ -1274,7 +1292,7 @@ bool Battleground::UpdatePlayerScore(Player* player, uint32 type, uint32 value, return false; if (type == SCORE_BONUS_HONOR && doAddHonor && isBattleground()) - player->RewardHonor(NULL, 1, value); // RewardHonor calls UpdatePlayerScore with doAddHonor = false + player->RewardHonor(nullptr, 1, value); // RewardHonor calls UpdatePlayerScore with doAddHonor = false else itr->second->UpdateScore(type, value); @@ -1315,7 +1333,7 @@ void Battleground::RelocateDeadPlayers(ObjectGuid guideGuid) GuidVector& ghostList = m_ReviveQueue[guideGuid]; if (!ghostList.empty()) { - WorldSafeLocsEntry const* closestGrave = NULL; + WorldSafeLocsEntry const* closestGrave = nullptr; for (GuidVector::const_iterator itr = ghostList.begin(); itr != ghostList.end(); ++itr) { Player* player = ObjectAccessor::FindPlayer(*itr); @@ -1323,7 +1341,7 @@ void Battleground::RelocateDeadPlayers(ObjectGuid guideGuid) continue; if (!closestGrave) - closestGrave = GetClosestGraveYard(player); + closestGrave = GetClosestGraveyard(player); if (closestGrave) player->TeleportTo(GetMapId(), closestGrave->x, closestGrave->y, closestGrave->z, player->GetOrientation()); @@ -1341,14 +1359,14 @@ bool Battleground::AddObject(uint32 type, uint32 entry, float x, float y, float if (!map) return false; - G3D::Quat rot(rotation0, rotation1, rotation2, rotation3); + QuaternionData rot(rotation0, rotation1, rotation2, rotation3); // Temporally add safety check for bad spawns and send log (object rotations need to be rechecked in sniff) if (!rotation0 && !rotation1 && !rotation2 && !rotation3) { TC_LOG_DEBUG("bg.battleground", "Battleground::AddObject: gameoobject [entry: %u, object type: %u] for BG (map: %u) has zeroed rotation fields, " "orientation used temporally, but please fix the spawn", entry, type, m_MapId); - rot = G3D::Matrix3::fromEulerAnglesZYX(o, 0.f, 0.f); + rot = QuaternionData::fromEulerAnglesZYX(o, 0.f, 0.f); } // Must be created this way, adding to godatamap would add it to the base map of the instance @@ -1482,7 +1500,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, Map* map = FindBgMap(); if (!map) - return NULL; + return nullptr; if (transport) { @@ -1492,7 +1510,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, return creature; } - return NULL; + return nullptr; } Creature* creature = new Creature(); @@ -1502,7 +1520,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, TC_LOG_ERROR("bg.battleground", "Battleground::AddCreature: cannot create creature (entry: %u) for BG (map: %u, instance id: %u)!", entry, m_MapId, m_InstanceID); delete creature; - return NULL; + return nullptr; } creature->SetHomePosition(x, y, z, o); @@ -1513,13 +1531,13 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, TC_LOG_ERROR("bg.battleground", "Battleground::AddCreature: creature template (entry: %u) does not exist for BG (map: %u, instance id: %u)!", entry, m_MapId, m_InstanceID); delete creature; - return NULL; + return nullptr; } if (!map->AddToMap(creature)) { delete creature; - return NULL; + return nullptr; } BgCreatures[type] = creature->GetGUID(); @@ -1644,7 +1662,7 @@ void Battleground::SendWarningToAll(uint32 entry, ...) vsnprintf(str, 1024, format, ap); va_end(ap); - ChatHandler::BuildChatPacket(localizedPackets[player->GetSession()->GetSessionDbLocaleIndex()], CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, NULL, NULL, str); + ChatHandler::BuildChatPacket(localizedPackets[player->GetSession()->GetSessionDbLocaleIndex()], CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, nullptr, nullptr, str); } player->SendDirectMessage(&localizedPackets[player->GetSession()->GetSessionDbLocaleIndex()]); @@ -1813,15 +1831,15 @@ void Battleground::SetBgRaid(uint32 TeamID, Group* bg_raid) { Group*& old_raid = TeamID == ALLIANCE ? m_BgRaids[TEAM_ALLIANCE] : m_BgRaids[TEAM_HORDE]; if (old_raid) - old_raid->SetBattlegroundGroup(NULL); + old_raid->SetBattlegroundGroup(nullptr); if (bg_raid) bg_raid->SetBattlegroundGroup(this); old_raid = bg_raid; } -WorldSafeLocsEntry const* Battleground::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* Battleground::GetClosestGraveyard(Player* player) { - return sObjectMgr->GetClosestGraveYard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), player->GetTeam()); + return sObjectMgr->GetClosestGraveyard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), player->GetTeam()); } void Battleground::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) diff --git a/src/server/game/Battlegrounds/Battleground.h b/src/server/game/Battlegrounds/Battleground.h index e012ead3d73..b19d9c470b2 100644 --- a/src/server/game/Battlegrounds/Battleground.h +++ b/src/server/game/Battlegrounds/Battleground.h @@ -20,23 +20,23 @@ #define __BATTLEGROUND_H #include "ArenaScore.h" -#include "Common.h" -#include "SharedDefines.h" #include "DBCEnums.h" -#include "WorldPacket.h" -#include "Object.h" -#include "GameObject.h" -#include "EventMap.h" +#include "ObjectGuid.h" +#include "Position.h" +#include "SharedDefines.h" +#include +class BattlegroundMap; class Creature; class GameObject; class Group; class Player; +class Transport; class Unit; class WorldObject; class WorldPacket; -class BattlegroundMap; +struct BattlegroundScore; struct PvPDifficultyEntry; struct WorldSafeLocsEntry; @@ -172,7 +172,7 @@ struct BattlegroundPlayer struct BattlegroundObjectInfo { - BattlegroundObjectInfo() : object(NULL), timer(0), spellid(0) { } + BattlegroundObjectInfo() : object(nullptr), timer(0), spellid(0) { } GameObject *object; int32 timer; @@ -243,7 +243,7 @@ class TC_GAME_API Battleground /* achievement req. */ virtual bool IsAllNodesControlledByTeam(uint32 /*team*/) const { return false; } void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); - virtual bool CheckAchievementCriteriaMeet(uint32 /*criteriaId*/, Player const* /*player*/, Unit const* /*target*/ = NULL, uint32 /*miscvalue1*/ = 0); + virtual bool CheckAchievementCriteriaMeet(uint32 /*criteriaId*/, Player const* /*player*/, Unit const* /*target*/ = nullptr, uint32 /*miscvalue1*/ = 0); /* Battleground */ // Get methods: @@ -352,10 +352,10 @@ class TC_GAME_API Battleground // Packet Transfer // method that should fill worldpacket with actual world states (not yet implemented for all battlegrounds!) virtual void FillInitialWorldStates(WorldPacket& /*data*/) { } - void SendPacketToTeam(uint32 TeamID, WorldPacket* packet, Player* sender = NULL, bool self = true); + void SendPacketToTeam(uint32 TeamID, WorldPacket* packet, Player* sender = nullptr, bool self = true); void SendPacketToAll(WorldPacket* packet); - void SendChatMessage(Creature* source, uint8 textId, WorldObject* target = NULL); + void SendChatMessage(Creature* source, uint8 textId, WorldObject* target = nullptr); template void BroadcastWorker(Do& _do); @@ -372,7 +372,7 @@ class TC_GAME_API Battleground void BlockMovement(Player* player); void SendWarningToAll(uint32 entry, ...); - void SendMessageToAll(uint32 entry, ChatMsg type, Player const* source = NULL); + void SendMessageToAll(uint32 entry, ChatMsg type, Player const* source = nullptr); void PSendMessageToAll(uint32 entry, ChatMsg type, Player const* source, ...); // specialized version with 2 string id args @@ -417,7 +417,7 @@ class TC_GAME_API Battleground virtual void EventPlayerClickedOnFlag(Player* /*player*/, GameObject* /*target_obj*/) { } void EventPlayerLoggedIn(Player* player); void EventPlayerLoggedOut(Player* player); - virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = NULL) { } + virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = nullptr) { } // this function can be used by spell to interact with the BG map virtual void DoAction(uint32 /*action*/, ObjectGuid /*var*/) { } @@ -425,7 +425,7 @@ class TC_GAME_API Battleground virtual void HandlePlayerResurrect(Player* /*player*/) { } // Death related - virtual WorldSafeLocsEntry const* GetClosestGraveYard(Player* player); + virtual WorldSafeLocsEntry const* GetClosestGraveyard(Player* player); virtual void AddPlayer(Player* player); // must be implemented in BG subclass @@ -443,8 +443,8 @@ class TC_GAME_API Battleground void SpawnBGObject(uint32 type, uint32 respawntime); virtual bool AddObject(uint32 type, uint32 entry, float x, float y, float z, float o, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime = 0, GOState goState = GO_STATE_READY); bool AddObject(uint32 type, uint32 entry, Position const& pos, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime = 0, GOState goState = GO_STATE_READY); - virtual Creature* AddCreature(uint32 entry, uint32 type, float x, float y, float z, float o, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = NULL); - Creature* AddCreature(uint32 entry, uint32 type, Position const& pos, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = NULL); + virtual Creature* AddCreature(uint32 entry, uint32 type, float x, float y, float z, float o, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = nullptr); + Creature* AddCreature(uint32 entry, uint32 type, Position const& pos, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = nullptr); bool DelCreature(uint32 type); bool DelObject(uint32 type); virtual bool AddSpiritGuide(uint32 type, float x, float y, float z, float o, TeamId teamId = TEAM_NEUTRAL); @@ -484,10 +484,10 @@ class TC_GAME_API Battleground void EndNow(); void PlayerAddedToBGCheckIfBGIsRunning(Player* player); - Player* _GetPlayer(ObjectGuid guid, bool offlineRemove, const char* context) const; - Player* _GetPlayer(BattlegroundPlayerMap::iterator itr, const char* context) { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } - Player* _GetPlayer(BattlegroundPlayerMap::const_iterator itr, const char* context) const { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } - Player* _GetPlayerForTeam(uint32 teamId, BattlegroundPlayerMap::const_iterator itr, const char* context) const; + Player* _GetPlayer(ObjectGuid guid, bool offlineRemove, char const* context) const; + Player* _GetPlayer(BattlegroundPlayerMap::iterator itr, char const* context) { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } + Player* _GetPlayer(BattlegroundPlayerMap::const_iterator itr, char const* context) const { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } + Player* _GetPlayerForTeam(uint32 teamId, BattlegroundPlayerMap::const_iterator itr, char const* context) const; void _ProcessOfflineQueue(); void _ProcessResurrect(uint32 diff); diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 0416a021d16..1b8fb8ee907 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -16,12 +16,7 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectMgr.h" #include "ArenaTeamMgr.h" -#include "World.h" -#include "WorldPacket.h" - #include "BattlegroundMgr.h" #include "BattlegroundAV.h" #include "BattlegroundAB.h" @@ -34,15 +29,26 @@ #include "BattlegroundDS.h" #include "BattlegroundRV.h" #include "BattlegroundIC.h" +#include "Common.h" +#include "Containers.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" +#include "Formulas.h" +#include "GameEventMgr.h" #include "Map.h" #include "MapManager.h" -#include "Player.h" -#include "GameEventMgr.h" #include "SharedDefines.h" -#include "Formulas.h" -#include "DisableMgr.h" +#include "ObjectMgr.h" #include "Opcodes.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" + +bool BattlegroundTemplate::IsArena() const +{ + return BattlemasterEntry->type == MAP_ARENA; +} /*********************************************************/ /*** BATTLEGROUND MANAGER ***/ @@ -160,7 +166,7 @@ void BattlegroundMgr::Update(uint32 diff) { if (m_AutoDistributionTimeChecker < diff) { - if (time(NULL) > m_NextAutoDistributionTime) + if (time(nullptr) > m_NextAutoDistributionTime) { sArenaTeamMgr->DistributeArenaPoints(); m_NextAutoDistributionTime = m_NextAutoDistributionTime + BATTLEGROUND_ARENA_POINT_DISTRIBUTION_DAY * sWorld->getIntConfig(CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS); @@ -265,14 +271,14 @@ Battleground* BattlegroundMgr::GetBattlegroundThroughClientInstance(uint32 insta //SMSG_BATTLEFIELD_LIST we need to find the battleground with this clientinstance-id Battleground* bg = GetBattlegroundTemplate(bgTypeId); if (!bg) - return NULL; + return nullptr; if (bg->isArena()) return GetBattleground(instanceId, bgTypeId); BattlegroundDataContainer::const_iterator it = bgDataStore.find(bgTypeId); if (it == bgDataStore.end()) - return NULL; + return nullptr; for (BattlegroundContainer::const_iterator itr = it->second.m_Battlegrounds.begin(); itr != it->second.m_Battlegrounds.end(); ++itr) { @@ -280,13 +286,13 @@ Battleground* BattlegroundMgr::GetBattlegroundThroughClientInstance(uint32 insta return itr->second; } - return NULL; + return nullptr; } Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId, BattlegroundTypeId bgTypeId) { if (!instanceId) - return NULL; + return nullptr; BattlegroundDataContainer::const_iterator begin, end; @@ -299,7 +305,7 @@ Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId, BattlegroundTy { end = bgDataStore.find(bgTypeId); if (end == bgDataStore.end()) - return NULL; + return nullptr; begin = end++; } @@ -311,18 +317,18 @@ Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId, BattlegroundTy return itr->second; } - return NULL; + return nullptr; } Battleground* BattlegroundMgr::GetBattlegroundTemplate(BattlegroundTypeId bgTypeId) { BattlegroundDataContainer::const_iterator itr = bgDataStore.find(bgTypeId); if (itr == bgDataStore.end()) - return NULL; + return nullptr; BattlegroundContainer const& bgs = itr->second.m_Battlegrounds; //map is sorted and we can be sure that lowest instance id has only BG template - return bgs.empty() ? NULL : bgs.begin()->second; + return bgs.empty() ? nullptr : bgs.begin()->second; } uint32 BattlegroundMgr::CreateClientVisibleInstanceId(BattlegroundTypeId bgTypeId, BattlegroundBracketId bracket_id) @@ -361,10 +367,10 @@ Battleground* BattlegroundMgr::CreateNewBattleground(BattlegroundTypeId original if (!bg_template) { TC_LOG_ERROR("bg.battleground", "Battleground: CreateNewBattleground - bg template not found for %u", bgTypeId); - return NULL; + return nullptr; } - Battleground* bg = NULL; + Battleground* bg = nullptr; // create a copy of the BG template switch (bgTypeId) { @@ -404,7 +410,7 @@ Battleground* BattlegroundMgr::CreateNewBattleground(BattlegroundTypeId original case BATTLEGROUND_RB: case BATTLEGROUND_AA: default: - return NULL; + return nullptr; } bool isRandom = bgTypeId != originalBgTypeId && !bg->isArena(); @@ -541,7 +547,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() BattlegroundTypeId bgTypeId = BattlegroundTypeId(fields[0].GetUInt32()); - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId, nullptr)) continue; // can be overwrite by values from DB @@ -624,7 +630,7 @@ void BattlegroundMgr::InitAutomaticArenaPointDistribution() return; time_t wstime = time_t(sWorld->getWorldState(WS_ARENA_DISTRIBUTION_TIME)); - time_t curtime = time(NULL); + time_t curtime = time(nullptr); TC_LOG_DEBUG("bg.battleground", "Initializing Automatic Arena Point Distribution"); if (wstime < curtime) { @@ -724,7 +730,7 @@ void BattlegroundMgr::SendAreaSpiritHealerQueryOpcode(Player* player, Battlegrou if (time_ == uint32(-1)) time_ = 0; data << guid << time_; - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } bool BattlegroundMgr::IsArenaType(BattlegroundTypeId bgTypeId) @@ -967,9 +973,11 @@ BattlegroundTypeId BattlegroundMgr::GetRandomBG(BattlegroundTypeId bgTypeId) { if (BattlegroundTemplate const* bgTemplate = GetBattlegroundTemplateByTypeId(bgTypeId)) { - uint32 weight = 0; BattlegroundSelectionWeightMap selectionWeights; - + std::vector ids; + ids.reserve(16); + std::vector weights; + weights.reserve(16); for (int32 mapId : bgTemplate->BattlemasterEntry->mapid) { if (mapId == -1) @@ -977,28 +985,12 @@ BattlegroundTypeId BattlegroundMgr::GetRandomBG(BattlegroundTypeId bgTypeId) if (BattlegroundTemplate const* bg = GetBattlegroundTemplateByMapId(mapId)) { - weight += bg->Weight; - selectionWeights[bg->Id] = bg->Weight; + ids.push_back(bg->Id); + weights.push_back(bg->Weight); } } - // there is only one bg to select - if (selectionWeights.size() == 1) - return selectionWeights.begin()->first; - - if (weight) - { - // Select a random value - uint32 selectedWeight = urand(0, weight - 1); - // Select the correct bg (if we have in DB A(10), B(20), C(10), D(15) --> [0---A---9|10---B---29|30---C---39|40---D---54]) - weight = 0; - for (auto it : selectionWeights) - { - weight += it.second; - if (selectedWeight < weight) - return it.first; - } - } + return *Trinity::Containers::SelectRandomWeightedContainerElement(ids, weights); } return BATTLEGROUND_TYPE_NONE; diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.h b/src/server/game/Battlegrounds/BattlegroundMgr.h index 84dfb482a9f..da5e89a5a5d 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.h +++ b/src/server/game/Battlegrounds/BattlegroundMgr.h @@ -23,6 +23,9 @@ #include "DBCEnums.h" #include "Battleground.h" #include "BattlegroundQueue.h" +#include + +struct BattlemasterListEntry; typedef std::map BattlegroundContainer; typedef std::set BattlegroundClientIdsContainer; @@ -56,7 +59,7 @@ struct BattlegroundTemplate uint32 ScriptId; BattlemasterListEntry const* BattlemasterEntry; - bool IsArena() const { return BattlemasterEntry->type == MAP_ARENA; } + bool IsArena() const; }; class TC_GAME_API BattlegroundMgr diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index 7643e1d3f5e..ea83422c205 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -16,17 +16,20 @@ * with this program. If not, see . */ +#include "BattlegroundQueue.h" #include "ArenaTeam.h" #include "ArenaTeamMgr.h" #include "BattlegroundMgr.h" -#include "BattlegroundQueue.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GameTime.h" #include "Group.h" -#include "Log.h" #include "Language.h" -#include "Player.h" +#include "Log.h" #include "ObjectAccessor.h" +#include "Player.h" +#include "World.h" /*********************************************************/ /*** BATTLEGROUND QUEUE SYSTEM ***/ @@ -170,7 +173,7 @@ GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, Battlegr //add players from group to ginfo if (grp) { - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -396,7 +399,7 @@ void BattlegroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount) // queue->removeplayer, it causes bugs WorldPacket data; sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0, 0); - plr2->GetSession()->SendPacket(&data); + plr2->SendDirectMessage(&data); } // then actually delete, this may delete the group as well! RemovePlayer(group->Players.begin()->first, decreaseInvitedCount); @@ -481,7 +484,7 @@ bool BattlegroundQueue::InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, // send status packet sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, 0, ginfo->ArenaType, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } return true; } @@ -890,8 +893,8 @@ void BattlegroundQueue::BattlegroundQueueUpdate(uint32 /*diff*/, BattlegroundTyp // 0 is on (automatic update call) and we must set it to team's with longest wait time if (!arenaRating) { - GroupQueueInfo* front1 = NULL; - GroupQueueInfo* front2 = NULL; + GroupQueueInfo* front1 = nullptr; + GroupQueueInfo* front2 = nullptr; if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty()) { front1 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].front(); @@ -1031,7 +1034,7 @@ bool BGQueueInviteEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) WorldPacket data; //we must send remaining time in queue sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, 0, m_ArenaType, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } return true; //event will be deleted @@ -1089,7 +1092,7 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) WorldPacket data; sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } diff --git a/src/server/game/Battlegrounds/BattlegroundScore.h b/src/server/game/Battlegrounds/BattlegroundScore.h index 8776a1d7c39..41fdbbf3117 100644 --- a/src/server/game/Battlegrounds/BattlegroundScore.h +++ b/src/server/game/Battlegrounds/BattlegroundScore.h @@ -18,8 +18,11 @@ #ifndef TRINITY_BATTLEGROUND_SCORE_H #define TRINITY_BATTLEGROUND_SCORE_H -#include "WorldPacket.h" +#include "Errors.h" #include "ObjectGuid.h" +#include "SharedDefines.h" + +class WorldPacket; enum ScoreType { @@ -89,20 +92,7 @@ struct BattlegroundScore } } - virtual void AppendToPacket(WorldPacket& data) - { - data << uint64(PlayerGuid); - - data << uint32(KillingBlows); - data << uint32(HonorableKills); - data << uint32(Deaths); - data << uint32(BonusHonor); - data << uint32(DamageDone); - data << uint32(HealingDone); - - BuildObjectivesBlock(data); - } - + virtual void AppendToPacket(WorldPacket& data); virtual void BuildObjectivesBlock(WorldPacket& /*data*/) = 0; // For Logging purpose diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp index c47662893b1..6ef3bbcc3c3 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp @@ -17,14 +17,26 @@ */ #include "BattlegroundAB.h" -#include "WorldPacket.h" #include "BattlegroundMgr.h" #include "Creature.h" +#include "DBCStores.h" +#include "GameObject.h" #include "Language.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "Random.h" #include "Util.h" +#include "WorldPacket.h" #include "WorldSession.h" +void BattlegroundABScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(2); + data << uint32(BasesAssaulted); + data << uint32(BasesDefended); +} + BattlegroundAB::BattlegroundAB() { m_IsInformedNearVictory = false; @@ -104,13 +116,13 @@ void BattlegroundAB::PostUpdateImpl(uint32 diff) if (teamIndex == 0) { // FIXME: team and node names not localized - SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, LANG_BG_AB_ALLY, _GetNodeNameId(node)); + SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_ALLIANCE, nullptr, LANG_BG_AB_ALLY, _GetNodeNameId(node)); PlaySoundToAll(BG_AB_SOUND_NODE_CAPTURED_ALLIANCE); } else { // FIXME: team and node names not localized - SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_HORDE, NULL, LANG_BG_AB_HORDE, _GetNodeNameId(node)); + SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_HORDE, nullptr, LANG_BG_AB_HORDE, _GetNodeNameId(node)); PlaySoundToAll(BG_AB_SOUND_NODE_CAPTURED_HORDE); } } @@ -390,7 +402,7 @@ void BattlegroundAB::_NodeOccupied(uint8 node, Team team) if (capturedNodes >= 4) CastSpellOnTeam(SPELL_AB_QUEST_REWARD_4_BASES, team); - Creature* trigger = !BgCreatures[node + 7] ? GetBGCreature(node + 7) : NULL; // 0-6 spirit guides + Creature* trigger = !BgCreatures[node + 7] ? GetBGCreature(node + 7) : nullptr; // 0-6 spirit guides if (!trigger) trigger = AddCreature(WORLD_TRIGGER, node+7, BG_AB_NodePositions[node], GetTeamIndexByTeamId(team)); @@ -541,9 +553,9 @@ void BattlegroundAB::EventPlayerClickedOnFlag(Player* source, GameObject* /*targ { // FIXME: team and node names not localized if (teamIndex == TEAM_ALLIANCE) - SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, LANG_BG_AB_ALLY, _GetNodeNameId(node)); + SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_ALLIANCE, nullptr, LANG_BG_AB_ALLY, _GetNodeNameId(node)); else - SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_HORDE, NULL, LANG_BG_AB_HORDE, _GetNodeNameId(node)); + SendMessage2ToAll(LANG_BG_AB_NODE_TAKEN, CHAT_MSG_BG_SYSTEM_HORDE, nullptr, LANG_BG_AB_HORDE, _GetNodeNameId(node)); } PlaySoundToAll(sound); } @@ -651,7 +663,7 @@ void BattlegroundAB::EndBattleground(uint32 winner) Battleground::EndBattleground(winner); } -WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveyard(Player* player) { TeamId teamIndex = GetTeamIndexByTeamId(player->GetTeam()); @@ -661,7 +673,7 @@ WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveYard(Player* player) if (m_Nodes[i] == teamIndex + 3) nodes.push_back(i); - WorldSafeLocsEntry const* good_entry = NULL; + WorldSafeLocsEntry const* good_entry = nullptr; // If so, select the closest node to place ghost on if (!nodes.empty()) { @@ -671,7 +683,7 @@ WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveYard(Player* player) float mindist = 999999.0f; for (uint8 i = 0; i < nodes.size(); ++i) { - WorldSafeLocsEntry const*entry = sWorldSafeLocsStore.LookupEntry(BG_AB_GraveyardIds[nodes[i]]); + WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(BG_AB_GraveyardIds[nodes[i]]); if (!entry) continue; float dist = (entry->x - plr_x)*(entry->x - plr_x)+(entry->y - plr_y)*(entry->y - plr_y); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.h b/src/server/game/Battlegrounds/Zones/BattlegroundAB.h index 71c8c0f71de..7f68ef3eb0d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.h @@ -260,12 +260,7 @@ struct BattlegroundABScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(2); - data << uint32(BasesAssaulted); - data << uint32(BasesDefended); - } + void BuildObjectivesBlock(WorldPacket& data) final override; uint32 GetAttr1() const final override { return BasesAssaulted; } uint32 GetAttr2() const final override { return BasesDefended; } @@ -288,7 +283,7 @@ class BattlegroundAB : public Battleground bool SetupBattleground() override; void Reset() override; void EndBattleground(uint32 winner) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; /* Scorekeeping */ bool UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true) override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp index c78b5439a75..fc2bee156ee 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp @@ -17,16 +17,27 @@ */ #include "BattlegroundAV.h" - -#include "ObjectMgr.h" -#include "WorldPacket.h" - +#include "Creature.h" +#include "CreatureAI.h" +#include "DBCStores.h" #include "GameObject.h" #include "Language.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "Player.h" -#include "ScriptedCreature.h" #include "WorldSession.h" +void BattlegroundAVScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(5); // Objectives Count + data << uint32(GraveyardsAssaulted); + data << uint32(GraveyardsDefended); + data << uint32(TowersAssaulted); + data << uint32(TowersDefended); + data << uint32(MinesCaptured); +} + BattlegroundAV::BattlegroundAV() { BgObjects.resize(BG_AV_OBJECT_MAX); @@ -273,7 +284,7 @@ void BattlegroundAV::UpdateScore(uint16 team, int16 points) Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type) { bool isStatic = false; - Creature* creature = NULL; + Creature* creature = nullptr; ASSERT(type <= AV_CPLACE_MAX + AV_STATICCPLACE_MAX); if (type >= AV_CPLACE_MAX) //static { @@ -292,7 +303,7 @@ Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type) creature = AddCreature(BG_AV_CreatureInfo[cinfoid], type, BG_AV_CreaturePos[type]); } if (!creature) - return NULL; + return nullptr; if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_CAPTAIN] || creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_CAPTAIN]) creature->SetRespawnDelay(RESPAWN_ONE_DAY); /// @todo look if this can be done by database + also add this for the wingcommanders @@ -392,7 +403,7 @@ void BattlegroundAV::PostUpdateImpl(uint32 diff) } } if (m_Mine_Timer <= 0) - m_Mine_Timer=AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines + m_Mine_Timer = AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines //looks for all timers of the nodes and destroy the building (for graveyards the building wont get destroyed, it goes just to the other team for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i < BG_AV_NODES_MAX; ++i) @@ -1092,10 +1103,10 @@ void BattlegroundAV::SendMineWorldStates(uint32 mine) UpdateWorldState(BG_AV_MineWorldStates[mine2][prevowner], 0); } -WorldSafeLocsEntry const* BattlegroundAV::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundAV::GetClosestGraveyard(Player* player) { - WorldSafeLocsEntry const* pGraveyard = NULL; - WorldSafeLocsEntry const* entry = NULL; + WorldSafeLocsEntry const* pGraveyard = nullptr; + WorldSafeLocsEntry const* entry = nullptr; float dist = 0; float minDist = 0; float x, y; @@ -1486,7 +1497,7 @@ void BattlegroundAV::ResetBGSubclass() InitNode(i, HORDE, true); InitNode(BG_AV_NODES_SNOWFALL_GRAVE, AV_NEUTRAL_TEAM, false); //give snowfall neutral owner - m_Mine_Timer=AV_MINE_TICK_TIMER; + m_Mine_Timer = AV_MINE_TICK_TIMER; for (uint16 i = 0; i < AV_CPLACE_MAX+AV_STATICCPLACE_MAX; i++) if (BgCreatures[i]) DelCreature(i); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.h b/src/server/game/Battlegrounds/Zones/BattlegroundAV.h index 5f687ec4eb1..9adaea025d3 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.h @@ -1581,15 +1581,7 @@ struct BattlegroundAVScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(5); // Objectives Count - data << uint32(GraveyardsAssaulted); - data << uint32(GraveyardsDefended); - data << uint32(TowersAssaulted); - data << uint32(TowersDefended); - data << uint32(MinesCaptured); - } + void BuildObjectivesBlock(WorldPacket& data) final override; uint32 GetAttr1() const final override { return GraveyardsAssaulted; } uint32 GetAttr2() const final override { return GraveyardsDefended; } @@ -1633,7 +1625,7 @@ class BattlegroundAV : public Battleground void EndBattleground(uint32 winner) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; // Achievement: Av perfection and Everything counts bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target = nullptr, uint32 miscvalue1 = 0) override; @@ -1669,7 +1661,7 @@ class BattlegroundAV : public Battleground bool IsTower(BG_AV_Nodes node) { return m_Nodes[node].Tower; } /*mine*/ - void ChangeMineOwner(uint8 mine, uint32 team, bool initial=false); + void ChangeMineOwner(uint8 mine, uint32 team, bool initial = false); /*worldstates*/ void FillInitialWorldStates(WorldPacket& data) override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp index 21e041fafe1..ca406413325 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp @@ -17,6 +17,7 @@ */ #include "BattlegroundBE.h" +#include "Log.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp index e4940add01c..4ba43b85e15 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp @@ -18,7 +18,9 @@ #include "BattlegroundDS.h" #include "Creature.h" +#include "Log.h" #include "Player.h" +#include "Random.h" #include "WorldPacket.h" BattlegroundDS::BattlegroundDS() diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.h b/src/server/game/Battlegrounds/Zones/BattlegroundDS.h index f55c8fedd01..e112e5cae6a 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.h @@ -20,6 +20,7 @@ #define __BATTLEGROUNDDS_H #include "Arena.h" +#include "EventMap.h" enum BattlegroundDSObjectTypes { @@ -109,4 +110,5 @@ class BattlegroundDS : public Arena uint32 _pipeKnockBackTimer; uint8 _pipeKnockBackCount; }; + #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp index 3f363a4bd19..e1d1394cb05 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp @@ -20,8 +20,13 @@ #include "WorldPacket.h" #include "BattlegroundMgr.h" #include "Creature.h" +#include "DBCStores.h" +#include "GameObject.h" #include "Language.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "Random.h" #include "Util.h" #include "ObjectAccessor.h" @@ -32,6 +37,12 @@ uint32 BG_EY_HonorScoreTicks[BG_HONOR_MODE_NUM] = 160 // holiday }; +void BattlegroundEYScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(1); // Objectives Count + data << uint32(FlagCaptures); +} + BattlegroundEY::BattlegroundEY() { m_BuffChange = true; @@ -107,10 +118,10 @@ void BattlegroundEY::PostUpdateImpl(uint32 diff) /*I used this order of calls, because although we will check if one player is in gameobject's distance 2 times but we can count of players on current point in CheckSomeoneLeftPoint */ - this->CheckSomeoneJoinedPoint(); + CheckSomeoneJoinedPoint(); //check if player left point - this->CheckSomeoneLeftPoint(); - this->UpdatePointStatuses(); + CheckSomeoneLeftPoint(); + UpdatePointStatuses(); m_TowerCapCheckTimer = BG_EY_FPOINTS_TICK_TIME; } } @@ -158,7 +169,7 @@ void BattlegroundEY::AddPoints(uint32 Team, uint32 Points) void BattlegroundEY::CheckSomeoneJoinedPoint() { - GameObject* obj = NULL; + GameObject* obj = nullptr; for (uint8 i = 0; i < EY_POINTS_MAX; ++i) { obj = GetBgMap()->GetGameObject(BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]); @@ -199,7 +210,7 @@ void BattlegroundEY::CheckSomeoneLeftPoint() //reset current point counts for (uint8 i = 0; i < 2*EY_POINTS_MAX; ++i) m_CurrentPointPlayersCount[i] = 0; - GameObject* obj = NULL; + GameObject* obj = nullptr; for (uint8 i = 0; i < EY_POINTS_MAX; ++i) { obj = GetBgMap()->GetGameObject(BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]); @@ -223,7 +234,7 @@ void BattlegroundEY::CheckSomeoneLeftPoint() { m_PlayersNearPoint[EY_POINTS_MAX].push_back(m_PlayersNearPoint[i][j]); m_PlayersNearPoint[i].erase(m_PlayersNearPoint[i].begin() + j); - this->UpdateWorldStateForPlayer(PROGRESS_BAR_SHOW, BG_EY_PROGRESS_BAR_DONT_SHOW, player); + UpdateWorldStateForPlayer(PROGRESS_BAR_SHOW, BG_EY_PROGRESS_BAR_DONT_SHOW, player); } else { @@ -266,17 +277,17 @@ void BattlegroundEY::UpdatePointStatuses() Player* player = ObjectAccessor::FindPlayer(m_PlayersNearPoint[point][i]); if (player) { - this->UpdateWorldStateForPlayer(PROGRESS_BAR_STATUS, m_PointBarStatus[point], player); + UpdateWorldStateForPlayer(PROGRESS_BAR_STATUS, m_PointBarStatus[point], player); //if point owner changed we must evoke event! if (pointOwnerTeamId != m_PointOwnedByTeam[point]) { //point was uncontrolled and player is from team which captured point if (m_PointState[point] == EY_POINT_STATE_UNCONTROLLED && player->GetTeam() == pointOwnerTeamId) - this->EventTeamCapturedPoint(player, point); + EventTeamCapturedPoint(player, point); //point was under control and player isn't from team which controlled it if (m_PointState[point] == EY_POINT_UNDER_CONTROL && player->GetTeam() != m_PointOwnedByTeam[point]) - this->EventTeamLostPoint(player, point); + EventTeamLostPoint(player, point); } /// @workaround The original AreaTrigger is covered by a bigger one and not triggered on client side. @@ -518,7 +529,7 @@ bool BattlegroundEY::SetupBattleground() TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Could not spawn Speedbuff Fel Reaver."); } - WorldSafeLocsEntry const* sg = NULL; + WorldSafeLocsEntry const* sg = nullptr; sg = sWorldSafeLocsStore.LookupEntry(EY_GRAVEYARD_MAIN_ALLIANCE); if (!sg || !AddSpiritGuide(EY_SPIRIT_MAIN_ALLIANCE, sg->x, sg->y, sg->z, 3.124139f, TEAM_ALLIANCE)) { @@ -640,9 +651,9 @@ void BattlegroundEY::EventPlayerDroppedFlag(Player* player) UpdateWorldState(NETHERSTORM_FLAG_STATE_ALLIANCE, BG_EY_FLAG_STATE_WAIT_RESPAWN); if (player->GetTeam() == ALLIANCE) - SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL); + SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, nullptr); else - SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL); + SendMessageToAll(LANG_BG_EY_DROPPED_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, nullptr); } void BattlegroundEY::EventPlayerClickedOnFlag(Player* player, GameObject* target_obj) @@ -672,9 +683,9 @@ void BattlegroundEY::EventPlayerClickedOnFlag(Player* player, GameObject* target player->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); if (player->GetTeam() == ALLIANCE) - PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, NULL, player->GetName().c_str()); + PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_ALLIANCE, nullptr, player->GetName().c_str()); else - PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, NULL, player->GetName().c_str()); + PSendMessageToAll(LANG_BG_EY_HAS_TAKEN_FLAG, CHAT_MSG_BG_SYSTEM_HORDE, nullptr, player->GetName().c_str()); } void BattlegroundEY::EventTeamLostPoint(Player* player, uint32 Point) @@ -763,11 +774,11 @@ void BattlegroundEY::EventTeamCapturedPoint(Player* player, uint32 Point) if (BgCreatures[Point]) DelCreature(Point); - WorldSafeLocsEntry const* sg = NULL; - sg = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[Point].GraveYardId); + WorldSafeLocsEntry const* sg = nullptr; + sg = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[Point].GraveyardId); if (!sg || !AddSpiritGuide(Point, sg->x, sg->y, sg->z, 3.124139f, GetTeamIndexByTeamId(Team))) TC_LOG_ERROR("bg.battleground", "BatteGroundEY: Failed to spawn spirit guide. point: %u, team: %u, graveyard_id: %u", - Point, Team, m_CapturingPointTypes[Point].GraveYardId); + Point, Team, m_CapturingPointTypes[Point].GraveyardId); // SpawnBGCreature(Point, RESPAWN_IMMEDIATELY); @@ -893,7 +904,7 @@ void BattlegroundEY::FillInitialWorldStates(WorldPacket& data) data << uint32(0xc0d) << uint32(0x17b); } -WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveyard(Player* player) { uint32 g_id = 0; @@ -901,20 +912,20 @@ WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) { case ALLIANCE: g_id = EY_GRAVEYARD_MAIN_ALLIANCE; break; case HORDE: g_id = EY_GRAVEYARD_MAIN_HORDE; break; - default: return NULL; + default: return nullptr; } float distance, nearestDistance; - WorldSafeLocsEntry const* entry = NULL; - WorldSafeLocsEntry const* nearestEntry = NULL; + WorldSafeLocsEntry const* entry = nullptr; + WorldSafeLocsEntry const* nearestEntry = nullptr; entry = sWorldSafeLocsStore.LookupEntry(g_id); nearestEntry = entry; if (!entry) { TC_LOG_ERROR("bg.battleground", "BattlegroundEY: The main team graveyard could not be found. The graveyard system will not be operational!"); - return NULL; + return nullptr; } float plr_x = player->GetPositionX(); @@ -928,9 +939,9 @@ WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) { if (m_PointOwnedByTeam[i] == player->GetTeam() && m_PointState[i] == EY_POINT_UNDER_CONTROL) { - entry = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[i].GraveYardId); + entry = sWorldSafeLocsStore.LookupEntry(m_CapturingPointTypes[i].GraveyardId); if (!entry) - TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Graveyard %u could not be found.", m_CapturingPointTypes[i].GraveYardId); + TC_LOG_ERROR("bg.battleground", "BattlegroundEY: Graveyard %u could not be found.", m_CapturingPointTypes[i].GraveyardId); 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/server/game/Battlegrounds/Zones/BattlegroundEY.h b/src/server/game/Battlegrounds/Zones/BattlegroundEY.h index 53f511f9f1d..2555bc40a29 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.h @@ -282,11 +282,11 @@ struct BattlegroundEYLosingPointStruct struct BattlegroundEYCapturingPointStruct { - BattlegroundEYCapturingPointStruct(uint32 _DespawnNeutralObjectType, uint32 _SpawnObjectTypeAlliance, uint32 _MessageIdAlliance, uint32 _SpawnObjectTypeHorde, uint32 _MessageIdHorde, uint32 _GraveYardId) + BattlegroundEYCapturingPointStruct(uint32 _DespawnNeutralObjectType, uint32 _SpawnObjectTypeAlliance, uint32 _MessageIdAlliance, uint32 _SpawnObjectTypeHorde, uint32 _MessageIdHorde, uint32 _GraveyardId) : DespawnNeutralObjectType(_DespawnNeutralObjectType), SpawnObjectTypeAlliance(_SpawnObjectTypeAlliance), MessageIdAlliance(_MessageIdAlliance), SpawnObjectTypeHorde(_SpawnObjectTypeHorde), MessageIdHorde(_MessageIdHorde), - GraveYardId(_GraveYardId) + GraveyardId(_GraveyardId) { } uint32 DespawnNeutralObjectType; @@ -294,7 +294,7 @@ struct BattlegroundEYCapturingPointStruct uint32 MessageIdAlliance; uint32 SpawnObjectTypeHorde; uint32 MessageIdHorde; - uint32 GraveYardId; + uint32 GraveyardId; }; const uint8 BG_EY_TickPoints[EY_POINTS_MAX] = {1, 2, 5, 10}; @@ -343,11 +343,7 @@ struct BattlegroundEYScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(1); // Objectives Count - data << uint32(FlagCaptures); - } + void BuildObjectivesBlock(WorldPacket& data) final override; uint32 GetAttr1() const final override { return FlagCaptures; } @@ -376,7 +372,7 @@ class BattlegroundEY : public Battleground void RemovePlayer(Player* player, ObjectGuid guid, uint32 team) override; void HandleAreaTrigger(Player* Source, uint32 Trigger) override; void HandleKillPlayer(Player* player, Player* killer) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; bool SetupBattleground() override; void Reset() override; void UpdateTeamScore(uint32 Team); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp index bbd4f16328a..21e20ab2752 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp @@ -16,16 +16,24 @@ * with this program. If not, see . */ -#include "Player.h" -#include "Battleground.h" #include "BattlegroundIC.h" -#include "Language.h" -#include "WorldPacket.h" #include "GameObject.h" +#include "Language.h" +#include "Log.h" +#include "Map.h" #include "ObjectMgr.h" -#include "Vehicle.h" -#include "Transport.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "Transport.h" +#include "Vehicle.h" +#include "WorldPacket.h" + +void BattlegroundICScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(2); // Objectives Count + data << uint32(BasesAssaulted); + data << uint32(BasesDefended); +} BattlegroundIC::BattlegroundIC() { @@ -53,8 +61,8 @@ BattlegroundIC::BattlegroundIC() siegeEngineWorkshopTimer = WORKSHOP_UPDATE_TIME; - gunshipHorde = NULL; - gunshipAlliance = NULL; + gunshipHorde = nullptr; + gunshipAlliance = nullptr; } BattlegroundIC::~BattlegroundIC() { } @@ -192,7 +200,7 @@ void BattlegroundIC::PostUpdateImpl(uint32 diff) UpdateNodeWorldState(&nodePoint[i]); HandleCapturedNodes(&nodePoint[i], false); - SendMessage2ToAll(LANG_BG_IC_TEAM_HAS_TAKEN_NODE, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL, (nodePoint[i].faction == TEAM_ALLIANCE ? LANG_BG_IC_ALLIANCE : LANG_BG_IC_HORDE), nodePoint[i].string); + SendMessage2ToAll(LANG_BG_IC_TEAM_HAS_TAKEN_NODE, CHAT_MSG_BG_SYSTEM_NEUTRAL, nullptr, (nodePoint[i].faction == TEAM_ALLIANCE ? LANG_BG_IC_ALLIANCE : LANG_BG_IC_HORDE), nodePoint[i].string); nodePoint[i].needChange = false; nodePoint[i].timer = BANNER_STATE_CHANGE_TIME; @@ -416,7 +424,7 @@ void BattlegroundIC::HandleKillPlayer(Player* player, Player* killer) void BattlegroundIC::EndBattleground(uint32 winner) { - SendMessage2ToAll(LANG_BG_IC_TEAM_WINS, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL, (winner == ALLIANCE ? LANG_BG_IC_ALLIANCE : LANG_BG_IC_HORDE)); + SendMessage2ToAll(LANG_BG_IC_TEAM_WINS, CHAT_MSG_BG_SYSTEM_NEUTRAL, nullptr, (winner == ALLIANCE ? LANG_BG_IC_ALLIANCE : LANG_BG_IC_HORDE)); Battleground::EndBattleground(winner); } @@ -842,10 +850,10 @@ void BattlegroundIC::DestroyGate(Player* player, GameObject* go) TC_LOG_ERROR("bg.battleground", "Isle of Conquest: There was an error spawning creature %u", BG_IC_NpcSpawnlocs[BG_IC_NPC_HIGH_COMMANDER_HALFORD_WYRMBANE].entry); } - SendMessage2ToAll(lang_entry, CHAT_MSG_BG_SYSTEM_NEUTRAL, NULL, (player->GetTeamId() == TEAM_ALLIANCE ? LANG_BG_IC_HORDE_KEEP : LANG_BG_IC_ALLIANCE_KEEP)); + SendMessage2ToAll(lang_entry, CHAT_MSG_BG_SYSTEM_NEUTRAL, nullptr, (player->GetTeamId() == TEAM_ALLIANCE ? LANG_BG_IC_HORDE_KEEP : LANG_BG_IC_ALLIANCE_KEEP)); } -WorldSafeLocsEntry const* BattlegroundIC::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundIC::GetClosestGraveyard(Player* player) { TeamId teamIndex = GetTeamIndexByTeamId(player->GetTeam()); @@ -855,7 +863,7 @@ WorldSafeLocsEntry const* BattlegroundIC::GetClosestGraveYard(Player* player) if (nodePoint[i].faction == player->GetTeamId()) nodes.push_back(i); - WorldSafeLocsEntry const* good_entry = NULL; + WorldSafeLocsEntry const* good_entry = nullptr; // If so, select the closest node to place ghost on if (!nodes.empty()) { diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.h b/src/server/game/Battlegrounds/Zones/BattlegroundIC.h index 0f04c60d22a..ef1724dd191 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.h @@ -903,12 +903,7 @@ struct BattlegroundICScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(2); // Objectives Count - data << uint32(BasesAssaulted); - data << uint32(BasesDefended); - } + void BuildObjectivesBlock(WorldPacket& data) final override; uint32 GetAttr1() const final override { return BasesAssaulted; } uint32 GetAttr2() const final override { return BasesDefended; } @@ -940,7 +935,7 @@ class BattlegroundIC : public Battleground void DestroyGate(Player* player, GameObject* go) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; /* Scorekeeping */ void FillInitialWorldStates(WorldPacket& data) override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp index d4380b043d7..e0df1d6138d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp @@ -17,6 +17,7 @@ */ #include "BattlegroundNA.h" +#include "Log.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp index be508ee3c9a..fd4d206385c 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp @@ -17,6 +17,7 @@ */ #include "BattlegroundRL.h" +#include "Log.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp index 35fb94b3cc3..9356110a228 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp @@ -18,6 +18,7 @@ #include "BattlegroundRV.h" #include "GameObject.h" +#include "Log.h" #include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp index 936106052c0..b28f31cd09c 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp @@ -17,14 +17,26 @@ */ #include "BattlegroundSA.h" +#include "DBCStores.h" #include "GameObject.h" #include "GameTime.h" #include "Language.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptedCreature.h" +#include "UpdateData.h" #include "WorldPacket.h" +void BattlegroundSAScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(2); // Objectives Count + data << uint32(DemolishersDestroyed); + data << uint32(GatesDestroyed); +} + BattlegroundSA::BattlegroundSA() { StartMessageIds[BG_STARTING_EVENT_FIRST] = LANG_BG_SA_START_TWO_MINUTES; @@ -152,8 +164,8 @@ bool BattlegroundSA::ResetObjs() } // MAD props for Kiper for discovering those values - 4 hours of his work. - GetBGObject(BG_SA_BOAT_ONE)->SetParentRotation(G3D::Quat(0.f, 0.f, 1.0f, 0.0002f)); - GetBGObject(BG_SA_BOAT_TWO)->SetParentRotation(G3D::Quat(0.f, 0.f, 1.0f, 0.00001f)); + GetBGObject(BG_SA_BOAT_ONE)->SetParentRotation(QuaternionData(0.f, 0.f, 1.0f, 0.0002f)); + GetBGObject(BG_SA_BOAT_TWO)->SetParentRotation(QuaternionData(0.f, 0.f, 1.0f, 0.00001f)); SpawnBGObject(BG_SA_BOAT_ONE, RESPAWN_IMMEDIATELY); SpawnBGObject(BG_SA_BOAT_TWO, RESPAWN_IMMEDIATELY); @@ -186,7 +198,7 @@ bool BattlegroundSA::ResetObjs() //Graveyards for (uint8 i = 0; i < BG_SA_MAX_GY; i++) { - WorldSafeLocsEntry const* sg = NULL; + WorldSafeLocsEntry const* sg = nullptr; sg = sWorldSafeLocsStore.LookupEntry(BG_SA_GYEntries[i]); if (!sg) @@ -541,7 +553,7 @@ void BattlegroundSA::TeleportToEntrancePosition(Player* player) player->TeleportTo(607, 1209.7f, -65.16f, 70.1f, 0.0f, 0); } -void BattlegroundSA::ProcessEvent(WorldObject* obj, uint32 eventId, WorldObject* invoker /*= NULL*/) +void BattlegroundSA::ProcessEvent(WorldObject* obj, uint32 eventId, WorldObject* invoker /*= nullptr*/) { if (GameObject* go = obj->ToGameObject()) { @@ -686,7 +698,7 @@ void BattlegroundSA::DestroyGate(Player* /*player*/, GameObject* /*go*/) { } -WorldSafeLocsEntry const* BattlegroundSA::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundSA::GetClosestGraveyard(Player* player) { uint32 safeloc = 0; WorldSafeLocsEntry const* ret; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.h b/src/server/game/Battlegrounds/Zones/BattlegroundSA.h index afbeffcd4e9..fc047b892c6 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.h @@ -531,12 +531,7 @@ struct BattlegroundSAScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(2); // Objectives Count - data << uint32(DemolishersDestroyed); - data << uint32(GatesDestroyed); - } + void BuildObjectivesBlock(WorldPacket& data) final override; uint32 GetAttr1() const final override { return DemolishersDestroyed; } uint32 GetAttr2() const final override { return GatesDestroyed; } @@ -573,9 +568,9 @@ class BattlegroundSA : public Battleground /// Called when a player kill a unit in bg void HandleKillUnit(Creature* creature, Player* killer) override; /// Return the nearest graveyard where player can respawn - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; /// Called when someone activates an event - void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = NULL) override; + void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = nullptr) override; /// Called when a player click on flag (graveyard flag) void EventPlayerClickedOnFlag(Player* source, GameObject* go) override; /// Called when a player clicked on relic @@ -587,7 +582,7 @@ class BattlegroundSA : public Battleground for (uint8 i = 0; i < MAX_GATES; ++i) if (Gates[i].GameObjectId == entry) return &Gates[i]; - return NULL; + return nullptr; } /// Called on battleground ending @@ -600,7 +595,7 @@ class BattlegroundSA : public Battleground /* Scorekeeping */ // Achievement: Not Even a Scratch - bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target = NULL, uint32 miscValue = 0) override; + bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target = nullptr, uint32 miscValue = 0) override; // Control Phase Shift bool IsSpellAllowed(uint32 spellId, Player const* player) const override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp index 6045ee78352..0129197e9ec 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp @@ -17,13 +17,16 @@ */ #include "BattlegroundWS.h" +#include "BattlegroundMgr.h" +#include "DBCStores.h" #include "GameObject.h" #include "Language.h" +#include "Log.h" +#include "Map.h" #include "Object.h" -#include "BattlegroundMgr.h" +#include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" -#include "ObjectAccessor.h" // these variables aren't used outside of this file, so declare them only here enum BG_WSG_Rewards @@ -69,6 +72,13 @@ BattlegroundWS::BattlegroundWS() _minutesElapsed = 0; } +void BattlegroundWGScore::BuildObjectivesBlock(WorldPacket& data) +{ + data << uint32(2); // Objectives Count + data << uint32(FlagCaptures); + data << uint32(FlagReturns); +} + BattlegroundWS::~BattlegroundWS() { } void BattlegroundWS::PostUpdateImpl(uint32 diff) @@ -804,7 +814,7 @@ bool BattlegroundWS::UpdatePlayerScore(Player* player, uint32 type, uint32 value return true; } -WorldSafeLocsEntry const* BattlegroundWS::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundWS::GetClosestGraveyard(Player* player) { //if status in progress, it returns main graveyards with spiritguides //else it will return the graveyard in the flagroom - this is especially good diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.h b/src/server/game/Battlegrounds/Zones/BattlegroundWS.h index 6541148843c..c6ab47eb7ba 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.h @@ -170,12 +170,7 @@ struct BattlegroundWGScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data) final override - { - data << uint32(2); // Objectives Count - data << uint32(FlagCaptures); - data << uint32(FlagReturns); - } + void BuildObjectivesBlock(WorldPacket& data) final override; uint32 GetAttr1() const final override { return FlagCaptures; } uint32 GetAttr2() const final override { return FlagReturns; } @@ -222,7 +217,7 @@ class BattlegroundWS : public Battleground bool SetupBattleground() override; void Reset() override; void EndBattleground(uint32 winner) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; void UpdateFlagState(uint32 team, uint32 value); void SetLastFlagCapture(uint32 team) { _lastFlagCaptureTeam = team; } diff --git a/src/server/game/Calendar/CalendarMgr.cpp b/src/server/game/Calendar/CalendarMgr.cpp index 4e86fdd1775..08a406c4f15 100644 --- a/src/server/game/Calendar/CalendarMgr.cpp +++ b/src/server/game/Calendar/CalendarMgr.cpp @@ -17,12 +17,15 @@ #include "CalendarMgr.h" #include "CharacterCache.h" -#include "QueryResult.h" -#include "Log.h" -#include "Player.h" +#include "DatabaseEnv.h" +#include "Guild.h" #include "GuildMgr.h" +#include "Log.h" +#include "Mail.h" #include "ObjectAccessor.h" #include "Opcodes.h" +#include "Player.h" +#include "WorldPacket.h" CalendarInvite::~CalendarInvite() { @@ -297,7 +300,7 @@ CalendarEvent* CalendarMgr::GetEvent(uint64 eventId) const return *itr; TC_LOG_DEBUG("calendar", "CalendarMgr::GetEvent: [" UI64FMTD "] not found!", eventId); - return NULL; + return nullptr; } CalendarInvite* CalendarMgr::GetInvite(uint64 inviteId) const @@ -308,7 +311,7 @@ CalendarInvite* CalendarMgr::GetInvite(uint64 inviteId) const return *itr2; TC_LOG_DEBUG("calendar", "CalendarMgr::GetInvite: [" UI64FMTD "] not found!", inviteId); - return NULL; + return nullptr; } void CalendarMgr::FreeEventId(uint64 id) @@ -618,7 +621,7 @@ void CalendarMgr::SendCalendarClearPendingAction(ObjectGuid guid) } } -void CalendarMgr::SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param /*= NULL*/) +void CalendarMgr::SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param /*= nullptr*/) { if (Player* player = ObjectAccessor::FindConnectedPlayer(guid)) { diff --git a/src/server/game/Calendar/CalendarMgr.h b/src/server/game/Calendar/CalendarMgr.h index ed590378f59..ded691c241d 100644 --- a/src/server/game/Calendar/CalendarMgr.h +++ b/src/server/game/Calendar/CalendarMgr.h @@ -19,9 +19,14 @@ #define TRINITY_CALENDARMGR_H #include "Common.h" -#include "DatabaseEnv.h" -#include "WorldPacket.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" +#include +#include +#include +#include + +class WorldPacket; enum CalendarMailAnswers { @@ -141,7 +146,7 @@ struct TC_GAME_API CalendarInvite _text = calendarInvite.GetText(); } - CalendarInvite() : _inviteId(1), _eventId(0), _invitee(), _senderGUID(), _statusTime(time(NULL)), + CalendarInvite() : _inviteId(1), _eventId(0), _invitee(), _senderGUID(), _statusTime(time(nullptr)), _status(CALENDAR_STATUS_INVITED), _rank(CALENDAR_RANK_PLAYER), _text("") { } CalendarInvite(uint64 inviteId, uint64 eventId, ObjectGuid invitee, ObjectGuid senderGUID, time_t statusTime, @@ -324,7 +329,7 @@ class TC_GAME_API CalendarMgr void SendCalendarEventRemovedAlert(CalendarEvent const& calendarEvent); void SendCalendarEventModeratorStatusAlert(CalendarEvent const& calendarEvent, CalendarInvite const& invite); void SendCalendarClearPendingAction(ObjectGuid guid); - void SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param = NULL); + void SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param = nullptr); void SendPacketToAllEventRelatives(WorldPacket& packet, CalendarEvent const& calendarEvent); }; diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index 83f25ddf0b2..fc6b38f0e69 100644 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -17,17 +17,20 @@ */ #include "Channel.h" +#include "AccountMgr.h" #include "ChannelAppenders.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "ObjectMgr.h" #include "Language.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" #include "SocialMgr.h" #include "World.h" -#include "DatabaseEnv.h" -#include "AccountMgr.h" -#include "Player.h" Channel::Channel(uint32 channelId, uint32 team /*= 0*/, AreaTableEntry const* zoneEntry /*= nullptr*/) : _announceEnabled(false), // no join/leave announces diff --git a/src/server/game/Chat/Channels/Channel.h b/src/server/game/Chat/Channels/Channel.h index 5c7460f10ec..364bec73a5f 100644 --- a/src/server/game/Chat/Channels/Channel.h +++ b/src/server/game/Chat/Channels/Channel.h @@ -20,11 +20,12 @@ #define _CHANNEL_H #include "Common.h" - -#include "WorldSession.h" -#include "WorldPacket.h" +#include "ObjectGuid.h" +#include +#include class Player; +struct AreaTableEntry; enum ChatNotify { diff --git a/src/server/game/Chat/Channels/ChannelAppenders.h b/src/server/game/Chat/Channels/ChannelAppenders.h index 03daf416f30..a6723ed1f8e 100644 --- a/src/server/game/Chat/Channels/ChannelAppenders.h +++ b/src/server/game/Chat/Channels/ChannelAppenders.h @@ -20,6 +20,8 @@ #include "Channel.h" #include "CharacterCache.h" +#include "World.h" +#include "WorldPacket.h" // initial packet data (notify type and channel name) template @@ -185,10 +187,7 @@ struct ChannelOwnerAppend { explicit ChannelOwnerAppend(Channel const* channel, ObjectGuid const& ownerGuid) : _channel(channel), _ownerGuid(ownerGuid) { - CharacterCacheEntry const* cInfo = sCharacterCache->GetCharacterCacheByGuid(_ownerGuid); - if (!cInfo || cInfo->Name.empty()) - _ownerName = "PLAYER_NOT_FOUND"; - else + if (CharacterCacheEntry const* cInfo = sCharacterCache->GetCharacterCacheByGuid(_ownerGuid)) _ownerName = cInfo->Name; } diff --git a/src/server/game/Chat/Channels/ChannelMgr.cpp b/src/server/game/Chat/Channels/ChannelMgr.cpp index 86328202737..48fd564af28 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.cpp +++ b/src/server/game/Chat/Channels/ChannelMgr.cpp @@ -18,8 +18,10 @@ #include "Channel.h" #include "ChannelMgr.h" +#include "DBCStores.h" #include "Player.h" #include "World.h" +#include "WorldSession.h" ChannelMgr::~ChannelMgr() { diff --git a/src/server/game/Chat/Channels/ChannelMgr.h b/src/server/game/Chat/Channels/ChannelMgr.h index ff1c7d6fd31..5482c3e2e1c 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.h +++ b/src/server/game/Chat/Channels/ChannelMgr.h @@ -18,9 +18,15 @@ #ifndef __TRINITY_CHANNELMGR_H #define __TRINITY_CHANNELMGR_H -#include "Common.h" +#include "Define.h" +#include "Hash.h" +#include +#include class Channel; +class Player; +class WorldPacket; +struct AreaTableEntry; class TC_GAME_API ChannelMgr { diff --git a/src/server/game/Chat/Chat.cpp b/src/server/game/Chat/Chat.cpp index 3926dda13f5..3e15ecc9319 100644 --- a/src/server/game/Chat/Chat.cpp +++ b/src/server/game/Chat/Chat.cpp @@ -16,22 +16,28 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectMgr.h" -#include "World.h" -#include "WorldSession.h" -#include "DatabaseEnv.h" - +#include "Chat.h" #include "AccountMgr.h" #include "CellImpl.h" #include "CharacterCache.h" -#include "Chat.h" +#include "ChatLink.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" #include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Optional.h" #include "Player.h" +#include "Realm.h" #include "ScriptMgr.h" -#include "ChatLink.h" +#include "World.h" + +ChatCommand::ChatCommand(char const* name, uint32 permission, bool allowConsole, pHandler handler, std::string help, std::vector childCommands /*= std::vector()*/) + : Name(ASSERT_NOTNULL(name)), Permission(permission), AllowConsole(allowConsole), Handler(handler), Help(std::move(help)), ChildCommands(std::move(childCommands)) +{ +} // Lazy loading of the command table cache from commands and the // ScriptMgr should be thread safe since the player commands, @@ -80,6 +86,16 @@ bool ChatHandler::isAvailable(ChatCommand const& cmd) const return HasPermission(cmd.Permission); } +bool ChatHandler::HasPermission(uint32 permission) const +{ + return m_session->HasPermission(permission); +} + +std::string ChatHandler::GetNameLink() const +{ + return GetNameLink(m_session->GetPlayer()); +} + bool ChatHandler::HasLowerSecurity(Player* target, ObjectGuid guid, bool strong) { WorldSession* target_session = nullptr; diff --git a/src/server/game/Chat/Chat.h b/src/server/game/Chat/Chat.h index 9bbe908fa0b..f2ab3772a0d 100644 --- a/src/server/game/Chat/Chat.h +++ b/src/server/game/Chat/Chat.h @@ -19,20 +19,21 @@ #ifndef TRINITYCORE_CHAT_H #define TRINITYCORE_CHAT_H +#include "Common.h" +#include "ObjectGuid.h" #include "SharedDefines.h" #include "StringFormat.h" -#include "WorldSession.h" -#include "RBAC.h" - #include class ChatHandler; class Creature; +class GameObject; class Group; class Player; class Unit; class WorldSession; class WorldObject; +class WorldPacket; struct GameTele; @@ -41,8 +42,7 @@ class TC_GAME_API ChatCommand typedef bool(*pHandler)(ChatHandler*, char const*); public: - ChatCommand(char const* name, uint32 permission, bool allowConsole, pHandler handler, std::string help, std::vector childCommands = std::vector()) - : Name(ASSERT_NOTNULL(name)), Permission(permission), AllowConsole(allowConsole), Handler(handler), Help(std::move(help)), ChildCommands(std::move(childCommands)) { } + ChatCommand(char const* name, uint32 permission, bool allowConsole, pHandler handler, std::string help, std::vector childCommands = std::vector()); char const* Name; uint32 Permission; // function pointer required correct align (use uint32) @@ -105,8 +105,8 @@ class TC_GAME_API ChatHandler // function with different implementation for chat/console virtual bool isAvailable(ChatCommand const& cmd) const; - virtual bool HasPermission(uint32 permission) const { return m_session->HasPermission(permission); } - virtual std::string GetNameLink() const { return GetNameLink(m_session->GetPlayer()); } + virtual bool HasPermission(uint32 permission) const; + virtual std::string GetNameLink() const; virtual bool needReportToTarget(Player* chr) const; virtual LocaleConstant GetSessionDbcLocale() const; virtual int GetSessionDbLocaleIndex() const; diff --git a/src/server/game/Chat/ChatLink.cpp b/src/server/game/Chat/ChatLink.cpp index 126124e2f07..db07e9e2efd 100644 --- a/src/server/game/Chat/ChatLink.cpp +++ b/src/server/game/Chat/ChatLink.cpp @@ -16,11 +16,12 @@ */ #include "ChatLink.h" -#include "SpellMgr.h" +#include "AchievementMgr.h" +#include "DBCStores.h" +#include "Log.h" #include "ObjectMgr.h" #include "SpellInfo.h" -#include "DBCStores.h" -#include "AchievementMgr.h" +#include "SpellMgr.h" // Supported shift-links (client generated and server side) // |color|Hachievement:achievement_id:player_guid:0:0:0:0:0:0:0:0|h[name]|h|r diff --git a/src/server/game/Chat/ChatLink.h b/src/server/game/Chat/ChatLink.h index c801deffe48..83864e58520 100644 --- a/src/server/game/Chat/ChatLink.h +++ b/src/server/game/Chat/ChatLink.h @@ -19,8 +19,10 @@ #define TRINITYCORE_CHATLINK_H #include "SharedDefines.h" -#include +#include "Common.h" #include +#include +#include #include struct ItemLocale; diff --git a/src/server/game/Combat/ThreatManager.cpp b/src/server/game/Combat/ThreatManager.cpp index c858314dc16..005e8fad2a8 100644 --- a/src/server/game/Combat/ThreatManager.cpp +++ b/src/server/game/Combat/ThreatManager.cpp @@ -44,7 +44,7 @@ float ThreatCalcHelper::calcThreat(Unit* hatedUnit, Unit* /*hatingUnit*/, float return threat; if (Player* modOwner = hatedUnit->GetSpellModOwner()) - modOwner->ApplySpellMod(threatSpell->Id, threat); + modOwner->ApplySpellMod(threatSpell->Id, SPELLMOD_THREAT, threat); } return hatedUnit->ApplyTotalThreatModifier(threat, schoolMask); @@ -266,7 +266,7 @@ void ThreatContainer::clearReferences() HostileReference* ThreatContainer::getReferenceByTarget(Unit* victim) const { if (!victim) - return NULL; + return nullptr; ObjectGuid guid = victim->GetGUID(); for (ThreatContainer::StorageType::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i) @@ -276,7 +276,7 @@ HostileReference* ThreatContainer::getReferenceByTarget(Unit* victim) const return ref; } - return NULL; + return nullptr; } //============================================================ @@ -315,7 +315,7 @@ void ThreatContainer::update() HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileReference* currentVictim) const { - HostileReference* currentRef = NULL; + HostileReference* currentRef = nullptr; bool found = false; bool noPriorityTargetFound = false; @@ -380,7 +380,7 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileR ++iter; } if (!found) - currentRef = NULL; + currentRef = nullptr; return currentRef; } @@ -389,7 +389,7 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileR //=================== ThreatManager ========================== //============================================================ -ThreatManager::ThreatManager(Unit* owner) : iCurrentVictim(NULL), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL) { } +ThreatManager::ThreatManager(Unit* owner) : iCurrentVictim(nullptr), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL) { } //============================================================ @@ -397,7 +397,7 @@ void ThreatManager::clearReferences() { iThreatContainer.clearReferences(); iThreatOfflineContainer.clearReferences(); - iCurrentVictim = NULL; + iCurrentVictim = nullptr; iUpdateTimer = THREAT_UPDATE_INTERVAL; } @@ -465,7 +465,7 @@ Unit* ThreatManager::getHostilTarget() iThreatContainer.update(); HostileReference* nextVictim = iThreatContainer.selectNextVictim(GetOwner()->ToCreature(), getCurrentVictim()); setCurrentVictim(nextVictim); - return getCurrentVictim() != NULL ? getCurrentVictim()->getTarget() : NULL; + return getCurrentVictim() != nullptr ? getCurrentVictim()->getTarget() : nullptr; } //============================================================ @@ -535,7 +535,7 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat { if (hostilRef == getCurrentVictim()) { - setCurrentVictim(NULL); + setCurrentVictim(nullptr); setDirty(true); } iOwner->SendRemoveFromThreatListOpcode(hostilRef); @@ -553,7 +553,7 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat case UEV_THREAT_REF_REMOVE_FROM_LIST: if (hostilRef == getCurrentVictim()) { - setCurrentVictim(NULL); + setCurrentVictim(nullptr); setDirty(true); } iOwner->SendRemoveFromThreatListOpcode(hostilRef); diff --git a/src/server/game/Combat/ThreatManager.h b/src/server/game/Combat/ThreatManager.h index e17a6926ffd..c500663214e 100644 --- a/src/server/game/Combat/ThreatManager.h +++ b/src/server/game/Combat/ThreatManager.h @@ -212,7 +212,7 @@ class TC_GAME_API ThreatManager void clearReferences(); - void addThreat(Unit* victim, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL); + void addThreat(Unit* victim, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); void doAddThreat(Unit* victim, float threat); diff --git a/src/server/game/Conditions/ConditionMgr.cpp b/src/server/game/Conditions/ConditionMgr.cpp index 4d7146b1f3c..146d2cb3bde 100644 --- a/src/server/game/Conditions/ConditionMgr.cpp +++ b/src/server/game/Conditions/ConditionMgr.cpp @@ -18,16 +18,21 @@ #include "ConditionMgr.h" #include "AchievementMgr.h" +#include "DatabaseEnv.h" #include "GameEventMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Log.h" +#include "LootMgr.h" +#include "Map.h" #include "ObjectMgr.h" #include "Player.h" #include "Pet.h" #include "ReputationMgr.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "SpellMgr.h" +#include "World.h" char const* const ConditionMgr::StaticSourceTypeData[CONDITION_SOURCE_TYPE_MAX] = { @@ -289,12 +294,12 @@ bool Condition::Meets(ConditionSourceInfo& sourceInfo) const } case CONDITION_NEAR_CREATURE: { - condMeets = GetClosestCreatureWithEntry(object, ConditionValue1, (float)ConditionValue2, bool(!ConditionValue3)) ? true : false; + condMeets = object->FindNearestCreature(ConditionValue1, (float)ConditionValue2, bool(!ConditionValue3)) != nullptr; break; } case CONDITION_NEAR_GAMEOBJECT: { - condMeets = GetClosestGameObjectWithEntry(object, ConditionValue1, (float)ConditionValue2) ? true : false; + condMeets = object->FindNearestGameObject(ConditionValue1, (float)ConditionValue2) != nullptr; break; } case CONDITION_OBJECT_ENTRY_GUID: @@ -1073,7 +1078,7 @@ void ConditionMgr::LoadConditions(bool isReload) } cond->ReferenceId = uint32(abs(iConditionTypeOrReference)); - const char* rowType = "reference template"; + char const* rowType = "reference template"; if (iSourceTypeOrReferenceId >= 0) rowType = "reference"; //check for useless data diff --git a/src/server/game/Conditions/ConditionMgr.h b/src/server/game/Conditions/ConditionMgr.h index 6e9086d45f7..ff3f096abae 100644 --- a/src/server/game/Conditions/ConditionMgr.h +++ b/src/server/game/Conditions/ConditionMgr.h @@ -19,7 +19,11 @@ #ifndef TRINITY_CONDITIONMGR_H #define TRINITY_CONDITIONMGR_H -#include "Common.h" +#include "Define.h" +#include "Hash.h" +#include +#include +#include class Creature; class Player; diff --git a/src/server/game/Conditions/DisableMgr.cpp b/src/server/game/Conditions/DisableMgr.cpp index c121cb2c15e..747ea936673 100644 --- a/src/server/game/Conditions/DisableMgr.cpp +++ b/src/server/game/Conditions/DisableMgr.cpp @@ -18,10 +18,13 @@ #include "DisableMgr.h" #include "AchievementMgr.h" +#include "DatabaseEnv.h" +#include "Log.h" #include "ObjectMgr.h" #include "OutdoorPvP.h" -#include "SpellMgr.h" #include "Player.h" +#include "SpellMgr.h" +#include "VMapManager2.h" #include "World.h" namespace DisableMgr @@ -391,13 +394,13 @@ bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags bool IsVMAPDisabledFor(uint32 entry, uint8 flags) { - return IsDisabledFor(DISABLE_TYPE_VMAP, entry, NULL, flags); + return IsDisabledFor(DISABLE_TYPE_VMAP, entry, nullptr, flags); } bool IsPathfindingEnabled(uint32 mapId) { return sWorld->getBoolConfig(CONFIG_ENABLE_MMAPS) - && !IsDisabledFor(DISABLE_TYPE_MMAP, mapId, NULL, MMAP_DISABLE_PATHFINDING); + && !IsDisabledFor(DISABLE_TYPE_MMAP, mapId, nullptr, MMAP_DISABLE_PATHFINDING); } } // Namespace diff --git a/src/server/game/Conditions/DisableMgr.h b/src/server/game/Conditions/DisableMgr.h index c7172b2ec23..ea76481c977 100644 --- a/src/server/game/Conditions/DisableMgr.h +++ b/src/server/game/Conditions/DisableMgr.h @@ -19,7 +19,6 @@ #ifndef TRINITY_DISABLEMGR_H #define TRINITY_DISABLEMGR_H -#include "VMapManager2.h" #include "Define.h" class Unit; diff --git a/src/server/game/DataStores/DBCEnums.h b/src/server/game/DataStores/DBCEnums.h index b8e429c0d14..f7d3fe325dc 100644 --- a/src/server/game/DataStores/DBCEnums.h +++ b/src/server/game/DataStores/DBCEnums.h @@ -19,6 +19,9 @@ #ifndef DBCENUMS_H #define DBCENUMS_H +#include "Define.h" +#include + #pragma pack(push, 1) struct DBCPosition2D @@ -115,7 +118,7 @@ enum AchievementCriteriaFlags ACHIEVEMENT_CRITERIA_FLAG_MONEY_COUNTER = 0x00000020 // Displays counter as money }; -enum AchievementCriteriaTimedTypes +enum AchievementCriteriaTimedTypes : uint8 { ACHIEVEMENT_TIMED_TYPE_EVENT = 1, // Timer is started by internal event with id in timerStartEvent ACHIEVEMENT_TIMED_TYPE_QUEST = 2, // Timer is started by accepting quest with entry in timerStartEvent @@ -127,7 +130,7 @@ enum AchievementCriteriaTimedTypes ACHIEVEMENT_TIMED_TYPE_MAX }; -enum AchievementCriteriaTypes +enum AchievementCriteriaTypes : uint8 { ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE = 0, ACHIEVEMENT_CRITERIA_TYPE_WIN_BG = 1, @@ -273,7 +276,7 @@ enum AreaFlags AREA_FLAG_NO_FLY_ZONE = 0x20000000 // Marks zones where you cannot fly }; -enum Difficulty +enum Difficulty : uint8 { REGULAR_DIFFICULTY = 0, @@ -383,6 +386,18 @@ enum SpellCategoryFlags SPELL_CATEGORY_FLAG_COOLDOWN_STARTS_ON_EVENT = 0x04 }; +#define MAX_SPELL_EFFECTS 3 +#define MAX_EFFECT_MASK 7 +#define MAX_SPELL_REAGENTS 8 + +enum EnchantmentSlotMask +{ + ENCHANTMENT_CAN_SOULBOUND = 0x01, + ENCHANTMENT_UNK1 = 0x02, + ENCHANTMENT_UNK2 = 0x04, + ENCHANTMENT_UNK3 = 0x08 +}; + // SummonProperties.dbc, col 1 enum SummonPropGroup { @@ -415,6 +430,13 @@ enum SummonPropFlags SUMMON_PROP_FLAG_UNK16 = 0x00008000 // Light/Dark Bullet, Soul/Fiery Consumption, Twisted Visage, Twilight Whelp. Phase related? }; +#define MAX_TALENT_RANK 5 +#define MAX_PET_TALENT_RANK 3 // use in calculations, expected <= MAX_TALENT_RANK +#define MAX_TALENT_TABS 3 + +#define TaxiMaskSize 14 +typedef std::array TaxiMask; + enum TotemCategoryType { TOTEM_CATEGORY_TYPE_KNIFE = 1, diff --git a/src/server/game/DataStores/DBCStores.cpp b/src/server/game/DataStores/DBCStores.cpp index e4db97cce4c..ce3463c5f5c 100644 --- a/src/server/game/DataStores/DBCStores.cpp +++ b/src/server/game/DataStores/DBCStores.cpp @@ -17,38 +17,26 @@ */ #include "DBCStores.h" +#include "DBCFileLoader.h" +#include "DBCfmt.h" +#include "Errors.h" #include "Log.h" +#include "ObjectDefines.h" +#include "Regex.h" #include "SharedDefines.h" #include "SpellMgr.h" -#include "TransportMgr.h" -#include "DBCfmt.h" #include "Timer.h" -#include "ObjectDefines.h" -#include "Regex.h" -#include +// temporary hack until includes are sorted out (don't want to pull in Windows.h) +#ifdef GetClassName +#undef GetClassName +#endif typedef std::map AreaFlagByAreaID; typedef std::map AreaFlagByMapID; -struct WMOAreaTableTripple -{ - WMOAreaTableTripple(int32 r, int32 a, int32 g) : groupId(g), rootId(r), adtId(a) - { - } - - bool operator <(const WMOAreaTableTripple& b) const - { - return memcmp(this, &b, sizeof(WMOAreaTableTripple))<0; - } - - // ordered by entropy; that way memcmp will have a minimal medium runtime - int32 groupId; - int32 rootId; - int32 adtId; -}; - -typedef std::map WMOAreaInfoByTripple; +typedef std::tuple WMOAreaTableKey; +typedef std::map WMOAreaInfoByTripple; typedef std::multimap CharSectionsMap; DBCStorage sAreaTableStore(AreaTableEntryfmt); @@ -231,18 +219,15 @@ static bool LoadDBC_assert_print(uint32 fsize, uint32 rsize, const std::string& } template -inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCStorage& storage, std::string const& dbcPath, std::string const& filename, std::string const* customFormat = NULL, std::string const* customIndexName = NULL) +inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCStorage& storage, std::string const& dbcPath, std::string const& filename, std::string const& customFormat = std::string(), std::string const& customIndexName = std::string()) { // compatibility format and C++ structure sizes ASSERT(DBCFileLoader::GetFormatRecordSize(storage.GetFormat()) == sizeof(T) || LoadDBC_assert_print(DBCFileLoader::GetFormatRecordSize(storage.GetFormat()), sizeof(T), filename)); ++DBCFileCount; std::string dbcFilename = dbcPath + filename; - SqlDbc * sql = NULL; - if (customFormat) - sql = new SqlDbc(&filename, customFormat, customIndexName, storage.GetFormat()); - if (storage.Load(dbcFilename.c_str(), sql)) + if (storage.Load(dbcFilename)) { for (uint8 i = 0; i < TOTAL_LOCALES; ++i) { @@ -255,8 +240,11 @@ inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCSt localizedName.append(filename); if (!storage.LoadStringsFrom(localizedName.c_str())) - availableDbcLocales &= ~(1<Race | (outfit->Class << 8) | (outfit->Gender << 16)] = outfit; - - LoadDBC(availableDbcLocales, bad_dbc_files, sCharSectionsStore, dbcPath, "CharSections.dbc"); - for (uint32 i = 0; i < sCharSectionsStore.GetNumRows(); ++i) - if (CharSectionsEntry const* entry = sCharSectionsStore.LookupEntry(i)) - if (entry->Race && ((1 << (entry->Race - 1)) & RACEMASK_ALL_PLAYABLE) != 0) //ignore Nonplayable races - sCharSectionMap.insert({ entry->GenType | (entry->Gender << 8) | (entry->Race << 16), entry }); - - LoadDBC(availableDbcLocales, bad_dbc_files, sCharTitlesStore, dbcPath, "CharTitles.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sChatChannelsStore, dbcPath, "ChatChannels.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sChrClassesStore, dbcPath, "ChrClasses.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sChrRacesStore, dbcPath, "ChrRaces.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicCameraStore, dbcPath, "CinematicCamera.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicSequencesStore, dbcPath, "CinematicSequences.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoStore, dbcPath, "CreatureDisplayInfo.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoExtraStore, dbcPath, "CreatureDisplayInfoExtra.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureFamilyStore, dbcPath, "CreatureFamily.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureModelDataStore, dbcPath, "CreatureModelData.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureSpellDataStore, dbcPath, "CreatureSpellData.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureTypeStore, dbcPath, "CreatureType.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCurrencyTypesStore, dbcPath, "CurrencyTypes.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sDestructibleModelDataStore, dbcPath, "DestructibleModelData.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sDungeonEncounterStore, dbcPath, "DungeonEncounter.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sDurabilityCostsStore, dbcPath, "DurabilityCosts.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sDurabilityQualityStore, dbcPath, "DurabilityQuality.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesStore, dbcPath, "Emotes.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesTextStore, dbcPath, "EmotesText.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesTextSoundStore, dbcPath, "EmotesTextSound.dbc"); - for (uint32 i = 0; i < sEmotesTextSoundStore.GetNumRows(); ++i) - if (EmotesTextSoundEntry const* entry = sEmotesTextSoundStore.LookupEntry(i)) - sEmotesTextSoundMap[EmotesTextSoundKey(entry->EmotesTextId, entry->RaceId, entry->SexId)] = entry; - LoadDBC(availableDbcLocales, bad_dbc_files, sFactionStore, dbcPath, "Faction.dbc"); - for (uint32 i=0; iRace | (outfit->Class << 8) | (outfit->Gender << 16)] = outfit; + + for (CharSectionsEntry const* entry : sCharSectionsStore) + if (entry->Race && ((1 << (entry->Race - 1)) & RACEMASK_ALL_PLAYABLE) != 0) //ignore Nonplayable races + sCharSectionMap.insert({ entry->GenType | (entry->Gender << 8) | (entry->Race << 16), entry }); + + for (EmotesTextSoundEntry const* entry : sEmotesTextSoundStore) + sEmotesTextSoundMap[EmotesTextSoundKey(entry->EmotesTextId, entry->RaceId, entry->SexId)] = entry; + + for (FactionEntry const* faction : sFactionStore) { - FactionEntry const* faction = sFactionStore.LookupEntry(i); - if (faction && faction->team) + if (faction->team) { - SimpleFactionsList &flist = sFactionTeamMap[faction->team]; - flist.push_back(i); + SimpleFactionsList& flist = sFactionTeamMap[faction->team]; + flist.push_back(faction->ID); } } - LoadDBC(availableDbcLocales, bad_dbc_files, sFactionTemplateStore, dbcPath, "FactionTemplate.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGameObjectDisplayInfoStore, dbcPath, "GameObjectDisplayInfo.dbc"); - for (uint32 i = 0; i < sGameObjectDisplayInfoStore.GetNumRows(); ++i) + for (GameObjectDisplayInfoEntry const* info : sGameObjectDisplayInfoStore) { - if (GameObjectDisplayInfoEntry const* info = sGameObjectDisplayInfoStore.LookupEntry(i)) - { - if (info->maxX < info->minX) - std::swap(*(float*)(&info->maxX), *(float*)(&info->minX)); - if (info->maxY < info->minY) - std::swap(*(float*)(&info->maxY), *(float*)(&info->minY)); - if (info->maxZ < info->minZ) - std::swap(*(float*)(&info->maxZ), *(float*)(&info->minZ)); - } + if (info->maxX < info->minX) + std::swap(*(float*)(&info->maxX), *(float*)(&info->minX)); + if (info->maxY < info->minY) + std::swap(*(float*)(&info->maxY), *(float*)(&info->minY)); + if (info->maxZ < info->minZ) + std::swap(*(float*)(&info->maxZ), *(float*)(&info->minZ)); } - LoadDBC(availableDbcLocales, bad_dbc_files, sGemPropertiesStore, dbcPath, "GemProperties.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGlyphPropertiesStore, dbcPath, "GlyphProperties.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGlyphSlotStore, dbcPath, "GlyphSlot.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtBarberShopCostBaseStore, dbcPath, "gtBarberShopCostBase.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtCombatRatingsStore, dbcPath, "gtCombatRatings.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToMeleeCritBaseStore, dbcPath, "gtChanceToMeleeCritBase.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToMeleeCritStore, dbcPath, "gtChanceToMeleeCrit.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToSpellCritBaseStore, dbcPath, "gtChanceToSpellCritBase.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToSpellCritStore, dbcPath, "gtChanceToSpellCrit.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtNPCManaCostScalerStore, dbcPath, "gtNPCManaCostScaler.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTClassCombatRatingScalarStore, dbcPath, "gtOCTClassCombatRatingScalar.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTRegenHPStore, dbcPath, "gtOCTRegenHP.dbc"); - //LoadDBC(dbcCount, availableDbcLocales, bad_dbc_files, sGtOCTRegenMPStore, dbcPath, "gtOCTRegenMP.dbc"); -- not used currently - LoadDBC(availableDbcLocales, bad_dbc_files, sGtRegenHPPerSptStore, dbcPath, "gtRegenHPPerSpt.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtRegenMPPerSptStore, dbcPath, "gtRegenMPPerSpt.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sHolidaysStore, dbcPath, "Holidays.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sItemStore, dbcPath, "Item.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sItemBagFamilyStore, dbcPath, "ItemBagFamily.dbc"); - //LoadDBC(dbcCount, availableDbcLocales, bad_dbc_files, sItemDisplayInfoStore, dbcPath, "ItemDisplayInfo.dbc"); -- not used currently - //LoadDBC(dbcCount, availableDbcLocales, bad_dbc_files, sItemCondExtCostsStore, dbcPath, "ItemCondExtCosts.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sItemExtendedCostStore, dbcPath, "ItemExtendedCost.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sItemLimitCategoryStore, dbcPath, "ItemLimitCategory.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sItemRandomPropertiesStore, dbcPath, "ItemRandomProperties.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sItemRandomSuffixStore, dbcPath, "ItemRandomSuffix.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sItemSetStore, dbcPath, "ItemSet.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sLFGDungeonStore, dbcPath, "LFGDungeons.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sLightStore, dbcPath, "Light.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sLiquidTypeStore, dbcPath, "LiquidType.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sLockStore, dbcPath, "Lock.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sMailTemplateStore, dbcPath, "MailTemplate.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sMapStore, dbcPath, "Map.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sMapDifficultyStore, dbcPath, "MapDifficulty.dbc"); // fill data - for (uint32 i = 1; i < sMapDifficultyStore.GetNumRows(); ++i) - if (MapDifficultyEntry const* entry = sMapDifficultyStore.LookupEntry(i)) - sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = MapDifficulty(entry->resetTime, entry->maxPlayers, entry->areaTriggerText[0] != '\0'); - sMapDifficultyStore.Clear(); - - LoadDBC(availableDbcLocales, bad_dbc_files, sMovieStore, dbcPath, "Movie.dbc"); + for (MapDifficultyEntry const* entry : sMapDifficultyStore) + sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = MapDifficulty(entry->resetTime, entry->maxPlayers, entry->areaTriggerText[0] != '\0'); - LoadDBC(availableDbcLocales, bad_dbc_files, sNamesProfanityStore, dbcPath, "NamesProfanity.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sNamesReservedStore, dbcPath, "NamesReserved.dbc"); - for (uint32 i = 0; i < sNamesProfanityStore.GetNumRows(); ++i) + for (NamesProfanityEntry const* namesProfanity : sNamesProfanityStore) { - NamesProfanityEntry const* namesProfanity = sNamesProfanityStore.LookupEntry(i); - if (!namesProfanity) - continue; - ASSERT(namesProfanity->Language < TOTAL_LOCALES || namesProfanity->Language == -1); std::wstring wname; ASSERT(Utf8toWStr(namesProfanity->Name, wname)); @@ -420,12 +441,8 @@ void LoadDBCStores(const std::string& dataPath) NamesProfaneValidators[i].emplace_back(wname, Trinity::regex::icase | Trinity::regex::optimize); } - for (uint32 i = 0; i < sNamesReservedStore.GetNumRows(); ++i) + for (NamesReservedEntry const* namesReserved : sNamesReservedStore) { - NamesReservedEntry const* namesReserved = sNamesReservedStore.LookupEntry(i); - if (!namesReserved) - continue; - ASSERT(namesReserved->Language < TOTAL_LOCALES || namesReserved->Language == -1); std::wstring wname; ASSERT(Utf8toWStr(namesReserved->Name, wname)); @@ -437,53 +454,21 @@ void LoadDBCStores(const std::string& dataPath) NamesReservedValidators[i].emplace_back(wname, Trinity::regex::icase | Trinity::regex::optimize); } + for (PvPDifficultyEntry const* entry : sPvPDifficultyStore) + if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) + ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); - LoadDBC(availableDbcLocales, bad_dbc_files, sOverrideSpellDataStore, dbcPath, "OverrideSpellData.dbc"); + for (SkillRaceClassInfoEntry const* entry : sSkillRaceClassInfoStore) + if (sSkillLineStore.LookupEntry(entry->SkillId)) + SkillRaceClassInfoBySkill.emplace(entry->SkillId, entry); - LoadDBC(availableDbcLocales, bad_dbc_files, sPowerDisplayStore, dbcPath, "PowerDisplay.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sPvPDifficultyStore, dbcPath, "PvpDifficulty.dbc"); - for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) - if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) - if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) - ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestXPStore, dbcPath, "QuestXP.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestFactionRewardStore, dbcPath, "QuestFactionReward.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestSortStore, dbcPath, "QuestSort.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sRandomPropertiesPointsStore, dbcPath, "RandPropPoints.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sScalingStatDistributionStore, dbcPath, "ScalingStatDistribution.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sScalingStatValuesStore, dbcPath, "ScalingStatValues.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillLineStore, dbcPath, "SkillLine.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillLineAbilityStore, dbcPath, "SkillLineAbility.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillRaceClassInfoStore, dbcPath, "SkillRaceClassInfo.dbc"); - for (uint32 i = 0; i < sSkillRaceClassInfoStore.GetNumRows(); ++i) - if (SkillRaceClassInfoEntry const* entry = sSkillRaceClassInfoStore.LookupEntry(i)) - if (sSkillLineStore.LookupEntry(entry->SkillId)) - SkillRaceClassInfoBySkill.emplace(entry->SkillId, entry); - - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillTiersStore, dbcPath, "SkillTiers.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSoundEntriesStore, dbcPath, "SoundEntries.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellStore, dbcPath, "Spell.dbc", &CustomSpellEntryfmt, &CustomSpellEntryIndex); - - for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) + for (SkillLineAbilityEntry const* skillLine : sSkillLineAbilityStore) { - SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j); - - if (!skillLine) - continue; - SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId); - if (spellInfo && spellInfo->Attributes & SPELL_ATTR0_PASSIVE) { - for (uint32 i = 1; i < sCreatureFamilyStore.GetNumRows(); ++i) + for (CreatureFamilyEntry const* cFamily : sCreatureFamilyStore) { - CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(i); - if (!cFamily) - continue; - if (skillLine->skillId != cFamily->skillLine[0] && skillLine->skillId != cFamily->skillLine[1]) continue; if (spellInfo->spellLevel) @@ -492,37 +477,17 @@ void LoadDBCStores(const std::string& dataPath) if (skillLine->AutolearnType != SKILL_LINE_ABILITY_LEARNED_ON_SKILL_LEARN) continue; - sPetFamilySpellsStore[i].insert(spellInfo->Id); + sPetFamilySpellsStore[cFamily->ID].insert(spellInfo->Id); } } } - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCastTimesStore, dbcPath, "SpellCastTimes.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCategoryStore, dbcPath, "SpellCategory.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellDifficultyStore, dbcPath, "SpellDifficulty.dbc", &CustomSpellDifficultyfmt, &CustomSpellDifficultyIndex); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellDurationStore, dbcPath, "SpellDuration.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellFocusObjectStore, dbcPath, "SpellFocusObject.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellItemEnchantmentStore, dbcPath, "SpellItemEnchantment.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellItemEnchantmentConditionStore, dbcPath, "SpellItemEnchantmentCondition.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRadiusStore, dbcPath, "SpellRadius.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRangeStore, dbcPath, "SpellRange.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRuneCostStore, dbcPath, "SpellRuneCost.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellShapeshiftStore, dbcPath, "SpellShapeshiftForm.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sStableSlotPricesStore, dbcPath, "StableSlotPrices.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSummonPropertiesStore, dbcPath, "SummonProperties.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sTalentStore, dbcPath, "Talent.dbc"); - // Create Spelldifficulty searcher - for (uint32 i = 0; i < sSpellDifficultyStore.GetNumRows(); ++i) + for (SpellDifficultyEntry const* spellDiff : sSpellDifficultyStore) { - SpellDifficultyEntry const* spellDiff = sSpellDifficultyStore.LookupEntry(i); - if (!spellDiff) - continue; - SpellDifficultyEntry newEntry; memset(newEntry.SpellID, 0, 4*sizeof(uint32)); - for (int x = 0; x < MAX_DIFFICULTY; ++x) + for (uint8 x = 0; x < MAX_DIFFICULTY; ++x) { if (spellDiff->SpellID[x] <= 0 || !sSpellStore.LookupEntry(spellDiff->SpellID[x])) { @@ -536,34 +501,25 @@ void LoadDBCStores(const std::string& dataPath) if (newEntry.SpellID[0] <= 0 || newEntry.SpellID[1] <= 0)//id0-1 must be always set! continue; - for (int x = 0; x < MAX_DIFFICULTY; ++x) + for (uint8 x = 0; x < MAX_DIFFICULTY; ++x) if (newEntry.SpellID[x]) sSpellMgr->SetSpellDifficultyId(uint32(newEntry.SpellID[x]), spellDiff->ID); } // create talent spells set - for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i) + for (TalentEntry const* talentInfo : sTalentStore) { - TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); - if (!talentInfo) - continue; - - for (int j = 0; j < MAX_TALENT_RANK; j++) + for (uint8 j = 0; j < MAX_TALENT_RANK; ++j) if (talentInfo->RankID[j]) - sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(i, j); + sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(talentInfo->TalentID, j); } - LoadDBC(availableDbcLocales, bad_dbc_files, sTalentTabStore, dbcPath, "TalentTab.dbc"); // prepare fast data access to bit pos of talent ranks for use at inspecting { // now have all max ranks (and then bit amount used for store talent ranks in inspect) - for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId) + for (TalentTabEntry const* talentTabInfo : sTalentTabStore) { - TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentTabId); - if (!talentTabInfo) - continue; - // prevent memory corruption; otherwise cls will become 12 below if ((talentTabInfo->ClassMask & CLASSMASK_ALL_PLAYABLE) == 0) continue; @@ -571,59 +527,48 @@ void LoadDBCStores(const std::string& dataPath) // store class talent tab pages for (uint32 cls = 1; cls < MAX_CLASSES; ++cls) if (talentTabInfo->ClassMask & (1 << (cls - 1))) - sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabId; + sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabInfo->TalentTabID; } } - LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiNodesStore, dbcPath, "TaxiNodes.dbc"); - LoadDBC(availableDbcLocales, 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(); + for (TaxiPathEntry const* entry : sTaxiPathStore) + sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID, entry->price); - //## TaxiPathNode.dbc ## Loaded only for initialization different structures - LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiPathNodeStore, dbcPath, "TaxiPathNode.dbc"); + uint32 pathCount = sTaxiPathStore.GetNumRows(); // Calculate path nodes count std::vector pathLength; pathLength.resize(pathCount); // 0 and some other indexes not used - for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) - if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) - { - if (pathLength[entry->PathID] < entry->NodeIndex + 1) - pathLength[entry->PathID] = entry->NodeIndex + 1; - } + for (TaxiPathNodeEntry const* entry : sTaxiPathNodeStore) + { + if (pathLength[entry->PathID] < entry->NodeIndex + 1) + pathLength[entry->PathID] = entry->NodeIndex + 1; + } + // Set path length sTaxiPathNodesByPath.resize(pathCount); // 0 and some other indexes not used for (uint32 i = 1; i < sTaxiPathNodesByPath.size(); ++i) sTaxiPathNodesByPath[i].resize(pathLength[i]); // fill data - for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) - if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) - sTaxiPathNodesByPath[entry->PathID][entry->NodeIndex] = entry; + for (TaxiPathNodeEntry const* entry : sTaxiPathNodeStore) + sTaxiPathNodesByPath[entry->PathID][entry->NodeIndex] = entry; // Initialize global taxinodes mask // include existed nodes that have at least single not spell base (scripted) path { std::set spellPaths; - for (uint32 i = 1; i < sSpellStore.GetNumRows(); ++i) - if (SpellEntry const* sInfo = sSpellStore.LookupEntry (i)) - for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) - if (sInfo->Effect[j] == SPELL_EFFECT_SEND_TAXI) - spellPaths.insert(sInfo->EffectMiscValue[j]); - - memset(sTaxiNodesMask, 0, sizeof(sTaxiNodesMask)); - memset(sOldContinentsNodesMask, 0, sizeof(sOldContinentsNodesMask)); - memset(sHordeTaxiNodesMask, 0, sizeof(sHordeTaxiNodesMask)); - memset(sAllianceTaxiNodesMask, 0, sizeof(sAllianceTaxiNodesMask)); - memset(sDeathKnightTaxiNodesMask, 0, sizeof(sDeathKnightTaxiNodesMask)); - for (uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i) + for (SpellEntry const* sInfo : sSpellStore) + for (uint8 j = 0; j < MAX_SPELL_EFFECTS; ++j) + if (sInfo->Effect[j] == SPELL_EFFECT_SEND_TAXI) + spellPaths.insert(sInfo->EffectMiscValue[j]); + + sTaxiNodesMask.fill(0); + sOldContinentsNodesMask.fill(0); + sHordeTaxiNodesMask.fill(0); + sAllianceTaxiNodesMask.fill(0); + sDeathKnightTaxiNodesMask.fill(0); + for (TaxiNodesEntry const* node : sTaxiNodesStore) { - TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i); - if (!node) - continue; - - TaxiPathSetBySource::const_iterator src_i = sTaxiPathSetBySource.find(i); + TaxiPathSetBySource::const_iterator src_i = sTaxiPathSetBySource.find(node->ID); if (src_i != sTaxiPathSetBySource.end() && !src_i->second.empty()) { bool ok = false; @@ -642,8 +587,8 @@ void LoadDBCStores(const std::string& dataPath) } // valid taxi network node - uint8 field = (uint8)((i - 1) / 32); - uint32 submask = 1<<((i-1)%32); + uint8 field = (uint8)((node->ID - 1) / 32); + uint32 submask = 1 << ((node->ID - 1) % 32); sTaxiNodesMask[field] |= submask; if (node->MountCreatureID[0] && node->MountCreatureID[0] != 32981) @@ -654,47 +599,17 @@ void LoadDBCStores(const std::string& dataPath) 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) + if (node->map_id < 2 || node->ID == 82 || node->ID == 83 || node->ID == 93 || node->ID == 94) sOldContinentsNodesMask[field] |= submask; // fix DK node at Ebon Hold and Shadow Vault flight master - if (i == 315 || i == 333) - ((TaxiNodesEntry*)node)->MountCreatureID[1] = 32981; + if (node->ID == 315 || node->ID == 333) + const_cast(node)->MountCreatureID[1] = 32981; } } - LoadDBC(availableDbcLocales, bad_dbc_files, sTeamContributionPointsStore, dbcPath, "TeamContributionPoints.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sTotemCategoryStore, dbcPath, "TotemCategory.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sTransportAnimationStore, dbcPath, "TransportAnimation.dbc"); - for (uint32 i = 0; i < sTransportAnimationStore.GetNumRows(); ++i) - { - TransportAnimationEntry const* anim = sTransportAnimationStore.LookupEntry(i); - if (!anim) - continue; - - sTransportMgr->AddPathNodeToTransport(anim->TransportEntry, anim->TimeSeg, anim); - } - - LoadDBC(availableDbcLocales, bad_dbc_files, sTransportRotationStore, dbcPath, "TransportRotation.dbc"); - for (uint32 i = 0; i < sTransportRotationStore.GetNumRows(); ++i) - { - TransportRotationEntry const* rot = sTransportRotationStore.LookupEntry(i); - if (!rot) - continue; - - sTransportMgr->AddPathRotationToTransport(rot->TransportEntry, rot->TimeSeg, rot); - } - - LoadDBC(availableDbcLocales, bad_dbc_files, sVehicleStore, dbcPath, "Vehicle.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sVehicleSeatStore, dbcPath, "VehicleSeat.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sWMOAreaTableStore, dbcPath, "WMOAreaTable.dbc"); - for (uint32 i = 0; i < sWMOAreaTableStore.GetNumRows(); ++i) - if (WMOAreaTableEntry const* entry = sWMOAreaTableStore.LookupEntry(i)) - sWMOAreaInfoByTripple.insert(WMOAreaInfoByTripple::value_type(WMOAreaTableTripple(entry->rootId, entry->adtId, entry->groupId), entry)); - LoadDBC(availableDbcLocales, bad_dbc_files, sWorldMapAreaStore, dbcPath, "WorldMapArea.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sWorldMapOverlayStore, dbcPath, "WorldMapOverlay.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sWorldSafeLocsStore, dbcPath, "WorldSafeLocs.dbc"); + for (WMOAreaTableEntry const* entry : sWMOAreaTableStore) + sWMOAreaInfoByTripple[WMOAreaTableKey(entry->rootId, entry->adtId, entry->groupId)] = entry; // error checks if (bad_dbc_files.size() >= DBCFileCount) @@ -715,11 +630,11 @@ void LoadDBCStores(const std::string& dataPath) // Check loaded DBC files proper version if (!sAreaTableStore.LookupEntry(4987) || // last area added in 3.3.5a !sCharTitlesStore.LookupEntry(177) || // last char title added in 3.3.5a - !sGemPropertiesStore.LookupEntry(1629) || // last added spell in 3.3.5a - !sItemStore.LookupEntry(56806) || // last gem property added in 3.3.5a + !sGemPropertiesStore.LookupEntry(1629) || // last gem property added in 3.3.5a + !sItemStore.LookupEntry(56806) || // last client known item added in 3.3.5a !sItemExtendedCostStore.LookupEntry(2997) || // last item extended cost added in 3.3.5a !sMapStore.LookupEntry(724) || // last map added in 3.3.5a - !sSpellStore.LookupEntry(80864) ) // last client known item added in 3.3.5a + !sSpellStore.LookupEntry(80864) ) // last added spell in 3.3.5a { TC_LOG_ERROR("misc", "You have _outdated_ DBC files. Please extract correct versions from current using client."); exit(1); @@ -735,24 +650,24 @@ SimpleFactionsList const* GetFactionTeamList(uint32 faction) if (itr != sFactionTeamMap.end()) return &itr->second; - return NULL; + return nullptr; } char* GetPetName(uint32 petfamily, uint32 dbclang) { if (!petfamily) - return NULL; + return nullptr; CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(petfamily); if (!pet_family) - return NULL; - return pet_family->Name[dbclang]?pet_family->Name[dbclang]:NULL; + return nullptr; + return pet_family->Name[dbclang]?pet_family->Name[dbclang]:nullptr; } TalentSpellPos const* GetTalentSpellPos(uint32 spellId) { TalentSpellPosMap::const_iterator itr = sTalentSpellPosMap.find(spellId); if (itr == sTalentSpellPosMap.end()) - return NULL; + return nullptr; return &itr->second; } @@ -765,25 +680,25 @@ uint32 GetTalentSpellCost(uint32 spellId) return 0; } - WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple(int32 rootid, int32 adtid, int32 groupid) { - WMOAreaInfoByTripple::iterator i = sWMOAreaInfoByTripple.find(WMOAreaTableTripple(rootid, adtid, groupid)); - if (i == sWMOAreaInfoByTripple.end()) - return NULL; - return i->second; + auto i = sWMOAreaInfoByTripple.find(WMOAreaTableKey(int16(rootid), int8(adtid), groupid)); + if (i != sWMOAreaInfoByTripple.end()) + return i->second; + + return nullptr; } char const* GetRaceName(uint8 race, uint8 locale) { ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race); - return raceEntry ? raceEntry->name[locale] : NULL; + return raceEntry ? raceEntry->name[locale] : nullptr; } char const* GetClassName(uint8 class_, uint8 locale) { ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_); - return classEntry ? classEntry->name[locale] : NULL; + return classEntry ? classEntry->name[locale] : nullptr; } uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId) @@ -864,7 +779,7 @@ void Map2ZoneCoordinates(float& x, float& y, uint32 zone) MapDifficulty const* GetMapDifficultyData(uint32 mapId, Difficulty difficulty) { MapDifficultyMap::const_iterator itr = sMapDifficultyMap.find(MAKE_PAIR32(mapId, difficulty)); - return itr != sMapDifficultyMap.end() ? &itr->second : NULL; + return itr != sMapDifficultyMap.end() ? &itr->second : nullptr; } MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &difficulty) @@ -893,7 +808,7 @@ MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &di PvPDifficultyEntry const* GetBattlegroundBracketByLevel(uint32 mapid, uint32 level) { - PvPDifficultyEntry const* maxEntry = NULL; // used for level > max listed level case + PvPDifficultyEntry const* maxEntry = nullptr; // used for level > max listed level case for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) { if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) @@ -922,7 +837,7 @@ PvPDifficultyEntry const* GetBattlegroundBracketById(uint32 mapid, BattlegroundB if (entry->mapId == mapid && entry->GetBracketId() == id) return entry; - return NULL; + return nullptr; } uint32 const* GetTalentTabPages(uint8 cls) @@ -942,7 +857,7 @@ CharStartOutfitEntry const* GetCharStartOutfitEntry(uint8 race, uint8 class_, ui { std::map::const_iterator itr = sCharStartOutfitMap.find(race | (class_ << 8) | (gender << 16)); if (itr == sCharStartOutfitMap.end()) - return NULL; + return nullptr; return itr->second; } @@ -956,7 +871,7 @@ CharSectionsEntry const* GetCharSectionEntry(uint8 race, CharSectionType genType return itr->second; } - return NULL; + return nullptr; } /// Returns LFGDungeonEntry for a specific map and difficulty. Will return first found entry if multiple dungeons use the same map (such as Scarlet Monastery) @@ -972,7 +887,7 @@ LFGDungeonEntry const* GetLFGDungeon(uint32 mapId, Difficulty difficulty) return dungeon; } - return NULL; + return nullptr; } uint32 GetDefaultMapLight(uint32 mapId) @@ -1003,7 +918,7 @@ SkillRaceClassInfoEntry const* GetSkillRaceClassInfo(uint32 skill, uint8 race, u return itr->second; } - return NULL; + return nullptr; } ResponseCodes ValidateName(std::wstring const& name, LocaleConstant locale) diff --git a/src/server/game/DataStores/DBCStores.h b/src/server/game/DataStores/DBCStores.h index 360b0d22b76..846b2b40c1a 100644 --- a/src/server/game/DataStores/DBCStores.h +++ b/src/server/game/DataStores/DBCStores.h @@ -19,12 +19,19 @@ #ifndef TRINITY_DBCSTORES_H #define TRINITY_DBCSTORES_H -#include "Common.h" #include "DBCStore.h" #include "DBCStructure.h" #include "SharedDefines.h" - #include +#include +#include + +enum LocaleConstant : uint8; + + // temporary hack until includes are sorted out (don't want to pull in Windows.h) +#ifdef GetClassName +#undef GetClassName +#endif typedef std::list SimpleFactionsList; TC_GAME_API SimpleFactionsList const* GetFactionTeamList(uint32 faction); @@ -40,7 +47,7 @@ TC_GAME_API WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple(int32 rootid, TC_GAME_API uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId); -enum ContentLevels +enum ContentLevels : uint8 { CONTENT_1_60 = 0, CONTENT_61_70, @@ -186,6 +193,8 @@ TC_GAME_API extern TaxiMask sAllianceTaxiNodesM TC_GAME_API extern TaxiMask sDeathKnightTaxiNodesMask; TC_GAME_API extern TaxiPathSetBySource sTaxiPathSetBySource; TC_GAME_API extern TaxiPathNodesByPath sTaxiPathNodesByPath; +TC_GAME_API extern DBCStorage sTransportAnimationStore; +TC_GAME_API extern DBCStorage sTransportRotationStore; TC_GAME_API extern DBCStorage sTeamContributionPointsStore; TC_GAME_API extern DBCStorage sTotemCategoryStore; TC_GAME_API extern DBCStorage sVehicleStore; diff --git a/src/server/game/DataStores/DBCStructure.h b/src/server/game/DataStores/DBCStructure.h index 7dc8f91826c..409f1ec25f7 100644 --- a/src/server/game/DataStores/DBCStructure.h +++ b/src/server/game/DataStores/DBCStructure.h @@ -19,9 +19,12 @@ #ifndef TRINITY_DBCSTRUCTURE_H #define TRINITY_DBCSTRUCTURE_H -#include "Common.h" +#include "Define.h" #include "DBCEnums.h" +#include "SharedDefines.h" #include "Util.h" +#include +#include // Structures using to access raw DBC data and required packing to portability #pragma pack(push, 1) @@ -501,8 +504,6 @@ struct CreatureModelDataEntry //float Unks[11] }; -#define MAX_CREATURE_SPELL_DATA_SLOT 4 - struct CreatureSpellDataEntry { uint32 ID; // 0 m_ID @@ -1316,10 +1317,6 @@ struct SoundEntriesEntry // 29 new in 3.1 }; -#define MAX_SPELL_EFFECTS 3 -#define MAX_EFFECT_MASK 7 -#define MAX_SPELL_REAGENTS 8 - struct SpellEntry { uint32 Id; // 0 m_ID @@ -1432,7 +1429,7 @@ struct SpellEntry }; typedef std::set PetFamilySpellsSet; -typedef std::map PetFamilySpellsStore; +typedef std::map PetFamilySpellsStore; struct SpellCastTimesEntry { @@ -1564,10 +1561,6 @@ struct SummonPropertiesEntry uint32 Flags; // 5 }; -#define MAX_TALENT_RANK 5 -#define MAX_PET_TALENT_RANK 3 // use in calculations, expected <= MAX_TALENT_RANK -#define MAX_TALENT_TABS 3 - struct TalentEntry { uint32 TalentID; // 0 @@ -1901,7 +1894,5 @@ typedef std::map TaxiPathSetBySource; typedef std::vector TaxiPathNodeList; typedef std::vector TaxiPathNodesByPath; -#define TaxiMaskSize 14 -typedef uint32 TaxiMask[TaxiMaskSize]; #endif diff --git a/src/server/game/DataStores/M2Stores.cpp b/src/server/game/DataStores/M2Stores.cpp index 8594ddb5281..1b9ace510d7 100644 --- a/src/server/game/DataStores/M2Stores.cpp +++ b/src/server/game/DataStores/M2Stores.cpp @@ -16,17 +16,18 @@ */ #include "DBCStores.h" -#include "M2Structure.h" -#include "M2Stores.h" #include "Common.h" #include "Containers.h" #include "Log.h" +#include "M2Structure.h" +#include "M2Stores.h" #include "World.h" +#include #include #include #include -#include +typedef std::vector FlyByCameraCollection; std::unordered_map sFlyByCameraStore; // Convert the geomoetry from a spline value, to an actual WoW XYZ @@ -90,10 +91,7 @@ bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, Ci // Add to vector FlyByCamera thisCam; thisCam.timeStamp = targTimestamps[i]; - thisCam.locations.x = newPos.x; - thisCam.locations.y = newPos.y; - thisCam.locations.z = newPos.z; - thisCam.locations.w = 0.0f; + thisCam.locations.Relocate(newPos.x, newPos.y, newPos.z, 0.0f); targetcam.push_back(thisCam); targPositions++; currPos += sizeof(M2SplineKey); @@ -127,9 +125,7 @@ bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, Ci // Add to vector FlyByCamera thisCam; thisCam.timeStamp = posTimestamps[i]; - thisCam.locations.x = newPos.x; - thisCam.locations.y = newPos.y; - thisCam.locations.z = newPos.z; + thisCam.locations.Relocate(newPos.x, newPos.y, newPos.z); if (targetcam.size() > 0) { @@ -149,28 +145,24 @@ bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, Ci lastTarget = targetcam[j]; } - float x = lastTarget.locations.x; - float y = lastTarget.locations.y; - float z = lastTarget.locations.z; + float x, y, z; + lastTarget.locations.GetPosition(x, y, z); // Now, the timestamps for target cam and position can be different. So, if they differ we interpolate if (lastTarget.timeStamp != posTimestamps[i]) { uint32 timeDiffTarget = nextTarget.timeStamp - lastTarget.timeStamp; uint32 timeDiffThis = posTimestamps[i] - lastTarget.timeStamp; - float xDiff = nextTarget.locations.x - lastTarget.locations.x; - float yDiff = nextTarget.locations.y - lastTarget.locations.y; - float zDiff = nextTarget.locations.z - lastTarget.locations.z; - x = lastTarget.locations.x + (xDiff * (float(timeDiffThis) / float(timeDiffTarget))); - y = lastTarget.locations.y + (yDiff * (float(timeDiffThis) / float(timeDiffTarget))); - z = lastTarget.locations.z + (zDiff * (float(timeDiffThis) / float(timeDiffTarget))); + float xDiff = nextTarget.locations.GetPositionX() - lastTarget.locations.GetPositionX(); + float yDiff = nextTarget.locations.GetPositionY() - lastTarget.locations.GetPositionY(); + float zDiff = nextTarget.locations.GetPositionZ() - lastTarget.locations.GetPositionZ(); + x = lastTarget.locations.GetPositionX() + (xDiff * (float(timeDiffThis) / float(timeDiffTarget))); + y = lastTarget.locations.GetPositionY() + (yDiff * (float(timeDiffThis) / float(timeDiffTarget))); + z = lastTarget.locations.GetPositionZ() + (zDiff * (float(timeDiffThis) / float(timeDiffTarget))); } - float xDiff = x - thisCam.locations.x; - float yDiff = y - thisCam.locations.y; - thisCam.locations.w = std::atan2(yDiff, xDiff); - - if (thisCam.locations.w < 0) - thisCam.locations.w += 2 * float(M_PI); + float xDiff = x - thisCam.locations.GetPositionX(); + float yDiff = y - thisCam.locations.GetPositionY(); + thisCam.locations.SetOrientation(std::atan2(yDiff, xDiff)); } cameras.push_back(thisCam); @@ -189,78 +181,81 @@ void LoadM2Cameras(std::string const& dataPath) TC_LOG_INFO("server.loading", ">> Loading Cinematic Camera files"); uint32 oldMSTime = getMSTime(); - for (uint32 i = 0; i < sCinematicCameraStore.GetNumRows(); ++i) + for (CinematicCameraEntry const* dbcentry : sCinematicCameraStore) { - if (CinematicCameraEntry const* dbcentry = sCinematicCameraStore.LookupEntry(i)) - { - std::string filenameWork = dataPath; - filenameWork.append(dbcentry->Model); + std::string filenameWork = dataPath; + filenameWork.append(dbcentry->Model); - // Replace slashes (always to forward slash, because boost!) - std::replace(filenameWork.begin(), filenameWork.end(), '\\', '/'); + // Replace slashes (always to forward slash, because boost!) + std::replace(filenameWork.begin(), filenameWork.end(), '\\', '/'); - boost::filesystem::path filename = filenameWork; + boost::filesystem::path filename = filenameWork; - // Convert to native format - filename.make_preferred(); + // Convert to native format + filename.make_preferred(); - // Replace mdx to .m2 - filename.replace_extension("m2"); + // Replace mdx to .m2 + filename.replace_extension("m2"); - std::ifstream m2file(filename.string().c_str(), std::ios::in | std::ios::binary); - if (!m2file.is_open()) - continue; + std::ifstream m2file(filename.string().c_str(), std::ios::in | std::ios::binary); + if (!m2file.is_open()) + continue; - // Get file size - m2file.seekg(0, std::ios::end); - std::streamoff const fileSize = m2file.tellg(); + // Get file size + m2file.seekg(0, std::ios::end); + std::streamoff const fileSize = m2file.tellg(); - // Reject if not at least the size of the header - if (static_cast(fileSize) < sizeof(M2Header)) - { - TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File is smaller than header size", filename.string().c_str()); - m2file.close(); - continue; - } - - // Read 4 bytes (signature) - m2file.seekg(0, std::ios::beg); - char fileCheck[5]; - m2file.read(fileCheck, 4); - fileCheck[4] = 0; + // Reject if not at least the size of the header + if (static_cast(fileSize) < sizeof(M2Header)) + { + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File is smaller than header size", filename.string().c_str()); + m2file.close(); + continue; + } - // Check file has correct magic (MD20) - if (strcmp(fileCheck, "MD20")) - { - TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File identifier not found", filename.string().c_str()); - m2file.close(); - continue; - } + // Read 4 bytes (signature) + m2file.seekg(0, std::ios::beg); + char fileCheck[5]; + m2file.read(fileCheck, 4); + fileCheck[4] = 0; - // Now we have a good file, read it all into a vector of char's, then close the file. - std::vector buffer(fileSize); - m2file.seekg(0, std::ios::beg); - if (!m2file.read(buffer.data(), fileSize)) - { - m2file.close(); - continue; - } + // Check file has correct magic (MD20) + if (strcmp(fileCheck, "MD20")) + { + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File identifier not found", filename.string().c_str()); m2file.close(); + continue; + } - // Read header - M2Header const* header = reinterpret_cast(buffer.data()); + // Now we have a good file, read it all into a vector of char's, then close the file. + std::vector buffer(fileSize); + m2file.seekg(0, std::ios::beg); + if (!m2file.read(buffer.data(), fileSize)) + { + m2file.close(); + continue; + } + m2file.close(); - if (header->ofsCameras + sizeof(M2Camera) > static_cast(fileSize)) - { - TC_LOG_ERROR("server.loading", "Camera file %s is damaged. Camera references position beyond file end", filename.string().c_str()); - continue; - } + // Read header + M2Header const* header = reinterpret_cast(buffer.data()); - // Get camera(s) - Main header, then dump them. - M2Camera const* cam = reinterpret_cast(buffer.data() + header->ofsCameras); - if (!readCamera(cam, fileSize, header, dbcentry)) - TC_LOG_ERROR("server.loading", "Camera file %s is damaged. Camera references position beyond file end", filename.string().c_str()); + if (header->ofsCameras + sizeof(M2Camera) > static_cast(fileSize)) + { + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. Camera references position beyond file end", filename.string().c_str()); + continue; } + + // Get camera(s) - Main header, then dump them. + M2Camera const* cam = reinterpret_cast(buffer.data() + header->ofsCameras); + if (!readCamera(cam, fileSize, header, dbcentry)) + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. Camera references position beyond file end", filename.string().c_str()); } + TC_LOG_INFO("server.loading", ">> Loaded %u cinematic waypoint sets in %u ms", (uint32)sFlyByCameraStore.size(), GetMSTimeDiffToNow(oldMSTime)); } + +std::vector const* GetFlyByCameras(uint32 cinematicCameraId) +{ + return Trinity::Containers::MapGetValuePtr(sFlyByCameraStore, cinematicCameraId); +} diff --git a/src/server/game/DataStores/M2Stores.h b/src/server/game/DataStores/M2Stores.h index c76497323a5..b37bff395d5 100644 --- a/src/server/game/DataStores/M2Stores.h +++ b/src/server/game/DataStores/M2Stores.h @@ -18,19 +18,18 @@ #ifndef TRINITY_M2STORES_H #define TRINITY_M2STORES_H -#include "SharedDefines.h" -#include "Common.h" +#include "Define.h" +#include "Position.h" +#include struct FlyByCamera { uint32 timeStamp; - G3D::Vector4 locations; + Position locations; }; -typedef std::vector FlyByCameraCollection; - -TC_GAME_API extern std::unordered_map sFlyByCameraStore; - TC_GAME_API void LoadM2Cameras(std::string const& dataPath); +TC_GAME_API std::vector const* GetFlyByCameras(uint32 cinematicCameraId); + #endif \ No newline at end of file diff --git a/src/server/game/DungeonFinding/LFG.cpp b/src/server/game/DungeonFinding/LFG.cpp index 497db7fd749..b39a304d548 100644 --- a/src/server/game/DungeonFinding/LFG.cpp +++ b/src/server/game/DungeonFinding/LFG.cpp @@ -18,6 +18,7 @@ #include "LFG.h" #include "Language.h" #include "ObjectMgr.h" +#include namespace lfg { diff --git a/src/server/game/DungeonFinding/LFG.h b/src/server/game/DungeonFinding/LFG.h index 3a16c243f46..4d65ebab887 100644 --- a/src/server/game/DungeonFinding/LFG.h +++ b/src/server/game/DungeonFinding/LFG.h @@ -18,8 +18,11 @@ #ifndef _LFG_H #define _LFG_H -#include "Common.h" +#include "Define.h" #include "ObjectGuid.h" +#include +#include +#include namespace lfg { diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index bf13095942e..39d30a28c4f 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -15,28 +15,46 @@ * with this program. If not, see . */ +#include "LFGMgr.h" #include "Common.h" -#include "SharedDefines.h" +#include "DatabaseEnv.h" #include "DBCStores.h" #include "DisableMgr.h" -#include "ObjectMgr.h" -#include "SocialMgr.h" -#include "LFGMgr.h" -#include "LFGScripts.h" +#include "GameEventMgr.h" +#include "Group.h" +#include "GroupMgr.h" +#include "InstanceSaveMgr.h" #include "LFGGroupData.h" #include "LFGPlayerData.h" +#include "LFGScripts.h" #include "LFGQueue.h" -#include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" #include "RBAC.h" -#include "GroupMgr.h" -#include "GameEventMgr.h" +#include "SharedDefines.h" +#include "SocialMgr.h" +#include "World.h" #include "WorldSession.h" -#include "InstanceSaveMgr.h" namespace lfg { +LFGDungeonData::LFGDungeonData() : id(0), name(), map(0), type(0), expansion(0), group(0), minlevel(0), + maxlevel(0), difficulty(REGULAR_DIFFICULTY), seasonal(false), x(0.0f), y(0.0f), z(0.0f), o(0.0f) +{ +} + +LFGDungeonData::LFGDungeonData(LFGDungeonEntry const* dbc) : id(dbc->ID), name(dbc->name[0]), map(dbc->map), + type(dbc->type), expansion(uint8(dbc->expansion)), group(uint8(dbc->grouptype)), + minlevel(uint8(dbc->minlevel)), maxlevel(uint8(dbc->maxlevel)), difficulty(Difficulty(dbc->difficulty)), + seasonal((dbc->flags & LFG_FLAG_SEASONAL) != 0), x(0.0f), y(0.0f), z(0.0f), o(0.0f) +{ +} + LFGMgr::LFGMgr(): m_QueueTimer(0), m_lfgProposalId(1), m_options(sWorld->getIntConfig(CONFIG_LFG_OPTIONSMASK)) { @@ -117,7 +135,7 @@ void LFGMgr::LoadRewards() uint32 count = 0; - Field* fields = NULL; + Field* fields = nullptr; do { fields = result->Fetch(); @@ -164,7 +182,7 @@ LFGDungeonData const* LFGMgr::GetLFGDungeon(uint32 id) if (itr != LfgDungeonStore.end()) return &(itr->second); - return NULL; + return nullptr; } void LFGMgr::LoadLFGDungeons(bool reload /* = false */) @@ -270,7 +288,7 @@ void LFGMgr::Update(uint32 diff) if (!isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) return; - time_t currTime = time(NULL); + time_t currTime = time(nullptr); // Remove obsolete role checks for (LfgRoleCheckContainer::iterator it = RoleChecksStore.begin(); it != RoleChecksStore.end();) @@ -424,7 +442,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const else { uint8 memberCount = 0; - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && joinData.result == LFG_JOIN_OK; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr && joinData.result == LFG_JOIN_OK; itr = itr->next()) { if (Player* plrg = itr->GetSource()) { @@ -522,7 +540,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const { // Create new rolecheck LfgRoleCheck& roleCheck = RoleChecksStore[gguid]; - roleCheck.cancelTime = time_t(time(NULL)) + LFG_TIME_ROLECHECK; + roleCheck.cancelTime = time_t(time(nullptr)) + LFG_TIME_ROLECHECK; roleCheck.state = LFG_ROLECHECK_INITIALITING; roleCheck.leader = guid; roleCheck.dungeons = dungeons; @@ -537,7 +555,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const SetState(gguid, LFG_STATE_ROLECHECK); // Send update to player LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment); - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { if (Player* plrg = itr->GetSource()) { @@ -560,7 +578,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const LfgRolesMap rolesMap; rolesMap[guid] = roles; LFGQueue& queue = GetQueue(guid); - queue.AddQueueData(guid, time(NULL), dungeons, rolesMap); + queue.AddQueueData(guid, time(nullptr), dungeons, rolesMap); if (!isContinue) { @@ -734,7 +752,7 @@ void LFGMgr::UpdateRoleCheck(ObjectGuid gguid, ObjectGuid guid /* = ObjectGuid:: { SetState(gguid, LFG_STATE_QUEUED); LFGQueue& queue = GetQueue(gguid); - queue.AddQueueData(gguid, time_t(time(NULL)), roleCheck.dungeons, roleCheck.roles); + queue.AddQueueData(gguid, time_t(time(nullptr)), roleCheck.dungeons, roleCheck.roles); RoleChecksStore.erase(itRoleCheck); } else if (roleCheck.state != LFG_ROLECHECK_INITIALITING) @@ -895,7 +913,7 @@ void LFGMgr::MakeNewGroup(LfgProposal const& proposal) LFGDungeonData const* dungeon = GetLFGDungeon(proposal.dungeonId); ASSERT(dungeon); - Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(proposal.group.GetCounter()) : NULL; + Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(proposal.group.GetCounter()) : nullptr; for (GuidList::const_iterator it = players.begin(); it != players.end(); ++it) { ObjectGuid pguid = (*it); @@ -997,7 +1015,7 @@ void LFGMgr::UpdateProposal(uint32 proposalId, ObjectGuid guid, bool accept) bool sendUpdate = proposal.state != LFG_PROPOSAL_SUCCESS; proposal.state = LFG_PROPOSAL_SUCCESS; - time_t joinTime = time(NULL); + time_t joinTime = time(nullptr); LFGQueue& queue = GetQueue(guid); LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_GROUP_FOUND); @@ -1166,7 +1184,7 @@ void LFGMgr::InitBoot(ObjectGuid gguid, ObjectGuid kicker, ObjectGuid victim, st LfgPlayerBoot& boot = BootsStore[gguid]; boot.inProgress = true; - boot.cancelTime = time_t(time(NULL)) + LFG_TIME_BOOT; + boot.cancelTime = time_t(time(nullptr)) + LFG_TIME_BOOT; boot.reason = reason; boot.victim = victim; @@ -1254,7 +1272,7 @@ void LFGMgr::UpdateBoot(ObjectGuid guid, bool accept) */ void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false*/) { - LFGDungeonData const* dungeon = NULL; + LFGDungeonData const* dungeon = nullptr; Group* group = player->GetGroup(); if (group && group->isLFGGroup()) @@ -1303,7 +1321,7 @@ void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false* if (!fromOpcode) { // Select a player inside to be teleported to - for (GroupReference* itr = group->GetFirstMember(); itr != NULL && !mapid; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr && !mapid; itr = itr->next()) { Player* plrg = itr->GetSource(); if (plrg && plrg != player && plrg->GetMapId() == uint32(dungeon->map)) @@ -1375,7 +1393,7 @@ void LFGMgr::FinishDungeon(ObjectGuid gguid, const uint32 dungeonId, Map const* } uint32 rDungeonId = 0; - const LfgDungeonSet& dungeons = GetSelectedDungeons(guid); + LfgDungeonSet const& dungeons = GetSelectedDungeons(guid); if (!dungeons.empty()) rDungeonId = (*dungeons.begin()); @@ -1421,7 +1439,7 @@ void LFGMgr::FinishDungeon(ObjectGuid gguid, const uint32 dungeonId, Map const* // if we can take the quest, means that we haven't done this kind of "run", IE: First Heroic Random of Day. if (player->CanRewardQuest(quest, false)) - player->RewardQuest(quest, 0, NULL, false); + player->RewardQuest(quest, 0, nullptr, false); else { done = true; @@ -1429,7 +1447,7 @@ void LFGMgr::FinishDungeon(ObjectGuid gguid, const uint32 dungeonId, Map const* if (!quest) continue; // we give reward without informing client (retail does this) - player->RewardQuest(quest, 0, NULL, false); + player->RewardQuest(quest, 0, nullptr, false); } // Give rewards @@ -1465,7 +1483,7 @@ LfgDungeonSet const& LFGMgr::GetDungeonsByRandom(uint32 randomdungeon) */ LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level) { - LfgReward const* rew = NULL; + LfgReward const* rew = nullptr; LfgRewardContainerBounds bounds = RewardMapStore.equal_range(dungeon & 0x00FFFFFF); for (LfgRewardContainer::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { diff --git a/src/server/game/DungeonFinding/LFGMgr.h b/src/server/game/DungeonFinding/LFGMgr.h index 96f5b2373ff..a3aa15e3a85 100644 --- a/src/server/game/DungeonFinding/LFGMgr.h +++ b/src/server/game/DungeonFinding/LFGMgr.h @@ -18,17 +18,20 @@ #ifndef _LFGMGR_H #define _LFGMGR_H -#include "DBCStructure.h" -#include "Field.h" +#include "Common.h" +#include "DatabaseEnvFwd.h" #include "LFG.h" #include "LFGQueue.h" #include "LFGGroupData.h" #include "LFGPlayerData.h" +#include class Group; class Player; class Quest; class Map; +struct LFGDungeonEntry; +enum Difficulty : uint8; namespace lfg { @@ -265,14 +268,8 @@ struct LfgPlayerBoot struct LFGDungeonData { - LFGDungeonData(): id(0), name(""), map(0), type(0), expansion(0), group(0), minlevel(0), - maxlevel(0), difficulty(REGULAR_DIFFICULTY), seasonal(false), x(0.0f), y(0.0f), z(0.0f), o(0.0f) - { } - LFGDungeonData(LFGDungeonEntry const* dbc): id(dbc->ID), name(dbc->name[0]), map(dbc->map), - type(dbc->type), expansion(dbc->expansion), group(dbc->grouptype), - minlevel(dbc->minlevel), maxlevel(dbc->maxlevel), difficulty(Difficulty(dbc->difficulty)), - seasonal((dbc->flags & LFG_FLAG_SEASONAL) != 0), x(0.0f), y(0.0f), z(0.0f), o(0.0f) - { } + LFGDungeonData(); + LFGDungeonData(LFGDungeonEntry const* dbc); uint32 id; std::string name; diff --git a/src/server/game/DungeonFinding/LFGPlayerData.h b/src/server/game/DungeonFinding/LFGPlayerData.h index 356a0bb3152..dc18c796997 100644 --- a/src/server/game/DungeonFinding/LFGPlayerData.h +++ b/src/server/game/DungeonFinding/LFGPlayerData.h @@ -41,7 +41,7 @@ class TC_GAME_API LfgPlayerData // Queue void SetRoles(uint8 roles); void SetComment(std::string const& comment); - void SetSelectedDungeons(const LfgDungeonSet& dungeons); + void SetSelectedDungeons(LfgDungeonSet const& dungeons); // General LfgState GetState() const; diff --git a/src/server/game/DungeonFinding/LFGQueue.cpp b/src/server/game/DungeonFinding/LFGQueue.cpp index 4cbff1e3307..2843275dfd1 100644 --- a/src/server/game/DungeonFinding/LFGQueue.cpp +++ b/src/server/game/DungeonFinding/LFGQueue.cpp @@ -283,7 +283,7 @@ LfgCompatibilityData* LFGQueue::GetCompatibilityData(std::string const& key) if (itr != CompatibleMapStore.end()) return &(itr->second); - return NULL; + return nullptr; } uint8 LFGQueue::FindGroups() @@ -508,7 +508,7 @@ LfgCompatibility LFGQueue::CheckCompatibility(GuidList check) else { ObjectGuid gguid = *check.begin(); - const LfgQueueData &queue = QueueDataStore[gguid]; + LfgQueueData const& queue = QueueDataStore[gguid]; proposalDungeons = queue.dungeons; proposalRoles = queue.roles; LFGMgr::CheckGroupRoles(proposalRoles); // assing new roles @@ -540,7 +540,7 @@ LfgCompatibility LFGQueue::CheckCompatibility(GuidList check) } // Create a new proposal - proposal.cancelTime = time(NULL) + LFG_TIME_PROPOSAL; + proposal.cancelTime = time(nullptr) + LFG_TIME_PROPOSAL; proposal.state = LFG_PROPOSAL_INITIATING; proposal.leader.Clear(); proposal.dungeonId = Trinity::Containers::SelectRandomContainerElement(proposalDungeons); @@ -674,7 +674,7 @@ std::string LFGQueue::DumpCompatibleInfo(bool full /* = false */) const { o << " ("; bool first = true; - for (const auto& role : itr->second.roles) + for (auto const& role : itr->second.roles) { if (!first) o << "|"; diff --git a/src/server/game/DungeonFinding/LFGQueue.h b/src/server/game/DungeonFinding/LFGQueue.h index 4d5d8849751..474b7a0bbdc 100644 --- a/src/server/game/DungeonFinding/LFGQueue.h +++ b/src/server/game/DungeonFinding/LFGQueue.h @@ -51,7 +51,7 @@ struct LfgCompatibilityData /// Stores player or group queue info struct LfgQueueData { - LfgQueueData(): joinTime(time_t(time(NULL))), tanks(LFG_TANKS_NEEDED), + LfgQueueData(): joinTime(time_t(time(nullptr))), tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) { } diff --git a/src/server/game/DungeonFinding/LFGScripts.cpp b/src/server/game/DungeonFinding/LFGScripts.cpp index 2e442a9720e..a816599e36f 100644 --- a/src/server/game/DungeonFinding/LFGScripts.cpp +++ b/src/server/game/DungeonFinding/LFGScripts.cpp @@ -19,14 +19,16 @@ * Interaction between core and LFGScripts */ +#include "LFGScripts.h" #include "Common.h" -#include "SharedDefines.h" -#include "Player.h" #include "Group.h" -#include "LFGScripts.h" #include "LFGMgr.h" -#include "ScriptMgr.h" +#include "Log.h" +#include "Map.h" +#include "Player.h" #include "ObjectAccessor.h" +#include "ScriptMgr.h" +#include "SharedDefines.h" #include "WorldSession.h" namespace lfg @@ -93,7 +95,7 @@ void LFGPlayerScript::OnMapChanged(Player* player) return; } - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) player->GetSession()->SendNameQueryOpcode(member->GetGUID()); diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index faac452bac0..37b29df81fa 100644 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -19,7 +19,10 @@ #include "CharacterCache.h" #include "Common.h" #include "Corpse.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "UpdateData.h" #include "UpdateMask.h" #include "ObjectAccessor.h" #include "DatabaseEnv.h" @@ -34,7 +37,7 @@ Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES), m_type(type m_valuesCount = CORPSE_END; - m_time = time(NULL); + m_time = time(nullptr); lootRecipient = nullptr; } diff --git a/src/server/game/Entities/Corpse/Corpse.h b/src/server/game/Entities/Corpse/Corpse.h index 533a520a515..1d37cdebfff 100644 --- a/src/server/game/Entities/Corpse/Corpse.h +++ b/src/server/game/Entities/Corpse/Corpse.h @@ -20,9 +20,9 @@ #define TRINITYCORE_CORPSE_H #include "Object.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "GridDefines.h" -#include "LootMgr.h" +#include "Loot.h" enum CorpseType { @@ -67,7 +67,7 @@ class TC_GAME_API Corpse : public WorldObject, public GridObject ObjectGuid GetOwnerGUID() const { return GetGuidValue(CORPSE_FIELD_OWNER); } time_t const& GetGhostTime() const { return m_time; } - void ResetGhostTime() { m_time = time(NULL); } + void ResetGhostTime() { m_time = time(nullptr); } CorpseType GetType() const { return m_type; } CellCoord const& GetCellCoord() const { return _cellCoord; } diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index ed98f7d70be..ef17eaa07bd 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -28,29 +28,30 @@ #include "GameEventMgr.h" #include "GameTime.h" #include "GossipDef.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "GroupMgr.h" #include "InstanceScript.h" #include "Log.h" #include "LootMgr.h" +#include "MotionMaster.h" #include "MoveSpline.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "PoolMgr.h" +#include "QueryPackets.h" #include "QuestDef.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" #include "SpellMgr.h" #include "TemporarySummon.h" +#include "Transport.h" #include "Util.h" #include "Vehicle.h" #include "World.h" #include "WorldPacket.h" -#include "Transport.h" -#include "ScriptedGossip.h" - -#include "Packets/QueryPackets.h" +#include TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const { @@ -61,27 +62,28 @@ TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const return nullptr; } +bool VendorItem::IsGoldRequired(ItemTemplate const* pProto) const +{ + return (pProto->Flags2 & ITEM_FLAG2_DONT_IGNORE_BUY_PRICE) || !ExtendedCost; +} + bool VendorItemData::RemoveItem(uint32 item_id) { - bool found = false; - for (VendorItemList::iterator i = m_items.begin(); i != m_items.end();) + auto newEnd = std::remove_if(m_items.begin(), m_items.end(), [=](VendorItem const& vendorItem) { - if ((*i)->item == item_id) - { - i = m_items.erase(i++); - found = true; - } - else - ++i; - } + return vendorItem.item == item_id; + }); + + bool found = (newEnd != m_items.end()); + m_items.erase(newEnd, m_items.end()); return found; } VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id, uint32 extendedCost) const { - for (VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i) - if ((*i)->item == item_id && (*i)->ExtendedCost == extendedCost) - return *i; + for (VendorItem const& vendorItem : m_items) + if (vendorItem.item == item_id && vendorItem.ExtendedCost == extendedCost) + return &vendorItem; return nullptr; } @@ -192,7 +194,7 @@ WorldPacket CreatureTemplate::BuildQueryData(LocaleConstant loc) const for (uint32 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) queryTemp.Stats.QuestItems[i] = 0; - if (CreatureQuestItemList const* items = sObjectMgr->GetCreatureQuestItemList(Entry)) + if (std::vector const* items = sObjectMgr->GetCreatureQuestItemList(Entry)) for (uint32 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) if (i < items->size()) queryTemp.Stats.QuestItems[i] = (*items)[i]; @@ -333,7 +335,7 @@ void Creature::RemoveCorpse(bool setSpawnTime, bool destroyForNearbyPlayers) if (getDeathState() != CORPSE) return; - m_corpseRemoveTime = time(NULL); + m_corpseRemoveTime = time(nullptr); setDeathState(DEAD); RemoveAllAuras(); loot.clear(); @@ -346,7 +348,7 @@ void Creature::RemoveCorpse(bool setSpawnTime, bool destroyForNearbyPlayers) // Should get removed later, just keep "compatibility" with scripts if (setSpawnTime) - m_respawnTime = std::max(time(NULL) + respawnDelay, m_respawnTime); + m_respawnTime = std::max(time(nullptr) + respawnDelay, m_respawnTime); // if corpse was removed during falling, the falling will continue and override relocation to respawn position if (IsFalling()) @@ -583,7 +585,7 @@ void Creature::Update(uint32 diff) break; case DEAD: { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime <= now) { // First check if there are any scripts that object to us respawning @@ -636,7 +638,7 @@ void Creature::Update(uint32 diff) } else m_groupLootTimer -= diff; } - else if (m_corpseRemoveTime <= time(NULL)) + else if (m_corpseRemoveTime <= time(nullptr)) { RemoveCorpse(false); TC_LOG_DEBUG("entities.unit", "Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY)); @@ -700,7 +702,7 @@ void Creature::Update(uint32 diff) if (m_combatPulseTime == 0) { - Map::PlayerList const &players = GetMap()->GetPlayers(); + Map::PlayerList const& players = GetMap()->GetPlayers(); if (!players.isEmpty()) for (Map::PlayerList::const_iterator it = players.begin(); it != players.end(); ++it) { @@ -709,11 +711,11 @@ void Creature::Update(uint32 diff) if (player->IsGameMaster()) continue; - if (player->IsAlive() && this->IsHostileTo(player)) + if (player->IsAlive() && IsHostileTo(player)) { if (CanHaveThreatList()) AddThreat(player, 0.0f); - this->SetInCombatWith(player); + SetInCombatWith(player); player->SetInCombatWith(this); } } @@ -1486,7 +1488,7 @@ bool Creature::LoadCreatureFromDB(ObjectGuid::LowType spawnId, Map* map, bool ad // Is the creature script objecting to us spawning? If yes, delay by one second (then re-check in ::Update) if (!m_respawnTime && !sScriptMgr->CanSpawn(spawnId, GetEntry(), GetCreatureTemplate(), GetCreatureData(), map)) - m_respawnTime = time(NULL)+1; + m_respawnTime = time(nullptr)+1; if (m_respawnTime) // respawn on Update { @@ -1620,7 +1622,7 @@ bool Creature::IsInvisibleDueToDespawn() const if (Unit::IsInvisibleDueToDespawn()) return true; - if (IsAlive() || isDying() || m_corpseRemoveTime > time(NULL)) + if (IsAlive() || isDying() || m_corpseRemoveTime > time(nullptr)) return false; return true; @@ -1739,11 +1741,11 @@ void Creature::setDeathState(DeathState s) if (s == JUST_DIED) { - m_corpseRemoveTime = time(NULL) + m_corpseDelay; + m_corpseRemoveTime = time(nullptr) + m_corpseDelay; if (IsDungeonBoss() && !m_respawnDelay) m_respawnTime = std::numeric_limits::max(); // never respawn in this instance else - m_respawnTime = time(NULL) + m_respawnDelay + m_corpseDelay; + m_respawnTime = time(nullptr) + m_respawnDelay + m_corpseDelay; // always save boss respawn time at death to prevent crash cheating if (sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY) || isWorldBoss()) @@ -1910,7 +1912,7 @@ void Creature::ForcedDespawn(uint32 timeMSToDespawn, Seconds const& forceRespawn void Creature::DespawnOrUnsummon(uint32 msTimeToDespawn /*= 0*/, Seconds const& forceRespawnTimer /*= 0*/) { - if (TempSummon* summon = this->ToTempSummon()) + if (TempSummon* summon = ToTempSummon()) summon->UnSummon(msTimeToDespawn); else ForcedDespawn(msTimeToDespawn, forceRespawnTimer); @@ -2162,7 +2164,7 @@ void Creature::CallForHelp(float radius) Cell::VisitGridObjects(this, worker, radius); } -bool Creature::CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction /*= true*/) const +bool Creature::CanAssistTo(Unit const* u, Unit const* enemy, bool checkfaction /*= true*/) const { if (IsInEvadeMode()) return false; @@ -2426,7 +2428,7 @@ void Creature::SetInCombatWithZone() return; } - Map::PlayerList const &PlList = map->GetPlayers(); + Map::PlayerList const& PlList = map->GetPlayers(); if (PlList.isEmpty()) return; @@ -2440,7 +2442,7 @@ void Creature::SetInCombatWithZone() if (player->IsAlive()) { - this->SetInCombatWith(player); + SetInCombatWith(player); player->SetInCombatWith(this); AddThreat(player, 0.0f); } @@ -2464,7 +2466,7 @@ bool Creature::HasSpell(uint32 spellID) const time_t Creature::GetRespawnTimeEx() const { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime > now) return m_respawnTime; else @@ -2508,7 +2510,7 @@ void Creature::AllLootRemovedFromCorpse() if (LootTemplates_Skinning.HaveLootFor(GetCreatureTemplate()->SkinLootId)) SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); - time_t now = time(NULL); + time_t now = time(nullptr); // Do not reset corpse remove time if corpse is already removed if (m_corpseRemoveTime <= now) return; @@ -2576,7 +2578,7 @@ uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem) VendorItemCount* vCount = &*itr; - time_t ptime = time(NULL); + time_t ptime = time(nullptr); if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) if (ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(vItem->item)) @@ -2614,7 +2616,7 @@ uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 us VendorItemCount* vCount = &*itr; - time_t ptime = time(NULL); + time_t ptime = time(nullptr); if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) if (ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(vItem->item)) @@ -2792,7 +2794,7 @@ float Creature::GetAggroRange(Unit const* target) const // Determines the aggro range for creatures (usually pets), used mainly for aggressive pet target selection. // Based on data from wowwiki due to lack of 3.3.5a data - if (target && this->IsPet()) + if (target && IsPet()) { uint32 targetLevel = 0; @@ -2841,7 +2843,7 @@ Unit* Creature::SelectNearestHostileUnitInAggroRange(bool useLOS) const // Selects nearest hostile target within creature's aggro range. Used primarily by // pets set to aggressive. Will not return neutral or friendly targets. - Unit* target = NULL; + Unit* target = nullptr; Trinity::NearestHostileUnitInAggroRangeCheck u_check(this, useLOS); Trinity::UnitSearcher searcher(this, target, u_check); diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index 2e398dcb223..77f383dcfd2 100644 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -19,15 +19,13 @@ #ifndef TRINITYCORE_CREATURE_H #define TRINITYCORE_CREATURE_H -#include "Common.h" #include "Unit.h" -#include "UpdateMask.h" -#include "ItemTemplate.h" -#include "LootMgr.h" -#include "DatabaseEnv.h" -#include "Cell.h" -#include "WorldPacket.h" - +#include "Common.h" +#include "CreatureData.h" +#include "DatabaseEnvFwd.h" +#include "Duration.h" +#include "Loot.h" +#include "MapObject.h" #include class CreatureAI; @@ -37,364 +35,12 @@ class Quest; class Player; class SpellInfo; class WorldSession; - -enum CreatureFlagsExtra : uint32 -{ - CREATURE_FLAG_EXTRA_INSTANCE_BIND = 0x00000001, // creature kill bind instance with killer and killer's group - CREATURE_FLAG_EXTRA_CIVILIAN = 0x00000002, // not aggro (ignore faction/reputation hostility) - CREATURE_FLAG_EXTRA_NO_PARRY = 0x00000004, // creature can't parry - CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN = 0x00000008, // creature can't counter-attack at parry - CREATURE_FLAG_EXTRA_NO_BLOCK = 0x00000010, // creature can't block - CREATURE_FLAG_EXTRA_NO_CRUSH = 0x00000020, // creature can't do crush attacks - CREATURE_FLAG_EXTRA_NO_XP_AT_KILL = 0x00000040, // creature kill not provide XP - CREATURE_FLAG_EXTRA_TRIGGER = 0x00000080, // trigger creature - CREATURE_FLAG_EXTRA_NO_TAUNT = 0x00000100, // creature is immune to taunt auras and effect attack me - CREATURE_FLAG_EXTRA_NO_MOVE_FLAGS_UPDATE = 0x00000200, // creature won't update movement flags - CREATURE_FLAG_EXTRA_GHOST_VISIBILITY = 0x00000400, // creature will be only visible for dead players - CREATURE_FLAG_EXTRA_UNUSED_11 = 0x00000800, - CREATURE_FLAG_EXTRA_UNUSED_12 = 0x00001000, - CREATURE_FLAG_EXTRA_UNUSED_13 = 0x00002000, - CREATURE_FLAG_EXTRA_WORLDEVENT = 0x00004000, // custom flag for world event creatures (left room for merging) - CREATURE_FLAG_EXTRA_GUARD = 0x00008000, // Creature is guard - CREATURE_FLAG_EXTRA_UNUSED_16 = 0x00010000, - CREATURE_FLAG_EXTRA_NO_CRIT = 0x00020000, // creature can't do critical strikes - CREATURE_FLAG_EXTRA_NO_SKILLGAIN = 0x00040000, // creature won't increase weapon skills - CREATURE_FLAG_EXTRA_TAUNT_DIMINISH = 0x00080000, // Taunt is a subject to diminishing returns on this creautre - CREATURE_FLAG_EXTRA_ALL_DIMINISH = 0x00100000, // creature is subject to all diminishing returns as player are - CREATURE_FLAG_EXTRA_NO_PLAYER_DAMAGE_REQ = 0x00200000, // creature does not need to take player damage for kill credit - CREATURE_FLAG_EXTRA_UNUSED_22 = 0x00400000, - CREATURE_FLAG_EXTRA_UNUSED_23 = 0x00800000, - CREATURE_FLAG_EXTRA_UNUSED_24 = 0x01000000, - CREATURE_FLAG_EXTRA_UNUSED_25 = 0x02000000, - CREATURE_FLAG_EXTRA_UNUSED_26 = 0x04000000, - CREATURE_FLAG_EXTRA_UNUSED_27 = 0x08000000, - CREATURE_FLAG_EXTRA_DUNGEON_BOSS = 0x10000000, // creature is a dungeon boss (SET DYNAMICALLY, DO NOT ADD IN DB) - CREATURE_FLAG_EXTRA_IGNORE_PATHFINDING = 0x20000000, // creature ignore pathfinding - CREATURE_FLAG_EXTRA_IMMUNITY_KNOCKBACK = 0x40000000, // creature is immune to knockback effects - CREATURE_FLAG_EXTRA_UNUSED_31 = 0x80000000, - - // Masks - CREATURE_FLAG_EXTRA_UNUSED = (CREATURE_FLAG_EXTRA_UNUSED_11 | CREATURE_FLAG_EXTRA_UNUSED_12 | CREATURE_FLAG_EXTRA_UNUSED_13 | - CREATURE_FLAG_EXTRA_UNUSED_16 | CREATURE_FLAG_EXTRA_UNUSED_22 | CREATURE_FLAG_EXTRA_UNUSED_23 | - CREATURE_FLAG_EXTRA_UNUSED_24 | CREATURE_FLAG_EXTRA_UNUSED_25 | CREATURE_FLAG_EXTRA_UNUSED_26 | - CREATURE_FLAG_EXTRA_UNUSED_27 | CREATURE_FLAG_EXTRA_UNUSED_31), - - CREATURE_FLAG_EXTRA_DB_ALLOWED = (0xFFFFFFFF & ~(CREATURE_FLAG_EXTRA_UNUSED | CREATURE_FLAG_EXTRA_DUNGEON_BOSS)) -}; - -static const uint32 CREATURE_REGEN_INTERVAL = 2 * IN_MILLISECONDS; -static const uint32 PET_FOCUS_REGEN_INTERVAL = 4 * IN_MILLISECONDS; -static const uint32 CREATURE_NOPATH_EVADE_TIME = 5 * IN_MILLISECONDS; - -static const uint8 MAX_KILL_CREDIT = 2; -static const uint32 MAX_CREATURE_MODELS = 4; -static const uint32 MAX_CREATURE_QUEST_ITEMS = 6; -static const uint32 MAX_CREATURE_SPELLS = 8; - -// from `creature_template` table -struct TC_GAME_API CreatureTemplate -{ - uint32 Entry; - uint32 DifficultyEntry[MAX_DIFFICULTY - 1]; - uint32 KillCredit[MAX_KILL_CREDIT]; - uint32 Modelid1; - uint32 Modelid2; - uint32 Modelid3; - uint32 Modelid4; - std::string Name; - std::string Title; - std::string IconName; - uint32 GossipMenuId; - uint8 minlevel; - uint8 maxlevel; - uint32 expansion; - uint32 faction; - uint32 npcflag; - float speed_walk; - float speed_run; - float scale; - uint32 rank; - uint32 dmgschool; - uint32 BaseAttackTime; - uint32 RangeAttackTime; - float BaseVariance; - float RangeVariance; - uint32 unit_class; // enum Classes. Note only 4 classes are known for creatures. - uint32 unit_flags; // enum UnitFlags mask values - uint32 unit_flags2; // enum UnitFlags2 mask values - uint32 dynamicflags; - CreatureFamily family; // enum CreatureFamily values (optional) - uint32 trainer_type; - uint32 trainer_spell; - uint32 trainer_class; - uint32 trainer_race; - uint32 type; // enum CreatureType values - uint32 type_flags; // enum CreatureTypeFlags mask values - uint32 lootid; - uint32 pickpocketLootId; - uint32 SkinLootId; - int32 resistance[MAX_SPELL_SCHOOL]; - uint32 spells[MAX_CREATURE_SPELLS]; - uint32 PetSpellDataId; - uint32 VehicleId; - uint32 mingold; - uint32 maxgold; - std::string AIName; - uint32 MovementType; - uint32 InhabitType; - float HoverHeight; - float ModHealth; - float ModMana; - float ModArmor; - float ModDamage; - float ModExperience; - bool RacialLeader; - uint32 movementId; - bool RegenHealth; - uint32 MechanicImmuneMask; - uint32 flags_extra; - uint32 ScriptID; - WorldPacket QueryData[TOTAL_LOCALES]; - uint32 GetRandomValidModelId() const; - uint32 GetFirstValidModelId() const; - uint32 GetFirstInvisibleModel() const; - uint32 GetFirstVisibleModel() const; - - // helpers - SkillType GetRequiredLootSkill() const - { - if (type_flags & CREATURE_TYPE_FLAG_HERB_SKINNING_SKILL) - return SKILL_HERBALISM; - else if (type_flags & CREATURE_TYPE_FLAG_MINING_SKINNING_SKILL) - return SKILL_MINING; - else if (type_flags & CREATURE_TYPE_FLAG_ENGINEERING_SKINNING_SKILL) - return SKILL_ENGINEERING; - else - return SKILL_SKINNING; // normal case - } - - bool IsExotic() const - { - return (type_flags & CREATURE_TYPE_FLAG_EXOTIC_PET) != 0; - } - - bool IsTameable(bool canTameExotic) const - { - if (type != CREATURE_TYPE_BEAST || family == CREATURE_FAMILY_NONE || (type_flags & CREATURE_TYPE_FLAG_TAMEABLE_PET) == 0) - return false; - - // if can tame exotic then can tame any tameable - return canTameExotic || !IsExotic(); - } - - void InitializeQueryData(); - WorldPacket BuildQueryData(LocaleConstant loc) const; -}; - -typedef std::vector CreatureQuestItemList; -typedef std::unordered_map CreatureQuestItemMap; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map CreatureTemplateContainer; - -#pragma pack(push, 1) - -// Defines base stats for creatures (used to calculate HP/mana/armor/attackpower/rangedattackpower/all damage). -struct TC_GAME_API CreatureBaseStats -{ - uint32 BaseHealth[MAX_EXPANSIONS]; - uint32 BaseMana; - uint32 BaseArmor; - uint32 AttackPower; - uint32 RangedAttackPower; - float BaseDamage[MAX_EXPANSIONS]; - - // Helpers - - uint32 GenerateHealth(CreatureTemplate const* info) const - { - return uint32(ceil(BaseHealth[info->expansion] * info->ModHealth)); - } - - uint32 GenerateMana(CreatureTemplate const* info) const - { - // Mana can be 0. - if (!BaseMana) - return 0; - - return uint32(ceil(BaseMana * info->ModMana)); - } - - uint32 GenerateArmor(CreatureTemplate const* info) const - { - return uint32(ceil(BaseArmor * info->ModArmor)); - } - - float GenerateBaseDamage(CreatureTemplate const* info) const - { - return BaseDamage[info->expansion]; - } - - static CreatureBaseStats const* GetBaseStats(uint8 level, uint8 unitClass); -}; - -typedef std::unordered_map CreatureBaseStatsContainer; - -struct CreatureLocale -{ - StringVector Name; - StringVector Title; -}; - -struct GossipMenuItemsLocale -{ - StringVector OptionText; - StringVector BoxText; -}; - -struct PointOfInterestLocale -{ - StringVector Name; -}; - -#define MAX_EQUIPMENT_ITEMS 3 - -struct EquipmentInfo -{ - uint32 ItemEntry[MAX_EQUIPMENT_ITEMS]; -}; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map EquipmentInfoContainerInternal; -typedef std::unordered_map EquipmentInfoContainer; - -// from `creature` table -struct CreatureData -{ - CreatureData() : id(0), mapid(0), phaseMask(0), displayid(0), equipmentId(0), - posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), - spawndist(0.0f), currentwaypoint(0), curhealth(0), curmana(0), movementType(0), - spawnMask(0), npcflag(0), unit_flags(0), dynamicflags(0), ScriptId(0), dbData(true) { } - uint32 id; // entry in creature_template - uint16 mapid; - uint32 phaseMask; - uint32 displayid; - int8 equipmentId; - float posX; - float posY; - float posZ; - float orientation; - uint32 spawntimesecs; - float spawndist; - uint32 currentwaypoint; - uint32 curhealth; - uint32 curmana; - uint8 movementType; - uint8 spawnMask; - uint32 npcflag; - uint32 unit_flags; // enum UnitFlags mask values - uint32 dynamicflags; - uint32 ScriptId; - bool dbData; -}; - -struct CreatureModelInfo -{ - float bounding_radius; - float combat_reach; - uint8 gender; - uint32 modelid_other_gender; - bool is_trigger; -}; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map CreatureModelContainer; - -enum InhabitTypeValues -{ - INHABIT_GROUND = 1, - INHABIT_WATER = 2, - INHABIT_AIR = 4, - INHABIT_ROOT = 8, - INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR | INHABIT_ROOT -}; - -// Enums used by StringTextData::Type (CreatureEventAI) -enum ChatType -{ - CHAT_TYPE_SAY = 0, - CHAT_TYPE_YELL = 1, - CHAT_TYPE_TEXT_EMOTE = 2, - CHAT_TYPE_BOSS_EMOTE = 3, - CHAT_TYPE_WHISPER = 4, - CHAT_TYPE_BOSS_WHISPER = 5, - CHAT_TYPE_ZONE_YELL = 6, - CHAT_TYPE_END = 255 -}; - -#pragma pack(pop) - -// `creature_addon` table -struct CreatureAddon -{ - uint32 path_id; - uint32 mount; - uint32 bytes1; - uint32 bytes2; - uint32 emote; - std::vector auras; -}; - -typedef std::unordered_map CreatureAddonContainer; -typedef std::unordered_map CreatureAddonTemplateContainer; - -// Vendors -struct VendorItem -{ - VendorItem(uint32 _item, int32 _maxcount, uint32 _incrtime, uint32 _ExtendedCost) - : item(_item), maxcount(_maxcount), incrtime(_incrtime), ExtendedCost(_ExtendedCost) { } - - uint32 item; - uint32 maxcount; // 0 for infinity item amount - uint32 incrtime; // time for restore items amount if maxcount != 0 - uint32 ExtendedCost; - - //helpers - bool IsGoldRequired(ItemTemplate const* pProto) const { return (pProto->Flags2 & ITEM_FLAG2_DONT_IGNORE_BUY_PRICE) || !ExtendedCost; } -}; -typedef std::vector VendorItemList; - -struct VendorItemData -{ - VendorItemList m_items; - - VendorItem* GetItem(uint32 slot) const - { - if (slot >= m_items.size()) - return NULL; - - return m_items[slot]; - } - bool Empty() const { return m_items.empty(); } - uint8 GetItemCount() const { return m_items.size(); } - void AddItem(uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost) - { - m_items.push_back(new VendorItem(item, maxcount, ptime, ExtendedCost)); - } - bool RemoveItem(uint32 item_id); - VendorItem const* FindItemCostPair(uint32 item_id, uint32 extendedCost) const; - void Clear() - { - for (VendorItemList::const_iterator itr = m_items.begin(); itr != m_items.end(); ++itr) - delete (*itr); - m_items.clear(); - } -}; +enum MovementGeneratorType : uint8; struct VendorItemCount { - explicit VendorItemCount(uint32 _item, uint32 _count) - : itemId(_item), count(_count), lastIncrementTime(time(NULL)) { } + VendorItemCount(uint32 _item, uint32 _count) + : itemId(_item), count(_count), lastIncrementTime(time(nullptr)) { } uint32 itemId; uint32 count; @@ -403,38 +49,6 @@ struct VendorItemCount typedef std::list VendorItemCounts; -struct TrainerSpell -{ - TrainerSpell() : SpellID(0), MoneyCost(0), ReqSkillLine(0), ReqSkillRank(0), ReqLevel(0) - { - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - ReqAbility[i] = 0; - } - - uint32 SpellID; - uint32 MoneyCost; - uint32 ReqSkillLine; - uint32 ReqSkillRank; - uint32 ReqLevel; - uint32 ReqAbility[3]; - - // helpers - bool IsCastable() const { return ReqAbility[0] != SpellID; } -}; - -typedef std::unordered_map TrainerSpellMap; - -struct TC_GAME_API TrainerSpellData -{ - TrainerSpellData() : trainerType(0) { } - ~TrainerSpellData() { spellList.clear(); } - - TrainerSpellMap spellList; - uint32 trainerType; // trainer type based at trainer spells, can be different from creature_template value. - // req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2. - TrainerSpell const* Find(uint32 spell_id) const; -}; - // max different by z coordinate for creature aggro reaction #define CREATURE_Z_ATTACK_RANGE 3 @@ -447,7 +61,6 @@ typedef std::unordered_map CreatureTextRepeatGroup class TC_GAME_API Creature : public Unit, public GridObject, public MapObject { public: - explicit Creature(bool isWorldObject = false); virtual ~Creature(); @@ -504,7 +117,7 @@ class TC_GAME_API Creature : public Unit, public GridObject, public Ma bool IsEvadingAttacks() const { return IsInEvadeMode() || CanNotReachTarget(); } bool AIM_Destroy(); - bool AIM_Initialize(CreatureAI* ai = NULL); + bool AIM_Initialize(CreatureAI* ai = nullptr); void Motion_Initialize(); CreatureAI* AI() const { return reinterpret_cast(i_AI); } @@ -611,8 +224,8 @@ class TC_GAME_API Creature : public Unit, public GridObject, public Ma void SetNoCallAssistance(bool val) { m_AlreadyCallAssistance = val; } void SetNoSearchAssistance(bool val) { m_AlreadySearchedAssistance = val; } bool HasSearchedAssistance() const { return m_AlreadySearchedAssistance; } - bool CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction = true) const; - bool _IsTargetAcceptable(const Unit* target) const; + bool CanAssistTo(Unit const* u, Unit const* enemy, bool checkfaction = true) const; + bool _IsTargetAcceptable(Unit const* target) const; MovementGeneratorType GetDefaultMovementType() const { return m_defaultMovementType; } void SetDefaultMovementType(MovementGeneratorType mgt) { m_defaultMovementType = mgt; } @@ -624,7 +237,7 @@ class TC_GAME_API Creature : public Unit, public GridObject, public Ma time_t const& GetRespawnTime() const { return m_respawnTime; } time_t GetRespawnTimeEx() const; - void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(NULL) + respawn : 0; } + void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(nullptr) + respawn : 0; } void Respawn(bool force = false); void SaveRespawnTime() override; @@ -669,12 +282,12 @@ class TC_GAME_API Creature : public Unit, public GridObject, public Ma bool CanNotReachTarget() const { return m_cannotReachTarget; } void SetHomePosition(float x, float y, float z, float o) { m_homePosition.Relocate(x, y, z, o); } - void SetHomePosition(const Position &pos) { m_homePosition.Relocate(pos); } + void SetHomePosition(Position const& pos) { m_homePosition.Relocate(pos); } void GetHomePosition(float& x, float& y, float& z, float& ori) const { m_homePosition.GetPosition(x, y, z, ori); } Position const& GetHomePosition() const { return m_homePosition; } void SetTransportHomePosition(float x, float y, float z, float o) { m_transportHomePosition.Relocate(x, y, z, o); } - void SetTransportHomePosition(const Position &pos) { m_transportHomePosition.Relocate(pos); } + void SetTransportHomePosition(Position const& pos) { m_transportHomePosition.Relocate(pos); } void GetTransportHomePosition(float& x, float& y, float& z, float& ori) const { m_transportHomePosition.GetPosition(x, y, z, ori); } Position const& GetTransportHomePosition() const { return m_transportHomePosition; } diff --git a/src/server/game/Entities/Creature/CreatureData.h b/src/server/game/Entities/Creature/CreatureData.h new file mode 100644 index 00000000000..754963f9812 --- /dev/null +++ b/src/server/game/Entities/Creature/CreatureData.h @@ -0,0 +1,370 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef CreatureData_h__ +#define CreatureData_h__ + +#include "DBCEnums.h" +#include "SharedDefines.h" +#include "UnitDefines.h" +#include "WorldPacket.h" +#include +#include +#include +#include + +struct ItemTemplate; + +enum CreatureFlagsExtra : uint32 +{ + CREATURE_FLAG_EXTRA_INSTANCE_BIND = 0x00000001, // creature kill bind instance with killer and killer's group + CREATURE_FLAG_EXTRA_CIVILIAN = 0x00000002, // not aggro (ignore faction/reputation hostility) + CREATURE_FLAG_EXTRA_NO_PARRY = 0x00000004, // creature can't parry + CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN = 0x00000008, // creature can't counter-attack at parry + CREATURE_FLAG_EXTRA_NO_BLOCK = 0x00000010, // creature can't block + CREATURE_FLAG_EXTRA_NO_CRUSH = 0x00000020, // creature can't do crush attacks + CREATURE_FLAG_EXTRA_NO_XP_AT_KILL = 0x00000040, // creature kill not provide XP + CREATURE_FLAG_EXTRA_TRIGGER = 0x00000080, // trigger creature + CREATURE_FLAG_EXTRA_NO_TAUNT = 0x00000100, // creature is immune to taunt auras and effect attack me + CREATURE_FLAG_EXTRA_NO_MOVE_FLAGS_UPDATE = 0x00000200, // creature won't update movement flags + CREATURE_FLAG_EXTRA_GHOST_VISIBILITY = 0x00000400, // creature will be only visible for dead players + CREATURE_FLAG_EXTRA_UNUSED_11 = 0x00000800, + CREATURE_FLAG_EXTRA_UNUSED_12 = 0x00001000, + CREATURE_FLAG_EXTRA_UNUSED_13 = 0x00002000, + CREATURE_FLAG_EXTRA_WORLDEVENT = 0x00004000, // custom flag for world event creatures (left room for merging) + CREATURE_FLAG_EXTRA_GUARD = 0x00008000, // Creature is guard + CREATURE_FLAG_EXTRA_UNUSED_16 = 0x00010000, + CREATURE_FLAG_EXTRA_NO_CRIT = 0x00020000, // creature can't do critical strikes + CREATURE_FLAG_EXTRA_NO_SKILLGAIN = 0x00040000, // creature won't increase weapon skills + CREATURE_FLAG_EXTRA_TAUNT_DIMINISH = 0x00080000, // Taunt is a subject to diminishing returns on this creautre + CREATURE_FLAG_EXTRA_ALL_DIMINISH = 0x00100000, // creature is subject to all diminishing returns as player are + CREATURE_FLAG_EXTRA_NO_PLAYER_DAMAGE_REQ = 0x00200000, // creature does not need to take player damage for kill credit + CREATURE_FLAG_EXTRA_UNUSED_22 = 0x00400000, + CREATURE_FLAG_EXTRA_UNUSED_23 = 0x00800000, + CREATURE_FLAG_EXTRA_UNUSED_24 = 0x01000000, + CREATURE_FLAG_EXTRA_UNUSED_25 = 0x02000000, + CREATURE_FLAG_EXTRA_UNUSED_26 = 0x04000000, + CREATURE_FLAG_EXTRA_UNUSED_27 = 0x08000000, + CREATURE_FLAG_EXTRA_DUNGEON_BOSS = 0x10000000, // creature is a dungeon boss (SET DYNAMICALLY, DO NOT ADD IN DB) + CREATURE_FLAG_EXTRA_IGNORE_PATHFINDING = 0x20000000, // creature ignore pathfinding + CREATURE_FLAG_EXTRA_IMMUNITY_KNOCKBACK = 0x40000000, // creature is immune to knockback effects + CREATURE_FLAG_EXTRA_UNUSED_31 = 0x80000000, + + // Masks + CREATURE_FLAG_EXTRA_UNUSED = (CREATURE_FLAG_EXTRA_UNUSED_11 | CREATURE_FLAG_EXTRA_UNUSED_12 | CREATURE_FLAG_EXTRA_UNUSED_13 | + CREATURE_FLAG_EXTRA_UNUSED_16 | CREATURE_FLAG_EXTRA_UNUSED_22 | CREATURE_FLAG_EXTRA_UNUSED_23 | + CREATURE_FLAG_EXTRA_UNUSED_24 | CREATURE_FLAG_EXTRA_UNUSED_25 | CREATURE_FLAG_EXTRA_UNUSED_26 | + CREATURE_FLAG_EXTRA_UNUSED_27 | CREATURE_FLAG_EXTRA_UNUSED_31), + + CREATURE_FLAG_EXTRA_DB_ALLOWED = (0xFFFFFFFF & ~(CREATURE_FLAG_EXTRA_UNUSED | CREATURE_FLAG_EXTRA_DUNGEON_BOSS)) +}; + +static const uint32 CREATURE_REGEN_INTERVAL = 2 * IN_MILLISECONDS; +static const uint32 PET_FOCUS_REGEN_INTERVAL = 4 * IN_MILLISECONDS; +static const uint32 CREATURE_NOPATH_EVADE_TIME = 5 * IN_MILLISECONDS; + +static const uint8 MAX_KILL_CREDIT = 2; +static const uint32 MAX_CREATURE_MODELS = 4; +static const uint32 MAX_CREATURE_QUEST_ITEMS = 6; +static const uint32 MAX_CREATURE_SPELLS = 8; + +// from `creature_template` table +struct TC_GAME_API CreatureTemplate +{ + uint32 Entry; + uint32 DifficultyEntry[MAX_DIFFICULTY - 1]; + uint32 KillCredit[MAX_KILL_CREDIT]; + uint32 Modelid1; + uint32 Modelid2; + uint32 Modelid3; + uint32 Modelid4; + std::string Name; + std::string Title; + std::string IconName; + uint32 GossipMenuId; + uint8 minlevel; + uint8 maxlevel; + uint32 expansion; + uint32 faction; + uint32 npcflag; + float speed_walk; + float speed_run; + float scale; + uint32 rank; + uint32 dmgschool; + uint32 BaseAttackTime; + uint32 RangeAttackTime; + float BaseVariance; + float RangeVariance; + uint32 unit_class; // enum Classes. Note only 4 classes are known for creatures. + uint32 unit_flags; // enum UnitFlags mask values + uint32 unit_flags2; // enum UnitFlags2 mask values + uint32 dynamicflags; + CreatureFamily family; // enum CreatureFamily values (optional) + uint32 trainer_type; + uint32 trainer_spell; + uint32 trainer_class; + uint32 trainer_race; + uint32 type; // enum CreatureType values + uint32 type_flags; // enum CreatureTypeFlags mask values + uint32 lootid; + uint32 pickpocketLootId; + uint32 SkinLootId; + int32 resistance[MAX_SPELL_SCHOOL]; + uint32 spells[MAX_CREATURE_SPELLS]; + uint32 PetSpellDataId; + uint32 VehicleId; + uint32 mingold; + uint32 maxgold; + std::string AIName; + uint32 MovementType; + uint32 InhabitType; + float HoverHeight; + float ModHealth; + float ModMana; + float ModArmor; + float ModDamage; + float ModExperience; + bool RacialLeader; + uint32 movementId; + bool RegenHealth; + uint32 MechanicImmuneMask; + uint32 flags_extra; + uint32 ScriptID; + WorldPacket QueryData[TOTAL_LOCALES]; + uint32 GetRandomValidModelId() const; + uint32 GetFirstValidModelId() const; + uint32 GetFirstInvisibleModel() const; + uint32 GetFirstVisibleModel() const; + + // helpers + SkillType GetRequiredLootSkill() const + { + if (type_flags & CREATURE_TYPE_FLAG_HERB_SKINNING_SKILL) + return SKILL_HERBALISM; + else if (type_flags & CREATURE_TYPE_FLAG_MINING_SKINNING_SKILL) + return SKILL_MINING; + else if (type_flags & CREATURE_TYPE_FLAG_ENGINEERING_SKINNING_SKILL) + return SKILL_ENGINEERING; + else + return SKILL_SKINNING; // normal case + } + + bool IsExotic() const + { + return (type_flags & CREATURE_TYPE_FLAG_EXOTIC_PET) != 0; + } + + bool IsTameable(bool canTameExotic) const + { + if (type != CREATURE_TYPE_BEAST || family == CREATURE_FAMILY_NONE || (type_flags & CREATURE_TYPE_FLAG_TAMEABLE_PET) == 0) + return false; + + // if can tame exotic then can tame any tameable + return canTameExotic || !IsExotic(); + } + + void InitializeQueryData(); + WorldPacket BuildQueryData(LocaleConstant loc) const; +}; + +#pragma pack(push, 1) + +// Defines base stats for creatures (used to calculate HP/mana/armor/attackpower/rangedattackpower/all damage). +struct TC_GAME_API CreatureBaseStats +{ + uint32 BaseHealth[MAX_EXPANSIONS]; + uint32 BaseMana; + uint32 BaseArmor; + uint32 AttackPower; + uint32 RangedAttackPower; + float BaseDamage[MAX_EXPANSIONS]; + + // Helpers + + uint32 GenerateHealth(CreatureTemplate const* info) const + { + return uint32(ceil(BaseHealth[info->expansion] * info->ModHealth)); + } + + uint32 GenerateMana(CreatureTemplate const* info) const + { + // Mana can be 0. + if (!BaseMana) + return 0; + + return uint32(ceil(BaseMana * info->ModMana)); + } + + uint32 GenerateArmor(CreatureTemplate const* info) const + { + return uint32(ceil(BaseArmor * info->ModArmor)); + } + + float GenerateBaseDamage(CreatureTemplate const* info) const + { + return BaseDamage[info->expansion]; + } + + static CreatureBaseStats const* GetBaseStats(uint8 level, uint8 unitClass); +}; + +struct CreatureLocale +{ + std::vector Name; + std::vector Title; +}; + +struct EquipmentInfo +{ + uint32 ItemEntry[MAX_EQUIPMENT_ITEMS]; +}; + +// from `creature` table +struct CreatureData +{ + CreatureData() : id(0), mapid(0), phaseMask(0), displayid(0), equipmentId(0), + posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), + spawndist(0.0f), currentwaypoint(0), curhealth(0), curmana(0), movementType(0), + spawnMask(0), npcflag(0), unit_flags(0), dynamicflags(0), ScriptId(0), dbData(true) { } + uint32 id; // entry in creature_template + uint16 mapid; + uint32 phaseMask; + uint32 displayid; + int8 equipmentId; + float posX; + float posY; + float posZ; + float orientation; + uint32 spawntimesecs; + float spawndist; + uint32 currentwaypoint; + uint32 curhealth; + uint32 curmana; + uint8 movementType; + uint8 spawnMask; + uint32 npcflag; + uint32 unit_flags; // enum UnitFlags mask values + uint32 dynamicflags; + uint32 ScriptId; + bool dbData; +}; + +struct CreatureModelInfo +{ + float bounding_radius; + float combat_reach; + uint8 gender; + uint32 modelid_other_gender; + bool is_trigger; +}; + +enum InhabitTypeValues +{ + INHABIT_GROUND = 1, + INHABIT_WATER = 2, + INHABIT_AIR = 4, + INHABIT_ROOT = 8, + INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR | INHABIT_ROOT +}; + +#pragma pack(pop) + +// `creature_addon` table +struct CreatureAddon +{ + uint32 path_id; + uint32 mount; + uint32 bytes1; + uint32 bytes2; + uint32 emote; + std::vector auras; +}; + +// Vendors +struct VendorItem +{ + VendorItem(uint32 _item, int32 _maxcount, uint32 _incrtime, uint32 _ExtendedCost) + : item(_item), maxcount(_maxcount), incrtime(_incrtime), ExtendedCost(_ExtendedCost) { } + + uint32 item; + uint32 maxcount; // 0 for infinity item amount + uint32 incrtime; // time for restore items amount if maxcount != 0 + uint32 ExtendedCost; + + //helpers + bool IsGoldRequired(ItemTemplate const* pProto) const; +}; + +struct VendorItemData +{ + std::vector m_items; + + VendorItem const* GetItem(uint32 slot) const + { + if (slot >= m_items.size()) + return nullptr; + + return &m_items[slot]; + } + bool Empty() const { return m_items.empty(); } + uint8 GetItemCount() const { return m_items.size(); } + void AddItem(uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost) + { + m_items.emplace_back(item, maxcount, ptime, ExtendedCost); + } + bool RemoveItem(uint32 item_id); + VendorItem const* FindItemCostPair(uint32 item_id, uint32 extendedCost) const; + void Clear() + { + m_items.clear(); + } +}; + +struct TrainerSpell +{ + TrainerSpell() : SpellID(0), MoneyCost(0), ReqSkillLine(0), ReqSkillRank(0), ReqLevel(0) + { + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + ReqAbility[i] = 0; + } + + uint32 SpellID; + uint32 MoneyCost; + uint32 ReqSkillLine; + uint32 ReqSkillRank; + uint32 ReqLevel; + uint32 ReqAbility[3]; + + // helpers + bool IsCastable() const { return ReqAbility[0] != SpellID; } +}; + +typedef std::unordered_map TrainerSpellMap; + +struct TC_GAME_API TrainerSpellData +{ + TrainerSpellData() : trainerType(0) { } + ~TrainerSpellData() { spellList.clear(); } + + TrainerSpellMap spellList; + uint32 trainerType; // trainer type based at trainer spells, can be different from creature_template value. + // req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2. + TrainerSpell const* Find(uint32 spell_id) const; +}; + +#endif // CreatureData_h__ diff --git a/src/server/game/Entities/Creature/CreatureGroups.cpp b/src/server/game/Entities/Creature/CreatureGroups.cpp index c0bdaddb767..0c19bdb502d 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.cpp +++ b/src/server/game/Entities/Creature/CreatureGroups.cpp @@ -16,11 +16,14 @@ * with this program. If not, see . */ -#include "Creature.h" #include "CreatureGroups.h" -#include "ObjectMgr.h" - +#include "Creature.h" #include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #define MAX_DESYNC 5.0f @@ -164,10 +167,10 @@ void CreatureGroup::AddMember(Creature* member) void CreatureGroup::RemoveMember(Creature* member) { if (m_leader == member) - m_leader = NULL; + m_leader = nullptr; m_members.erase(member); - member->SetFormation(NULL); + member->SetFormation(nullptr); } void CreatureGroup::MemberAttackStart(Creature* member, Unit* target) @@ -217,7 +220,7 @@ void CreatureGroup::FormationReset(bool dismiss) m_Formed = !dismiss; } -void CreatureGroup::LeaderMoveTo(Position destination, uint32 id /*= 0*/, uint32 moveType /*= 0*/, bool orientation /*= false*/) +void CreatureGroup::LeaderMoveTo(Position const& destination, uint32 id /*= 0*/, uint32 moveType /*= 0*/, bool orientation /*= false*/) { //! To do: This should probably get its own movement generator or use WaypointMovementGenerator. //! If the leader's path is known, member's path can be plotted as well using formation offsets. diff --git a/src/server/game/Entities/Creature/CreatureGroups.h b/src/server/game/Entities/Creature/CreatureGroups.h index ae57d7b9152..ddb8b6876ec 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.h +++ b/src/server/game/Entities/Creature/CreatureGroups.h @@ -20,11 +20,14 @@ #define _FORMATIONS_H #include "Define.h" +#include "ObjectGuid.h" #include #include class Creature; class CreatureGroup; +class Unit; +struct Position; struct FormationInfo { @@ -65,7 +68,7 @@ class TC_GAME_API CreatureGroup public: //Group cannot be created empty - explicit CreatureGroup(uint32 id) : m_leader(NULL), m_groupID(id), m_Formed(false) { } + explicit CreatureGroup(uint32 id) : m_leader(nullptr), m_groupID(id), m_Formed(false) { } ~CreatureGroup() { } Creature* getLeader() const { return m_leader; } @@ -77,7 +80,7 @@ class TC_GAME_API CreatureGroup void RemoveMember(Creature* member); void FormationReset(bool dismiss); - void LeaderMoveTo(Position destination, uint32 id = 0, uint32 moveType = 0, bool orientation = false); + void LeaderMoveTo(Position const& destination, uint32 id = 0, uint32 moveType = 0, bool orientation = false); void MemberAttackStart(Creature* member, Unit* target); }; diff --git a/src/server/game/Entities/Creature/GossipDef.cpp b/src/server/game/Entities/Creature/GossipDef.cpp index 0c395eb8cad..caa700f6672 100644 --- a/src/server/game/Entities/Creature/GossipDef.cpp +++ b/src/server/game/Entities/Creature/GossipDef.cpp @@ -16,11 +16,13 @@ * with this program. If not, see . */ -#include "QuestDef.h" #include "GossipDef.h" +#include "Log.h" #include "ObjectMgr.h" +#include "Player.h" +#include "QuestDef.h" +#include "World.h" #include "WorldSession.h" -#include "Formulas.h" GossipMenu::GossipMenu() { @@ -229,7 +231,7 @@ void PlayerMenu::SendGossipMenu(uint32 titleTextId, ObjectGuid objectGUID) std::string title = quest->GetTitle(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(questID)) ObjectMgr::GetLocaleString(localeData->Title, localeConstant, title); @@ -263,7 +265,7 @@ void PlayerMenu::SendPointOfInterest(uint32 id) const std::string name = poi->Name; LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (PointOfInterestLocale const* localeData = sObjectMgr->GetPointOfInterestLocale(id)) ObjectMgr::GetLocaleString(localeData->Name, localeConstant, name); @@ -348,7 +350,7 @@ void PlayerMenu::SendQuestGiverQuestList(QEmote const& eEmote, const std::string std::string title = quest->GetTitle(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(questID)) ObjectMgr::GetLocaleString(localeData->Title, localeConstant, title); @@ -387,7 +389,7 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, ObjectGuid npcGU std::string questAreaDescription = quest->GetAreaDescription(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { @@ -506,7 +508,7 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* quest, ObjectGuid npcGUI std::string questOfferRewardText = quest->GetOfferRewardText(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { @@ -603,7 +605,7 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* quest, ObjectGuid npcGU std::string requestItemsText = quest->GetRequestItemsText(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { diff --git a/src/server/game/Entities/Creature/GossipDef.h b/src/server/game/Entities/Creature/GossipDef.h index 9826057361d..cd9d529605f 100644 --- a/src/server/game/Entities/Creature/GossipDef.h +++ b/src/server/game/Entities/Creature/GossipDef.h @@ -21,9 +21,10 @@ #include "Common.h" #include "ObjectGuid.h" -#include "QuestDef.h" #include "NPCHandler.h" +#include +class Quest; class WorldSession; #define GOSSIP_MAX_MENU_ITEMS 32 @@ -192,7 +193,7 @@ class TC_GAME_API GossipMenu if (itr != _menuItems.end()) return &itr->second; - return NULL; + return nullptr; } GossipMenuItemData const* GetItemData(uint32 indexId) const @@ -201,7 +202,7 @@ class TC_GAME_API GossipMenu if (itr != _menuItemData.end()) return &itr->second; - return NULL; + return nullptr; } uint32 GetMenuItemSender(uint32 menuItemId) const; diff --git a/src/server/game/Entities/Creature/TemporarySummon.cpp b/src/server/game/Entities/Creature/TemporarySummon.cpp index bc433ed2d69..7e9cf6bf7a3 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.cpp +++ b/src/server/game/Entities/Creature/TemporarySummon.cpp @@ -16,10 +16,12 @@ * with this program. If not, see . */ +#include "TemporarySummon.h" +#include "CreatureAI.h" +#include "DBCStructure.h" #include "Log.h" +#include "Map.h" #include "ObjectAccessor.h" -#include "CreatureAI.h" -#include "TemporarySummon.h" #include "Pet.h" #include "Player.h" @@ -35,12 +37,12 @@ m_timer(0), m_lifetime(0) Unit* TempSummon::GetSummoner() const { - return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : NULL; + return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : nullptr; } Creature* TempSummon::GetSummonerCreatureBase() const { - return m_summonerGUID ? ObjectAccessor::GetCreature(*this, m_summonerGUID) : NULL; + return m_summonerGUID ? ObjectAccessor::GetCreature(*this, m_summonerGUID) : nullptr; } void TempSummon::Update(uint32 diff) @@ -250,7 +252,7 @@ void TempSummon::UnSummon(uint32 msTime) //ASSERT(!IsPet()); if (IsPet()) { - ((Pet*)this)->Remove(PET_SAVE_NOT_IN_SLOT); + ToPet()->Remove(PET_SAVE_NOT_IN_SLOT); ASSERT(!IsInWorld()); return; } @@ -395,6 +397,6 @@ void Puppet::RemoveFromWorld() if (!IsInWorld()) return; - RemoveCharmedBy(NULL); + RemoveCharmedBy(nullptr); Minion::RemoveFromWorld(); } diff --git a/src/server/game/Entities/Creature/TemporarySummon.h b/src/server/game/Entities/Creature/TemporarySummon.h index 50f6c592b9e..50d7f9f712f 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.h +++ b/src/server/game/Entities/Creature/TemporarySummon.h @@ -21,21 +21,7 @@ #include "Creature.h" -enum SummonerType -{ - SUMMONER_TYPE_CREATURE = 0, - SUMMONER_TYPE_GAMEOBJECT = 1, - SUMMONER_TYPE_MAP = 2 -}; - -/// Stores data for temp summons -struct TempSummonData -{ - uint32 entry; ///< Entry of summoned creature - Position pos; ///< Position, where should be creature spawned - TempSummonType type; ///< Summon type, see TempSummonType for available types - uint32 time; ///< Despawn time, usable only with certain temp summon types -}; +struct SummonPropertiesEntry; class TC_GAME_API TempSummon : public Creature { @@ -56,7 +42,7 @@ class TC_GAME_API TempSummon : public Creature TempSummonType const& GetSummonType() { return m_type; } uint32 GetTimer() const { return m_timer; } - const SummonPropertiesEntry* const m_Properties; + SummonPropertiesEntry const* const m_Properties; private: TempSummonType m_type; uint32 m_timer; diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.cpp b/src/server/game/Entities/DynamicObject/DynamicObject.cpp index b9be22478f6..87603080ada 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.cpp +++ b/src/server/game/Entities/DynamicObject/DynamicObject.cpp @@ -16,19 +16,22 @@ * with this program. If not, see . */ +#include "DynamicObject.h" #include "Common.h" -#include "UpdateMask.h" -#include "World.h" -#include "ObjectAccessor.h" -#include "DatabaseEnv.h" #include "GameTime.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "SpellAuras.h" +#include "SpellMgr.h" #include "ScriptMgr.h" #include "Transport.h" +#include "Unit.h" +#include "UpdateData.h" DynamicObject::DynamicObject(bool isWorldObject) : WorldObject(isWorldObject), - _aura(NULL), _removedAura(NULL), _caster(NULL), _duration(0), _isViewpoint(false) + _aura(nullptr), _removedAura(nullptr), _caster(nullptr), _duration(0), _isViewpoint(false) { m_objectType |= TYPEMASK_DYNAMICOBJECT; m_objectTypeId = TYPEID_DYNAMICOBJECT; @@ -204,7 +207,7 @@ void DynamicObject::RemoveAura() { ASSERT(_aura && !_removedAura); _removedAura = _aura; - _aura = NULL; + _aura = nullptr; if (!_removedAura->IsRemoved()) _removedAura->_Remove(AURA_REMOVE_BY_DEFAULT); } @@ -240,5 +243,10 @@ void DynamicObject::UnbindFromCaster() { ASSERT(_caster); _caster->_UnregisterDynObject(this); - _caster = NULL; + _caster = nullptr; +} + +SpellInfo const* DynamicObject::GetSpellInfo() const +{ + return sSpellMgr->GetSpellInfo(GetSpellId()); } diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.h b/src/server/game/Entities/DynamicObject/DynamicObject.h index 4eb6cb0dcca..94bb0d8bc8d 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.h +++ b/src/server/game/Entities/DynamicObject/DynamicObject.h @@ -20,6 +20,7 @@ #define TRINITYCORE_DYNAMICOBJECT_H #include "Object.h" +#include "MapObject.h" class Unit; class Aura; @@ -54,7 +55,8 @@ class TC_GAME_API DynamicObject : public WorldObject, public GridObject. */ -#include "GameObjectAI.h" +#include "GameObject.h" #include "Battleground.h" #include "CellImpl.h" #include "CreatureAISelector.h" +#include "DatabaseEnv.h" +#include "GameObjectAI.h" #include "GameObjectModel.h" #include "GameTime.h" +#include "GossipDef.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "GroupMgr.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" #include "PoolMgr.h" +#include "QueryPackets.h" #include "ScriptMgr.h" #include "SpellMgr.h" +#include "Transport.h" #include "UpdateFieldFlags.h" #include "World.h" -#include "Transport.h" -#include "GossipDef.h" - -#include "Packets/QueryPackets.h" +#include void GameObjectTemplate::InitializeQueryData() { @@ -76,7 +81,7 @@ WorldPacket GameObjectTemplate::BuildQueryData(LocaleConstant loc) const for (uint32 i = 0; i < MAX_GAMEOBJECT_QUEST_ITEMS; ++i) queryTemp.Stats.QuestItems[i] = 0; - if (GameObjectQuestItemList const* items = sObjectMgr->GetGameObjectQuestItemList(entry)) + if (std::vector const* items = sObjectMgr->GetGameObjectQuestItemList(entry)) for (uint32 i = 0; i < MAX_GAMEOBJECT_QUEST_ITEMS; ++i) if (i < items->size()) queryTemp.Stats.QuestItems[i] = (*items)[i]; @@ -84,6 +89,17 @@ WorldPacket GameObjectTemplate::BuildQueryData(LocaleConstant loc) const return *queryTemp.Write(); } +bool QuaternionData::isUnit() const +{ + return fabs(x * x + y * y + z * z + w * w - 1.0f) < 1e-5f; +} + +QuaternionData QuaternionData::fromEulerAnglesZYX(float Z, float Y, float X) +{ + G3D::Quat quat(G3D::Matrix3::fromEulerAnglesZYX(Z, Y, X)); + return QuaternionData(quat.x, quat.y, quat.z, quat.w); +} + GameObject::GameObject() : WorldObject(false), MapObject(), m_model(nullptr), m_goValue(), m_AI(nullptr) { @@ -224,7 +240,7 @@ void GameObject::RemoveFromWorld() } } -bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, G3D::Quat const& rotation, uint32 animprogress, GOState go_state, uint32 artKit /*= 0*/) +bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, QuaternionData const& rotation, uint32 animprogress, GOState go_state, uint32 artKit /*= 0*/) { ASSERT(map); SetMap(map); @@ -274,11 +290,11 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u return false; } - SetWorldRotation(rotation); + SetWorldRotation(rotation.x, rotation.y, rotation.z, rotation.w); GameObjectAddon const* gameObjectAddon = sObjectMgr->GetGameObjectAddon(GetSpawnId()); // For most of gameobjects is (0, 0, 0, 1) quaternion, there are only some transports with not standard rotation - G3D::Quat parentRotation; + QuaternionData parentRotation; if (gameObjectAddon) parentRotation = gameObjectAddon->ParentRotation; @@ -417,7 +433,10 @@ void GameObject::Update(uint32 diff) { m_goValue.Transport.CurrentSeg = node->TimeSeg; - G3D::Quat rotation = m_goValue.Transport.AnimationInfo->GetAnimRotation(timer); + G3D::Quat rotation; + if (TransportRotationEntry const* rot = m_goValue.Transport.AnimationInfo->GetAnimRotation(timer)) + rotation = G3D::Quat(rot->X, rot->Y, rot->Z, rot->W); + G3D::Vector3 pos = rotation.toRotationMatrix() * G3D::Matrix3::fromEulerAnglesZYX(GetOrientation(), 0.0f, 0.0f) * G3D::Vector3(node->X, node->Y, node->Z); @@ -437,7 +456,7 @@ void GameObject::Update(uint32 diff) case GAMEOBJECT_TYPE_FISHINGNODE: { // fishing code (bobber ready) - if (time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME) + if (time(nullptr) > m_respawnTime - FISHING_BOBBER_READY_TIME) { // splash bobber (bobber ready now) Unit* caster = GetOwner(); @@ -469,7 +488,7 @@ void GameObject::Update(uint32 diff) { if (m_respawnTime > 0) // timer on { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime <= now) // timer expired { ObjectGuid dbtableHighGuid(HighGuid::GameObject, GetEntry(), m_spawnId); @@ -738,7 +757,7 @@ void GameObject::Update(uint32 diff) return; } - m_respawnTime = time(NULL) + m_respawnDelayTime; + m_respawnTime = time(nullptr) + m_respawnDelayTime; // if option not set then object will be saved at grid unload if (sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY)) @@ -841,8 +860,7 @@ void GameObject::SaveToDB() void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) { - const GameObjectTemplate* goI = GetGOInfo(); - + GameObjectTemplate const* goI = GetGOInfo(); if (!goI) return; @@ -1039,7 +1057,7 @@ Unit* GameObject::GetOwner() const void GameObject::SaveRespawnTime() { - if (m_goData && m_goData->dbData && m_respawnTime > time(NULL) && m_spawnedByDefault) + if (m_goData && m_goData->dbData && m_respawnTime > time(nullptr) && m_spawnedByDefault) GetMap()->SaveGORespawnTime(m_spawnId, m_respawnTime); } @@ -1092,11 +1110,19 @@ bool GameObject::IsInvisibleDueToDespawn() const return false; } +uint8 GameObject::getLevelForTarget(WorldObject const* target) const +{ + if (Unit* owner = GetOwner()) + return owner->getLevelForTarget(target); + + return 1; +} + void GameObject::Respawn() { if (m_spawnedByDefault && m_respawnTime > 0) { - m_respawnTime = time(NULL); + m_respawnTime = time(nullptr); GetMap()->RemoveGORespawnTime(m_spawnId); } } @@ -1208,7 +1234,7 @@ void GameObject::SetGoArtKit(uint8 kit) void GameObject::SetGoArtKit(uint8 artkit, GameObject* go, ObjectGuid::LowType lowguid) { - const GameObjectData* data = nullptr; + GameObjectData const* data = nullptr; if (go) { go->SetGoArtKit(artkit); @@ -1981,13 +2007,18 @@ void GameObject::UpdatePackedRotation() m_packedRotation = z | (y << 21) | (x << 42); } -void GameObject::SetWorldRotation(G3D::Quat const& rot) +void GameObject::SetWorldRotation(float qx, float qy, float qz, float qw) { - m_worldRotation = rot.toUnit(); + G3D::Quat rotation(qx, qy, qz, qw); + rotation.unitize(); + m_worldRotation.x = rotation.x; + m_worldRotation.y = rotation.y; + m_worldRotation.z = rotation.z; + m_worldRotation.w = rotation.w; UpdatePackedRotation(); } -void GameObject::SetParentRotation(G3D::Quat const& rotation) +void GameObject::SetParentRotation(QuaternionData const& rotation) { SetFloatValue(GAMEOBJECT_PARENTROTATION + 0, rotation.x); SetFloatValue(GAMEOBJECT_PARENTROTATION + 1, rotation.y); @@ -1997,7 +2028,8 @@ void GameObject::SetParentRotation(G3D::Quat const& rotation) void GameObject::SetWorldRotationAngles(float z_rot, float y_rot, float x_rot) { - SetWorldRotation(G3D::Quat(G3D::Matrix3::fromEulerAnglesZYX(z_rot, y_rot, x_rot))); + G3D::Quat quat(G3D::Matrix3::fromEulerAnglesZYX(z_rot, y_rot, x_rot)); + SetWorldRotation(quat.x, quat.y, quat.z, quat.w); } void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= nullptr*/, uint32 spellId /*= 0*/) diff --git a/src/server/game/Entities/GameObject/GameObject.h b/src/server/game/Entities/GameObject/GameObject.h index 371728c7196..3080bd94860 100644 --- a/src/server/game/Entities/GameObject/GameObject.h +++ b/src/server/game/Entities/GameObject/GameObject.h @@ -19,569 +19,21 @@ #ifndef TRINITYCORE_GAMEOBJECT_H #define TRINITYCORE_GAMEOBJECT_H -#include "Common.h" -#include "SharedDefines.h" -#include "Unit.h" #include "Object.h" -#include "LootMgr.h" -#include "DatabaseEnv.h" -#include "WorldPacket.h" -#include +#include "DatabaseEnvFwd.h" +#include "GameObjectData.h" +#include "Loot.h" +#include "MapObject.h" +#include "SharedDefines.h" class GameObjectAI; +class GameObjectModel; class Group; -class Transport; - -#define MAX_GAMEOBJECT_QUEST_ITEMS 6 - -// from `gameobject_template` -struct GameObjectTemplate -{ - uint32 entry; - uint32 type; - uint32 displayId; - std::string name; - std::string IconName; - std::string castBarCaption; - std::string unk1; - float size; - union // different GO types have different data field - { - //0 GAMEOBJECT_TYPE_DOOR - struct - { - uint32 startOpen; //0 used client side to determine GO_ACTIVATED means open/closed - uint32 lockId; //1 -> Lock.dbc - uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 - uint32 noDamageImmune; //3 break opening whenever you recieve damage? - uint32 openTextID; //4 can be used to replace castBarCaption? - uint32 closeTextID; //5 - uint32 ignoredByPathing; //6 - uint32 conditionID1; //7 - } door; - //1 GAMEOBJECT_TYPE_BUTTON - struct - { - uint32 startOpen; //0 - uint32 lockId; //1 -> Lock.dbc - uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 - uint32 linkedTrap; //3 - uint32 noDamageImmune; //4 isBattlegroundObject - uint32 large; //5 - uint32 openTextID; //6 can be used to replace castBarCaption? - uint32 closeTextID; //7 - uint32 losOK; //8 - uint32 conditionID1; //9 - } button; - //2 GAMEOBJECT_TYPE_QUESTGIVER - struct - { - uint32 lockId; //0 -> Lock.dbc - uint32 questList; //1 - uint32 pageMaterial; //2 - uint32 gossipID; //3 - uint32 customAnim; //4 - uint32 noDamageImmune; //5 - uint32 openTextID; //6 can be used to replace castBarCaption? - uint32 losOK; //7 - uint32 allowMounted; //8 Is usable while on mount/vehicle. (0/1) - uint32 large; //9 - uint32 conditionID1; //10 - } questgiver; - //3 GAMEOBJECT_TYPE_CHEST - struct - { - uint32 lockId; //0 -> Lock.dbc - uint32 lootId; //1 - uint32 chestRestockTime; //2 - uint32 consumable; //3 - uint32 minSuccessOpens; //4 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use - uint32 maxSuccessOpens; //5 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use - uint32 eventId; //6 lootedEvent - uint32 linkedTrapId; //7 - uint32 questId; //8 not used currently but store quest required for GO activation for player - uint32 level; //9 - uint32 losOK; //10 - uint32 leaveLoot; //11 - uint32 notInCombat; //12 - uint32 logLoot; //13 - uint32 openTextID; //14 can be used to replace castBarCaption? - uint32 groupLootRules; //15 - uint32 floatingTooltip; //16 - uint32 conditionID1; //17 - } chest; - //4 GAMEOBJECT_TYPE_BINDER - empty - //5 GAMEOBJECT_TYPE_GENERIC - struct - { - uint32 floatingTooltip; //0 - uint32 highlight; //1 - uint32 serverOnly; //2 - uint32 large; //3 - uint32 floatOnWater; //4 - int32 questID; //5 - uint32 conditionID1; //6 - } _generic; - //6 GAMEOBJECT_TYPE_TRAP - struct - { - uint32 lockId; //0 -> Lock.dbc - uint32 level; //1 - uint32 diameter; //2 diameter for trap activation - uint32 spellId; //3 - uint32 type; //4 0 trap with no despawn after cast. 1 trap despawns after cast. 2 bomb casts on spawn. - uint32 cooldown; //5 time in secs - int32 autoCloseTime; //6 - uint32 startDelay; //7 - uint32 serverOnly; //8 - uint32 stealthed; //9 - uint32 large; //10 - uint32 invisible; //11 - uint32 openTextID; //12 can be used to replace castBarCaption? - uint32 closeTextID; //13 - uint32 ignoreTotems; //14 - uint32 conditionID1; //15 - } trap; - //7 GAMEOBJECT_TYPE_CHAIR - struct - { - uint32 slots; //0 - uint32 height; //1 - uint32 onlyCreatorUse; //2 - uint32 triggeredEvent; //3 - uint32 conditionID1; //4 - } chair; - //8 GAMEOBJECT_TYPE_SPELL_FOCUS - struct - { - uint32 focusId; //0 - uint32 dist; //1 - uint32 linkedTrapId; //2 - uint32 serverOnly; //3 - uint32 questID; //4 - uint32 large; //5 - uint32 floatingTooltip; //6 - uint32 floatOnWater; //7 - uint32 conditionID1; //8 - } spellFocus; - //9 GAMEOBJECT_TYPE_TEXT - struct - { - uint32 pageID; //0 - uint32 language; //1 - uint32 pageMaterial; //2 - uint32 allowMounted; //3 Is usable while on mount/vehicle. (0/1) - uint32 conditionID1; //4 - } text; - //10 GAMEOBJECT_TYPE_GOOBER - struct - { - uint32 lockId; //0 -> Lock.dbc - int32 questId; //1 - uint32 eventId; //2 - uint32 autoCloseTime; //3 - uint32 customAnim; //4 - uint32 consumable; //5 - uint32 cooldown; //6 - uint32 pageId; //7 - uint32 language; //8 - uint32 pageMaterial; //9 - uint32 spellId; //10 - uint32 noDamageImmune; //11 - uint32 linkedTrapId; //12 - uint32 large; //13 - uint32 openTextID; //14 can be used to replace castBarCaption? - uint32 closeTextID; //15 - uint32 losOK; //16 isBattlegroundObject - uint32 allowMounted; //17 Is usable while on mount/vehicle. (0/1) - uint32 floatingTooltip; //18 - uint32 gossipID; //19 - uint32 WorldStateSetsState; //20 - uint32 floatOnWater; //21 - uint32 conditionID1; //22 - } goober; - //11 GAMEOBJECT_TYPE_TRANSPORT - struct - { - uint32 pause; //0 - uint32 startOpen; //1 - uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 - uint32 pause1EventID; //3 - uint32 pause2EventID; //4 - uint32 mapID; //5 - } transport; - //12 GAMEOBJECT_TYPE_AREADAMAGE - struct - { - uint32 lockId; //0 - uint32 radius; //1 - uint32 damageMin; //2 - uint32 damageMax; //3 - uint32 damageSchool; //4 - uint32 autoCloseTime; //5 secs till autoclose = autoCloseTime / 0x10000 - uint32 openTextID; //6 - uint32 closeTextID; //7 - } areadamage; - //13 GAMEOBJECT_TYPE_CAMERA - struct - { - uint32 lockId; //0 -> Lock.dbc - uint32 cinematicId; //1 - uint32 eventID; //2 - uint32 openTextID; //3 can be used to replace castBarCaption? - uint32 conditionID1; //4 - } camera; - //14 GAMEOBJECT_TYPE_MAPOBJECT - empty - //15 GAMEOBJECT_TYPE_MO_TRANSPORT - struct - { - uint32 taxiPathId; //0 - uint32 moveSpeed; //1 - uint32 accelRate; //2 - uint32 startEventID; //3 - uint32 stopEventID; //4 - uint32 transportPhysics; //5 - uint32 mapID; //6 - uint32 worldState1; //7 - uint32 canBeStopped; //8 - } moTransport; - //16 GAMEOBJECT_TYPE_DUELFLAG - empty - //17 GAMEOBJECT_TYPE_FISHINGNODE - empty - //18 GAMEOBJECT_TYPE_SUMMONING_RITUAL - struct - { - uint32 reqParticipants; //0 - uint32 spellId; //1 - uint32 animSpell; //2 - uint32 ritualPersistent; //3 - uint32 casterTargetSpell; //4 - uint32 casterTargetSpellTargets; //5 - uint32 castersGrouped; //6 - uint32 ritualNoTargetCheck; //7 - uint32 conditionID1; //8 - } summoningRitual; - //19 GAMEOBJECT_TYPE_MAILBOX - struct - { - uint32 conditionID1; //0 - } mailbox; - //20 GAMEOBJECT_TYPE_DO_NOT_USE - empty - //21 GAMEOBJECT_TYPE_GUARDPOST - struct - { - uint32 creatureID; //0 - uint32 charges; //1 - } guardpost; - //22 GAMEOBJECT_TYPE_SPELLCASTER - struct - { - uint32 spellId; //0 - uint32 charges; //1 - uint32 partyOnly; //2 - uint32 allowMounted; //3 Is usable while on mount/vehicle. (0/1) - uint32 large; //4 - uint32 conditionID1; //5 - } spellcaster; - //23 GAMEOBJECT_TYPE_MEETINGSTONE - struct - { - uint32 minLevel; //0 - uint32 maxLevel; //1 - uint32 areaID; //2 - } meetingstone; - //24 GAMEOBJECT_TYPE_FLAGSTAND - struct - { - uint32 lockId; //0 - uint32 pickupSpell; //1 - uint32 radius; //2 - uint32 returnAura; //3 - uint32 returnSpell; //4 - uint32 noDamageImmune; //5 - uint32 openTextID; //6 - uint32 losOK; //7 - uint32 conditionID1; //8 - } flagstand; - //25 GAMEOBJECT_TYPE_FISHINGHOLE - struct - { - uint32 radius; //0 how close bobber must land for sending loot - uint32 lootId; //1 - uint32 minSuccessOpens; //2 - uint32 maxSuccessOpens; //3 - uint32 lockId; //4 -> Lock.dbc; possibly 1628 for all? - } fishinghole; - //26 GAMEOBJECT_TYPE_FLAGDROP - struct - { - uint32 lockId; //0 - uint32 eventID; //1 - uint32 pickupSpell; //2 - uint32 noDamageImmune; //3 - uint32 openTextID; //4 - } flagdrop; - //27 GAMEOBJECT_TYPE_MINI_GAME - struct - { - uint32 gameType; //0 - } miniGame; - //29 GAMEOBJECT_TYPE_CAPTURE_POINT - struct - { - uint32 radius; //0 - uint32 spell; //1 - uint32 worldState1; //2 - uint32 worldstate2; //3 - uint32 winEventID1; //4 - uint32 winEventID2; //5 - uint32 contestedEventID1; //6 - uint32 contestedEventID2; //7 - uint32 progressEventID1; //8 - uint32 progressEventID2; //9 - uint32 neutralEventID1; //10 - uint32 neutralEventID2; //11 - uint32 neutralPercent; //12 - uint32 worldstate3; //13 - uint32 minSuperiority; //14 - uint32 maxSuperiority; //15 - uint32 minTime; //16 - uint32 maxTime; //17 - uint32 large; //18 - uint32 highlight; //19 - uint32 startingValue; //20 - uint32 unidirectional; //21 - } capturePoint; - //30 GAMEOBJECT_TYPE_AURA_GENERATOR - struct - { - uint32 startOpen; //0 - uint32 radius; //1 - uint32 auraID1; //2 - uint32 conditionID1; //3 - uint32 auraID2; //4 - uint32 conditionID2; //5 - uint32 serverOnly; //6 - } auraGenerator; - //31 GAMEOBJECT_TYPE_DUNGEON_DIFFICULTY - struct - { - uint32 mapID; //0 - uint32 difficulty; //1 - } dungeonDifficulty; - //32 GAMEOBJECT_TYPE_BARBER_CHAIR - struct - { - uint32 chairheight; //0 - uint32 heightOffset; //1 - } barberChair; - //33 GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING - struct - { - uint32 intactNumHits; //0 - uint32 creditProxyCreature; //1 - uint32 empty1; //2 - uint32 intactEvent; //3 - uint32 empty2; //4 - uint32 damagedNumHits; //5 - uint32 empty3; //6 - uint32 empty4; //7 - uint32 empty5; //8 - uint32 damagedEvent; //9 - uint32 empty6; //10 - uint32 empty7; //11 - uint32 empty8; //12 - uint32 empty9; //13 - uint32 destroyedEvent; //14 - uint32 empty10; //15 - uint32 rebuildingTimeSecs; //16 - uint32 empty11; //17 - uint32 destructibleData; //18 - uint32 rebuildingEvent; //19 - uint32 empty12; //20 - uint32 empty13; //21 - uint32 damageEvent; //22 - uint32 empty14; //23 - } building; - //34 GAMEOBJECT_TYPE_GUILDBANK - struct - { - uint32 conditionID1; //0 - } guildbank; - //35 GAMEOBJECT_TYPE_TRAPDOOR - struct - { - uint32 whenToPause; // 0 - uint32 startOpen; // 1 - uint32 autoClose; // 2 - } trapDoor; - - // not use for specific field access (only for output with loop by all filed), also this determinate max union size - struct - { - uint32 data[MAX_GAMEOBJECT_DATA]; - } raw; - }; - - std::string AIName; - uint32 ScriptId; - WorldPacket QueryData[TOTAL_LOCALES]; - - // helpers - bool IsDespawnAtAction() const - { - switch (type) - { - case GAMEOBJECT_TYPE_CHEST: return chest.consumable != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.consumable != 0; - default: return false; - } - } - - bool IsUsableMounted() const - { - switch (type) - { - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.allowMounted != 0; - case GAMEOBJECT_TYPE_TEXT: return text.allowMounted != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.allowMounted != 0; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.allowMounted != 0; - default: return false; - } - } - - uint32 GetLockId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_DOOR: return door.lockId; - case GAMEOBJECT_TYPE_BUTTON: return button.lockId; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.lockId; - case GAMEOBJECT_TYPE_CHEST: return chest.lockId; - case GAMEOBJECT_TYPE_TRAP: return trap.lockId; - case GAMEOBJECT_TYPE_GOOBER: return goober.lockId; - case GAMEOBJECT_TYPE_AREADAMAGE: return areadamage.lockId; - case GAMEOBJECT_TYPE_CAMERA: return camera.lockId; - case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.lockId; - case GAMEOBJECT_TYPE_FISHINGHOLE:return fishinghole.lockId; - case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.lockId; - default: return 0; - } - } - - bool GetDespawnPossibility() const // despawn at targeting of cast? - { - switch (type) - { - case GAMEOBJECT_TYPE_DOOR: return door.noDamageImmune != 0; - case GAMEOBJECT_TYPE_BUTTON: return button.noDamageImmune != 0; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.noDamageImmune != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.noDamageImmune != 0; - case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.noDamageImmune != 0; - case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.noDamageImmune != 0; - default: return true; - } - } - - uint32 GetCharges() const // despawn at uses amount - { - switch (type) - { - //case GAMEOBJECT_TYPE_TRAP: return trap.charges; - case GAMEOBJECT_TYPE_GUARDPOST: return guardpost.charges; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.charges; - default: return 0; - } - } - - uint32 GetLinkedGameObjectEntry() const - { - switch (type) - { - case GAMEOBJECT_TYPE_BUTTON: return button.linkedTrap; - case GAMEOBJECT_TYPE_CHEST: return chest.linkedTrapId; - case GAMEOBJECT_TYPE_SPELL_FOCUS: return spellFocus.linkedTrapId; - case GAMEOBJECT_TYPE_GOOBER: return goober.linkedTrapId; - default: return 0; - } - } - - uint32 GetAutoCloseTime() const - { - uint32 autoCloseTime = 0; - switch (type) - { - case GAMEOBJECT_TYPE_DOOR: autoCloseTime = door.autoCloseTime; break; - case GAMEOBJECT_TYPE_BUTTON: autoCloseTime = button.autoCloseTime; break; - case GAMEOBJECT_TYPE_TRAP: autoCloseTime = trap.autoCloseTime; break; - case GAMEOBJECT_TYPE_GOOBER: autoCloseTime = goober.autoCloseTime; break; - case GAMEOBJECT_TYPE_TRANSPORT: autoCloseTime = transport.autoCloseTime; break; - case GAMEOBJECT_TYPE_AREADAMAGE: autoCloseTime = areadamage.autoCloseTime; break; - default: break; - } - return autoCloseTime; // prior to 3.0.3, conversion was / 0x10000; - } - - uint32 GetLootId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_CHEST: return chest.lootId; - case GAMEOBJECT_TYPE_FISHINGHOLE: return fishinghole.lootId; - default: return 0; - } - } - - uint32 GetGossipMenuId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.gossipID; - case GAMEOBJECT_TYPE_GOOBER: return goober.gossipID; - default: return 0; - } - } - - uint32 GetEventScriptId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_GOOBER: return goober.eventId; - case GAMEOBJECT_TYPE_CHEST: return chest.eventId; - case GAMEOBJECT_TYPE_CAMERA: return camera.eventID; - default: return 0; - } - } - - uint32 GetCooldown() const // Cooldown preventing goober and traps to cast spell - { - switch (type) - { - case GAMEOBJECT_TYPE_TRAP: return trap.cooldown; - case GAMEOBJECT_TYPE_GOOBER: return goober.cooldown; - default: return 0; - } - } - - void InitializeQueryData(); - WorldPacket BuildQueryData(LocaleConstant loc) const; -}; - -// From `gameobject_template_addon` -struct GameObjectTemplateAddon -{ - uint32 entry; - uint32 faction; - uint32 flags; - uint32 mingold; - uint32 maxgold; -}; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map GameObjectTemplateContainer; -typedef std::unordered_map GameObjectTemplateAddonContainer; - class OPvPCapturePoint; +class Transport; +class Unit; struct TransportAnimation; +enum TriggerCastFlags : uint32; union GameObjectValue { @@ -610,57 +62,6 @@ union GameObjectValue } Building; }; -struct GameObjectLocale -{ - StringVector Name; - StringVector CastBarCaption; -}; - -// `gameobject_addon` table -struct GameObjectAddon -{ - G3D::Quat ParentRotation; - InvisibilityType invisibilityType; - uint32 InvisibilityValue; -}; - -typedef std::unordered_map GameObjectAddonContainer; - -// client side GO show states -enum GOState -{ - GO_STATE_ACTIVE = 0, // show in world as used and not reset (closed door open) - GO_STATE_READY = 1, // show in world as ready (closed door close) - GO_STATE_ACTIVE_ALTERNATIVE = 2 // show in world as used in alt way and not reset (closed door open by cannon fire) -}; - -#define MAX_GO_STATE 3 - -// from `gameobject` -struct GameObjectData -{ - explicit GameObjectData() : id(0), mapid(0), phaseMask(0), posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), - animprogress(0), go_state(GO_STATE_ACTIVE), spawnMask(0), artKit(0), ScriptId(0), dbData(true) { } - uint32 id; // entry in gamobject_template - uint16 mapid; - uint32 phaseMask; - float posX; - float posY; - float posZ; - float orientation; - G3D::Quat rotation; - int32 spawntimesecs; - uint32 animprogress; - GOState go_state; - uint8 spawnMask; - uint8 artKit; - uint32 ScriptId; - bool dbData; -}; - -typedef std::vector GameObjectQuestItemList; -typedef std::unordered_map GameObjectQuestItemMap; - // For containers: [GO_NOT_READY]->GO_READY (close)->GO_ACTIVATED (open) ->GO_JUST_DEACTIVATED->GO_READY -> ... // For bobber: GO_NOT_READY ->GO_READY (close)->GO_ACTIVATED (open) ->GO_JUST_DEACTIVATED-> // For door(closed):[GO_NOT_READY]->GO_READY (close)->GO_ACTIVATED (open) ->GO_JUST_DEACTIVATED->GO_READY(close) -> ... @@ -673,9 +74,6 @@ enum LootState GO_JUST_DEACTIVATED }; -class Unit; -class GameObjectModel; - // 5 sec for bobber catch #define FISHING_BOBBER_READY_TIME 5 @@ -691,7 +89,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void RemoveFromWorld() override; void CleanupsBeforeDelete(bool finalCleanup = true) override; - bool Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, G3D::Quat const& rotation, uint32 animprogress, GOState go_state, uint32 artKit = 0); + bool Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, QuaternionData const& rotation, uint32 animprogress, GOState go_state, uint32 artKit = 0); void Update(uint32 p_time) override; GameObjectTemplate const* GetGOInfo() const { return m_goInfo; } GameObjectTemplateAddon const* GetTemplateAddon() const { return m_goTemplateAddon; } @@ -706,9 +104,8 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject // z_rot, y_rot, x_rot - rotation angles around z, y and x axes void SetWorldRotationAngles(float z_rot, float y_rot, float x_rot); - void SetWorldRotation(G3D::Quat const& rot); - G3D::Quat const& GetWorldRotation() const { return m_worldRotation; } - void SetParentRotation(G3D::Quat const& rotation); // transforms(rotates) transport's path + void SetWorldRotation(float qx, float qy, float qz, float qw); + void SetParentRotation(QuaternionData const& rotation); // transforms(rotates) transport's path int64 GetPackedWorldRotation() const { return m_packedRotation; } // overwrite WorldObject function for proper name localization @@ -743,7 +140,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject time_t GetRespawnTime() const { return m_respawnTime; } time_t GetRespawnTimeEx() const { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime > now) return m_respawnTime; else @@ -752,7 +149,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void SetRespawnTime(int32 respawn) { - m_respawnTime = respawn > 0 ? time(NULL) + respawn : 0; + m_respawnTime = respawn > 0 ? time(nullptr) + respawn : 0; m_respawnDelayTime = respawn > 0 ? respawn : 0; } void Respawn(); @@ -787,7 +184,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject LootState getLootState() const { return m_lootState; } // Note: unit is only used when s = GO_ACTIVATED - void SetLootState(LootState s, Unit* unit = NULL); + void SetLootState(LootState s, Unit* unit = nullptr); uint16 GetLootMode() const { return m_LootMode; } bool HasLootMode(uint16 lootMode) const { return (m_LootMode & lootMode) != 0; } @@ -833,7 +230,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject bool hasQuest(uint32 quest_id) const override; bool hasInvolvedQuest(uint32 quest_id) const override; bool ActivateToQuest(Player* target) const; - void UseDoorOrButton(uint32 time_to_restore = 0, bool alternative = false, Unit* user = NULL); + void UseDoorOrButton(uint32 time_to_restore = 0, bool alternative = false, Unit* user = nullptr); // 0 = use `gameobject`.`spawntimesecs` void ResetDoorOrButton(); @@ -844,13 +241,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject bool IsAlwaysVisibleFor(WorldObject const* seer) const override; bool IsInvisibleDueToDespawn() const override; - uint8 getLevelForTarget(WorldObject const* target) const override - { - if (Unit* owner = GetOwner()) - return owner->getLevelForTarget(target); - - return 1; - } + uint8 getLevelForTarget(WorldObject const* target) const override; GameObject* LookupFishingHoleAround(float range); @@ -859,9 +250,9 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void SendCustomAnim(uint32 anim); bool IsInRange(float x, float y, float z, float radius) const; - void ModifyHealth(int32 change, Unit* attackerOrHealer = NULL, uint32 spellId = 0); + void ModifyHealth(int32 change, Unit* attackerOrHealer = nullptr, uint32 spellId = 0); // sets GameObject type 33 destruction flags and optionally default health for that state - void SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker = NULL, bool setHealth = false); + void SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker = nullptr, bool setHealth = false); GameObjectDestructibleState GetDestructibleState() const { if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED)) @@ -871,7 +262,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject return GO_DESTRUCTIBLE_INTACT; } - void EventInform(uint32 eventId, WorldObject* invoker = NULL); + void EventInform(uint32 eventId, WorldObject* invoker = nullptr); uint32 GetScriptId() const; GameObjectAI* AI() const { return m_AI; } @@ -884,10 +275,10 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void SetFaction(uint32 faction) { SetUInt32Value(GAMEOBJECT_FACTION, faction); } GameObjectModel* m_model; - void GetRespawnPosition(float &x, float &y, float &z, float* ori = NULL) const; + void GetRespawnPosition(float &x, float &y, float &z, float* ori = nullptr) const; - Transport* ToTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return NULL; } - Transport const* ToTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return NULL; } + Transport* ToTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + Transport const* ToTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } float GetStationaryX() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionX(); return GetPositionX(); } float GetStationaryY() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionY(); return GetPositionY(); } @@ -931,7 +322,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject GameObjectValue m_goValue; int64 m_packedRotation; - G3D::Quat m_worldRotation; + QuaternionData m_worldRotation; Position m_stationaryPosition; ObjectGuid m_lootRecipient; diff --git a/src/server/game/Entities/GameObject/GameObjectData.h b/src/server/game/Entities/GameObject/GameObjectData.h new file mode 100644 index 00000000000..e2d2f27e5b5 --- /dev/null +++ b/src/server/game/Entities/GameObject/GameObjectData.h @@ -0,0 +1,618 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef GameObjectData_h__ +#define GameObjectData_h__ + +#include "Common.h" +#include "SharedDefines.h" +#include "WorldPacket.h" +#include +#include + +#define MAX_GAMEOBJECT_QUEST_ITEMS 6 + +// from `gameobject_template` +struct GameObjectTemplate +{ + uint32 entry; + uint32 type; + uint32 displayId; + std::string name; + std::string IconName; + std::string castBarCaption; + std::string unk1; + float size; + union // different GO types have different data field + { + //0 GAMEOBJECT_TYPE_DOOR + struct + { + uint32 startOpen; //0 used client side to determine GO_ACTIVATED means open/closed + uint32 lockId; //1 -> Lock.dbc + uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 + uint32 noDamageImmune; //3 break opening whenever you recieve damage? + uint32 openTextID; //4 can be used to replace castBarCaption? + uint32 closeTextID; //5 + uint32 ignoredByPathing; //6 + uint32 conditionID1; //7 + } door; + //1 GAMEOBJECT_TYPE_BUTTON + struct + { + uint32 startOpen; //0 + uint32 lockId; //1 -> Lock.dbc + uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 + uint32 linkedTrap; //3 + uint32 noDamageImmune; //4 isBattlegroundObject + uint32 large; //5 + uint32 openTextID; //6 can be used to replace castBarCaption? + uint32 closeTextID; //7 + uint32 losOK; //8 + uint32 conditionID1; //9 + } button; + //2 GAMEOBJECT_TYPE_QUESTGIVER + struct + { + uint32 lockId; //0 -> Lock.dbc + uint32 questList; //1 + uint32 pageMaterial; //2 + uint32 gossipID; //3 + uint32 customAnim; //4 + uint32 noDamageImmune; //5 + uint32 openTextID; //6 can be used to replace castBarCaption? + uint32 losOK; //7 + uint32 allowMounted; //8 Is usable while on mount/vehicle. (0/1) + uint32 large; //9 + uint32 conditionID1; //10 + } questgiver; + //3 GAMEOBJECT_TYPE_CHEST + struct + { + uint32 lockId; //0 -> Lock.dbc + uint32 lootId; //1 + uint32 chestRestockTime; //2 + uint32 consumable; //3 + uint32 minSuccessOpens; //4 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use + uint32 maxSuccessOpens; //5 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use + uint32 eventId; //6 lootedEvent + uint32 linkedTrapId; //7 + uint32 questId; //8 not used currently but store quest required for GO activation for player + uint32 level; //9 + uint32 losOK; //10 + uint32 leaveLoot; //11 + uint32 notInCombat; //12 + uint32 logLoot; //13 + uint32 openTextID; //14 can be used to replace castBarCaption? + uint32 groupLootRules; //15 + uint32 floatingTooltip; //16 + uint32 conditionID1; //17 + } chest; + //4 GAMEOBJECT_TYPE_BINDER - empty + //5 GAMEOBJECT_TYPE_GENERIC + struct + { + uint32 floatingTooltip; //0 + uint32 highlight; //1 + uint32 serverOnly; //2 + uint32 large; //3 + uint32 floatOnWater; //4 + int32 questID; //5 + uint32 conditionID1; //6 + } _generic; + //6 GAMEOBJECT_TYPE_TRAP + struct + { + uint32 lockId; //0 -> Lock.dbc + uint32 level; //1 + uint32 diameter; //2 diameter for trap activation + uint32 spellId; //3 + uint32 type; //4 0 trap with no despawn after cast. 1 trap despawns after cast. 2 bomb casts on spawn. + uint32 cooldown; //5 time in secs + int32 autoCloseTime; //6 + uint32 startDelay; //7 + uint32 serverOnly; //8 + uint32 stealthed; //9 + uint32 large; //10 + uint32 invisible; //11 + uint32 openTextID; //12 can be used to replace castBarCaption? + uint32 closeTextID; //13 + uint32 ignoreTotems; //14 + uint32 conditionID1; //15 + } trap; + //7 GAMEOBJECT_TYPE_CHAIR + struct + { + uint32 slots; //0 + uint32 height; //1 + uint32 onlyCreatorUse; //2 + uint32 triggeredEvent; //3 + uint32 conditionID1; //4 + } chair; + //8 GAMEOBJECT_TYPE_SPELL_FOCUS + struct + { + uint32 focusId; //0 + uint32 dist; //1 + uint32 linkedTrapId; //2 + uint32 serverOnly; //3 + uint32 questID; //4 + uint32 large; //5 + uint32 floatingTooltip; //6 + uint32 floatOnWater; //7 + uint32 conditionID1; //8 + } spellFocus; + //9 GAMEOBJECT_TYPE_TEXT + struct + { + uint32 pageID; //0 + uint32 language; //1 + uint32 pageMaterial; //2 + uint32 allowMounted; //3 Is usable while on mount/vehicle. (0/1) + uint32 conditionID1; //4 + } text; + //10 GAMEOBJECT_TYPE_GOOBER + struct + { + uint32 lockId; //0 -> Lock.dbc + int32 questId; //1 + uint32 eventId; //2 + uint32 autoCloseTime; //3 + uint32 customAnim; //4 + uint32 consumable; //5 + uint32 cooldown; //6 + uint32 pageId; //7 + uint32 language; //8 + uint32 pageMaterial; //9 + uint32 spellId; //10 + uint32 noDamageImmune; //11 + uint32 linkedTrapId; //12 + uint32 large; //13 + uint32 openTextID; //14 can be used to replace castBarCaption? + uint32 closeTextID; //15 + uint32 losOK; //16 isBattlegroundObject + uint32 allowMounted; //17 Is usable while on mount/vehicle. (0/1) + uint32 floatingTooltip; //18 + uint32 gossipID; //19 + uint32 WorldStateSetsState; //20 + uint32 floatOnWater; //21 + uint32 conditionID1; //22 + } goober; + //11 GAMEOBJECT_TYPE_TRANSPORT + struct + { + uint32 pause; //0 + uint32 startOpen; //1 + uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 + uint32 pause1EventID; //3 + uint32 pause2EventID; //4 + uint32 mapID; //5 + } transport; + //12 GAMEOBJECT_TYPE_AREADAMAGE + struct + { + uint32 lockId; //0 + uint32 radius; //1 + uint32 damageMin; //2 + uint32 damageMax; //3 + uint32 damageSchool; //4 + uint32 autoCloseTime; //5 secs till autoclose = autoCloseTime / 0x10000 + uint32 openTextID; //6 + uint32 closeTextID; //7 + } areadamage; + //13 GAMEOBJECT_TYPE_CAMERA + struct + { + uint32 lockId; //0 -> Lock.dbc + uint32 cinematicId; //1 + uint32 eventID; //2 + uint32 openTextID; //3 can be used to replace castBarCaption? + uint32 conditionID1; //4 + } camera; + //14 GAMEOBJECT_TYPE_MAPOBJECT - empty + //15 GAMEOBJECT_TYPE_MO_TRANSPORT + struct + { + uint32 taxiPathId; //0 + uint32 moveSpeed; //1 + uint32 accelRate; //2 + uint32 startEventID; //3 + uint32 stopEventID; //4 + uint32 transportPhysics; //5 + uint32 mapID; //6 + uint32 worldState1; //7 + uint32 canBeStopped; //8 + } moTransport; + //16 GAMEOBJECT_TYPE_DUELFLAG - empty + //17 GAMEOBJECT_TYPE_FISHINGNODE - empty + //18 GAMEOBJECT_TYPE_SUMMONING_RITUAL + struct + { + uint32 reqParticipants; //0 + uint32 spellId; //1 + uint32 animSpell; //2 + uint32 ritualPersistent; //3 + uint32 casterTargetSpell; //4 + uint32 casterTargetSpellTargets; //5 + uint32 castersGrouped; //6 + uint32 ritualNoTargetCheck; //7 + uint32 conditionID1; //8 + } summoningRitual; + //19 GAMEOBJECT_TYPE_MAILBOX + struct + { + uint32 conditionID1; //0 + } mailbox; + //20 GAMEOBJECT_TYPE_DO_NOT_USE - empty + //21 GAMEOBJECT_TYPE_GUARDPOST + struct + { + uint32 creatureID; //0 + uint32 charges; //1 + } guardpost; + //22 GAMEOBJECT_TYPE_SPELLCASTER + struct + { + uint32 spellId; //0 + uint32 charges; //1 + uint32 partyOnly; //2 + uint32 allowMounted; //3 Is usable while on mount/vehicle. (0/1) + uint32 large; //4 + uint32 conditionID1; //5 + } spellcaster; + //23 GAMEOBJECT_TYPE_MEETINGSTONE + struct + { + uint32 minLevel; //0 + uint32 maxLevel; //1 + uint32 areaID; //2 + } meetingstone; + //24 GAMEOBJECT_TYPE_FLAGSTAND + struct + { + uint32 lockId; //0 + uint32 pickupSpell; //1 + uint32 radius; //2 + uint32 returnAura; //3 + uint32 returnSpell; //4 + uint32 noDamageImmune; //5 + uint32 openTextID; //6 + uint32 losOK; //7 + uint32 conditionID1; //8 + } flagstand; + //25 GAMEOBJECT_TYPE_FISHINGHOLE + struct + { + uint32 radius; //0 how close bobber must land for sending loot + uint32 lootId; //1 + uint32 minSuccessOpens; //2 + uint32 maxSuccessOpens; //3 + uint32 lockId; //4 -> Lock.dbc; possibly 1628 for all? + } fishinghole; + //26 GAMEOBJECT_TYPE_FLAGDROP + struct + { + uint32 lockId; //0 + uint32 eventID; //1 + uint32 pickupSpell; //2 + uint32 noDamageImmune; //3 + uint32 openTextID; //4 + } flagdrop; + //27 GAMEOBJECT_TYPE_MINI_GAME + struct + { + uint32 gameType; //0 + } miniGame; + //29 GAMEOBJECT_TYPE_CAPTURE_POINT + struct + { + uint32 radius; //0 + uint32 spell; //1 + uint32 worldState1; //2 + uint32 worldstate2; //3 + uint32 winEventID1; //4 + uint32 winEventID2; //5 + uint32 contestedEventID1; //6 + uint32 contestedEventID2; //7 + uint32 progressEventID1; //8 + uint32 progressEventID2; //9 + uint32 neutralEventID1; //10 + uint32 neutralEventID2; //11 + uint32 neutralPercent; //12 + uint32 worldstate3; //13 + uint32 minSuperiority; //14 + uint32 maxSuperiority; //15 + uint32 minTime; //16 + uint32 maxTime; //17 + uint32 large; //18 + uint32 highlight; //19 + uint32 startingValue; //20 + uint32 unidirectional; //21 + } capturePoint; + //30 GAMEOBJECT_TYPE_AURA_GENERATOR + struct + { + uint32 startOpen; //0 + uint32 radius; //1 + uint32 auraID1; //2 + uint32 conditionID1; //3 + uint32 auraID2; //4 + uint32 conditionID2; //5 + uint32 serverOnly; //6 + } auraGenerator; + //31 GAMEOBJECT_TYPE_DUNGEON_DIFFICULTY + struct + { + uint32 mapID; //0 + uint32 difficulty; //1 + } dungeonDifficulty; + //32 GAMEOBJECT_TYPE_BARBER_CHAIR + struct + { + uint32 chairheight; //0 + uint32 heightOffset; //1 + } barberChair; + //33 GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING + struct + { + uint32 intactNumHits; //0 + uint32 creditProxyCreature; //1 + uint32 empty1; //2 + uint32 intactEvent; //3 + uint32 empty2; //4 + uint32 damagedNumHits; //5 + uint32 empty3; //6 + uint32 empty4; //7 + uint32 empty5; //8 + uint32 damagedEvent; //9 + uint32 empty6; //10 + uint32 empty7; //11 + uint32 empty8; //12 + uint32 empty9; //13 + uint32 destroyedEvent; //14 + uint32 empty10; //15 + uint32 rebuildingTimeSecs; //16 + uint32 empty11; //17 + uint32 destructibleData; //18 + uint32 rebuildingEvent; //19 + uint32 empty12; //20 + uint32 empty13; //21 + uint32 damageEvent; //22 + uint32 empty14; //23 + } building; + //34 GAMEOBJECT_TYPE_GUILDBANK + struct + { + uint32 conditionID1; //0 + } guildbank; + //35 GAMEOBJECT_TYPE_TRAPDOOR + struct + { + uint32 whenToPause; // 0 + uint32 startOpen; // 1 + uint32 autoClose; // 2 + } trapDoor; + + // not use for specific field access (only for output with loop by all filed), also this determinate max union size + struct + { + uint32 data[MAX_GAMEOBJECT_DATA]; + } raw; + }; + + std::string AIName; + uint32 ScriptId; + WorldPacket QueryData[TOTAL_LOCALES]; + + // helpers + bool IsDespawnAtAction() const + { + switch (type) + { + case GAMEOBJECT_TYPE_CHEST: return chest.consumable != 0; + case GAMEOBJECT_TYPE_GOOBER: return goober.consumable != 0; + default: return false; + } + } + + bool IsUsableMounted() const + { + switch (type) + { + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.allowMounted != 0; + case GAMEOBJECT_TYPE_TEXT: return text.allowMounted != 0; + case GAMEOBJECT_TYPE_GOOBER: return goober.allowMounted != 0; + case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.allowMounted != 0; + default: return false; + } + } + + uint32 GetLockId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_DOOR: return door.lockId; + case GAMEOBJECT_TYPE_BUTTON: return button.lockId; + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.lockId; + case GAMEOBJECT_TYPE_CHEST: return chest.lockId; + case GAMEOBJECT_TYPE_TRAP: return trap.lockId; + case GAMEOBJECT_TYPE_GOOBER: return goober.lockId; + case GAMEOBJECT_TYPE_AREADAMAGE: return areadamage.lockId; + case GAMEOBJECT_TYPE_CAMERA: return camera.lockId; + case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.lockId; + case GAMEOBJECT_TYPE_FISHINGHOLE:return fishinghole.lockId; + case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.lockId; + default: return 0; + } + } + + bool GetDespawnPossibility() const // despawn at targeting of cast? + { + switch (type) + { + case GAMEOBJECT_TYPE_DOOR: return door.noDamageImmune != 0; + case GAMEOBJECT_TYPE_BUTTON: return button.noDamageImmune != 0; + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.noDamageImmune != 0; + case GAMEOBJECT_TYPE_GOOBER: return goober.noDamageImmune != 0; + case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.noDamageImmune != 0; + case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.noDamageImmune != 0; + default: return true; + } + } + + uint32 GetCharges() const // despawn at uses amount + { + switch (type) + { + //case GAMEOBJECT_TYPE_TRAP: return trap.charges; + case GAMEOBJECT_TYPE_GUARDPOST: return guardpost.charges; + case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.charges; + default: return 0; + } + } + + uint32 GetLinkedGameObjectEntry() const + { + switch (type) + { + case GAMEOBJECT_TYPE_BUTTON: return button.linkedTrap; + case GAMEOBJECT_TYPE_CHEST: return chest.linkedTrapId; + case GAMEOBJECT_TYPE_SPELL_FOCUS: return spellFocus.linkedTrapId; + case GAMEOBJECT_TYPE_GOOBER: return goober.linkedTrapId; + default: return 0; + } + } + + uint32 GetAutoCloseTime() const + { + uint32 autoCloseTime = 0; + switch (type) + { + case GAMEOBJECT_TYPE_DOOR: autoCloseTime = door.autoCloseTime; break; + case GAMEOBJECT_TYPE_BUTTON: autoCloseTime = button.autoCloseTime; break; + case GAMEOBJECT_TYPE_TRAP: autoCloseTime = trap.autoCloseTime; break; + case GAMEOBJECT_TYPE_GOOBER: autoCloseTime = goober.autoCloseTime; break; + case GAMEOBJECT_TYPE_TRANSPORT: autoCloseTime = transport.autoCloseTime; break; + case GAMEOBJECT_TYPE_AREADAMAGE: autoCloseTime = areadamage.autoCloseTime; break; + default: break; + } + return autoCloseTime; // prior to 3.0.3, conversion was / 0x10000; + } + + uint32 GetLootId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_CHEST: return chest.lootId; + case GAMEOBJECT_TYPE_FISHINGHOLE: return fishinghole.lootId; + default: return 0; + } + } + + uint32 GetGossipMenuId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.gossipID; + case GAMEOBJECT_TYPE_GOOBER: return goober.gossipID; + default: return 0; + } + } + + uint32 GetEventScriptId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_GOOBER: return goober.eventId; + case GAMEOBJECT_TYPE_CHEST: return chest.eventId; + case GAMEOBJECT_TYPE_CAMERA: return camera.eventID; + default: return 0; + } + } + + uint32 GetCooldown() const // Cooldown preventing goober and traps to cast spell + { + switch (type) + { + case GAMEOBJECT_TYPE_TRAP: return trap.cooldown; + case GAMEOBJECT_TYPE_GOOBER: return goober.cooldown; + default: return 0; + } + } + + void InitializeQueryData(); + WorldPacket BuildQueryData(LocaleConstant loc) const; +}; + +// From `gameobject_template_addon` +struct GameObjectTemplateAddon +{ + uint32 entry; + uint32 faction; + uint32 flags; + uint32 mingold; + uint32 maxgold; +}; + +struct GameObjectLocale +{ + std::vector Name; + std::vector CastBarCaption; +}; + +struct TC_GAME_API QuaternionData +{ + float x, y, z, w; + + QuaternionData() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) { } + QuaternionData(float X, float Y, float Z, float W) : x(X), y(Y), z(Z), w(W) { } + + bool isUnit() const; + static QuaternionData fromEulerAnglesZYX(float Z, float Y, float X); +}; + +// `gameobject_addon` table +struct GameObjectAddon +{ + QuaternionData ParentRotation; + InvisibilityType invisibilityType; + uint32 InvisibilityValue; +}; + +// from `gameobject` +struct GameObjectData +{ + explicit GameObjectData() : id(0), mapid(0), phaseMask(0), posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), + animprogress(0), go_state(GO_STATE_ACTIVE), spawnMask(0), artKit(0), ScriptId(0), dbData(true) { } + uint32 id; // entry in gamobject_template + uint16 mapid; + uint32 phaseMask; + float posX; + float posY; + float posZ; + float orientation; + QuaternionData rotation; + int32 spawntimesecs; + uint32 animprogress; + GOState go_state; + uint8 spawnMask; + uint8 artKit; + uint32 ScriptId; + bool dbData; +}; + +#endif // GameObjectData_h__ diff --git a/src/server/game/Entities/Item/Container/Bag.cpp b/src/server/game/Entities/Item/Container/Bag.cpp index 523b2e440a7..847142f2ad4 100644 --- a/src/server/game/Entities/Item/Container/Bag.cpp +++ b/src/server/game/Entities/Item/Container/Bag.cpp @@ -98,7 +98,7 @@ bool Bag::Create(ObjectGuid::LowType guidlow, uint32 itemid, Player const* owner for (uint8 i = 0; i < MAX_BAG_SIZE; ++i) { SetGuidValue(CONTAINER_FIELD_SLOT_1 + (i*2), ObjectGuid::Empty); - m_bagslot[i] = NULL; + m_bagslot[i] = nullptr; } return true; @@ -121,7 +121,7 @@ bool Bag::LoadFromDB(ObjectGuid::LowType guid, ObjectGuid owner_guid, Field* fie { SetGuidValue(CONTAINER_FIELD_SLOT_1 + (i * 2), ObjectGuid::Empty); delete m_bagslot[i]; - m_bagslot[i] = NULL; + m_bagslot[i] = nullptr; } return true; @@ -151,9 +151,9 @@ void Bag::RemoveItem(uint8 slot, bool /*update*/) ASSERT(slot < MAX_BAG_SIZE); if (m_bagslot[slot]) - m_bagslot[slot]->SetContainer(NULL); + m_bagslot[slot]->SetContainer(nullptr); - m_bagslot[slot] = NULL; + m_bagslot[slot] = nullptr; SetGuidValue(CONTAINER_FIELD_SLOT_1 + (slot * 2), ObjectGuid::Empty); } @@ -161,7 +161,7 @@ void Bag::StoreItem(uint8 slot, Item* pItem, bool /*update*/) { ASSERT(slot < MAX_BAG_SIZE); - if (pItem && pItem->GetGUID() != this->GetGUID()) + if (pItem && pItem->GetGUID() != GetGUID()) { m_bagslot[slot] = pItem; SetGuidValue(CONTAINER_FIELD_SLOT_1 + (slot * 2), pItem->GetGUID()); @@ -243,6 +243,6 @@ Item* Bag::GetItemByPos(uint8 slot) const if (slot < GetBagSize()) return m_bagslot[slot]; - return NULL; + return nullptr; } diff --git a/src/server/game/Entities/Item/Container/Bag.h b/src/server/game/Entities/Item/Container/Bag.h index 7f5e5aff2d3..e39a7ed6b66 100644 --- a/src/server/game/Entities/Item/Container/Bag.h +++ b/src/server/game/Entities/Item/Container/Bag.h @@ -23,7 +23,6 @@ #define MAX_BAG_SIZE 36 // 2.0.12 #include "Item.h" -#include "ItemTemplate.h" class TC_GAME_API Bag : public Item { @@ -42,8 +41,8 @@ class TC_GAME_API Bag : public Item void RemoveItem(uint8 slot, bool update); Item* GetItemByPos(uint8 slot) const; - uint32 GetItemCount(uint32 item, Item* eItem = NULL) const; - uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = NULL) const; + uint32 GetItemCount(uint32 item, Item* eItem = nullptr) const; + uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; uint8 GetSlotByItemGUID(ObjectGuid guid) const; bool IsEmpty() const; diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index 6ea1665ce35..7556c7d007c 100644 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -16,20 +16,26 @@ * with this program. If not, see . */ -#include "Common.h" #include "Item.h" -#include "ObjectMgr.h" -#include "WorldPacket.h" +#include "Bag.h" +#include "Common.h" +#include "ConditionMgr.h" #include "DatabaseEnv.h" +#include "DBCStores.h" #include "ItemEnchantmentMgr.h" +#include "Log.h" #include "LootItemStorage.h" -#include "SpellMgr.h" -#include "SpellInfo.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ConditionMgr.h" +#include "SpellInfo.h" +#include "SpellMgr.h" #include "Player.h" -#include "WorldSession.h" #include "TradeData.h" +#include "UpdateData.h" +#include "WorldPacket.h" +#include "WorldSession.h" void AddItemsSetItem(Player* player, Item* item) { @@ -47,7 +53,7 @@ void AddItemsSetItem(Player* player, Item* item) if (set->required_skill_id && player->GetSkillValue(set->required_skill_id) < set->required_skill_value) return; - ItemSetEffect* eff = NULL; + ItemSetEffect* eff = nullptr; for (size_t x = 0; x < player->ItemSetEff.size(); ++x) { @@ -105,7 +111,7 @@ void AddItemsSetItem(Player* player, Item* item) } // spell cast only if fit form requirement, in other case will cast at form change - player->ApplyEquipSpell(spellInfo, NULL, true); + player->ApplyEquipSpell(spellInfo, nullptr, true); eff->spells[y] = spellInfo; break; } @@ -125,7 +131,7 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) return; } - ItemSetEffect* eff = NULL; + ItemSetEffect* eff = nullptr; size_t setindex = 0; for (; setindex < player->ItemSetEff.size(); setindex++) { @@ -156,8 +162,8 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) if (eff->spells[z] && eff->spells[z]->Id == set->spells[x]) { // spell can be not active if not fit form requirement - player->ApplyEquipSpell(eff->spells[z], NULL, false); - eff->spells[z]=NULL; + player->ApplyEquipSpell(eff->spells[z], nullptr, false); + eff->spells[z]=nullptr; break; } } @@ -167,7 +173,7 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) { ASSERT(eff == player->ItemSetEff[setindex]); delete eff; - player->ItemSetEff[setindex] = NULL; + player->ItemSetEff[setindex] = nullptr; } } @@ -247,10 +253,10 @@ Item::Item() m_slot = 0; uState = ITEM_NEW; uQueuePos = -1; - m_container = NULL; + m_container = nullptr; m_lootGenerated = false; mb_in_trade = false; - m_lastPlayedTimeUpdate = time(NULL); + m_lastPlayedTimeUpdate = time(nullptr); m_refundRecipient = 0; m_paidMoney = 0; @@ -569,52 +575,6 @@ uint32 Item::GetSpell() return 0; } -int32 Item::GenerateItemRandomPropertyId(uint32 item_id) -{ - ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id); - - if (!itemProto) - return 0; - - // item must have one from this field values not null if it can have random enchantments - if ((!itemProto->RandomProperty) && (!itemProto->RandomSuffix)) - return 0; - - // item can have not null only one from field values - if ((itemProto->RandomProperty) && (itemProto->RandomSuffix)) - { - TC_LOG_ERROR("sql.sql", "Item template %u have RandomProperty == %u and RandomSuffix == %u, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix); - return 0; - } - - // RandomProperty case - if (itemProto->RandomProperty) - { - uint32 randomPropId = GetItemEnchantMod(itemProto->RandomProperty); - ItemRandomPropertiesEntry const* random_id = sItemRandomPropertiesStore.LookupEntry(randomPropId); - if (!random_id) - { - TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId); - return 0; - } - - return random_id->ID; - } - // RandomSuffix case - else - { - uint32 randomPropId = GetItemEnchantMod(itemProto->RandomSuffix); - ItemRandomSuffixEntry const* random_id = sItemRandomSuffixStore.LookupEntry(randomPropId); - if (!random_id) - { - TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in sItemRandomSuffixStore.", randomPropId); - return 0; - } - - return -int32(random_id->ID); - } -} - void Item::SetItemRandomProperties(int32 randomPropId) { if (!randomPropId) @@ -668,7 +628,7 @@ void Item::SetState(ItemUpdateState state, Player* forplayer) // pretend the item never existed if (forplayer) { - RemoveFromUpdateQueueOf(forplayer); + RemoveItemFromUpdateQueueOf(this, forplayer); forplayer->DeleteRefundReference(GetGUID()); } delete this; @@ -681,7 +641,7 @@ void Item::SetState(ItemUpdateState state, Player* forplayer) uState = state; if (forplayer) - AddToUpdateQueueOf(forplayer); + AddItemToUpdateQueueOf(this, forplayer); } else { @@ -692,46 +652,46 @@ void Item::SetState(ItemUpdateState state, Player* forplayer) } } -void Item::AddToUpdateQueueOf(Player* player) +void AddItemToUpdateQueueOf(Item* item, Player* player) { - if (IsInUpdateQueue()) + if (item->IsInUpdateQueue()) return; - ASSERT(player != NULL); + ASSERT(player != nullptr); - if (player->GetGUID() != GetOwnerGUID()) + if (player->GetGUID() != item->GetOwnerGUID()) { - TC_LOG_DEBUG("entities.player.items", "Item::AddToUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", - GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("entities.player.items", "AddItemToUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", + item->GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); return; } if (player->m_itemUpdateQueueBlocked) return; - player->m_itemUpdateQueue.push_back(this); - uQueuePos = player->m_itemUpdateQueue.size()-1; + player->m_itemUpdateQueue.push_back(item); + item->uQueuePos = player->m_itemUpdateQueue.size() - 1; } -void Item::RemoveFromUpdateQueueOf(Player* player) +void RemoveItemFromUpdateQueueOf(Item* item, Player* player) { - if (!IsInUpdateQueue()) + if (!item->IsInUpdateQueue()) return; - ASSERT(player != NULL); + ASSERT(player != nullptr); - if (player->GetGUID() != GetOwnerGUID()) + if (player->GetGUID() != item->GetOwnerGUID()) { - TC_LOG_DEBUG("entities.player.items", "Item::RemoveFromUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", - GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("entities.player.items", "RemoveItemFromUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", + item->GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); return; } if (player->m_itemUpdateQueueBlocked) return; - player->m_itemUpdateQueue[uQueuePos] = NULL; - uQueuePos = -1; + player->m_itemUpdateQueue[item->uQueuePos] = nullptr; + item->uQueuePos = -1; } uint8 Item::GetBagSlot() const @@ -752,7 +712,7 @@ bool Item::CanBeTraded(bool mail, bool trade) const if ((!mail || !IsBoundAccountWide()) && (IsSoulBound() && (!HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE) || !trade))) return false; - if (IsBag() && (Player::IsBagPos(GetPos()) || !((Bag const*)this)->IsEmpty())) + if (IsBag() && (Player::IsBagPos(GetPos()) || !ToBag()->IsEmpty())) return false; if (Player* owner = GetOwner()) @@ -769,7 +729,7 @@ bool Item::CanBeTraded(bool mail, bool trade) const return true; } -bool Item::HasEnchantRequiredSkill(const Player* player) const +bool Item::HasEnchantRequiredSkill(Player const* player) const { // Check all enchants for required skill for (uint32 enchant_slot = PERM_ENCHANTMENT_SLOT; enchant_slot < MAX_ENCHANTMENT_SLOT; ++enchant_slot) @@ -1002,7 +962,7 @@ void Item::SendUpdateSockets() for (uint32 i = SOCK_ENCHANTMENT_SLOT; i <= BONUS_ENCHANTMENT_SLOT; ++i) data << uint32(GetEnchantmentId(EnchantmentSlot(i))); - GetOwner()->GetSession()->SendPacket(&data); + GetOwner()->SendDirectMessage(&data); } // Though the client has the information in the item's data field, @@ -1017,7 +977,7 @@ void Item::SendTimeUpdate(Player* owner) WorldPacket data(SMSG_ITEM_TIME_UPDATE, (8+4)); data << uint64(GetGUID()); data << uint32(duration); - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); } Item* Item::CreateItem(uint32 itemEntry, uint32 count, Player const* player /*= nullptr*/) @@ -1074,7 +1034,7 @@ bool Item::IsBindedNotWith(Player const* player) const return false; if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE)) - if (allowedGUIDs.find(player->GetGUID().GetCounter()) != allowedGUIDs.end()) + if (allowedGUIDs.find(player->GetGUID()) != allowedGUIDs.end()) return false; // BOA item case @@ -1132,7 +1092,7 @@ void Item::DeleteRefundDataFromDB(SQLTransaction* trans) } } -void Item::SetNotRefundable(Player* owner, bool changestate /*=true*/, SQLTransaction* trans /*=NULL*/) +void Item::SetNotRefundable(Player* owner, bool changestate /*=true*/, SQLTransaction* trans /*=nullptr*/) { if (!HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE)) return; @@ -1159,7 +1119,7 @@ void Item::UpdatePlayedTime(Player* owner) // Get current played time uint32 current_playtime = GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME); // Calculate time elapsed since last played time update - time_t curtime = time(NULL); + time_t curtime = time(nullptr); uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); uint32 new_playtime = current_playtime + elapsed; // Check if the refund timer has expired yet @@ -1180,7 +1140,7 @@ void Item::UpdatePlayedTime(Player* owner) uint32 Item::GetPlayedTime() { - time_t curtime = time(NULL); + time_t curtime = time(nullptr); uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); return GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + elapsed; } @@ -1190,7 +1150,7 @@ bool Item::IsRefundExpired() return (GetPlayedTime() > 2*HOUR); } -void Item::SetSoulboundTradeable(AllowedLooterSet const& allowedLooters) +void Item::SetSoulboundTradeable(GuidSet const& allowedLooters) { SetFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE); allowedGUIDs = allowedLooters; diff --git a/src/server/game/Entities/Item/Item.h b/src/server/game/Entities/Item/Item.h index 421d13b9aa1..a34ff9124ff 100644 --- a/src/server/game/Entities/Item/Item.h +++ b/src/server/game/Entities/Item/Item.h @@ -19,11 +19,13 @@ #ifndef TRINITYCORE_ITEM_H #define TRINITYCORE_ITEM_H -#include "Common.h" #include "Object.h" -#include "LootMgr.h" +#include "Common.h" +#include "DatabaseEnvFwd.h" +#include "ItemDefines.h" +#include "ItemEnchantmentMgr.h" #include "ItemTemplate.h" -#include "DatabaseEnv.h" +#include "Loot.h" class SpellInfo; class Bag; @@ -36,144 +38,6 @@ struct ItemSetEffect SpellInfo const* spells[8]; }; -enum InventoryResult -{ - EQUIP_ERR_OK = 0, - EQUIP_ERR_CANT_EQUIP_LEVEL_I = 1, - EQUIP_ERR_CANT_EQUIP_SKILL = 2, - EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT = 3, - EQUIP_ERR_BAG_FULL = 4, - EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG = 5, - EQUIP_ERR_CANT_TRADE_EQUIP_BAGS = 6, - EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE = 7, - EQUIP_ERR_NO_REQUIRED_PROFICIENCY = 8, - EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE = 9, - EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM = 10, - EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM2 = 11, - EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE2 = 12, - EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED = 13, - EQUIP_ERR_CANT_DUAL_WIELD = 14, - EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG = 15, - EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2 = 16, - EQUIP_ERR_CANT_CARRY_MORE_OF_THIS = 17, - EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE3 = 18, - EQUIP_ERR_ITEM_CANT_STACK = 19, - EQUIP_ERR_ITEM_CANT_BE_EQUIPPED = 20, - EQUIP_ERR_ITEMS_CANT_BE_SWAPPED = 21, - EQUIP_ERR_SLOT_IS_EMPTY = 22, - EQUIP_ERR_ITEM_NOT_FOUND = 23, - EQUIP_ERR_CANT_DROP_SOULBOUND = 24, - EQUIP_ERR_OUT_OF_RANGE = 25, - EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT = 26, - EQUIP_ERR_COULDNT_SPLIT_ITEMS = 27, - EQUIP_ERR_MISSING_REAGENT = 28, - EQUIP_ERR_NOT_ENOUGH_MONEY = 29, - EQUIP_ERR_NOT_A_BAG = 30, - EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS = 31, - EQUIP_ERR_DONT_OWN_THAT_ITEM = 32, - EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER = 33, - EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT = 34, - EQUIP_ERR_TOO_FAR_AWAY_FROM_BANK = 35, - EQUIP_ERR_ITEM_LOCKED = 36, - EQUIP_ERR_YOU_ARE_STUNNED = 37, - EQUIP_ERR_YOU_ARE_DEAD = 38, - EQUIP_ERR_CANT_DO_RIGHT_NOW = 39, - EQUIP_ERR_INT_BAG_ERROR = 40, - EQUIP_ERR_CAN_EQUIP_ONLY1_BOLT = 41, - EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH = 42, - EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED = 43, - EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED = 44, - EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED = 45, - EQUIP_ERR_BOUND_CANT_BE_WRAPPED = 46, - EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED = 47, - EQUIP_ERR_BAGS_CANT_BE_WRAPPED = 48, - EQUIP_ERR_ALREADY_LOOTED = 49, - EQUIP_ERR_INVENTORY_FULL = 50, - EQUIP_ERR_BANK_FULL = 51, - EQUIP_ERR_ITEM_IS_CURRENTLY_SOLD_OUT = 52, - EQUIP_ERR_BAG_FULL3 = 53, - EQUIP_ERR_ITEM_NOT_FOUND2 = 54, - EQUIP_ERR_ITEM_CANT_STACK2 = 55, - EQUIP_ERR_BAG_FULL4 = 56, - EQUIP_ERR_ITEM_SOLD_OUT = 57, - EQUIP_ERR_OBJECT_IS_BUSY = 58, - EQUIP_ERR_NONE = 59, - EQUIP_ERR_NOT_IN_COMBAT = 60, - EQUIP_ERR_NOT_WHILE_DISARMED = 61, - EQUIP_ERR_BAG_FULL6 = 62, - EQUIP_ERR_CANT_EQUIP_RANK = 63, - EQUIP_ERR_CANT_EQUIP_REPUTATION = 64, - EQUIP_ERR_TOO_MANY_SPECIAL_BAGS = 65, - EQUIP_ERR_LOOT_CANT_LOOT_THAT_NOW = 66, - EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE = 67, - EQUIP_ERR_VENDOR_MISSING_TURNINS = 68, - EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS = 69, - EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS = 70, - EQUIP_ERR_ITEM_MAX_COUNT_SOCKETED = 71, - EQUIP_ERR_MAIL_BOUND_ITEM = 72, - EQUIP_ERR_NO_SPLIT_WHILE_PROSPECTING = 73, - EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED = 75, - EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED = 76, - EQUIP_ERR_TOO_MUCH_GOLD = 77, - EQUIP_ERR_NOT_DURING_ARENA_MATCH = 78, - EQUIP_ERR_CANNOT_TRADE_THAT = 79, - EQUIP_ERR_PERSONAL_ARENA_RATING_TOO_LOW = 80, - EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM = 81, - EQUIP_ERR_ARTEFACTS_ONLY_FOR_OWN_CHARACTERS = 82, - // no output = 83, - EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED = 84, - EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED = 85, - EQUIP_ERR_SCALING_STAT_ITEM_LEVEL_EXCEEDED = 86, - EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW = 87, - EQUIP_ERR_CANT_EQUIP_NEED_TALENT = 88, - EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED = 89 -}; - -enum BuyResult -{ - BUY_ERR_CANT_FIND_ITEM = 0, - BUY_ERR_ITEM_ALREADY_SOLD = 1, - BUY_ERR_NOT_ENOUGHT_MONEY = 2, - BUY_ERR_SELLER_DONT_LIKE_YOU = 4, - BUY_ERR_DISTANCE_TOO_FAR = 5, - BUY_ERR_ITEM_SOLD_OUT = 7, - BUY_ERR_CANT_CARRY_MORE = 8, - BUY_ERR_RANK_REQUIRE = 11, - BUY_ERR_REPUTATION_REQUIRE = 12 -}; - -enum SellResult -{ - SELL_ERR_CANT_FIND_ITEM = 1, - SELL_ERR_CANT_SELL_ITEM = 2, // merchant doesn't like that item - SELL_ERR_CANT_FIND_VENDOR = 3, // merchant doesn't like you - SELL_ERR_YOU_DONT_OWN_THAT_ITEM = 4, // you don't own that item - SELL_ERR_UNK = 5, // nothing appears... - SELL_ERR_ONLY_EMPTY_BAG = 6 // can only do with empty bags -}; - -// -1 from client enchantment slot number -enum EnchantmentSlot -{ - PERM_ENCHANTMENT_SLOT = 0, - TEMP_ENCHANTMENT_SLOT = 1, - SOCK_ENCHANTMENT_SLOT = 2, - SOCK_ENCHANTMENT_SLOT_2 = 3, - SOCK_ENCHANTMENT_SLOT_3 = 4, - BONUS_ENCHANTMENT_SLOT = 5, - PRISMATIC_ENCHANTMENT_SLOT = 6, // added at apply special permanent enchantment - MAX_INSPECTED_ENCHANTMENT_SLOT = 7, - - PROP_ENCHANTMENT_SLOT_0 = 7, // used with RandomSuffix - PROP_ENCHANTMENT_SLOT_1 = 8, // used with RandomSuffix - PROP_ENCHANTMENT_SLOT_2 = 9, // used with RandomSuffix and RandomProperty - PROP_ENCHANTMENT_SLOT_3 = 10, // used with RandomProperty - PROP_ENCHANTMENT_SLOT_4 = 11, // used with RandomProperty - MAX_ENCHANTMENT_SLOT = 12 -}; - -#define MAX_VISIBLE_ITEM_OFFSET 2 // 2 fields per visible item (entry+enchantment) - #define MAX_GEM_SOCKETS MAX_ITEM_PROTO_SOCKETS// (BONUS_ENCHANTMENT_SLOT-SOCK_ENCHANTMENT_SLOT) and item proto size, equal value expected enum EnchantmentOffset @@ -185,14 +49,6 @@ enum EnchantmentOffset #define MAX_ENCHANTMENT_OFFSET 3 -enum EnchantmentSlotMask -{ - ENCHANTMENT_CAN_SOULBOUND = 0x01, - ENCHANTMENT_UNK1 = 0x02, - ENCHANTMENT_UNK2 = 0x04, - ENCHANTMENT_UNK3 = 0x08 -}; - enum ItemUpdateState { ITEM_UNCHANGED = 0, @@ -205,6 +61,9 @@ bool ItemCanGoIntoBag(ItemTemplate const* proto, ItemTemplate const* pBagProto); class TC_GAME_API Item : public Object { + friend void AddItemToUpdateQueueOf(Item* item, Player* player); + friend void RemoveItemFromUpdateQueueOf(Item* item, Player* player); + public: static Item* CreateItem(uint32 itemEntry, uint32 count, Player const* player = nullptr); Item* CloneItem(uint32 count, Player const* player = nullptr) const; @@ -234,8 +93,8 @@ class TC_GAME_API Item : public Object void SaveRefundDataToDB(); void DeleteRefundDataFromDB(SQLTransaction* trans); - Bag* ToBag() { if (IsBag()) return reinterpret_cast(this); else return NULL; } - const Bag* ToBag() const { if (IsBag()) return reinterpret_cast(this); else return NULL; } + Bag* ToBag() { if (IsBag()) return reinterpret_cast(this); else return nullptr; } + Bag const* ToBag() const { if (IsBag()) return reinterpret_cast(this); else return nullptr; } bool IsLocked() const { return !HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_UNLOCKED); } bool IsBag() const { return GetTemplate()->InventoryType == INVTYPE_BAG; } @@ -246,7 +105,7 @@ class TC_GAME_API Item : public Object void SetInTrade(bool b = true) { mb_in_trade = b; } bool IsInTrade() const { return mb_in_trade; } - bool HasEnchantRequiredSkill(const Player* player) const; + bool HasEnchantRequiredSkill(Player const* player) const; uint32 GetEnchantRequiredLevel() const; bool IsFitToSpellRequirements(SpellInfo const* spellInfo) const; @@ -267,7 +126,7 @@ class TC_GAME_API Item : public Object uint16 GetPos() const { return uint16(GetBagSlot()) << 8 | GetSlot(); } void SetContainer(Bag* container) { m_container = container; } - bool IsInBag() const { return m_container != NULL; } + bool IsInBag() const { return m_container != nullptr; } bool IsEquipped() const; uint32 GetSkill(); @@ -278,7 +137,6 @@ class TC_GAME_API Item : public Object uint32 GetItemSuffixFactor() const { return GetUInt32Value(ITEM_FIELD_PROPERTY_SEED); } void SetItemRandomProperties(int32 randomPropId); void UpdateItemSuffixFactor(); - static int32 GenerateItemRandomPropertyId(uint32 item_id); void SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint32 charges, ObjectGuid caster = ObjectGuid::Empty); void SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* owner); void SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges); @@ -304,9 +162,7 @@ class TC_GAME_API Item : public Object // Update States ItemUpdateState GetState() const { return uState; } - void SetState(ItemUpdateState state, Player* forplayer = NULL); - void AddToUpdateQueueOf(Player* player); - void RemoveFromUpdateQueueOf(Player* player); + void SetState(ItemUpdateState state, Player* forplayer = nullptr); bool IsInUpdateQueue() const { return uQueuePos != -1; } uint16 GetQueuePos() const { return uQueuePos; } void FSetState(ItemUpdateState state) // forced @@ -322,7 +178,7 @@ class TC_GAME_API Item : public Object bool IsConjuredConsumable() const { return GetTemplate()->IsConjuredConsumable(); } // Item Refund system - void SetNotRefundable(Player* owner, bool changestate = true, SQLTransaction* trans = NULL); + void SetNotRefundable(Player* owner, bool changestate = true, SQLTransaction* trans = nullptr); void SetRefundRecipient(ObjectGuid::LowType pGuidLow) { m_refundRecipient = pGuidLow; } void SetPaidMoney(uint32 money) { m_paidMoney = money; } void SetPaidExtendedCost(uint32 iece) { m_paidExtendedCost = iece; } @@ -336,7 +192,7 @@ class TC_GAME_API Item : public Object bool IsRefundExpired(); // Soulbound trade system - void SetSoulboundTradeable(AllowedLooterSet const& allowedLooters); + void SetSoulboundTradeable(GuidSet const& allowedLooters); void ClearSoulboundTradeable(Player* currentOwner); bool CheckSoulboundTradeExpire(); @@ -357,6 +213,6 @@ class TC_GAME_API Item : public Object ObjectGuid::LowType m_refundRecipient; uint32 m_paidMoney; uint32 m_paidExtendedCost; - AllowedLooterSet allowedGUIDs; + GuidSet allowedGUIDs; }; #endif diff --git a/src/server/game/Entities/Item/ItemDefines.h b/src/server/game/Entities/Item/ItemDefines.h new file mode 100644 index 00000000000..a4e59526a91 --- /dev/null +++ b/src/server/game/Entities/Item/ItemDefines.h @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef ItemDefines_h__ +#define ItemDefines_h__ + +#include "Define.h" + +enum InventoryResult : uint8 +{ + EQUIP_ERR_OK = 0, + EQUIP_ERR_CANT_EQUIP_LEVEL_I = 1, + EQUIP_ERR_CANT_EQUIP_SKILL = 2, + EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT = 3, + EQUIP_ERR_BAG_FULL = 4, + EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG = 5, + EQUIP_ERR_CANT_TRADE_EQUIP_BAGS = 6, + EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE = 7, + EQUIP_ERR_NO_REQUIRED_PROFICIENCY = 8, + EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE = 9, + EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM = 10, + EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM2 = 11, + EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE2 = 12, + EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED = 13, + EQUIP_ERR_CANT_DUAL_WIELD = 14, + EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG = 15, + EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2 = 16, + EQUIP_ERR_CANT_CARRY_MORE_OF_THIS = 17, + EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE3 = 18, + EQUIP_ERR_ITEM_CANT_STACK = 19, + EQUIP_ERR_ITEM_CANT_BE_EQUIPPED = 20, + EQUIP_ERR_ITEMS_CANT_BE_SWAPPED = 21, + EQUIP_ERR_SLOT_IS_EMPTY = 22, + EQUIP_ERR_ITEM_NOT_FOUND = 23, + EQUIP_ERR_CANT_DROP_SOULBOUND = 24, + EQUIP_ERR_OUT_OF_RANGE = 25, + EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT = 26, + EQUIP_ERR_COULDNT_SPLIT_ITEMS = 27, + EQUIP_ERR_MISSING_REAGENT = 28, + EQUIP_ERR_NOT_ENOUGH_MONEY = 29, + EQUIP_ERR_NOT_A_BAG = 30, + EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS = 31, + EQUIP_ERR_DONT_OWN_THAT_ITEM = 32, + EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER = 33, + EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT = 34, + EQUIP_ERR_TOO_FAR_AWAY_FROM_BANK = 35, + EQUIP_ERR_ITEM_LOCKED = 36, + EQUIP_ERR_YOU_ARE_STUNNED = 37, + EQUIP_ERR_YOU_ARE_DEAD = 38, + EQUIP_ERR_CANT_DO_RIGHT_NOW = 39, + EQUIP_ERR_INT_BAG_ERROR = 40, + EQUIP_ERR_CAN_EQUIP_ONLY1_BOLT = 41, + EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH = 42, + EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED = 43, + EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED = 44, + EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED = 45, + EQUIP_ERR_BOUND_CANT_BE_WRAPPED = 46, + EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED = 47, + EQUIP_ERR_BAGS_CANT_BE_WRAPPED = 48, + EQUIP_ERR_ALREADY_LOOTED = 49, + EQUIP_ERR_INVENTORY_FULL = 50, + EQUIP_ERR_BANK_FULL = 51, + EQUIP_ERR_ITEM_IS_CURRENTLY_SOLD_OUT = 52, + EQUIP_ERR_BAG_FULL3 = 53, + EQUIP_ERR_ITEM_NOT_FOUND2 = 54, + EQUIP_ERR_ITEM_CANT_STACK2 = 55, + EQUIP_ERR_BAG_FULL4 = 56, + EQUIP_ERR_ITEM_SOLD_OUT = 57, + EQUIP_ERR_OBJECT_IS_BUSY = 58, + EQUIP_ERR_NONE = 59, + EQUIP_ERR_NOT_IN_COMBAT = 60, + EQUIP_ERR_NOT_WHILE_DISARMED = 61, + EQUIP_ERR_BAG_FULL6 = 62, + EQUIP_ERR_CANT_EQUIP_RANK = 63, + EQUIP_ERR_CANT_EQUIP_REPUTATION = 64, + EQUIP_ERR_TOO_MANY_SPECIAL_BAGS = 65, + EQUIP_ERR_LOOT_CANT_LOOT_THAT_NOW = 66, + EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE = 67, + EQUIP_ERR_VENDOR_MISSING_TURNINS = 68, + EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS = 69, + EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS = 70, + EQUIP_ERR_ITEM_MAX_COUNT_SOCKETED = 71, + EQUIP_ERR_MAIL_BOUND_ITEM = 72, + EQUIP_ERR_NO_SPLIT_WHILE_PROSPECTING = 73, + EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED = 75, + EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED = 76, + EQUIP_ERR_TOO_MUCH_GOLD = 77, + EQUIP_ERR_NOT_DURING_ARENA_MATCH = 78, + EQUIP_ERR_CANNOT_TRADE_THAT = 79, + EQUIP_ERR_PERSONAL_ARENA_RATING_TOO_LOW = 80, + EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM = 81, + EQUIP_ERR_ARTEFACTS_ONLY_FOR_OWN_CHARACTERS = 82, + // no output = 83, + EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED = 84, + EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED = 85, + EQUIP_ERR_SCALING_STAT_ITEM_LEVEL_EXCEEDED = 86, + EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW = 87, + EQUIP_ERR_CANT_EQUIP_NEED_TALENT = 88, + EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED = 89 +}; + +enum BuyResult +{ + BUY_ERR_CANT_FIND_ITEM = 0, + BUY_ERR_ITEM_ALREADY_SOLD = 1, + BUY_ERR_NOT_ENOUGHT_MONEY = 2, + BUY_ERR_SELLER_DONT_LIKE_YOU = 4, + BUY_ERR_DISTANCE_TOO_FAR = 5, + BUY_ERR_ITEM_SOLD_OUT = 7, + BUY_ERR_CANT_CARRY_MORE = 8, + BUY_ERR_RANK_REQUIRE = 11, + BUY_ERR_REPUTATION_REQUIRE = 12 +}; + +enum SellResult +{ + SELL_ERR_CANT_FIND_ITEM = 1, + SELL_ERR_CANT_SELL_ITEM = 2, // merchant doesn't like that item + SELL_ERR_CANT_FIND_VENDOR = 3, // merchant doesn't like you + SELL_ERR_YOU_DONT_OWN_THAT_ITEM = 4, // you don't own that item + SELL_ERR_UNK = 5, // nothing appears... + SELL_ERR_ONLY_EMPTY_BAG = 6 // can only do with empty bags +}; + +// -1 from client enchantment slot number +enum EnchantmentSlot : uint16 +{ + PERM_ENCHANTMENT_SLOT = 0, + TEMP_ENCHANTMENT_SLOT = 1, + SOCK_ENCHANTMENT_SLOT = 2, + SOCK_ENCHANTMENT_SLOT_2 = 3, + SOCK_ENCHANTMENT_SLOT_3 = 4, + BONUS_ENCHANTMENT_SLOT = 5, + PRISMATIC_ENCHANTMENT_SLOT = 6, // added at apply special permanent enchantment + MAX_INSPECTED_ENCHANTMENT_SLOT = 7, + + PROP_ENCHANTMENT_SLOT_0 = 7, // used with RandomSuffix + PROP_ENCHANTMENT_SLOT_1 = 8, // used with RandomSuffix + PROP_ENCHANTMENT_SLOT_2 = 9, // used with RandomSuffix and RandomProperty + PROP_ENCHANTMENT_SLOT_3 = 10, // used with RandomProperty + PROP_ENCHANTMENT_SLOT_4 = 11, // used with RandomProperty + MAX_ENCHANTMENT_SLOT = 12 +}; + +#define MAX_VISIBLE_ITEM_OFFSET 2 // 2 fields per visible item (entry+enchantment) + +#endif // ItemDefines_h__ diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp index f316ee84e83..50e0805797c 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp @@ -22,6 +22,8 @@ #include "ObjectMgr.h" #include "Util.h" #include "DBCStores.h" +#include "Random.h" +#include "Timer.h" #include #include @@ -118,6 +120,52 @@ uint32 GetItemEnchantMod(int32 entry) return 0; } +int32 GenerateItemRandomPropertyId(uint32 item_id) +{ + ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id); + + if (!itemProto) + return 0; + + // item must have one from this field values not null if it can have random enchantments + if ((!itemProto->RandomProperty) && (!itemProto->RandomSuffix)) + return 0; + + // item can have not null only one from field values + if ((itemProto->RandomProperty) && (itemProto->RandomSuffix)) + { + TC_LOG_ERROR("sql.sql", "Item template %u have RandomProperty == %u and RandomSuffix == %u, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix); + return 0; + } + + // RandomProperty case + if (itemProto->RandomProperty) + { + uint32 randomPropId = GetItemEnchantMod(itemProto->RandomProperty); + ItemRandomPropertiesEntry const* random_id = sItemRandomPropertiesStore.LookupEntry(randomPropId); + if (!random_id) + { + TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId); + return 0; + } + + return random_id->ID; + } + // RandomSuffix case + else + { + uint32 randomPropId = GetItemEnchantMod(itemProto->RandomSuffix); + ItemRandomSuffixEntry const* random_id = sItemRandomSuffixStore.LookupEntry(randomPropId); + if (!random_id) + { + TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in sItemRandomSuffixStore.", randomPropId); + return 0; + } + + return -int32(random_id->ID); + } +} + uint32 GenerateEnchSuffixFactor(uint32 item_id) { ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id); diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.h b/src/server/game/Entities/Item/ItemEnchantmentMgr.h index a9d8cf52f91..9692a491c89 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.h +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.h @@ -22,6 +22,7 @@ #include "Common.h" TC_GAME_API void LoadRandomEnchantmentsTable(); +TC_GAME_API int32 GenerateItemRandomPropertyId(uint32 item_id); TC_GAME_API uint32 GetItemEnchantMod(int32 entry); TC_GAME_API uint32 GenerateEnchSuffixFactor(uint32 item_id); diff --git a/src/server/game/Entities/Item/ItemTemplate.h b/src/server/game/Entities/Item/ItemTemplate.h index 5ea34aedb01..0f43a6bb8c2 100644 --- a/src/server/game/Entities/Item/ItemTemplate.h +++ b/src/server/game/Entities/Item/ItemTemplate.h @@ -22,6 +22,7 @@ #include "Common.h" #include "SharedDefines.h" #include "WorldPacket.h" +#include class ObjectMgr; @@ -256,7 +257,7 @@ enum SocketColor #define SOCKET_COLOR_ALL (SOCKET_COLOR_META | SOCKET_COLOR_RED | SOCKET_COLOR_YELLOW | SOCKET_COLOR_BLUE) -enum InventoryType +enum InventoryType : uint8 { INVTYPE_NON_EQUIP = 0, INVTYPE_HEAD = 1, @@ -291,7 +292,7 @@ enum InventoryType #define MAX_INVTYPE 29 -enum ItemClass +enum ItemClass : uint8 { ITEM_CLASS_CONSUMABLE = 0, ITEM_CLASS_CONTAINER = 1, @@ -723,13 +724,10 @@ private: void _LoadTotalAP(); }; -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map ItemTemplateContainer; - struct ItemLocale { - StringVector Name; - StringVector Description; + std::vector Name; + std::vector Description; }; struct ItemSetNameEntry @@ -740,7 +738,7 @@ struct ItemSetNameEntry struct ItemSetNameLocale { - StringVector Name; + std::vector Name; }; #endif diff --git a/src/server/game/Entities/Object/MovementInfo.h b/src/server/game/Entities/Object/MovementInfo.h new file mode 100644 index 00000000000..f8262f44d51 --- /dev/null +++ b/src/server/game/Entities/Object/MovementInfo.h @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef MovementInfo_h__ +#define MovementInfo_h__ + +#include "ObjectGuid.h" +#include "Position.h" + +struct MovementInfo +{ + // common + ObjectGuid guid; + uint32 flags; + uint16 flags2; + Position pos; + uint32 time; + + // transport + struct TransportInfo + { + void Reset() + { + guid.Clear(); + pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + seat = -1; + time = 0; + time2 = 0; + } + + ObjectGuid guid; + Position pos; + int8 seat; + uint32 time; + uint32 time2; + } transport; + + // swimming/flying + float pitch; + + // falling + uint32 fallTime; + + // jumping + struct JumpInfo + { + void Reset() + { + zspeed = sinAngle = cosAngle = xyspeed = 0.0f; + } + + float zspeed, sinAngle, cosAngle, xyspeed; + + } jump; + + // spline + float splineElevation; + + MovementInfo() : + guid(), flags(0), flags2(0), time(0), pitch(0.0f), fallTime(0), splineElevation(0.0f) + { + pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + transport.Reset(); + jump.Reset(); + } + + uint32 GetMovementFlags() const { return flags; } + void SetMovementFlags(uint32 flag) { flags = flag; } + void AddMovementFlag(uint32 flag) { flags |= flag; } + void RemoveMovementFlag(uint32 flag) { flags &= ~flag; } + bool HasMovementFlag(uint32 flag) const { return (flags & flag) != 0; } + + uint16 GetExtraMovementFlags() const { return flags2; } + void AddExtraMovementFlag(uint16 flag) { flags2 |= flag; } + bool HasExtraMovementFlag(uint16 flag) const { return (flags2 & flag) != 0; } + + void SetFallTime(uint32 val) { fallTime = val; } + + void OutDebug(); +}; + +#endif // MovementInfo_h__ diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index 6f3a96102cd..ba48a64d719 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -17,33 +17,32 @@ */ #include "Object.h" +#include "BattlefieldMgr.h" +#include "Battleground.h" +#include "CellImpl.h" +#include "CinematicMgr.h" #include "Common.h" -#include "SharedDefines.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "World.h" #include "Creature.h" -#include "Player.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "UpdateData.h" -#include "UpdateMask.h" -#include "Util.h" -#include "ObjectAccessor.h" -#include "Transport.h" -#include "VMapFactory.h" -#include "CellImpl.h" -#include "GridNotifiers.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" -#include "UpdateFieldFlags.h" +#include "Item.h" +#include "Log.h" +#include "Map.h" +#include "MovementInfo.h" +#include "MovementPacketBuilder.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "OutdoorPvPMgr.h" +#include "Player.h" #include "TemporarySummon.h" #include "Totem.h" -#include "OutdoorPvPMgr.h" -#include "MovementPacketBuilder.h" -#include "BattlefieldMgr.h" -#include "Battleground.h" -#include "GameTime.h" +#include "Transport.h" +#include "Unit.h" +#include "UpdateFieldFlags.h" +#include "Vehicle.h" +#include "VMapFactory.h" +#include "World.h" +#include Object::Object() : m_PackGUID(sizeof(uint64)+1) { @@ -51,7 +50,7 @@ Object::Object() : m_PackGUID(sizeof(uint64)+1) m_objectType = TYPEMASK_OBJECT; m_updateFlag = UPDATEFLAG_NONE; - m_uint32Values = NULL; + m_uint32Values = nullptr; m_valuesCount = 0; _fieldNotifyFlags = UF_FLAG_DYNAMIC; @@ -227,7 +226,7 @@ void Object::SendUpdateToPlayer(Player* player) else BuildCreateUpdateBlockForPlayer(&upd, player); upd.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Object::BuildValuesUpdateBlockForPlayer(UpdateData* data, Player* target) const @@ -259,7 +258,7 @@ void Object::DestroyForPlayer(Player* target, bool onDeath) const { WorldPacket data(SMSG_ARENA_UNIT_DESTROYED, 8); data << uint64(GetGUID()); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); } } } @@ -269,7 +268,7 @@ void Object::DestroyForPlayer(Player* target, bool onDeath) const //! If the following bool is true, the client will call "void CGUnit_C::OnDeath()" for this object. //! OnDeath() does for eg trigger death animation and interrupts certain spells/missiles/auras/sounds... data << uint8(onDeath ? 1 : 0); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); } int32 Object::GetInt32Value(uint16 index) const @@ -318,8 +317,8 @@ ObjectGuid Object::GetGuidValue(uint16 index) const void Object::BuildMovementUpdate(ByteBuffer* data, uint16 flags) const { - Unit const* unit = NULL; - WorldObject const* object = NULL; + Unit const* unit = nullptr; + WorldObject const* object = nullptr; if (isType(TYPEMASK_UNIT)) unit = ToUnit(); @@ -493,7 +492,7 @@ void Object::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* targe UpdateMask updateMask; updateMask.SetCount(m_valuesCount); - uint32* flags = NULL; + uint32* flags = nullptr; uint32 visibleFlag = GetUpdateFieldData(target, flags); ASSERT(flags); @@ -974,7 +973,7 @@ void MovementInfo::OutDebug() TC_LOG_DEBUG("misc", "%s", guid.ToString().c_str()); TC_LOG_DEBUG("misc", "flags %u", flags); TC_LOG_DEBUG("misc", "flags2 %u", flags2); - TC_LOG_DEBUG("misc", "time %u current time " UI64FMTD "", flags2, uint64(::time(NULL))); + TC_LOG_DEBUG("misc", "time %u current time " UI64FMTD "", flags2, uint64(::time(nullptr))); TC_LOG_DEBUG("misc", "position: `%s`", pos.ToString().c_str()); if (flags & MOVEMENTFLAG_ONTRANSPORT) { @@ -999,8 +998,8 @@ void MovementInfo::OutDebug() } WorldObject::WorldObject(bool isWorldObject) : WorldLocation(), LastUsedScriptID(0), -m_name(""), m_isActive(false), m_isWorldObject(isWorldObject), m_zoneScript(NULL), -m_transport(NULL), m_zoneId(0), m_areaId(0), m_staticFloorZ(VMAP_INVALID_HEIGHT), m_currMap(NULL), m_InstanceId(0), +m_name(""), m_isActive(false), m_isWorldObject(isWorldObject), m_zoneScript(nullptr), +m_transport(nullptr), m_zoneId(0), m_areaId(0), m_staticFloorZ(VMAP_INVALID_HEIGHT), m_currMap(nullptr), m_InstanceId(0), m_phaseMask(PHASEMASK_NORMAL), m_notifyflags(0), m_executed_notifies(0) { m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE | GHOST_VISIBILITY_GHOST); @@ -1046,14 +1045,14 @@ void WorldObject::setActive(bool on) if (on) { if (GetTypeId() == TYPEID_UNIT) - map->AddToActive(this->ToCreature()); + map->AddToActive(ToCreature()); else if (GetTypeId() == TYPEID_DYNAMICOBJECT) map->AddToActive((DynamicObject*)this); } else { if (GetTypeId() == TYPEID_UNIT) - map->RemoveFromActive(this->ToCreature()); + map->RemoveFromActive(ToCreature()); else if (GetTypeId() == TYPEID_DYNAMICOBJECT) map->RemoveFromActive((DynamicObject*)this); } @@ -1109,10 +1108,10 @@ void WorldObject::RemoveFromWorld() InstanceScript* WorldObject::GetInstanceScript() { Map* map = GetMap(); - return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceScript() : NULL; + return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceScript() : nullptr; } -float WorldObject::GetDistanceZ(const WorldObject* obj) const +float WorldObject::GetDistanceZ(WorldObject const* obj) const { float dz = std::fabs(GetPositionZ() - obj->GetPositionZ()); float sizefactor = GetCombatReach() + obj->GetCombatReach(); @@ -1142,13 +1141,13 @@ bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool return thisOrTransport->IsInDist2d(objOrObjTransport, maxdist); } -float WorldObject::GetDistance(const WorldObject* obj) const +float WorldObject::GetDistance(WorldObject const* obj) const { float d = GetExactDist(obj) - GetCombatReach() - obj->GetCombatReach(); return d > 0.0f ? d : 0.0f; } -float WorldObject::GetDistance(const Position &pos) const +float WorldObject::GetDistance(Position const& pos) const { float d = GetExactDist(&pos) - GetCombatReach(); return d > 0.0f ? d : 0.0f; @@ -1160,7 +1159,7 @@ float WorldObject::GetDistance(float x, float y, float z) const return d > 0.0f ? d : 0.0f; } -float WorldObject::GetDistance2d(const WorldObject* obj) const +float WorldObject::GetDistance2d(WorldObject const* obj) const { float d = GetExactDist2d(obj) - GetCombatReach() - obj->GetCombatReach(); return d > 0.0f ? d : 0.0f; @@ -1172,14 +1171,14 @@ float WorldObject::GetDistance2d(float x, float y) const return d > 0.0f ? d : 0.0f; } -bool WorldObject::IsSelfOrInSameMap(const WorldObject* obj) const +bool WorldObject::IsSelfOrInSameMap(WorldObject const* obj) const { if (this == obj) return true; return IsInMap(obj); } -bool WorldObject::IsInMap(const WorldObject* obj) const +bool WorldObject::IsInMap(WorldObject const* obj) const { if (obj) return IsInWorld() && obj->IsInWorld() && (GetMap() == obj->GetMap()); @@ -1191,7 +1190,7 @@ bool WorldObject::IsWithinDist3d(float x, float y, float z, float dist) const return IsInDist(x, y, z, dist + GetCombatReach()); } -bool WorldObject::IsWithinDist3d(const Position* pos, float dist) const +bool WorldObject::IsWithinDist3d(Position const* pos, float dist) const { return IsInDist(pos, dist + GetCombatReach()); } @@ -1201,7 +1200,7 @@ bool WorldObject::IsWithinDist2d(float x, float y, float dist) const return IsInDist2d(x, y, dist + GetCombatReach()); } -bool WorldObject::IsWithinDist2d(const Position* pos, float dist) const +bool WorldObject::IsWithinDist2d(Position const* pos, float dist) const { return IsInDist2d(pos, dist + GetCombatReach()); } @@ -1241,7 +1240,7 @@ bool WorldObject::IsWithinLOS(float ox, float oy, float oz, LineOfSightChecks ch return true; } -bool WorldObject::IsWithinLOSInMap(const WorldObject* obj, LineOfSightChecks checks, VMAP::ModelIgnoreFlags ignoreFlags) const +bool WorldObject::IsWithinLOSInMap(WorldObject const* obj, LineOfSightChecks checks, VMAP::ModelIgnoreFlags ignoreFlags) const { if (!IsInMap(obj)) return false; @@ -1379,7 +1378,7 @@ bool WorldObject::isInBack(WorldObject const* target, float arc) const return !HasInArc(2 * float(M_PI) - arc, target); } -void WorldObject::GetRandomPoint(const Position &pos, float distance, float &rand_x, float &rand_y, float &rand_z) const +void WorldObject::GetRandomPoint(Position const& pos, float distance, float& rand_x, float& rand_y, float& rand_z) const { if (!distance) { @@ -1401,7 +1400,7 @@ void WorldObject::GetRandomPoint(const Position &pos, float distance, float &ran UpdateGroundPositionZ(rand_x, rand_y, rand_z); // update to LOS height if available } -Position WorldObject::GetRandomPoint(const Position &srcPos, float distance) const +Position WorldObject::GetRandomPoint(Position const& srcPos, float distance) const { float x, y, z; GetRandomPoint(srcPos, distance, x, y, z); @@ -1507,7 +1506,7 @@ float WorldObject::GetVisibilityRange() const return GetMap()->GetVisibilityRange(); } -float WorldObject::GetSightRange(const WorldObject* target) const +float WorldObject::GetSightRange(WorldObject const* target) const { if (ToUnit()) { @@ -1573,7 +1572,7 @@ bool WorldObject::CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth, boo } WorldObject const* viewpoint = this; - if (Player const* player = this->ToPlayer()) + if (Player const* player = ToPlayer()) viewpoint = player->GetViewpoint(); if (!viewpoint) @@ -1627,7 +1626,7 @@ bool WorldObject::CanNeverSee(WorldObject const* obj) const bool WorldObject::CanDetect(WorldObject const* obj, bool ignoreStealth, bool checkAlert) const { - const WorldObject* seer = this; + WorldObject const* seer = this; // Pets don't have detection, they use the detection of their masters if (Unit const* thisUnit = ToUnit()) @@ -1809,7 +1808,7 @@ void WorldObject::ResetMap() ASSERT(!IsInWorld()); if (IsWorldObject()) m_currMap->RemoveWorldObject(this); - m_currMap = NULL; + m_currMap = nullptr; //maybe not for corpse //m_mapId = 0; //m_InstanceId = 0; @@ -1881,7 +1880,7 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert break; } default: - return NULL; + return nullptr; } } @@ -1889,7 +1888,7 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert if (summoner) phase = summoner->GetPhaseMask(); - TempSummon* summon = NULL; + TempSummon* summon = nullptr; switch (mask) { case UNIT_MASK_SUMMON: @@ -1912,7 +1911,7 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert if (!summon->Create(GenerateLowGuid(), this, phase, entry, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), nullptr, vehId)) { delete summon; - return NULL; + return nullptr; } summon->SetUInt32Value(UNIT_CREATED_BY_SPELL, spellId); @@ -1937,14 +1936,14 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert * @param list List to store pointers to summoned creatures. */ -void Map::SummonCreatureGroup(uint8 group, std::list* list /*= NULL*/) +void Map::SummonCreatureGroup(uint8 group, std::list* list /*= nullptr*/) { std::vector const* data = sObjectMgr->GetSummonGroup(GetId(), SUMMONER_TYPE_MAP, group); if (!data) return; for (std::vector::const_iterator itr = data->begin(); itr != data->end(); ++itr) - if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, NULL, itr->time)) + if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, nullptr, itr->time)) if (list) list->push_back(summon); } @@ -1967,14 +1966,14 @@ void WorldObject::SetZoneScript() void WorldObject::ClearZoneScript() { - m_zoneScript = NULL; + m_zoneScript = nullptr; } TempSummon* WorldObject::SummonCreature(uint32 entry, Position const& pos, TempSummonType spwtype /*= TEMPSUMMON_MANUAL_DESPAWN*/, uint32 duration /*= 0*/, uint32 /*vehId = 0*/) const { if (Map* map = FindMap()) { - if (TempSummon* summon = map->SummonCreature(entry, pos, NULL, duration, isType(TYPEMASK_UNIT) ? (Unit*)this : NULL)) + if (TempSummon* summon = map->SummonCreature(entry, pos, nullptr, duration, isType(TYPEMASK_UNIT) ? (Unit*)this : nullptr)) { summon->SetTempSummonType(spwtype); return summon; @@ -1997,7 +1996,7 @@ TempSummon* WorldObject::SummonCreature(uint32 id, float x, float y, float z, fl return SummonCreature(id, pos, spwtype, despwtime, 0); } -GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot, uint32 respawnTime) +GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, QuaternionData const& rot, uint32 respawnTime) { if (!IsInWorld()) return nullptr; @@ -2027,7 +2026,7 @@ GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, G3D return go; } -GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, G3D::Quat const& rot, uint32 respawnTime) +GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, QuaternionData const& rot, uint32 respawnTime) { if (!x && !y && !z) { @@ -2064,7 +2063,7 @@ Creature* WorldObject::SummonTrigger(float x, float y, float z, float ang, uint3 * @param group Id of group to summon. * @param list List to store pointers to summoned creatures. */ -void WorldObject::SummonCreatureGroup(uint8 group, std::list* list /*= NULL*/) +void WorldObject::SummonCreatureGroup(uint8 group, std::list* list /*= nullptr*/) { ASSERT((GetTypeId() == TYPEID_GAMEOBJECT || GetTypeId() == TYPEID_UNIT) && "Only GOs and creatures can summon npc groups!"); @@ -2215,7 +2214,7 @@ Position WorldObject::GetRandomNearPosition(float radius) return pos; } -void WorldObject::GetContactPoint(const WorldObject* obj, float &x, float &y, float &z, float distance2d /*= CONTACT_DISTANCE*/) const +void WorldObject::GetContactPoint(WorldObject const* obj, float& x, float& y, float& z, float distance2d /*= CONTACT_DISTANCE*/) const { // angle to face `obj` to `this` using distance includes size of `obj` GetNearPoint(obj, x, y, z, obj->GetCombatReach(), distance2d, GetAngle(obj)); @@ -2368,7 +2367,7 @@ bool WorldObject::InSamePhase(WorldObject const* obj) const return InSamePhase(obj->GetPhaseMask()); } -void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= NULL*/) +void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= nullptr*/) { WorldPacket data(SMSG_PLAY_OBJECT_SOUND, 4+8); data << uint32(sound_id); @@ -2379,7 +2378,7 @@ void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= NULL*/) SendMessageToSet(&data, true); } -void WorldObject::PlayDirectSound(uint32 sound_id, Player* target /*= NULL*/) +void WorldObject::PlayDirectSound(uint32 sound_id, Player* target /*= nullptr*/) { WorldPacket data(SMSG_PLAY_SOUND, 4); data << uint32(sound_id); @@ -2389,7 +2388,7 @@ void WorldObject::PlayDirectSound(uint32 sound_id, Player* target /*= NULL*/) SendMessageToSet(&data, true); } -void WorldObject::PlayDirectMusic(uint32 music_id, Player* target /*= NULL*/) +void WorldObject::PlayDirectMusic(uint32 music_id, Player* target /*= nullptr*/) { WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(music_id); @@ -2445,7 +2444,7 @@ struct WorldObjectChangeAccumulator WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d) : i_updateDatas(d), i_object(obj) { } void Visit(PlayerMapType &m) { - Player* source = NULL; + Player* source = nullptr; for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); @@ -2463,7 +2462,7 @@ struct WorldObjectChangeAccumulator void Visit(CreatureMapType &m) { - Creature* source = NULL; + Creature* source = nullptr; for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); @@ -2478,7 +2477,7 @@ struct WorldObjectChangeAccumulator void Visit(DynamicObjectMapType &m) { - DynamicObject* source = NULL; + DynamicObject* source = nullptr; for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); @@ -2486,7 +2485,7 @@ struct WorldObjectChangeAccumulator if (guid.IsPlayer()) { - //Caster may be NULL if DynObj is in removelist + //Caster may be nullptr if DynObj is in removelist if (Player* caster = ObjectAccessor::FindPlayer(guid)) if (caster->GetGuidValue(PLAYER_FARSIGHT) == source->GetGUID()) BuildPacket(caster); diff --git a/src/server/game/Entities/Object/Object.h b/src/server/game/Entities/Object/Object.h index 3438e428a75..f5ff5100b78 100644 --- a/src/server/game/Entities/Object/Object.h +++ b/src/server/game/Entities/Object/Object.h @@ -20,59 +20,19 @@ #define _OBJECT_H #include "Common.h" -#include "Position.h" -#include "UpdateMask.h" #include "GridReference.h" -#include "ObjectDefines.h" -#include "Map.h" +#include "GridRefManager.h" #include "ModelIgnoreFlags.h" - +#include "MovementInfo.h" +#include "ObjectDefines.h" +#include "ObjectGuid.h" +#include "Position.h" +#include "SharedDefines.h" +#include "UpdateFields.h" +#include "UpdateMask.h" +#include #include -#include -#include - -#define CONTACT_DISTANCE 0.5f -#define INTERACTION_DISTANCE 5.0f -#define ATTACK_DISTANCE 5.0f -#define INSPECT_DISTANCE 28.0f -#define TRADE_DISTANCE 11.11f -#define MAX_VISIBILITY_DISTANCE SIZE_OF_GRIDS // max distance for visible objects -#define SIGHT_RANGE_UNIT 50.0f -#define DEFAULT_VISIBILITY_DISTANCE 90.0f // default visible distance, 90 yards on continents -#define DEFAULT_VISIBILITY_INSTANCE 170.0f // default visible distance in instances, 170 yards -#define DEFAULT_VISIBILITY_BGARENAS 533.0f // default visible distance in BG/Arenas, roughly 533 yards - -#define DEFAULT_PLAYER_BOUNDING_RADIUS 0.388999998569489f // player size, also currently used (correctly?) for any non Unit world objects -#define DEFAULT_PLAYER_COMBAT_REACH 1.5f -#define MIN_MELEE_REACH 2.0f -#define NOMINAL_MELEE_RANGE 5.0f -#define MELEE_RANGE (NOMINAL_MELEE_RANGE - MIN_MELEE_REACH * 2) //center to center for players - -enum TempSummonType -{ - TEMPSUMMON_TIMED_OR_DEAD_DESPAWN = 1, // despawns after a specified time OR when the creature disappears - TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN = 2, // despawns after a specified time OR when the creature dies - TEMPSUMMON_TIMED_DESPAWN = 3, // despawns after a specified time - TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT = 4, // despawns after a specified time after the creature is out of combat - TEMPSUMMON_CORPSE_DESPAWN = 5, // despawns instantly after death - TEMPSUMMON_CORPSE_TIMED_DESPAWN = 6, // despawns after a specified time after death - TEMPSUMMON_DEAD_DESPAWN = 7, // despawns when the creature disappears - TEMPSUMMON_MANUAL_DESPAWN = 8 // despawns when UnSummon() is called -}; - -enum PhaseMasks -{ - PHASEMASK_NORMAL = 0x00000001, - PHASEMASK_ANYWHERE = 0xFFFFFFFF -}; - -enum NotifyFlags -{ - NOTIFY_NONE = 0x00, - NOTIFY_AI_RELOCATION = 0x01, - NOTIFY_VISIBILITY_CHANGED = 0x02, - NOTIFY_ALL = 0xFF -}; +#include class Corpse; class Creature; @@ -80,6 +40,7 @@ class CreatureAI; class DynamicObject; class GameObject; class InstanceScript; +class Map; class Player; class TempSummon; class Transport; @@ -88,6 +49,8 @@ class UpdateData; class WorldObject; class WorldPacket; class ZoneScript; +struct PositionFullTerrainStatus; +struct QuaternionData; typedef std::unordered_map UpdateDataMapType; @@ -183,23 +146,23 @@ class TC_GAME_API Object // FG: some hacky helpers void ForceValuesUpdateAtIndex(uint32); - Player* ToPlayer() { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return NULL; } - Player const* ToPlayer() const { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return NULL; } + Player* ToPlayer() { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } + Player const* ToPlayer() const { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } - Creature* ToCreature() { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return NULL; } - Creature const* ToCreature() const { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return NULL; } + Creature* ToCreature() { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return nullptr; } + Creature const* ToCreature() const { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return nullptr; } - Unit* ToUnit() { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return NULL; } - Unit const* ToUnit() const { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return NULL; } + Unit* ToUnit() { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return nullptr; } + Unit const* ToUnit() const { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return nullptr; } - GameObject* ToGameObject() { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return NULL; } - GameObject const* ToGameObject() const { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return NULL; } + GameObject* ToGameObject() { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return nullptr; } + GameObject const* ToGameObject() const { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return nullptr; } - Corpse* ToCorpse() { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return NULL; } - Corpse const* ToCorpse() const { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return NULL; } + Corpse* ToCorpse() { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return nullptr; } + Corpse const* ToCorpse() const { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return nullptr; } - DynamicObject* ToDynObject() { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return NULL; } - DynamicObject const* ToDynObject() const { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return NULL; } + DynamicObject* ToDynObject() { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } + DynamicObject const* ToDynObject() const { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } protected: Object(); @@ -249,114 +212,6 @@ class TC_GAME_API Object Object& operator=(Object const& right) = delete; }; -struct MovementInfo -{ - // common - ObjectGuid guid; - uint32 flags; - uint16 flags2; - Position pos; - uint32 time; - - // transport - struct TransportInfo - { - void Reset() - { - guid.Clear(); - pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - seat = -1; - time = 0; - time2 = 0; - } - - ObjectGuid guid; - Position pos; - int8 seat; - uint32 time; - uint32 time2; - } transport; - - // swimming/flying - float pitch; - - // falling - uint32 fallTime; - - // jumping - struct JumpInfo - { - void Reset() - { - zspeed = sinAngle = cosAngle = xyspeed = 0.0f; - } - - float zspeed, sinAngle, cosAngle, xyspeed; - - } jump; - - // spline - float splineElevation; - - MovementInfo() : - guid(), flags(0), flags2(0), time(0), pitch(0.0f), fallTime(0), splineElevation(0.0f) - { - pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - transport.Reset(); - jump.Reset(); - } - - uint32 GetMovementFlags() const { return flags; } - void SetMovementFlags(uint32 flag) { flags = flag; } - void AddMovementFlag(uint32 flag) { flags |= flag; } - void RemoveMovementFlag(uint32 flag) { flags &= ~flag; } - bool HasMovementFlag(uint32 flag) const { return (flags & flag) != 0; } - - uint16 GetExtraMovementFlags() const { return flags2; } - void AddExtraMovementFlag(uint16 flag) { flags2 |= flag; } - bool HasExtraMovementFlag(uint16 flag) const { return (flags2 & flag) != 0; } - - void SetFallTime(uint32 val) { fallTime = val; } - - void OutDebug(); -}; - -#define MAPID_INVALID 0xFFFFFFFF - -class WorldLocation : public Position -{ - public: - explicit WorldLocation(uint32 _mapId = MAPID_INVALID, float _x = 0.f, float _y = 0.f, float _z = 0.f, float _o = 0.f) - : Position(_x, _y, _z, _o), m_mapId(_mapId) { } - - WorldLocation(uint32 mapId, Position const& position) - : Position(position), m_mapId(mapId) { } - - WorldLocation(WorldLocation const& loc) - : Position(loc), m_mapId(loc.GetMapId()) { } - - void WorldRelocate(WorldLocation const& loc) - { - m_mapId = loc.GetMapId(); - Relocate(loc); - } - - void WorldRelocate(uint32 _mapId = MAPID_INVALID, float _x = 0.f, float _y = 0.f, float _z = 0.f, float _o = 0.f) - { - m_mapId = _mapId; - Relocate(_x, _y, _z, _o); - } - - WorldLocation GetWorldLocation() const - { - return *this; - } - - uint32 GetMapId() const { return m_mapId; } - - uint32 m_mapId; -}; - template class GridObject { @@ -376,7 +231,8 @@ class FlaggedValuesArray32 public: FlaggedValuesArray32() { - memset(&m_values, 0x00, sizeof(T_VALUES) * ARRAY_SIZE); + for (uint32 i = 0; i < ARRAY_SIZE; ++i) + m_values[i] = T_VALUES(0); m_flags = 0; } @@ -394,38 +250,6 @@ class FlaggedValuesArray32 T_FLAGS m_flags; }; -enum MapObjectCellMoveState -{ - MAP_OBJECT_CELL_MOVE_NONE, //not in move list - MAP_OBJECT_CELL_MOVE_ACTIVE, //in move list - MAP_OBJECT_CELL_MOVE_INACTIVE, //in move list but should not move -}; - -class TC_GAME_API MapObject -{ - friend class Map; //map for moving creatures - friend class ObjectGridLoader; //grid loader for loading creatures - - protected: - MapObject() : _moveState(MAP_OBJECT_CELL_MOVE_NONE) - { - _newPosition.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - } - - private: - Cell _currentCell; - Cell const& GetCurrentCell() const { return _currentCell; } - void SetCurrentCell(Cell const& cell) { _currentCell = cell; } - - MapObjectCellMoveState _moveState; - Position _newPosition; - void SetNewCellPosition(float x, float y, float z, float o) - { - _moveState = MAP_OBJECT_CELL_MOVE_ACTIVE; - _newPosition.Relocate(x, y, z, o); - } -}; - class TC_GAME_API WorldObject : public Object, public WorldLocation { protected: @@ -453,8 +277,8 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation void UpdateGroundPositionZ(float x, float y, float &z) const; void UpdateAllowedPositionZ(float x, float y, float &z) const; - void GetRandomPoint(Position const &srcPos, float distance, float &rand_x, float &rand_y, float &rand_z) const; - Position GetRandomPoint(Position const &srcPos, float distance) const; + void GetRandomPoint(Position const& srcPos, float distance, float& rand_x, float& rand_y, float& rand_z) const; + Position GetRandomPoint(Position const& srcPos, float distance) const; uint32 GetInstanceId() const { return m_InstanceId; } @@ -470,12 +294,12 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation InstanceScript* GetInstanceScript(); std::string const& GetName() const { return m_name; } - void SetName(std::string const& newname) { m_name=newname; } + void SetName(std::string const& newname) { m_name = newname; } virtual std::string const& GetNameForLocaleIdx(LocaleConstant /*locale_idx*/) const { return m_name; } float GetDistance(WorldObject const* obj) const; - float GetDistance(Position const &pos) const; + float GetDistance(Position const& pos) const; float GetDistance(float x, float y, float z) const; float GetDistance2d(WorldObject const* obj) const; float GetDistance2d(float x, float y) const; @@ -512,9 +336,9 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation virtual uint8 getLevelForTarget(WorldObject const* /*target*/) const { return 1; } - void PlayDistanceSound(uint32 sound_id, Player* target = NULL); - void PlayDirectSound(uint32 sound_id, Player* target = NULL); - void PlayDirectMusic(uint32 music_id, Player* target = NULL); + void PlayDistanceSound(uint32 sound_id, Player* target = nullptr); + void PlayDirectSound(uint32 sound_id, Player* target = nullptr); + void PlayDirectMusic(uint32 music_id, Player* target = nullptr); void SendObjectDeSpawnAnim(ObjectGuid guid); @@ -523,7 +347,7 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation float GetGridActivationRange() const; float GetVisibilityRange() const; - float GetSightRange(WorldObject const* target = NULL) const; + float GetSightRange(WorldObject const* target = nullptr) const; bool CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth = false, bool distanceCheck = false, bool checkAlert = false) const; FlaggedValuesArray32 m_stealth; @@ -550,10 +374,10 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation TempSummon* SummonCreature(uint32 id, Position const& pos, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0, uint32 vehId = 0) const; TempSummon* SummonCreature(uint32 id, float x, float y, float z, float ang = 0, TempSummonType spwtype = TEMPSUMMON_MANUAL_DESPAWN, uint32 despwtime = 0) const; - GameObject* SummonGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot, uint32 respawnTime /* s */); - GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, G3D::Quat const& rot, uint32 respawnTime /* s */); - Creature* SummonTrigger(float x, float y, float z, float ang, uint32 dur, CreatureAI* (*GetAI)(Creature*) = NULL); - void SummonCreatureGroup(uint8 group, std::list* list = NULL); + GameObject* SummonGameObject(uint32 entry, Position const& pos, QuaternionData const& rot, uint32 respawnTime /* s */); + GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, QuaternionData const& rot, uint32 respawnTime /* s */); + Creature* SummonTrigger(float x, float y, float z, float ang, uint32 dur, CreatureAI* (*GetAI)(Creature*) = nullptr); + void SummonCreatureGroup(uint8 group, std::list* list = nullptr); Creature* FindNearestCreature(uint32 entry, float range, bool alive = true) const; GameObject* FindNearestGameObject(uint32 entry, float range) const; @@ -604,6 +428,7 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation float GetTransOffsetY() const { return m_movementInfo.transport.pos.GetPositionY(); } float GetTransOffsetZ() const { return m_movementInfo.transport.pos.GetPositionZ(); } float GetTransOffsetO() const { return m_movementInfo.transport.pos.GetOrientation(); } + Position const& GetTransOffset() const { return m_movementInfo.transport.pos; } uint32 GetTransTime() const { return m_movementInfo.transport.time; } int8 GetTransSeat() const { return m_movementInfo.transport.seat; } virtual ObjectGuid GetTransGUID() const; diff --git a/src/server/game/Entities/Object/ObjectDefines.h b/src/server/game/Entities/Object/ObjectDefines.h index 8c2735502b4..fb3b8191af4 100644 --- a/src/server/game/Entities/Object/ObjectDefines.h +++ b/src/server/game/Entities/Object/ObjectDefines.h @@ -20,48 +20,81 @@ #define TRINITY_OBJECTDEFINES_H #include "Define.h" -#include "ObjectGuid.h" -// used for creating values for respawn for example -inline uint64 MAKE_PAIR64(uint32 l, uint32 h); -inline uint32 PAIR64_HIPART(uint64 x); -inline uint32 PAIR64_LOPART(uint64 x); -inline uint16 MAKE_PAIR16(uint8 l, uint8 h); -inline uint32 MAKE_PAIR32(uint16 l, uint16 h); -inline uint16 PAIR32_HIPART(uint32 x); -inline uint16 PAIR32_LOPART(uint32 x); +#define CONTACT_DISTANCE 0.5f +#define INTERACTION_DISTANCE 5.0f +#define ATTACK_DISTANCE 5.0f +#define INSPECT_DISTANCE 28.0f +#define TRADE_DISTANCE 11.11f +#define MAX_VISIBILITY_DISTANCE SIZE_OF_GRIDS // max distance for visible objects +#define SIGHT_RANGE_UNIT 50.0f +#define DEFAULT_VISIBILITY_DISTANCE 90.0f // default visible distance, 90 yards on continents +#define DEFAULT_VISIBILITY_INSTANCE 170.0f // default visible distance in instances, 170 yards +#define DEFAULT_VISIBILITY_BGARENAS 533.0f // default visible distance in BG/Arenas, roughly 533 yards -uint64 MAKE_PAIR64(uint32 l, uint32 h) +#define DEFAULT_PLAYER_BOUNDING_RADIUS 0.388999998569489f // player size, also currently used (correctly?) for any non Unit world objects +#define DEFAULT_PLAYER_COMBAT_REACH 1.5f +#define MIN_MELEE_REACH 2.0f +#define NOMINAL_MELEE_RANGE 5.0f +#define MELEE_RANGE (NOMINAL_MELEE_RANGE - MIN_MELEE_REACH * 2) //center to center for players + +enum TempSummonType +{ + TEMPSUMMON_TIMED_OR_DEAD_DESPAWN = 1, // despawns after a specified time OR when the creature disappears + TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN = 2, // despawns after a specified time OR when the creature dies + TEMPSUMMON_TIMED_DESPAWN = 3, // despawns after a specified time + TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT = 4, // despawns after a specified time after the creature is out of combat + TEMPSUMMON_CORPSE_DESPAWN = 5, // despawns instantly after death + TEMPSUMMON_CORPSE_TIMED_DESPAWN = 6, // despawns after a specified time after death + TEMPSUMMON_DEAD_DESPAWN = 7, // despawns when the creature disappears + TEMPSUMMON_MANUAL_DESPAWN = 8 // despawns when UnSummon() is called +}; + +enum PhaseMasks +{ + PHASEMASK_NORMAL = 0x00000001, + PHASEMASK_ANYWHERE = 0xFFFFFFFF +}; + +enum NotifyFlags +{ + NOTIFY_NONE = 0x00, + NOTIFY_AI_RELOCATION = 0x01, + NOTIFY_VISIBILITY_CHANGED = 0x02, + NOTIFY_ALL = 0xFF +}; + +inline uint64 MAKE_PAIR64(uint32 l, uint32 h) { return uint64(l | (uint64(h) << 32)); } -uint32 PAIR64_HIPART(uint64 x) +inline uint32 PAIR64_HIPART(uint64 x) { return (uint32)((x >> 32) & UI64LIT(0x00000000FFFFFFFF)); } -uint32 PAIR64_LOPART(uint64 x) +inline uint32 PAIR64_LOPART(uint64 x) { return (uint32)(x & UI64LIT(0x00000000FFFFFFFF)); } -uint16 MAKE_PAIR16(uint8 l, uint8 h) +inline uint16 MAKE_PAIR16(uint8 l, uint8 h) { return uint16(l | (uint16(h) << 8)); } -uint32 MAKE_PAIR32(uint16 l, uint16 h) +inline uint32 MAKE_PAIR32(uint16 l, uint16 h) { return uint32(l | (uint32(h) << 16)); } -uint16 PAIR32_HIPART(uint32 x) +inline uint16 PAIR32_HIPART(uint32 x) { return (uint16)((x >> 16) & 0x0000FFFF); } -uint16 PAIR32_LOPART(uint32 x) +inline uint16 PAIR32_LOPART(uint32 x) { return (uint16)(x & 0x0000FFFF); } diff --git a/src/server/game/Entities/Object/ObjectGuid.cpp b/src/server/game/Entities/Object/ObjectGuid.cpp index ef93a499fc0..3a26dfd0d7f 100644 --- a/src/server/game/Entities/Object/ObjectGuid.cpp +++ b/src/server/game/Entities/Object/ObjectGuid.cpp @@ -17,8 +17,9 @@ */ #include "ObjectGuid.h" +#include "Hash.h" +#include "Log.h" #include "World.h" -#include "ObjectMgr.h" #include #include @@ -87,7 +88,7 @@ ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid) ByteBuffer& operator>>(ByteBuffer& buf, PackedGuidReader const& guid) { - buf.readPackGUID(*reinterpret_cast(guid.GuidPtr)); + buf.readPackGUID(reinterpret_cast(guid.Guid)); return buf; } diff --git a/src/server/game/Entities/Object/ObjectGuid.h b/src/server/game/Entities/Object/ObjectGuid.h index 1bf5c15c2b6..75410aa4f28 100644 --- a/src/server/game/Entities/Object/ObjectGuid.h +++ b/src/server/game/Entities/Object/ObjectGuid.h @@ -19,10 +19,16 @@ #ifndef ObjectGuid_h__ #define ObjectGuid_h__ -#include "Common.h" #include "ByteBuffer.h" -#include +#include "Define.h" +#include #include +#include +#include +#include +#include +#include +#include enum TypeID { @@ -107,8 +113,8 @@ class PackedGuid; struct PackedGuidReader { - explicit PackedGuidReader(ObjectGuid& guid) : GuidPtr(&guid) { } - ObjectGuid* GuidPtr; + explicit PackedGuidReader(ObjectGuid& guid) : Guid(guid) { } + ObjectGuid& Guid; }; class TC_GAME_API ObjectGuid @@ -180,7 +186,7 @@ class TC_GAME_API ObjectGuid switch (high) { case HighGuid::Item: return TYPEID_ITEM; - //case HighGuid::Container: return TYPEID_CONTAINER; HighGuid::Container==HighGuid::Item currently + //case HighGuid::Container: return TYPEID_CONTAINER; HighGuid::Container == HighGuid::Item currently case HighGuid::Unit: return TYPEID_UNIT; case HighGuid::Pet: return TYPEID_UNIT; case HighGuid::Player: return TYPEID_PLAYER; @@ -199,8 +205,8 @@ class TC_GAME_API ObjectGuid TypeID GetTypeId() const { return GetTypeId(GetHigh()); } bool operator!() const { return IsEmpty(); } - bool operator== (ObjectGuid const& guid) const { return GetRawValue() == guid.GetRawValue(); } - bool operator!= (ObjectGuid const& guid) const { return GetRawValue() != guid.GetRawValue(); } + bool operator==(ObjectGuid const& guid) const { return GetRawValue() == guid.GetRawValue(); } + bool operator!=(ObjectGuid const& guid) const { return GetRawValue() != guid.GetRawValue(); } bool operator< (ObjectGuid const& guid) const { return GetRawValue() < guid.GetRawValue(); } static char const* GetTypeName(HighGuid high); @@ -254,7 +260,7 @@ typedef std::unordered_set GuidUnorderedSet; class TC_GAME_API PackedGuid { - friend TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid); + friend TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid); public: explicit PackedGuid() : _packedGuid(PACKED_GUID_MIN_BUFFER_SIZE) { _packedGuid.appendPackGUID(0); } @@ -264,7 +270,7 @@ class TC_GAME_API PackedGuid void Set(uint64 guid) { _packedGuid.wpos(0); _packedGuid.appendPackGUID(guid); } void Set(ObjectGuid guid) { _packedGuid.wpos(0); _packedGuid.appendPackGUID(guid.GetRawValue()); } - size_t size() const { return _packedGuid.size(); } + std::size_t size() const { return _packedGuid.size(); } private: ByteBuffer _packedGuid; @@ -314,7 +320,7 @@ namespace std public: size_t operator()(ObjectGuid const& key) const { - return hash()(key.GetRawValue()); + return std::hash()(key.GetRawValue()); } }; } diff --git a/src/server/game/Entities/Object/ObjectPosSelector.cpp b/src/server/game/Entities/Object/ObjectPosSelector.cpp index bfb3022a2b7..e9acd8099ec 100644 --- a/src/server/game/Entities/Object/ObjectPosSelector.cpp +++ b/src/server/game/Entities/Object/ObjectPosSelector.cpp @@ -32,8 +32,8 @@ ObjectPosSelector::ObjectPosSelector(float x, float y, float size, float dist) m_smallStepOk[USED_POS_PLUS] = false; m_smallStepOk[USED_POS_MINUS] = false; - m_smallStepNextUsedPos[USED_POS_PLUS] = NULL; - m_smallStepNextUsedPos[USED_POS_MINUS] = NULL; + m_smallStepNextUsedPos[USED_POS_PLUS] = nullptr; + m_smallStepNextUsedPos[USED_POS_MINUS] = nullptr; } ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos(UsedPosType uptype) @@ -42,12 +42,12 @@ ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos if (itr!=m_UsedPosLists[uptype].end()) ++itr; - if (itr==m_UsedPosLists[uptype].end()) + if (itr == m_UsedPosLists[uptype].end()) { if (!m_UsedPosLists[~uptype].empty()) return &*m_UsedPosLists[~uptype].rbegin(); else - return NULL; + return nullptr; } else return &*itr; diff --git a/src/server/game/Entities/Object/ObjectPosSelector.h b/src/server/game/Entities/Object/ObjectPosSelector.h index d5414e0e245..8185a2a0c21 100644 --- a/src/server/game/Entities/Object/ObjectPosSelector.h +++ b/src/server/game/Entities/Object/ObjectPosSelector.h @@ -19,15 +19,15 @@ #ifndef _OBJECT_POS_SELECTOR_H #define _OBJECT_POS_SELECTOR_H -#include - -#include +#include "Common.h" +#include +#include enum UsedPosType { USED_POS_PLUS, USED_POS_MINUS }; -inline UsedPosType operator ~(UsedPosType uptype) +inline UsedPosType operator~(UsedPosType uptype) { - return uptype==USED_POS_PLUS ? USED_POS_MINUS : USED_POS_PLUS; + return uptype == USED_POS_PLUS ? USED_POS_MINUS : USED_POS_PLUS; } struct TC_GAME_API ObjectPosSelector diff --git a/src/server/game/Entities/Object/Position.cpp b/src/server/game/Entities/Object/Position.cpp index a8cb363e272..99bc433ff91 100644 --- a/src/server/game/Entities/Object/Position.cpp +++ b/src/server/game/Entities/Object/Position.cpp @@ -18,21 +18,12 @@ #include "Position.h" #include "ByteBuffer.h" #include "GridDefines.h" +#include "Random.h" #include -#include +#include -Position::Position(G3D::Vector3 const& vect) -{ - Relocate(vect.x, vect.y, vect.z, 0.f); -} - -Position::operator G3D::Vector3() const -{ - return { m_positionX, m_positionY, m_positionZ }; -} - -bool Position::operator==(Position const &a) +bool Position::operator==(Position const& a) { return (G3D::fuzzyEq(a.m_positionX, m_positionX) && G3D::fuzzyEq(a.m_positionY, m_positionY) && @@ -40,7 +31,7 @@ bool Position::operator==(Position const &a) G3D::fuzzyEq(a.m_orientation, m_orientation)); } -void Position::RelocateOffset(const Position & offset) +void Position::RelocateOffset(Position const& offset) { m_positionX = GetPositionX() + (offset.GetPositionX() * std::cos(GetOrientation()) + offset.GetPositionY() * std::sin(GetOrientation() + float(M_PI))); m_positionY = GetPositionY() + (offset.GetPositionY() * std::cos(GetOrientation()) + offset.GetPositionX() * std::sin(GetOrientation())); @@ -53,7 +44,27 @@ bool Position::IsPositionValid() const return Trinity::IsValidMapCoord(m_positionX, m_positionY, m_positionZ, m_orientation); } -void Position::GetPositionOffsetTo(const Position & endPos, Position & retOffset) const +float Position::GetExactDist2d(const float x, const float y) const +{ + return std::sqrt(GetExactDist2dSq(x, y)); +} + +float Position::GetExactDist2d(Position const* pos) const +{ + return std::sqrt(GetExactDist2dSq(pos)); +} + +float Position::GetExactDist(float x, float y, float z) const +{ + return std::sqrt(GetExactDistSq(x, y, z)); +} + +float Position::GetExactDist(Position const* pos) const +{ + return std::sqrt(GetExactDistSq(pos)); +} + +void Position::GetPositionOffsetTo(Position const& endPos, Position& retOffset) const { float dx = endPos.GetPositionX() - GetPositionX(); float dy = endPos.GetPositionY() - GetPositionY(); @@ -109,7 +120,7 @@ void Position::GetSinCos(const float x, const float y, float &vsin, float &vcos) } } -bool Position::IsWithinBox(const Position& center, float xradius, float yradius, float zradius) const +bool Position::IsWithinBox(Position const& center, float xradius, float yradius, float zradius) const { // rotate the WorldObject position instead of rotating the whole cube, that way we can make a simplified // is-in-cube check and we have to calculate only one point instead of 4 @@ -143,7 +154,7 @@ bool Position::IsWithinDoubleVerticalCylinder(Position const* center, float radi return IsInDist2d(center, radius) && std::abs(verticalDelta) <= height; } -bool Position::HasInArc(float arc, const Position* obj, float border) const +bool Position::HasInArc(float arc, Position const* obj, float border) const { // always have self in arc if (obj == this) @@ -182,14 +193,28 @@ std::string Position::ToString() const return sstr.str(); } -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYStreamer const& streamer) +float Position::NormalizeOrientation(float o) +{ + // fmod only supports positive numbers. Thus we have + // to emulate negative numbers + if (o < 0) + { + float mod = o *-1; + mod = std::fmod(mod, 2.0f * static_cast(M_PI)); + mod = -mod + 2.0f * static_cast(M_PI); + return mod; + } + return std::fmod(o, 2.0f * static_cast(M_PI)); +} + +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) { buf << streamer.Pos->GetPositionX(); buf << streamer.Pos->GetPositionY(); return buf; } -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& streamer) +ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer) { float x, y; buf >> x >> y; @@ -197,7 +222,7 @@ ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& stre return buf; } -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer) +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) { buf << streamer.Pos->GetPositionX(); buf << streamer.Pos->GetPositionY(); @@ -205,7 +230,7 @@ ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& str return buf; } -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer) +ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer) { float x, y, z; buf >> x >> y >> z; @@ -213,7 +238,7 @@ ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& str return buf; } -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer) +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) { buf << streamer.Pos->GetPositionX(); buf << streamer.Pos->GetPositionY(); @@ -222,10 +247,16 @@ ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& st return buf; } -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer) +ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer) { float x, y, z, o; buf >> x >> y >> z >> o; streamer.Pos->Relocate(x, y, z, o); return buf; } + +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) +{ + buf.appendPackXYZ(streamer.Pos->GetPositionX(), streamer.Pos->GetPositionY(), streamer.Pos->GetPositionZ()); + return buf; +} diff --git a/src/server/game/Entities/Object/Position.h b/src/server/game/Entities/Object/Position.h index 4dba3d1f330..98cb82df2e1 100644 --- a/src/server/game/Entities/Object/Position.h +++ b/src/server/game/Entities/Object/Position.h @@ -18,12 +18,9 @@ #ifndef Trinity_game_Position_h__ #define Trinity_game_Position_h__ -#include "Common.h" - -namespace G3D -{ - class Vector3; -} +#include "Define.h" +#include +#include class ByteBuffer; @@ -34,25 +31,24 @@ struct TC_GAME_API Position Position(Position const& loc) { Relocate(loc); } - Position(G3D::Vector3 const& vect); - - operator G3D::Vector3() const; + // streamer tags + struct XY; + struct XYZ; + struct XYZO; + struct PackedXYZ; - struct PositionXYStreamer + template + struct ConstStreamer { - explicit PositionXYStreamer(Position& pos) : Pos(&pos) { } - Position* Pos; + explicit ConstStreamer(Position const& pos) : Pos(&pos) { } + Position const* Pos; }; - struct PositionXYZStreamer + template + struct Streamer { - explicit PositionXYZStreamer(Position& pos) : Pos(&pos) { } - Position* Pos; - }; - - struct PositionXYZOStreamer - { - explicit PositionXYZOStreamer(Position& pos) : Pos(&pos) { } + explicit Streamer(Position& pos) : Pos(&pos) { } + operator ConstStreamer() const { return ConstStreamer(*Pos); } Position* Pos; }; @@ -64,9 +60,9 @@ private: float m_orientation; public: - bool operator==(Position const &a); + bool operator==(Position const& a); - inline bool operator!=(Position const &a) + inline bool operator!=(Position const& a) { return !(operator==(a)); } @@ -86,7 +82,7 @@ public: m_positionX = x; m_positionY = y; m_positionZ = z; SetOrientation(orientation); } - void Relocate(Position const &pos) + void Relocate(Position const& pos) { m_positionX = pos.m_positionX; m_positionY = pos.m_positionY; m_positionZ = pos.m_positionZ; SetOrientation(pos.m_orientation); } @@ -96,7 +92,7 @@ public: m_positionX = pos->m_positionX; m_positionY = pos->m_positionY; m_positionZ = pos->m_positionZ; SetOrientation(pos->m_orientation); } - void RelocateOffset(Position const &offset); + void RelocateOffset(Position const& offset); void SetOrientation(float orientation) { @@ -125,9 +121,14 @@ public: Position GetPosition() const { return *this; } - Position::PositionXYStreamer PositionXYStream() { return PositionXYStreamer(*this); } - Position::PositionXYZStreamer PositionXYZStream() { return PositionXYZStreamer(*this); } - Position::PositionXYZOStreamer PositionXYZOStream() { return PositionXYZOStreamer(*this); } + Streamer PositionXYStream() { return Streamer(*this); } + ConstStreamer PositionXYStream() const { return ConstStreamer(*this); } + Streamer PositionXYZStream() { return Streamer(*this); } + ConstStreamer PositionXYZStream() const { return ConstStreamer(*this); } + Streamer PositionXYZOStream() { return Streamer(*this); } + ConstStreamer PositionXYZOStream() const { return ConstStreamer(*this); } + Streamer PositionPackedXYZStream() { return Streamer(*this); } + ConstStreamer PositionPackedXYZStream() const { return ConstStreamer(*this); } bool IsPositionValid() const; @@ -136,10 +137,7 @@ public: float dx = m_positionX - x; float dy = m_positionY - y; return dx*dx + dy*dy; } - float GetExactDist2d(const float x, const float y) const - { - return std::sqrt(GetExactDist2dSq(x, y)); - } + float GetExactDist2d(const float x, const float y) const; float GetExactDist2dSq(Position const& pos) const { @@ -156,20 +154,14 @@ public: float dx = m_positionX - pos->m_positionX; float dy = m_positionY - pos->m_positionY; return dx*dx + dy*dy; } - float GetExactDist2d(Position const* pos) const - { - return std::sqrt(GetExactDist2dSq(pos)); - } + float GetExactDist2d(Position const* pos) const; float GetExactDistSq(float x, float y, float z) const { float dz = m_positionZ - z; return GetExactDist2dSq(x, y) + dz*dz; } - float GetExactDist(float x, float y, float z) const - { - return std::sqrt(GetExactDistSq(x, y, z)); - } + float GetExactDist(float x, float y, float z) const; float GetExactDistSq(Position const& pos) const { @@ -186,10 +178,7 @@ public: float dx = m_positionX - pos->m_positionX; float dy = m_positionY - pos->m_positionY; float dz = m_positionZ - pos->m_positionZ; return dx*dx + dy*dy + dz*dz; } - float GetExactDist(Position const* pos) const - { - return std::sqrt(GetExactDistSq(pos)); - } + float GetExactDist(Position const* pos) const; void GetPositionOffsetTo(Position const & endPos, Position & retOffset) const; Position GetPositionWithOffset(Position const& offset) const; @@ -228,7 +217,7 @@ public: return GetExactDistSq(pos) < dist * dist; } - bool IsWithinBox(const Position& center, float xradius, float yradius, float zradius) const; + bool IsWithinBox(Position const& center, float xradius, float yradius, float zradius) const; /* search using this relation: dist2d < radius && abs(dz) < height @@ -239,26 +228,71 @@ public: std::string ToString() const; // modulos a radian orientation to the range of 0..2PI - static float NormalizeOrientation(float o) - { - // fmod only supports positive numbers. Thus we have - // to emulate negative numbers - if (o < 0) + static float NormalizeOrientation(float o); +}; + +#define MAPID_INVALID 0xFFFFFFFF + +class WorldLocation : public Position +{ + public: + explicit WorldLocation(uint32 _mapId = MAPID_INVALID, float x = 0.f, float y = 0.f, float z = 0.f, float o = 0.f) + : Position(x, y, z, o), m_mapId(_mapId) { } + + WorldLocation(uint32 mapId, Position const& position) + : Position(position), m_mapId(mapId) { } + + WorldLocation(WorldLocation const& loc) + : Position(loc), m_mapId(loc.GetMapId()) { } + + void WorldRelocate(WorldLocation const& loc) { - float mod = o *-1; - mod = std::fmod(mod, 2.0f * static_cast(M_PI)); - mod = -mod + 2.0f * static_cast(M_PI); - return mod; + m_mapId = loc.GetMapId(); + Relocate(loc); } - return std::fmod(o, 2.0f * static_cast(M_PI)); - } + + void WorldRelocate(uint32 _mapId = MAPID_INVALID, float x = 0.f, float y = 0.f, float z = 0.f, float o = 0.f) + { + m_mapId = _mapId; + Relocate(x, y, z, o); + } + + WorldLocation GetWorldLocation() const + { + return *this; + } + + uint32 GetMapId() const { return m_mapId; } + + uint32 m_mapId; }; -TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYStreamer const& streamer); -TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& streamer); -TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer); -TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer); -TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer); -TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); + +template +struct TaggedPosition +{ + TaggedPosition(float x = 0.0f, float y = 0.0f, float z = 0.0f, float o = 0.0f) : Pos(x, y, z, o) { } + TaggedPosition(Position const& pos) : Pos(pos) { } + + TaggedPosition& operator=(Position const& pos) + { + Pos.Relocate(pos); + return *this; + } + + operator Position() const { return Pos; } + + friend ByteBuffer& operator<<(ByteBuffer& buf, TaggedPosition const& tagged) { return buf << Position::ConstStreamer(tagged.Pos); } + friend ByteBuffer& operator>>(ByteBuffer& buf, TaggedPosition& tagged) { return buf >> Position::Streamer(tagged.Pos); } + + Position Pos; +}; #endif // Trinity_game_Position_h__ diff --git a/src/server/game/Entities/Object/Updates/UpdateData.cpp b/src/server/game/Entities/Object/Updates/UpdateData.cpp index 0674fc4579c..cb8ecf45e2f 100644 --- a/src/server/game/Entities/Object/Updates/UpdateData.cpp +++ b/src/server/game/Entities/Object/Updates/UpdateData.cpp @@ -16,13 +16,13 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ByteBuffer.h" -#include "WorldPacket.h" #include "UpdateData.h" +#include "Errors.h" +#include "Log.h" #include "Opcodes.h" #include "World.h" -#include "zlib.h" +#include "WorldPacket.h" +#include UpdateData::UpdateData() : m_blockCount(0) { } @@ -36,7 +36,7 @@ void UpdateData::AddOutOfRangeGUID(ObjectGuid guid) m_outOfRangeGUIDs.insert(guid); } -void UpdateData::AddUpdateBlock(const ByteBuffer &block) +void UpdateData::AddUpdateBlock(ByteBuffer const& block) { m_data.append(block); ++m_blockCount; diff --git a/src/server/game/Entities/Object/Updates/UpdateData.h b/src/server/game/Entities/Object/Updates/UpdateData.h index 308d8662d40..e3437595c0b 100644 --- a/src/server/game/Entities/Object/Updates/UpdateData.h +++ b/src/server/game/Entities/Object/Updates/UpdateData.h @@ -19,6 +19,7 @@ #ifndef __UPDATEDATA_H #define __UPDATEDATA_H +#include "Define.h" #include "ByteBuffer.h" #include "ObjectGuid.h" #include @@ -62,7 +63,7 @@ class UpdateData void AddOutOfRangeGUID(GuidSet& guids); void AddOutOfRangeGUID(ObjectGuid guid); - void AddUpdateBlock(const ByteBuffer &block); + void AddUpdateBlock(ByteBuffer const& block); bool BuildPacket(WorldPacket* packet); bool HasData() const { return m_blockCount > 0 || !m_outOfRangeGUIDs.empty(); } void Clear(); diff --git a/src/server/game/Entities/Object/Updates/UpdateMask.h b/src/server/game/Entities/Object/Updates/UpdateMask.h index 5550a50b314..21fe8d700f7 100644 --- a/src/server/game/Entities/Object/Updates/UpdateMask.h +++ b/src/server/game/Entities/Object/Updates/UpdateMask.h @@ -20,7 +20,6 @@ #define __UPDATEMASK_H #include "UpdateFields.h" -#include "Errors.h" #include "ByteBuffer.h" class UpdateMask @@ -34,9 +33,9 @@ class UpdateMask CLIENT_UPDATE_MASK_BITS = sizeof(ClientUpdateMaskType) * 8, }; - UpdateMask() : _fieldCount(0), _blockCount(0), _bits(NULL) { } + UpdateMask() : _fieldCount(0), _blockCount(0), _bits(nullptr) { } - UpdateMask(UpdateMask const& right) : _bits(NULL) + UpdateMask(UpdateMask const& right) : _bits(nullptr) { SetCount(right.GetCount()); memcpy(_bits, right._bits, sizeof(uint8) * _blockCount * 32); diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index a1a0a44f822..20f9e57b666 100644 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -16,28 +16,30 @@ * with this program. If not, see . */ +#include "Pet.h" #include "Common.h" #include "DatabaseEnv.h" +#include "Formulas.h" +#include "Group.h" #include "Log.h" -#include "WorldPacket.h" #include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Pet.h" -#include "Formulas.h" -#include "SpellHistory.h" -#include "SpellAuras.h" +#include "Player.h" +#include "Spell.h" #include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellHistory.h" +#include "SpellMgr.h" #include "Unit.h" #include "Util.h" -#include "Group.h" +#include "WorldPacket.h" #include "WorldSession.h" #define PET_XP_FACTOR 0.05f Pet::Pet(Player* owner, PetType type) : - Guardian(NULL, owner, true), m_usedTalentCount(0), m_removed(false), + Guardian(nullptr, owner, true), m_usedTalentCount(0), m_removed(false), m_happinessTimer(7500), m_petType(type), m_duration(0), m_auraRaidUpdateMask(0), m_loading(false), - m_declinedname(NULL) + m_declinedname(nullptr) { ASSERT(GetOwner()); @@ -196,7 +198,7 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c return false; } - map->AddToMap(this->ToCreature()); + map->AddToMap(ToCreature()); return true; } @@ -235,7 +237,7 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c break; } - SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped here + SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped here SetCreatorGUID(owner->GetGUID()); InitStatsForLevel(petlevel); @@ -312,11 +314,11 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c } owner->SetMinion(this, true); - map->AddToMap(this->ToCreature()); + map->AddToMap(ToCreature()); InitTalentForLevel(); // set original talents points before spell loading - uint32 timediff = uint32(time(NULL) - fields[14].GetUInt32()); + uint32 timediff = uint32(time(nullptr) - fields[14].GetUInt32()); _LoadAuras(timediff); // load action bar, if data broken will fill later by default spells. @@ -544,7 +546,7 @@ void Pet::Update(uint32 diff) { case CORPSE: { - if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(NULL)) + if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(nullptr)) { Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER! return; @@ -764,7 +766,7 @@ bool Pet::CreateBaseAtCreatureInfo(CreatureTemplate const* cinfo, Unit* owner) bool Pet::CreateBaseAtTamed(CreatureTemplate const* cinfo, Map* map, uint32 phaseMask) { TC_LOG_DEBUG("entities.pet", "Pet::CreateBaseForTamed"); - ObjectGuid::LowType guid=map->GenerateLowGuid(); + ObjectGuid::LowType guid = map->GenerateLowGuid(); uint32 petId = sObjectMgr->GeneratePetNumber(); if (!Create(guid, map, phaseMask, cinfo->Entry, petId)) return false; @@ -1201,7 +1203,7 @@ void Pet::_LoadAuras(uint32 timediff) else remaincharges = 0; - if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, NULL, &baseDamage[0], NULL, caster_guid)) + if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, nullptr, &baseDamage[0], nullptr, caster_guid)) { if (!aura->CanBeSaved()) { @@ -1405,7 +1407,7 @@ bool Pet::addSpell(uint32 spellId, ActiveStates active /*= ACT_DECIDE*/, PetSpel int32 free_points = GetMaxTalentPointsForLevel(getLevel()); m_usedTalentCount += talentCost; // update free talent points - free_points-=m_usedTalentCount; + free_points -= m_usedTalentCount; SetFreeTalentPoints(free_points > 0 ? free_points : 0); } return true; @@ -1421,7 +1423,7 @@ bool Pet::learnSpell(uint32 spell_id) { WorldPacket data(SMSG_PET_LEARNED_SPELL, 4); data << uint32(spell_id); - GetOwner()->GetSession()->SendPacket(&data); + GetOwner()->SendDirectMessage(&data); GetOwner()->PetSpellInitialize(); } return true; @@ -1431,7 +1433,7 @@ void Pet::InitLevelupSpellsForLevel() { uint8 level = getLevel(); - if (PetLevelupSpellSet const* levelupSpells = GetCreatureTemplate()->family ? sSpellMgr->GetPetLevelupSpellList(GetCreatureTemplate()->family) : NULL) + if (PetLevelupSpellSet const* levelupSpells = GetCreatureTemplate()->family ? sSpellMgr->GetPetLevelupSpellList(GetCreatureTemplate()->family) : nullptr) { // PetLevelupSpellSet ordered by levels, process in reversed order for (PetLevelupSpellSet::const_reverse_iterator itr = levelupSpells->rbegin(); itr != levelupSpells->rend(); ++itr) @@ -1474,7 +1476,7 @@ bool Pet::unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab) { WorldPacket data(SMSG_PET_REMOVED_SPELL, 4); data << uint32(spell_id); - GetOwner()->GetSession()->SendPacket(&data); + GetOwner()->SendDirectMessage(&data); } return true; } @@ -1627,7 +1629,7 @@ bool Pet::resetTalents() return true; } -void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* onlinePet /*= NULL*/) +void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* onlinePet /*= nullptr*/) { // not need after this call if (owner->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS)) @@ -1873,7 +1875,7 @@ void Pet::CastPetAura(PetAura const* aura) if (auraId == 35696) // Demonic Knowledge { int32 basePoints = CalculatePct(aura->GetDamage(), GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)); - CastCustomSpell(this, auraId, &basePoints, NULL, NULL, true); + CastCustomSpell(this, auraId, &basePoints, nullptr, nullptr, true); } else CastSpell(this, auraId, true); diff --git a/src/server/game/Entities/Player/CinematicMgr.cpp b/src/server/game/Entities/Player/CinematicMgr.cpp index 4ea1413055d..56a017d1e79 100644 --- a/src/server/game/Entities/Player/CinematicMgr.cpp +++ b/src/server/game/Entities/Player/CinematicMgr.cpp @@ -17,7 +17,9 @@ */ #include "CinematicMgr.h" -#include "Creature.h" +#include "Map.h" +#include "M2Stores.h" +#include "MotionMaster.h" #include "Player.h" #include "TemporarySummon.h" @@ -45,21 +47,20 @@ void CinematicMgr::BeginCinematic() if (m_activeCinematicCameraId == 0) return; - auto itr = sFlyByCameraStore.find(m_activeCinematicCameraId); - if (itr != sFlyByCameraStore.end()) + if (std::vector const* flyByCameras = GetFlyByCameras(m_activeCinematicCameraId)) { // Initialize diff, and set camera m_cinematicDiff = 0; - m_cinematicCamera = &itr->second; + m_cinematicCamera = flyByCameras; auto camitr = m_cinematicCamera->begin(); if (camitr != m_cinematicCamera->end()) { - Position pos(camitr->locations.x, camitr->locations.y, camitr->locations.z, camitr->locations.w); + Position const& pos = camitr->locations; if (!pos.IsPositionValid()) return; - player->GetMap()->LoadGrid(camitr->locations.x, camitr->locations.y); + player->GetMap()->LoadGrid(pos.GetPositionX(), pos.GetPositionY()); m_CinematicObject = player->SummonCreature(VISUAL_WAYPOINT, pos.m_positionX, pos.m_positionY, pos.m_positionZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 5 * MINUTE * IN_MILLISECONDS); if (m_CinematicObject) { @@ -68,11 +69,7 @@ void CinematicMgr::BeginCinematic() } // Get cinematic length - FlyByCameraCollection::const_reverse_iterator camrevitr = m_cinematicCamera->rbegin(); - if (camrevitr != m_cinematicCamera->rend()) - m_cinematicLength = camrevitr->timeStamp; - else - m_cinematicLength = 0; + m_cinematicLength = flyByCameras->back().timeStamp; } } } @@ -110,11 +107,11 @@ void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) { if (cam.timeStamp > m_cinematicDiff) { - nextPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + nextPosition.Relocate(cam.locations); nextTimestamp = cam.timeStamp; break; } - lastPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + lastPosition.Relocate(cam.locations); lastTimestamp = cam.timeStamp; } float angle = lastPosition.GetAngle(&nextPosition); @@ -129,7 +126,7 @@ void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) workDiff += static_cast(float(CINEMATIC_LOOKAHEAD) * cos(angle)); // Get an iterator to the last entry in the cameras, to make sure we don't go beyond the end - FlyByCameraCollection::const_reverse_iterator endItr = m_cinematicCamera->rbegin(); + auto endItr = m_cinematicCamera->rbegin(); if (endItr != m_cinematicCamera->rend() && workDiff > static_cast(endItr->timeStamp)) workDiff = endItr->timeStamp; @@ -142,11 +139,11 @@ void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) { if (static_cast(cam.timeStamp) >= workDiff) { - nextPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + nextPosition.Relocate(cam.locations); nextTimestamp = cam.timeStamp; break; } - lastPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + lastPosition.Relocate(cam.locations); lastTimestamp = cam.timeStamp; } diff --git a/src/server/game/Entities/Player/CinematicMgr.h b/src/server/game/Entities/Player/CinematicMgr.h index 96d6e04b949..f2c0970fb81 100644 --- a/src/server/game/Entities/Player/CinematicMgr.h +++ b/src/server/game/Entities/Player/CinematicMgr.h @@ -21,12 +21,12 @@ #include "Define.h" #include "Object.h" -#include "M2Stores.h" #define CINEMATIC_LOOKAHEAD (2 * IN_MILLISECONDS) #define CINEMATIC_UPDATEDIFF 500 class Player; +struct FlyByCamera; class TC_GAME_API CinematicMgr { @@ -52,7 +52,7 @@ protected: uint32 m_lastCinematicCheck; uint32 m_activeCinematicCameraId; uint32 m_cinematicLength; - FlyByCameraCollection* m_cinematicCamera; + std::vector const* m_cinematicCamera; Position m_remoteSightPosition; TempSummon* m_CinematicObject; }; diff --git a/src/server/game/Entities/Player/EquipmentSet.h b/src/server/game/Entities/Player/EquipmentSet.h new file mode 100644 index 00000000000..779025fbec3 --- /dev/null +++ b/src/server/game/Entities/Player/EquipmentSet.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef EquipmentSet_h__ +#define EquipmentSet_h__ + +#include "Define.h" +#include "ObjectGuid.h" +#include +#include + +enum EquipmentSetUpdateState +{ + EQUIPMENT_SET_UNCHANGED = 0, + EQUIPMENT_SET_CHANGED = 1, + EQUIPMENT_SET_NEW = 2, + EQUIPMENT_SET_DELETED = 3 +}; + +#define EQUIPMENT_SET_SLOTS 19 + +struct EquipmentSetInfo +{ + /// Data sent in EquipmentSet related packets + struct EquipmentSetData + { + uint64 Guid = 0; ///< Set Identifier + uint32 SetID = 0; ///< Index + std::string SetName; + std::string SetIcon; + uint32 IgnoreMask = 0; ///< Mask of EquipmentSlot + std::array Pieces; + } Data; + + /// Server-side data + EquipmentSetUpdateState State = EQUIPMENT_SET_NEW; +}; + +#define MAX_EQUIPMENT_SET_INDEX 10 // client limit + +typedef std::map EquipmentSetContainer; + + +#endif // EquipmentSet_h__ diff --git a/src/server/game/Entities/Player/KillRewarder.cpp b/src/server/game/Entities/Player/KillRewarder.cpp index 61a6277e6cd..b7d714ed5ad 100644 --- a/src/server/game/Entities/Player/KillRewarder.cpp +++ b/src/server/game/Entities/Player/KillRewarder.cpp @@ -270,5 +270,5 @@ void KillRewarder::Reward() if (Creature* victim = _victim->ToCreature()) if (victim->IsDungeonBoss()) if (InstanceScript* instance = _victim->GetInstanceScript()) - instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, _victim->GetEntry(), _victim); + instance->UpdateEncounterStateForKilledCreature(_victim->GetEntry(), _victim); } diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 2394e822efc..f7766a7fcc0 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -21,6 +21,7 @@ #include "AchievementMgr.h" #include "ArenaTeam.h" #include "ArenaTeamMgr.h" +#include "Bag.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "BattlefieldWG.h" @@ -33,6 +34,7 @@ #include "CharacterCache.h" #include "CharacterDatabaseCleaner.h" #include "Chat.h" +#include "CinematicMgr.h" #include "Common.h" #include "ConditionMgr.h" #include "CreatureAI.h" @@ -40,7 +42,9 @@ #include "DisableMgr.h" #include "Formulas.h" #include "GameEventMgr.h" +#include "GameObjectAI.h" #include "GameTime.h" +#include "GitRevision.h" #include "GossipDef.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" @@ -50,33 +54,38 @@ #include "GuildMgr.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" +#include "Item.h" #include "KillRewarder.h" -#include "LFGMgr.h" #include "Language.h" +#include "LFGMgr.h" #include "Log.h" #include "LootItemStorage.h" +#include "LootMgr.h" +#include "Mail.h" #include "MapManager.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "OutdoorPvP.h" #include "OutdoorPvPMgr.h" #include "Pet.h" -#include "PoolMgr.h" #include "PetitionMgr.h" -#include "QueryCallback.h" +#include "PoolMgr.h" +#include "QueryHolder.h" #include "QuestDef.h" +#include "Realm.h" #include "ReputationMgr.h" -#include "GitRevision.h" #include "SkillDiscovery.h" #include "SocialMgr.h" #include "Spell.h" #include "SpellAuraEffects.h" #include "SpellAuras.h" -#include "SpellMgr.h" #include "SpellHistory.h" -#include "Transport.h" +#include "SpellMgr.h" #include "TicketMgr.h" +#include "TradeData.h" +#include "Transport.h" #include "UpdateData.h" #include "UpdateFieldFlags.h" #include "UpdateMask.h" @@ -86,7 +95,6 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "GameObjectAI.h" #define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS) @@ -155,147 +163,6 @@ static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 }; uint32 const MAX_MONEY_AMOUNT = static_cast(std::numeric_limits::max()); -// == PlayerTaxi ================================================ - -PlayerTaxi::PlayerTaxi() -{ - memset(m_taximask, 0, sizeof(m_taximask)); -} - -void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level) -{ - // class specific initial known nodes - switch (chrClass) - { - case CLASS_DEATH_KNIGHT: - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - m_taximask[i] |= sOldContinentsNodesMask[i]; - break; - } - } - - // race specific initial known nodes: capital and taxi hub masks - switch (race) - { - case RACE_HUMAN: SetTaximaskNode(2); break; // Human - case RACE_ORC: SetTaximaskNode(23); break; // Orc - case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf - case RACE_NIGHTELF: SetTaximaskNode(26); - SetTaximaskNode(27); break; // Night Elf - case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead - case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren - case RACE_GNOME: SetTaximaskNode(6); break; // Gnome - case RACE_TROLL: SetTaximaskNode(23); break; // Troll - case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf - case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei - } - - // new continent starting masks (It will be accessible only at new map) - switch (Player::TeamForRace(race)) - { - case ALLIANCE: SetTaximaskNode(100); break; - case HORDE: SetTaximaskNode(99); break; - } - // level dependent taxi hubs - if (level >= 68) - SetTaximaskNode(213); //Shattered Sun Staging Area -} - -void PlayerTaxi::LoadTaxiMask(std::string const &data) -{ - Tokenizer tokens(data, ' '); - - uint8 index = 0; - for (Tokenizer::const_iterator iter = tokens.begin(); index < TaxiMaskSize && iter != tokens.end(); ++iter, ++index) - { - // load and set bits only for existing taxi nodes - m_taximask[index] = sTaxiNodesMask[index] & atoul(*iter); - } -} - -void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) -{ - if (all) - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - data << uint32(sTaxiNodesMask[i]); // all existing nodes - } - else - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - data << uint32(m_taximask[i]); // known nodes - } -} - -bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, uint32 team) -{ - ClearTaxiDestinations(); - - Tokenizer Tokenizer(values, ' '); - - for (Tokenizer::const_iterator iter = Tokenizer.begin(); iter != Tokenizer.end(); ++iter) - { - uint32 node = atoul(*iter); - AddTaxiDestination(node); - } - - if (m_TaxiDestinations.empty()) - return true; - - // Check integrity - if (m_TaxiDestinations.size() < 2) - return false; - - for (size_t i = 1; i < m_TaxiDestinations.size(); ++i) - { - uint32 cost; - uint32 path; - sObjectMgr->GetTaxiPath(m_TaxiDestinations[i-1], m_TaxiDestinations[i], path, cost); - if (!path) - return false; - } - - // can't load taxi path without mount set (quest taxi path?) - if (!sObjectMgr->GetTaxiMountDisplayId(GetTaxiSource(), team, true)) - return false; - - return true; -} - -std::string PlayerTaxi::SaveTaxiDestinationsToString() -{ - if (m_TaxiDestinations.empty()) - return ""; - - std::ostringstream ss; - - for (size_t i=0; i < m_TaxiDestinations.size(); ++i) - ss << m_TaxiDestinations[i] << ' '; - - return ss.str(); -} - -uint32 PlayerTaxi::GetCurrentTaxiPath() const -{ - if (m_TaxiDestinations.size() < 2) - return 0; - - uint32 path; - uint32 cost; - - sObjectMgr->GetTaxiPath(m_TaxiDestinations[0], m_TaxiDestinations[1], path, cost); - - return path; -} - -std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi) -{ - for (uint8 i = 0; i < TaxiMaskSize; ++i) - ss << taxi.m_taximask[i] << ' '; - return ss; -} - Player::Player(WorldSession* session): Unit(true) { m_speakTime = 0; @@ -544,7 +411,7 @@ Player::Player(WorldSession* session): Unit(true) Player::~Player() { // it must be unloaded already in PlayerLogout and accessed only for logged in player - //m_social = NULL; + //m_social = nullptr; // Note: buy back item already deleted from DB when player was saved for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i) @@ -846,7 +713,7 @@ bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) InventoryResult msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount); if (msg == EQUIP_ERR_OK) { - StoreNewItem(sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id)); + StoreNewItem(sDest, titem_id, true, GenerateItemRandomPropertyId(titem_id)); return true; // stored } @@ -871,7 +738,7 @@ void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 Curre data << Regen; data << (uint8)0; data << (uint32)0; // spell id - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::StopMirrorTimer(MirrorTimerType Type) @@ -879,7 +746,7 @@ void Player::StopMirrorTimer(MirrorTimerType Type) m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER; WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4); data << (uint32)Type; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::IsImmuneToEnvironmentalDamage() const @@ -933,7 +800,7 @@ uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage) DurabilityLossAll(0.10f, false); // durability lost message WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0); - GetSession()->SendPacket(&data2); + SendDirectMessage(&data2); } UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type); @@ -1003,14 +870,14 @@ void Player::HandleDrowning(uint32 time_diff) } else // If activated - do tick { - m_MirrorTimer[BREATH_TIMER]-=time_diff; + m_MirrorTimer[BREATH_TIMER] -= time_diff; // Timer limit - need deal damage if (m_MirrorTimer[BREATH_TIMER] < 0) { - m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[BREATH_TIMER] += 1 * IN_MILLISECONDS; // Calculate and deal damage /// @todo Check this formula - uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); + uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel() - 1); EnvironmentalDamage(DAMAGE_DROWNING, damage); } else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need @@ -1021,7 +888,7 @@ void Player::HandleDrowning(uint32 time_diff) { int32 UnderWaterTime = getMaxTimer(BREATH_TIMER); // Need breath regen - m_MirrorTimer[BREATH_TIMER]+=10*time_diff; + m_MirrorTimer[BREATH_TIMER] += 10 * time_diff; if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !IsAlive()) StopMirrorTimer(BREATH_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER) @@ -1039,14 +906,14 @@ void Player::HandleDrowning(uint32 time_diff) } else { - m_MirrorTimer[FATIGUE_TIMER]-=time_diff; + m_MirrorTimer[FATIGUE_TIMER] -= time_diff; // Timer limit - need deal damage or teleport ghost to graveyard if (m_MirrorTimer[FATIGUE_TIMER] < 0) { - m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[FATIGUE_TIMER] += 1 * IN_MILLISECONDS; if (IsAlive()) // Calculate and deal damage { - uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); + uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel() - 1); EnvironmentalDamage(DAMAGE_EXHAUSTED, damage); } else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard @@ -1059,7 +926,7 @@ void Player::HandleDrowning(uint32 time_diff) else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer { int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER); - m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff; + m_MirrorTimer[FATIGUE_TIMER] += 10 * time_diff; if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !IsAlive()) StopMirrorTimer(FATIGUE_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER) @@ -1076,7 +943,7 @@ void Player::HandleDrowning(uint32 time_diff) m_MirrorTimer[FIRE_TIMER] -= time_diff; if (m_MirrorTimer[FIRE_TIMER] < 0) { - m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[FIRE_TIMER] += 1 * IN_MILLISECONDS; // Calculate and deal damage /// @todo Check this formula uint32 damage = urand(600, 700); @@ -1093,13 +960,15 @@ void Player::HandleDrowning(uint32 time_diff) m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER; // Recheck timers flag - m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS; - for (uint8 i = 0; i< MAX_TIMERS; ++i) + m_MirrorTimerFlags &= ~UNDERWATER_EXIST_TIMERS; + for (uint8 i = 0; i < MAX_TIMERS; ++i) + { if (m_MirrorTimer[i] != DISABLED_MIRROR_TIMER) { - m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS; + m_MirrorTimerFlags |= UNDERWATER_EXIST_TIMERS; break; } + } m_MirrorTimerFlagsLast = m_MirrorTimerFlags; } @@ -1714,7 +1583,7 @@ bool Player::BuildEnumData(PreparedQueryResult result, WorldPacket* data) continue; } - SpellItemEnchantmentEntry const* enchant = NULL; + SpellItemEnchantmentEntry const* enchant = nullptr; uint32 enchants = GetUInt32ValueFromArray(equipment, visualBase + 1); for (uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot) @@ -1877,7 +1746,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati return false; // far teleport to another map - Map* oldmap = IsInWorld() ? GetMap() : NULL; + Map* oldmap = IsInWorld() ? GetMap() : nullptr; // check if we can enter before stopping combat / removing pet / totems / interrupting spells // Check enter rights before map getting to avoid creating instance copy for player @@ -1955,7 +1824,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati if (Transport* transport = GetTransport()) data << transport->GetEntry() << GetMapId(); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } // remove from old map now @@ -1976,7 +1845,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati else data << m_teleport_dest.PositionXYZOStream(); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendSavedInstances(); } @@ -1990,7 +1859,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati return true; } -bool Player::TeleportTo(WorldLocation const &loc, uint32 options /*= 0*/) +bool Player::TeleportTo(WorldLocation const& loc, uint32 options /*= 0*/) { return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options); } @@ -2107,6 +1976,13 @@ void Player::RemoveFromWorld() } } +void Player::SetObjectScale(float scale) +{ + Unit::SetObjectScale(scale); + SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, scale * DEFAULT_PLAYER_BOUNDING_RADIUS); + SetFloatValue(UNIT_FIELD_COMBATREACH, scale * DEFAULT_PLAYER_COMBAT_REACH); +} + bool Player::IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index, Unit* caster) const { // players are immune to taunt (the aura and the spell effect) @@ -2457,7 +2333,7 @@ void Player::SetInWater(bool apply) getHostileRefManager().updateThreatTables(); } -bool Player::IsInAreaTriggerRadius(const AreaTriggerEntry* trigger) const +bool Player::IsInAreaTriggerRadius(AreaTriggerEntry const* trigger) const { if (!trigger || GetMapId() != trigger->mapid) return false; @@ -2615,7 +2491,7 @@ void Player::UninviteFromGroup() } } -void Player::RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method /* = GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /* = ObjectGuid::Empty */, const char* reason /* = NULL */) +void Player::RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= ObjectGuid::Empty*/, char const* reason /*= nullptr*/) { if (!group) return; @@ -2639,7 +2515,7 @@ void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool re } data << uint8(recruitAFriend ? 1 : 0); // does the GivenXP include a RaF bonus? - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::GiveXP(uint32 xp, Unit* victim, float group_rate) @@ -2726,7 +2602,7 @@ void Player::GiveLevel(uint8 level) for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4) data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i))); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr->GetXPForLevel(level)); @@ -3023,7 +2899,7 @@ void Player::SendInitialSpells() GetSpellHistory()->WritePacket(data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::RemoveMail(uint32 id) @@ -3052,7 +2928,7 @@ void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResp data << (uint32) item_guid; // item guid low? data << (uint32) item_count; // item count? } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendNewMail() const @@ -3060,7 +2936,7 @@ void Player::SendNewMail() const // deliver undelivered mail WorldPacket data(SMSG_RECEIVED_MAIL, 4); data << (uint32) 0; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::UpdateNextMailTimeAndUnreads() @@ -3276,7 +3152,7 @@ bool Player::AddSpell(uint32 spellId, bool active, bool learning, bool dependent { WorldPacket data(SMSG_REMOVED_SPELL, 4); data << uint32(spellId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -3577,7 +3453,7 @@ void Player::LearnSpell(uint32 spell_id, bool dependent, uint32 fromSkill /*= 0* WorldPacket data(SMSG_LEARNED_SPELL, 6); data << uint32(spell_id); data << uint16(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } // learn all disabled higher ranks and required spells (recursive) @@ -3758,7 +3634,7 @@ void Player::RemoveSpell(uint32 spell_id, bool disabled, bool learn_low_rank) // learnSpell(prev_id, false); } // if ranked non-stackable spell: need activate lesser rank and update dendence state - /// No need to check for spellInfo != NULL here because if cur_active is true, then that means that the spell was already in m_spells, and only valid spells can be pushed there. + /// No need to check for spellInfo != nullptr here because if cur_active is true, then that means that the spell was already in m_spells, and only valid spells can be pushed there. else if (cur_active && !spellInfo->IsStackableWithRanks() && spellInfo->IsRanked()) { // need manually update dependence state (learn spell ignore like attempts) @@ -3803,7 +3679,7 @@ void Player::RemoveSpell(uint32 spell_id, bool disabled, bool learn_low_rank) { WorldPacket data(SMSG_REMOVED_SPELL, 4); data << uint32(spell_id); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -3943,7 +3819,7 @@ bool Player::ResetTalents(bool no_cost) // skip non-existing talent ranks if (talentInfo->RankID[rank] == 0) continue; - const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]); + SpellInfo const* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]); if (!_spellEntry) continue; RemoveSpell(talentInfo->RankID[rank], true); @@ -3972,14 +3848,14 @@ bool Player::ResetTalents(bool no_cost) UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1); m_resetTalentsCost = cost; - m_resetTalentsTime = time(NULL); + m_resetTalentsTime = time(nullptr); } /* when prev line will dropped use next line if (Pet* pet = GetPet()) { if (pet->getPetType() == HUNTER_PET && !pet->GetCreatureTemplate()->IsTameable(CanTameExoticPets())) - RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); } */ @@ -4022,7 +3898,7 @@ void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) c } for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { - if (m_items[i] == NULL) + if (m_items[i] == nullptr) continue; m_items[i]->BuildCreateUpdateBlockForPlayer(data, target); @@ -4055,7 +3931,7 @@ void Player::DestroyForPlayer(Player* target, bool onDeath) const } for (uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i) { - if (m_items[i] == NULL) + if (m_items[i] == nullptr) continue; m_items[i]->DestroyForPlayer(target); @@ -4590,7 +4466,7 @@ void Player::SetMovement(PlayerMovementType pType) } data << GetPackGUID(); data << uint32(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /* Preconditions: @@ -4601,7 +4477,7 @@ void Player::BuildPlayerRepop() { WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size()); data << GetPackGUID(); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (getRace() == RACE_NIGHTELF) CastSpell(this, 20584, true); @@ -4661,7 +4537,7 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) data << float(0); data << float(0); data << float(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // speed change, land walk @@ -5087,13 +4963,13 @@ void Player::RepopAtGraveyard() // Special handle for battleground maps if (Battleground* bg = GetBattleground()) - ClosestGrave = bg->GetClosestGraveYard(this); + ClosestGrave = bg->GetClosestGraveyard(this); else { if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(GetZoneId())) - ClosestGrave = bf->GetClosestGraveYard(this); + ClosestGrave = bf->GetClosestGraveyard(this); else - ClosestGrave = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()); + ClosestGrave = sObjectMgr->GetClosestGraveyard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()); } // stop countdown until repop @@ -5108,10 +4984,8 @@ void Player::RepopAtGraveyard() { WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap data << ClosestGrave->map_id; - data << ClosestGrave->x; - data << ClosestGrave->y; - data << ClosestGrave->z; - GetSession()->SendPacket(&data); + data << TaggedPosition(ClosestGrave->x, ClosestGrave->y, ClosestGrave->z); + SendDirectMessage(&data); } } else if (GetPositionZ() < GetMap()->GetMinHeight(GetPositionX(), GetPositionY())) @@ -5477,8 +5351,8 @@ float Player::GetSpellCritFromIntellect() const if (critBase == nullptr || critRatio == nullptr) return 0.0f; - float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio; - return crit*100.0f; + float crit = critBase->base + GetStat(STAT_INTELLECT) * critRatio->ratio; + return crit * 100.0f; } float Player::GetRatingMultiplier(CombatRating cr) const @@ -5526,7 +5400,7 @@ float Player::OCTRegenHPPerSpirit() const GtOCTRegenHPEntry const* baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); GtRegenHPPerSptEntry const* moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1); - if (baseRatio == NULL || moreRatio == NULL) + if (baseRatio == nullptr || moreRatio == nullptr) return 0.0f; // Formula from PaperDollFrame script @@ -5699,6 +5573,11 @@ void Player::SetRegularAttackTime() } } +void Player::StoreRaidMapDifficulty() +{ + m_raidMapDifficulty = GetMap()->GetDifficulty(); +} + //skill+step, checking for max value bool Player::UpdateSkill(uint32 skill_id, uint32 step) { @@ -6320,7 +6199,7 @@ void Player::SendActionButtons(uint32 state) const } } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } @@ -6450,7 +6329,7 @@ bool Player::UpdatePosition(float x, float y, float z, float orientation, bool t void Player::SendMessageToSetInRange(WorldPacket const* data, float dist, bool self) { if (self) - GetSession()->SendPacket(data); + SendDirectMessage(data); Trinity::MessageDistDeliverer notifier(this, data, dist); Cell::VisitWorldObjects(this, notifier, dist); @@ -6459,7 +6338,7 @@ void Player::SendMessageToSetInRange(WorldPacket const* data, float dist, bool s void Player::SendMessageToSetInRange(WorldPacket const* data, float dist, bool self, bool own_team_only) { if (self) - GetSession()->SendPacket(data); + SendDirectMessage(data); Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only); Cell::VisitWorldObjects(this, notifier, dist); @@ -6468,7 +6347,7 @@ void Player::SendMessageToSetInRange(WorldPacket const* data, float dist, bool s void Player::SendMessageToSet(WorldPacket const* data, Player const* skipped_rcvr) { if (skipped_rcvr != this) - GetSession()->SendPacket(data); + SendDirectMessage(data); // we use World::GetMaxVisibleDistance() because i cannot see why not use a distance // update: replaced by GetMap()->GetVisibilityDistance() @@ -6931,7 +6810,7 @@ bool Player::RewardHonor(Unit* victim, uint32 groupsize, int32 honor, bool pvpto data << uint64(victim_guid); data << uint32(victim_rank); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // add honor points ModifyHonorPoints(honor); @@ -7218,7 +7097,7 @@ void Player::CheckDuelDistance(time_t currTime) duel->outOfBound = currTime; WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } else @@ -7228,7 +7107,7 @@ void Player::CheckDuelDistance(time_t currTime) duel->outOfBound = 0; WorldPacket data(SMSG_DUEL_INBOUNDS, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } else if (currTime >= (duel->outOfBound+10)) DuelComplete(DUEL_FLED); @@ -7258,10 +7137,10 @@ void Player::DuelComplete(DuelCompleteType type) WorldPacket data(SMSG_DUEL_COMPLETE, (1)); data << (uint8)((type != DUEL_INTERRUPTED) ? 1 : 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (duel->opponent->GetSession()) - duel->opponent->GetSession()->SendPacket(&data); + duel->opponent->SendDirectMessage(&data); if (type != DUEL_INTERRUPTED) { @@ -7408,7 +7287,7 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply if (slot >= INVENTORY_SLOT_BAG_END || !proto) return; - ScalingStatDistributionEntry const* ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL; + ScalingStatDistributionEntry const* ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : nullptr; if (only_level_scale && !ssd) return; @@ -7417,7 +7296,7 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply if (ssd && ssd_level > ssd->MaxLevel) ssd_level = ssd->MaxLevel; - ScalingStatValuesEntry const* ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL; + ScalingStatValuesEntry const* ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : nullptr; if (only_level_scale && !ssv) return; @@ -7960,8 +7839,8 @@ void Player::UpdateEquipSpellsAtFormChange() 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 + ApplyEquipSpell(spellInfo, nullptr, false, true); // remove spells that not fit to form + ApplyEquipSpell(spellInfo, nullptr, true, true); // add spells that fit form but not active } } } @@ -8112,7 +7991,7 @@ void Player::CastItemCombatSpell(DamageInfo const& damageInfo, Item* item, ItemT } // Apply spell mods - ApplySpellMod(pEnchant->spellid[s], chance); + ApplySpellMod(pEnchant->spellid[s], SPELLMOD_CHANCE_OF_SUCCESS, chance); // Shiv has 100% chance to apply the poison if (FindCurrentSpellBySpellId(5938) && e_slot == TEMP_ENCHANTMENT_SLOT) @@ -8157,7 +8036,7 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 if (!spellInfo) { TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: %u) has wrong spell id %u, ignoring.", proto->ItemId, learn_spell_id); - SendEquipError(EQUIP_ERR_NONE, item, NULL); + SendEquipError(EQUIP_ERR_NONE, item, nullptr); return; } @@ -8363,7 +8242,7 @@ void Player::_ApplyAmmoBonuses() UpdateDamagePhysical(RANGED_ATTACK); } -bool Player::CheckAmmoCompatibility(const ItemTemplate* ammo_proto) const +bool Player::CheckAmmoCompatibility(ItemTemplate const* ammo_proto) const { if (!ammo_proto) return false; @@ -8817,14 +8696,14 @@ void Player::SendLootError(ObjectGuid guid, LootError error) const void Player::SendNotifyLootMoneyRemoved() const { WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendNotifyLootItemRemoved(uint8 lootSlot) const { WorldPacket data(SMSG_LOOT_REMOVED, 1); data << uint8(lootSlot); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendUpdateWorldState(uint32 Field, uint32 Value) const @@ -8832,7 +8711,7 @@ void Player::SendUpdateWorldState(uint32 Field, uint32 Value) const WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8); data << Field; data << Value; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) @@ -9457,7 +9336,7 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) uint16 length = (data.wpos() - countPos) / 8; data.put(countPos, length); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendBGWeekendWorldStates(); SendBattlefieldWorldStates(); } @@ -9508,7 +9387,7 @@ void Player::SetBindPoint(ObjectGuid guid) const { WorldPacket data(SMSG_BINDER_CONFIRM, 8); data << uint64(guid); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendTalentWipeConfirm(ObjectGuid guid) const @@ -9517,7 +9396,7 @@ void Player::SendTalentWipeConfirm(ObjectGuid guid) const data << uint64(guid); uint32 cost = sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : ResetTalentsCost(); data << cost; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::ResetPetTalents() @@ -9956,7 +9835,7 @@ Item* Player::GetItemByPos(uint8 bag, uint8 slot) const Item* Player::GetUseableItemByPos(uint8 bag, uint8 slot) const { if (!CanUseAttackType(GetAttackBySlot(slot))) - return NULL; + return nullptr; return GetItemByPos(bag, slot); } @@ -10290,7 +10169,7 @@ bool Player::HasGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, return false; } -InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count /*= NULL*/, uint32* itemLimitCategory /*= NULL*/) const +InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count /*= nullptr*/, uint32* itemLimitCategory /*= nullptr*/) const { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry); if (!pProto) @@ -10346,7 +10225,12 @@ InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item return EQUIP_ERR_OK; } -InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= NULL*/) const +InventoryResult Player::CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory /*= nullptr*/) const +{ + return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem, nullptr, itemLimitCategory); +} + +InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= nullptr*/) const { return CanStoreItem(bag, slot, dest, item, count, nullptr, false, no_space_count); } @@ -11898,7 +11782,7 @@ void Player::SetAmmo(uint32 item) InventoryResult msg = CanUseAmmo(item); if (msg != EQUIP_ERR_OK) { - SendEquipError(msg, NULL, NULL, item); + SendEquipError(msg, nullptr, nullptr, item); return; } } @@ -11919,7 +11803,7 @@ void Player::RemoveAmmo() } // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case. -Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId, AllowedLooterSet const& allowedLooters) +Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId, GuidSet const& allowedLooters) { uint32 count = 0; for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr) @@ -11943,10 +11827,10 @@ Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update // save data std::ostringstream ss; - AllowedLooterSet::const_iterator itr = allowedLooters.begin(); + GuidSet::const_iterator itr = allowedLooters.begin(); ss << *itr; for (++itr; itr != allowedLooters.end(); ++itr) - ss << ' ' << *itr; + ss << ' ' << itr->GetCounter(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE); stmt->setUInt32(0, pItem->GetGUID().GetCounter()); @@ -12010,7 +11894,7 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) pItem->SetBinding(true); - Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? NULL : GetBagByPos(bag); + Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? nullptr : GetBagByPos(bag); if (!pBag) { m_items[slot] = pItem; @@ -12138,7 +12022,7 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) GetSpellHistory()->AddGlobalCooldown(spellProto, m_weaponChangeTimer); WorldPacket data; GetSpellHistory()->BuildCooldownPacket(data, SPELL_COOLDOWN_FLAG_INCLUDE_GCD, cooldownSpell, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } } @@ -12369,7 +12253,7 @@ void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) ItemRemovedQuestCheck(it->GetEntry(), it->GetCount()); RemoveItem(bag, slot, update); it->SetNotRefundable(this, false); - it->RemoveFromUpdateQueueOf(this); + RemoveItemFromUpdateQueueOf(it, this); if (it->IsInWorld()) { it->RemoveFromWorld(); @@ -13403,7 +13287,7 @@ void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint break; } } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param) const @@ -13414,7 +13298,7 @@ void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 if (param > 0) data << uint32(param); data << uint8(msg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, uint32 param) const @@ -13425,7 +13309,7 @@ void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid, if (param > 0) data << uint32(param); data << uint8(msg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::IsUseEquipedWeapon(bool mainhand) const @@ -13543,7 +13427,7 @@ void Player::UpdateItemDuration(uint32 time, bool realtimeonly) void Player::UpdateEnchantTime(uint32 time) { - for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr=next) + for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next) { ASSERT(itr->item); next = itr; @@ -14125,7 +14009,7 @@ void Player::SendNewItem(Item* item, uint32 count, bool received, bool created, if (broadcast && GetGroup()) GetGroup()->BroadcastPacket(&data, true); else - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /*********************************************************/ @@ -14640,7 +14524,7 @@ void Player::SendPreparedQuest(ObjectGuid guid) title = gossiptext->Options[0].Text_0; LocaleConstant localeConstant = GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid)) ObjectMgr::GetLocaleString(nl->Text_0[0], localeConstant, title); } @@ -14649,7 +14533,7 @@ void Player::SendPreparedQuest(ObjectGuid guid) title = gossiptext->Options[0].Text_1; LocaleConstant localeConstant = GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid)) ObjectMgr::GetLocaleString(nl->Text_1[0], localeConstant, title); } @@ -15124,7 +15008,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, ItemPosCountVec dest; if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardChoiceItemCount[reward]) == EQUIP_ERR_OK) { - Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); SendNewItem(item, quest->RewardChoiceItemCount[reward], true, false); } } @@ -15139,7 +15023,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, ItemPosCountVec dest; if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardItemIdCount[i]) == EQUIP_ERR_OK) { - Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); SendNewItem(item, quest->RewardItemIdCount[i], true, false); } else if (quest->IsDFQuest()) @@ -15193,7 +15077,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, if (quest->GetBonusTalents()) { - m_questRewardTalentCount+=quest->GetBonusTalents(); + m_questRewardTalentCount += quest->GetBonusTalents(); InitTalentForLevel(); } @@ -15414,7 +15298,7 @@ bool Player::SatisfyQuestLog(bool msg) const if (msg) { WorldPacket data(SMSG_QUESTLOG_FULL, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } return false; } @@ -16656,7 +16540,7 @@ void Player::SendQuestComplete(uint32 quest_id) const { WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4); data << uint32(quest_id); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -16681,7 +16565,7 @@ void Player::SendQuestReward(Quest const* quest, uint32 XP) const data << uint32(10 * quest->CalculateHonorGain(GetQuestLevel(quest))); data << uint32(quest->GetBonusTalents()); // bonus talents data << uint32(quest->GetRewArenaPoints()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendQuestFailed(uint32 questId, InventoryResult reason) const @@ -16691,7 +16575,7 @@ void Player::SendQuestFailed(uint32 questId, InventoryResult reason) const WorldPacket data(SMSG_QUESTGIVER_QUEST_FAILED, 4 + 4); data << uint32(questId); data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message) - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -16701,7 +16585,7 @@ void Player::SendQuestTimerFailed(uint32 quest_id) const { WorldPacket data(SMSG_QUESTUPDATE_FAILEDTIMER, 4); data << uint32(quest_id); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER"); } } @@ -16710,26 +16594,26 @@ void Player::SendCanTakeQuestResponse(QuestFailedReason msg) const { WorldPacket data(SMSG_QUESTGIVER_QUEST_INVALID, 4); data << uint32(msg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID"); } -void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver) const +void Player::SendQuestConfirmAccept(Quest const* quest, Player* pReceiver) const { if (pReceiver) { std::string strTitle = quest->GetTitle(); LocaleConstant localeConstant = pReceiver->GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) - if (const QuestLocale* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId())) + if (localeConstant != LOCALE_enUS) + if (QuestLocale const* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId())) ObjectMgr::GetLocaleString(pLocale->Title, localeConstant, strTitle); WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8)); data << uint32(quest->GetQuestId()); data << strTitle; data << uint64(GetGUID()); - pReceiver->GetSession()->SendPacket(&data); + pReceiver->SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT"); } @@ -16753,7 +16637,7 @@ void Player::SendQuestUpdateAddItem(Quest const* /*quest*/, uint32 /*item_idx*/, TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM"); //data << quest->RequiredItemId[item_idx]; //data << count; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, ObjectGuid guid, uint32 creatureOrGO_idx, uint16 old_count, uint16 add_count) @@ -16772,7 +16656,7 @@ void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, ObjectGuid guid, data << uint32(old_count + add_count); data << uint32(quest->RequiredNpcOrGoCount[ creatureOrGO_idx ]); data << uint64(guid); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); uint16 log_slot = FindQuestSlot(quest->GetQuestId()); if (log_slot < MAX_QUEST_LOG_SIZE) @@ -16787,7 +16671,7 @@ void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint data << uint32(quest->GetQuestId()); data << uint32(old_count + add_count); data << uint32(quest->GetPlayersSlain()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); uint16 log_slot = FindQuestSlot(quest->GetQuestId()); if (log_slot < MAX_QUEST_LOG_SIZE) @@ -16835,7 +16719,7 @@ void Player::SendQuestGiverStatusMultiple() } data.put(0, count); // write real count - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::HasPvPForcingQuest() const @@ -16925,30 +16809,27 @@ void Player::_LoadEquipmentSets(PreparedQueryResult result) if (!result) return; - uint32 count = 0; do { Field* fields = result->Fetch(); - EquipmentSet eqSet; + EquipmentSetInfo eqSet; - eqSet.Guid = fields[0].GetUInt64(); - uint8 index = fields[1].GetUInt8(); - eqSet.Name = fields[2].GetString(); - eqSet.IconName = fields[3].GetString(); - eqSet.IgnoreMask = fields[4].GetUInt32(); - eqSet.state = EQUIPMENT_SET_UNCHANGED; + eqSet.Data.Guid = fields[0].GetUInt64(); + eqSet.Data.SetID = fields[1].GetUInt8(); + eqSet.Data.SetName = fields[2].GetString(); + eqSet.Data.SetIcon = fields[3].GetString(); + eqSet.Data.IgnoreMask = fields[4].GetUInt32(); + eqSet.State = EQUIPMENT_SET_UNCHANGED; for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) - eqSet.Items[i] = fields[5+i].GetUInt32(); + if (ObjectGuid::LowType guid = fields[5 + i].GetUInt32()) + eqSet.Data.Pieces[i] = ObjectGuid::Create(guid); - m_EquipmentSets[index] = eqSet; - - ++count; + if (eqSet.Data.SetID >= MAX_EQUIPMENT_SET_INDEX) // client limit + continue; - if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit - break; - } - while (result->NextRow()); + _equipmentSets[eqSet.Data.Guid] = eqSet; + } while (result->NextRow()); } void Player::_LoadBGData(PreparedQueryResult result) @@ -17766,7 +17647,7 @@ bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) return true; } -bool Player::isAllowedToLoot(const Creature* creature) +bool Player::isAllowedToLoot(Creature const* creature) { if (!creature->isDead() || !creature->IsDamageEnoughForLootingAndReward()) return false; @@ -17774,7 +17655,7 @@ bool Player::isAllowedToLoot(const Creature* creature) if (HasPendingBind()) return false; - const Loot* loot = &creature->loot; + Loot const* loot = &creature->loot; if (loot->isLooted()) // nothing to loot or everything looted. return false; if (!loot->hasItemForAll() && !loot->hasItemFor(this)) // no loot in creature for this player @@ -18172,9 +18053,9 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { std::string strGUID = (*result)[0].GetString(); Tokenizer GUIDlist(strGUID, ' '); - AllowedLooterSet looters; + GuidSet looters; for (Tokenizer::const_iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr) - looters.insert(atol(*itr)); + looters.insert(ObjectGuid::Create(uint32(strtoul(*itr, nullptr, 10)))); if (looters.size() > 1 && item->GetTemplate()->GetMaxStackSize() == 1 && item->IsSoulBound()) { @@ -18750,7 +18631,7 @@ InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty InstanceSave* Player::GetInstanceSave(uint32 mapid, bool raid) { InstancePlayerBind* pBind = GetBoundInstance(mapid, GetDifficulty(raid)); - InstanceSave* pSave = pBind ? pBind->save : NULL; + InstanceSave* pSave = pBind ? pBind->save : nullptr; if (!pBind || !pBind->perm) if (Group* group = GetGroup()) if (InstanceGroupBind* groupBind = group->GetBoundInstance(GetDifficulty(raid), mapid)) @@ -18856,12 +18737,12 @@ InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, B void Player::BindToInstance() { InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(_pendingBindId); - if (!mapSave) //it seems sometimes mapSave is NULL, but I did not check why + if (!mapSave) //it seems sometimes mapSave is nullptr, but I did not check why return; WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4); data << uint32(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (!IsGameMaster()) { BindToInstance(mapSave, true, EXTEND_STATE_KEEP); @@ -18908,7 +18789,7 @@ void Player::SendRaidInfo() } } data.put(p_counter, counter); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /* @@ -18934,7 +18815,7 @@ void Player::SendSavedInstances() //Send opcode 811. true or false means, whether you have current raid/heroic instances data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP); data << uint32(hasBeenSaved); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (!hasBeenSaved) return; @@ -18947,7 +18828,7 @@ void Player::SendSavedInstances() { data.Initialize(SMSG_UPDATE_LAST_INSTANCE); data << uint32(itr->second.save->GetMapId()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } } @@ -19195,6 +19076,8 @@ void Player::SaveToDB(bool create /*=false*/) stmt->setUInt32(0, GetGUID().GetCounter()); trans->Append(stmt); + auto finiteAlways = [](float f) { return std::isfinite(f) ? f : 0.0f; }; + if (create) { //! Insert query @@ -20211,7 +20094,7 @@ bool Player::CanSpeak() const void Player::SendAttackSwingNotInRange() const { WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGuid guid, SQLTransaction& trans) @@ -20258,25 +20141,25 @@ void Player::Customize(CharacterCustomizeInfo const* customizeInfo, SQLTransacti void Player::SendAttackSwingDeadTarget() const { WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAttackSwingCantAttack() const { WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAttackSwingCancelAttack() const { WorldPacket data(SMSG_CANCEL_COMBAT, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAttackSwingBadFacingAttack() const { WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAutoRepeatCancel(Unit* target) @@ -20291,7 +20174,7 @@ void Player::SendExplorationExperience(uint32 Area, uint32 Experience) const WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8); data << uint32(Area); data << uint32(Experience); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendDungeonDifficulty(bool IsInGroup) const @@ -20301,7 +20184,7 @@ void Player::SendDungeonDifficulty(bool IsInGroup) const data << (uint32)GetDungeonDifficulty(); data << uint32(val); data << uint32(IsInGroup); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) const @@ -20311,14 +20194,14 @@ void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) const data << uint32(forcedDifficulty == -1 ? GetRaidDifficulty() : forcedDifficulty); data << uint32(val); data << uint32(IsInGroup); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendResetFailedNotify(uint32 mapid) const { WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4); data << uint32(mapid); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /// Reset all solo instances and optionally send a message on success for each @@ -20332,7 +20215,7 @@ void Player::ResetInstances(uint8 method, bool isRaid) for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();) { InstanceSave* p = itr->second.save; - const MapEntry* entry = sMapStore.LookupEntry(itr->first); + MapEntry const* entry = sMapStore.LookupEntry(itr->first); if (!entry || entry->IsRaid() != isRaid || !p->CanReset()) { ++itr; @@ -20374,7 +20257,7 @@ void Player::SendResetInstanceSuccess(uint32 MapId) const { WorldPacket data(SMSG_INSTANCE_RESET, 4); data << uint32(MapId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) const @@ -20387,7 +20270,7 @@ void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) const WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4); data << uint32(reason); data << uint32(MapId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /*********************************************************/ @@ -20544,7 +20427,7 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_PET); @@ -20659,14 +20542,14 @@ void Player::Whisper(std::string const& text, Language language, Player* target, WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, Language(language), this, this, _text); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); // rest stuff shouldn't happen in case of addon message if (isAddonMessage) return; ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER_INFORM, Language(language), target, target, _text); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (!isAcceptWhispers() && !IsGameMaster() && !target->IsGameMaster()) { @@ -20702,7 +20585,7 @@ void Player::Whisper(uint32 textId, Player* target, bool /*isBossWhisper = false Item* Player::GetMItem(uint32 id) { ItemMap::const_iterator itr = mMitems.find(id); - return itr != mMitems.end() ? itr->second : NULL; + return itr != mMitems.end() ? itr->second : nullptr; } void Player::AddMItem(Item* it) @@ -20720,7 +20603,7 @@ bool Player::RemoveMItem(uint32 id) void Player::SendOnCancelExpectedVehicleRideAura() const { WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::PetSpellInitialize() @@ -20769,7 +20652,7 @@ void Player::PetSpellInitialize() //Cooldowns pet->GetSpellHistory()->WritePacket(data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::PossessSpellInitialize() @@ -20797,7 +20680,7 @@ void Player::PossessSpellInitialize() data << uint8(0); // spells count data << uint8(0); // cooldowns count - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::VehicleSpellInitialize() @@ -20848,7 +20731,7 @@ void Player::VehicleSpellInitialize() // Cooldowns vehicle->GetSpellHistory()->WritePacket(data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::CharmSpellInitialize() @@ -20903,14 +20786,14 @@ void Player::CharmSpellInitialize() data << uint8(0); // cooldowns count - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendRemoveControlBar() const { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell) @@ -20929,6 +20812,120 @@ bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod return spellInfo->IsAffectedBySpellMod(mod); } +template +void Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell /*= nullptr*/) const +{ + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); + if (!spellInfo) + return; + + float totalmul = 1.0f; + int32 totalflat = 0; + + // Drop charges for triggering spells instead of triggered ones + if (m_spellModTakingSpell) + spell = m_spellModTakingSpell; + + switch (op) + { + // special case, if a mod makes spell instant, only consume that mod + case SPELLMOD_CASTING_TIME: + { + SpellModifier* modInstantSpell = nullptr; + for (SpellModifier* mod : m_spellMods[op]) + { + if (!IsAffectedBySpellmod(spellInfo, mod, spell)) + continue; + + if (mod->type == SPELLMOD_PCT && basevalue < T(10000) && mod->value <= -100) + { + modInstantSpell = mod; + break; + } + } + + if (modInstantSpell) + { + Player::ApplyModToSpell(modInstantSpell, spell); + basevalue = T(0); + return; + } + break; + } + // special case if two mods apply 100% critical chance, only consume one + case SPELLMOD_CRITICAL_CHANCE: + { + SpellModifier* modCritical = nullptr; + for (SpellModifier* mod : m_spellMods[op]) + { + if (!IsAffectedBySpellmod(spellInfo, mod, spell)) + continue; + + if (mod->type == SPELLMOD_FLAT && mod->value >= 100) + { + modCritical = mod; + break; + } + } + + if (modCritical) + { + Player::ApplyModToSpell(modCritical, spell); + basevalue = T(100); + return; + } + break; + } + default: + break; + } + + for (SpellModifier* mod : m_spellMods[op]) + { + if (!IsAffectedBySpellmod(spellInfo, mod, spell)) + continue; + + switch (mod->type) + { + case SPELLMOD_FLAT: + totalflat += mod->value; + break; + case SPELLMOD_PCT: + { + // skip percent mods with 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 (op == SPELLMOD_CASTING_TIME && mod->value <= -100 && basevalue >= T(10000)) + continue; + else if (!Player::HasSpellModApplied(mod, spell)) + { + // special case for Surge of Light, don't apply critical chance reduction if other mods not applied (ie procs while casting another spell) + // (Surge of Light is the only PCT_MOD on critical chance) + if (op == SPELLMOD_CRITICAL_CHANCE) + continue; + // special case for Backdraft, dont' apply GCD reduction if cast time reduction wasn't applied (ie when Backlash is consumed first) + // (Backdraft is the only PCT_MOD on global cooldown) + else if (op == SPELLMOD_GLOBAL_COOLDOWN) + continue; + } + + totalmul += CalculatePct(1.0f, mod->value); + break; + } + } + + Player::ApplyModToSpell(mod, spell); + } + + basevalue = T(float(basevalue + totalflat) * totalmul); +} + +template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, int32& basevalue, Spell* spell) const; +template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, uint32& basevalue, Spell* spell) const; +template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, float& basevalue, Spell* spell) const; + void Player::AddSpellMod(SpellModifier* mod, bool apply) { TC_LOG_DEBUG("spells", "Player::AddSpellMod: Player '%s' (%s), SpellID: %d", GetName().c_str(), GetGUID().ToString().c_str(), mod->spellId); @@ -21003,7 +21000,7 @@ void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) const { WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4); data << uint8(itemClass) << uint32(itemSubclassMask); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::RemovePetitionsAndSigns(ObjectGuid guid, CharterTypes type) @@ -21422,7 +21419,7 @@ inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 c data << uint32(vendorslot + 1); // numbered from 1 at client data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF); data << uint32(count); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendNewItem(it, pProto->BuyCount * count, true, false, false); if (!bStore) @@ -21643,7 +21640,7 @@ void Player::UpdateHomebindTime(uint32 time) WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); data << uint32(0); data << uint32(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } // instance is valid, reset homebind timer m_HomebindTimer = 0; @@ -21666,7 +21663,7 @@ void Player::UpdateHomebindTime(uint32 time) WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); data << uint32(m_HomebindTimer); data << uint32(1); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("maps", "Player::UpdateHomebindTime: Player '%s' (%s) will be teleported to homebind in 60 seconds", GetName().c_str(), GetGUID().ToString().c_str()); } @@ -21958,7 +21955,7 @@ void Player::SetBattlegroundEntryPoint() // If map is dungeon find linked graveyard if (GetMap()->IsDungeon()) { - if (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam())) + if (WorldSafeLocsEntry const* entry = sObjectMgr->GetClosestGraveyard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam())) m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f); else TC_LOG_ERROR("entities.player", "Player::SetBattlegroundEntryPoint: Dungeon (MapID: %u) has no linked graveyard, setting home location as entry point.", GetMapId()); @@ -22109,7 +22106,7 @@ bool Player::IsAlwaysDetectableFor(WorldObject const* seer) const if (Unit::IsAlwaysDetectableFor(seer)) return true; - if (const Player* seerPlayer = seer->ToPlayer()) + if (Player const* seerPlayer = seer->ToPlayer()) if (IsGroupVisibleFor(seerPlayer)) return !(seerPlayer->duel && seerPlayer->duel->startTime != 0 && seerPlayer->duel->opponent == this); @@ -22250,7 +22247,7 @@ void Player::UpdateTriggerVisibility() return; udata.BuildPacket(&packet); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } void Player::SendInitialVisiblePackets(Unit* target) const @@ -22398,7 +22395,7 @@ void Player::SendComboPoints() data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1); data << combotarget->GetPackGUID(); data << uint8(m_comboPoints); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -22496,7 +22493,7 @@ void Player::SendInitialPacketsBeforeAddToMap() data << m_homebindX << m_homebindY << m_homebindZ; data << (uint32) m_homebindMapId; data << (uint32) m_homebindAreaId; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // SMSG_SET_PROFICIENCY // SMSG_SET_PCT_SPELL_MODIFIER @@ -22509,13 +22506,13 @@ void Player::SendInitialPacketsBeforeAddToMap() data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4); data << uint32(GetMap()->GetDifficulty()); data << uint32(GetMap()->GetEntry()->IsDynamicDifficultyMap() && GetMap()->IsHeroic()); // Raid dynamic difficulty - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendInitialSpells(); data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4); data << uint32(0); // count, for (count) uint32; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendInitialActionButtons(); m_reputationMgr->SendInitialReputations(); @@ -22527,7 +22524,7 @@ void Player::SendInitialPacketsBeforeAddToMap() data.AppendPackedTime(GameTime::GetGameTime()); data << float(0.01666667f); // game speed data << uint32(0); // added in 3.1.2 - GetSession()->SendPacket(&data); + SendDirectMessage(&data); GetReputationMgr().SendForceReactions(); // SMSG_SET_FORCED_REACTIONS @@ -22591,11 +22588,11 @@ void Player::SendInitialPacketsAfterAddToMap() if (GetMap()->GetDifficulty() != GetRaidDifficulty()) { StoreRaidMapDifficulty(); - SendRaidDifficulty(GetGroup() != NULL, GetStoredRaidDifficulty()); + SendRaidDifficulty(GetGroup() != nullptr, GetStoredRaidDifficulty()); } } else if (GetRaidDifficulty() != GetStoredRaidDifficulty()) - SendRaidDifficulty(GetGroup() != NULL); + SendRaidDifficulty(GetGroup() != nullptr); if (GetPlayerSharingQuest()) { @@ -22635,7 +22632,7 @@ void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 default: break; } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const @@ -22663,7 +22660,7 @@ void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint3 data << uint8(0); // is locked data << uint8(0); // is extended, ignored if prev field is 0 } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::ApplyEquipCooldown(Item* pItem) @@ -22705,7 +22702,7 @@ void Player::ApplyEquipCooldown(Item* pItem) WorldPacket data(SMSG_ITEM_COOLDOWN, 8 + 4); data << uint64(pItem->GetGUID()); data << uint32(spellData.SpellId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -22998,7 +22995,7 @@ void Player::SendAurasForTarget(Unit* target) const auraApp->BuildUpdatePacket(data, false); } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SetDailyQuestStatus(uint32 quest_id) @@ -23246,6 +23243,11 @@ float Player::GetReputationPriceDiscount(Creature const* creature) const return 1.0f - 0.05f* (rank - REP_NEUTRAL); } +Player* Player::GetTrader() const +{ + return m_trade ? m_trade->GetTrader() : nullptr; +} + bool Player::IsSpellFitByClassAndRace(uint32 spell_id) const { uint32 racemask = getRaceMask(); @@ -23353,7 +23355,7 @@ void Player::UpdateForQuestWorldObjects() } } udata.BuildPacket(&packet); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } bool Player::HasSummonPending() const @@ -23381,7 +23383,7 @@ void Player::SendSummonRequestFrom(Unit* summoner) data << uint64(summoner->GetGUID()); // summoner guid data << uint32(summoner->GetZoneId()); // summoner zone data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SummonIfPossible(bool agree) @@ -23635,7 +23637,7 @@ bool Player::GetsRecruitAFriendBonus(bool forXP) bool recruitAFriend = false; if (getLevel() <= sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL) || !forXP) { - if (Group* group = this->GetGroup()) + if (Group* group = GetGroup()) { for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { @@ -23709,7 +23711,7 @@ bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const if (!pRewardSource || !IsInMap(pRewardSource)) return false; - const WorldObject* player = GetCorpse(); + WorldObject const* player = GetCorpse(); if (!player || IsAlive()) player = this; @@ -23724,7 +23726,7 @@ bool Player::IsAtRecruitAFriendDistance(WorldObject const* pOther) const if (!pOther || !IsInMap(pOther)) return false; - const WorldObject* player = GetCorpse(); + WorldObject const* player = GetCorpse(); if (!player || IsAlive()) player = this; @@ -23796,7 +23798,7 @@ void Player::SetClientControl(Unit* target, bool allowMove) WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1); data << target->GetPackGUID(); data << uint8(allowMove ? 1 : 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (this != target) SetViewpoint(target, allowMove); @@ -23928,7 +23930,7 @@ void Player::SendCorpseReclaimDelay(uint32 delay) const { WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4); data << uint32(delay); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } Player* Player::GetNextRandomRaidMember(float radius) @@ -24182,7 +24184,7 @@ void Player::SetViewpoint(WorldObject* target, bool apply) SetSeer(this); //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0); - //GetSession()->SendPacket(&data); + //SendDirectMessage(&data); } // HACK: Make sure update for PLAYER_FARSIGHT is received before SMSG_PET_SPELLS to properly hide "Release spirit" dialog @@ -24196,7 +24198,7 @@ void Player::SetViewpoint(WorldObject* target, bool apply) for (UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter) { iter->second.BuildPacket(&packet); - iter->first->GetSession()->SendPacket(&packet); + iter->first->SendDirectMessage(&packet); packet.clear(); } } @@ -24336,6 +24338,11 @@ bool Player::HasTitle(uint32 bitIndex) const return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } +bool Player::HasTitle(CharTitlesEntry const* title) const +{ + return HasTitle(title->bit_index); +} + void Player::SetTitle(CharTitlesEntry const* title, bool lost) { uint32 fieldIndexOffset = title->bit_index / 32; @@ -24359,7 +24366,7 @@ void Player::SetTitle(CharTitlesEntry const* title, bool lost) WorldPacket data(SMSG_TITLE_EARNED, 4 + 4); data << uint32(title->bit_index); data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } uint32 Player::GetRuneBaseCooldown(uint8 index) @@ -24445,7 +24452,7 @@ void Player::ConvertRune(uint8 index, RuneType newType) WorldPacket data(SMSG_CONVERT_RUNE, 2); data << uint8(index); data << uint8(newType); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::ResyncRunes(uint8 count) const @@ -24457,14 +24464,14 @@ void Player::ResyncRunes(uint8 count) const data << uint8(GetCurrentRune(i)); // rune type data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255) } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::AddRunePower(uint8 index) const { WorldPacket data(SMSG_ADD_RUNE_POWER, 4); data << uint32(1 << index); // mask (0x00-0x3F probably) - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } static RuneType runeSlotTypes[MAX_RUNES] = @@ -24576,7 +24583,7 @@ void Player::StoreLootItem(uint8 lootSlot, Loot* loot) InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item->itemid, item->count); if (msg == EQUIP_ERR_OK) { - AllowedLooterSet looters = item->GetAllowedLooters(); + GuidSet looters = item->GetAllowedLooters(); Item* newitem = StoreNewItem(dest, item->itemid, true, item->randomPropertyId, looters); if (qitem) @@ -24935,7 +24942,7 @@ void Player::ResetAchievementCriteria(AchievementCriteriaCondition condition, ui m_achievementMgr->ResetAchievementCriteria(condition, value, evenIfCriteriaComplete); } -void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) +void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= nullptr*/) { m_achievementMgr->UpdateAchievementCriteria(type, miscValue1, miscValue2, unit); } @@ -25011,7 +25018,7 @@ void Player::LearnTalent(uint32 talentId, uint32 talentRank) uint32 tTab = talentInfo->TalentTab; if (talentInfo->Row > 0) for (uint32 i = 0; i < sTalentStore.GetNumRows(); i++) // Loop through all talents. - if (const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i)) // the way talents are tracked + if (TalentEntry const* tmpTalent = sTalentStore.LookupEntry(i)) // the way talents are tracked if (tmpTalent->TalentTab == tTab) for (uint8 rank = 0; rank < MAX_TALENT_RANK; rank++) if (tmpTalent->RankID[rank] != 0) @@ -25135,7 +25142,7 @@ void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRa for (uint32 i = 0; i < numRows; ++i) // Loop through all talents. { // Someday, someone needs to revamp - const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i); + TalentEntry const* tmpTalent = sTalentStore.LookupEntry(i); if (tmpTalent) // the way talents are tracked { if (tmpTalent->TalentTab == tTab) @@ -25398,7 +25405,7 @@ void Player::SendTalentsInfoData(bool pet) BuildPetTalentsInfoData(&data); else BuildPlayerTalentsInfoData(&data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::BuildEnchantmentsInfoData(WorldPacket* data) @@ -25447,123 +25454,112 @@ void Player::BuildEnchantmentsInfoData(WorldPacket* data) void Player::SendEquipmentSetList() { uint32 count = 0; - WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4); + WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 1000); // guess size size_t count_pos = data.wpos(); data << uint32(count); // count placeholder - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) + + for (EquipmentSetContainer::value_type const& eqSet : _equipmentSets) { - if (itr->second.state == EQUIPMENT_SET_DELETED) + if (eqSet.second.State == EQUIPMENT_SET_DELETED) continue; - data.appendPackGUID(itr->second.Guid); - data << uint32(itr->first); - data << itr->second.Name; - data << itr->second.IconName; + data.appendPackGUID(eqSet.first); + data << uint32(eqSet.second.Data.SetID); + data << eqSet.second.Data.SetName; + data << eqSet.second.Data.SetIcon; + for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { // ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HighGuid::Item - if (itr->second.IgnoreMask & (1 << i)) + if (eqSet.second.Data.IgnoreMask & (1 << i)) data.appendPackGUID(uint64(1)); - else if (itr->second.Items[i] > 0) // send proper data (do not append 0 with high guid) - data << ObjectGuid(HighGuid::Item, 0, itr->second.Items[i]).WriteAsPacked(); else - data.appendPackGUID(uint64(0)); + data.appendPackGUID(eqSet.second.Data.Pieces[i]); } ++count; // client have limit but it checked at loading and set } data.put(count_pos, count); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } -void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset) +void Player::SetEquipmentSet(EquipmentSetInfo::EquipmentSetData const& eqSet) { - if (eqset.Guid != 0) + if (eqSet.Guid != 0) { - bool found = false; - - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) - { - if ((itr->second.Guid == eqset.Guid) && (itr->first == index)) - { - found = true; - break; - } - } - - if (!found) // something wrong... + // something wrong... + auto itr = _equipmentSets.find(eqSet.Guid); + if (itr == _equipmentSets.end() || itr->second.Data.Guid != eqSet.Guid) { TC_LOG_ERROR("entities.player", "Player::SetEquipmentSet: Player '%s' (%s) tried to save nonexistent equipment set " UI64FMTD " (index: %u)", - GetName().c_str(), GetGUID().ToString().c_str(), eqset.Guid, index); + GetName().c_str(), GetGUID().ToString().c_str(), eqSet.Guid, eqSet.SetID); return; } } - EquipmentSet& eqslot = m_EquipmentSets[index]; - - EquipmentSetUpdateState old_state = eqslot.state; + EquipmentSetInfo& eqSlot = _equipmentSets[eqSet.Guid]; - eqslot = eqset; + EquipmentSetUpdateState oldState = eqSlot.State; + eqSlot.Data = eqSet; - if (eqset.Guid == 0) + if (eqSet.Guid == 0) { - eqslot.Guid = sObjectMgr->GenerateEquipmentSetGuid(); + eqSlot.Data.Guid = sObjectMgr->GenerateEquipmentSetGuid(); WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1); - data << uint32(index); - data.appendPackGUID(eqslot.Guid); - GetSession()->SendPacket(&data); + data << uint32(eqSlot.Data.SetID); + data.appendPackGUID(eqSlot.Data.Guid); + SendDirectMessage(&data); } - eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED; + eqSlot.State = (oldState == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED); } void Player::_SaveEquipmentSets(SQLTransaction& trans) { - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();) + for (EquipmentSetContainer::iterator itr = _equipmentSets.begin(); itr != _equipmentSets.end();) { - uint32 index = itr->first; - EquipmentSet& eqset = itr->second; - PreparedStatement* stmt = nullptr; + EquipmentSetInfo& eqSet = itr->second; + PreparedStatement* stmt; uint8 j = 0; - switch (eqset.state) + switch (eqSet.State) { case EQUIPMENT_SET_UNCHANGED: ++itr; break; // nothing do case EQUIPMENT_SET_CHANGED: stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EQUIP_SET); - stmt->setString(j++, eqset.Name.c_str()); - stmt->setString(j++, eqset.IconName.c_str()); - stmt->setUInt32(j++, eqset.IgnoreMask); - for (uint8 i=0; isetUInt32(j++, eqset.Items[i]); + stmt->setString(j++, eqSet.Data.SetName); + stmt->setString(j++, eqSet.Data.SetIcon); + stmt->setUInt32(j++, eqSet.Data.IgnoreMask); + for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) + stmt->setUInt32(j++, eqSet.Data.Pieces[i].GetCounter()); stmt->setUInt32(j++, GetGUID().GetCounter()); - stmt->setUInt64(j++, eqset.Guid); - stmt->setUInt32(j, index); + stmt->setUInt64(j++, eqSet.Data.Guid); + stmt->setUInt32(j, eqSet.Data.SetID); trans->Append(stmt); - eqset.state = EQUIPMENT_SET_UNCHANGED; + eqSet.State = EQUIPMENT_SET_UNCHANGED; ++itr; break; case EQUIPMENT_SET_NEW: stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET); stmt->setUInt32(j++, GetGUID().GetCounter()); - stmt->setUInt64(j++, eqset.Guid); - stmt->setUInt32(j++, index); - stmt->setString(j++, eqset.Name.c_str()); - stmt->setString(j++, eqset.IconName.c_str()); - stmt->setUInt32(j++, eqset.IgnoreMask); - for (uint8 i=0; isetUInt32(j++, eqset.Items[i]); + stmt->setUInt64(j++, eqSet.Data.Guid); + stmt->setUInt32(j++, eqSet.Data.SetID); + stmt->setString(j++, eqSet.Data.SetName); + stmt->setString(j++, eqSet.Data.SetIcon); + stmt->setUInt32(j++, eqSet.Data.IgnoreMask); + for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) + stmt->setUInt32(j++, eqSet.Data.Pieces[i].GetCounter()); trans->Append(stmt); - eqset.state = EQUIPMENT_SET_UNCHANGED; + eqSet.State = EQUIPMENT_SET_UNCHANGED; ++itr; break; case EQUIPMENT_SET_DELETED: stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EQUIP_SET); - stmt->setUInt64(0, eqset.Guid); + stmt->setUInt64(0, eqSet.Data.Guid); trans->Append(stmt); - m_EquipmentSets.erase(itr++); + itr = _equipmentSets.erase(itr); break; } } @@ -25592,16 +25588,17 @@ void Player::_SaveBGData(SQLTransaction& trans) void Player::DeleteEquipmentSet(uint64 setGuid) { - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) + for (EquipmentSetContainer::iterator itr = _equipmentSets.begin(); itr != _equipmentSets.end();) { - if (itr->second.Guid == setGuid) + if (itr->second.Data.Guid == setGuid) { - if (itr->second.state == EQUIPMENT_SET_NEW) - m_EquipmentSets.erase(itr); + if (itr->second.State == EQUIPMENT_SET_NEW) + itr = _equipmentSets.erase(itr); else - itr->second.state = EQUIPMENT_SET_DELETED; + itr->second.State = EQUIPMENT_SET_DELETED; break; } + ++itr; } } @@ -25626,7 +25623,7 @@ void Player::ResetMap() // after decrement+unlink, ++m_mapRefIter will continue correctly // when the first element of the list is being removed // nocheck_prev will return the padding element of the RefManager - // instead of NULL in the case of prev + // instead of nullptr in the case of prev GetMap()->UpdateIteratorBack(this); Unit::ResetMap(); GetMapRef().unlink(); @@ -25698,7 +25695,7 @@ void Player::_LoadTalents(PreparedQueryResult result) void Player::_SaveTalents(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i) { @@ -25824,7 +25821,7 @@ void Player::ActivateSpec(uint8 spec) if (GetPet()) GetPet()->RemoveAllAurasOnDeath();*/ - //RemoveAllAuras(GetGUID(), NULL, false, true); // removes too many auras + //RemoveAllAuras(GetGUID(), nullptr, false, true); // removes too many auras //ExitVehicle(); // should be impossible to switch specs from inside a vehicle.. // Let client clear his current Actions @@ -25854,7 +25851,7 @@ void Player::ActivateSpec(uint8 spec) if (talentInfo->RankID[rank] == 0) continue; RemoveSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells.. - if (const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank])) + if (SpellInfo const* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank])) for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellInfo for valid trigger spells if (_spellEntry->Effects[i].TriggerSpell > 0 && _spellEntry->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL) RemoveSpell(_spellEntry->Effects[i].TriggerSpell, true); // and remove any spells that the talent teaches @@ -25973,7 +25970,7 @@ void Player::SendTimeSync() { WorldPacket data(SMSG_TIME_SYNC_REQ, 4); data << uint32(m_timeSyncCounter++); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // Schedule next sync in 10 sec m_timeSyncTimer = 10000; @@ -25998,7 +25995,7 @@ void Player::SendDuelCountdown(uint32 counter) { WorldPacket data(SMSG_DUEL_COUNTDOWN, 4); data << uint32(counter); // seconds - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::AddRefundReference(ObjectGuid it) @@ -26050,7 +26047,7 @@ void Player::SendRefundInfo(Item* item) } data << uint32(0); data << uint32(GetTotalPlayedTime() - item->GetPlayedTime()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::AddItem(uint32 itemId, uint32 count) @@ -26068,7 +26065,7 @@ bool Player::AddItem(uint32 itemId, uint32 count) return false; } - Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); if (item) SendNewItem(item, count, true, false); else @@ -26090,7 +26087,7 @@ void Player::RefundItem(Item* item) WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4); data << uint64(item->GetGUID()); // Guid data << uint32(10); // Error! - GetSession()->SendPacket(&data); + SendDirectMessage(&data); return; } @@ -26131,7 +26128,7 @@ void Player::RefundItem(Item* item) WorldPacket data(SMSG_ITEM_REFUND_RESULT, 8+4); data << uint64(item->GetGUID()); // Guid data << uint32(10); // Error! - GetSession()->SendPacket(&data); + SendDirectMessage(&data); return; } @@ -26146,7 +26143,7 @@ void Player::RefundItem(Item* item) data << uint32(iece->reqitem[i]); data << uint32(iece->reqitemcount[i]); } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); uint32 moneyRefund = item->GetPaidMoney(); // item-> will be invalidated in DestroyItem @@ -26443,7 +26440,7 @@ void Player::SetInGuild(uint32 guildId) Guild* Player::GetGuild() { uint32 guildId = GetGuildId(); - return guildId ? sGuildMgr->GetGuildById(guildId) : NULL; + return guildId ? sGuildMgr->GetGuildById(guildId) : nullptr; } Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 duration) @@ -26563,7 +26560,7 @@ void Player::SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const { WorldPacket data(SMSG_SUPERCEDED_SPELL, 8); data << uint32(oldSpell) << uint32(newSpell); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::ValidateAppearance(uint8 race, uint8 class_, uint8 gender, uint8 hairID, uint8 hairColor, uint8 faceID, uint8 facialHair, uint8 skinColor, bool create /*=false*/) diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 99e5f37ee7b..8120c4bc531 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -19,46 +19,63 @@ #ifndef _PLAYER_H #define _PLAYER_H -#include "DBCStores.h" +#include "Unit.h" +#include "DatabaseEnvFwd.h" +#include "DBCEnums.h" +#include "EquipmentSet.h" #include "GroupReference.h" +#include "ItemDefines.h" +#include "ItemEnchantmentMgr.h" #include "MapReference.h" - -#include "Item.h" #include "PetDefines.h" +#include "PlayerTaxi.h" #include "QuestDef.h" -#include "SpellMgr.h" -#include "SpellHistory.h" -#include "Unit.h" -#include "TradeData.h" -#include "CinematicMgr.h" - -#include -#include -#include +#include +struct AccessRequirement; +struct AchievementEntry; +struct AreaTableEntry; +struct AreaTriggerEntry; +struct BarberShopStyleEntry; +struct CharacterCustomizeInfo; +struct CharTitlesEntry; +struct ChatChannelsEntry; struct CreatureTemplate; +struct FactionEntry; +struct ItemSetEffect; +struct ItemTemplate; +struct Loot; struct Mail; +struct ScalingStatValuesEntry; struct TrainerSpell; struct VendorItem; class AchievementMgr; -class ReputationMgr; +class Bag; +class Battleground; +class CinematicMgr; class Channel; class CharacterCreateInfo; class Creature; class DynamicObject; class Group; class Guild; +class Item; +class LootStore; class OutdoorPvP; class Pet; class PetAura; +class PlayerAI; class PlayerMenu; class PlayerSocial; +class ReputationMgr; class SpellCastTargets; -class UpdateMask; -class PlayerAI; +class TradeData; -struct CharacterCustomizeInfo; +enum InventoryType : uint8; +enum ItemClass : uint8; +enum LootError : uint8; +enum LootType : uint8; typedef std::deque PlayerMails; @@ -203,81 +220,6 @@ struct ActionButton typedef std::map ActionButtonList; -struct PlayerCreateInfoItem -{ - PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) { } - - uint32 item_id; - uint32 item_amount; -}; - -typedef std::list PlayerCreateInfoItems; - -struct PlayerClassLevelInfo -{ - PlayerClassLevelInfo() : basehealth(0), basemana(0) { } - uint16 basehealth; - uint16 basemana; -}; - -struct PlayerClassInfo -{ - PlayerClassInfo() : levelInfo(NULL) { } - - PlayerClassLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1 -}; - -struct PlayerLevelInfo -{ - PlayerLevelInfo() { for (uint8 i=0; i < MAX_STATS; ++i) stats[i] = 0; } - - uint8 stats[MAX_STATS]; -}; - -typedef std::list PlayerCreateInfoSpells; - -struct PlayerCreateInfoAction -{ - PlayerCreateInfoAction() : button(0), type(0), action(0) { } - PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) { } - - uint8 button; - uint8 type; - uint32 action; -}; - -typedef std::list PlayerCreateInfoActions; - -struct PlayerCreateInfoSkill -{ - uint16 SkillId; - uint16 Rank; -}; - -typedef std::list PlayerCreateInfoSkills; - -struct PlayerInfo -{ - // existence checked by displayId != 0 - PlayerInfo() : mapId(0), areaId(0), positionX(0.0f), positionY(0.0f), positionZ(0.0f), orientation(0.0f), displayId_m(0), displayId_f(0), levelInfo(nullptr) { } - - uint32 mapId; - uint32 areaId; - float positionX; - float positionY; - float positionZ; - float orientation; - uint16 displayId_m; - uint16 displayId_f; - PlayerCreateInfoItems item; - PlayerCreateInfoSpells customSpells; - PlayerCreateInfoSpells castSpells; - PlayerCreateInfoActions action; - PlayerCreateInfoSkills skills; - - PlayerLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1 -}; - struct PvPInfo { PvPInfo() : IsHostile(false), IsInHostileArea(false), IsInNoPvPArea(false), IsInFFAPvPArea(false), EndTimer(0) { } @@ -655,34 +597,6 @@ enum CurrencyTokenSlots // 32 slots CURRENCYTOKEN_SLOT_END = 150 }; -enum EquipmentSetUpdateState -{ - EQUIPMENT_SET_UNCHANGED = 0, - EQUIPMENT_SET_CHANGED = 1, - EQUIPMENT_SET_NEW = 2, - EQUIPMENT_SET_DELETED = 3 -}; - -struct EquipmentSet -{ - EquipmentSet() : Guid(0), IgnoreMask(0), state(EQUIPMENT_SET_NEW) - { - for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) - Items[i] = 0; - } - - uint64 Guid; - std::string Name; - std::string IconName; - uint32 IgnoreMask; - uint32 Items[EQUIPMENT_SLOT_END]; - EquipmentSetUpdateState state; -}; - -#define MAX_EQUIPMENT_SET_INDEX 10 // client limit - -typedef std::map EquipmentSets; - struct ItemPosCount { ItemPosCount(uint16 _pos, uint32 _count) : pos(_pos), count(_count) { } @@ -862,19 +776,6 @@ struct InstancePlayerBind InstancePlayerBind() : save(nullptr), perm(false), extendState(EXTEND_STATE_NORMAL) { } }; -struct AccessRequirement -{ - uint8 levelMin; - uint8 levelMax; - uint16 item_level; - uint32 item; - uint32 item2; - uint32 quest_A; - uint32 quest_H; - uint32 achievement; - std::string questFailedText; -}; - enum CharDeleteMethod { CHAR_DELETE_REMOVE = 0, // Completely remove from the database @@ -923,61 +824,6 @@ enum PlayerCommandStates CHEAT_WATERWALK = 0x10 }; -class TC_GAME_API PlayerTaxi -{ - public: - PlayerTaxi(); - ~PlayerTaxi() { } - // Nodes - void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level); - void LoadTaxiMask(std::string const& data); - - bool IsTaximaskNodeKnown(uint32 nodeidx) const - { - uint8 field = uint8((nodeidx - 1) / 32); - uint32 submask = 1 << ((nodeidx-1) % 32); - return (m_taximask[field] & submask) == submask; - } - bool SetTaximaskNode(uint32 nodeidx) - { - uint8 field = uint8((nodeidx - 1) / 32); - uint32 submask = 1 << ((nodeidx - 1) % 32); - if ((m_taximask[field] & submask) != submask) - { - m_taximask[field] |= submask; - return true; - } - else - return false; - } - void AppendTaximaskTo(ByteBuffer& data, bool all); - - // Destinations - bool LoadTaxiDestinationsFromString(std::string const& values, uint32 team); - std::string SaveTaxiDestinationsToString(); - - void ClearTaxiDestinations() { m_TaxiDestinations.clear(); } - void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } - uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); } - uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; } - uint32 GetCurrentTaxiPath() const; - uint32 NextTaxiDestination() - { - m_TaxiDestinations.pop_front(); - return GetTaxiDestination(); - } - - std::deque const& GetPath() const { return m_TaxiDestinations; } - bool empty() const { return m_TaxiDestinations.empty(); } - - friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); - private: - TaxiMask m_taximask; - std::deque m_TaxiDestinations; -}; - -std::ostringstream& operator << (std::ostringstream& ss, PlayerTaxi const& taxi); - class Player; /// Holder for Battleground data @@ -1033,8 +879,8 @@ class TC_GAME_API Player : public Unit, public GridObject { friend class WorldSession; friend class CinematicMgr; - friend void Item::AddToUpdateQueueOf(Player* player); - friend void Item::RemoveFromUpdateQueueOf(Player* player); + friend void AddItemToUpdateQueueOf(Item* item, Player* player); + friend void RemoveItemFromUpdateQueueOf(Item* item, Player* player); public: explicit Player(WorldSession* session); ~Player(); @@ -1046,15 +892,10 @@ class TC_GAME_API Player : public Unit, public GridObject void AddToWorld() override; void RemoveFromWorld() override; - void SetObjectScale(float scale) override - { - Unit::SetObjectScale(scale); - SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, scale * DEFAULT_PLAYER_BOUNDING_RADIUS); - SetFloatValue(UNIT_FIELD_COMBATREACH, scale * DEFAULT_PLAYER_COMBAT_REACH); - } + void SetObjectScale(float scale) override; bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0); - bool TeleportTo(WorldLocation const &loc, uint32 options = 0); + bool TeleportTo(WorldLocation const& loc, uint32 options = 0); bool TeleportToBGEntryPoint(); bool HasSummonPending() const; @@ -1074,7 +915,7 @@ class TC_GAME_API Player : public Unit, public GridObject bool IsInWater() const override { return m_isInWater; } bool IsUnderWater() const override; bool IsFalling() { return GetPositionZ() < m_lastFallZ; } - bool IsInAreaTriggerRadius(const AreaTriggerEntry* trigger) const; + bool IsInAreaTriggerRadius(AreaTriggerEntry const* trigger) const; void SendInitialPacketsBeforeAddToMap(); void SendInitialPacketsAfterAddToMap(); @@ -1209,8 +1050,8 @@ class TC_GAME_API Player : public Unit, public GridObject bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasItemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; - InventoryResult CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory = NULL) const { return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem, NULL, itemLimitCategory); } - InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, uint32* itemLimitCategory = NULL) const { return CanTakeMoreSimilarItems(entry, count, NULL, NULL, itemLimitCategory); } + InventoryResult CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory = nullptr) const; + InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, uint32* itemLimitCategory = nullptr) const { return CanTakeMoreSimilarItems(entry, count, nullptr, nullptr, itemLimitCategory); } InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = nullptr) const; InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const; InventoryResult CanStoreItems(Item** items, int count, uint32* itemLimitCategory) const; @@ -1227,7 +1068,7 @@ class TC_GAME_API Player : public Unit, public GridObject InventoryResult CanUseItem(ItemTemplate const* pItem) const; InventoryResult CanUseAmmo(uint32 item) const; InventoryResult CanRollForItemInLFG(ItemTemplate const* item, WorldObject const* lootedObject) const; - Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0, AllowedLooterSet const& allowedLooters = AllowedLooterSet()); + Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0, GuidSet const& allowedLooters = GuidSet()); Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update); Item* EquipNewItem(uint16 pos, uint32 item, bool update); Item* EquipItem(uint16 pos, Item* pItem, bool update); @@ -1237,7 +1078,7 @@ class TC_GAME_API Player : public Unit, public GridObject void AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast = false) { AutoStoreLoot(NULL_BAG, NULL_SLOT, loot_id, store, broadcast); } void StoreLootItem(uint8 lootSlot, Loot* loot); - InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = NULL, uint32* itemLimitCategory = NULL) const; + InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = nullptr, uint32* itemLimitCategory = nullptr) const; InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = nullptr, bool swap = false, uint32* no_space_count = nullptr) const; void AddRefundReference(ObjectGuid it); @@ -1247,7 +1088,7 @@ class TC_GAME_API Player : public Unit, public GridObject void SetAmmo(uint32 item); void RemoveAmmo(); float GetAmmoDPS() const { return m_ammoDPS; } - bool CheckAmmoCompatibility(const ItemTemplate* ammo_proto) const; + bool CheckAmmoCompatibility(ItemTemplate const* ammo_proto) const; void QuickEquipItem(uint16 pos, Item* pItem); void VisualizeItem(uint8 slot, Item* pItem); void SetVisibleItemSlot(uint8 slot, Item* pItem); @@ -1285,7 +1126,7 @@ class TC_GAME_API Player : public Unit, public GridObject float GetReputationPriceDiscount(Creature const* creature) const; - Player* GetTrader() const { return m_trade ? m_trade->GetTrader() : nullptr; } + Player* GetTrader() const; TradeData* GetTradeData() const { return m_trade; } void TradeCancel(bool sendback); @@ -1616,8 +1457,8 @@ class TC_GAME_API Player : public Unit, public GridObject void AddSpellMod(SpellModifier* mod, bool apply); static bool IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell = nullptr); - template - void ApplySpellMod(uint32 spellId, T& basevalue, Spell* spell = nullptr) const; + template + void ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell = nullptr) const; static void ApplyModToSpell(SpellModifier* mod, Spell* spell); static bool HasSpellModApplied(SpellModifier* mod, Spell* spell); void SetSpellModTakingSpell(Spell* spell, bool apply); @@ -1659,7 +1500,7 @@ class TC_GAME_API Player : public Unit, public GridObject PvPInfo pvpInfo; void UpdatePvPState(bool onlyFFA = false); void SetPvP(bool state) override; - void UpdatePvP(bool state, bool override=false); + void UpdatePvP(bool state, bool override = false); void UpdateZone(uint32 newZone, uint32 newArea); void UpdateArea(uint32 newArea); void SetNeedsZoneUpdate(bool needsUpdate) { m_needsZoneUpdate = needsUpdate; } @@ -1684,7 +1525,7 @@ class TC_GAME_API Player : public Unit, public GridObject bool IsInSameGroupWith(Player const* p) const; bool IsInSameRaidWith(Player const* p) const; void UninviteFromGroup(); - static void RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, const char* reason = nullptr); + static void RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, char const* reason = nullptr); void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(), GetGUID(), method); } void SendUpdateToOutOfRangeGroupMembers(); @@ -1712,7 +1553,7 @@ class TC_GAME_API Player : public Unit, public GridObject Difficulty GetStoredRaidDifficulty() const { return m_raidMapDifficulty; } // only for use in difficulty packet after exiting to raid map void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; } void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; } - void StoreRaidMapDifficulty() { m_raidMapDifficulty = GetMap()->GetDifficulty(); } + void StoreRaidMapDifficulty(); bool UpdateSkill(uint32 skill_id, uint32 step); bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step); @@ -1809,7 +1650,7 @@ class TC_GAME_API Player : public Unit, public GridObject void SendResetFailedNotify(uint32 mapid) const; bool UpdatePosition(float x, float y, float z, float orientation, bool teleport = false) override; - bool UpdatePosition(const Position &pos, bool teleport = false) override { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } + bool UpdatePosition(Position const& pos, bool teleport = false) override { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } void ProcessTerrainStatusUpdate(ZLiquidStatus status, Optional const& liquidData) override; void SendMessageToSet(WorldPacket const* data, bool self) override { SendMessageToSetInRange(data, GetVisibilityRange(), self); } @@ -2002,7 +1843,7 @@ class TC_GAME_API Player : public Unit, public GridObject void CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 cast_count, uint32 glyphIndex); void SendEquipmentSetList(); - void SetEquipmentSet(uint32 index, EquipmentSet eqset); + void SetEquipmentSet(EquipmentSetInfo::EquipmentSetData const& eqset); void DeleteEquipmentSet(uint64 setGuid); void SendInitWorldStates(uint32 zone, uint32 area); @@ -2236,7 +2077,7 @@ class TC_GAME_API Player : public Unit, public GridObject void SetMap(Map* map) override; void ResetMap() override; - bool isAllowedToLoot(const Creature* creature); + bool isAllowedToLoot(Creature const* creature); DeclinedName const* GetDeclinedNames() const { return m_declinedname; } uint8 GetRunesState() const { return m_runes->runeState; } @@ -2263,13 +2104,13 @@ class TC_GAME_API Player : public Unit, public GridObject bool HasAchieved(uint32 achievementId) const; void ResetAchievements(); void ResetAchievementCriteria(AchievementCriteriaCondition condition, uint32 value, bool evenIfCriteriaComplete = false); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = NULL); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost = 0); void RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); void CompletedAchievement(AchievementEntry const* entry); bool HasTitle(uint32 bitIndex) const; - bool HasTitle(CharTitlesEntry const* title) const { return HasTitle(title->bit_index); } + bool HasTitle(CharTitlesEntry const* title) const; void SetTitle(CharTitlesEntry const* title, bool lost = false); //bool isActiveObject() const { return true; } @@ -2545,7 +2386,7 @@ class TC_GAME_API Player : public Unit, public GridObject DeclinedName *m_declinedname; Runes *m_runes; - EquipmentSets m_EquipmentSets; + EquipmentSetContainer _equipmentSets; bool CanAlwaysSee(WorldObject const* obj) const override; @@ -2638,115 +2479,4 @@ class TC_GAME_API Player : public Unit, public GridObject TC_GAME_API void AddItemsSetItem(Player* player, Item* item); TC_GAME_API void RemoveItemsSetItem(Player* player, ItemTemplate const* proto); -// "the bodies of template functions must be made available in a header file" -template -void Player::ApplySpellMod(uint32 spellId, T& basevalue, Spell* spell /*= nullptr*/) const -{ - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); - if (!spellInfo) - return; - - float totalmul = 1.0f; - int32 totalflat = 0; - - // Drop charges for triggering spells instead of triggered ones - if (m_spellModTakingSpell) - spell = m_spellModTakingSpell; - - switch (op) - { - // special case, if a mod makes spell instant, only consume that mod - case SPELLMOD_CASTING_TIME: - { - SpellModifier* modInstantSpell = nullptr; - for (SpellModifier* mod : m_spellMods[op]) - { - if (!IsAffectedBySpellmod(spellInfo, mod, spell)) - continue; - - if (mod->type == SPELLMOD_PCT && basevalue < T(10000) && mod->value <= -100) - { - modInstantSpell = mod; - break; - } - } - - if (modInstantSpell) - { - Player::ApplyModToSpell(modInstantSpell, spell); - basevalue = T(0); - return; - } - break; - } - // special case if two mods apply 100% critical chance, only consume one - case SPELLMOD_CRITICAL_CHANCE: - { - SpellModifier* modCritical = nullptr; - for (SpellModifier* mod : m_spellMods[op]) - { - if (!IsAffectedBySpellmod(spellInfo, mod, spell)) - continue; - - if (mod->type == SPELLMOD_FLAT && mod->value >= 100) - { - modCritical = mod; - break; - } - } - - if (modCritical) - { - Player::ApplyModToSpell(modCritical, spell); - basevalue = T(100); - return; - } - break; - } - default: - break; - } - - for (SpellModifier* mod : m_spellMods[op]) - { - if (!IsAffectedBySpellmod(spellInfo, mod, spell)) - continue; - - switch (mod->type) - { - case SPELLMOD_FLAT: - totalflat += mod->value; - break; - case SPELLMOD_PCT: - { - // skip percent mods with 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 (op == SPELLMOD_CASTING_TIME && mod->value <= -100 && basevalue >= T(10000)) - continue; - else if (!Player::HasSpellModApplied(mod, spell)) - { - // special case for Surge of Light, don't apply critical chance reduction if other mods not applied (ie procs while casting another spell) - // (Surge of Light is the only PCT_MOD on critical chance) - if (op == SPELLMOD_CRITICAL_CHANCE) - continue; - // special case for Backdraft, dont' apply GCD reduction if cast time reduction wasn't applied (ie when Backlash is consumed first) - // (Backdraft is the only PCT_MOD on global cooldown) - else if (op == SPELLMOD_GLOBAL_COOLDOWN) - continue; - } - - totalmul += CalculatePct(1.0f, mod->value); - break; - } - } - - Player::ApplyModToSpell(mod, spell); - } - - basevalue = T(float(basevalue + totalflat) * totalmul); -} - #endif diff --git a/src/server/game/Entities/Player/PlayerTaxi.cpp b/src/server/game/Entities/Player/PlayerTaxi.cpp new file mode 100644 index 00000000000..9a53838e4a9 --- /dev/null +++ b/src/server/game/Entities/Player/PlayerTaxi.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "PlayerTaxi.h" +#include "DBCStores.h" +#include "ObjectMgr.h" +#include "Player.h" +#include + +void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level) +{ + // class specific initial known nodes + switch (chrClass) + { + case CLASS_DEATH_KNIGHT: + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + m_taximask[i] |= sOldContinentsNodesMask[i]; + break; + } + } + + // race specific initial known nodes: capital and taxi hub masks + switch (race) + { + case RACE_HUMAN: SetTaximaskNode(2); break; // Human + case RACE_ORC: SetTaximaskNode(23); break; // Orc + case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf + case RACE_NIGHTELF: SetTaximaskNode(26); + SetTaximaskNode(27); break; // Night Elf + case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead + case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren + case RACE_GNOME: SetTaximaskNode(6); break; // Gnome + case RACE_TROLL: SetTaximaskNode(23); break; // Troll + case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf + case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei + } + + // new continent starting masks (It will be accessible only at new map) + switch (Player::TeamForRace(race)) + { + case ALLIANCE: SetTaximaskNode(100); break; + case HORDE: SetTaximaskNode(99); break; + } + // level dependent taxi hubs + if (level >= 68) + SetTaximaskNode(213); //Shattered Sun Staging Area +} + +void PlayerTaxi::LoadTaxiMask(std::string const& data) +{ + Tokenizer tokens(data, ' '); + + uint8 index = 0; + for (Tokenizer::const_iterator iter = tokens.begin(); index < TaxiMaskSize && iter != tokens.end(); ++iter, ++index) + { + // load and set bits only for existing taxi nodes + m_taximask[index] = sTaxiNodesMask[index] & atoul(*iter); + } +} + +void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) +{ + if (all) + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + data << uint32(sTaxiNodesMask[i]); // all existing nodes + } + else + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + data << uint32(m_taximask[i]); // known nodes + } +} + +bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, uint32 team) +{ + ClearTaxiDestinations(); + + Tokenizer Tokenizer(values, ' '); + + for (Tokenizer::const_iterator iter = Tokenizer.begin(); iter != Tokenizer.end(); ++iter) + { + uint32 node = atoul(*iter); + AddTaxiDestination(node); + } + + if (m_TaxiDestinations.empty()) + return true; + + // Check integrity + if (m_TaxiDestinations.size() < 2) + return false; + + for (size_t i = 1; i < m_TaxiDestinations.size(); ++i) + { + uint32 cost; + uint32 path; + sObjectMgr->GetTaxiPath(m_TaxiDestinations[i - 1], m_TaxiDestinations[i], path, cost); + if (!path) + return false; + } + + // can't load taxi path without mount set (quest taxi path?) + if (!sObjectMgr->GetTaxiMountDisplayId(GetTaxiSource(), team, true)) + return false; + + return true; +} + +std::string PlayerTaxi::SaveTaxiDestinationsToString() +{ + if (m_TaxiDestinations.empty()) + return ""; + + std::ostringstream ss; + + for (size_t i = 0; i < m_TaxiDestinations.size(); ++i) + ss << m_TaxiDestinations[i] << ' '; + + return ss.str(); +} + +uint32 PlayerTaxi::GetCurrentTaxiPath() const +{ + if (m_TaxiDestinations.size() < 2) + return 0; + + uint32 path; + uint32 cost; + + sObjectMgr->GetTaxiPath(m_TaxiDestinations[0], m_TaxiDestinations[1], path, cost); + + return path; +} + +std::ostringstream& operator<<(std::ostringstream& ss, PlayerTaxi const& taxi) +{ + for (uint8 i = 0; i < TaxiMaskSize; ++i) + ss << taxi.m_taximask[i] << ' '; + return ss; +} diff --git a/src/server/game/Entities/Player/PlayerTaxi.h b/src/server/game/Entities/Player/PlayerTaxi.h new file mode 100644 index 00000000000..ae5052b3e7a --- /dev/null +++ b/src/server/game/Entities/Player/PlayerTaxi.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef PlayerTaxi_h__ +#define PlayerTaxi_h__ + +#include "DBCEnums.h" +#include "Define.h" +#include +#include + +class ByteBuffer; + +class TC_GAME_API PlayerTaxi +{ + public: + PlayerTaxi() { m_taximask.fill(0); } + ~PlayerTaxi() { } + // Nodes + void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level); + void LoadTaxiMask(std::string const& data); + + bool IsTaximaskNodeKnown(uint32 nodeidx) const + { + uint8 field = uint8((nodeidx - 1) / 32); + uint32 submask = 1 << ((nodeidx-1) % 32); + return (m_taximask[field] & submask) == submask; + } + bool SetTaximaskNode(uint32 nodeidx) + { + uint8 field = uint8((nodeidx - 1) / 32); + uint32 submask = 1 << ((nodeidx - 1) % 32); + if ((m_taximask[field] & submask) != submask) + { + m_taximask[field] |= submask; + return true; + } + else + return false; + } + void AppendTaximaskTo(ByteBuffer& data, bool all); + + // Destinations + bool LoadTaxiDestinationsFromString(std::string const& values, uint32 team); + std::string SaveTaxiDestinationsToString(); + + void ClearTaxiDestinations() { m_TaxiDestinations.clear(); } + void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } + uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); } + uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; } + uint32 GetCurrentTaxiPath() const; + uint32 NextTaxiDestination() + { + m_TaxiDestinations.pop_front(); + return GetTaxiDestination(); + } + + std::deque const& GetPath() const { return m_TaxiDestinations; } + bool empty() const { return m_TaxiDestinations.empty(); } + + friend std::ostringstream& operator<<(std::ostringstream& ss, PlayerTaxi const& taxi); + private: + TaxiMask m_taximask; + std::deque m_TaxiDestinations; +}; + +std::ostringstream& operator<<(std::ostringstream& ss, PlayerTaxi const& taxi); + +#endif // PlayerTaxi_h__ diff --git a/src/server/game/Entities/Player/SocialMgr.cpp b/src/server/game/Entities/Player/SocialMgr.cpp index d3638c36029..6c9cdd67287 100644 --- a/src/server/game/Entities/Player/SocialMgr.cpp +++ b/src/server/game/Entities/Player/SocialMgr.cpp @@ -17,12 +17,13 @@ */ #include "SocialMgr.h" -#include "WorldSession.h" -#include "WorldPacket.h" #include "DatabaseEnv.h" #include "ObjectAccessor.h" #include "Player.h" +#include "RBAC.h" #include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" PlayerSocial::PlayerSocial(): _playerGUID() { } diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index b8482ecc9f0..343675eae9d 100644 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -19,9 +19,10 @@ #ifndef __TRINITY_SOCIALMGR_H #define __TRINITY_SOCIALMGR_H -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "Common.h" #include "ObjectGuid.h" +#include class Player; class WorldPacket; diff --git a/src/server/game/Entities/Player/TradeData.cpp b/src/server/game/Entities/Player/TradeData.cpp index c36173a6b41..83f33b3537e 100644 --- a/src/server/game/Entities/Player/TradeData.cpp +++ b/src/server/game/Entities/Player/TradeData.cpp @@ -16,6 +16,7 @@ */ #include "TradeData.h" +#include "Item.h" #include "Player.h" #include "WorldSession.h" diff --git a/src/server/game/Entities/Totem/Totem.cpp b/src/server/game/Entities/Totem/Totem.cpp index 74acba5c0a9..7d956ebd8af 100644 --- a/src/server/game/Entities/Totem/Totem.cpp +++ b/src/server/game/Entities/Totem/Totem.cpp @@ -133,7 +133,7 @@ void Totem::UnSummon(uint32 msTime) if (Group* group = owner->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* target = itr->GetSource(); if (target && target->IsInMap(owner) && group->SameSubGroup(owner, target)) diff --git a/src/server/game/Entities/Transport/Transport.cpp b/src/server/game/Entities/Transport/Transport.cpp index a7e89f9aac0..6d36095ee7d 100644 --- a/src/server/game/Entities/Transport/Transport.cpp +++ b/src/server/game/Entities/Transport/Transport.cpp @@ -16,21 +16,25 @@ * with this program. If not, see . */ -#include "Common.h" #include "Transport.h" +#include "Cell.h" +#include "CellImpl.h" +#include "Common.h" +#include "DBCStores.h" +#include "GameObjectAI.h" +#include "Log.h" #include "MapManager.h" #include "ObjectMgr.h" #include "ScriptMgr.h" -#include "DBCStores.h" -#include "GameObjectAI.h" -#include "Vehicle.h" +#include "Spline.h" #include "Player.h" -#include "Cell.h" -#include "CellImpl.h" #include "Totem.h" +#include "UpdateData.h" +#include "Vehicle.h" +#include Transport::Transport() : GameObject(), - _transportInfo(NULL), _isMoving(true), _pendingStop(false), + _transportInfo(nullptr), _isMoving(true), _pendingStop(false), _triggeredArrivalEvent(false), _triggeredDepartureEvent(false), _passengerTeleportItr(_passengers.begin()), _delayedAddModel(false), _delayedTeleport(false) { @@ -96,8 +100,8 @@ bool Transport::Create(ObjectGuid::LowType guidlow, uint32 entry, uint32 mapid, SetGoType(GAMEOBJECT_TYPE_MO_TRANSPORT); SetGoAnimProgress(animprogress); SetName(goinfo->name); - SetWorldRotation(G3D::Quat()); - SetParentRotation(G3D::Quat()); + SetWorldRotation(0.0f, 0.0f, 0.0f, 1.0f); + SetParentRotation(QuaternionData()); m_model = CreateModel(); return true; @@ -280,7 +284,7 @@ void Transport::RemovePassenger(WorldObject* passenger) if (erased || _staticPassengers.erase(passenger)) // static passenger can remove itself in case of grid unload { - passenger->SetTransport(NULL); + passenger->SetTransport(nullptr); passenger->m_movementInfo.RemoveMovementFlag(MOVEMENTFLAG_ONTRANSPORT); passenger->m_movementInfo.transport.Reset(); TC_LOG_DEBUG("entities.transport", "Object %s removed from transport %s.", passenger->GetName().c_str(), GetName().c_str()); @@ -301,7 +305,7 @@ Creature* Transport::CreateNPCPassenger(ObjectGuid::LowType guid, CreatureData c if (!creature->LoadCreatureFromDB(guid, map, false)) { delete creature; - return NULL; + return nullptr; } float x = data->posX; @@ -326,13 +330,13 @@ Creature* Transport::CreateNPCPassenger(ObjectGuid::LowType guid, CreatureData c { TC_LOG_ERROR("entities.transport", "Creature (guidlow %d, entry %d) not created. Suggested coordinates aren't valid (X: %f Y: %f)",creature->GetGUID().GetCounter(),creature->GetEntry(),creature->GetPositionX(),creature->GetPositionY()); delete creature; - return NULL; + return nullptr; } if (!map->AddToMap(creature)) { delete creature; - return NULL; + return nullptr; } _staticPassengers.insert(creature); @@ -348,7 +352,7 @@ GameObject* Transport::CreateGOPassenger(ObjectGuid::LowType guid, GameObjectDat if (!go->LoadGameObjectFromDB(guid, map, false)) { delete go; - return NULL; + return nullptr; } ASSERT(data); @@ -369,24 +373,24 @@ GameObject* Transport::CreateGOPassenger(ObjectGuid::LowType guid, GameObjectDat { TC_LOG_ERROR("entities.transport", "GameObject (guidlow %d, entry %d) not created. Suggested coordinates aren't valid (X: %f Y: %f)", go->GetGUID().GetCounter(), go->GetEntry(), go->GetPositionX(), go->GetPositionY()); delete go; - return NULL; + return nullptr; } if (!map->AddToMap(go)) { delete go; - return NULL; + return nullptr; } _staticPassengers.insert(go); return go; } -TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties /*= NULL*/, uint32 duration /*= 0*/, Unit* summoner /*= NULL*/, uint32 spellId /*= 0*/, uint32 vehId /*= 0*/) +TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties /*= nullptr*/, uint32 duration /*= 0*/, Unit* summoner /*= nullptr*/, uint32 spellId /*= 0*/, uint32 vehId /*= 0*/) { Map* map = FindMap(); if (!map) - return NULL; + return nullptr; uint32 mask = UNIT_MASK_SUMMON; if (properties) @@ -432,7 +436,7 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu break; } default: - return NULL; + return nullptr; } } @@ -440,7 +444,7 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu if (summoner) phase = summoner->GetPhaseMask(); - TempSummon* summon = NULL; + TempSummon* summon = nullptr; switch (mask) { case UNIT_MASK_SUMMON: @@ -467,7 +471,7 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu if (!summon->Create(map->GenerateLowGuid(), map, phase, entry, x, y, z, o, nullptr, vehId)) { delete summon; - return NULL; + return nullptr; } summon->SetUInt32Value(UNIT_CREATED_BY_SPELL, spellId); @@ -489,7 +493,7 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu if (!map->AddToMap(summon)) { delete summon; - return NULL; + return nullptr; } _staticPassengers.insert(summon); diff --git a/src/server/game/Entities/Transport/Transport.h b/src/server/game/Entities/Transport/Transport.h index 5dd77f3df90..757a493f673 100644 --- a/src/server/game/Entities/Transport/Transport.h +++ b/src/server/game/Entities/Transport/Transport.h @@ -66,16 +66,16 @@ class TC_GAME_API Transport : public GameObject, public TransportBase * * @return Summoned creature. */ - TempSummon* SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties = NULL, uint32 duration = 0, Unit* summoner = NULL, uint32 spellId = 0, uint32 vehId = 0); + TempSummon* SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties = nullptr, uint32 duration = 0, Unit* summoner = nullptr, uint32 spellId = 0, uint32 vehId = 0); /// This method transforms supplied transport offsets into global coordinates - void CalculatePassengerPosition(float& x, float& y, float& z, float* o = NULL) const override + void CalculatePassengerPosition(float& x, float& y, float& z, float* o = nullptr) const override { TransportBase::CalculatePassengerPosition(x, y, z, o, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); } /// This method transforms supplied global coordinates into local offsets - void CalculatePassengerOffset(float& x, float& y, float& z, float* o = NULL) const override + void CalculatePassengerOffset(float& x, float& y, float& z, float* o = nullptr) const override { TransportBase::CalculatePassengerOffset(x, y, z, o, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); } diff --git a/src/server/game/Entities/Unit/StatSystem.cpp b/src/server/game/Entities/Unit/StatSystem.cpp index 436740c6fe1..cf61198ddd9 100644 --- a/src/server/game/Entities/Unit/StatSystem.cpp +++ b/src/server/game/Entities/Unit/StatSystem.cpp @@ -17,13 +17,16 @@ */ #include "Unit.h" -#include "Player.h" -#include "Pet.h" #include "Creature.h" +#include "Item.h" +#include "Pet.h" +#include "Player.h" #include "SharedDefines.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" +#include "SpellMgr.h" #include "World.h" +#include inline bool _ModifyUInt32(bool apply, uint32& baseValue, int32& amount) { diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index bb08b9bc862..941ad019396 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -17,26 +17,29 @@ */ #include "Unit.h" -#include "CharacterCache.h" -#include "Common.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Battleground.h" #include "BattlegroundScore.h" #include "CellImpl.h" +#include "CharacterCache.h" +#include "Chat.h" #include "ChatTextBuilder.h" +#include "Common.h" #include "ConditionMgr.h" #include "CreatureAI.h" #include "CreatureAIImpl.h" #include "CreatureGroups.h" -#include "Creature.h" #include "Formulas.h" #include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" +#include "Item.h" #include "Log.h" +#include "LootMgr.h" +#include "MotionMaster.h" #include "MoveSpline.h" #include "MoveSplineInit.h" #include "ObjectAccessor.h" @@ -65,7 +68,6 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" - #include float baseMoveSpeed[MAX_MOVE_TYPE] = @@ -262,13 +264,25 @@ SpellSchoolMask ProcEventInfo::GetSchoolMask() const return SPELL_SCHOOL_MASK_NONE; } +DispelableAura::DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges) : + _aura(aura), _chance(dispelChance), _charges(dispelCharges) +{ +} + +DispelableAura::~DispelableAura() = default; + +bool DispelableAura::RollDispel() const +{ + return roll_chance_i(_chance); +} + Unit::Unit(bool isWorldObject) : WorldObject(isWorldObject), m_playerMovingMe(nullptr), m_lastSanctuaryTime(0), IsAIEnabled(false), NeedChangeAI(false), LastCharmerGUID(), m_ControlledByPlayer(false), movespline(new Movement::MoveSpline()), i_AI(nullptr), i_disabledAI(nullptr), m_AutoRepeatFirstCast(false), m_procDeep(0), m_removedAurasCount(0), i_motionMaster(new MotionMaster(this)), m_regenTimer(0), m_ThreatManager(this), - m_vehicle(nullptr), m_vehicleKit(nullptr), m_unitTypeMask(UNIT_MASK_NONE), + m_vehicle(nullptr), m_vehicleKit(nullptr), m_unitTypeMask(UNIT_MASK_NONE), m_Diminishing(), m_HostileRefManager(this), m_spellHistory(new SpellHistory(this)) { m_objectType |= TYPEMASK_UNIT; @@ -292,7 +306,7 @@ Unit::Unit(bool isWorldObject) : m_deathState = ALIVE; for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i) - m_currentSpells[i] = NULL; + m_currentSpells[i] = nullptr; for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i) m_SummonSlot[i].Clear(); @@ -540,7 +554,7 @@ void Unit::resetAttackTimer(WeaponAttackType type) m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]); } -bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const +bool Unit::IsWithinCombatRange(Unit const* obj, float dist2compare) const { if (!obj || !IsInMap(obj) || !InSamePhase(obj)) return false; @@ -577,7 +591,7 @@ float Unit::GetMeleeRange(Unit const* target) const return std::max(range, NOMINAL_MELEE_RANGE); } -void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const +void Unit::GetRandomContactPoint(Unit const* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const { float combat_reach = GetCombatReach(); if (combat_reach < 0.1f) // sometimes bugged for players @@ -646,7 +660,7 @@ bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) const { uint32 excludeAura = 0; - if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : NULL) + if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : nullptr) excludeAura = currentChanneledSpell->GetSpellInfo()->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction return ( HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura) @@ -735,8 +749,8 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam uint32 share = CalculatePct(damage, (*i)->GetAmount()); /// @todo check packets if damage is done by victim, or by attacker of victim - DealDamageMods(shareDamageTarget, share, NULL); - DealDamage(shareDamageTarget, share, NULL, NODAMAGE, spell->GetSchoolMask(), spell, false); + DealDamageMods(shareDamageTarget, share, nullptr); + DealDamage(shareDamageTarget, share, nullptr, NODAMAGE, spell->GetSchoolMask(), spell, false); } } @@ -928,7 +942,7 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam ASSERT(he && he->duel); - if (duel_wasMounted) // In this case victim==mount + if (duel_wasMounted) // In this case victim == mount victim->SetHealth(1); else he->SetHealth(1); @@ -1127,7 +1141,7 @@ void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 dama uint32 crit_bonus = damage; // Apply crit_damage bonus for melee spells if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, crit_bonus); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); damage += crit_bonus; // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE @@ -1222,7 +1236,7 @@ void Unit::DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss) return; SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(damageInfo->SpellID); - if (spellProto == NULL) + if (spellProto == nullptr) { TC_LOG_DEBUG("entities.unit", "Unit::DealSpellDamage has wrong damageInfo->SpellID: %u", damageInfo->SpellID); return; @@ -1296,7 +1310,7 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam // Calculate armor reduction if (IsDamageReducedByArmor((SpellSchoolMask)(damageInfo->damageSchoolMask))) { - damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL, damageInfo->attackType); + damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, nullptr, damageInfo->attackType); damageInfo->cleanDamage += damage - damageInfo->damage; } else @@ -1405,7 +1419,7 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam int32 resilienceReduction = damageInfo->damage; // attackType is checked already for BASE_ATTACK or OFF_ATTACK so it can't be RANGED_ATTACK here - ApplyResilience(victim, NULL, &resilienceReduction, (damageInfo->hitOutCome == MELEE_HIT_CRIT), CR_CRIT_TAKEN_MELEE); + ApplyResilience(victim, nullptr, &resilienceReduction, (damageInfo->hitOutCome == MELEE_HIT_CRIT), CR_CRIT_TAKEN_MELEE); resilienceReduction = damageInfo->damage - resilienceReduction; damageInfo->damage -= resilienceReduction; damageInfo->cleanDamage += resilienceReduction; @@ -1480,7 +1494,7 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) // Call default DealDamage CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, damageInfo->attackType, damageInfo->hitOutCome); - DealDamage(victim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss); + DealDamage(victim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), nullptr, durabilityLoss); // If this is a creature and it attacks from behind it has a probability to daze it's victim if ((damageInfo->hitOutCome == MELEE_HIT_CRIT || damageInfo->hitOutCome == MELEE_HIT_CRUSHING || damageInfo->hitOutCome == MELEE_HIT_NORMAL || damageInfo->hitOutCome == MELEE_HIT_GLANCING) && @@ -1570,7 +1584,7 @@ void Unit::HandleEmoteCommand(uint32 anim_id) SendMessageToSet(&data, true); } -bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* spellInfo, uint8 effIndex) +bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* spellInfo /*= nullptr*/, int8 effIndex /*= -1*/) { // only physical spells damage gets reduced by armor if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0) @@ -1582,7 +1596,7 @@ bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* s return false; // bleeding effects are not reduced by armor - if (effIndex != MAX_SPELL_EFFECTS) + if (effIndex != -1) { if (spellInfo->Effects[effIndex].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE || spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SCHOOL_DAMAGE) @@ -1602,7 +1616,7 @@ uint32 Unit::CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo if (spellInfo) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, armor); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor); AuraEffectList const& resIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_ABILITY_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = resIgnoreAurasAb.begin(); j != resIgnoreAurasAb.end(); ++j) @@ -2613,7 +2627,7 @@ SpellMissInfo Unit::MagicSpellHitResult(Unit* victim, SpellInfo const* spellInfo // Spellmod from SPELLMOD_RESIST_MISS_CHANCE if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, modHitChance); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance); // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras modHitChance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask); @@ -3045,7 +3059,7 @@ void Unit::_UpdateSpells(uint32 time) if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED) { m_currentSpells[i]->SetReferencedFromCurrent(false); - m_currentSpells[i] = NULL; // remove pointer + m_currentSpells[i] = nullptr; // remove pointer } } @@ -3094,7 +3108,7 @@ void Unit::_UpdateSpells(uint32 time) void Unit::_UpdateAutoRepeatSpell() { - const SpellInfo* autoRepeatSpellInfo = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo; + SpellInfo const* autoRepeatSpellInfo = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo; // check "realtime" interrupts if ((GetTypeId() == TYPEID_PLAYER && ToPlayer()->isMoving()) || IsNonMeleeSpellCast(false, false, true, autoRepeatSpellInfo->Id == 75)) @@ -3231,7 +3245,7 @@ void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool wi if (spell->getState() != SPELL_STATE_FINISHED) spell->cancel(); - m_currentSpells[spellType] = NULL; + m_currentSpells[spellType] = nullptr; spell->SetReferencedFromCurrent(false); } } @@ -3298,7 +3312,7 @@ Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++) if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id == spell_id) return m_currentSpells[i]; - return NULL; + return nullptr; } int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const @@ -3501,7 +3515,7 @@ AuraApplication * Unit::_CreateAuraApplication(Aura* aura, uint8 effMask) // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load) if (!IsAlive() && !aurSpellInfo->IsDeathPersistent() && (GetTypeId() != TYPEID_PLAYER || !ToPlayer()->GetSession()->PlayerLoading())) - return NULL; + return nullptr; Unit* caster = aura->GetCaster(); @@ -3811,7 +3825,7 @@ Aura* Unit::GetOwnedAura(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemC return itr->second; } } - return NULL; + return nullptr; } void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode) @@ -4506,7 +4520,7 @@ AuraEffect* Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, ObjectGuid caste return itr->second->GetBase()->GetEffect(effIndex); } } - return NULL; + return nullptr; } AuraEffect* Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, ObjectGuid caster) const @@ -4518,7 +4532,7 @@ AuraEffect* Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, Obj return aurEff; rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell); } - return NULL; + return nullptr; } AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const @@ -4532,7 +4546,7 @@ AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 ico if (spell->SpellIconID == iconId && spell->SpellFamilyName == uint32(name) && !spell->SpellFamilyFlags) return *itr; } - return NULL; + return nullptr; } AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, ObjectGuid casterGUID) const @@ -4548,7 +4562,7 @@ AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 f return (*i); } } - return NULL; + return nullptr; } AuraEffect* Unit::GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const @@ -4572,13 +4586,13 @@ AuraApplication * Unit::GetAuraApplication(uint32 spellId, ObjectGuid casterGUID return app; } } - return NULL; + return nullptr; } Aura* Unit::GetAura(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemCasterGUID, uint8 reqEffMask) const { AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask); - return aurApp ? aurApp->GetBase() : NULL; + return aurApp ? aurApp->GetBase() : nullptr; } AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const @@ -4590,13 +4604,13 @@ AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGu return aurApp; rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell); } - return NULL; + return nullptr; } Aura* Unit::GetAuraOfRankedSpell(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemCasterGUID, uint8 reqEffMask) const { AuraApplication * aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask); - return aurApp ? aurApp->GetBase() : NULL; + return aurApp ? aurApp->GetBase() : nullptr; } void Unit::GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList, bool isReflect /*= false*/) const @@ -4768,7 +4782,7 @@ AuraEffect* Unit::IsScriptOverriden(SpellInfo const* spell, int32 script) const if ((*i)->IsAffectedOnSpell(spell)) return (*i); } - return NULL; + return nullptr; } uint32 Unit::GetDiseasesByCaster(ObjectGuid casterGUID, bool remove) @@ -5162,14 +5176,14 @@ void Unit::_UnregisterDynObject(DynamicObject* dynObj) DynamicObject* Unit::GetDynObject(uint32 spellId) { if (m_dynObj.empty()) - return NULL; + return nullptr; for (DynObjectList::const_iterator i = m_dynObj.begin(); i != m_dynObj.end();++i) { DynamicObject* dynObj = *i; if (dynObj->GetSpellId() == spellId) return dynObj; } - return NULL; + return nullptr; } void Unit::RemoveDynObject(uint32 spellId) @@ -5201,7 +5215,7 @@ GameObject* Unit::GetGameObject(uint32 spellId) const if ((*i)->GetSpellId() == spellId) return *i; - return NULL; + return nullptr; } void Unit::AddGameObject(GameObject* gameObj) @@ -6017,7 +6031,7 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) if (!spellInfo || !spellInfo->IsPassive()) continue; if (spellInfo->CasterAuraState == uint32(flag)) - CastSpell(this, itr->first, true, NULL); + CastSpell(this, itr->first, true, nullptr); } } else if (Pet* pet = ToCreature()->ToPet()) @@ -6030,7 +6044,7 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) if (!spellInfo || !spellInfo->IsPassive()) continue; if (spellInfo->CasterAuraState == uint32(flag)) - CastSpell(this, itr->first, true, NULL); + CastSpell(this, itr->first, true, nullptr); } } } @@ -6120,7 +6134,7 @@ Unit* Unit::GetOwner() const if (ObjectGuid ownerGUID = GetOwnerGUID()) return ObjectAccessor::GetUnit(*this, ownerGUID); - return NULL; + return nullptr; } Unit* Unit::GetCharmer() const @@ -6148,7 +6162,7 @@ Player* Unit::GetAffectingPlayer() const if (Unit* owner = GetCharmerOrOwner()) return owner->GetCharmerOrOwnerPlayerOrPlayerItself(); - return NULL; + return nullptr; } Minion *Unit::GetFirstMinion() const @@ -6163,7 +6177,7 @@ Minion *Unit::GetFirstMinion() const const_cast(this)->SetMinionGUID(ObjectGuid::Empty); } - return NULL; + return nullptr; } Guardian* Unit::GetGuardianPet() const @@ -6178,7 +6192,7 @@ Guardian* Unit::GetGuardianPet() const const_cast(this)->SetPetGUID(ObjectGuid::Empty); } - return NULL; + return nullptr; } Unit* Unit::GetCharm() const @@ -6192,7 +6206,7 @@ Unit* Unit::GetCharm() const const_cast(this)->SetGuidValue(UNIT_FIELD_CHARM, ObjectGuid::Empty); } - return NULL; + return nullptr; } Unit* Unit::GetCharmerOrOwner() const @@ -6619,7 +6633,7 @@ bool Unit::isPossessing() const Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) { - Player* player = NULL; + Player* player = nullptr; if (GetTypeId() == TYPEID_PLAYER) player = ToPlayer(); // Should we enable this also for charmed units? @@ -6627,27 +6641,27 @@ Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) player = GetOwner()->ToPlayer(); if (!player) - return NULL; + return nullptr; Group* group = player->GetGroup(); // When there is no group check pet presence if (!group) { // We are pet now, return owner if (player != this) - return IsWithinDistInMap(player, radius) ? player : NULL; + return IsWithinDistInMap(player, radius) ? player : nullptr; Unit* pet = GetGuardianPet(); // No pet, no group, nothing to return if (!pet) - return NULL; + return nullptr; // We are owner now, return pet - return IsWithinDistInMap(pet, radius) ? pet : NULL; + return IsWithinDistInMap(pet, radius) ? pet : nullptr; } std::vector nearMembers; // reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then) nearMembers.reserve(group->GetMembersCount() * 2); - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* Target = itr->GetSource()) { // IsHostileTo check duel and controlled by enemy @@ -6661,7 +6675,7 @@ Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) } if (nearMembers.empty()) - return NULL; + return nullptr; uint32 randTarget = urand(0, nearMembers.size()-1); return nearMembers[randTarget]; @@ -6874,7 +6888,7 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } DoneTotal += int32(DoneAdvertisedBenefit * coeff * factorMod); @@ -6890,7 +6904,7 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin // apply spellmod to Done damage (flat and pct) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, tmpDamage); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage); } return uint32(std::max(tmpDamage, 0.0f)); @@ -7276,7 +7290,7 @@ uint32 Unit::SpellDamageBonusTaken(Unit* caster, SpellInfo const* spellProto, ui if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } TakenTotal += int32(TakenAdvertisedBenefit * coeff * factorMod); @@ -7569,7 +7583,7 @@ float Unit::GetUnitSpellCriticalChance(Unit* victim, SpellInfo const* spellProto // percent done // only players use intelligence for critical chance computations if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, crit_chance); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance); // for this types the bonus was already added in GetUnitCriticalChance, do not add twice if (spellProto->DmgClass != SPELL_DAMAGE_CLASS_MELEE && spellProto->DmgClass != SPELL_DAMAGE_CLASS_RANGED) @@ -7617,7 +7631,7 @@ uint32 Unit::SpellCriticalDamageBonus(SpellInfo const* spellProto, uint32 damage { // adds additional damage to critBonus (from talents) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, crit_bonus); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); } crit_bonus += damage; @@ -7759,7 +7773,7 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } @@ -7794,7 +7808,7 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui // apply spellmod to Done amount if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, heal); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, heal); } return uint32(std::max(heal, 0.0f)); @@ -7939,7 +7953,7 @@ uint32 Unit::SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, u if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } @@ -8363,7 +8377,7 @@ uint32 Unit::MeleeDamageBonusDone(Unit* victim, uint32 pdamage, WeaponAttackType // apply spellmod to Done damage if (spellProto) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, tmpDamage); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage); // bonus result can be negative return uint32(std::max(tmpDamage, 0.0f)); @@ -8507,7 +8521,7 @@ float Unit::GetWeaponProcChance() const return 0; } -float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const +float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, SpellInfo const* spellProto) const { // proc per minute chance calculation if (PPM <= 0) @@ -8516,7 +8530,7 @@ float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spe // Apply chance modifer aura if (spellProto) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, PPM); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_PROC_PER_MINUTE, PPM); return std::floor((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60)) } @@ -8542,7 +8556,7 @@ void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry) SendMessageToSet(&data, true); data.Initialize(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); // mounts can also have accessories GetVehicleKit()->InstallAllAccessories(false); @@ -8570,7 +8584,7 @@ void Unit::Mount(uint32 mount, uint32 VehicleId, uint32 creatureEntry) data << GetPackGUID(); data << uint32(GameTime::GetGameTime()); // Packet counter data << player->GetCollisionHeight(true); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNT); @@ -8590,7 +8604,7 @@ void Unit::Dismount() data << GetPackGUID(); data << uint32(GameTime::GetGameTime()); // Packet counter data << thisPlayer->GetCollisionHeight(false); - thisPlayer->GetSession()->SendPacket(&data); + thisPlayer->SendDirectMessage(&data); } WorldPacket data(SMSG_DISMOUNT, 8); @@ -8803,7 +8817,7 @@ bool Unit::isTargetableForAttack(bool checkFakeDeath) const bool Unit::IsValidAttackTarget(Unit const* target) const { - return _IsValidAttackTarget(target, NULL); + return _IsValidAttackTarget(target, nullptr); } // function based on function Unit::CanAttack from 13850 client @@ -8926,7 +8940,7 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo bool Unit::IsValidAssistTarget(Unit const* target) const { - return _IsValidAssistTarget(target, NULL); + return _IsValidAssistTarget(target, nullptr); } // function based on function Unit::CanAssist from 13850 client @@ -9371,7 +9385,7 @@ void Unit::SetSpeedRate(UnitMoveType mtype, float rate) if (mtype == MOVE_RUN) self << uint8(1); // unknown byte added in 2.1.0 self << float(GetSpeed(mtype)); - playerMover->GetSession()->SendPacket(&self); + playerMover->SendDirectMessage(&self); // Send notification to other players. sent to every clients (if in range) except one: the client of the player concerned by the change. WorldPacket data; @@ -9712,17 +9726,17 @@ float Unit::ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index { if (Player* modOwner = GetSpellModOwner()) { - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value); switch (effect_index) { case EFFECT_0: - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value); break; case EFFECT_1: - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value); break; case EFFECT_2: - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value); break; } } @@ -9865,7 +9879,7 @@ void Unit::ModSpellCastTime(SpellInfo const* spellInfo, int32 & castTime, Spell* // called from caster if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, castTime, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell); if (!(spellInfo->HasAttribute(SPELL_ATTR0_ABILITY) || spellInfo->HasAttribute(SPELL_ATTR0_TRADESPELL) || spellInfo->HasAttribute(SPELL_ATTR3_NO_DONE_BONUS)) && ((GetTypeId() == TYPEID_PLAYER && spellInfo->SpellFamilyName) || GetTypeId() == TYPEID_UNIT)) @@ -9886,7 +9900,7 @@ void Unit::ModSpellDurationTime(SpellInfo const* spellInfo, int32 & duration, Sp // called from caster if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, duration, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, duration, spell); if (!(spellInfo->HasAttribute(SPELL_ATTR0_ABILITY) || spellInfo->HasAttribute(SPELL_ATTR0_TRADESPELL) || spellInfo->HasAttribute(SPELL_ATTR3_NO_DONE_BONUS)) && ((GetTypeId() == TYPEID_PLAYER && spellInfo->SpellFamilyName) || GetTypeId() == TYPEID_UNIT)) @@ -10003,8 +10017,8 @@ void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) void Unit::ClearDiminishings() { - for (uint32 i = 0; i < DIMINISHING_MAX; ++i) - m_Diminishing[i].Clear(); + for (DiminishingReturn& dim : m_Diminishing) + dim.Clear(); } float Unit::GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const @@ -10768,7 +10782,7 @@ void Unit::DeleteCharmInfo() m_charmInfo->RestoreState(); delete m_charmInfo; - m_charmInfo = NULL; + m_charmInfo = nullptr; } CharmInfo::CharmInfo(Unit* unit) @@ -11333,7 +11347,7 @@ void Unit::SendPetActionFeedback(uint8 msg) WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1); data << uint8(msg); - owner->ToPlayer()->GetSession()->SendPacket(&data); + owner->ToPlayer()->SendDirectMessage(&data); } void Unit::SendPetTalk(uint32 pettalk) @@ -11345,7 +11359,7 @@ void Unit::SendPetTalk(uint32 pettalk) WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4); data << uint64(GetGUID()); data << uint32(pettalk); - owner->ToPlayer()->GetSession()->SendPacket(&data); + owner->ToPlayer()->SendDirectMessage(&data); } void Unit::SendPetAIReaction(ObjectGuid guid) @@ -11357,11 +11371,16 @@ void Unit::SendPetAIReaction(ObjectGuid guid) WorldPacket data(SMSG_AI_REACTION, 8 + 4); data << uint64(guid); data << uint32(AI_REACTION_HOSTILE); - owner->ToPlayer()->GetSession()->SendPacket(&data); + owner->ToPlayer()->SendDirectMessage(&data); } ///----------End of Pet responses methods---------- +void Unit::PropagateSpeedChange() +{ + GetMotionMaster()->PropagateSpeedChange(); +} + void Unit::StopMoving() { ClearUnitState(UNIT_STATE_MOVING); @@ -11409,7 +11428,7 @@ void Unit::SetStandState(uint8 state) { WorldPacket data(SMSG_STANDSTATE_UPDATE, 1); data << (uint8)state; - ToPlayer()->GetSession()->SendPacket(&data); + ToPlayer()->SendDirectMessage(&data); } } @@ -11568,7 +11587,7 @@ Unit* Unit::SelectNearbyTarget(Unit* exclude, float dist) const // no appropriate targets if (targets.empty()) - return NULL; + return nullptr; // select random return Trinity::Containers::SelectRandomContainerElement(targets); @@ -11834,14 +11853,14 @@ void Unit::SetContestedPvP(Player* attackedPlayer) Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) - return NULL; + return nullptr; Pet* pet = new Pet(ToPlayer(), HUNTER_PET); if (!pet->CreateBaseAtCreature(creatureTarget)) { delete pet; - return NULL; + return nullptr; } uint8 level = creatureTarget->getLevel() + 5 < getLevel() ? (getLevel() - 5) : creatureTarget->getLevel(); @@ -11854,18 +11873,18 @@ Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id) Pet* Unit::CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) - return NULL; + return nullptr; CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry); if (!creatureInfo) - return NULL; + return nullptr; Pet* pet = new Pet(ToPlayer(), HUNTER_PET); if (!pet->CreateBaseAtCreatureInfo(creatureInfo, this) || !InitTamedPet(pet, getLevel(), spell_id)) { delete pet; - return NULL; + return nullptr; } return pet; @@ -11909,7 +11928,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) { isRewardAllowed = creature->IsDamageEnoughForLootingAndReward(); if (!isRewardAllowed) - creature->SetLootRecipient(NULL); + creature->SetLootRecipient(nullptr); } if (isRewardAllowed && creature && creature->GetLootRecipient()) @@ -11980,7 +11999,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) if (hasLooterGuid) group->SendLooter(creature, looter); else - group->SendLooter(creature, NULL); + group->SendLooter(creature, nullptr); // Update round robin looter only if the creature had loot if (!loot->empty()) @@ -12030,7 +12049,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) victim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); // FORM_SPIRITOFREDEMPTION and related auras - victim->CastSpell(victim, 27827, true, NULL, aurEff); + victim->CastSpell(victim, 27827, true, nullptr, aurEff); spiritOfRedemption = true; break; } @@ -12059,7 +12078,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) { // remember victim PvP death for corpse type and corpse reclaim delay // at original death (not at SpiritOfRedemtionTalent timeout) - plrVictim->SetPvPDeath(player != NULL); + plrVictim->SetPvPDeath(player != nullptr); // only if not player and not controlled by player pet. And not at BG if ((durabilityLoss && !player && !victim->ToPlayer()->InBattleground()) || (player && sWorld->getBoolConfig(CONFIG_DURABILITY_LOSS_IN_PVP))) @@ -12068,7 +12087,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) plrVictim->DurabilityLossAll(sWorld->getRate(RATE_DURABILITY_LOSS_ON_DEATH), false); // durability lost message WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0); - plrVictim->GetSession()->SendPacket(&data); + plrVictim->SendDirectMessage(&data); } // Call KilledUnit for creatures if (GetTypeId() == TYPEID_UNIT && IsAIEnabled) @@ -12392,7 +12411,7 @@ void Unit::SetFeared(bool apply) { SetTarget(ObjectGuid::Empty); - Unit* caster = NULL; + Unit* caster = nullptr; Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType(SPELL_AURA_MOD_FEAR); if (!fearAuras.empty()) caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID()); @@ -12584,7 +12603,7 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true); // if charmed two demons the same session, the 2nd gets the 1st one's name - SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped + SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped } } playerCharmer->CharmSpellInitialize(); @@ -12731,7 +12750,7 @@ void Unit::RestoreFaction() Unit* Unit::GetRedirectThreatTarget() { - return _redirectThreadInfo.GetTargetGUID() ? ObjectAccessor::GetUnit(*this, _redirectThreadInfo.GetTargetGUID()) : NULL; + return _redirectThreadInfo.GetTargetGUID() ? ObjectAccessor::GetUnit(*this, _redirectThreadInfo.GetTargetGUID()) : nullptr; } bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry) @@ -12754,21 +12773,21 @@ void Unit::RemoveVehicleKit() m_vehicleKit->Uninstall(); delete m_vehicleKit; - m_vehicleKit = NULL; + m_vehicleKit = nullptr; m_updateFlag &= ~UPDATEFLAG_VEHICLE; m_unitTypeMask &= ~UNIT_MASK_VEHICLE; RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK | UNIT_NPC_FLAG_PLAYER_VEHICLE); } -bool Unit::IsOnVehicle(const Unit* vehicle) const +bool Unit::IsOnVehicle(Unit const* vehicle) const { return m_vehicle && m_vehicle == vehicle->GetVehicleKit(); } Unit* Unit::GetVehicleBase() const { - return m_vehicle ? m_vehicle->GetBase() : NULL; + return m_vehicle ? m_vehicle->GetBase() : nullptr; } Creature* Unit::GetVehicleCreatureBase() const @@ -12777,7 +12796,7 @@ Creature* Unit::GetVehicleCreatureBase() const if (Creature* c = veh->ToCreature()) return c; - return NULL; + return nullptr; } ObjectGuid Unit::GetTransGUID() const @@ -12838,7 +12857,7 @@ bool Unit::IsInRaidWith(Unit const* unit) const void Unit::GetPartyMembers(std::list &TagUnitMap) { Unit* owner = GetCharmerOrOwnerOrSelf(); - Group* group = NULL; + Group* group = nullptr; if (owner->GetTypeId() == TYPEID_PLAYER) group = owner->ToPlayer()->GetGroup(); @@ -12846,7 +12865,7 @@ void Unit::GetPartyMembers(std::list &TagUnitMap) { uint8 subgroup = owner->ToPlayer()->GetSubGroup(); - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* Target = itr->GetSource(); @@ -12891,14 +12910,14 @@ void Unit::SetPvP(bool state) Aura* Unit::AddAura(uint32 spellId, Unit* target) { if (!target) - return NULL; + return nullptr; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) - return NULL; + return nullptr; if (!target->IsAlive() && !spellInfo->IsPassive() && !spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_DEAD)) - return NULL; + return nullptr; return AddAura(spellInfo, MAX_EFFECT_MASK, target); } @@ -12906,10 +12925,10 @@ Aura* Unit::AddAura(uint32 spellId, Unit* target) Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target) { if (!spellInfo) - return NULL; + return nullptr; if (target->IsImmunedToSpell(spellInfo, this)) - return NULL; + return nullptr; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { @@ -12924,7 +12943,7 @@ Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target) aura->ApplyForTargets(); return aura; } - return NULL; + return nullptr; } void Unit::SetAuraStack(uint32 spellId, Unit* target, uint32 stack) @@ -12958,13 +12977,13 @@ void Unit::ApplyResilience(Unit const* victim, float* crit, int32* damage, bool if (IsVehicle() || (victim->IsVehicle() && victim->GetTypeId() != TYPEID_PLAYER)) return; - Unit const* source = NULL; + Unit const* source = nullptr; if (GetTypeId() == TYPEID_PLAYER) source = this; else if (GetTypeId() == TYPEID_UNIT && GetOwner() && GetOwner()->GetTypeId() == TYPEID_PLAYER) source = GetOwner(); - Unit const* target = NULL; + Unit const* target = nullptr; if (victim->GetTypeId() == TYPEID_PLAYER) target = victim; else if (victim->GetTypeId() == TYPEID_UNIT && victim->GetOwner() && victim->GetOwner()->GetTypeId() == TYPEID_PLAYER) @@ -13042,7 +13061,7 @@ float Unit::MeleeSpellMissChance(Unit const* victim, WeaponAttackType attType, i if (spellId) { if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellId, resistMissChance); + modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_MISS_CHANCE, resistMissChance); } missChance -= resistMissChance - 100.0f; @@ -13141,7 +13160,7 @@ void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ) { player = charmer->ToPlayer(); if (player && player->m_unitMovedByMe != this) - player = NULL; + player = nullptr; } } @@ -13157,12 +13176,11 @@ void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ) WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8 + 4 + 4 + 4 + 4 + 4)); data << GetPackGUID(); data << uint32(0); // counter - data << float(vcos); // x direction - data << float(vsin); // y direction + data << TaggedPosition(vcos, vsin); data << float(speedXY); // Horizontal speed data << float(-speedZ); // Z Movement speed (vertical) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); if (player->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED) || player->HasAuraType(SPELL_AURA_FLY)) player->SetCanFly(true, true); @@ -13494,12 +13512,11 @@ void Unit::JumpTo(float speedXY, float speedZ, bool forward) WorldPacket data(SMSG_MOVE_KNOCK_BACK, (8+4+4+4+4+4)); data << GetPackGUID(); data << uint32(0); // Sequence - data << float(vcos); // x direction - data << float(vsin); // y direction + data << TaggedPosition(vcos, vsin); data << float(speedXY); // Horizontal speed data << float(-speedZ); // Z Movement speed (vertical) - ToPlayer()->GetSession()->SendPacket(&data); + ToPlayer()->SendDirectMessage(&data); } } @@ -13556,7 +13573,7 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) } if (IsInMap(caster)) - caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId + 1, target, flags, NULL, NULL, origCasterGUID); + caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId + 1, target, flags, nullptr, nullptr, origCasterGUID); else // This can happen during Player::_LoadAuras { int32 bp0[MAX_SPELL_EFFECTS]; @@ -13564,15 +13581,15 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) bp0[j] = spellEntry->Effects[j].BasePoints; bp0[i] = seatId; - Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, bp0, NULL, origCasterGUID); + Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, bp0, nullptr, origCasterGUID); } } else { if (IsInMap(caster)) - caster->CastSpell(target, spellEntry, flags, NULL, NULL, origCasterGUID); + caster->CastSpell(target, spellEntry, flags, nullptr, nullptr, origCasterGUID); else - Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, NULL, NULL, origCasterGUID); + Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, nullptr, nullptr, origCasterGUID); } result = true; @@ -13645,7 +13662,7 @@ void Unit::ChangeSeat(int8 seatId, bool next) if (seat == m_vehicle->Seats.end() || !seat->second.IsEmpty()) return; - AuraEffect* rideVehicleEffect = NULL; + AuraEffect* rideVehicleEffect = nullptr; AuraEffectList const& vehicleAuras = m_vehicle->GetBase()->GetAuraEffectsByType(SPELL_AURA_CONTROL_VEHICLE); for (AuraEffectList::const_iterator itr = vehicleAuras.begin(); itr != vehicleAuras.end(); ++itr) { @@ -13760,19 +13777,13 @@ void Unit::BuildMovementPacket(Position const& pos, Position const& transportPos *data << uint32(movementInfo.GetMovementFlags()); *data << uint16(movementInfo.GetExtraMovementFlags()); *data << uint32(GameTime::GetGameTimeMS()); // time / counter - *data << float(pos.GetPositionX()); - *data << float(pos.GetPositionY()); - *data << float(pos.GetPositionZ()); - *data << float(pos.GetOrientation()); + *data << TaggedPosition(pos); // 0x00000200 if (movementInfo.HasMovementFlag(MOVEMENTFLAG_ONTRANSPORT)) { *data << movementInfo.transport.guid.WriteAsPacked(); - *data << float(transportPos.GetPositionX()); - *data << float(transportPos.GetPositionY()); - *data << float(transportPos.GetPositionZ()); - *data << float(transportPos.GetOrientation()); + *data << TaggedPosition(transportPos); *data << uint32(movementInfo.transport.time); *data << int8(movementInfo.transport.seat); @@ -13904,7 +13915,7 @@ bool Unit::UpdatePosition(float x, float y, float z, float orientation, bool tel return (relocated || turn); } -bool Unit::UpdatePosition(const Position &pos, bool teleport) +bool Unit::UpdatePosition(Position const& pos, bool teleport) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } @@ -13935,7 +13946,7 @@ void Unit::SendThreatListUpdate() WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8); data << GetPackGUID(); data << uint32(count); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data << (*itr)->getUnitGuid().WriteAsPacked(); @@ -13956,7 +13967,7 @@ void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference) data << GetPackGUID(); data << pHostileReference->getUnitGuid().WriteAsPacked(); data << uint32(count); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data << (*itr)->getUnitGuid().WriteAsPacked(); diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index 61e1ad86c3e..5ed2e57cc3f 100644 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -19,15 +19,18 @@ #ifndef __UNIT_H #define __UNIT_H -#include "DBCStructure.h" +#include "Object.h" #include "EventProcessor.h" #include "FollowerReference.h" #include "FollowerRefManager.h" #include "HostileRefManager.h" -#include "MotionMaster.h" -#include "Object.h" +#include "OptionalFwd.h" #include "SpellAuraDefines.h" #include "ThreatManager.h" +#include "Timer.h" +#include "UnitDefines.h" +#include "Util.h" +#include #define WORLD_TRIGGER 12999 @@ -118,7 +121,7 @@ enum SpellModOp : uint8 MAX_SPELLMOD }; -enum SpellValueMod +enum SpellValueMod : uint8 { SPELLVALUE_BASE_POINT0, SPELLVALUE_BASE_POINT1, @@ -161,69 +164,6 @@ enum SpellFacingFlags SPELL_FACING_FLAG_INFRONT = 0x0001 }; -#define BASE_MINDAMAGE 1.0f -#define BASE_MAXDAMAGE 2.0f -#define BASE_ATTACK_TIME 2000 - -// byte value (UNIT_FIELD_BYTES_1, 0) -enum UnitStandStateType -{ - UNIT_STAND_STATE_STAND = 0, - UNIT_STAND_STATE_SIT = 1, - UNIT_STAND_STATE_SIT_CHAIR = 2, - UNIT_STAND_STATE_SLEEP = 3, - UNIT_STAND_STATE_SIT_LOW_CHAIR = 4, - UNIT_STAND_STATE_SIT_MEDIUM_CHAIR = 5, - UNIT_STAND_STATE_SIT_HIGH_CHAIR = 6, - UNIT_STAND_STATE_DEAD = 7, - UNIT_STAND_STATE_KNEEL = 8, - UNIT_STAND_STATE_SUBMERGED = 9 -}; - -// byte flag value (UNIT_FIELD_BYTES_1, 2) -enum UnitStandFlags -{ - UNIT_STAND_FLAGS_UNK1 = 0x01, - UNIT_STAND_FLAGS_CREEP = 0x02, - UNIT_STAND_FLAGS_UNTRACKABLE = 0x04, - UNIT_STAND_FLAGS_UNK4 = 0x08, - UNIT_STAND_FLAGS_UNK5 = 0x10, - UNIT_STAND_FLAGS_ALL = 0xFF -}; - -enum UnitBytes0Offsets -{ - UNIT_BYTES_0_OFFSET_RACE = 0, - UNIT_BYTES_0_OFFSET_CLASS = 1, - UNIT_BYTES_0_OFFSET_GENDER = 2, - UNIT_BYTES_0_OFFSET_POWER_TYPE = 3, -}; - -enum UnitBytes1Offsets -{ - UNIT_BYTES_1_OFFSET_STAND_STATE = 0, - UNIT_BYTES_1_OFFSET_PET_TALENTS = 1, - UNIT_BYTES_1_OFFSET_VIS_FLAG = 2, - UNIT_BYTES_1_OFFSET_ANIM_TIER = 3 -}; - -enum UnitBytes2Offsets -{ - UNIT_BYTES_2_OFFSET_SHEATH_STATE = 0, - UNIT_BYTES_2_OFFSET_PVP_FLAG = 1, - UNIT_BYTES_2_OFFSET_PET_FLAGS = 2, - UNIT_BYTES_2_OFFSET_SHAPESHIFT_FORM = 3 -}; - -// byte flags value (UNIT_FIELD_BYTES_1, 3) -enum UnitBytes1_Flags -{ - UNIT_BYTE1_FLAG_ALWAYS_STAND = 0x01, - UNIT_BYTE1_FLAG_HOVER = 0x02, - UNIT_BYTE1_FLAG_UNK_3 = 0x04, - UNIT_BYTE1_FLAG_ALL = 0xFF -}; - // high byte (3 from 0..3) of UNIT_FIELD_BYTES_2 enum ShapeshiftForm { @@ -260,36 +200,6 @@ enum ShapeshiftForm FORM_SPIRITOFREDEMPTION = 0x20 }; -// low byte (0 from 0..3) of UNIT_FIELD_BYTES_2 -enum SheathState -{ - SHEATH_STATE_UNARMED = 0, // non prepared weapon - SHEATH_STATE_MELEE = 1, // prepared melee weapon - SHEATH_STATE_RANGED = 2 // prepared ranged weapon -}; - -#define MAX_SHEATH_STATE 3 - -// byte (1 from 0..3) of UNIT_FIELD_BYTES_2 -enum UnitPVPStateFlags -{ - UNIT_BYTE2_FLAG_PVP = 0x01, - UNIT_BYTE2_FLAG_UNK1 = 0x02, - UNIT_BYTE2_FLAG_FFA_PVP = 0x04, - UNIT_BYTE2_FLAG_SANCTUARY = 0x08, - UNIT_BYTE2_FLAG_UNK4 = 0x10, - UNIT_BYTE2_FLAG_UNK5 = 0x20, - UNIT_BYTE2_FLAG_UNK6 = 0x40, - UNIT_BYTE2_FLAG_UNK7 = 0x80 -}; - -// byte (2 from 0..3) of UNIT_FIELD_BYTES_2 -enum UnitRename -{ - UNIT_CAN_BE_RENAMED = 0x01, - UNIT_CAN_BE_ABANDONED = 0x02 -}; - #define MAX_SPELL_CHARM 4 #define MAX_SPELL_VEHICLE 6 #define MAX_SPELL_POSSESS 8 @@ -311,36 +221,6 @@ enum VictimState VICTIMSTATE_DEFLECTS = 8 }; -enum HitInfo -{ - HITINFO_NORMALSWING = 0x00000000, - HITINFO_UNK1 = 0x00000001, // req correct packet structure - HITINFO_AFFECTS_VICTIM = 0x00000002, - HITINFO_OFFHAND = 0x00000004, - HITINFO_UNK2 = 0x00000008, - HITINFO_MISS = 0x00000010, - HITINFO_FULL_ABSORB = 0x00000020, - HITINFO_PARTIAL_ABSORB = 0x00000040, - HITINFO_FULL_RESIST = 0x00000080, - HITINFO_PARTIAL_RESIST = 0x00000100, - HITINFO_CRITICALHIT = 0x00000200, // critical hit - HITINFO_UNK10 = 0x00000400, - HITINFO_UNK11 = 0x00000800, - HITINFO_UNK12 = 0x00001000, - HITINFO_BLOCK = 0x00002000, // blocked damage - HITINFO_UNK14 = 0x00004000, // set only if meleespellid is present// no world text when victim is hit for 0 dmg(HideWorldTextForNoDamage?) - HITINFO_UNK15 = 0x00008000, // player victim?// something related to blod sprut visual (BloodSpurtInBack?) - HITINFO_GLANCING = 0x00010000, - HITINFO_CRUSHING = 0x00020000, - HITINFO_NO_ANIMATION = 0x00040000, - HITINFO_UNK19 = 0x00080000, - HITINFO_UNK20 = 0x00100000, - HITINFO_SWINGNOHITSOUND = 0x00200000, // unused? - HITINFO_UNK22 = 0x00400000, - HITINFO_RAGE_GAIN = 0x00800000, - HITINFO_FAKE_DAMAGE = 0x01000000 // enables damage animation even if no damage done, set only if no damage -}; - //i would like to remove this: (it is defined in item.h enum InventorySlot { @@ -349,40 +229,46 @@ enum InventorySlot }; struct FactionTemplateEntry; +struct LiquidData; +struct LiquidTypeEntry; struct SpellValue; -class AuraApplication; class Aura; -class UnitAura; +class AuraApplication; class AuraEffect; class Creature; -class Spell; -class SpellInfo; -class SpellHistory; class DynamicObject; class GameObject; +class Guardian; class Item; -class Pet; class Minion; -class Guardian; -class UnitAI; +class MotionMaster; +class Pet; +class PetAura; +class Spell; +class SpellCastTargets; +class SpellHistory; +class SpellInfo; class Totem; class Transport; +class TransportBase; +class UnitAI; +class UnitAura; class Vehicle; class VehicleJoinEvent; -class TransportBase; -class SpellCastTargets; + +enum ZLiquidStatus : uint32; typedef std::list UnitList; class DispelableAura { public: - DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges) : - _aura(aura), _chance(dispelChance), _charges(dispelCharges) { } + DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges); + ~DispelableAura(); Aura* GetAura() const { return _aura; } - bool RollDispel() const { return roll_chance_i(_chance); } + bool RollDispel() const; uint8 GetDispelCharges() const { return _charges; } void IncrementCharges() { ++_charges; } @@ -424,17 +310,7 @@ enum WeaponDamageRange MAXDAMAGE }; -enum AuraRemoveMode -{ - AURA_REMOVE_NONE = 0, - AURA_REMOVE_BY_DEFAULT = 1, // scripted remove, remove by stack with aura with different ids and sc aura remove - AURA_REMOVE_BY_CANCEL, - AURA_REMOVE_BY_ENEMY_SPELL, // dispel and absorb aura destroy - AURA_REMOVE_BY_EXPIRE, // aura duration has ended - AURA_REMOVE_BY_DEATH -}; - -enum TriggerCastFlags +enum TriggerCastFlags : uint32 { TRIGGERED_NONE = 0x00000000, //! Not triggered TRIGGERED_IGNORE_GCD = 0x00000001, //! Will ignore GCD @@ -625,7 +501,7 @@ enum CombatRating #define MAX_COMBAT_RATING 25 -enum DamageEffectType +enum DamageEffectType : uint8 { DIRECT_DAMAGE = 0, // used for normal weapon damage (not for class abilities or spells) SPELL_DIRECT_DAMAGE = 1, // spell/class abilities damage @@ -635,176 +511,6 @@ enum DamageEffectType SELF_DAMAGE = 5 }; -// Value masks for UNIT_FIELD_FLAGS -enum UnitFlags : uint32 -{ - UNIT_FLAG_SERVER_CONTROLLED = 0x00000001, // set only when unit movement is controlled by server - by SPLINE/MONSTER_MOVE packets, together with UNIT_FLAG_STUNNED; only set to units controlled by client; client function CGUnit_C::IsClientControlled returns false when set for owner - UNIT_FLAG_NON_ATTACKABLE = 0x00000002, // not attackable - UNIT_FLAG_REMOVE_CLIENT_CONTROL = 0x00000004, // This is a legacy flag used to disable movement player's movement while controlling other units, SMSG_CLIENT_CONTROL replaces this functionality clientside now. CONFUSED and FLEEING flags have the same effect on client movement asDISABLE_MOVE_CONTROL in addition to preventing spell casts/autoattack (they all allow climbing steeper hills and emotes while moving) - UNIT_FLAG_PVP_ATTACKABLE = 0x00000008, // allow apply pvp rules to attackable state in addition to faction dependent state - UNIT_FLAG_RENAME = 0x00000010, - UNIT_FLAG_PREPARATION = 0x00000020, // don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP - UNIT_FLAG_UNK_6 = 0x00000040, - UNIT_FLAG_NOT_ATTACKABLE_1 = 0x00000080, // ?? (UNIT_FLAG_PVP_ATTACKABLE | UNIT_FLAG_NOT_ATTACKABLE_1) is NON_PVP_ATTACKABLE - UNIT_FLAG_IMMUNE_TO_PC = 0x00000100, // disables combat/assistance with PlayerCharacters (PC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget - UNIT_FLAG_IMMUNE_TO_NPC = 0x00000200, // disables combat/assistance with NonPlayerCharacters (NPC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget - UNIT_FLAG_LOOTING = 0x00000400, // loot animation - UNIT_FLAG_PET_IN_COMBAT = 0x00000800, // in combat?, 2.0.8 - UNIT_FLAG_PVP = 0x00001000, // changed in 3.0.3 - UNIT_FLAG_SILENCED = 0x00002000, // silenced, 2.1.1 - UNIT_FLAG_CANNOT_SWIM = 0x00004000, // 2.0.8 - UNIT_FLAG_UNK_15 = 0x00008000, - UNIT_FLAG_UNK_16 = 0x00010000, - UNIT_FLAG_PACIFIED = 0x00020000, // 3.0.3 ok - UNIT_FLAG_STUNNED = 0x00040000, // 3.0.3 ok - UNIT_FLAG_IN_COMBAT = 0x00080000, - UNIT_FLAG_TAXI_FLIGHT = 0x00100000, // disable casting at client side spell not allowed by taxi flight (mounted?), probably used with 0x4 flag - UNIT_FLAG_DISARMED = 0x00200000, // 3.0.3, disable melee spells casting..., "Required melee weapon" added to melee spells tooltip. - UNIT_FLAG_CONFUSED = 0x00400000, - UNIT_FLAG_FLEEING = 0x00800000, - UNIT_FLAG_PLAYER_CONTROLLED = 0x01000000, // used in spell Eyes of the Beast for pet... let attack by controlled creature - UNIT_FLAG_NOT_SELECTABLE = 0x02000000, - UNIT_FLAG_SKINNABLE = 0x04000000, - UNIT_FLAG_MOUNT = 0x08000000, - UNIT_FLAG_UNK_28 = 0x10000000, - UNIT_FLAG_UNK_29 = 0x20000000, // used in Feing Death spell - UNIT_FLAG_SHEATHE = 0x40000000, - UNIT_FLAG_UNK_31 = 0x80000000, - MAX_UNIT_FLAGS = 33 -}; - -// Value masks for UNIT_FIELD_FLAGS_2 -enum UnitFlags2 -{ - UNIT_FLAG2_FEIGN_DEATH = 0x00000001, - UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip) - UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004, - UNIT_FLAG2_COMPREHEND_LANG = 0x00000008, - UNIT_FLAG2_MIRROR_IMAGE = 0x00000010, - UNIT_FLAG2_INSTANTLY_APPEAR_MODEL = 0x00000020, // Unit model instantly appears when summoned (does not fade in) - UNIT_FLAG2_FORCE_MOVEMENT = 0x00000040, - UNIT_FLAG2_DISARM_OFFHAND = 0x00000080, - UNIT_FLAG2_DISABLE_PRED_STATS = 0x00000100, // Player has disabled predicted stats (Used by raid frames) - UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?) - UNIT_FLAG2_REGENERATE_POWER = 0x00000800, - UNIT_FLAG2_RESTRICT_PARTY_INTERACTION = 0x00001000, // Restrict interaction to party or raid - UNIT_FLAG2_PREVENT_SPELL_CLICK = 0x00002000, // Prevent spellclick - UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000, - UNIT_FLAG2_DISABLE_TURN = 0x00008000, - UNIT_FLAG2_UNK2 = 0x00010000, - UNIT_FLAG2_PLAY_DEATH_ANIM = 0x00020000, // Plays special death animation upon death - UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000 // Allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL -}; - -/// Non Player Character flags -enum NPCFlags -{ - UNIT_NPC_FLAG_NONE = 0x00000000, - UNIT_NPC_FLAG_GOSSIP = 0x00000001, // 100% - UNIT_NPC_FLAG_QUESTGIVER = 0x00000002, // guessed, probably ok - UNIT_NPC_FLAG_UNK1 = 0x00000004, - UNIT_NPC_FLAG_UNK2 = 0x00000008, - UNIT_NPC_FLAG_TRAINER = 0x00000010, // 100% - UNIT_NPC_FLAG_TRAINER_CLASS = 0x00000020, // 100% - UNIT_NPC_FLAG_TRAINER_PROFESSION = 0x00000040, // 100% - UNIT_NPC_FLAG_VENDOR = 0x00000080, // 100% - UNIT_NPC_FLAG_VENDOR_AMMO = 0x00000100, // 100%, general goods vendor - UNIT_NPC_FLAG_VENDOR_FOOD = 0x00000200, // 100% - UNIT_NPC_FLAG_VENDOR_POISON = 0x00000400, // guessed - UNIT_NPC_FLAG_VENDOR_REAGENT = 0x00000800, // 100% - UNIT_NPC_FLAG_REPAIR = 0x00001000, // 100% - UNIT_NPC_FLAG_FLIGHTMASTER = 0x00002000, // 100% - UNIT_NPC_FLAG_SPIRITHEALER = 0x00004000, // guessed - UNIT_NPC_FLAG_SPIRITGUIDE = 0x00008000, // guessed - UNIT_NPC_FLAG_INNKEEPER = 0x00010000, // 100% - UNIT_NPC_FLAG_BANKER = 0x00020000, // 100% - UNIT_NPC_FLAG_PETITIONER = 0x00040000, // 100% 0xC0000 = guild petitions, 0x40000 = arena team petitions - UNIT_NPC_FLAG_TABARDDESIGNER = 0x00080000, // 100% - UNIT_NPC_FLAG_BATTLEMASTER = 0x00100000, // 100% - UNIT_NPC_FLAG_AUCTIONEER = 0x00200000, // 100% - UNIT_NPC_FLAG_STABLEMASTER = 0x00400000, // 100% - UNIT_NPC_FLAG_GUILD_BANKER = 0x00800000, // cause client to send 997 opcode - UNIT_NPC_FLAG_SPELLCLICK = 0x01000000, // cause client to send 1015 opcode (spell click) - UNIT_NPC_FLAG_PLAYER_VEHICLE = 0x02000000, // players with mounts that have vehicle data should have it set - UNIT_NPC_FLAG_MAILBOX = 0x04000000 // -}; - -enum MovementFlags -{ - MOVEMENTFLAG_NONE = 0x00000000, - MOVEMENTFLAG_FORWARD = 0x00000001, - MOVEMENTFLAG_BACKWARD = 0x00000002, - MOVEMENTFLAG_STRAFE_LEFT = 0x00000004, - MOVEMENTFLAG_STRAFE_RIGHT = 0x00000008, - MOVEMENTFLAG_LEFT = 0x00000010, - MOVEMENTFLAG_RIGHT = 0x00000020, - MOVEMENTFLAG_PITCH_UP = 0x00000040, - MOVEMENTFLAG_PITCH_DOWN = 0x00000080, - MOVEMENTFLAG_WALKING = 0x00000100, // Walking - MOVEMENTFLAG_ONTRANSPORT = 0x00000200, // Used for flying on some creatures - MOVEMENTFLAG_DISABLE_GRAVITY = 0x00000400, // Former MOVEMENTFLAG_LEVITATING. This is used when walking is not possible. - MOVEMENTFLAG_ROOT = 0x00000800, // Must not be set along with MOVEMENTFLAG_MASK_MOVING - MOVEMENTFLAG_FALLING = 0x00001000, // damage dealt on that type of falling - MOVEMENTFLAG_FALLING_FAR = 0x00002000, - MOVEMENTFLAG_PENDING_STOP = 0x00004000, - MOVEMENTFLAG_PENDING_STRAFE_STOP = 0x00008000, - MOVEMENTFLAG_PENDING_FORWARD = 0x00010000, - MOVEMENTFLAG_PENDING_BACKWARD = 0x00020000, - MOVEMENTFLAG_PENDING_STRAFE_LEFT = 0x00040000, - MOVEMENTFLAG_PENDING_STRAFE_RIGHT = 0x00080000, - MOVEMENTFLAG_PENDING_ROOT = 0x00100000, - MOVEMENTFLAG_SWIMMING = 0x00200000, // appears with fly flag also - MOVEMENTFLAG_ASCENDING = 0x00400000, // press "space" when flying - MOVEMENTFLAG_DESCENDING = 0x00800000, - MOVEMENTFLAG_CAN_FLY = 0x01000000, // Appears when unit can fly AND also walk - MOVEMENTFLAG_FLYING = 0x02000000, // unit is actually flying. pretty sure this is only used for players. creatures use disable_gravity - MOVEMENTFLAG_SPLINE_ELEVATION = 0x04000000, // used for flight paths - MOVEMENTFLAG_SPLINE_ENABLED = 0x08000000, // used for flight paths - MOVEMENTFLAG_WATERWALKING = 0x10000000, // prevent unit from falling through water - MOVEMENTFLAG_FALLING_SLOW = 0x20000000, // active rogue safe fall spell (passive) - MOVEMENTFLAG_HOVER = 0x40000000, // hover, cannot jump - - MOVEMENTFLAG_MASK_MOVING = - MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT | - MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING | - MOVEMENTFLAG_SPLINE_ELEVATION, - - MOVEMENTFLAG_MASK_TURNING = - MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT | MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN, - - MOVEMENTFLAG_MASK_MOVING_FLY = - MOVEMENTFLAG_FLYING | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING, - - /// @todo if needed: add more flags to this masks that are exclusive to players - MOVEMENTFLAG_MASK_PLAYER_ONLY = - MOVEMENTFLAG_FLYING, - - /// Movement flags that have change status opcodes associated for players - MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE = MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | - MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER -}; - -enum MovementFlags2 -{ - MOVEMENTFLAG2_NONE = 0x00000000, - MOVEMENTFLAG2_NO_STRAFE = 0x00000001, - MOVEMENTFLAG2_NO_JUMPING = 0x00000002, - MOVEMENTFLAG2_UNK3 = 0x00000004, // Overrides various clientside checks - MOVEMENTFLAG2_FULL_SPEED_TURNING = 0x00000008, - MOVEMENTFLAG2_FULL_SPEED_PITCHING = 0x00000010, - MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING = 0x00000020, - MOVEMENTFLAG2_UNK7 = 0x00000040, - MOVEMENTFLAG2_UNK8 = 0x00000080, - MOVEMENTFLAG2_UNK9 = 0x00000100, - MOVEMENTFLAG2_UNK10 = 0x00000200, - MOVEMENTFLAG2_INTERPOLATED_MOVEMENT = 0x00000400, - MOVEMENTFLAG2_INTERPOLATED_TURNING = 0x00000800, - MOVEMENTFLAG2_INTERPOLATED_PITCHING = 0x00001000, - MOVEMENTFLAG2_UNK14 = 0x00002000, - MOVEMENTFLAG2_UNK15 = 0x00004000, - MOVEMENTFLAG2_UNK16 = 0x00008000 -}; - enum UnitTypeMask { UNIT_MASK_NONE = 0x00000000, @@ -1065,14 +771,7 @@ struct RedirectThreatInfo } }; -#define MAX_DECLINED_NAME_CASES 5 - -struct DeclinedName -{ - std::string name[MAX_DECLINED_NAME_CASES]; -}; - -enum CurrentSpellTypes +enum CurrentSpellTypes : uint8 { CURRENT_MELEE_SPELL = 0, CURRENT_GENERIC_SPELL = 1, @@ -1083,31 +782,6 @@ enum CurrentSpellTypes #define CURRENT_FIRST_NON_MELEE_SPELL 1 #define CURRENT_MAX_SPELL 4 -enum ActiveStates -{ - ACT_PASSIVE = 0x01, // 0x01 - passive - ACT_DISABLED = 0x81, // 0x80 - castable - ACT_ENABLED = 0xC1, // 0x40 | 0x80 - auto cast + castable - ACT_COMMAND = 0x07, // 0x01 | 0x02 | 0x04 - ACT_REACTION = 0x06, // 0x02 | 0x04 - ACT_DECIDE = 0x00 // custom -}; - -enum ReactStates -{ - REACT_PASSIVE = 0, - REACT_DEFENSIVE = 1, - REACT_AGGRESSIVE = 2 -}; - -enum CommandStates : uint8 -{ - COMMAND_STAY = 0, - COMMAND_FOLLOW = 1, - COMMAND_ATTACK = 2, - COMMAND_ABANDON = 3 -}; - #define UNIT_ACTION_BUTTON_ACTION(X) (uint32(X) & 0x00FFFFFF) #define UNIT_ACTION_BUTTON_TYPE(X) ((uint32(X) & 0xFF000000) >> 24) #define MAKE_UNIT_ACTION_BUTTON(A, T) (uint32(A) | (uint32(T) << 24)) @@ -1286,7 +960,6 @@ class TC_GAME_API Unit : public WorldObject typedef std::list AuraEffectList; typedef std::list AuraList; typedef std::list AuraApplicationList; - typedef std::array Diminishing; typedef std::vector> AuraApplicationProcContainer; @@ -1323,10 +996,10 @@ class TC_GAME_API Unit : public WorldObject bool CanDualWield() const { return m_canDualWield; } virtual void SetCanDualWield(bool value) { m_canDualWield = value; } float GetCombatReach() const override { return m_floatValues[UNIT_FIELD_COMBATREACH]; } - bool IsWithinCombatRange(const Unit* obj, float dist2compare) const; + bool IsWithinCombatRange(Unit const* obj, float dist2compare) const; bool IsWithinMeleeRange(Unit const* obj) const; float GetMeleeRange(Unit const* target) const; - void GetRandomContactPoint(const Unit* target, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const; + void GetRandomContactPoint(Unit const* target, float& x, float& y, float& z, float distance2dMin, float distance2dMax) const; uint32 m_extraAttacks; bool m_canDualWield; @@ -1351,8 +1024,8 @@ class TC_GAME_API Unit : public WorldObject void CombatStop(bool includingCast = false); void CombatStopWithPets(bool includingCast = false); void StopAttackFaction(uint32 faction_id); - Unit* SelectNearbyTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const; - void SendMeleeAttackStop(Unit* victim = NULL); + Unit* SelectNearbyTarget(Unit* exclude = nullptr, float dist = NOMINAL_MELEE_RANGE) const; + void SendMeleeAttackStop(Unit* victim = nullptr); void SendMeleeAttackStart(Unit* victim); void AddUnitState(uint32 f) { m_state |= f; } @@ -1462,7 +1135,7 @@ class TC_GAME_API Unit : public WorldObject uint32 GetMaxSkillValueForLevel(Unit const* target = nullptr) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } void DealDamageMods(Unit const* victim, uint32 &damage, uint32* absorb) const; - uint32 DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = NULL, bool durabilityLoss = true); + uint32 DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage = nullptr, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = nullptr, bool durabilityLoss = true); void Kill(Unit* victim, bool durabilityLoss = true); void KillSelf(bool durabilityLoss = true) { Kill(this, durabilityLoss); } void DealHeal(HealInfo& healInfo); @@ -1524,7 +1197,7 @@ class TC_GAME_API Unit : public WorldObject uint32 GetDefenseSkillValue(Unit const* target = nullptr) const; uint32 GetWeaponSkillValue(WeaponAttackType attType, Unit const* target = nullptr) const; float GetWeaponProcChance() const; - float GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const; + float GetPPMProcChance(uint32 WeaponSpeed, float PPM, SpellInfo const* spellProto) const; MeleeHitOutcome RollMeleeOutcomeAgainst(Unit const* victim, WeaponAttackType attType) const; @@ -1552,7 +1225,7 @@ class TC_GAME_API Unit : public WorldObject bool IsPetInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); } bool IsInCombatWith(Unit const* who) const; void CombatStart(Unit* target, bool initialAggro = true); - void SetInCombatState(bool PvP, Unit* enemy = NULL); + void SetInCombatState(bool PvP, Unit* enemy = nullptr); void SetInCombatWith(Unit* enemy); void ClearInCombat(); void ClearInPetCombat(); @@ -1561,7 +1234,7 @@ class TC_GAME_API Unit : public WorldObject bool HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const; bool virtual HasSpell(uint32 /*spellID*/) const { return false; } bool HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura = 0) const; - bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = NULL) const; + bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = nullptr) const; bool HasStealthAura() const { return HasAuraType(SPELL_AURA_MOD_STEALTH); } bool HasInvisibilityAura() const { return HasAuraType(SPELL_AURA_MOD_INVISIBILITY); } @@ -1574,7 +1247,7 @@ class TC_GAME_API Unit : public WorldObject bool isTargetableForAttack(bool checkFakeDeath = true) const; bool IsValidAttackTarget(Unit const* target) const; - bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = NULL) const; + bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = nullptr) const; bool IsValidAssistTarget(Unit const* target) const; bool _IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const; @@ -1599,7 +1272,7 @@ class TC_GAME_API Unit : public WorldObject void CastCustomSpell(Unit* victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim, bool triggered, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); void CastCustomSpell(uint32 spellId, SpellValueMod mod, int32 value, Unit* victim = nullptr, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); - void CastCustomSpell(uint32 spellId, CustomSpellValues const &value, Unit* victim = nullptr, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); + void CastCustomSpell(uint32 spellId, CustomSpellValues const& value, Unit* victim = nullptr, TriggerCastFlags triggerFlags = TRIGGERED_NONE, Item* castItem = nullptr, AuraEffect const* triggeredByAura = nullptr, ObjectGuid originalCaster = ObjectGuid::Empty); Aura* AddAura(uint32 spellId, Unit* target); Aura* AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target); void SetAuraStack(uint32 spellId, Unit* target, uint32 stack); @@ -1622,7 +1295,7 @@ class TC_GAME_API Unit : public WorldObject void SendTeleportPacket(Position const& pos, bool teleportingTransport = false); virtual bool UpdatePosition(float x, float y, float z, float ang, bool teleport = false); // returns true if unit's position really changed - virtual bool UpdatePosition(const Position &pos, bool teleport = false); + virtual bool UpdatePosition(Position const& pos, bool teleport = false); void UpdateOrientation(float orientation); void UpdateHeight(float newZ); @@ -1631,8 +1304,8 @@ class TC_GAME_API Unit : public WorldObject void JumpTo(WorldObject* obj, float speedZ, bool withOrientation = false); void MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath = false, bool forceDestination = false); - //void SetFacing(float ori, WorldObject* obj = NULL); - //void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player = NULL); + //void SetFacing(float ori, WorldObject* obj = nullptr); + //void SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player = nullptr); void SendMovementFlagUpdate(bool self = false); bool IsLevitating() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_DISABLE_GRAVITY); } @@ -1702,7 +1375,7 @@ class TC_GAME_API Unit : public WorldObject void RemoveAllMinionsByEntry(uint32 entry); void SetCharm(Unit* target, bool apply); Unit* GetNextRandomRaidMemberOrPet(float radius); - bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = NULL); + bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = nullptr); void RemoveCharmedBy(Unit* charmer); void RestoreFaction(); @@ -1758,7 +1431,7 @@ class TC_GAME_API Unit : public WorldObject void RemoveOwnedAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); void RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - Aura* GetOwnedAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, Aura* except = NULL) const; + Aura* GetOwnedAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, Aura* except = nullptr) const; // m_appliedAuras container management AuraApplicationMap & GetAppliedAuras() { return m_appliedAuras; } @@ -1784,7 +1457,7 @@ class TC_GAME_API Unit : public WorldObject void RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, ObjectGuid casterGUID, Unit* dispeller, uint8 chargesRemoved = 1); void RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGUID, Unit* stealer); void RemoveAurasDueToItemSpell(uint32 spellId, ObjectGuid castItemGuid); - void RemoveAurasByType(AuraType auraType, ObjectGuid casterGUID = ObjectGuid::Empty, Aura* except = NULL, bool negative = true, bool positive = true); + void RemoveAurasByType(AuraType auraType, ObjectGuid casterGUID = ObjectGuid::Empty, Aura* except = nullptr, bool negative = true, bool positive = true); void RemoveNotOwnSingleTargetAuras(uint32 newPhase = 0x0); void RemoveAurasWithInterruptFlags(uint32 flag, uint32 except = 0); void RemoveAurasWithAttribute(uint32 flags); @@ -1817,10 +1490,10 @@ class TC_GAME_API Unit : public WorldObject AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, ObjectGuid casterGUID = ObjectGuid::Empty) const; AuraEffect* GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const; - AuraApplication * GetAuraApplication(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = NULL) const; + AuraApplication * GetAuraApplication(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = nullptr) const; Aura* GetAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0) const; - AuraApplication * GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = NULL) const; + AuraApplication * GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = nullptr) const; Aura* GetAuraOfRankedSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0) const; void GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList, bool isReflect = false) const; @@ -1987,7 +1660,7 @@ class TC_GAME_API Unit : public WorldObject // Threat related methods bool CanHaveThreatList(bool skipAliveCheck = false) const; - void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL); + void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); float ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL); void DeleteThreatList(); void TauntApply(Unit* victim); @@ -2029,11 +1702,11 @@ class TC_GAME_API Unit : public WorldObject void ModifyAuraState(AuraStateType flag, bool apply); uint32 BuildAuraStateUpdateForTarget(Unit* target) const; - bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = NULL, Unit const* Caster = NULL) const; + bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = nullptr, Unit const* Caster = nullptr) const; void UnsummonAllTotems(); bool IsMagnet() const; Unit* GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo); - Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = NULL); + Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = nullptr); int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) const; int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask) const; @@ -2046,8 +1719,8 @@ class TC_GAME_API Unit : public WorldObject float SpellHealingPctDone(Unit* victim, SpellInfo const* spellProto) const; uint32 SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack = 1) const; - uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const* spellProto = NULL); - uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto = NULL); + uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const* spellProto = nullptr); + uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto = nullptr); bool isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType attackType = BASE_ATTACK); bool isBlockCritical(); @@ -2059,7 +1732,7 @@ class TC_GAME_API Unit : public WorldObject void SetLastManaUse(uint32 spellCastTime) { m_lastManaUse = spellCastTime; } bool IsUnderLastManaUseEffect() const; - void SetContestedPvP(Player* attackedPlayer = NULL); + void SetContestedPvP(Player* attackedPlayer = nullptr); uint32 GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime) const; float CalculateDefaultCoefficient(SpellInfo const* spellInfo, DamageEffectType damagetype) const; @@ -2076,7 +1749,7 @@ class TC_GAME_API Unit : public WorldObject bool IsImmunedToDamage(SpellInfo const* spellInfo) const; virtual bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index, Unit* caster) const; // redefined in Creature - static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = NULL, uint8 effIndex = MAX_SPELL_EFFECTS); + static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = nullptr, int8 effIndex = -1); uint32 CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType = MAX_ATTACK) const; uint32 CalcSpellResistedDamage(Unit* victim, uint32 damage, SpellSchoolMask schoolMask, SpellInfo const* spellInfo) const; void CalcAbsorbResist(DamageInfo& damageInfo); @@ -2089,18 +1762,18 @@ class TC_GAME_API Unit : public WorldObject void SetSpeedRate(UnitMoveType mtype, float rate); float ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index, float value) const; - int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = NULL) const; + int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = nullptr) const; int32 CalcSpellDuration(SpellInfo const* spellProto); int32 ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask); - void ModSpellCastTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = NULL); - void ModSpellDurationTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = NULL); + void ModSpellCastTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = nullptr); + void ModSpellDurationTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = nullptr); float CalculateLevelPenalty(SpellInfo const* spellProto) const; void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); } void removeFollower(FollowerReference* /*pRef*/) { /* nothing to do yet */ } MotionMaster* GetMotionMaster() { return i_motionMaster; } - const MotionMaster* GetMotionMaster() const { return i_motionMaster; } + MotionMaster const* GetMotionMaster() const { return i_motionMaster; } bool IsStopped() const { return !(HasUnitState(UNIT_STATE_MOVING)); } void StopMoving(); @@ -2131,7 +1804,7 @@ class TC_GAME_API Unit : public WorldObject void SendPetAIReaction(ObjectGuid guid); ///----------End of Pet responses methods---------- - void PropagateSpeedChange() { GetMotionMaster()->PropagateSpeedChange(); } + void PropagateSpeedChange(); // reactive attacks void ClearAllReactives(); @@ -2163,7 +1836,7 @@ class TC_GAME_API Unit : public WorldObject Vehicle* GetVehicleKit()const { return m_vehicleKit; } Vehicle* GetVehicle() const { return m_vehicle; } void SetVehicle(Vehicle* vehicle) { m_vehicle = vehicle; } - bool IsOnVehicle(const Unit* vehicle) const; + bool IsOnVehicle(Unit const* vehicle) const; Unit* GetVehicleBase() const; Creature* GetVehicleCreatureBase() const; ObjectGuid GetTransGUID() const override; @@ -2174,12 +1847,12 @@ class TC_GAME_API Unit : public WorldObject bool HandleSpellClick(Unit* clicker, int8 seatId = -1); void EnterVehicle(Unit* base, int8 seatId = -1); - void ExitVehicle(Position const* exitPosition = NULL); + void ExitVehicle(Position const* exitPosition = nullptr); void ChangeSeat(int8 seatId, bool next = true); // Should only be called by AuraEffect::HandleAuraControlVehicle(AuraApplication const* auraApp, uint8 mode, bool apply) const; - void _ExitVehicle(Position const* exitPosition = NULL); - void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = NULL); + void _ExitVehicle(Position const* exitPosition = nullptr); + void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = nullptr); void BuildMovementPacket(ByteBuffer* data) const; static void BuildMovementPacket(Position const& pos, Position const& transportPos, MovementInfo const& movementInfo, ByteBuffer* data); @@ -2198,14 +1871,14 @@ class TC_GAME_API Unit : public WorldObject virtual bool IsLoading() const { return false; } bool IsDuringRemoveFromWorld() const {return m_duringRemoveFromWorld;} - Pet* ToPet() { if (IsPet()) return reinterpret_cast(this); else return NULL; } - Pet const* ToPet() const { if (IsPet()) return reinterpret_cast(this); else return NULL; } + Pet* ToPet() { if (IsPet()) return reinterpret_cast(this); else return nullptr; } + Pet const* ToPet() const { if (IsPet()) return reinterpret_cast(this); else return nullptr; } - Totem* ToTotem() { if (IsTotem()) return reinterpret_cast(this); else return NULL; } - Totem const* ToTotem() const { if (IsTotem()) return reinterpret_cast(this); else return NULL; } + Totem* ToTotem() { if (IsTotem()) return reinterpret_cast(this); else return nullptr; } + Totem const* ToTotem() const { if (IsTotem()) return reinterpret_cast(this); else return nullptr; } - TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast(this); else return NULL; } - TempSummon const* ToTempSummon() const { if (IsSummon()) return reinterpret_cast(this); else return NULL; } + TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } + TempSummon const* ToTempSummon() const { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } ObjectGuid GetTarget() const { return GetGuidValue(UNIT_FIELD_TARGET); } virtual void SetTarget(ObjectGuid /*guid*/) = 0; @@ -2334,7 +2007,7 @@ class TC_GAME_API Unit : public WorldObject uint32 m_lastManaUse; // msecs TimeTrackerSmall m_movesplineTimer; - Diminishing m_Diminishing; + DiminishingReturn m_Diminishing[DIMINISHING_MAX]; // Manage all Units that are threatened by us HostileRefManager m_HostileRefManager; @@ -2409,4 +2082,5 @@ namespace Trinity bool const _ascending; }; } + #endif diff --git a/src/server/game/Entities/Unit/UnitDefines.h b/src/server/game/Entities/Unit/UnitDefines.h new file mode 100644 index 00000000000..47f0ed28923 --- /dev/null +++ b/src/server/game/Entities/Unit/UnitDefines.h @@ -0,0 +1,352 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef UnitDefines_h__ +#define UnitDefines_h__ + +#include "Define.h" +#include + +#define BASE_MINDAMAGE 1.0f +#define BASE_MAXDAMAGE 2.0f +#define BASE_ATTACK_TIME 2000 + +#define MAX_EQUIPMENT_ITEMS 3 + +// byte value (UNIT_FIELD_BYTES_1, 0) +enum UnitStandStateType : uint8 +{ + UNIT_STAND_STATE_STAND = 0, + UNIT_STAND_STATE_SIT = 1, + UNIT_STAND_STATE_SIT_CHAIR = 2, + UNIT_STAND_STATE_SLEEP = 3, + UNIT_STAND_STATE_SIT_LOW_CHAIR = 4, + UNIT_STAND_STATE_SIT_MEDIUM_CHAIR = 5, + UNIT_STAND_STATE_SIT_HIGH_CHAIR = 6, + UNIT_STAND_STATE_DEAD = 7, + UNIT_STAND_STATE_KNEEL = 8, + UNIT_STAND_STATE_SUBMERGED = 9 +}; + +// byte flag value (UNIT_FIELD_BYTES_1, 2) +enum UnitStandFlags : uint8 +{ + UNIT_STAND_FLAGS_UNK1 = 0x01, + UNIT_STAND_FLAGS_CREEP = 0x02, + UNIT_STAND_FLAGS_UNTRACKABLE = 0x04, + UNIT_STAND_FLAGS_UNK4 = 0x08, + UNIT_STAND_FLAGS_UNK5 = 0x10, + UNIT_STAND_FLAGS_ALL = 0xFF +}; + +enum UnitBytes0Offsets : uint8 +{ + UNIT_BYTES_0_OFFSET_RACE = 0, + UNIT_BYTES_0_OFFSET_CLASS = 1, + UNIT_BYTES_0_OFFSET_GENDER = 2, + UNIT_BYTES_0_OFFSET_POWER_TYPE = 3, +}; + +enum UnitBytes1Offsets : uint8 +{ + UNIT_BYTES_1_OFFSET_STAND_STATE = 0, + UNIT_BYTES_1_OFFSET_PET_TALENTS = 1, + UNIT_BYTES_1_OFFSET_VIS_FLAG = 2, + UNIT_BYTES_1_OFFSET_ANIM_TIER = 3 +}; + +enum UnitBytes2Offsets : uint8 +{ + UNIT_BYTES_2_OFFSET_SHEATH_STATE = 0, + UNIT_BYTES_2_OFFSET_PVP_FLAG = 1, + UNIT_BYTES_2_OFFSET_PET_FLAGS = 2, + UNIT_BYTES_2_OFFSET_SHAPESHIFT_FORM = 3 +}; + +// byte flags value (UNIT_FIELD_BYTES_1, 3) +enum UnitBytes1_Flags : uint8 +{ + UNIT_BYTE1_FLAG_ALWAYS_STAND = 0x01, + UNIT_BYTE1_FLAG_HOVER = 0x02, + UNIT_BYTE1_FLAG_UNK_3 = 0x04, + UNIT_BYTE1_FLAG_ALL = 0xFF +}; + +// low byte (0 from 0..3) of UNIT_FIELD_BYTES_2 +enum SheathState : uint8 +{ + SHEATH_STATE_UNARMED = 0, // non prepared weapon + SHEATH_STATE_MELEE = 1, // prepared melee weapon + SHEATH_STATE_RANGED = 2 // prepared ranged weapon +}; + +#define MAX_SHEATH_STATE 3 + +// byte (1 from 0..3) of UNIT_FIELD_BYTES_2 +enum UnitPVPStateFlags : uint8 +{ + UNIT_BYTE2_FLAG_PVP = 0x01, + UNIT_BYTE2_FLAG_UNK1 = 0x02, + UNIT_BYTE2_FLAG_FFA_PVP = 0x04, + UNIT_BYTE2_FLAG_SANCTUARY = 0x08, + UNIT_BYTE2_FLAG_UNK4 = 0x10, + UNIT_BYTE2_FLAG_UNK5 = 0x20, + UNIT_BYTE2_FLAG_UNK6 = 0x40, + UNIT_BYTE2_FLAG_UNK7 = 0x80 +}; + +// byte (2 from 0..3) of UNIT_FIELD_BYTES_2 +enum UnitRename : uint8 +{ + UNIT_CAN_BE_RENAMED = 0x01, + UNIT_CAN_BE_ABANDONED = 0x02 +}; + +// Value masks for UNIT_FIELD_FLAGS +enum UnitFlags : uint32 +{ + UNIT_FLAG_SERVER_CONTROLLED = 0x00000001, // set only when unit movement is controlled by server - by SPLINE/MONSTER_MOVE packets, together with UNIT_FLAG_STUNNED; only set to units controlled by client; client function CGUnit_C::IsClientControlled returns false when set for owner + UNIT_FLAG_NON_ATTACKABLE = 0x00000002, // not attackable + UNIT_FLAG_REMOVE_CLIENT_CONTROL = 0x00000004, // This is a legacy flag used to disable movement player's movement while controlling other units, SMSG_CLIENT_CONTROL replaces this functionality clientside now. CONFUSED and FLEEING flags have the same effect on client movement asDISABLE_MOVE_CONTROL in addition to preventing spell casts/autoattack (they all allow climbing steeper hills and emotes while moving) + UNIT_FLAG_PVP_ATTACKABLE = 0x00000008, // allow apply pvp rules to attackable state in addition to faction dependent state + UNIT_FLAG_RENAME = 0x00000010, + UNIT_FLAG_PREPARATION = 0x00000020, // don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP + UNIT_FLAG_UNK_6 = 0x00000040, + UNIT_FLAG_NOT_ATTACKABLE_1 = 0x00000080, // ?? (UNIT_FLAG_PVP_ATTACKABLE | UNIT_FLAG_NOT_ATTACKABLE_1) is NON_PVP_ATTACKABLE + UNIT_FLAG_IMMUNE_TO_PC = 0x00000100, // disables combat/assistance with PlayerCharacters (PC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget + UNIT_FLAG_IMMUNE_TO_NPC = 0x00000200, // disables combat/assistance with NonPlayerCharacters (NPC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget + UNIT_FLAG_LOOTING = 0x00000400, // loot animation + UNIT_FLAG_PET_IN_COMBAT = 0x00000800, // in combat?, 2.0.8 + UNIT_FLAG_PVP = 0x00001000, // changed in 3.0.3 + UNIT_FLAG_SILENCED = 0x00002000, // silenced, 2.1.1 + UNIT_FLAG_CANNOT_SWIM = 0x00004000, // 2.0.8 + UNIT_FLAG_UNK_15 = 0x00008000, + UNIT_FLAG_UNK_16 = 0x00010000, + UNIT_FLAG_PACIFIED = 0x00020000, // 3.0.3 ok + UNIT_FLAG_STUNNED = 0x00040000, // 3.0.3 ok + UNIT_FLAG_IN_COMBAT = 0x00080000, + UNIT_FLAG_TAXI_FLIGHT = 0x00100000, // disable casting at client side spell not allowed by taxi flight (mounted?), probably used with 0x4 flag + UNIT_FLAG_DISARMED = 0x00200000, // 3.0.3, disable melee spells casting..., "Required melee weapon" added to melee spells tooltip. + UNIT_FLAG_CONFUSED = 0x00400000, + UNIT_FLAG_FLEEING = 0x00800000, + UNIT_FLAG_PLAYER_CONTROLLED = 0x01000000, // used in spell Eyes of the Beast for pet... let attack by controlled creature + UNIT_FLAG_NOT_SELECTABLE = 0x02000000, + UNIT_FLAG_SKINNABLE = 0x04000000, + UNIT_FLAG_MOUNT = 0x08000000, + UNIT_FLAG_UNK_28 = 0x10000000, + UNIT_FLAG_UNK_29 = 0x20000000, // used in Feing Death spell + UNIT_FLAG_SHEATHE = 0x40000000, + UNIT_FLAG_UNK_31 = 0x80000000, + MAX_UNIT_FLAGS = 33 +}; + +// Value masks for UNIT_FIELD_FLAGS_2 +enum UnitFlags2 : uint32 +{ + UNIT_FLAG2_FEIGN_DEATH = 0x00000001, + UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip) + UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004, + UNIT_FLAG2_COMPREHEND_LANG = 0x00000008, + UNIT_FLAG2_MIRROR_IMAGE = 0x00000010, + UNIT_FLAG2_INSTANTLY_APPEAR_MODEL = 0x00000020, // Unit model instantly appears when summoned (does not fade in) + UNIT_FLAG2_FORCE_MOVEMENT = 0x00000040, + UNIT_FLAG2_DISARM_OFFHAND = 0x00000080, + UNIT_FLAG2_DISABLE_PRED_STATS = 0x00000100, // Player has disabled predicted stats (Used by raid frames) + UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?) + UNIT_FLAG2_REGENERATE_POWER = 0x00000800, + UNIT_FLAG2_RESTRICT_PARTY_INTERACTION = 0x00001000, // Restrict interaction to party or raid + UNIT_FLAG2_PREVENT_SPELL_CLICK = 0x00002000, // Prevent spellclick + UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000, + UNIT_FLAG2_DISABLE_TURN = 0x00008000, + UNIT_FLAG2_UNK2 = 0x00010000, + UNIT_FLAG2_PLAY_DEATH_ANIM = 0x00020000, // Plays special death animation upon death + UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000 // Allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL +}; + +/// Non Player Character flags +enum NPCFlags : uint32 +{ + UNIT_NPC_FLAG_NONE = 0x00000000, + UNIT_NPC_FLAG_GOSSIP = 0x00000001, // 100% + UNIT_NPC_FLAG_QUESTGIVER = 0x00000002, // guessed, probably ok + UNIT_NPC_FLAG_UNK1 = 0x00000004, + UNIT_NPC_FLAG_UNK2 = 0x00000008, + UNIT_NPC_FLAG_TRAINER = 0x00000010, // 100% + UNIT_NPC_FLAG_TRAINER_CLASS = 0x00000020, // 100% + UNIT_NPC_FLAG_TRAINER_PROFESSION = 0x00000040, // 100% + UNIT_NPC_FLAG_VENDOR = 0x00000080, // 100% + UNIT_NPC_FLAG_VENDOR_AMMO = 0x00000100, // 100%, general goods vendor + UNIT_NPC_FLAG_VENDOR_FOOD = 0x00000200, // 100% + UNIT_NPC_FLAG_VENDOR_POISON = 0x00000400, // guessed + UNIT_NPC_FLAG_VENDOR_REAGENT = 0x00000800, // 100% + UNIT_NPC_FLAG_REPAIR = 0x00001000, // 100% + UNIT_NPC_FLAG_FLIGHTMASTER = 0x00002000, // 100% + UNIT_NPC_FLAG_SPIRITHEALER = 0x00004000, // guessed + UNIT_NPC_FLAG_SPIRITGUIDE = 0x00008000, // guessed + UNIT_NPC_FLAG_INNKEEPER = 0x00010000, // 100% + UNIT_NPC_FLAG_BANKER = 0x00020000, // 100% + UNIT_NPC_FLAG_PETITIONER = 0x00040000, // 100% 0xC0000 = guild petitions, 0x40000 = arena team petitions + UNIT_NPC_FLAG_TABARDDESIGNER = 0x00080000, // 100% + UNIT_NPC_FLAG_BATTLEMASTER = 0x00100000, // 100% + UNIT_NPC_FLAG_AUCTIONEER = 0x00200000, // 100% + UNIT_NPC_FLAG_STABLEMASTER = 0x00400000, // 100% + UNIT_NPC_FLAG_GUILD_BANKER = 0x00800000, // cause client to send 997 opcode + UNIT_NPC_FLAG_SPELLCLICK = 0x01000000, // cause client to send 1015 opcode (spell click) + UNIT_NPC_FLAG_PLAYER_VEHICLE = 0x02000000, // players with mounts that have vehicle data should have it set + UNIT_NPC_FLAG_MAILBOX = 0x04000000 // +}; + +enum MovementFlags : uint32 +{ + MOVEMENTFLAG_NONE = 0x00000000, + MOVEMENTFLAG_FORWARD = 0x00000001, + MOVEMENTFLAG_BACKWARD = 0x00000002, + MOVEMENTFLAG_STRAFE_LEFT = 0x00000004, + MOVEMENTFLAG_STRAFE_RIGHT = 0x00000008, + MOVEMENTFLAG_LEFT = 0x00000010, + MOVEMENTFLAG_RIGHT = 0x00000020, + MOVEMENTFLAG_PITCH_UP = 0x00000040, + MOVEMENTFLAG_PITCH_DOWN = 0x00000080, + MOVEMENTFLAG_WALKING = 0x00000100, // Walking + MOVEMENTFLAG_ONTRANSPORT = 0x00000200, // Used for flying on some creatures + MOVEMENTFLAG_DISABLE_GRAVITY = 0x00000400, // Former MOVEMENTFLAG_LEVITATING. This is used when walking is not possible. + MOVEMENTFLAG_ROOT = 0x00000800, // Must not be set along with MOVEMENTFLAG_MASK_MOVING + MOVEMENTFLAG_FALLING = 0x00001000, // damage dealt on that type of falling + MOVEMENTFLAG_FALLING_FAR = 0x00002000, + MOVEMENTFLAG_PENDING_STOP = 0x00004000, + MOVEMENTFLAG_PENDING_STRAFE_STOP = 0x00008000, + MOVEMENTFLAG_PENDING_FORWARD = 0x00010000, + MOVEMENTFLAG_PENDING_BACKWARD = 0x00020000, + MOVEMENTFLAG_PENDING_STRAFE_LEFT = 0x00040000, + MOVEMENTFLAG_PENDING_STRAFE_RIGHT = 0x00080000, + MOVEMENTFLAG_PENDING_ROOT = 0x00100000, + MOVEMENTFLAG_SWIMMING = 0x00200000, // appears with fly flag also + MOVEMENTFLAG_ASCENDING = 0x00400000, // press "space" when flying + MOVEMENTFLAG_DESCENDING = 0x00800000, + MOVEMENTFLAG_CAN_FLY = 0x01000000, // Appears when unit can fly AND also walk + MOVEMENTFLAG_FLYING = 0x02000000, // unit is actually flying. pretty sure this is only used for players. creatures use disable_gravity + MOVEMENTFLAG_SPLINE_ELEVATION = 0x04000000, // used for flight paths + MOVEMENTFLAG_SPLINE_ENABLED = 0x08000000, // used for flight paths + MOVEMENTFLAG_WATERWALKING = 0x10000000, // prevent unit from falling through water + MOVEMENTFLAG_FALLING_SLOW = 0x20000000, // active rogue safe fall spell (passive) + MOVEMENTFLAG_HOVER = 0x40000000, // hover, cannot jump + + MOVEMENTFLAG_MASK_MOVING = + MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT | + MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING | + MOVEMENTFLAG_SPLINE_ELEVATION, + + MOVEMENTFLAG_MASK_TURNING = + MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT | MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN, + + MOVEMENTFLAG_MASK_MOVING_FLY = + MOVEMENTFLAG_FLYING | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING, + + /// @todo if needed: add more flags to this masks that are exclusive to players + MOVEMENTFLAG_MASK_PLAYER_ONLY = + MOVEMENTFLAG_FLYING, + + /// Movement flags that have change status opcodes associated for players + MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE = MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | + MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER +}; + +enum MovementFlags2 : uint32 +{ + MOVEMENTFLAG2_NONE = 0x00000000, + MOVEMENTFLAG2_NO_STRAFE = 0x00000001, + MOVEMENTFLAG2_NO_JUMPING = 0x00000002, + MOVEMENTFLAG2_UNK3 = 0x00000004, // Overrides various clientside checks + MOVEMENTFLAG2_FULL_SPEED_TURNING = 0x00000008, + MOVEMENTFLAG2_FULL_SPEED_PITCHING = 0x00000010, + MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING = 0x00000020, + MOVEMENTFLAG2_UNK7 = 0x00000040, + MOVEMENTFLAG2_UNK8 = 0x00000080, + MOVEMENTFLAG2_UNK9 = 0x00000100, + MOVEMENTFLAG2_UNK10 = 0x00000200, + MOVEMENTFLAG2_INTERPOLATED_MOVEMENT = 0x00000400, + MOVEMENTFLAG2_INTERPOLATED_TURNING = 0x00000800, + MOVEMENTFLAG2_INTERPOLATED_PITCHING = 0x00001000, + MOVEMENTFLAG2_UNK14 = 0x00002000, + MOVEMENTFLAG2_UNK15 = 0x00004000, + MOVEMENTFLAG2_UNK16 = 0x00008000 +}; + +enum HitInfo +{ + HITINFO_NORMALSWING = 0x00000000, + HITINFO_UNK1 = 0x00000001, // req correct packet structure + HITINFO_AFFECTS_VICTIM = 0x00000002, + HITINFO_OFFHAND = 0x00000004, + HITINFO_UNK2 = 0x00000008, + HITINFO_MISS = 0x00000010, + HITINFO_FULL_ABSORB = 0x00000020, + HITINFO_PARTIAL_ABSORB = 0x00000040, + HITINFO_FULL_RESIST = 0x00000080, + HITINFO_PARTIAL_RESIST = 0x00000100, + HITINFO_CRITICALHIT = 0x00000200, // critical hit + HITINFO_UNK10 = 0x00000400, + HITINFO_UNK11 = 0x00000800, + HITINFO_UNK12 = 0x00001000, + HITINFO_BLOCK = 0x00002000, // blocked damage + HITINFO_UNK14 = 0x00004000, // set only if meleespellid is present// no world text when victim is hit for 0 dmg(HideWorldTextForNoDamage?) + HITINFO_UNK15 = 0x00008000, // player victim?// something related to blod sprut visual (BloodSpurtInBack?) + HITINFO_GLANCING = 0x00010000, + HITINFO_CRUSHING = 0x00020000, + HITINFO_NO_ANIMATION = 0x00040000, + HITINFO_UNK19 = 0x00080000, + HITINFO_UNK20 = 0x00100000, + HITINFO_SWINGNOHITSOUND = 0x00200000, // unused? + HITINFO_UNK22 = 0x00400000, + HITINFO_RAGE_GAIN = 0x00800000, + HITINFO_FAKE_DAMAGE = 0x01000000 // enables damage animation even if no damage done, set only if no damage +}; + +#define MAX_DECLINED_NAME_CASES 5 + +struct DeclinedName +{ + std::string name[MAX_DECLINED_NAME_CASES]; +}; + +enum ActiveStates +{ + ACT_PASSIVE = 0x01, // 0x01 - passive + ACT_DISABLED = 0x81, // 0x80 - castable + ACT_ENABLED = 0xC1, // 0x40 | 0x80 - auto cast + castable + ACT_COMMAND = 0x07, // 0x01 | 0x02 | 0x04 + ACT_REACTION = 0x06, // 0x02 | 0x04 + ACT_DECIDE = 0x00 // custom +}; + +enum ReactStates +{ + REACT_PASSIVE = 0, + REACT_DEFENSIVE = 1, + REACT_AGGRESSIVE = 2 +}; + +enum CommandStates : uint8 +{ + COMMAND_STAY = 0, + COMMAND_FOLLOW = 1, + COMMAND_ATTACK = 2, + COMMAND_ABANDON = 3 +}; + +#endif // UnitDefines_h__ diff --git a/src/server/game/Entities/Vehicle/Vehicle.cpp b/src/server/game/Entities/Vehicle/Vehicle.cpp index 8c71df670ad..357cceb99b6 100755 --- a/src/server/game/Entities/Vehicle/Vehicle.cpp +++ b/src/server/game/Entities/Vehicle/Vehicle.cpp @@ -16,19 +16,21 @@ * with this program. If not, see . */ +#include "Vehicle.h" +#include "Battleground.h" #include "Common.h" +#include "CreatureAI.h" +#include "DBCStores.h" +#include "EventProcessor.h" #include "Log.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "Vehicle.h" -#include "Unit.h" -#include "Util.h" +#include "Player.h" #include "ScriptMgr.h" -#include "CreatureAI.h" -#include "MoveSplineInit.h" #include "TemporarySummon.h" -#include "EventProcessor.h" -#include "Player.h" -#include "Battleground.h" +#include "Unit.h" +#include "Util.h" Vehicle::Vehicle(Unit* unit, VehicleEntry const* vehInfo, uint32 creatureEntry) : UsableSeatNum(0), _me(unit), _vehicleInfo(vehInfo), _creatureEntry(creatureEntry), _status(STATUS_NONE), _lastShootPos() @@ -239,7 +241,7 @@ void Vehicle::RemoveAllPassengers() /// This will properly "reset" the pending join process for the passenger. { /// Update vehicle pointer in every pending join event - Abort may be called after vehicle is deleted - Vehicle* eventVehicle = _status != STATUS_UNINSTALLING ? this : NULL; + Vehicle* eventVehicle = _status != STATUS_UNINSTALLING ? this : nullptr; while (!_pendingJoinEvents.empty()) { @@ -300,7 +302,7 @@ Unit* Vehicle::GetPassenger(int8 seatId) const { SeatMap::const_iterator seat = Seats.find(seatId); if (seat == Seats.end()) - return NULL; + return nullptr; return ObjectAccessor::GetUnit(*GetBase(), seat->second.Passenger.Guid); } @@ -480,7 +482,7 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) Vehicle* Vehicle::RemovePassenger(Unit* unit) { if (unit->GetVehicle() != this) - return NULL; + return nullptr; SeatMap::iterator seat = GetSeatIteratorForPassenger(unit); ASSERT(seat != Seats.end()); @@ -521,7 +523,7 @@ Vehicle* Vehicle::RemovePassenger(Unit* unit) if (GetBase()->GetTypeId() == TYPEID_UNIT) sScriptMgr->OnRemovePassenger(this, unit); - unit->SetVehicle(NULL); + unit->SetVehicle(nullptr); return this; } @@ -623,7 +625,7 @@ VehicleSeatEntry const* Vehicle::GetSeatForPassenger(Unit const* passenger) cons if (itr->second.Passenger.Guid == passenger->GetGUID()) return itr->second.SeatInfo; - return NULL; + return nullptr; } /** diff --git a/src/server/game/Entities/Vehicle/Vehicle.h b/src/server/game/Entities/Vehicle/Vehicle.h index 08f3e7f8f1a..d022174bd08 100644 --- a/src/server/game/Entities/Vehicle/Vehicle.h +++ b/src/server/game/Entities/Vehicle/Vehicle.h @@ -87,7 +87,7 @@ class TC_GAME_API Vehicle : public TransportBase void InitMovementInfoForBase(); /// This method transforms supplied transport offsets into global coordinates - void CalculatePassengerPosition(float& x, float& y, float& z, float* o /*= NULL*/) const override + void CalculatePassengerPosition(float& x, float& y, float& z, float* o /*= nullptr*/) const override { TransportBase::CalculatePassengerPosition(x, y, z, o, GetBase()->GetPositionX(), GetBase()->GetPositionY(), @@ -95,7 +95,7 @@ class TC_GAME_API Vehicle : public TransportBase } /// This method transforms supplied global coordinates into local offsets - void CalculatePassengerOffset(float& x, float& y, float& z, float* o /*= NULL*/) const override + void CalculatePassengerOffset(float& x, float& y, float& z, float* o /*= nullptr*/) const override { TransportBase::CalculatePassengerOffset(x, y, z, o, GetBase()->GetPositionX(), GetBase()->GetPositionY(), diff --git a/src/server/game/Entities/Vehicle/VehicleDefines.h b/src/server/game/Entities/Vehicle/VehicleDefines.h index 0b53465bba6..e4d41276d64 100644 --- a/src/server/game/Entities/Vehicle/VehicleDefines.h +++ b/src/server/game/Entities/Vehicle/VehicleDefines.h @@ -102,10 +102,10 @@ protected: public: /// This method transforms supplied transport offsets into global coordinates - virtual void CalculatePassengerPosition(float& x, float& y, float& z, float* o = NULL) const = 0; + virtual void CalculatePassengerPosition(float& x, float& y, float& z, float* o = nullptr) const = 0; /// This method transforms supplied global coordinates into local offsets - virtual void CalculatePassengerOffset(float& x, float& y, float& z, float* o = NULL) const = 0; + virtual void CalculatePassengerOffset(float& x, float& y, float& z, float* o = nullptr) const = 0; protected: static void CalculatePassengerPosition(float& x, float& y, float& z, float* o, float transX, float transY, float transZ, float transO) diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index b126eb9c644..fc00ce5ee9e 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -17,17 +17,19 @@ */ #include "GameEventMgr.h" -#include "World.h" -#include "ObjectMgr.h" -#include "WorldPacket.h" -#include "PoolMgr.h" +#include "BattlegroundMgr.h" +#include "CreatureAI.h" +#include "DBCStores.h" +#include "DatabaseEnv.h" +#include "GameObjectAI.h" #include "Language.h" #include "Log.h" #include "MapManager.h" +#include "ObjectMgr.h" +#include "PoolMgr.h" #include "Player.h" -#include "BattlegroundMgr.h" -#include "UnitAI.h" -#include "GameObjectAI.h" +#include "World.h" +#include "WorldPacket.h" GameEventMgr* GameEventMgr::instance() { @@ -42,7 +44,7 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const default: case GAMEEVENT_NORMAL: { - time_t currenttime = time(NULL); + time_t currenttime = time(nullptr); // Get the event information return mGameEvent[entry].start < currenttime && currenttime < mGameEvent[entry].end @@ -59,7 +61,7 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const // if inactive world event, check the prerequisite events case GAMEEVENT_WORLD_INACTIVE: { - time_t currenttime = time(NULL); + time_t currenttime = time(nullptr); for (std::set::const_iterator itr = mGameEvent[entry].prerequisite_events.begin(); itr != mGameEvent[entry].prerequisite_events.end(); ++itr) { if ((mGameEvent[*itr].state != GAMEEVENT_WORLD_NEXTPHASE && mGameEvent[*itr].state != GAMEEVENT_WORLD_FINISHED) || // if prereq not in nextphase or finished state, then can't start this one @@ -75,7 +77,7 @@ bool GameEventMgr::CheckOneGameEvent(uint16 entry) const uint32 GameEventMgr::NextCheck(uint16 entry) const { - time_t currenttime = time(NULL); + time_t currenttime = time(nullptr); // for NEXTPHASE state world events, return the delay to start the next event, so the followup event will be checked correctly if ((mGameEvent[entry].state == GAMEEVENT_WORLD_NEXTPHASE || mGameEvent[entry].state == GAMEEVENT_WORLD_FINISHED) && mGameEvent[entry].nextstart >= currenttime) @@ -135,13 +137,13 @@ bool GameEventMgr::StartEvent(uint16 event_id, bool overwrite) ApplyNewEvent(event_id); if (overwrite) { - mGameEvent[event_id].start = time(NULL); + mGameEvent[event_id].start = time(nullptr); if (data.end <= data.start) data.end = data.start + data.length; } // When event is started, set its worldstate to current time - sWorld->setWorldState(event_id, time(NULL)); + sWorld->setWorldState(event_id, time(nullptr)); return false; } else @@ -182,7 +184,7 @@ void GameEventMgr::StopEvent(uint16 event_id, bool overwrite) if (overwrite && !serverwide_evt) { - data.start = time(NULL) - data.length * MINUTE; + data.start = time(nullptr) - data.length * MINUTE; if (data.end <= data.start) data.end = data.start + data.length; } @@ -464,7 +466,7 @@ void GameEventMgr::LoadFromDB() // 0 1 2 3 4 QueryResult result = WorldDatabase.Query("SELECT creature.guid, creature.id, game_event_model_equip.eventEntry, game_event_model_equip.modelid, game_event_model_equip.equipment_id " - "FROM creature JOIN game_event_model_equip ON creature.guid=game_event_model_equip.guid"); + "FROM creature JOIN game_event_model_equip ON creature.guid = game_event_model_equip.guid"); if (!result) TC_LOG_INFO("server.loading", ">> Loaded 0 model/equipment changes in game events. DB table `game_event_model_equip` is empty."); @@ -834,7 +836,7 @@ void GameEventMgr::LoadFromDB() newEntry.entry = data->id; // check validity with event's npcflag - if (!sObjectMgr->IsVendorItemValid(newEntry.entry, newEntry.item, newEntry.maxcount, newEntry.incrtime, newEntry.ExtendedCost, NULL, NULL, event_npc_flag)) + if (!sObjectMgr->IsVendorItemValid(newEntry.entry, newEntry.item, newEntry.maxcount, newEntry.incrtime, newEntry.ExtendedCost, nullptr, nullptr, event_npc_flag)) continue; vendors.push_back(newEntry); @@ -1004,7 +1006,7 @@ void GameEventMgr::StartArenaSeason() uint32 GameEventMgr::Update() // return the next event delay in ms { - time_t currenttime = time(NULL); + time_t currenttime = time(nullptr); uint32 nextEventDelay = max_ge_check_delay; // 1 day uint32 calcDelay; std::set activate, deactivate; @@ -1592,7 +1594,7 @@ bool GameEventMgr::CheckOneGameEventConditions(uint16 event_id) // set the followup events' start time if (!mGameEvent[event_id].nextstart) { - time_t currenttime = time(NULL); + time_t currenttime = time(nullptr); mGameEvent[event_id].nextstart = currenttime + mGameEvent[event_id].length * 60; } return true; diff --git a/src/server/game/Events/GameEventMgr.h b/src/server/game/Events/GameEventMgr.h index 05737b23426..bee6dfc8fb3 100644 --- a/src/server/game/Events/GameEventMgr.h +++ b/src/server/game/Events/GameEventMgr.h @@ -23,6 +23,11 @@ #include "ObjectGuid.h" #include "SharedDefines.h" #include "Define.h" +#include +#include +#include +#include +#include #define max_ge_check_delay DAY // 1 day in seconds diff --git a/src/server/game/Globals/ObjectAccessor.cpp b/src/server/game/Globals/ObjectAccessor.cpp index 71da19b1bc6..d4dfb96485e 100644 --- a/src/server/game/Globals/ObjectAccessor.cpp +++ b/src/server/game/Globals/ObjectAccessor.cpp @@ -37,6 +37,10 @@ template void HashMapHolder::Insert(T* o) { + static_assert(std::is_same::value + || std::is_same::value, + "Only Player and Transport can be registered in global HashMapHolder"); + boost::unique_lock lock(*GetLock()); GetContainer()[o->GetGUID()] = o; @@ -56,7 +60,7 @@ T* HashMapHolder::Find(ObjectGuid guid) boost::shared_lock lock(*GetLock()); typename MapType::iterator itr = GetContainer().find(guid); - return (itr != GetContainer().end()) ? itr->second : NULL; + return (itr != GetContainer().end()) ? itr->second : nullptr; } template @@ -120,7 +124,7 @@ WorldObject* ObjectAccessor::GetWorldObject(WorldObject const& p, ObjectGuid con case HighGuid::Pet: return GetPet(p, guid); case HighGuid::DynamicObject: return GetDynamicObject(p, guid); case HighGuid::Corpse: return GetCorpse(p, guid); - default: return NULL; + default: return nullptr; } } @@ -161,7 +165,7 @@ Object* ObjectAccessor::GetObjectByTypeMask(WorldObject const& p, ObjectGuid con break; } - return NULL; + return nullptr; } Corpse* ObjectAccessor::GetCorpse(WorldObject const& u, ObjectGuid const& guid) @@ -227,7 +231,7 @@ Creature* ObjectAccessor::GetCreatureOrPetOrVehicle(WorldObject const& u, Object if (guid.IsCreatureOrVehicle()) return GetCreature(u, guid); - return NULL; + return nullptr; } Player* ObjectAccessor::FindPlayer(ObjectGuid const& guid) diff --git a/src/server/game/Globals/ObjectAccessor.h b/src/server/game/Globals/ObjectAccessor.h index b86ccccd5da..bc4062eed77 100644 --- a/src/server/game/Globals/ObjectAccessor.h +++ b/src/server/game/Globals/ObjectAccessor.h @@ -19,27 +19,25 @@ #ifndef TRINITY_OBJECTACCESSOR_H #define TRINITY_OBJECTACCESSOR_H -#include -#include +#include "ObjectGuid.h" #include -#include -#include -#include "Define.h" -#include "GridDefines.h" -#include "UpdateData.h" -#include "Object.h" - -class Creature; class Corpse; -class Unit; -class GameObject; +class Creature; class DynamicObject; -class WorldObject; -class Vehicle; +class GameObject; class Map; -class WorldRunnable; +class Object; +class Pet; +class Player; class Transport; +class Unit; +class WorldObject; + +namespace boost +{ + class shared_mutex; +} template class TC_GAME_API HashMapHolder @@ -48,9 +46,6 @@ class TC_GAME_API HashMapHolder HashMapHolder() { } public: - static_assert(std::is_same::value - || std::is_same::value, - "Only Player and Transport can be registered in global HashMapHolder"); typedef std::unordered_map MapType; diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index 048eff35504..1b7713ab363 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -16,16 +16,15 @@ * with this program. If not, see . */ -#include "AccountMgr.h" +#include "ObjectMgr.h" #include "AchievementMgr.h" -#include "ArenaTeam.h" #include "ArenaTeamMgr.h" -#include "BattlegroundMgr.h" +#include "Bag.h" #include "Chat.h" -#include "Common.h" #include "CreatureAIFactory.h" #include "DatabaseEnv.h" #include "DisableMgr.h" +#include "GameObject.h" #include "GameObjectAIFactory.h" #include "GossipDef.h" #include "GroupMgr.h" @@ -34,22 +33,26 @@ #include "Language.h" #include "LFGMgr.h" #include "Log.h" +#include "LootMgr.h" +#include "Mail.h" #include "MapManager.h" -#include "Object.h" -#include "ObjectMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "PoolMgr.h" +#include "QueryPackets.h" +#include "Random.h" #include "ReputationMgr.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "SpellMgr.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "UpdateMask.h" #include "Util.h" #include "Vehicle.h" #include "World.h" -#include "Packets/QueryPackets.h" - ScriptMapMap sSpellScripts; ScriptMapMap sEventScripts; ScriptMapMap sWaypointScripts; @@ -284,7 +287,7 @@ ObjectMgr::~ObjectMgr() delete itr->second; } -void ObjectMgr::AddLocaleString(std::string const& value, LocaleConstant localeConstant, StringVector& data) +void ObjectMgr::AddLocaleString(std::string const& value, LocaleConstant localeConstant, std::vector& data) { if (!value.empty()) { @@ -1128,7 +1131,7 @@ void ObjectMgr::LoadGameObjectAddons() } GameObjectAddon& gameObjectAddon = _gameObjectAddonStore[guid]; - gameObjectAddon.ParentRotation = G3D::Quat(fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat()); + gameObjectAddon.ParentRotation = QuaternionData(fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat()); gameObjectAddon.invisibilityType = InvisibilityType(fields[5].GetUInt8()); gameObjectAddon.InvisibilityValue = fields[6].GetUInt32(); @@ -1148,7 +1151,7 @@ void ObjectMgr::LoadGameObjectAddons() if (!gameObjectAddon.ParentRotation.isUnit()) { TC_LOG_ERROR("sql.sql", "GameObject (GUID: %u) has invalid parent rotation in `gameobject_addon`, set to default", guid); - gameObjectAddon.ParentRotation = G3D::Quat(); + gameObjectAddon.ParentRotation = QuaternionData(); } ++count; @@ -1310,7 +1313,7 @@ uint32 ObjectMgr::ChooseDisplayId(CreatureTemplate const* cinfo, CreatureData co return cinfo->GetFirstInvisibleModel(); } -void ObjectMgr::ChooseCreatureFlags(const CreatureTemplate* cinfo, uint32& npcflag, uint32& unit_flags, uint32& dynamicflags, const CreatureData* data /*= nullptr*/) +void ObjectMgr::ChooseCreatureFlags(CreatureTemplate const* cinfo, uint32& npcflag, uint32& unit_flags, uint32& dynamicflags, CreatureData const* data /*= nullptr*/) { npcflag = cinfo->npcflag; unit_flags = cinfo->unit_flags; @@ -1442,7 +1445,7 @@ void ObjectMgr::LoadLinkedRespawn() { case CREATURE_TO_CREATURE: { - const CreatureData* slave = GetCreatureData(guidLow); + CreatureData const* slave = GetCreatureData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (guid) '%u' not found in creature table", guidLow); @@ -1450,7 +1453,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const CreatureData* master = GetCreatureData(linkedGuidLow); + CreatureData const* master = GetCreatureData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (linkedGuid) '%u' not found in creature table", linkedGuidLow); @@ -1458,7 +1461,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature '%u' linking to Creature '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1479,7 +1482,7 @@ void ObjectMgr::LoadLinkedRespawn() } case CREATURE_TO_GO: { - const CreatureData* slave = GetCreatureData(guidLow); + CreatureData const* slave = GetCreatureData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (guid) '%u' not found in creature table", guidLow); @@ -1487,7 +1490,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const GameObjectData* master = GetGOData(linkedGuidLow); + GameObjectData const* master = GetGOData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (linkedGuid) '%u' not found in gameobject table", linkedGuidLow); @@ -1495,7 +1498,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature '%u' linking to Gameobject '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1516,7 +1519,7 @@ void ObjectMgr::LoadLinkedRespawn() } case GO_TO_GO: { - const GameObjectData* slave = GetGOData(guidLow); + GameObjectData const* slave = GetGOData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (guid) '%u' not found in gameobject table", guidLow); @@ -1524,7 +1527,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const GameObjectData* master = GetGOData(linkedGuidLow); + GameObjectData const* master = GetGOData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (linkedGuid) '%u' not found in gameobject table", linkedGuidLow); @@ -1532,7 +1535,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '%u' linking to Gameobject '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1553,7 +1556,7 @@ void ObjectMgr::LoadLinkedRespawn() } case GO_TO_CREATURE: { - const GameObjectData* slave = GetGOData(guidLow); + GameObjectData const* slave = GetGOData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (guid) '%u' not found in gameobject table", guidLow); @@ -1561,7 +1564,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const CreatureData* master = GetCreatureData(linkedGuidLow); + CreatureData const* master = GetCreatureData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (linkedGuid) '%u' not found in creature table", linkedGuidLow); @@ -1569,7 +1572,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '%u' linking to Creature '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1838,7 +1841,7 @@ void ObjectMgr::LoadCreatures() if (cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND) { - if (!mapEntry || !mapEntry->IsDungeon()) + if (!mapEntry->IsDungeon()) TC_LOG_ERROR("sql.sql", "Table `creature` has creature (GUID: %u Entry: %u) with `creature_template`.`flags_extra` including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature is not in instance.", guid, data.id); } @@ -1934,7 +1937,7 @@ void ObjectMgr::RemoveCreatureFromGrid(ObjectGuid::LowType guid, CreatureData co } } -ObjectGuid::LowType ObjectMgr::AddGOData(uint32 entry, uint32 mapId, Position const& pos, G3D::Quat const& rot, uint32 spawntimedelay /*= 0*/) +ObjectGuid::LowType ObjectMgr::AddGOData(uint32 entry, uint32 mapId, Position const& pos, QuaternionData const& rot, uint32 spawntimedelay /*= 0*/) { GameObjectTemplate const* goinfo = GetGameObjectTemplate(entry); if (!goinfo) @@ -4670,6 +4673,18 @@ void ObjectMgr::LoadQuests() TC_LOG_INFO("server.loading", ">> Loaded %lu quests definitions in %u ms", (unsigned long)_questTemplates.size(), GetMSTimeDiffToNow(oldMSTime)); } +void ObjectMgr::LoadQuestStartersAndEnders() +{ + TC_LOG_INFO("server.loading", "Loading GO Start Quest Data..."); + LoadGameobjectQuestStarters(); + TC_LOG_INFO("server.loading", "Loading GO End Quest Data..."); + LoadGameobjectQuestEnders(); + TC_LOG_INFO("server.loading", "Loading Creature Start Quest Data..."); + LoadCreatureQuestStarters(); + TC_LOG_INFO("server.loading", "Loading Creature End Quest Data..."); + LoadCreatureQuestEnders(); +} + void ObjectMgr::LoadQuestLocales() { uint32 oldMSTime = getMSTime(); @@ -5957,7 +5972,7 @@ void ObjectMgr::LoadGraveyardZones() { uint32 oldMSTime = getMSTime(); - GraveYardStore.clear(); // need for reload case + GraveyardStore.clear(); // need for reload case // 0 1 2 QueryResult result = WorldDatabase.Query("SELECT ID, GhostZone, Faction FROM graveyard_zone"); @@ -6006,14 +6021,14 @@ void ObjectMgr::LoadGraveyardZones() continue; } - if (!AddGraveYardLink(safeLocId, zoneId, team, false)) + if (!AddGraveyardLink(safeLocId, zoneId, team, false)) TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` has a duplicate record for Graveyard (ID: %u) and Zone (ID: %u), skipped.", safeLocId, zoneId); } while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %u graveyard-zone links in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } -WorldSafeLocsEntry const* ObjectMgr::GetDefaultGraveYard(uint32 team) const +WorldSafeLocsEntry const* ObjectMgr::GetDefaultGraveyard(uint32 team) const { enum DefaultGraveyard { @@ -6028,7 +6043,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetDefaultGraveYard(uint32 team) const else return nullptr; } -WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team) const +WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveyard(float x, float y, float z, uint32 MapId, uint32 team) const { // search for zone associated closest graveyard uint32 zoneId = sMapMgr->GetZoneId(MapId, x, y, z); @@ -6038,7 +6053,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float if (z > -500) { TC_LOG_ERROR("misc", "ZoneId not found for map %u coords (%f, %f, %f)", MapId, x, y, z); - return GetDefaultGraveYard(team); + return GetDefaultGraveyard(team); } } @@ -6049,7 +6064,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float // then check faction // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated // then check faction - GraveYardMapBounds range = GraveYardStore.equal_range(zoneId); + GraveyardMapBounds range = GraveyardStore.equal_range(zoneId); MapEntry const* map = sMapStore.LookupEntry(MapId); // not need to check validity of map object; MapId _MUST_ be valid here @@ -6057,7 +6072,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float { if (zoneId != 0) // zone == 0 can't be fixed, used by bliz for bugged zones TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); - return GetDefaultGraveYard(team); + return GetDefaultGraveyard(team); } // at corpse map @@ -6077,7 +6092,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float for (; range.first != range.second; ++range.first) { - GraveYardData const& data = range.first->second; + GraveyardData const& data = range.first->second; WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.LookupEntry(data.safeLocId); if (!entry) @@ -6153,29 +6168,45 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(float x, float y, float return entryFar; } -GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId) const +GraveyardData const* ObjectMgr::FindGraveyardData(uint32 id, uint32 zoneId) const { - GraveYardMapBounds range = GraveYardStore.equal_range(zoneId); + GraveyardMapBounds range = GraveyardStore.equal_range(zoneId); for (; range.first != range.second; ++range.first) { - GraveYardData const& data = range.first->second; + GraveyardData const& data = range.first->second; if (data.safeLocId == id) return &data; } return nullptr; } -bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= true*/) +AreaTrigger const* ObjectMgr::GetAreaTrigger(uint32 trigger) const +{ + AreaTriggerContainer::const_iterator itr = _areaTriggerStore.find(trigger); + if (itr != _areaTriggerStore.end()) + return &itr->second; + return nullptr; +} + +AccessRequirement const* ObjectMgr::GetAccessRequirement(uint32 mapid, Difficulty difficulty) const +{ + AccessRequirementContainer::const_iterator itr = _accessRequirementStore.find(MAKE_PAIR32(mapid, difficulty)); + if (itr != _accessRequirementStore.end()) + return itr->second; + return nullptr; +} + +bool ObjectMgr::AddGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= true*/) { - if (FindGraveYardData(id, zoneId)) + if (FindGraveyardData(id, zoneId)) return false; // add link to loaded data - GraveYardData data; + GraveyardData data; data.safeLocId = id; data.team = team; - GraveYardStore.insert(GraveYardContainer::value_type(zoneId, data)); + GraveyardStore.insert(GraveyardContainer::value_type(zoneId, data)); // add link to DB if (persist) @@ -6192,9 +6223,9 @@ bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool per return true; } -void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= false*/) +void ObjectMgr::RemoveGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= false*/) { - GraveYardMapBoundsNonConst range = GraveYardStore.equal_range(zoneId); + GraveyardMapBoundsNonConst range = GraveyardStore.equal_range(zoneId); if (range.first == range.second) { //TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); @@ -6206,7 +6237,7 @@ void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool for (; range.first != range.second; ++range.first) { - GraveYardData & data = range.first->second; + GraveyardData & data = range.first->second; // skip not matching safezone id if (data.safeLocId != id) @@ -6226,7 +6257,7 @@ void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool return; // remove from links - GraveYardStore.erase(range.first); + GraveyardStore.erase(range.first); // remove link from DB if (persist) @@ -6405,13 +6436,13 @@ AreaTrigger const* ObjectMgr::GetGoBackTrigger(uint32 Map) const { bool useParentDbValue = false; uint32 parentId = 0; - const MapEntry* mapEntry = sMapStore.LookupEntry(Map); + MapEntry const* mapEntry = sMapStore.LookupEntry(Map); if (!mapEntry || mapEntry->entrance_map < 0) return nullptr; if (mapEntry->IsDungeon()) { - const InstanceTemplate* iTemplate = sObjectMgr->GetInstanceTemplate(Map); + InstanceTemplate const* iTemplate = sObjectMgr->GetInstanceTemplate(Map); if (!iTemplate) return nullptr; @@ -6984,8 +7015,8 @@ void ObjectMgr::LoadPetNumber() std::string ObjectMgr::GeneratePetName(uint32 entry) { - StringVector& list0 = _petHalfName0[entry]; - StringVector& list1 = _petHalfName1[entry]; + std::vector& list0 = _petHalfName0[entry]; + std::vector& list1 = _petHalfName1[entry]; if (list0.empty() || list1.empty()) { @@ -9217,6 +9248,14 @@ VehicleAccessoryList const* ObjectMgr::GetVehicleAccessoryList(Vehicle* veh) con return nullptr; } +DungeonEncounterList const* ObjectMgr::GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) const +{ + std::unordered_map::const_iterator itr = _dungeonEncounterStore.find(MAKE_PAIR32(mapId, difficulty)); + if (itr != _dungeonEncounterStore.end()) + return &itr->second; + return nullptr; +} + PlayerInfo const* ObjectMgr::GetPlayerInfo(uint32 race, uint32 class_) const { if (race >= MAX_RACES) diff --git a/src/server/game/Globals/ObjectMgr.h b/src/server/game/Globals/ObjectMgr.h index d88dbc10167..95e7019dacf 100644 --- a/src/server/game/Globals/ObjectMgr.h +++ b/src/server/game/Globals/ObjectMgr.h @@ -19,40 +19,35 @@ #ifndef _OBJECTMGR_H #define _OBJECTMGR_H -#include "Log.h" -#include "Object.h" -#include "Bag.h" -#include "Creature.h" -#include "DynamicObject.h" -#include "GameObject.h" -#include "TemporarySummon.h" -#include "Corpse.h" -#include "QuestDef.h" +#include "Common.h" +#include "ConditionMgr.h" +#include "CreatureData.h" +#include "DatabaseEnvFwd.h" +#include "GameObjectData.h" #include "ItemTemplate.h" #include "NPCHandler.h" -#include "DatabaseEnv.h" -#include "Mail.h" -#include "Map.h" -#include "ObjectAccessor.h" #include "ObjectDefines.h" +#include "ObjectGuid.h" +#include "Position.h" +#include "QuestDef.h" +#include "SharedDefines.h" #include "VehicleDefines.h" -#include "ConditionMgr.h" -#include "DBCStores.h" -#include -#include #include -#include -#include -#include +#include class Item; +class Unit; +class Vehicle; struct AccessRequirement; +struct DeclinedName; +struct DungeonEncounterEntry; +struct FactionEntry; struct PlayerClassInfo; struct PlayerClassLevelInfo; struct PlayerInfo; struct PlayerLevelInfo; - -#pragma pack(push, 1) +struct SkillRaceClassInfoEntry; +struct WorldSafeLocsEntry; struct PageText { @@ -60,6 +55,15 @@ struct PageText uint32 NextPageID; }; +enum SummonerType +{ + SUMMONER_TYPE_CREATURE = 0, + SUMMONER_TYPE_GAMEOBJECT = 1, + SUMMONER_TYPE_MAP = 2 +}; + +#pragma pack(push, 1) + /// Key for storing temp summon data in TempSummonDataContainer struct TempSummonGroupKey { @@ -80,6 +84,15 @@ private: uint8 _summonGroup; ///< Summon's group id }; +/// Stores data for temp summons +struct TempSummonData +{ + uint32 entry; ///< Entry of summoned creature + Position pos; ///< Position, where should be creature spawned + TempSummonType type; ///< Summon type, see TempSummonType for available types + uint32 time; ///< Despawn time, usable only with certain temp summon types +}; + #pragma pack(pop) // DB scripting commands @@ -119,10 +132,27 @@ enum ScriptCommands SCRIPT_COMMAND_PLAY_ANIMKIT = 36 // source = Creature, datalong = AnimKit id (NOT ON 3.3.5A, DON'T REUSE) }; -// Benchmarked: Faster than std::unordered_map (insert/find) +enum ChatType +{ + CHAT_TYPE_SAY = 0, + CHAT_TYPE_YELL = 1, + CHAT_TYPE_TEXT_EMOTE = 2, + CHAT_TYPE_BOSS_EMOTE = 3, + CHAT_TYPE_WHISPER = 4, + CHAT_TYPE_BOSS_WHISPER = 5, + CHAT_TYPE_ZONE_YELL = 6, + CHAT_TYPE_END = 255 +}; + typedef std::map PageTextContainer; -// Benchmarked: Faster than std::map (insert/find) +struct InstanceTemplate +{ + uint32 Parent; + uint32 ScriptId; + bool AllowMount; +}; + typedef std::unordered_map InstanceTemplateContainer; struct GameTele @@ -411,6 +441,19 @@ struct AreaTrigger float target_Orientation; }; +struct AccessRequirement +{ + uint8 levelMin; + uint8 levelMax; + uint16 item_level; + uint32 item; + uint32 item2; + uint32 quest_A; + uint32 quest_H; + uint32 achievement; + std::string questFailedText; +}; + struct BroadcastText { BroadcastText() : Id(0), Language(0), EmoteId0(0), EmoteId1(0), EmoteId2(0), @@ -422,8 +465,8 @@ struct BroadcastText uint32 Id; uint32 Language; - StringVector MaleText; - StringVector FemaleText; + std::vector MaleText; + std::vector FemaleText; uint32 EmoteId0; uint32 EmoteId1; uint32 EmoteId2; @@ -468,21 +511,47 @@ typedef std::unordered_map Content; }; typedef std::map LinkedRespawnContainer; +typedef std::unordered_map CreatureTemplateContainer; +typedef std::unordered_map CreatureTemplateAddonContainer; typedef std::unordered_map CreatureDataContainer; +typedef std::unordered_map CreatureAddonContainer; +typedef std::unordered_map CreatureBaseStatsContainer; +typedef std::unordered_map EquipmentInfoContainerInternal; +typedef std::unordered_map EquipmentInfoContainer; +typedef std::unordered_map CreatureModelContainer; +typedef std::unordered_map> CreatureQuestItemMap; +typedef std::unordered_map GameObjectTemplateContainer; +typedef std::unordered_map GameObjectTemplateAddonContainer; typedef std::unordered_map GameObjectDataContainer; -typedef std::map > TempSummonDataContainer; +typedef std::unordered_map GameObjectAddonContainer; +typedef std::unordered_map> GameObjectQuestItemMap; +typedef std::map> TempSummonDataContainer; typedef std::unordered_map CreatureLocaleContainer; typedef std::unordered_map GameObjectLocaleContainer; +typedef std::unordered_map ItemTemplateContainer; typedef std::unordered_map ItemLocaleContainer; typedef std::unordered_map ItemSetNameLocaleContainer; typedef std::unordered_map QuestLocaleContainer; typedef std::unordered_map NpcTextLocaleContainer; typedef std::unordered_map PageTextLocaleContainer; + +struct GossipMenuItemsLocale +{ + std::vector OptionText; + std::vector BoxText; +}; + typedef std::unordered_map GossipMenuItemsLocaleContainer; + +struct PointOfInterestLocale +{ + std::vector Name; +}; + typedef std::unordered_map PointOfInterestLocaleContainer; typedef std::unordered_map TrinityStringContainer; @@ -492,12 +561,86 @@ typedef std::multimap QuestRelationsReverse; // quest -> unit/go typedef std::pair QuestRelationBounds; typedef std::pair QuestRelationReverseBounds; +struct PlayerCreateInfoItem +{ + PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) { } + + uint32 item_id = 0; + uint32 item_amount = 0; +}; + +typedef std::vector PlayerCreateInfoItems; + +struct PlayerClassLevelInfo +{ + uint16 basehealth = 0; + uint16 basemana = 0; +}; + +struct PlayerClassInfo +{ + //[level-1] 0..MaxPlayerLevel-1 + PlayerClassLevelInfo* levelInfo = nullptr; +}; + +struct PlayerLevelInfo +{ + uint8 stats[MAX_STATS] = { }; +}; + +typedef std::vector PlayerCreateInfoSpells; + +struct PlayerCreateInfoAction +{ + PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) { } + + uint8 button = 0; + uint8 type = 0; + uint32 action = 0; +}; + +typedef std::vector PlayerCreateInfoActions; + +struct PlayerCreateInfoSkill +{ + uint16 SkillId; + uint16 Rank; +}; + +typedef std::vector PlayerCreateInfoSkills; + +// existence checked by displayId != 0 +struct PlayerInfo +{ + uint32 mapId = 0; + uint32 areaId = 0; + float positionX = 0.0f; + float positionY = 0.0f; + float positionZ = 0.0f; + float orientation = 0.0f; + uint16 displayId_m = 0; + uint16 displayId_f = 0; + PlayerCreateInfoItems item; + PlayerCreateInfoSpells customSpells; + PlayerCreateInfoSpells castSpells; + PlayerCreateInfoActions action; + PlayerCreateInfoSkills skills; + + //[level-1] 0..MaxPlayerLevel-1 + PlayerLevelInfo* levelInfo = nullptr; +}; + + typedef std::multimap ExclusiveQuestGroups; // exclusiveGroupId -> quest typedef std::pair ExclusiveQuestGroupsBounds; struct PetLevelInfo { - PetLevelInfo() : health(0), mana(0), armor(0) { for (uint8 i=0; i < MAX_STATS; ++i) stats[i] = 0; } + PetLevelInfo() : health(0), mana(0), armor(0) + { + for (uint16& stat : stats) + stat = 0; + } uint16 stats[MAX_STATS]; uint16 health; @@ -630,15 +773,15 @@ struct QuestPOIWrapper typedef std::unordered_map QuestPOIContainer; -struct GraveYardData +struct GraveyardData { uint32 safeLocId; uint32 team; }; -typedef std::multimap GraveYardContainer; -typedef std::pair GraveYardMapBounds; -typedef std::pair GraveYardMapBoundsNonConst; +typedef std::multimap GraveyardContainer; +typedef std::pair GraveyardMapBounds; +typedef std::pair GraveyardMapBoundsNonConst; typedef std::unordered_map CacheVendorItemContainer; typedef std::unordered_map CacheTrainerSpellContainer; @@ -671,7 +814,7 @@ struct LanguageDesc TC_GAME_API extern LanguageDesc lang_description[LANGUAGES_COUNT]; LanguageDesc const* GetLanguageDescByID(uint32 lang); -enum EncounterCreditType +enum EncounterCreditType : uint8 { ENCOUNTER_CREDIT_KILL_CREATURE = 0, ENCOUNTER_CREDIT_CAST_SPELL = 1 @@ -721,8 +864,6 @@ class TC_GAME_API ObjectMgr static ObjectMgr* instance(); - typedef std::unordered_map ItemMap; - typedef std::unordered_map QuestMap; typedef std::unordered_map AreaTriggerContainer; @@ -786,7 +927,7 @@ class TC_GAME_API ObjectMgr void GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, PlayerLevelInfo* info) const; - GameObjectQuestItemList const* GetGameObjectQuestItemList(uint32 id) const + std::vector const* GetGameObjectQuestItemList(uint32 id) const { GameObjectQuestItemMap::const_iterator itr = _gameObjectQuestItemStore.find(id); if (itr != _gameObjectQuestItemStore.end()) @@ -795,7 +936,7 @@ class TC_GAME_API ObjectMgr } GameObjectQuestItemMap const* GetGameObjectQuestItemMap() const { return &_gameObjectQuestItemStore; } - CreatureQuestItemList const* GetCreatureQuestItemList(uint32 id) const + std::vector const* GetCreatureQuestItemList(uint32 id) const { CreatureQuestItemMap::const_iterator itr = _creatureQuestItemStore.find(id); if (itr != _creatureQuestItemStore.end()) @@ -836,29 +977,15 @@ class TC_GAME_API ObjectMgr GossipText const* GetGossipText(uint32 Text_ID) const; - WorldSafeLocsEntry const* GetDefaultGraveYard(uint32 team) const; - WorldSafeLocsEntry const* GetClosestGraveYard(float x, float y, float z, uint32 MapId, uint32 team) const; - bool AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = true); - void RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = false); + WorldSafeLocsEntry const* GetDefaultGraveyard(uint32 team) const; + WorldSafeLocsEntry const* GetClosestGraveyard(float x, float y, float z, uint32 MapId, uint32 team) const; + bool AddGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = true); + void RemoveGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = false); void LoadGraveyardZones(); - GraveYardData const* FindGraveYardData(uint32 id, uint32 zone) const; - - AreaTrigger const* GetAreaTrigger(uint32 trigger) const - { - AreaTriggerContainer::const_iterator itr = _areaTriggerStore.find(trigger); - if (itr != _areaTriggerStore.end()) - return &itr->second; - return nullptr; - } - - AccessRequirement const* GetAccessRequirement(uint32 mapid, Difficulty difficulty) const - { - AccessRequirementContainer::const_iterator itr = _accessRequirementStore.find(MAKE_PAIR32(mapid, difficulty)); - if (itr != _accessRequirementStore.end()) - return itr->second; - return nullptr; - } + GraveyardData const* FindGraveyardData(uint32 id, uint32 zone) const; + AreaTrigger const* GetAreaTrigger(uint32 trigger) const; + AccessRequirement const* GetAccessRequirement(uint32 mapid, Difficulty difficulty) const; AreaTrigger const* GetGoBackTrigger(uint32 Map) const; AreaTrigger const* GetMapEntranceTrigger(uint32 Map) const; @@ -911,26 +1038,10 @@ class TC_GAME_API ObjectMgr VehicleAccessoryList const* GetVehicleAccessoryList(Vehicle* veh) const; - DungeonEncounterList const* GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) const - { - std::unordered_map::const_iterator itr = _dungeonEncounterStore.find(MAKE_PAIR32(mapId, difficulty)); - if (itr != _dungeonEncounterStore.end()) - return &itr->second; - return nullptr; - } + DungeonEncounterList const* GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) const; void LoadQuests(); - void LoadQuestStartersAndEnders() - { - TC_LOG_INFO("server.loading", "Loading GO Start Quest Data..."); - LoadGameobjectQuestStarters(); - TC_LOG_INFO("server.loading", "Loading GO End Quest Data..."); - LoadGameobjectQuestEnders(); - TC_LOG_INFO("server.loading", "Loading Creature Start Quest Data..."); - LoadCreatureQuestStarters(); - TC_LOG_INFO("server.loading", "Loading Creature End Quest Data..."); - LoadCreatureQuestEnders(); - } + void LoadQuestStartersAndEnders(); void LoadGameobjectQuestStarters(); void LoadGameobjectQuestEnders(); void LoadCreatureQuestStarters(); @@ -1238,7 +1349,7 @@ class TC_GAME_API ObjectMgr void RemoveCreatureFromGrid(ObjectGuid::LowType guid, CreatureData const* data); void AddGameobjectToGrid(ObjectGuid::LowType guid, GameObjectData const* data); void RemoveGameobjectFromGrid(ObjectGuid::LowType guid, GameObjectData const* data); - ObjectGuid::LowType AddGOData(uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot, uint32 spawntimedelay = 0); + ObjectGuid::LowType AddGOData(uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot, uint32 spawntimedelay = 0); ObjectGuid::LowType AddCreatureData(uint32 entry, uint32 map, Position const& pos, uint32 spawntimedelay = 0); // reserved names @@ -1315,10 +1426,10 @@ class TC_GAME_API ObjectMgr } // for wintergrasp only - GraveYardContainer GraveYardStore; + GraveyardContainer GraveyardStore; - static void AddLocaleString(std::string const& value, LocaleConstant localeConstant, StringVector& data); - static inline void GetLocaleString(StringVector const& data, LocaleConstant localeConstant, std::string& value) + static void AddLocaleString(std::string const& value, LocaleConstant localeConstant, std::vector& data); + static inline void GetLocaleString(std::vector const& data, LocaleConstant localeConstant, std::string& value) { if (data.size() > size_t(localeConstant) && !data[localeConstant].empty()) value = data[localeConstant]; @@ -1445,7 +1556,7 @@ class TC_GAME_API ObjectMgr typedef std::map FishingBaseSkillContainer; // [areaId][base skill level] FishingBaseSkillContainer _fishingBaseForAreaStore; - typedef std::map HalfNameContainer; + typedef std::map> HalfNameContainer; HalfNameContainer _petHalfName0; HalfNameContainer _petHalfName1; @@ -1457,7 +1568,7 @@ class TC_GAME_API ObjectMgr CreatureTemplateContainer _creatureTemplateStore; CreatureModelContainer _creatureModelStore; CreatureAddonContainer _creatureAddonStore; - CreatureAddonTemplateContainer _creatureTemplateAddonStore; + CreatureTemplateAddonContainer _creatureTemplateAddonStore; GameObjectAddonContainer _gameObjectAddonStore; GameObjectQuestItemMap _gameObjectQuestItemStore; CreatureQuestItemMap _creatureQuestItemStore; diff --git a/src/server/game/Grids/Cells/Cell.h b/src/server/game/Grids/Cells/Cell.h index d4169dff855..56aa7f794af 100644 --- a/src/server/game/Grids/Cells/Cell.h +++ b/src/server/game/Grids/Cells/Cell.h @@ -59,13 +59,13 @@ struct Cell y = data.Part.grid_y * MAX_NUMBER_OF_CELLS + data.Part.cell_y; } - bool DiffCell(const Cell &cell) const + bool DiffCell(Cell const& cell) const { return(data.Part.cell_x != cell.data.Part.cell_x || data.Part.cell_y != cell.data.Part.cell_y); } - bool DiffGrid(const Cell &cell) const + bool DiffGrid(Cell const& cell) const { return(data.Part.grid_x != cell.data.Part.grid_x || data.Part.grid_y != cell.data.Part.grid_y); diff --git a/src/server/game/Grids/Dynamic/TypeContainer.h b/src/server/game/Grids/Dynamic/TypeContainer.h new file mode 100644 index 00000000000..d095baf059d --- /dev/null +++ b/src/server/game/Grids/Dynamic/TypeContainer.h @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef TRINITY_TYPECONTAINER_H +#define TRINITY_TYPECONTAINER_H + +/* + * Here, you'll find a series of containers that allow you to hold multiple + * types of object at the same time. + */ + +#include +#include +#include +#include "Define.h" +#include "Dynamic/TypeList.h" +#include "GridRefManager.h" + +/* + * @class ContainerMapList is a mulit-type container for map elements + * By itself its meaningless but collaborate along with TypeContainers, + * it become the most powerfully container in the whole system. + */ +template +struct ContainerMapList +{ + //std::map _element; + GridRefManager _element; +}; + +template<> +struct ContainerMapList /* nothing is in type null */ +{ +}; + +template +struct ContainerMapList > +{ + ContainerMapList _elements; + ContainerMapList _TailElements; +}; + +template +struct ContainerUnorderedMap +{ + std::unordered_map _element; +}; + +template +struct ContainerUnorderedMap +{ +}; + +template +struct ContainerUnorderedMap, KEY_TYPE> +{ + ContainerUnorderedMap _elements; + ContainerUnorderedMap _TailElements; +}; + +#include "TypeContainerFunctions.h" + +/* + * @class TypeMapContainer contains a fixed number of types and is + * determined at compile time. This is probably the most complicated + * class and do its simplest thing, that is, holds objects + * of different types. + */ + +template +class TypeMapContainer +{ + public: + template size_t Count() const { return Trinity::Count(i_elements, (SPECIFIC_TYPE*)nullptr); } + + /// inserts a specific object into the container + template + bool insert(SPECIFIC_TYPE *obj) + { + SPECIFIC_TYPE* t = Trinity::Insert(i_elements, obj); + return (t != nullptr); + } + + /// Removes the object from the container, and returns the removed object + //template + //bool remove(SPECIFIC_TYPE* obj) + //{ + // SPECIFIC_TYPE* t = Trinity::Remove(i_elements, obj); + // return (t != nullptr); + //} + + ContainerMapList & GetElements(void) { return i_elements; } + const ContainerMapList & GetElements(void) const { return i_elements;} + + private: + ContainerMapList i_elements; +}; + +template +class TypeUnorderedMapContainer +{ +public: + template + bool Insert(KEY_TYPE const& handle, SPECIFIC_TYPE* obj) + { + return Trinity::Insert(_elements, handle, obj); + } + + template + bool Remove(KEY_TYPE const& handle) + { + return Trinity::Remove(_elements, handle, (SPECIFIC_TYPE*)nullptr); + } + + template + SPECIFIC_TYPE* Find(KEY_TYPE const& handle) + { + return Trinity::Find(_elements, handle, (SPECIFIC_TYPE*)nullptr); + } + + ContainerUnorderedMap& GetElements() { return _elements; } + ContainerUnorderedMap const& GetElements() const { return _elements; } + +private: + ContainerUnorderedMap _elements; +}; + +#endif diff --git a/src/server/game/Grids/Dynamic/TypeContainerFunctions.h b/src/server/game/Grids/Dynamic/TypeContainerFunctions.h new file mode 100644 index 00000000000..97d20922a05 --- /dev/null +++ b/src/server/game/Grids/Dynamic/TypeContainerFunctions.h @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef TYPECONTAINER_FUNCTIONS_H +#define TYPECONTAINER_FUNCTIONS_H + +/* + * Here you'll find a list of helper functions to make + * the TypeContainer usefull. Without it, its hard + * to access or mutate the container. + */ + +#include "Define.h" +#include "Dynamic/TypeList.h" +#include +#include + +namespace Trinity +{ + // Helpers + // Insert helpers + template + bool Insert(ContainerUnorderedMap& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* obj) + { + auto i = elements._element.find(handle); + if (i == elements._element.end()) + { + elements._element[handle] = obj; + return true; + } + else + { + ASSERT(i->second == obj, "Object with certain key already in but objects are different!"); + return false; + } + } + + template + bool Insert(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) + { + return false; + } + + template + bool Insert(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) + { + return false; + } + + template + bool Insert(ContainerUnorderedMap, KEY_TYPE>& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* obj) + { + bool ret = Insert(elements._elements, handle, obj); + return ret ? ret : Insert(elements._TailElements, handle, obj); + } + + // Find helpers + template + SPECIFIC_TYPE* Find(ContainerUnorderedMap const& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) + { + auto i = elements._element.find(handle); + if (i == elements._element.end()) + return nullptr; + else + return i->second; + } + + template + SPECIFIC_TYPE* Find(ContainerUnorderedMap const& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) + { + return nullptr; + } + + template + SPECIFIC_TYPE* Find(ContainerUnorderedMap const& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) + { + return nullptr; + } + + template + SPECIFIC_TYPE* Find(ContainerUnorderedMap, KEY_TYPE> const& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) + { + SPECIFIC_TYPE* ret = Find(elements._elements, handle, (SPECIFIC_TYPE*)nullptr); + return ret ? ret : Find(elements._TailElements, handle, (SPECIFIC_TYPE*)nullptr); + } + + // Erase helpers + template + bool Remove(ContainerUnorderedMap& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) + { + elements._element.erase(handle); + return true; + } + + template + bool Remove(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) + { + return false; + } + + template + bool Remove(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) + { + return false; + } + + template + bool Remove(ContainerUnorderedMap, KEY_TYPE>& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) + { + bool ret = Remove(elements._elements, handle, (SPECIFIC_TYPE*)nullptr); + return ret ? ret : Remove(elements._TailElements, handle, (SPECIFIC_TYPE*)nullptr); + } + + /* ContainerMapList Helpers */ + // count functions + template + size_t Count(ContainerMapList const& elements, SPECIFIC_TYPE* /*fake*/) + { + return elements._element.getSize(); + } + + template + size_t Count(ContainerMapList const& /*elements*/, SPECIFIC_TYPE* /*fake*/) + { + return 0; + } + + template + size_t Count(ContainerMapList const& /*elements*/, SPECIFIC_TYPE* /*fake*/) + { + return 0; + } + + template + size_t Count(ContainerMapList> const& elements, SPECIFIC_TYPE* fake) + { + return Count(elements._elements, fake); + } + + template + size_t Count(ContainerMapList> const& elements, SPECIFIC_TYPE* fake) + { + return Count(elements._TailElements, fake); + } + + // non-const insert functions + template + SPECIFIC_TYPE* Insert(ContainerMapList& elements, SPECIFIC_TYPE* obj) + { + //elements._element[hdl] = obj; + obj->AddToGrid(elements._element); + return obj; + } + + template + SPECIFIC_TYPE* Insert(ContainerMapList& /*elements*/, SPECIFIC_TYPE* /*obj*/) + { + return nullptr; + } + + // this is a missed + template + SPECIFIC_TYPE* Insert(ContainerMapList& /*elements*/, SPECIFIC_TYPE* /*obj*/) + { + return nullptr; // a missed + } + + // Recursion + template + SPECIFIC_TYPE* Insert(ContainerMapList>& elements, SPECIFIC_TYPE* obj) + { + SPECIFIC_TYPE* t = Insert(elements._elements, obj); + return (t != nullptr ? t : Insert(elements._TailElements, obj)); + } + + //// non-const remove method + //template SPECIFIC_TYPE* Remove(ContainerMapList & /*elements*/, SPECIFIC_TYPE *obj) + //{ + // obj->GetGridRef().unlink(); + // return obj; + //} + + //template SPECIFIC_TYPE* Remove(ContainerMapList &/*elements*/, SPECIFIC_TYPE * /*obj*/) + //{ + // return nullptr; + //} + + //// this is a missed + //template SPECIFIC_TYPE* Remove(ContainerMapList &/*elements*/, SPECIFIC_TYPE * /*obj*/) + //{ + // return nullptr; // a missed + //} + + //template SPECIFIC_TYPE* Remove(ContainerMapList > &elements, SPECIFIC_TYPE *obj) + //{ + // // The head element is bad + // SPECIFIC_TYPE* t = Remove(elements._elements, obj); + // return (t != nullptr ? t : Remove(elements._TailElements, obj)); + //} +} +#endif + diff --git a/src/server/game/Grids/Dynamic/TypeContainerVisitor.h b/src/server/game/Grids/Dynamic/TypeContainerVisitor.h new file mode 100644 index 00000000000..2d08da778e9 --- /dev/null +++ b/src/server/game/Grids/Dynamic/TypeContainerVisitor.h @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef TRINITY_TYPECONTAINERVISITOR_H +#define TRINITY_TYPECONTAINERVISITOR_H + +/* + * @class TypeContainerVisitor is implemented as a visitor pattern. It is + * a visitor to the TypeContainerList or TypeContainerMapList. The visitor has + * to overload its types as a visit method is called. + */ + +#include "Define.h" +#include "Dynamic/TypeContainer.h" + +// forward declaration +template class TypeContainerVisitor; + +// visitor helper +template void VisitorHelper(VISITOR &v, TYPE_CONTAINER &c) +{ + v.Visit(c); +} + +// terminate condition container map list +template void VisitorHelper(VISITOR &/*v*/, ContainerMapList &/*c*/) { } + +template void VisitorHelper(VISITOR &v, ContainerMapList &c) +{ + v.Visit(c._element); +} + +// recursion container map list +template void VisitorHelper(VISITOR &v, ContainerMapList > &c) +{ + VisitorHelper(v, c._elements); + VisitorHelper(v, c._TailElements); +} + +// for TypeMapContainer +template void VisitorHelper(VISITOR &v, TypeMapContainer &c) +{ + VisitorHelper(v, c.GetElements()); +} + +// TypeUnorderedMapContainer +template +void VisitorHelper(VISITOR& /*v*/, ContainerUnorderedMap& /*c*/) { } + +template +void VisitorHelper(VISITOR& v, ContainerUnorderedMap& c) +{ + v.Visit(c._element); +} + +template +void VisitorHelper(VISITOR& v, ContainerUnorderedMap, KEY_TYPE>& c) +{ + VisitorHelper(v, c._elements); + VisitorHelper(v, c._TailElements); +} + +template +void VisitorHelper(VISITOR& v, TypeUnorderedMapContainer& c) +{ + VisitorHelper(v, c.GetElements()); +} + +template +class TypeContainerVisitor +{ + public: + TypeContainerVisitor(VISITOR &v) : i_visitor(v) { } + + void Visit(TYPE_CONTAINER& c) + { + VisitorHelper(i_visitor, c); + } + + void Visit(TYPE_CONTAINER const& c) const + { + VisitorHelper(i_visitor, c); + } + + private: + VISITOR &i_visitor; +}; +#endif + diff --git a/src/server/game/Grids/GridRefManager.h b/src/server/game/Grids/GridRefManager.h index 4d21a8d3446..89d6cc9e7e6 100644 --- a/src/server/game/Grids/GridRefManager.h +++ b/src/server/game/Grids/GridRefManager.h @@ -34,7 +34,7 @@ class GridRefManager : public RefManager, OBJECT> GridReference* getLast() { return (GridReference*)RefManager, OBJECT>::getLast(); } iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(NULL); } + iterator end() { return iterator(nullptr); } }; #endif diff --git a/src/server/game/Grids/GridStates.cpp b/src/server/game/Grids/GridStates.cpp index 98f9006235b..4e3b11154af 100644 --- a/src/server/game/Grids/GridStates.cpp +++ b/src/server/game/Grids/GridStates.cpp @@ -19,9 +19,12 @@ #include "GridStates.h" #include "GridNotifiers.h" #include "Log.h" +#include "Map.h" +#include "ObjectGridLoader.h" void InvalidState::Update(Map&, NGridType&, GridInfo&, uint32) const -{ } +{ +} void ActiveState::Update(Map& map, NGridType& grid, GridInfo& info, uint32 diff) const { diff --git a/src/server/game/Grids/NGrid.cpp b/src/server/game/Grids/NGrid.cpp new file mode 100644 index 00000000000..e5d69dae44a --- /dev/null +++ b/src/server/game/Grids/NGrid.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "NGrid.h" +#include "Random.h" + +GridInfo::GridInfo() : i_timer(0), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), + i_unloadActiveLockCount(0), i_unloadExplicitLock(false), i_unloadReferenceLock(false) +{ +} + +GridInfo::GridInfo(time_t expiry, bool unload /*= true */) : i_timer(expiry), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), + i_unloadActiveLockCount(0), i_unloadExplicitLock(!unload), i_unloadReferenceLock(false) +{ +} diff --git a/src/server/game/Grids/NGrid.h b/src/server/game/Grids/NGrid.h index 69ab43106a9..dc6f2561e4f 100644 --- a/src/server/game/Grids/NGrid.h +++ b/src/server/game/Grids/NGrid.h @@ -29,23 +29,19 @@ #define DEFAULT_VISIBILITY_NOTIFY_PERIOD 1000 -class GridInfo +class TC_GAME_API GridInfo { public: - GridInfo() - : i_timer(0), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), - i_unloadActiveLockCount(0), i_unloadExplicitLock(false), i_unloadReferenceLock(false) { } - GridInfo(time_t expiry, bool unload = true ) - : i_timer(expiry), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), - i_unloadActiveLockCount(0), i_unloadExplicitLock(!unload), i_unloadReferenceLock(false) { } - const TimeTracker& getTimeTracker() const { return i_timer; } + GridInfo(); + GridInfo(time_t expiry, bool unload = true); + TimeTracker const& getTimeTracker() const { return i_timer; } bool getUnloadLock() const { return i_unloadActiveLockCount || i_unloadExplicitLock || i_unloadReferenceLock; } void setUnloadExplicitLock(bool on) { i_unloadExplicitLock = on; } void setUnloadReferenceLock(bool on) { i_unloadReferenceLock = on; } void incUnloadActiveLock() { ++i_unloadActiveLockCount; } void decUnloadActiveLock() { if (i_unloadActiveLockCount) --i_unloadActiveLockCount; } - void setTimer(const TimeTracker& pTimer) { i_timer = pTimer; } + void setTimer(TimeTracker const& pTimer) { i_timer = pTimer; } void ResetTimeTracker(time_t interval) { i_timer.Reset(interval); } void UpdateTimeTracker(time_t diff) { i_timer.Update(diff); } PeriodicTimer& getRelocationTimer() { return vis_Update; } @@ -110,7 +106,7 @@ class NGrid void setGridObjectDataLoaded(bool pLoaded) { i_GridObjectDataLoaded = pLoaded; } GridInfo* getGridInfoRef() { return &i_GridInfo; } - const TimeTracker& getTimeTracker() const { return i_GridInfo.getTimeTracker(); } + TimeTracker const& getTimeTracker() const { return i_GridInfo.getTimeTracker(); } bool getUnloadLock() const { return i_GridInfo.getUnloadLock(); } void setUnloadExplicitLock(bool on) { i_GridInfo.setUnloadExplicitLock(on); } void setUnloadReferenceLock(bool on) { i_GridInfo.setUnloadReferenceLock(on); } diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.cpp b/src/server/game/Grids/Notifiers/GridNotifiers.cpp index 70d472604e2..623010310ea 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.cpp +++ b/src/server/game/Grids/Notifiers/GridNotifiers.cpp @@ -80,7 +80,7 @@ void VisibleNotifier::SendToSelf() WorldPacket packet; i_data.BuildPacket(&packet); - i_player.GetSession()->SendPacket(&packet); + i_player.SendDirectMessage(&packet); for (std::set::const_iterator it = i_visibleNow.begin(); it != i_visibleNow.end(); ++it) i_player.SendInitialVisiblePackets(*it); diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.h b/src/server/game/Grids/Notifiers/GridNotifiers.h index 1378b4a5778..897e43d5e03 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.h +++ b/src/server/game/Grids/Notifiers/GridNotifiers.h @@ -19,22 +19,16 @@ #ifndef TRINITY_GRIDNOTIFIERS_H #define TRINITY_GRIDNOTIFIERS_H -#include "ObjectGridLoader.h" -#include "UpdateData.h" -#include - +#include "Creature.h" #include "Corpse.h" -#include "Object.h" +#include "CreatureAI.h" #include "DynamicObject.h" #include "GameObject.h" #include "Player.h" -#include "Unit.h" -#include "CreatureAI.h" #include "Spell.h" -#include "WorldSession.h" - -class Player; -//class Map; +#include "SpellInfo.h" +#include "UnitAI.h" +#include "UpdateData.h" namespace Trinity { @@ -128,7 +122,7 @@ namespace Trinity float i_distSq; uint32 team; Player const* skipped_receiver; - MessageDistDeliverer(WorldObject* src, WorldPacket const* msg, float dist, bool own_team_only = false, Player const* skipped = NULL) + MessageDistDeliverer(WorldObject* src, WorldPacket const* msg, float dist, bool own_team_only = false, Player const* skipped = nullptr) : i_source(src), i_message(msg), i_phaseMask(src->GetPhaseMask()), i_distSq(dist * dist) , team(0) , skipped_receiver(skipped) @@ -152,8 +146,7 @@ namespace Trinity if (!player->HaveAtClient(i_source)) return; - if (WorldSession* session = player->GetSession()) - session->SendPacket(i_message); + player->SendDirectMessage(i_message); } }; @@ -180,8 +173,7 @@ namespace Trinity if (player == i_source || !player->HaveAtClient(i_source) || player->IsFriendlyTo(i_source)) return; - if (WorldSession* session = player->GetSession()) - session->SendPacket(i_message); + player->SendDirectMessage(i_message); } }; @@ -641,7 +633,7 @@ namespace Trinity { public: AnyDeadUnitSpellTargetInRangeCheck(Unit* searchObj, float range, SpellInfo const* spellInfo, SpellTargetCheckTypes check) - : AnyDeadUnitObjectInRangeCheck(searchObj, range), i_spellInfo(spellInfo), i_check(searchObj, searchObj, spellInfo, check, NULL) + : AnyDeadUnitObjectInRangeCheck(searchObj, range), i_spellInfo(spellInfo), i_check(searchObj, searchObj, spellInfo, check, nullptr) { } bool operator()(Player* u); bool operator()(Corpse* u); @@ -967,9 +959,6 @@ namespace Trinity bool operator()(Unit* u) const { - if (G3D::fuzzyEq(_range, 0.0f)) - return false; - if (_playerOnly && u->GetTypeId() != TYPEID_PLAYER) return false; @@ -1059,7 +1048,7 @@ namespace Trinity { if (!_spellInfo) if (DynamicObject const* dynObj = i_obj->ToDynObject()) - _spellInfo = sSpellMgr->GetSpellInfo(dynObj->GetSpellId()); + _spellInfo = dynObj->GetSpellInfo(); } bool operator()(Unit* u) const @@ -1115,8 +1104,8 @@ namespace Trinity if (!u->IsWithinLOSInMap(i_enemy)) return; - if (u->AI()) - u->AI()->AttackStart(i_enemy); + if (u->GetAI() && u->IsAIEnabled) + u->GetAI()->AttackStart(i_enemy); } private: Unit* const i_funit; @@ -1374,7 +1363,7 @@ namespace Trinity class AllGameObjectsWithEntryInRange { public: - AllGameObjectsWithEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } + AllGameObjectsWithEntryInRange(WorldObject const* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } bool operator()(GameObject* go) const { @@ -1393,7 +1382,7 @@ namespace Trinity class AllCreaturesOfEntryInRange { public: - AllCreaturesOfEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } + AllCreaturesOfEntryInRange(WorldObject const* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } bool operator()(Unit* unit) const { @@ -1449,7 +1438,7 @@ namespace Trinity class AllWorldObjectsInRange { public: - AllWorldObjectsInRange(const WorldObject* object, float maxRange) : m_pObject(object), m_fRange(maxRange) { } + AllWorldObjectsInRange(WorldObject const* object, float maxRange) : m_pObject(object), m_fRange(maxRange) { } bool operator()(WorldObject* go) const { diff --git a/src/server/game/Grids/Notifiers/GridNotifiersImpl.h b/src/server/game/Grids/Notifiers/GridNotifiersImpl.h index dc6a8f59d61..26e74839496 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiersImpl.h +++ b/src/server/game/Grids/Notifiers/GridNotifiersImpl.h @@ -20,13 +20,13 @@ #define TRINITY_GRIDNOTIFIERSIMPL_H #include "GridNotifiers.h" -#include "WorldPacket.h" #include "Corpse.h" -#include "Player.h" -#include "UpdateData.h" #include "CreatureAI.h" +#include "Player.h" #include "SpellAuras.h" -#include "Opcodes.h" +#include "UpdateData.h" +#include "WorldPacket.h" +#include "WorldSession.h" template inline void Trinity::VisibleNotifier::Visit(GridRefManager &m) diff --git a/src/server/game/Grids/ObjectGridLoader.cpp b/src/server/game/Grids/ObjectGridLoader.cpp index 1cdedf34ec5..848df6f60dc 100644 --- a/src/server/game/Grids/ObjectGridLoader.cpp +++ b/src/server/game/Grids/ObjectGridLoader.cpp @@ -17,15 +17,16 @@ */ #include "ObjectGridLoader.h" -#include "ObjectAccessor.h" -#include "ObjectMgr.h" +#include "CellImpl.h" +#include "Corpse.h" #include "Creature.h" -#include "GameObject.h" +#include "CreatureAI.h" #include "DynamicObject.h" -#include "Corpse.h" +#include "Log.h" +#include "GameObject.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "World.h" -#include "CellImpl.h" -#include "CreatureAI.h" void ObjectGridEvacuator::Visit(CreatureMapType &m) { diff --git a/src/server/game/Grids/ObjectGridLoader.h b/src/server/game/Grids/ObjectGridLoader.h index 32d27ebe502..b823044347f 100644 --- a/src/server/game/Grids/ObjectGridLoader.h +++ b/src/server/game/Grids/ObjectGridLoader.h @@ -32,7 +32,7 @@ class TC_GAME_API ObjectGridLoader friend class ObjectWorldLoader; public: - ObjectGridLoader(NGridType &grid, Map* map, const Cell &cell) + ObjectGridLoader(NGridType& grid, Map* map, Cell const& cell) : i_cell(cell), i_grid(grid), i_map(map), i_gameObjects(0), i_creatures(0), i_corpses (0) { } diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index dffe6250444..76b7de68ea9 100644 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -16,26 +16,32 @@ * with this program. If not, see . */ -#include "CharacterCache.h" -#include "Common.h" -#include "Opcodes.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Player.h" -#include "World.h" -#include "ObjectMgr.h" -#include "GroupMgr.h" #include "Group.h" -#include "Formulas.h" -#include "ObjectAccessor.h" #include "Battleground.h" #include "BattlegroundMgr.h" -#include "MapManager.h" +#include "Common.h" +#include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "Formulas.h" +#include "GameObject.h" +#include "GroupMgr.h" #include "InstanceSaveMgr.h" -#include "Util.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" +#include "MapManager.h" +#include "Log.h" #include "LFGMgr.h" -#include "UpdateFieldFlags.h" +#include "Random.h" #include "SpellAuras.h" +#include "UpdateData.h" +#include "UpdateFieldFlags.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" Roll::Roll(ObjectGuid _guid, LootItem const& li) : itemGUID(_guid), itemid(li.itemid), itemRandomPropId(li.randomPropertyId), itemRandomSuffix(li.randomSuffix), itemCount(li.count), @@ -56,8 +62,8 @@ Loot* Roll::getLoot() Group::Group() : m_leaderGuid(), m_leaderName(""), m_groupType(GROUPTYPE_NORMAL), m_dungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL), m_raidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL), -m_bgGroup(NULL), m_bfGroup(NULL), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON), m_looterGuid(), -m_masterLooterGuid(), m_subGroupsCounts(NULL), m_guid(), m_counter(0), m_maxEnchantingLevel(0), m_dbStoreId(0) +m_bgGroup(nullptr), m_bfGroup(nullptr), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON), m_looterGuid(), +m_masterLooterGuid(), m_subGroupsCounts(nullptr), m_guid(), m_counter(0), m_maxEnchantingLevel(0), m_dbStoreId(0) { for (uint8 i = 0; i < TARGETICONCOUNT; ++i) m_targetIcons[i].Clear(); @@ -68,9 +74,12 @@ Group::~Group() if (m_bgGroup) { TC_LOG_DEBUG("bg.battleground", "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 TC_LOG_ERROR("misc", "Group::~Group: battleground group is not linked to the correct battleground."); + if (m_bgGroup->GetBgRaid(ALLIANCE) == this) + m_bgGroup->SetBgRaid(ALLIANCE, nullptr); + else if (m_bgGroup->GetBgRaid(HORDE) == this) + m_bgGroup->SetBgRaid(HORDE, nullptr); + else + TC_LOG_ERROR("misc", "Group::~Group: battleground group is not linked to the correct battleground."); } Rolls::iterator itr; while (!RollId.empty()) @@ -301,15 +310,15 @@ void Group::RemoveInvite(Player* player) if (player) { m_invitees.erase(player); - player->SetGroupInvite(NULL); + player->SetGroupInvite(nullptr); } } void Group::RemoveAllInvites() { - for (InvitesList::iterator itr=m_invitees.begin(); itr != m_invitees.end(); ++itr) + for (InvitesList::iterator itr = m_invitees.begin(); itr != m_invitees.end(); ++itr) if (*itr) - (*itr)->SetGroupInvite(NULL); + (*itr)->SetGroupInvite(nullptr); m_invitees.clear(); } @@ -321,7 +330,7 @@ Player* Group::GetInvited(ObjectGuid guid) const if ((*itr) && (*itr)->GetGUID() == guid) return (*itr); } - return NULL; + return nullptr; } Player* Group::GetInvited(const std::string& name) const @@ -331,7 +340,7 @@ Player* Group::GetInvited(const std::string& name) const if ((*itr) && (*itr)->GetName() == name) return (*itr); } - return NULL; + return nullptr; } bool Group::AddMember(Player* player) @@ -364,7 +373,7 @@ bool Group::AddMember(Player* player) SubGroupCounterIncrease(subGroup); - player->SetGroupInvite(NULL); + player->SetGroupInvite(nullptr); if (player->GetGroup()) { if (isBGGroup() || isBFGroup()) // if player is in group and he is being added to BG raid group, then call SetBattlegroundRaid() @@ -437,7 +446,7 @@ bool Group::AddMember(Player* player) WorldPacket groupDataPacket; // Broadcast group members' fields to player - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { if (itr->GetSource() == player) continue; @@ -480,7 +489,7 @@ bool Group::AddMember(Player* player) return true; } -bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= 0*/, const char* reason /*= NULL*/) +bool Group::RemoveMember(ObjectGuid guid, RemoveMethod const& method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= ObjectGuid::Empty*/, char const* reason /*= nullptr*/) { BroadcastGroupUpdate(); @@ -518,9 +527,9 @@ bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_R // Regular group { if (player->GetOriginalGroup() == this) - player->SetOriginalGroup(NULL); + player->SetOriginalGroup(nullptr); else - player->SetGroup(NULL); + player->SetGroup(nullptr); // quest related GO state dependent from raid membership player->UpdateForQuestWorldObjects(); @@ -531,14 +540,14 @@ bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_R if (method == GROUP_REMOVEMETHOD_KICK || method == GROUP_REMOVEMETHOD_KICK_LFG) { data.Initialize(SMSG_GROUP_UNINVITE, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } // Do we really need to send this opcode? data.Initialize(SMSG_GROUP_LIST, 1+1+1+1+8+4+4+8); data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0); data << uint64(m_guid) << uint32(m_counter) << uint32(0) << uint64(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); _homebindIfInstance(player); } @@ -750,9 +759,9 @@ void Group::Disband(bool hideDestroy /* = false */) { //we can remove player who is in battleground from his original group if (player->GetOriginalGroup() == this) - player->SetOriginalGroup(NULL); + player->SetOriginalGroup(nullptr); else - player->SetGroup(NULL); + player->SetGroup(nullptr); } // quest related GO state dependent from raid membership @@ -766,7 +775,7 @@ void Group::Disband(bool hideDestroy /* = false */) if (!hideDestroy) { data.Initialize(SMSG_GROUP_DESTROYED, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } //we already removed player from group and in player->GetGroup() is his original group, send update @@ -779,7 +788,7 @@ void Group::Disband(bool hideDestroy /* = false */) data.Initialize(SMSG_GROUP_LIST, 1+1+1+1+8+4+4+8); data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0); data << uint64(m_guid) << uint32(m_counter) << uint32(0) << uint64(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } _homebindIfInstance(player); @@ -803,8 +812,8 @@ void Group::Disband(bool hideDestroy /* = false */) CharacterDatabase.CommitTransaction(trans); - ResetInstances(INSTANCE_RESET_GROUP_DISBAND, false, NULL); - ResetInstances(INSTANCE_RESET_GROUP_DISBAND, true, NULL); + ResetInstances(INSTANCE_RESET_GROUP_DISBAND, false, nullptr); + ResetInstances(INSTANCE_RESET_GROUP_DISBAND, true, nullptr); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_LFG_DATA); stmt->setUInt32(0, m_dbStoreId); @@ -821,7 +830,7 @@ void Group::Disband(bool hideDestroy /* = false */) /*** LOOT SYSTEM ***/ /*********************************************************/ -void Group::SendLootStartRoll(uint32 countDown, uint32 mapid, const Roll &r) +void Group::SendLootStartRoll(uint32 countDown, uint32 mapid, Roll const& r) { WorldPacket data(SMSG_LOOT_START_ROLL, (8+4+4+4+4+4+4+1)); data << uint64(r.itemGUID); // guid of rolled item @@ -841,7 +850,7 @@ void Group::SendLootStartRoll(uint32 countDown, uint32 mapid, const Roll &r) continue; if (itr->second == NOT_EMITED_YET) - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } } @@ -864,7 +873,7 @@ void Group::SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, voteMask &= ~ROLL_FLAG_TYPE_NEED; data << uint8(voteMask); // roll type mask - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } void Group::SendLootRoll(ObjectGuid sourceGuid, ObjectGuid targetGuid, uint8 rollNumber, uint8 rollType, Roll const& roll) @@ -887,7 +896,7 @@ void Group::SendLootRoll(ObjectGuid sourceGuid, ObjectGuid targetGuid, uint8 rol continue; if (itr->second != NOT_VALID) - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } } @@ -910,7 +919,7 @@ void Group::SendLootRollWon(ObjectGuid sourceGuid, ObjectGuid targetGuid, uint8 continue; if (itr->second != NOT_VALID) - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } } @@ -930,7 +939,7 @@ void Group::SendLootAllPassed(Roll const& roll) continue; if (itr->second != NOT_VALID) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -981,7 +990,7 @@ void Group::GroupLoot(Loot* loot, WorldObject* pLootedObject) Roll* r = new Roll(newitemGUID, *i); //a vector is filled with only near party members - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member || !member->GetSession()) @@ -1063,7 +1072,7 @@ void Group::GroupLoot(Loot* loot, WorldObject* pLootedObject) Roll* r = new Roll(newitemGUID, *i); //a vector is filled with only near party members - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member || !member->GetSession()) @@ -1121,7 +1130,7 @@ void Group::NeedBeforeGreed(Loot* loot, WorldObject* lootedObject) Roll* r = new Roll(newitemGUID, *i); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* playerToRoll = itr->GetSource(); if (!playerToRoll || !playerToRoll->GetSession()) @@ -1196,7 +1205,7 @@ void Group::NeedBeforeGreed(Loot* loot, WorldObject* lootedObject) Roll* r = new Roll(newitemGUID, *i); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* playerToRoll = itr->GetSource(); if (!playerToRoll || !playerToRoll->GetSession()) @@ -1272,7 +1281,7 @@ void Group::MasterLoot(Loot* loot, WorldObject* pLootedObject) WorldPacket data(SMSG_LOOT_MASTER_LIST, 1 + GetMembersCount() * 8); data << uint8(GetMembersCount()); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* looter = itr->GetSource(); if (!looter->IsInWorld()) @@ -1287,11 +1296,11 @@ void Group::MasterLoot(Loot* loot, WorldObject* pLootedObject) data.put(0, real_count); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* looter = itr->GetSource(); if (looter->IsAtGroupRewardDistance(pLootedObject)) - looter->GetSession()->SendPacket(&data); + looter->SendDirectMessage(&data); } } @@ -1372,7 +1381,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) ObjectGuid maxguid = ObjectGuid::Empty; Player* player = nullptr; - for (Roll::PlayerVote::const_iterator itr=roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr) + for (Roll::PlayerVote::const_iterator itr = roll->playerVote.begin(); itr != roll->playerVote.end(); ++itr) { if (itr->second != NEED) continue; @@ -1416,7 +1425,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) { item->is_blocked = false; item->rollWinnerGUID = player->GetGUID(); - player->SendEquipError(msg, NULL, NULL, roll->itemid); + player->SendEquipError(msg, nullptr, nullptr, roll->itemid); } } } @@ -1441,7 +1450,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) continue; player = ObjectAccessor::FindPlayer(itr->first); - if (!player || (allowedMap != NULL && player->FindMap() != allowedMap)) + if (!player || (allowedMap != nullptr && player->FindMap() != allowedMap)) { --roll->totalGreed; continue; @@ -1483,7 +1492,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) { item->is_blocked = false; item->rollWinnerGUID = player->GetGUID(); - player->SendEquipError(msg, NULL, NULL, roll->itemid); + player->SendEquipError(msg, nullptr, nullptr, roll->itemid); } } else if (rollvote == DISENCHANT) @@ -1507,7 +1516,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) for (uint32 i = 0; i < max_slot; ++i) { LootItem* lootItem = loot.LootItemInSlot(i, player); - player->SendEquipError(msg, NULL, NULL, lootItem->itemid); + player->SendEquipError(msg, nullptr, nullptr, lootItem->itemid); player->SendItemRetrievalMail(lootItem->itemid, lootItem->count); } } @@ -1647,7 +1656,7 @@ void Group::SendUpdateToPlayer(ObjectGuid playerGUID, MemberSlot* slot) data << uint8(m_raidDifficulty >= RAID_DIFFICULTY_10MAN_HEROIC); // 3.3 Dynamic Raid Difficulty - 0 normal/1 heroic } - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Group::UpdatePlayerOutOfRange(Player* player) @@ -1659,35 +1668,35 @@ void Group::UpdatePlayerOutOfRange(Player* player) player->GetSession()->BuildPartyMemberStatsChangedPacket(player, &data); Player* member; - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { member = itr->GetSource(); if (member && member != player && (!member->IsInMap(player) || !member->IsWithinDist(player, member->GetSightRange(), false))) - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); } } void Group::BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group /*= -1*/, ObjectGuid ignoredPlayer /*= ObjectGuid::Empty*/) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player || (!ignoredPlayer.IsEmpty() && player->GetGUID() == ignoredPlayer) || (ignorePlayersInBGRaid && player->GetGroup() != this)) continue; if (player->GetSession() && (group == -1 || itr->getSubGroup() == group)) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } } void Group::BroadcastReadyCheck(WorldPacket* packet) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (player && player->GetSession()) if (IsLeader(player->GetGUID()) || IsAssistant(player->GetGUID())) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } } @@ -1827,7 +1836,7 @@ void Group::UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed) } // search next after current - Player* pNewLooter = NULL; + Player* pNewLooter = nullptr; for (member_citerator itr = guid_itr; itr != m_memberSlots.end(); ++itr) { if (Player* player = ObjectAccessor::FindPlayer(itr->guid)) @@ -1900,7 +1909,7 @@ GroupJoinBattlegroundResult Group::CanJoinBattlegroundQueue(Battleground const* // check every member of the group to be able to join memberscount = 0; - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next(), ++memberscount) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next(), ++memberscount) { Player* member = itr->GetSource(); // offline member? don't let join @@ -1969,7 +1978,7 @@ void Group::SetDungeonDifficulty(Difficulty difficulty) CharacterDatabase.Execute(stmt); } - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player->GetSession()) @@ -1993,7 +2002,7 @@ void Group::SetRaidDifficulty(Difficulty difficulty) CharacterDatabase.Execute(stmt); } - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player->GetSession()) @@ -2006,7 +2015,7 @@ void Group::SetRaidDifficulty(Difficulty difficulty) bool Group::InCombatToInstance(uint32 instanceId) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (player && player->GetInstanceId() == instanceId && !player->getAttackers().empty() && (player->GetMap()->IsRaidOrHeroicDungeon())) @@ -2030,7 +2039,7 @@ void Group::ResetInstances(uint8 method, bool isRaid, Player* SendMsgTo) for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();) { InstanceSave* instanceSave = itr->second.save; - const MapEntry* entry = sMapStore.LookupEntry(itr->first); + MapEntry const* entry = sMapStore.LookupEntry(itr->first); if (!entry || entry->IsRaid() != isRaid || (!instanceSave->CanReset() && method != INSTANCE_RESET_GROUP_DISBAND)) { ++itr; @@ -2066,7 +2075,7 @@ void Group::ResetInstances(uint8 method, bool isRaid, Player* SendMsgTo) { if (Group* group = SendMsgTo->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* player = groupRef->GetSource()) player->SendResetInstanceSuccess(instanceSave->GetMapId()); } @@ -2122,7 +2131,7 @@ InstanceGroupBind* Group::GetBoundInstance(Map* aMap) InstanceGroupBind* Group::GetBoundInstance(MapEntry const* mapEntry) { if (!mapEntry || !mapEntry->IsDungeon()) - return NULL; + return nullptr; Difficulty difficulty = GetDifficulty(mapEntry->IsRaid()); return GetBoundInstance(difficulty, mapEntry->MapID); @@ -2137,13 +2146,13 @@ InstanceGroupBind* Group::GetBoundInstance(Difficulty difficulty, uint32 mapId) if (itr != m_boundInstances[difficulty].end()) return &itr->second; else - return NULL; + return nullptr; } InstanceGroupBind* Group::BindToInstance(InstanceSave* save, bool permanent, bool load) { if (!save || isBGGroup() || isBFGroup()) - return NULL; + return nullptr; InstanceGroupBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()]; if (!load && (!bind.save || permanent != bind.perm || save != bind.save)) @@ -2218,7 +2227,7 @@ void Group::BroadcastGroupUpdate(void) void Group::ResetMaxEnchantingLevel() { m_maxEnchantingLevel = 0; - Player* member = NULL; + Player* member = nullptr; for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr) { member = ObjectAccessor::FindPlayer(citr->guid); @@ -2274,12 +2283,12 @@ bool Group::isRaidGroup() const bool Group::isBGGroup() const { - return m_bgGroup != NULL; + return m_bgGroup != nullptr; } bool Group::isBFGroup() const { - return m_bfGroup != NULL; + return m_bfGroup != nullptr; } bool Group::IsCreated() const @@ -2459,7 +2468,7 @@ bool Group::isRollLootActive() const Group::Rolls::iterator Group::GetRoll(ObjectGuid Guid) { Rolls::iterator iter; - for (iter=RollId.begin(); iter != RollId.end(); ++iter) + for (iter = RollId.begin(); iter != RollId.end(); ++iter) if ((*iter)->itemGUID == Guid && (*iter)->isValid()) return iter; return RollId.end(); diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index bee3f95350a..1aa498842cf 100644 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -20,10 +20,11 @@ #define TRINITYCORE_GROUP_H #include "DBCEnums.h" +#include "DatabaseEnvFwd.h" #include "GroupRefManager.h" -#include "LootMgr.h" -#include "QueryResult.h" +#include "Loot.h" #include "SharedDefines.h" +#include class Battlefield; class Battleground; @@ -153,7 +154,7 @@ struct InstanceGroupBind bool perm; /* permanent InstanceGroupBinds exist if the leader has a permanent PlayerInstanceBind for the same instance. */ - InstanceGroupBind() : save(NULL), perm(false) { } + InstanceGroupBind() : save(nullptr), perm(false) { } }; /** request member stats checken **/ @@ -192,7 +193,7 @@ class TC_GAME_API Group void RemoveAllInvites(); bool AddLeaderInvite(Player* player); bool AddMember(Player* player); - bool RemoveMember(ObjectGuid guid, const RemoveMethod &method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, const char* reason = NULL); + bool RemoveMember(ObjectGuid guid, RemoveMethod const& method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, char const* reason = nullptr); void ChangeLeader(ObjectGuid guid); static void ConvertLeaderInstancesToGroup(Player* player, Group* group, bool switchLeader); void SetLootMethod(LootMethod method); @@ -272,7 +273,7 @@ class TC_GAME_API Group //void SendInit(WorldSession* session); void SendTargetIconList(WorldSession* session); void SendUpdate(); - void SendUpdateToPlayer(ObjectGuid playerGUID, MemberSlot* slot = NULL); + void SendUpdateToPlayer(ObjectGuid playerGUID, MemberSlot* slot = nullptr); void UpdatePlayerOutOfRange(Player* player); template @@ -298,10 +299,10 @@ class TC_GAME_API Group /*********************************************************/ bool isRollLootActive() const; - void SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll &r); + void SendLootStartRoll(uint32 CountDown, uint32 mapid, Roll const& r); void SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, bool canNeed, Roll const& r); - void SendLootRoll(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r); - void SendLootRollWon(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r); + void SendLootRoll(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, Roll const& r); + void SendLootRollWon(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, Roll const& r); void SendLootAllPassed(Roll const& roll); void SendLooter(Creature* creature, Player* pLooter); void GroupLoot(Loot* loot, WorldObject* pLootedObject); diff --git a/src/server/game/Groups/GroupMgr.cpp b/src/server/game/Groups/GroupMgr.cpp index 1d0714bdf3e..13a017c4443 100644 --- a/src/server/game/Groups/GroupMgr.cpp +++ b/src/server/game/Groups/GroupMgr.cpp @@ -15,11 +15,13 @@ * with this program. If not, see . */ -#include "Common.h" #include "GroupMgr.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "InstanceSaveMgr.h" +#include "Log.h" #include "World.h" -#include "DBCStores.h" GroupMgr::GroupMgr() { @@ -39,7 +41,7 @@ uint32 GroupMgr::GenerateNewGroupDbStoreId() for (uint32 i = ++NextGroupDbStoreId; i < 0xFFFFFFFF; ++i) { - if ((i < GroupDbStore.size() && GroupDbStore[i] == NULL) || i >= GroupDbStore.size()) + if ((i < GroupDbStore.size() && GroupDbStore[i] == nullptr) || i >= GroupDbStore.size()) { NextGroupDbStoreId = i; break; @@ -71,7 +73,7 @@ void GroupMgr::FreeGroupDbStoreId(Group* group) if (storageId < NextGroupDbStoreId) NextGroupDbStoreId = storageId; - GroupDbStore[storageId] = NULL; + GroupDbStore[storageId] = nullptr; } Group* GroupMgr::GetGroupByDbStoreId(uint32 storageId) const @@ -79,7 +81,7 @@ Group* GroupMgr::GetGroupByDbStoreId(uint32 storageId) const if (storageId < GroupDbStore.size()) return GroupDbStore[storageId]; - return NULL; + return nullptr; } ObjectGuid::LowType GroupMgr::GenerateGroupId() @@ -104,7 +106,7 @@ Group* GroupMgr::GetGroupByGUID(ObjectGuid::LowType groupId) const if (itr != GroupStore.end()) return itr->second; - return NULL; + return nullptr; } void GroupMgr::AddGroup(Group* group) diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index 488601d9536..54d802ef546 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -16,20 +16,25 @@ * with this program. If not, see . */ +#include "Guild.h" #include "AccountMgr.h" +#include "Bag.h" #include "CalendarMgr.h" #include "CharacterCache.h" #include "Chat.h" #include "Config.h" #include "DatabaseEnv.h" -#include "Guild.h" #include "GuildMgr.h" #include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" #include "ScriptMgr.h" #include "SocialMgr.h" -#include "Opcodes.h" - +#include "World.h" +#include "WorldSession.h" size_t const MAX_GUILD_BANK_TAB_TEXT_LEN = 500; @@ -384,6 +389,11 @@ void Guild::RankInfo::SetBankTabSlotsAndRights(GuildBankRightsAndSlots rightsAnd } // BankTab +Guild::BankTab::BankTab(ObjectGuid::LowType guildId, uint8 tabId) : m_guildId(guildId), m_tabId(tabId) +{ + memset(m_items, 0, GUILD_BANK_MAX_SLOTS * sizeof(Item*)); +} + void Guild::BankTab::LoadFromDB(Field* fields) { m_name = fields[2].GetString(); @@ -505,6 +515,12 @@ bool Guild::BankTab::WriteSlotPacket(WorldPacket& data, uint8 slotId, bool ignor return true; } +void Guild::BankTab::WriteInfoPacket(WorldPacket& data) const +{ + data << m_name; + data << m_icon; +} + void Guild::BankTab::SetInfo(std::string const& name, std::string const& icon) { if (m_name == name && m_icon == icon) @@ -589,6 +605,20 @@ void Guild::BankTab::SendText(Guild const* guild, WorldSession* session) const } // Member +Guild::Member::Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId) : + m_guildId(guildId), + m_guid(guid), + m_zoneId(0), + m_level(0), + m_class(0), + m_flags(GUILDMEMBER_STATUS_NONE), + m_logoutTime(::time(nullptr)), + m_accountId(0), + m_rankId(rankId) +{ + memset(m_bankWithdraw, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(int32)); +} + void Guild::Member::SetStats(Player* player) { m_name = player->GetName(); @@ -728,6 +758,16 @@ void Guild::Member::WritePacket(WorldPacket& data, bool sendOfficerNote) const data << ""; } +Player* Guild::Member::FindPlayer() const +{ + return ObjectAccessor::FindPlayer(m_guid); +} + +Player* Guild::Member::FindConnectedPlayer() const +{ + return ObjectAccessor::FindConnectedPlayer(m_guid); +} + // Decreases amount of money/slots left for today. // If (tabId == GUILD_BANK_MAX_TABS) decrease money amount. // Otherwise decrease remaining items amount for specified tab. @@ -801,6 +841,15 @@ void EmblemInfo::SaveToDB(ObjectGuid::LowType guildId) const } // MoveItemData +Guild::MoveItemData::MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId) : m_pGuild(guild), m_pPlayer(player), +m_container(container), m_slotId(slotId), m_pItem(nullptr), m_pClonedItem(nullptr) +{ +} + +Guild::MoveItemData::~MoveItemData() +{ +} + bool Guild::MoveItemData::CheckItem(uint32& splitedAmount) { ASSERT(m_pItem); @@ -1392,7 +1441,7 @@ void Guild::HandleSetInfo(WorldSession* session, std::string const& info) } } -void Guild::HandleSetEmblem(WorldSession* session, const EmblemInfo& emblemInfo) +void Guild::HandleSetEmblem(WorldSession* session, EmblemInfo const& emblemInfo) { Player* player = session->GetPlayer(); if (!_IsLeader(player)) @@ -1463,7 +1512,7 @@ void Guild::HandleSetMemberNote(WorldSession* session, std::string const& name, } } -void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, const GuildBankRightsAndSlotsVec& rightsAndSlots) +void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, GuildBankRightsAndSlotsVec const& rightsAndSlots) { // Only leader can modify ranks if (!_IsLeader(session->GetPlayer())) @@ -1561,7 +1610,7 @@ void Guild::HandleInviteMember(WorldSession* session, std::string const& name) WorldPacket data(SMSG_GUILD_INVITE, 8 + 10); // Guess size data << player->GetName(); data << m_name; - pInvitee->GetSession()->SendPacket(&data); + pInvitee->SendDirectMessage(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_INVITE [%s]", pInvitee->GetName().c_str()); } @@ -1857,7 +1906,7 @@ void Guild::SendBankLog(WorldSession* session, uint8 tabId) const // GUILD_BANK_MAX_TABS send by client for money log if (tabId < _GetPurchasedTabsSize() || tabId == GUILD_BANK_MAX_TABS) { - const LogHolder* pLog = m_bankEventLog[tabId]; + LogHolder const* pLog = m_bankEventLog[tabId]; WorldPacket data(MSG_GUILD_BANK_LOG_QUERY, pLog->GetSize() * (4 * 4 + 1) + 1 + 1); data << uint8(tabId); pLog->WritePacket(data); @@ -2164,7 +2213,7 @@ void Guild::BroadcastToGuild(WorldSession* session, bool officerOnly, std::strin if (Player* player = itr->second->FindConnectedPlayer()) if (player->GetSession() && _HasRankRight(player, officerOnly ? GR_RIGHT_OFFCHATLISTEN : GR_RIGHT_GCHATLISTEN) && !player->GetSocial()->HasIgnore(session->GetPlayer()->GetGUID())) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -2173,14 +2222,14 @@ void Guild::BroadcastPacketToRank(WorldPacket* packet, uint8 rankId) const for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->second->IsRank(rankId)) if (Player* player = itr->second->FindConnectedPlayer()) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void Guild::BroadcastPacket(WorldPacket* packet) const { for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (Player* player = itr->second->FindPlayer()) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void Guild::MassInviteToEvent(WorldSession* session, uint32 minLevel, uint32 maxLevel, uint32 minRank) @@ -2406,6 +2455,21 @@ void Guild::SetBankTabText(uint8 tabId, std::string const& text) } } +bool Guild::_HasRankRight(Player* player, uint32 right) const +{ + if (player) + if (Member const* member = GetMember(player->GetGUID())) + return (_GetRankRights(member->GetRankId()) & right) != GR_RIGHT_EMPTY; + return false; +} + +void Guild::_DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid) +{ + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); + stmt->setUInt32(0, lowguid); + CharacterDatabase.ExecuteOrAppend(trans, stmt); +} + // Private methods void Guild::_CreateLogHolders() { @@ -2499,7 +2563,7 @@ bool Guild::_IsLeader(Player* player) const { if (player->GetGUID() == m_leaderGuid) return true; - if (const Member* member = GetMember(player->GetGUID())) + if (Member const* member = GetMember(player->GetGUID())) return member->IsRank(GR_GUILDMASTER); return false; } @@ -2568,21 +2632,21 @@ void Guild::_SetRankBankTabRightsAndSlots(uint8 rankId, GuildBankRightsAndSlots inline std::string Guild::_GetRankName(uint8 rankId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetName(); return ""; } inline uint32 Guild::_GetRankRights(uint8 rankId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetRights(); return 0; } inline int32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankMoneyPerDay(); return 0; } @@ -2590,14 +2654,14 @@ inline int32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const inline int32 Guild::_GetRankBankTabSlotsPerDay(uint8 rankId, uint8 tabId) const { if (tabId < _GetPurchasedTabsSize()) - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabSlotsPerDay(tabId); return 0; } inline int8 Guild::_GetRankBankTabRights(uint8 rankId, uint8 tabId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabRights(tabId); return 0; } @@ -2650,7 +2714,7 @@ inline void Guild::_UpdateMemberWithdrawSlots(SQLTransaction& trans, ObjectGuid inline bool Guild::_MemberHasTabRights(ObjectGuid guid, uint8 tabId, uint32 rights) const { - if (const Member* member = GetMember(guid)) + if (Member const* member = GetMember(guid)) { // Leader always has full rights if (member->IsRank(GR_GUILDMASTER) || m_leaderGuid == guid) @@ -2694,7 +2758,7 @@ void Guild::_LogBankEvent(SQLTransaction& trans, GuildBankEventLogTypes eventTyp inline Item* Guild::_GetItem(uint8 tabId, uint8 slotId) const { - if (const BankTab* tab = GetBankTab(tabId)) + if (BankTab const* tab = GetBankTab(tabId)) return tab->GetItem(slotId); return nullptr; } @@ -2861,7 +2925,7 @@ void Guild::_SendBankContentUpdate(uint8 tabId, SlotIds slots) const _SendBankList(nullptr, tabId, false, &slots); } -void Guild::_BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, const char* param1, const char* param2, const char* param3) const +void Guild::_BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, char const* param1, char const* param2, char const* param3) const { uint8 count = !param3 ? (!param2 ? (!param1 ? 0 : 1) : 2) : 3; @@ -2936,7 +3000,7 @@ void Guild::_SendBankList(WorldSession* session /* = nullptr*/, uint8 tabId /*= uint32 numSlots = _GetMemberRemainingSlots(itr->second, tabId); data.put(rempos, numSlots); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_BANK_LIST [%s]: TabId: %u, FullSlots: %u, slots: %u" , player->GetName().c_str(), tabId, sendAllSlots, numSlots); } diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index 38510d8c06b..4c904dd8e37 100644 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -19,13 +19,18 @@ #ifndef TRINITYCORE_GUILD_H #define TRINITYCORE_GUILD_H -#include "World.h" -#include "Item.h" -#include "WorldPacket.h" -#include "ObjectMgr.h" -#include "Player.h" +#include "DatabaseEnvFwd.h" +#include "ObjectGuid.h" +#include "SharedDefines.h" +#include class Item; +class Player; +class WorldPacket; +class WorldSession; +struct ItemPosCount; +enum InventoryResult : uint8; +enum LocaleConstant : uint8; enum GuildMisc { @@ -270,19 +275,7 @@ class TC_GAME_API Guild class Member { public: - Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId) : - m_guildId(guildId), - m_guid(guid), - m_zoneId(0), - m_level(0), - m_class(0), - m_flags(GUILDMEMBER_STATUS_NONE), - m_logoutTime(::time(nullptr)), - m_accountId(0), - m_rankId(rankId) - { - memset(m_bankWithdraw, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(int32)); - } + Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId); void SetStats(Player* player); void SetStats(std::string const& name, uint8 level, uint8 _class, uint32 zoneId, uint32 accountId); @@ -325,8 +318,8 @@ class TC_GAME_API Guild int32 GetBankWithdrawValue(uint8 tabId) const; void ResetValues(); - inline Player* FindPlayer() const { return ObjectAccessor::FindPlayer(m_guid); } - inline Player* FindConnectedPlayer() const { return ObjectAccessor::FindConnectedPlayer(m_guid); } + Player* FindPlayer() const; + Player* FindConnectedPlayer() const; private: ObjectGuid::LowType m_guildId; @@ -501,10 +494,7 @@ class TC_GAME_API Guild class BankTab { public: - BankTab(ObjectGuid::LowType guildId, uint8 tabId) : m_guildId(guildId), m_tabId(tabId) - { - memset(m_items, 0, GUILD_BANK_MAX_SLOTS * sizeof(Item*)); - } + BankTab(ObjectGuid::LowType guildId, uint8 tabId); void LoadFromDB(Field* fields); bool LoadItemFromDB(Field* fields); @@ -512,17 +502,13 @@ class TC_GAME_API Guild void WritePacket(WorldPacket& data) const; bool WriteSlotPacket(WorldPacket& data, uint8 slotId, bool ignoreEmpty = true) const; - void WriteInfoPacket(WorldPacket& data) const - { - data << m_name; - data << m_icon; - } + void WriteInfoPacket(WorldPacket& data) const; void SetInfo(std::string const& name, std::string const& icon); void SetText(std::string const& text); - void SendText(const Guild* guild, WorldSession* session) const; + void SendText(Guild const* guild, WorldSession* session) const; - inline Item* GetItem(uint8 slotId) const { return slotId < GUILD_BANK_MAX_SLOTS ? m_items[slotId] : NULL; } + inline Item* GetItem(uint8 slotId) const { return slotId < GUILD_BANK_MAX_SLOTS ? m_items[slotId] : nullptr; } bool SetItem(SQLTransaction& trans, uint8 slotId, Item* pItem); private: @@ -539,9 +525,8 @@ class TC_GAME_API Guild class MoveItemData { public: - MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId) : m_pGuild(guild), m_pPlayer(player), - m_container(container), m_slotId(slotId), m_pItem(NULL), m_pClonedItem(NULL) { } - virtual ~MoveItemData() { } + MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId); + virtual ~MoveItemData(); virtual bool IsBank() const = 0; // Initializes item pointer. Returns true, if item exists, false otherwise. @@ -580,7 +565,7 @@ class TC_GAME_API Guild uint8 m_slotId; Item* m_pItem; Item* m_pClonedItem; - ItemPosCountVec m_vec; + std::vector m_vec; }; class PlayerMoveItemData : public MoveItemData @@ -653,11 +638,11 @@ class TC_GAME_API Guild void HandleQuery(WorldSession* session); void HandleSetMOTD(WorldSession* session, std::string const& motd); void HandleSetInfo(WorldSession* session, std::string const& info); - void HandleSetEmblem(WorldSession* session, const EmblemInfo& emblemInfo); + void HandleSetEmblem(WorldSession* session, EmblemInfo const& emblemInfo); void HandleSetLeader(WorldSession* session, std::string const& name); void HandleSetBankTabInfo(WorldSession* session, uint8 tabId, std::string const& name, std::string const& icon); void HandleSetMemberNote(WorldSession* session, std::string const& name, std::string const& note, bool officer); - void HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, const GuildBankRightsAndSlotsVec& rightsAndSlots); + void HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, GuildBankRightsAndSlotsVec const& rightsAndSlots); void HandleBuyBankTab(WorldSession* session, uint8 tabId); void HandleInviteMember(WorldSession* session, std::string const& name); void HandleAcceptMember(WorldSession* session); @@ -752,13 +737,7 @@ class TC_GAME_API Guild inline uint8 _GetRanksSize() const { return uint8(m_ranks.size()); } inline RankInfo const* GetRankInfo(uint8 rankId) const { return rankId < _GetRanksSize() ? &m_ranks[rankId] : nullptr; } inline RankInfo* GetRankInfo(uint8 rankId) { return rankId < _GetRanksSize() ? &m_ranks[rankId] : nullptr; } - inline bool _HasRankRight(Player* player, uint32 right) const - { - if (player) - if (Member const* member = GetMember(player->GetGUID())) - return (_GetRankRights(member->GetRankId()) & right) != GR_RIGHT_EMPTY; - return false; - } + bool _HasRankRight(Player* player, uint32 right) const; inline uint8 _GetLowestRankId() const { return uint8(m_ranks.size() - 1); } @@ -787,12 +766,7 @@ class TC_GAME_API Guild return nullptr; } - inline void _DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid) const - { - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); - stmt->setUInt32(0, lowguid); - CharacterDatabase.ExecuteOrAppend(trans, stmt); - } + static void _DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid); // Creates log holders (either when loading or when creating guild) void _CreateLogHolders(); @@ -834,8 +808,8 @@ class TC_GAME_API Guild void _SendBankMoneyUpdate(WorldSession* session) const; void _SendBankContentUpdate(MoveItemData* pSrc, MoveItemData* pDest) const; void _SendBankContentUpdate(uint8 tabId, SlotIds slots) const; - void _SendBankList(WorldSession* session = NULL, uint8 tabId = 0, bool sendFullSlots = false, SlotIds *slots = NULL) const; + void _SendBankList(WorldSession* session = nullptr, uint8 tabId = 0, bool sendFullSlots = false, SlotIds* slots = nullptr) const; - void _BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, const char* param1 = NULL, const char* param2 = NULL, const char* param3 = NULL) const; + void _BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, char const* param1 = nullptr, char const* param2 = nullptr, char const* param3 = nullptr) const; }; #endif diff --git a/src/server/game/Guilds/GuildMgr.cpp b/src/server/game/Guilds/GuildMgr.cpp index ca89fae95c1..e49e3dd624e 100644 --- a/src/server/game/Guilds/GuildMgr.cpp +++ b/src/server/game/Guilds/GuildMgr.cpp @@ -15,8 +15,12 @@ * with this program. If not, see . */ -#include "Common.h" #include "GuildMgr.h" +#include "DatabaseEnv.h" +#include "Guild.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "World.h" GuildMgr::GuildMgr() : NextGuildId(1) { } @@ -54,7 +58,7 @@ Guild* GuildMgr::GetGuildById(ObjectGuid::LowType guildId) const if (itr != GuildStore.end()) return itr->second; - return NULL; + return nullptr; } Guild* GuildMgr::GetGuildByName(const std::string& guildName) const @@ -68,7 +72,7 @@ Guild* GuildMgr::GetGuildByName(const std::string& guildName) const if (search == gname) return itr->second; } - return NULL; + return nullptr; } std::string GuildMgr::GetGuildNameById(ObjectGuid::LowType guildId) const @@ -91,7 +95,7 @@ Guild* GuildMgr::GetGuildByLeader(ObjectGuid guid) const if (itr->second->GetLeaderGUID() == guid) return itr->second; - return NULL; + return nullptr; } void GuildMgr::LoadGuilds() diff --git a/src/server/game/Guilds/GuildMgr.h b/src/server/game/Guilds/GuildMgr.h index 75ff0648090..b1fa01f28a0 100644 --- a/src/server/game/Guilds/GuildMgr.h +++ b/src/server/game/Guilds/GuildMgr.h @@ -18,13 +18,20 @@ #ifndef _GUILDMGR_H #define _GUILDMGR_H -#include "Guild.h" +#include "Define.h" +#include "ObjectGuid.h" +#include +#include + +class Guild; class TC_GAME_API GuildMgr { private: GuildMgr(); ~GuildMgr(); + GuildMgr(GuildMgr const&) = delete; + GuildMgr& operator=(GuildMgr const&) = delete; public: static GuildMgr* instance(); diff --git a/src/server/game/Handlers/ArenaTeamHandler.cpp b/src/server/game/Handlers/ArenaTeamHandler.cpp index 63c766433fa..9c7efa1ee05 100644 --- a/src/server/game/Handlers/ArenaTeamHandler.cpp +++ b/src/server/game/Handlers/ArenaTeamHandler.cpp @@ -16,16 +16,18 @@ * with this program. If not, see . */ -#include "Player.h" -#include "WorldPacket.h" #include "WorldSession.h" #include "ArenaTeam.h" -#include "SocialMgr.h" #include "ArenaTeamMgr.h" -#include "Opcodes.h" +#include "CharacterCache.h" +#include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "CharacterCache.h" +#include "Opcodes.h" +#include "Player.h" +#include "SocialMgr.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleInspectArenaTeamsOpcode(WorldPacket& recvData) { @@ -88,7 +90,7 @@ void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket& recvData) uint32 arenaTeamId; // arena team id std::string invitedName; - Player* player = NULL; + Player* player = nullptr; recvData >> arenaTeamId >> invitedName; @@ -160,7 +162,7 @@ void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket& recvData) WorldPacket data(SMSG_ARENA_TEAM_INVITE, (8+10)); data << GetPlayer()->GetName(); data << arenaTeam->GetName(); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_ARENA_TEAM_INVITE"); } diff --git a/src/server/game/Handlers/AuctionHouseHandler.cpp b/src/server/game/Handlers/AuctionHouseHandler.cpp index 49373d97036..a0d6ae3bdd2 100644 --- a/src/server/game/Handlers/AuctionHouseHandler.cpp +++ b/src/server/game/Handlers/AuctionHouseHandler.cpp @@ -16,19 +16,24 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" -#include "Player.h" -#include "World.h" -#include "WorldPacket.h" #include "WorldSession.h" - +#include "AccountMgr.h" #include "AuctionHouseMgr.h" #include "CharacterCache.h" -#include "Log.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "DBCStructure.h" +#include "Item.h" #include "Language.h" +#include "Log.h" +#include "Mail.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" #include "UpdateMask.h" #include "Util.h" -#include "AccountMgr.h" +#include "World.h" +#include "WorldPacket.h" //void called when player click on auctioneer npc void WorldSession::HandleAuctionHelloOpcode(WorldPacket& recvData) @@ -280,7 +285,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) return; } - const AuctionHouseEntry* AHEntry = sAuctionMgr->GetAuctionHouseEntry(auctioneerInfo->faction); + AuctionHouseEntry const* AHEntry = sAuctionMgr->GetAuctionHouseEntry(auctioneerInfo->faction); AH->houseId = AHEntry->houseId; } @@ -302,7 +307,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) AH->bidder = 0; AH->bid = 0; AH->buyout = buyout; - AH->expire_time = time(NULL) + auctionTime; + AH->expire_time = time(nullptr) + auctionTime; AH->deposit = deposit; AH->etime = etime; AH->auctionHouseEntry = auctionHouseEntry; @@ -359,7 +364,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) AH->bidder = 0; AH->bid = 0; AH->buyout = buyout; - AH->expire_time = time(NULL) + auctionTime; + AH->expire_time = time(nullptr) + auctionTime; AH->deposit = deposit; AH->etime = etime; AH->auctionHouseEntry = auctionHouseEntry; diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index ba5cb325098..8b03ff91240 100644 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -16,25 +16,29 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectAccessor.h" -#include "ObjectMgr.h" -#include "ArenaTeamMgr.h" -#include "WorldPacket.h" #include "WorldSession.h" - #include "ArenaTeam.h" -#include "BattlegroundMgr.h" +#include "ArenaTeamMgr.h" #include "Battleground.h" +#include "BattlegroundMgr.h" #include "Chat.h" +#include "Common.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "DisableMgr.h" #include "GameTime.h" +#include "Group.h" #include "Language.h" #include "Log.h" -#include "Player.h" +#include "MotionMaster.h" #include "Object.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" -#include "DisableMgr.h" -#include "Group.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket& recvData) { @@ -42,13 +46,10 @@ void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket& recvData) recvData >> guid; TC_LOG_DEBUG("network", "WORLD: Recvd CMSG_BATTLEMASTER_HELLO Message from %s", guid.ToString().c_str()); - Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); + Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_BATTLEMASTER); if (!unit) return; - if (!unit->IsBattleMaster()) // it's not battlemaster - return; - // Stop the npc if moving unit->StopMoving(); @@ -78,7 +79,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) uint32 instanceId; uint8 joinAsGroup; bool isPremade = false; - Group* grp = NULL; + Group* grp = nullptr; recvData >> guid; // battlemaster guid recvData >> bgTypeId_; // battleground type id (DBC id) @@ -91,7 +92,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) return; } - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId_, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId_, nullptr)) { ChatHandler(this).PSendSysMessage(LANG_BG_DISABLED); return; @@ -110,7 +111,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) return; // get bg instance or bg template if instance not found - Battleground* bg = NULL; + Battleground* bg = nullptr; if (instanceId) bg = sBattlegroundMgr->GetBattlegroundThroughClientInstance(instanceId, bgTypeId); @@ -134,7 +135,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) // player is using dungeon finder or raid finder WorldPacket data; sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_LFG_CANT_USE_BATTLEGROUND); - GetPlayer()->GetSession()->SendPacket(&data); + GetPlayer()->SendDirectMessage(&data); return; } @@ -143,7 +144,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -152,7 +153,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) // player is already in random queue WorldPacket data; sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_IN_RANDOM_BG); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -161,7 +162,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) // player is already in queue, can't start random queue WorldPacket data; sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_IN_NON_RANDOM_BG); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -175,7 +176,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_BATTLEGROUND_TOO_MANY_QUEUES); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -185,7 +186,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId); - GroupQueueInfo* ginfo = bgQueue.AddGroup(_player, NULL, bgTypeId, bracketEntry, 0, false, isPremade, 0, 0); + GroupQueueInfo* ginfo = bgQueue.AddGroup(_player, nullptr, bgTypeId, bracketEntry, 0, false, isPremade, 0, 0); uint32 avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); // already checked if queueSlot is valid, now just get it uint32 queueSlot = _player->AddBattlegroundQueueId(bgQueueTypeId); @@ -209,7 +210,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) isPremade = (grp->GetMembersCount() >= bg->GetMinPlayersPerTeam()); BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId); - GroupQueueInfo* ginfo = NULL; + GroupQueueInfo* ginfo = nullptr; uint32 avgTime = 0; if (err > 0) @@ -219,7 +220,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); } - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -230,7 +231,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) if (err <= 0) { sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); continue; } @@ -239,9 +240,9 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) // send status packet (in queue) sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->ArenaType, 0); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); TC_LOG_DEBUG("bg.battleground", "Battleground: player joined queue for bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUID().GetCounter(), member->GetName().c_str()); } @@ -259,8 +260,8 @@ void WorldSession::HandleBattlegroundPlayerPositionsOpcode(WorldPacket& /*recvDa return; uint32 flagCarrierCount = 0; - Player* allianceFlagCarrier = NULL; - Player* hordeFlagCarrier = NULL; + Player* allianceFlagCarrier = nullptr; + Player* hordeFlagCarrier = nullptr; if (ObjectGuid guid = bg->GetFlagPickerGUID(TEAM_ALLIANCE)) { @@ -423,7 +424,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) //send bg command result to show nice message WorldPacket data2; sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data2, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); - _player->GetSession()->SendPacket(&data2); + _player->SendDirectMessage(&data2); action = 0; TC_LOG_DEBUG("bg.battleground", "Player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName().c_str(), _player->GetGUID().GetCounter()); } @@ -463,7 +464,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) } sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime(), bg->GetArenaType(), ginfo.Team); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); // remove battleground queue status from BGmgr bgQueue.RemovePlayer(_player->GetGUID(), false); @@ -545,7 +546,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) WorldPacket data; // we must update all queues here - Battleground* bg = NULL; + Battleground* bg = nullptr; for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) { BattlegroundQueueTypeId bgQueueTypeId = _player->GetBattlegroundQueueTypeId(i); @@ -610,7 +611,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) uint8 arenaslot; // 2v2, 3v3 or 5v5 uint8 asGroup; // asGroup uint8 isRated; // isRated - Group* grp = NULL; + Group* grp = nullptr; recvData >> guid >> arenaslot >> asGroup >> isRated; @@ -618,13 +619,10 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) if (_player->InBattleground()) return; - Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); + Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_BATTLEMASTER); if (!unit) return; - if (!unit->IsBattleMaster()) // it's not battle master - return; - uint8 arenatype = 0; uint32 arenaRating = 0; uint32 matchmakerRating = 0; @@ -653,7 +651,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) return; } - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, BATTLEGROUND_AA, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, BATTLEGROUND_AA, nullptr)) { ChatHandler(this).PSendSysMessage(LANG_ARENA_DISABLED); return; @@ -729,7 +727,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); } - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -740,7 +738,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) if (err <= 0) { sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); continue; } @@ -749,15 +747,15 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) // send status packet (in queue) sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype, 0); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); TC_LOG_DEBUG("bg.battleground", "Battleground: player joined queue for arena as group bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUID().GetCounter(), member->GetName().c_str()); } } else { - GroupQueueInfo* ginfo = bgQueue.AddGroup(_player, NULL, bgTypeId, bracketEntry, arenatype, isRated != 0, false, arenaRating, matchmakerRating, ateamId); + GroupQueueInfo* ginfo = bgQueue.AddGroup(_player, nullptr, bgTypeId, bracketEntry, arenatype, isRated != 0, false, arenaRating, matchmakerRating, ateamId); uint32 avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); uint32 queueSlot = _player->AddBattlegroundQueueId(bgQueueTypeId); diff --git a/src/server/game/Handlers/BattlefieldHandler.cpp b/src/server/game/Handlers/BattlefieldHandler.cpp index a1107702ae6..cbf6b0b87a9 100644 --- a/src/server/game/Handlers/BattlefieldHandler.cpp +++ b/src/server/game/Handlers/BattlefieldHandler.cpp @@ -15,13 +15,13 @@ * with this program. If not, see . */ -#include "Opcodes.h" -#include "Player.h" -#include "WorldPacket.h" #include "WorldSession.h" - #include "Battlefield.h" #include "BattlefieldMgr.h" +#include "Log.h" +#include "Opcodes.h" +#include "Player.h" +#include "WorldPacket.h" /** * @fn void WorldSession::SendBfInvitePlayerToWar(uint32 battleId, uint32 zoneId, uint32 acceptTime) @@ -37,7 +37,7 @@ void WorldSession::SendBfInvitePlayerToWar(uint32 battleId, uint32 zoneId, uint3 WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 12); data << uint32(battleId); data << uint32(zoneId); - data << uint32(time(NULL) + acceptTime); + data << uint32(time(nullptr) + acceptTime); SendPacket(&data); } diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index 8b314838cf1..6d884ca2ee9 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -35,25 +35,29 @@ Copied events should probably have a new owner */ +#include "WorldSession.h" +#include "ArenaTeamMgr.h" +#include "CalendarMgr.h" #include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Guild.h" +#include "GuildMgr.h" #include "InstanceSaveMgr.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" #include "SocialMgr.h" -#include "CalendarMgr.h" -#include "ObjectAccessor.h" -#include "DatabaseEnv.h" -#include "GuildMgr.h" -#include "ArenaTeamMgr.h" -#include "WorldSession.h" +#include "World.h" void WorldSession::HandleCalendarGetCalendar(WorldPacket& /*recvData*/) { ObjectGuid guid = _player->GetGUID(); TC_LOG_DEBUG("network", "CMSG_CALENDAR_GET_CALENDAR [%s]", guid.ToString().c_str()); - time_t currTime = time(NULL); + time_t currTime = time(nullptr); WorldPacket data(SMSG_CALENDAR_SEND_CALENDAR, 1000); // Average size if no instance @@ -236,7 +240,7 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventPackedTime) < (time(NULL) - time_t(86400L))) + if (time_t(eventPackedTime) < (time(nullptr) - time_t(86400L))) { recvData.rfinish(); return; @@ -283,7 +287,7 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) catch (ByteBufferException const&) { delete calendarEvent; - calendarEvent = NULL; + calendarEvent = nullptr; throw; } @@ -329,7 +333,7 @@ void WorldSession::HandleCalendarUpdateEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventPackedTime) < (time(NULL) - time_t(86400L))) + if (time_t(eventPackedTime) < (time(nullptr) - time_t(86400L))) { recvData.rfinish(); return; @@ -386,7 +390,7 @@ void WorldSession::HandleCalendarCopyEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventTime) < (time(NULL) - time_t(86400L))) + if (time_t(eventTime) < (time(nullptr) - time_t(86400L))) { recvData.rfinish(); return; @@ -529,7 +533,7 @@ void WorldSession::HandleCalendarEventSignup(WorldPacket& recvData) } CalendarInviteStatus status = tentative ? CALENDAR_STATUS_TENTATIVE : CALENDAR_STATUS_SIGNED_UP; - CalendarInvite* invite = new CalendarInvite(sCalendarMgr->GetFreeInviteId(), eventId, guid, guid, time(NULL), status, CALENDAR_RANK_PLAYER, ""); + CalendarInvite* invite = new CalendarInvite(sCalendarMgr->GetFreeInviteId(), eventId, guid, guid, time(nullptr), status, CALENDAR_RANK_PLAYER, ""); sCalendarMgr->AddInvite(calendarEvent, invite); sCalendarMgr->SendCalendarClearPendingAction(guid); } @@ -561,7 +565,7 @@ void WorldSession::HandleCalendarEventRsvp(WorldPacket& recvData) if (CalendarInvite* invite = sCalendarMgr->GetInvite(inviteId)) { invite->SetStatus(CalendarInviteStatus(status)); - invite->SetStatusTime(time(NULL)); + invite->SetStatusTime(time(nullptr)); sCalendarMgr->UpdateInvite(invite); sCalendarMgr->SendCalendarEventStatus(*calendarEvent, *invite); @@ -624,7 +628,7 @@ void WorldSession::HandleCalendarEventStatus(WorldPacket& recvData) { invite->SetStatus((CalendarInviteStatus)status); // not sure if we should set response time when moderator changes invite status - //invite->SetStatusTime(time(NULL)); + //invite->SetStatusTime(time(nullptr)); sCalendarMgr->UpdateInvite(invite); sCalendarMgr->SendCalendarEventStatus(*calendarEvent, *invite); @@ -730,7 +734,7 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPacket& recvData) void WorldSession::SendCalendarRaidLockout(InstanceSave const* save, bool add) { TC_LOG_DEBUG("network", "%s", add ? "SMSG_CALENDAR_RAID_LOCKOUT_ADDED" : "SMSG_CALENDAR_RAID_LOCKOUT_REMOVED"); - time_t currTime = time(NULL); + time_t currTime = time(nullptr); WorldPacket data(SMSG_CALENDAR_RAID_LOCKOUT_REMOVED, (add ? 4 : 0) + 4 + 4 + 4 + 8); if (add) @@ -755,7 +759,7 @@ void WorldSession::SendCalendarRaidLockoutUpdated(InstanceSave const* save) TC_LOG_DEBUG("network", "SMSG_CALENDAR_RAID_LOCKOUT_UPDATED [%s] Map: %u, Difficulty %u", guid.ToString().c_str(), save->GetMapId(), save->GetDifficulty()); - time_t currTime = time(NULL); + time_t currTime = time(nullptr); WorldPacket data(SMSG_CALENDAR_RAID_LOCKOUT_UPDATED, 4 + 4 + 4 + 4 + 8); data.AppendPackedTime(currTime); diff --git a/src/server/game/Handlers/ChannelHandler.cpp b/src/server/game/Handlers/ChannelHandler.cpp index 009691838c9..75ec79819a0 100644 --- a/src/server/game/Handlers/ChannelHandler.cpp +++ b/src/server/game/Handlers/ChannelHandler.cpp @@ -16,12 +16,13 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" // for normalizePlayerName +#include "WorldSession.h" #include "Channel.h" #include "ChannelMgr.h" +#include "DBCStores.h" +#include "Log.h" +#include "ObjectMgr.h" // for normalizePlayerName #include "Player.h" -#include "WorldSession.h" - #include static size_t const MAX_CHANNEL_PASS_STR = 31; diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index a8a1bb3e329..9bdf294c9b3 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -16,41 +16,40 @@ * with this program. If not, see . */ -#include "AccountMgr.h" -#include "ArenaTeam.h" +#include "WorldSession.h" #include "ArenaTeamMgr.h" -#include "Battleground.h" #include "CalendarMgr.h" #include "CharacterCache.h" #include "Chat.h" -#include "Common.h" #include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameTime.h" +#include "GitRevision.h" #include "Group.h" #include "Guild.h" #include "GuildMgr.h" +#include "InstanceSaveMgr.h" +#include "Item.h" #include "Language.h" #include "Log.h" +#include "Map.h" +#include "Metric.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Pet.h" -#include "PlayerDump.h" #include "Player.h" -#include "QueryCallback.h" +#include "PlayerDump.h" +#include "RBAC.h" +#include "Realm.h" #include "ReputationMgr.h" -#include "GitRevision.h" #include "ScriptMgr.h" #include "ServerMotd.h" -#include "SharedDefines.h" #include "SocialMgr.h" -#include "UpdateMask.h" -#include "Util.h" +#include "QueryHolder.h" #include "World.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Metric.h" - class LoginQueryHolder : public SQLQueryHolder { @@ -126,7 +125,7 @@ bool LoginQueryHolder::Initialize() stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILCOUNT); stmt->setUInt32(0, lowGuid); - stmt->setUInt64(1, uint64(time(NULL))); + stmt->setUInt64(1, uint64(time(nullptr))); res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_COUNT, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILDATE); @@ -680,7 +679,7 @@ void WorldSession::HandleCharDeleteOpcode(WorldPacket& recvData) void WorldSession::HandlePlayerLoginOpcode(WorldPacket& recvData) { - if (PlayerLoading() || GetPlayer() != NULL) + if (PlayerLoading() || GetPlayer() != nullptr) { TC_LOG_ERROR("network", "Player tries to login again, AccountId = %d", GetAccountId()); KickPlayer(); @@ -721,7 +720,7 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) // "GetAccountId() == db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools) if (!pCurrChar->LoadFromDB(playerGuid, holder)) { - SetPlayer(NULL); + SetPlayer(nullptr); KickPlayer(); // disconnect client, player no set to session and it will not deleted or saved at kick delete pCurrChar; // delete it manually delete holder; // delete all unprocessed queries @@ -1481,12 +1480,11 @@ void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData) std::string iconName; recvData >> iconName; - EquipmentSet eqSet; - - eqSet.Guid = setGuid; - eqSet.Name = name; - eqSet.IconName = iconName; - eqSet.state = EQUIPMENT_SET_NEW; + EquipmentSetInfo::EquipmentSetData eqData; + eqData.Guid = setGuid; + eqData.SetID = index; + eqData.SetName = name; + eqData.SetIcon = iconName; for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { @@ -1495,31 +1493,25 @@ void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData) // if client sends 0, it means empty slot if (itemGuid.IsEmpty()) - { - eqSet.Items[i] = 0; continue; - } // equipment manager sends "1" (as raw GUID) for slots set to "ignore" (don't touch slot at equip set) if (itemGuid.GetRawValue() == 1) { // ignored slots saved as bit mask because we have no free special values for Items[i] - eqSet.IgnoreMask |= 1 << i; + eqData.IgnoreMask |= 1 << i; continue; } // some cheating checks Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (!item || item->GetGUID() != itemGuid) - { - eqSet.Items[i] = 0; continue; - } - eqSet.Items[i] = itemGuid.GetCounter(); + eqData.Pieces[i] = itemGuid; } - _player->SetEquipmentSet(index, eqSet); + _player->SetEquipmentSet(eqData); } void WorldSession::HandleEquipmentSetDelete(WorldPacket& recvData) @@ -1572,7 +1564,7 @@ void WorldSession::HandleEquipmentSetUse(WorldPacket& recvData) _player->StoreItem(sDest, uItem, true); } else - _player->SendEquipError(msg, uItem, NULL); + _player->SendEquipError(msg, uItem, nullptr); continue; } diff --git a/src/server/game/Handlers/ChatHandler.cpp b/src/server/game/Handlers/ChatHandler.cpp index 3cfa2293067..eb3200ea87d 100644 --- a/src/server/game/Handlers/ChatHandler.cpp +++ b/src/server/game/Handlers/ChatHandler.cpp @@ -16,29 +16,30 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectAccessor.h" -#include "ObjectMgr.h" -#include "GuildMgr.h" -#include "World.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "DatabaseEnv.h" +#include "AccountMgr.h" #include "CellImpl.h" -#include "Chat.h" +#include "Common.h" #include "Channel.h" #include "ChannelMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "Guild.h" +#include "GuildMgr.h" #include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "ScriptMgr.h" #include "SpellAuraEffects.h" #include "Util.h" -#include "ScriptMgr.h" -#include "AccountMgr.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) { @@ -160,7 +161,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) if (!sender->CanSpeak()) { - std::string timeStr = secsToTimeString(m_muteTime - time(NULL)); + std::string timeStr = secsToTimeString(m_muteTime - time(nullptr)); SendNotification(GetTrinityString(LANG_WAIT_BEFORE_SPEAKING), timeStr.c_str()); recvData.rfinish(); // Prevent warnings return; @@ -343,7 +344,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false, group->GetMemberGroup(GetPlayer()->GetGUID())); break; } @@ -387,7 +388,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID, Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID, Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -405,7 +406,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_LEADER, Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_LEADER, Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -419,7 +420,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; //in battleground, raid warning is sent only to players in battleground - code is ok - ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_WARNING, Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_WARNING, Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -433,7 +434,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND, Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND, Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -447,7 +448,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND_LEADER, Language(lang), sender, NULL, msg);; + ChatHandler::BuildChatPacket(data, CHAT_MSG_BATTLEGROUND_LEADER, Language(lang), sender, nullptr, msg);; group->BroadcastPacket(&data, false); break; } @@ -572,7 +573,7 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket& recvData) if (!GetPlayer()->CanSpeak()) { - std::string timeStr = secsToTimeString(m_muteTime - time(NULL)); + std::string timeStr = secsToTimeString(m_muteTime - time(nullptr)); SendNotification(GetTrinityString(LANG_WAIT_BEFORE_SPEAKING), timeStr.c_str()); return; } @@ -642,7 +643,7 @@ void WorldSession::HandleChatIgnoredOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_IGNORED, LANG_UNIVERSAL, _player, _player, GetPlayer()->GetName()); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void WorldSession::HandleChannelDeclineInvite(WorldPacket &recvPacket) diff --git a/src/server/game/Handlers/CombatHandler.cpp b/src/server/game/Handlers/CombatHandler.cpp index 894f6233c6b..07cadd837fa 100644 --- a/src/server/game/Handlers/CombatHandler.cpp +++ b/src/server/game/Handlers/CombatHandler.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" +#include "CreatureAI.h" +#include "DBCStructure.h" #include "Log.h" -#include "WorldPacket.h" -#include "WorldSession.h" #include "ObjectAccessor.h" -#include "CreatureAI.h" -#include "Vehicle.h" #include "Player.h" +#include "Vehicle.h" +#include "WorldPacket.h" void WorldSession::HandleAttackSwingOpcode(WorldPacket& recvData) { @@ -37,7 +38,7 @@ void WorldSession::HandleAttackSwingOpcode(WorldPacket& recvData) if (!pEnemy) { // stop attack state at client - SendAttackStop(NULL); + SendAttackStop(nullptr); return; } diff --git a/src/server/game/Handlers/DuelHandler.cpp b/src/server/game/Handlers/DuelHandler.cpp index 52513106e77..c520100b470 100644 --- a/src/server/game/Handlers/DuelHandler.cpp +++ b/src/server/game/Handlers/DuelHandler.cpp @@ -43,7 +43,7 @@ void WorldSession::HandleDuelAcceptedOpcode(WorldPacket& recvPacket) TC_LOG_DEBUG("network", "Player 1 is: %u (%s)", player->GetGUID().GetCounter(), player->GetName().c_str()); TC_LOG_DEBUG("network", "Player 2 is: %u (%s)", plTarget->GetGUID().GetCounter(), plTarget->GetName().c_str()); - time_t now = time(NULL); + time_t now = time(nullptr); player->duel->startTimer = now; plTarget->duel->startTimer = now; diff --git a/src/server/game/Handlers/GroupHandler.cpp b/src/server/game/Handlers/GroupHandler.cpp index 857c3a33d49..c3a6362ad8c 100644 --- a/src/server/game/Handlers/GroupHandler.cpp +++ b/src/server/game/Handlers/GroupHandler.cpp @@ -16,12 +16,14 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "CharacterCache.h" #include "Common.h" #include "DatabaseEnv.h" #include "Group.h" #include "GroupMgr.h" #include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Pet.h" #include "Player.h" @@ -31,7 +33,6 @@ #include "Vehicle.h" #include "World.h" #include "WorldPacket.h" -#include "WorldSession.h" class Aura; @@ -151,7 +152,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) data << uint32(0); // unk data << uint8(0); // count data << uint32(0); // unk - invitedPlayer->GetSession()->SendPacket(&data); + invitedPlayer->SendDirectMessage(&data); } return; @@ -209,7 +210,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) data << uint32(0); // unk data << uint8(0); // count data << uint32(0); // unk - invitedPlayer->GetSession()->SendPacket(&data); + invitedPlayer->SendDirectMessage(&data); SendPartyResult(PARTY_OP_INVITE, membername, ERR_PARTY_RESULT_OK); } @@ -286,7 +287,7 @@ void WorldSession::HandleGroupDeclineOpcode(WorldPacket & /*recvData*/) // report WorldPacket data(SMSG_GROUP_DECLINE, GetPlayer()->GetName().length()); data << GetPlayer()->GetName(); - leader->GetSession()->SendPacket(&data); + leader->SendDirectMessage(&data); } void WorldSession::HandleGroupUninviteGuidOpcode(WorldPacket& recvData) diff --git a/src/server/game/Handlers/GuildHandler.cpp b/src/server/game/Handlers/GuildHandler.cpp index 0476cbf3afb..b34b84adf67 100644 --- a/src/server/game/Handlers/GuildHandler.cpp +++ b/src/server/game/Handlers/GuildHandler.cpp @@ -16,14 +16,14 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" -#include "ObjectMgr.h" +#include "Common.h" +#include "Guild.h" #include "GuildMgr.h" #include "Log.h" -#include "Guild.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "WorldPacket.h" void WorldSession::HandleGuildQueryOpcode(WorldPacket& recvPacket) { @@ -457,7 +457,7 @@ void WorldSession::HandleGuildBankSwapItems(WorldPacket& recvData) // Player <-> Bank // Allow to work with inventory only if (!Player::IsInventoryPos(playerBag, playerSlotId) && !(playerBag == NULL_BAG && playerSlotId == NULL_SLOT)) - GetPlayer()->SendEquipError(EQUIP_ERR_NONE, NULL); + GetPlayer()->SendEquipError(EQUIP_ERR_NONE, nullptr); else guild->SwapItemsWithInventory(GetPlayer(), toChar != 0, tabId, slotId, playerBag, playerSlotId, splitedAmount); } diff --git a/src/server/game/Handlers/ItemHandler.cpp b/src/server/game/Handlers/ItemHandler.cpp index 9159cf7f329..9f3e2a52efe 100644 --- a/src/server/game/Handlers/ItemHandler.cpp +++ b/src/server/game/Handlers/ItemHandler.cpp @@ -16,17 +16,20 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" +#include "Bag.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Opcodes.h" +#include "Item.h" #include "Log.h" #include "ObjectMgr.h" #include "Player.h" -#include "Item.h" #include "SpellInfo.h" - -#include "Packets/QueryPackets.h" +#include "QueryPackets.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleSplitItemOpcode(WorldPacket& recvData) { @@ -48,13 +51,13 @@ void WorldSession::HandleSplitItemOpcode(WorldPacket& recvData) if (!_player->IsValidPos(srcbag, srcslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(dstbag, dstslot, false)) // can be autostore pos { - _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } @@ -75,13 +78,13 @@ void WorldSession::HandleSwapInvItemOpcode(WorldPacket& recvData) if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, srcslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, dstslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } @@ -139,13 +142,13 @@ void WorldSession::HandleSwapItem(WorldPacket& recvData) if (!_player->IsValidPos(srcbag, srcslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(dstbag, dstslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } @@ -180,7 +183,7 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanEquipItem(NULL_SLOT, dest, pSrcItem, !pSrcItem->IsBag()); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pSrcItem, NULL); + _player->SendEquipError(msg, pSrcItem, nullptr); return; } @@ -203,7 +206,7 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recvData) msg = _player->CanUnequipItem(dest, !pSrcItem->IsBag()); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pDstItem, NULL); + _player->SendEquipError(msg, pDstItem, nullptr); return; } @@ -279,7 +282,7 @@ void WorldSession::HandleDestroyItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanUnequipItem(pos, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, _player->GetItemByPos(pos), NULL); + _player->SendEquipError(msg, _player->GetItemByPos(pos), nullptr); return; } } @@ -287,13 +290,13 @@ void WorldSession::HandleDestroyItemOpcode(WorldPacket& recvData) Item* pItem = _player->GetItemByPos(bag, slot); if (!pItem) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (pItem->GetTemplate()->Flags & ITEM_FLAG_NO_USER_DESTROY) { - _player->SendEquipError(EQUIP_ERR_CANT_DROP_SOULBOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_DROP_SOULBOUND, nullptr, nullptr); return; } @@ -354,13 +357,13 @@ void WorldSession::HandleReadItem(WorldPacket& recvData) { data.Initialize(SMSG_READ_ITEM_FAILED, 8); TC_LOG_INFO("network", "STORAGE: Unable to read item"); - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); } data << pItem->GetGUID(); SendPacket(&data); } else - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); } void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) @@ -378,7 +381,7 @@ void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) if (!creature) { TC_LOG_DEBUG("network", "WORLD: HandleSellItemOpcode - %s not found or you can not interact with him.", vendorguid.ToString().c_str()); - _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, NULL, itemguid, 0); + _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, itemguid, 0); return; } @@ -458,7 +461,7 @@ void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) { _player->ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount()); _player->RemoveItem(pItem->GetBagSlot(), pItem->GetSlot(), true); - pItem->RemoveFromUpdateQueueOf(_player); + RemoveItemFromUpdateQueueOf(pItem, _player); _player->AddItemToBuyBackSlot(pItem); } @@ -487,7 +490,7 @@ void WorldSession::HandleBuybackItem(WorldPacket& recvData) if (!creature) { TC_LOG_DEBUG("network", "WORLD: HandleBuybackItem - Unit (%s) not found or you can not interact with him.", vendorguid.ToString().c_str()); - _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, NULL, ObjectGuid::Empty, 0); + _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty, 0); return; } @@ -516,7 +519,7 @@ void WorldSession::HandleBuybackItem(WorldPacket& recvData) _player->StoreItem(dest, pItem, true); } else - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } else @@ -603,7 +606,7 @@ void WorldSession::SendListInventory(ObjectGuid vendorGuid) if (!vendor) { TC_LOG_DEBUG("network", "WORLD: SendListInventory - %s not found or you can not interact with him.", vendorGuid.ToString().c_str()); - _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, NULL, ObjectGuid::Empty, 0); + _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty, 0); return; } @@ -704,7 +707,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) if (!_player->IsValidPos(dstbag, NULL_SLOT, false)) // can be autostore pos { - _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } @@ -716,7 +719,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanUnequipItem(src, !_player->IsBagPos (src)); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } } @@ -725,7 +728,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanStoreItem(dstbag, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } @@ -733,7 +736,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) if (dest.size() == 1 && dest[0].pos == src) { // just remove grey item state - _player->SendEquipError(EQUIP_ERR_NONE, pItem, NULL); + _player->SendEquipError(EQUIP_ERR_NONE, pItem, nullptr); return; } @@ -812,13 +815,13 @@ void WorldSession::HandleAutoBankItemOpcode(WorldPacket& recvPacket) InventoryResult msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } if (dest.size() == 1 && dest[0].pos == pItem->GetPos()) { - _player->SendEquipError(EQUIP_ERR_NONE, pItem, NULL); + _player->SendEquipError(EQUIP_ERR_NONE, pItem, nullptr); return; } @@ -851,7 +854,7 @@ void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket) InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } @@ -865,7 +868,7 @@ void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket) InventoryResult msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } @@ -878,7 +881,7 @@ void WorldSession::HandleSetAmmoOpcode(WorldPacket& recvData) { if (!_player->IsAlive()) { - _player->SendEquipError(EQUIP_ERR_YOU_ARE_DEAD, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_YOU_ARE_DEAD, nullptr, nullptr); return; } @@ -891,7 +894,7 @@ void WorldSession::HandleSetAmmoOpcode(WorldPacket& recvData) { if (!_player->GetItemCount(item)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -934,7 +937,7 @@ void WorldSession::HandleItemNameQueryOpcode(WorldPacket& recvData) { std::string Name = pName->name; LocaleConstant localeConstant = GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (ItemSetNameLocale const* isnl = sObjectMgr->GetItemSetNameLocale(itemid)) ObjectMgr::GetLocaleString(isnl->Name, localeConstant, Name); @@ -960,13 +963,13 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) Item* gift = _player->GetItemByPos(gift_bag, gift_slot); if (!gift) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr); return; } if (!(gift->GetTemplate()->Flags & ITEM_FLAG_IS_WRAPPER)) // cheating: non-wrapper wrapper { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr); return; } @@ -974,50 +977,50 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) if (!item) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr); return; } if (item == gift) // not possable with pacjket from real client { - _player->SendEquipError(EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, nullptr); return; } if (item->IsEquipped()) { - _player->SendEquipError(EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED, item, nullptr); return; } if (!item->GetGuidValue(ITEM_FIELD_GIFTCREATOR).IsEmpty()) // HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED); { - _player->SendEquipError(EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, nullptr); return; } if (item->IsBag()) { - _player->SendEquipError(EQUIP_ERR_BAGS_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_BAGS_CANT_BE_WRAPPED, item, nullptr); return; } if (item->IsSoulBound()) { - _player->SendEquipError(EQUIP_ERR_BOUND_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_BOUND_CANT_BE_WRAPPED, item, nullptr); return; } if (item->GetMaxStackCount() != 1) { - _player->SendEquipError(EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED, item, nullptr); return; } // maybe not correct check (it is better than nothing) if (item->GetTemplate()->MaxCount>0) { - _player->SendEquipError(EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED, item, nullptr); return; } @@ -1048,7 +1051,7 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) if (item->GetState() == ITEM_NEW) // save new item, to have alway for `character_gifts` record in `item_instance` { // after save it will be impossible to remove the item from the queue - item->RemoveFromUpdateQueueOf(_player); + RemoveItemFromUpdateQueueOf(item, _player); item->SaveToDB(trans); // item gave inventory record unchanged and can be save standalone } CharacterDatabase.CommitTransaction(trans); @@ -1089,11 +1092,11 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) Item* Gems[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) - Gems[i] = gem_guids[i] ? _player->GetItemByGuid(gem_guids[i]) : NULL; + Gems[i] = gem_guids[i] ? _player->GetItemByGuid(gem_guids[i]) : nullptr; 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]->GetTemplate()->GemProperties) : NULL; + GemProps[i] = (Gems[i]) ? sGemPropertiesStore.LookupEntry(Gems[i]->GetTemplate()->GemProperties) : nullptr; // Find first prismatic socket int32 firstPrismatic = 0; @@ -1154,7 +1157,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (iGemProto->ItemId == Gems[j]->GetEntry()) { - _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } @@ -1164,7 +1167,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (iGemProto->ItemId == enchantEntry->GemID) { - _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } @@ -1199,7 +1202,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) if (limit_newcount > 0 && uint32(limit_newcount) > limitEntry->maxCount) { - _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } @@ -1210,7 +1213,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (InventoryResult res = _player->CanEquipUniqueItem(Gems[i], slot, std::max(limit_newcount, 0))) { - _player->SendEquipError(res, itemTarget, NULL); + _player->SendEquipError(res, itemTarget, nullptr); return; } } diff --git a/src/server/game/Handlers/LFGHandler.cpp b/src/server/game/Handlers/LFGHandler.cpp index e3cbbe512d3..499d51f21ec 100644 --- a/src/server/game/Handlers/LFGHandler.cpp +++ b/src/server/game/Handlers/LFGHandler.cpp @@ -16,10 +16,12 @@ */ #include "LFGMgr.h" -#include "ObjectMgr.h" +#include "Log.h" #include "Group.h" -#include "Player.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" +#include "Player.h" #include "WorldPacket.h" #include "WorldSession.h" @@ -186,7 +188,7 @@ void WorldSession::HandleLfgPlayerLockInfoRequestOpcode(WorldPacket& /*recvData* { data << uint32(*it); // Dungeon Entry (id + type) lfg::LfgReward const* reward = sLFGMgr->GetRandomDungeonReward(*it, level); - Quest const* quest = NULL; + Quest const* quest = nullptr; bool done = false; if (reward) { @@ -244,7 +246,7 @@ void WorldSession::HandleLfgPartyLockInfoRequestOpcode(WorldPacket& /*recvData* // Get the locked dungeons of the other party members lfg::LfgLockPartyMap lockMap; - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* plrg = itr->GetSource(); if (!plrg) @@ -526,7 +528,7 @@ void WorldSession::SendLfgBootProposalUpdate(lfg::LfgPlayerBoot const& boot) lfg::LfgAnswer playerVote = boot.votes.find(guid)->second; uint8 votesNum = 0; uint8 agreeNum = 0; - uint32 secsleft = uint8((boot.cancelTime - time(NULL)) / 1000); + uint32 secsleft = uint8((boot.cancelTime - time(nullptr)) / 1000); for (lfg::LfgAnswerContainer::const_iterator it = boot.votes.begin(); it != boot.votes.end(); ++it) { if (it->second != lfg::LFG_ANSWER_PENDING) diff --git a/src/server/game/Handlers/LootHandler.cpp b/src/server/game/Handlers/LootHandler.cpp index 4a0013b71c1..949e858095d 100644 --- a/src/server/game/Handlers/LootHandler.cpp +++ b/src/server/game/Handlers/LootHandler.cpp @@ -16,26 +16,28 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" -#include "Log.h" #include "Corpse.h" #include "Creature.h" #include "GameObject.h" #include "Group.h" +#include "Item.h" +#include "Log.h" #include "LootItemStorage.h" #include "LootMgr.h" -#include "ObjectAccessor.h" +#include "Map.h" #include "Object.h" +#include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" -#include "WorldSession.h" void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: CMSG_AUTOSTORE_LOOT_ITEM"); Player* player = GetPlayer(); ObjectGuid lguid = player->GetLootGUID(); - Loot* loot = NULL; + Loot* loot = nullptr; uint8 lootSlot = 0; recvData >> lootSlot; @@ -106,7 +108,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) if (!guid) return; - Loot* loot = NULL; + Loot* loot = nullptr; bool shareMoney = true; switch (guid.GetHigh()) @@ -169,7 +171,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) Group* group = player->GetGroup(); std::vector playersNear; - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -189,7 +191,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) WorldPacket data(SMSG_LOOT_MONEY_NOTIFY, 4 + 1); data << uint32(goldPerPlayer); data << uint8(playersNear.size() <= 1); // Controls the text displayed in chat. 0 is "Your share is..." and 1 is "You loot..." - (*i)->GetSession()->SendPacket(&data); + (*i)->SendDirectMessage(&data); } } else @@ -371,7 +373,7 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) loot->roundRobinPlayer.Clear(); if (Group* group = player->GetGroup()) - group->SendLooter(creature, NULL); + group->SendLooter(creature, nullptr); } // force dynflag update to update looter and lootable info creature->ForceValuesUpdateAtIndex(UNIT_DYNAMIC_FLAGS); @@ -418,7 +420,7 @@ void WorldSession::HandleLootMasterGiveOpcode(WorldPacket& recvData) return; } - Loot* loot = NULL; + Loot* loot = nullptr; if (GetPlayer()->GetLootGUID().IsCreatureOrVehicle()) { @@ -462,12 +464,12 @@ void WorldSession::HandleLootMasterGiveOpcode(WorldPacket& recvData) else _player->SendLootError(lootguid, LOOT_ERROR_MASTER_OTHER); - target->SendEquipError(msg, NULL, NULL, item.itemid); + target->SendEquipError(msg, nullptr, nullptr, item.itemid); return; } // list of players allowed to receive this item in trade - AllowedLooterSet looters = item.GetAllowedLooters(); + GuidSet looters = item.GetAllowedLooters(); // now move item from loot to target inventory Item* newitem = target->StoreNewItem(dest, item.itemid, true, item.randomPropertyId, looters); diff --git a/src/server/game/Handlers/MailHandler.cpp b/src/server/game/Handlers/MailHandler.cpp index 1b186ae6c0a..fc283e1d3df 100644 --- a/src/server/game/Handlers/MailHandler.cpp +++ b/src/server/game/Handlers/MailHandler.cpp @@ -15,20 +15,21 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" -#include "Mail.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "Opcodes.h" +#include "AccountMgr.h" +#include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Item.h" +#include "Language.h" #include "Log.h" -#include "World.h" +#include "Mail.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" +#include "Opcodes.h" #include "Player.h" -#include "Language.h" -#include "DBCStores.h" -#include "Item.h" -#include "AccountMgr.h" -#include "CharacterCache.h" +#include "World.h" +#include "WorldPacket.h" bool WorldSession::CanOpenMailBox(ObjectGuid guid) { @@ -395,7 +396,7 @@ void WorldSession::HandleMailReturnToSender(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) { player->SendMailResult(mailId, MAIL_RETURNED_TO_SENDER, MAIL_ERR_INTERNAL_ERROR); return; @@ -461,7 +462,7 @@ void WorldSession::HandleMailTakeItem(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) { player->SendMailResult(mailId, MAIL_ITEM_TAKEN, MAIL_ERR_INTERNAL_ERROR); return; @@ -562,7 +563,7 @@ void WorldSession::HandleMailTakeMoney(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) { player->SendMailResult(mailId, MAIL_MONEY_TAKEN, MAIL_ERR_INTERNAL_ERROR); return; @@ -611,7 +612,7 @@ void WorldSession::HandleGetMailList(WorldPacket& recvData) WorldPacket data(SMSG_MAIL_LIST_RESULT, (200)); // guess size data << uint32(0); // real mail's count data << uint8(0); // mail's count - time_t cur_time = time(NULL); + time_t cur_time = time(nullptr); for (PlayerMails::iterator itr = player->GetMailBegin(); itr != player->GetMailEnd(); ++itr) { @@ -658,7 +659,7 @@ void WorldSession::HandleGetMailList(WorldPacket& recvData) data << uint32((*itr)->stationery); // stationery (Stationery.dbc) data << uint32((*itr)->money); // Gold data << uint32((*itr)->checked); // flags - data << float(float((*itr)->expire_time-time(NULL))/DAY); // Time + data << float(float((*itr)->expire_time-time(nullptr))/DAY); // Time data << uint32((*itr)->mailTemplateId); // mail template (MailTemplate.dbc) data << (*itr)->subject; // Subject string - once 00, when mail type = 3, max 256 data << (*itr)->body; // message? max 8000 @@ -722,7 +723,7 @@ void WorldSession::HandleMailCreateTextItem(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || (m->body.empty() && !m->mailTemplateId) || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL) || (m->checked & MAIL_CHECK_MASK_COPIED)) + if (!m || (m->body.empty() && !m->mailTemplateId) || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr) || (m->checked & MAIL_CHECK_MASK_COPIED)) { player->SendMailResult(mailId, MAIL_MADE_PERMANENT, MAIL_ERR_INTERNAL_ERROR); return; @@ -784,7 +785,7 @@ void WorldSession::HandleQueryNextMailTime(WorldPacket & /*recvData*/) data << uint32(0); // count uint32 count = 0; - time_t now = time(NULL); + time_t now = time(nullptr); std::set sentSenders; for (PlayerMails::iterator itr = _player->GetMailBegin(); itr != _player->GetMailEnd(); ++itr) { diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 2e18f843a8d..a632bf1979c 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -16,36 +16,42 @@ * with this program. If not, see . */ +#include "WorldSession.h" +#include "AccountMgr.h" +#include "Battlefield.h" +#include "BattlefieldMgr.h" +#include "Battleground.h" +#include "BattlegroundMgr.h" +#include "Chat.h" +#include "CinematicMgr.h" #include "Common.h" -#include "Language.h" +#include "Corpse.h" +#include "Creature.h" +#include "CreatureAI.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "Player.h" +#include "DBCStores.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "GameTime.h" #include "GossipDef.h" -#include "World.h" -#include "ObjectMgr.h" +#include "Group.h" #include "GuildMgr.h" -#include "WorldSession.h" -#include "Chat.h" -#include "zlib.h" -#include "ObjectAccessor.h" +#include "Language.h" +#include "Log.h" +#include "MapManager.h" #include "Object.h" -#include "Battleground.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" #include "OutdoorPvP.h" -#include "AccountMgr.h" -#include "DBCEnums.h" +#include "Player.h" #include "ScriptMgr.h" -#include "MapManager.h" -#include "GameObjectAI.h" -#include "Group.h" #include "Spell.h" -#include "BattlegroundMgr.h" -#include "Battlefield.h" -#include "BattlefieldMgr.h" +#include "SpellInfo.h" #include "WhoListStorage.h" +#include "World.h" +#include "WorldPacket.h" +#include void WorldSession::HandleRepopRequestOpcode(WorldPacket& recvData) { @@ -73,7 +79,7 @@ void WorldSession::HandleRepopRequestOpcode(WorldPacket& recvData) //this is spirit release confirm? GetPlayer()->RemoveGhoul(); - GetPlayer()->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + GetPlayer()->RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); GetPlayer()->BuildPlayerRepop(); GetPlayer()->RepopAtGraveyard(); } @@ -102,8 +108,8 @@ void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recvData) if (_player->PlayerTalkClass->GetGossipMenu().GetSenderGUID() != guid) return; - Creature* unit = NULL; - GameObject* go = NULL; + Creature* unit = nullptr; + GameObject* go = nullptr; if (guid.IsCreatureOrVehicle()) { unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_GOSSIP); @@ -397,7 +403,7 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket& /*recvData*/) GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } - LogoutRequest(time(NULL)); + LogoutRequest(time(nullptr)); } void WorldSession::HandlePlayerLogoutOpcode(WorldPacket& /*recvData*/) @@ -459,7 +465,7 @@ void WorldSession::HandleTogglePvP(WorldPacket& recvData) else { if (!GetPlayer()->pvpInfo.IsHostile && GetPlayer()->IsPvP()) - GetPlayer()->pvpInfo.EndTimer = time(NULL); // start toggle-off + GetPlayer()->pvpInfo.EndTimer = time(nullptr); // start toggle-off } //if (OutdoorPvP* pvp = _player->GetOutdoorPvP()) @@ -544,7 +550,7 @@ void WorldSession::HandleReclaimCorpseOpcode(WorldPacket& recvData) return; // prevent resurrect before 30-sec delay after body release not finished - if (time_t(corpse->GetGhostTime() + _player->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP)) > time_t(time(NULL))) + if (time_t(corpse->GetGhostTime() + _player->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP)) > time_t(time(nullptr))) return; if (!corpse->IsWithinDistInMap(_player, CORPSE_RECLAIM_RADIUS, true)) @@ -581,7 +587,7 @@ void WorldSession::HandleResurrectResponseOpcode(WorldPacket& recvData) GetPlayer()->ResurrectUsingRequestData(); } -void WorldSession::SendAreaTriggerMessage(const char* Text, ...) +void WorldSession::SendAreaTriggerMessage(char const* Text, ...) { va_list ap; char szStr [1024]; @@ -686,7 +692,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) WorldPacket data(SMSG_RAID_GROUP_ONLY, 4 + 4); data << uint32(0); data << uint32(2); // You must be in a raid group to enter this instance. - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); TC_LOG_DEBUG("maps", "MAP: Player '%s' must be in a raid group to enter instance map %d", player->GetName().c_str(), at->target_mapId); reviveAtTrigger = true; break; @@ -694,7 +700,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) case Map::CANNOT_ENTER_CORPSE_IN_DIFFERENT_INSTANCE: { WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); TC_LOG_DEBUG("maps", "MAP: Player '%s' does not have a corpse in instance map %d and cannot enter", player->GetName().c_str(), at->target_mapId); break; } @@ -1301,7 +1307,7 @@ void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recvData) { if (group->IsLeader(_player->GetGUID())) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupGuy = itr->GetSource(); if (!groupGuy) @@ -1359,7 +1365,7 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket& recvData) { if (group->IsLeader(_player->GetGUID())) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupGuy = itr->GetSource(); if (!groupGuy) @@ -1471,7 +1477,7 @@ void WorldSession::HandleWorldStateUITimerUpdate(WorldPacket& /*recvData*/) TC_LOG_DEBUG("network", "WORLD: CMSG_WORLD_STATE_UI_TIMER_UPDATE"); WorldPacket data(SMSG_WORLD_STATE_UI_TIMER_UPDATE, 4); - data << uint32(time(NULL)); + data << uint32(time(nullptr)); SendPacket(&data); } @@ -1583,30 +1589,25 @@ void WorldSession::HandleUpdateMissileTrajectory(WorldPacket& recvPacket) ObjectGuid guid; uint32 spellId; float elevation, speed; - float curX, curY, curZ; - float targetX, targetY, targetZ; + TaggedPosition firePos; + TaggedPosition impactPos; uint8 moveStop; recvPacket >> guid >> spellId >> elevation >> speed; - recvPacket >> curX >> curY >> curZ; - recvPacket >> targetX >> targetY >> targetZ; + recvPacket >> firePos; + recvPacket >> impactPos; recvPacket >> moveStop; Unit* caster = ObjectAccessor::GetUnit(*_player, guid); - Spell* spell = caster ? caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) : NULL; + Spell* spell = caster ? caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) : nullptr; if (!spell || spell->m_spellInfo->Id != spellId || !spell->m_targets.HasDst() || !spell->m_targets.HasSrc()) { recvPacket.rfinish(); return; } - Position pos = *spell->m_targets.GetSrcPos(); - pos.Relocate(curX, curY, curZ); - spell->m_targets.ModSrc(pos); - - pos = *spell->m_targets.GetDstPos(); - pos.Relocate(targetX, targetY, targetZ); - spell->m_targets.ModDst(pos); + spell->m_targets.ModSrc(firePos); + spell->m_targets.ModDst(impactPos); spell->m_targets.SetElevation(elevation); spell->m_targets.SetSpeed(speed); diff --git a/src/server/game/Handlers/MovementHandler.cpp b/src/server/game/Handlers/MovementHandler.cpp index 871031025e5..8b64e0e08bb 100644 --- a/src/server/game/Handlers/MovementHandler.cpp +++ b/src/server/game/Handlers/MovementHandler.cpp @@ -163,7 +163,7 @@ void WorldSession::HandleMoveWorldportAck() { if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(mEntry->MapID, diff)) { - uint32 timeleft = uint32(timeReset - time(NULL)); + uint32 timeleft = uint32(timeReset - time(nullptr)); GetPlayer()->SendInstanceResetWarning(mEntry->MapID, diff, timeleft, true); } } @@ -257,7 +257,7 @@ void WorldSession::HandleMovementOpcodes(WorldPacket& recvData) Unit* mover = _player->m_unitMovedByMe; - ASSERT(mover != NULL); // there must always be a mover + ASSERT(mover != nullptr); // there must always be a mover Player* plrMover = mover->ToPlayer(); diff --git a/src/server/game/Handlers/NPCHandler.cpp b/src/server/game/Handlers/NPCHandler.cpp index beca093a6a9..ddde13ae860 100644 --- a/src/server/game/Handlers/NPCHandler.cpp +++ b/src/server/game/Handlers/NPCHandler.cpp @@ -16,26 +16,29 @@ * with this program. If not, see . */ +#include "WorldSession.h" +#include "Battleground.h" +#include "BattlegroundMgr.h" #include "Common.h" -#include "Language.h" +#include "Creature.h" +#include "CreatureAI.h" #include "DatabaseEnv.h" -#include "QueryCallback.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Opcodes.h" +#include "DBCStores.h" +#include "GossipDef.h" +#include "Item.h" +#include "Language.h" #include "Log.h" +#include "Map.h" +#include "Opcodes.h" #include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Player.h" -#include "GossipDef.h" -#include "Creature.h" #include "Pet.h" +#include "Player.h" +#include "QueryCallback.h" #include "ReputationMgr.h" -#include "BattlegroundMgr.h" -#include "Battleground.h" #include "ScriptMgr.h" -#include "CreatureAI.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "WorldPacket.h" enum StableResultCode { @@ -373,11 +376,11 @@ void WorldSession::SendSpiritResurrect() _player->DurabilityLossAll(0.25f, true); // get corpse nearest graveyard - WorldSafeLocsEntry const* corpseGrave = NULL; + WorldSafeLocsEntry const* corpseGrave = nullptr; WorldLocation corpseLocation = _player->GetCorpseLocation(); if (_player->HasCorpse()) { - corpseGrave = sObjectMgr->GetClosestGraveYard(corpseLocation.GetPositionX(), corpseLocation.GetPositionY(), + corpseGrave = sObjectMgr->GetClosestGraveyard(corpseLocation.GetPositionX(), corpseLocation.GetPositionY(), corpseLocation.GetPositionZ(), corpseLocation.GetMapId(), _player->GetTeam()); } @@ -387,7 +390,7 @@ void WorldSession::SendSpiritResurrect() // teleport to nearest from corpse graveyard, if different from nearest to player ghost if (corpseGrave) { - WorldSafeLocsEntry const* ghostGrave = sObjectMgr->GetClosestGraveYard( + WorldSafeLocsEntry const* ghostGrave = sObjectMgr->GetClosestGraveyard( _player->GetPositionX(), _player->GetPositionY(), _player->GetPositionZ(), _player->GetMapId(), _player->GetTeam()); if (corpseGrave != ghostGrave) @@ -675,7 +678,7 @@ void WorldSession::HandleUnstablePetCallback(uint32 petId, PreparedQueryResult r if (!newPet->LoadPetFromDB(_player, petEntry, petId)) { delete newPet; - newPet = NULL; + newPet = nullptr; SendStableResult(STABLE_ERR_STABLE); return; } diff --git a/src/server/game/Handlers/NPCHandler.h b/src/server/game/Handlers/NPCHandler.h index fb7006b1712..61db8bfb04c 100644 --- a/src/server/game/Handlers/NPCHandler.h +++ b/src/server/game/Handlers/NPCHandler.h @@ -46,15 +46,15 @@ struct GossipText struct PageTextLocale { - StringVector Text; + std::vector Text; }; struct NpcTextLocale { NpcTextLocale() { } - StringVector Text_0[MAX_GOSSIP_TEXT_OPTIONS]; - StringVector Text_1[MAX_GOSSIP_TEXT_OPTIONS]; + std::vector Text_0[MAX_GOSSIP_TEXT_OPTIONS]; + std::vector Text_1[MAX_GOSSIP_TEXT_OPTIONS]; }; #endif diff --git a/src/server/game/Handlers/PetHandler.cpp b/src/server/game/Handlers/PetHandler.cpp index 53dc69ffd94..296e444f939 100644 --- a/src/server/game/Handlers/PetHandler.cpp +++ b/src/server/game/Handlers/PetHandler.cpp @@ -16,24 +16,26 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" +#include "Common.h" +#include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "Group.h" #include "Log.h" -#include "Opcodes.h" -#include "Spell.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" -#include "CreatureAI.h" -#include "PetAI.h" -#include "Util.h" +#include "ObjectMgr.h" +#include "Opcodes.h" #include "Pet.h" -#include "World.h" -#include "Group.h" +#include "PetAI.h" +#include "Player.h" +#include "Spell.h" #include "SpellHistory.h" #include "SpellInfo.h" -#include "Player.h" +#include "SpellMgr.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleDismissCritter(WorldPacket& recvData) { @@ -88,7 +90,7 @@ void WorldSession::HandlePetAction(WorldPacket& recvData) if (!pet->IsAlive()) { - SpellInfo const* spell = (flag == ACT_ENABLED || flag == ACT_PASSIVE) ? sSpellMgr->GetSpellInfo(spellid) : NULL; + SpellInfo const* spell = (flag == ACT_ENABLED || flag == ACT_PASSIVE) ? sSpellMgr->GetSpellInfo(spellid) : nullptr; if (!spell) return; if (!spell->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_DEAD)) @@ -288,7 +290,7 @@ void WorldSession::HandlePetActionHelper(Unit* pet, ObjectGuid guid1, uint32 spe case ACT_PASSIVE: // 0x01 case ACT_ENABLED: // 0xC1 spell { - Unit* unit_target = NULL; + Unit* unit_target = nullptr; if (guid2) unit_target = ObjectAccessor::GetUnit(*_player, guid2); @@ -429,7 +431,7 @@ void WorldSession::SendPetNameQuery(ObjectGuid petguid, uint32 petnumber) data << uint8(0); data << uint32(0); data << uint8(0); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -447,7 +449,7 @@ void WorldSession::SendPetNameQuery(ObjectGuid petguid, uint32 petnumber) else data << uint8(0); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); } bool WorldSession::CheckStableMaster(ObjectGuid guid) @@ -614,13 +616,13 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) PetNameInvalidReason res = ObjectMgr::CheckPetName(name, GetSessionDbcLocale()); if (res != PET_NAME_SUCCESS) { - SendPetNameInvalid(res, name, NULL); + SendPetNameInvalid(res, name, nullptr); return; } if (sObjectMgr->IsReservedName(name)) { - SendPetNameInvalid(PET_NAME_RESERVED, name, NULL); + SendPetNameInvalid(PET_NAME_RESERVED, name, nullptr); return; } @@ -673,7 +675,7 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) CharacterDatabase.CommitTransaction(trans); - pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped + pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped } void WorldSession::HandlePetAbandon(WorldPacket& recvData) @@ -713,7 +715,7 @@ void WorldSession::HandlePetSpellAutocastOpcode(WorldPacket& recvPacket) if (guid.IsPlayer()) return; - Creature* pet=ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); + Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); if (!pet || (pet != _player->GetGuardianPet() && pet != _player->GetCharm())) { @@ -793,7 +795,7 @@ void WorldSession::HandlePetCastSpellOpcode(WorldPacket& recvPacket) spell->m_cast_count = castCount; // probably pending spell cast spell->m_targets = targets; - SpellCastResult result = spell->CheckPetCast(NULL); + SpellCastResult result = spell->CheckPetCast(nullptr); if (result == SPELL_CAST_OK) { diff --git a/src/server/game/Handlers/PetitionsHandler.cpp b/src/server/game/Handlers/PetitionsHandler.cpp index 809237b72fd..4e47f260fff 100644 --- a/src/server/game/Handlers/PetitionsHandler.cpp +++ b/src/server/game/Handlers/PetitionsHandler.cpp @@ -16,20 +16,25 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Language.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" -#include "ObjectMgr.h" +#include "ArenaTeam.h" #include "ArenaTeamMgr.h" +#include "CharacterCache.h" +#include "Common.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "Guild.h" #include "GuildMgr.h" +#include "Item.h" +#include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" -#include "Guild.h" -#include "ArenaTeam.h" -#include "CharacterCache.h" +#include "Player.h" #include "PetitionMgr.h" +#include "WorldPacket.h" +#include "World.h" #define CHARTER_DISPLAY_ID 16161 @@ -170,7 +175,7 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(charterid); if (!pProto) { - _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, charterid, 0); + _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, charterid, 0); return; } @@ -184,7 +189,7 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, NULL, NULL, charterid); + _player->SendEquipError(msg, nullptr, nullptr, charterid); return; } @@ -252,7 +257,7 @@ void WorldSession::SendPetitionSigns(Petition const* petition, Player* sendTo) data << uint32(0); // there 0 ... } - sendTo->GetSession()->SendPacket(&data); + sendTo->SendDirectMessage(&data); } void WorldSession::HandlePetitionQueryOpcode(WorldPacket& recvData) @@ -467,7 +472,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recvData) // update for owner if online if (Player* owner = ObjectAccessor::FindConnectedPlayer(ownerGuid)) - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); return; } @@ -484,7 +489,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recvData) // update for owner if online if (Player* owner = ObjectAccessor::FindConnectedPlayer(ownerGuid)) - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); } void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recvData) @@ -504,7 +509,7 @@ void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recvData) { WorldPacket data(MSG_PETITION_DECLINE, 8); data << uint64(_player->GetGUID()); - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); } } @@ -622,7 +627,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recvData) { data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << (uint32)PETITION_TURN_ALREADY_IN_GUILD; - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } diff --git a/src/server/game/Handlers/QueryHandler.cpp b/src/server/game/Handlers/QueryHandler.cpp index aec8553cb53..a2566c9a7f0 100644 --- a/src/server/game/Handlers/QueryHandler.cpp +++ b/src/server/game/Handlers/QueryHandler.cpp @@ -16,20 +16,20 @@ * with this program. If not, see . */ +#include "WorldSession.h" +#include "CharacterCache.h" #include "Common.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" +#include "DBCStores.h" #include "Log.h" -#include "World.h" +#include "MapManager.h" +#include "NPCHandler.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" +#include "QueryPackets.h" #include "UpdateMask.h" -#include "NPCHandler.h" -#include "MapManager.h" -#include "CharacterCache.h" - -#include "Packets/QueryPackets.h" +#include "World.h" void WorldSession::SendNameQueryOpcode(ObjectGuid guid) { @@ -52,7 +52,7 @@ void WorldSession::SendNameQueryOpcode(ObjectGuid guid) data << uint8(nameData->Sex); data << uint8(nameData->Class); - if (DeclinedName const* names = (player ? player->GetDeclinedNames() : NULL)) + if (DeclinedName const* names = (player ? player->GetDeclinedNames() : nullptr)) { data << uint8(1); // Name is declined for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i) @@ -83,8 +83,8 @@ void WorldSession::HandleQueryTimeOpcode(WorldPacket & /*recvData*/) void WorldSession::SendQueryTimeResponse() { WorldPacket data(SMSG_QUERY_TIME_RESPONSE, 4+4); - data << uint32(time(NULL)); - data << uint32(sWorld->GetNextDailyQuestsResetTime() - time(NULL)); + data << uint32(time(nullptr)); + data << uint32(sWorld->GetNextDailyQuestsResetTime() - time(nullptr)); SendPacket(&data); } @@ -300,7 +300,7 @@ void WorldSession::HandlePageTextQueryOpcode(WorldPacket& recvData) std::string Text = pageText->Text; LocaleConstant localeConstant = GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (PageTextLocale const* pageTextLocale = sObjectMgr->GetPageTextLocale(pageID)) ObjectMgr::GetLocaleString(pageTextLocale->Text, localeConstant, Text); diff --git a/src/server/game/Handlers/QuestHandler.cpp b/src/server/game/Handlers/QuestHandler.cpp index 1cff4d27279..f95fb01ed36 100644 --- a/src/server/game/Handlers/QuestHandler.cpp +++ b/src/server/game/Handlers/QuestHandler.cpp @@ -16,22 +16,25 @@ * with this program. If not, see . */ +#include "WorldSession.h" +#include "Battleground.h" #include "Common.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GossipDef.h" +#include "Group.h" #include "Log.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "World.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "GossipDef.h" #include "QuestDef.h" -#include "ObjectAccessor.h" -#include "Group.h" -#include "Battleground.h" +#include "QuestPackets.h" #include "ScriptMgr.h" -#include "GameObjectAI.h" - -#include "Packets/QuestPackets.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recvData) { @@ -183,7 +186,7 @@ void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvData) { if (Group* group = _player->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); @@ -253,9 +256,6 @@ void WorldSession::HandleQuestgiverQueryQuestOpcode(WorldPacket& recvData) void WorldSession::HandleQuestQueryOpcode(WorldPackets::Quest::QueryQuestInfo& query) { - if (!_player) - return; - TC_LOG_DEBUG("network", "WORLD: Received CMSG_QUEST_QUERY quest = %u", query.QuestID); if (Quest const* quest = sObjectMgr->GetQuestTemplate(query.QuestID)) @@ -474,7 +474,7 @@ void WorldSession::HandleQuestConfirmAccept(WorldPacket& recvData) if (_player->CanAddQuest(quest, true)) { - _player->AddQuestAndCheckCompletion(quest, NULL); // NULL, this prevent DB script from duplicate running + _player->AddQuestAndCheckCompletion(quest, nullptr); // NULL, this prevent DB script from duplicate running if (quest->GetSrcSpell() > 0) _player->CastSpell(_player, quest->GetSrcSpell(), true); @@ -559,7 +559,7 @@ void WorldSession::HandlePushQuestToParty(WorldPacket& recvPacket) return; } - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* receiver = itr->GetSource(); @@ -653,7 +653,7 @@ void WorldSession::HandleQueryQuestsCompleted(WorldPacket & /*recvData*/) WorldPacket data(SMSG_QUERY_QUESTS_COMPLETED_RESPONSE, 4 + 4 * rew_count); data << uint32(rew_count); - const RewardedQuestSet &rewQuests = _player->getRewardedQuests(); + RewardedQuestSet const& rewQuests = _player->getRewardedQuests(); for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) data << uint32(*itr); diff --git a/src/server/game/Handlers/ReferAFriendHandler.cpp b/src/server/game/Handlers/ReferAFriendHandler.cpp index a10744929dd..b415f2c75c1 100644 --- a/src/server/game/Handlers/ReferAFriendHandler.cpp +++ b/src/server/game/Handlers/ReferAFriendHandler.cpp @@ -16,9 +16,10 @@ */ #include "WorldSession.h" -#include "Player.h" -#include "ObjectMgr.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "World.h" void WorldSession::HandleGrantLevel(WorldPacket& recvData) { @@ -60,7 +61,7 @@ void WorldSession::HandleGrantLevel(WorldPacket& recvData) WorldPacket data2(SMSG_PROPOSE_LEVEL_GRANT, 8); data2 << _player->GetPackGUID(); - target->GetSession()->SendPacket(&data2); + target->SendDirectMessage(&data2); } void WorldSession::HandleAcceptGrantLevel(WorldPacket& recvData) diff --git a/src/server/game/Handlers/SkillHandler.cpp b/src/server/game/Handlers/SkillHandler.cpp index e16b19bbf51..ecfb793cd06 100644 --- a/src/server/game/Handlers/SkillHandler.cpp +++ b/src/server/game/Handlers/SkillHandler.cpp @@ -16,13 +16,14 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" +#include "DBCStores.h" #include "Log.h" #include "ObjectAccessor.h" -#include "Player.h" #include "Pet.h" +#include "Player.h" #include "WorldPacket.h" -#include "WorldSession.h" void WorldSession::HandleLearnTalentOpcode(WorldPacket& recvData) { diff --git a/src/server/game/Handlers/SocialHandler.cpp b/src/server/game/Handlers/SocialHandler.cpp index 752ac0dace5..d1c1233c188 100644 --- a/src/server/game/Handlers/SocialHandler.cpp +++ b/src/server/game/Handlers/SocialHandler.cpp @@ -15,12 +15,17 @@ * with this program. If not, see . */ -#include "CharacterCache.h" #include "WorldSession.h" +#include "AccountMgr.h" +#include "CharacterCache.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" -#include "QueryCallback.h" +#include "RBAC.h" +#include "Realm.h" #include "SocialMgr.h" -#include "ObjectMgr.h" +#include "World.h" void WorldSession::HandleContactListOpcode(WorldPacket& recvData) { diff --git a/src/server/game/Handlers/SpellHandler.cpp b/src/server/game/Handlers/SpellHandler.cpp index bea6cb7bbe5..e5336d4af21 100644 --- a/src/server/game/Handlers/SpellHandler.cpp +++ b/src/server/game/Handlers/SpellHandler.cpp @@ -16,22 +16,26 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" +#include "Config.h" +#include "DatabaseEnv.h" +#include "Log.h" #include "DBCStores.h" -#include "WorldPacket.h" -#include "WorldSession.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "Item.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Log.h" #include "Opcodes.h" -#include "Spell.h" -#include "Totem.h" +#include "Player.h" #include "ScriptMgr.h" -#include "GameObjectAI.h" +#include "Spell.h" #include "SpellAuraEffects.h" -#include "Player.h" -#include "Config.h" -#include "QueryCallback.h" +#include "SpellMgr.h" +#include "Totem.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlags, SpellCastTargets& targets) { @@ -75,20 +79,20 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) if (glyphIndex >= MAX_GLYPH_SLOT_INDEX) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } Item* pItem = pUser->GetUseableItemByPos(bagIndex, slot); if (!pItem) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (pItem->GetGUID() != itemGUID) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -97,35 +101,35 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) ItemTemplate const* proto = pItem->GetTemplate(); if (!proto) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, nullptr); return; } // some item classes can be used only in equipped state if (proto->InventoryType != INVTYPE_NON_EQUIP && !pItem->IsEquipped()) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, nullptr); return; } InventoryResult msg = pUser->CanUseItem(pItem); if (msg != EQUIP_ERR_OK) { - pUser->SendEquipError(msg, pItem, NULL); + pUser->SendEquipError(msg, pItem, nullptr); return; } // only allow conjured consumable, bandage, poisons (all should have the 2^21 item flag set in DB) if (proto->Class == ITEM_CLASS_CONSUMABLE && !(proto->Flags & ITEM_FLAG_IGNORE_DEFAULT_ARENA_RESTRICTIONS) && pUser->InArena()) { - pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, nullptr); return; } // don't allow items banned in arena if ((proto->Flags & ITEM_FLAG_NOT_USEABLE_IN_ARENA) && pUser->InArena()) { - pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, nullptr); return; } @@ -137,7 +141,7 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) { if (!spellInfo->CanBeUsedInCombat()) { - pUser->SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, pItem, nullptr); return; } } @@ -205,7 +209,7 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) // Verify that the bag is an actual bag or wrapped item that can be used "normally" if (!(proto->Flags & ITEM_FLAG_HAS_LOOT) && !item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) { - player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); + player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, nullptr); TC_LOG_ERROR("entities.player.cheat", "Possible hacking attempt: Player %s [guid: %u] tried to open item [guid: %u, entry: %u] which is not openable!", player->GetName().c_str(), player->GetGUID().GetCounter(), item->GetGUID().GetCounter(), proto->ItemId); return; @@ -485,7 +489,7 @@ void WorldSession::HandlePetCancelAuraOpcode(WorldPacket& recvPacket) return; } - Creature* pet=ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); + Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); if (!pet) { @@ -546,8 +550,7 @@ void WorldSession::HandleTotemDestroyed(WorldPacket& recvPacket) if (!_player->m_SummonSlot[slotId]) return; - Creature* totem = GetPlayer()->GetMap()->GetCreature(_player->m_SummonSlot[slotId]); - + Creature* totem = ObjectAccessor::GetCreature(*_player, _player->m_SummonSlot[slotId]); if (totem && totem->IsTotem()) totem->ToTotem()->UnSummon(); } diff --git a/src/server/game/Handlers/TaxiHandler.cpp b/src/server/game/Handlers/TaxiHandler.cpp index de1a3748b6c..3912707ea25 100644 --- a/src/server/game/Handlers/TaxiHandler.cpp +++ b/src/server/game/Handlers/TaxiHandler.cpp @@ -16,15 +16,16 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Opcodes.h" +#include "DBCStores.h" #include "Log.h" #include "ObjectMgr.h" +#include "Opcodes.h" #include "Player.h" #include "WaypointMovementGenerator.h" +#include "WorldPacket.h" void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvData) { @@ -39,10 +40,10 @@ void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvData) void WorldSession::SendTaxiStatus(ObjectGuid guid) { // cheating checks - Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); + Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_FLIGHTMASTER); if (!unit) { - TC_LOG_DEBUG("network", "WorldSession::SendTaxiStatus - %s not found.", guid.ToString().c_str()); + TC_LOG_DEBUG("network", "WorldSession::SendTaxiStatus - %s not found or you can't interact with him.", guid.ToString().c_str()); return; } diff --git a/src/server/game/Handlers/TicketHandler.cpp b/src/server/game/Handlers/TicketHandler.cpp index ad1114e10bb..6510875ed7a 100644 --- a/src/server/game/Handlers/TicketHandler.cpp +++ b/src/server/game/Handlers/TicketHandler.cpp @@ -16,16 +16,20 @@ * with this program. If not, see . */ -#include "zlib.h" +#include "WorldSession.h" #include "Common.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "Log.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "Random.h" #include "TicketMgr.h" #include "Util.h" +#include "World.h" #include "WorldPacket.h" -#include "WorldSession.h" +#include void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recvData) { @@ -126,7 +130,7 @@ void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket& recvData) GMTicketResponse response = GMTICKET_RESPONSE_UPDATE_ERROR; if (GmTicket* ticket = sTicketMgr->GetTicketByPlayer(GetPlayer()->GetGUID())) { - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetMessage(message); ticket->SaveToDB(trans); @@ -151,7 +155,7 @@ void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket & /*recvData*/) sWorld->SendGMText(LANG_COMMAND_TICKETPLAYERABANDON, GetPlayer()->GetName().c_str(), ticket->GetId()); sTicketMgr->CloseTicket(ticket->GetId(), GetPlayer()->GetGUID()); - sTicketMgr->SendTicket(this, NULL); + sTicketMgr->SendTicket(this, nullptr); } } @@ -167,7 +171,7 @@ void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket & /*recvData*/) sTicketMgr->SendTicket(this, ticket); } else - sTicketMgr->SendTicket(this, NULL); + sTicketMgr->SendTicket(this, nullptr); } void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket & /*recvData*/) @@ -247,7 +251,7 @@ void WorldSession::HandleReportLag(WorldPacket& recvData) stmt->setFloat (4, y); stmt->setFloat (5, z); stmt->setUInt32(6, GetLatency()); - stmt->setUInt32(7, time(NULL)); + stmt->setUInt32(7, time(nullptr)); CharacterDatabase.Execute(stmt); } @@ -257,7 +261,7 @@ void WorldSession::HandleGMResponseResolve(WorldPacket& /*recvPacket*/) if (GmTicket* ticket = sTicketMgr->GetTicketByPlayer(GetPlayer()->GetGUID())) { uint8 getSurvey = 0; - if (float(rand_chance()) < sWorld->getFloatConfig(CONFIG_CHANCE_OF_GM_SURVEY)) + if (roll_chance_f(sWorld->getFloatConfig(CONFIG_CHANCE_OF_GM_SURVEY))) getSurvey = 1; WorldPacket data(SMSG_GMRESPONSE_STATUS_UPDATE, 4); @@ -269,6 +273,6 @@ void WorldSession::HandleGMResponseResolve(WorldPacket& /*recvPacket*/) SendPacket(&data2); sTicketMgr->CloseTicket(ticket->GetId(), GetPlayer()->GetGUID()); - sTicketMgr->SendTicket(this, NULL); + sTicketMgr->SendTicket(this, nullptr); } } diff --git a/src/server/game/Handlers/TradeHandler.cpp b/src/server/game/Handlers/TradeHandler.cpp index dc992ebb537..3490e6da98d 100644 --- a/src/server/game/Handlers/TradeHandler.cpp +++ b/src/server/game/Handlers/TradeHandler.cpp @@ -16,19 +16,21 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" -#include "ObjectAccessor.h" +#include "AccountMgr.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "Item.h" +#include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "Item.h" #include "Spell.h" +#include "SpellMgr.h" #include "SocialMgr.h" -#include "Language.h" -#include "AccountMgr.h" #include "TradeData.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::SendTradeStatus(TradeStatusInfo const& info) { @@ -132,8 +134,8 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[]) { ItemPosCountVec traderDst; ItemPosCountVec playerDst; - bool traderCanTrade = (myItems[i] == NULL || trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, myItems[i], false) == EQUIP_ERR_OK); - bool playerCanTrade = (hisItems[i] == NULL || _player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false) == EQUIP_ERR_OK); + bool traderCanTrade = (myItems[i] == nullptr || trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, myItems[i], false) == EQUIP_ERR_OK); + bool playerCanTrade = (hisItems[i] == nullptr || _player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false) == EQUIP_ERR_OK); if (traderCanTrade && playerCanTrade) { // Ok, if trade item exists and can be stored @@ -216,7 +218,7 @@ static void setAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade, Item* *m if (Item* item = myTrade->GetItem(TradeSlots(i))) { TC_LOG_DEBUG("network", "player trade item %u bag: %u slot: %u", item->GetGUID().GetCounter(), item->GetBagSlot(), item->GetSlot()); - //Can return NULL + //Can return nullptr myItems[i] = item; myItems[i]->SetInTrade(); } @@ -260,8 +262,8 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) if (!his_trade) return; - Item* myItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL }; - Item* hisItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL }; + Item* myItems[TRADE_SLOT_TRADED_COUNT] = { }; + Item* hisItems[TRADE_SLOT_TRADED_COUNT] = { }; // set before checks for propertly undo at problems (it already set in to client) my_trade->SetAccepted(true); @@ -355,10 +357,10 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) { setAcceptTradeMode(my_trade, his_trade, myItems, hisItems); - Spell* my_spell = NULL; + Spell* my_spell = nullptr; SpellCastTargets my_targets; - Spell* his_spell = NULL; + Spell* his_spell = nullptr; SpellCastTargets his_targets; // not accept if spell can't be cast now (cheating) @@ -527,9 +529,9 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) // cleanup clearAcceptTradeMode(my_trade, his_trade); delete _player->m_trade; - _player->m_trade = NULL; + _player->m_trade = nullptr; delete trader->m_trade; - trader->m_trade = NULL; + trader->m_trade = nullptr; // desynchronized with the other saves here (SaveInventoryAndGoldToDB() not have own transaction guards) SQLTransaction trans = CharacterDatabase.BeginTransaction(); @@ -791,5 +793,5 @@ void WorldSession::HandleClearTradeItemOpcode(WorldPacket& recvPacket) if (tradeSlot >= TRADE_SLOT_COUNT) return; - my_trade->SetItem(TradeSlots(tradeSlot), NULL); + my_trade->SetItem(TradeSlots(tradeSlot), nullptr); } diff --git a/src/server/game/Handlers/VehicleHandler.cpp b/src/server/game/Handlers/VehicleHandler.cpp index 17af33cb270..8e80fbe2063 100644 --- a/src/server/game/Handlers/VehicleHandler.cpp +++ b/src/server/game/Handlers/VehicleHandler.cpp @@ -15,12 +15,14 @@ * with this program. If not, see . */ -#include "WorldPacket.h" #include "WorldSession.h" -#include "Vehicle.h" -#include "Player.h" +#include "DBCStructure.h" #include "Log.h" +#include "Map.h" #include "ObjectAccessor.h" +#include "Player.h" +#include "Vehicle.h" +#include "WorldPacket.h" void WorldSession::HandleDismissControlledVehicle(WorldPacket &recvData) { diff --git a/src/server/game/Handlers/VoiceChatHandler.cpp b/src/server/game/Handlers/VoiceChatHandler.cpp index 25724c80f40..e67124b0316 100644 --- a/src/server/game/Handlers/VoiceChatHandler.cpp +++ b/src/server/game/Handlers/VoiceChatHandler.cpp @@ -17,6 +17,7 @@ */ #include "Common.h" +#include "Log.h" #include "WorldPacket.h" #include "WorldSession.h" diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp index bce01828896..a4b53c3ab78 100644 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ b/src/server/game/Instances/InstanceSaveMgr.cpp @@ -16,21 +16,23 @@ * with this program. If not, see . */ +#include "InstanceSaveMgr.h" #include "Common.h" -#include "Player.h" +#include "Config.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiers.h" -#include "Log.h" #include "GridStates.h" +#include "Group.h" +#include "InstanceScript.h" +#include "Log.h" #include "Map.h" -#include "MapManager.h" #include "MapInstanced.h" -#include "InstanceSaveMgr.h" -#include "Timer.h" -#include "Config.h" +#include "MapManager.h" #include "ObjectMgr.h" +#include "Player.h" +#include "Timer.h" #include "World.h" -#include "Group.h" -#include "InstanceScript.h" uint16 InstanceSaveManager::ResetTimeDelay[] = {3600, 900, 300, 60}; @@ -76,23 +78,23 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance if (InstanceSave* old_save = GetInstanceSave(instanceId)) return old_save; - const MapEntry* entry = sMapStore.LookupEntry(mapId); + MapEntry const* entry = sMapStore.LookupEntry(mapId); if (!entry) { TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: wrong mapid = %d, instanceid = %d!", mapId, instanceId); - return NULL; + return nullptr; } if (instanceId == 0) { TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, wrong instanceid = %d!", mapId, instanceId); - return NULL; + return nullptr; } if (difficulty >= (entry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY)) { TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d, wrong dificalty %u!", mapId, instanceId, difficulty); - return NULL; + return nullptr; } if (!resetTime) @@ -103,7 +105,7 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance resetTime = GetResetTimeFor(mapId, difficulty); else { - resetTime = time(NULL) + 2 * HOUR; + resetTime = time(nullptr) + 2 * HOUR; // normally this will be removed soon after in InstanceMap::Add, prevent error ScheduleReset(true, resetTime, InstResetEvent(0, mapId, difficulty, instanceId)); } @@ -122,7 +124,7 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance InstanceSave* InstanceSaveManager::GetInstanceSave(uint32 InstanceId) { InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId); - return itr != m_instanceSaveById.end() ? itr->second : NULL; + return itr != m_instanceSaveById.end() ? itr->second : nullptr; } void InstanceSaveManager::DeleteInstanceFromDB(uint32 instanceid) @@ -219,7 +221,7 @@ void InstanceSave::SaveToDB() time_t InstanceSave::GetResetTimeForDB() { // only save the reset time for normal instances - const MapEntry* entry = sMapStore.LookupEntry(GetMapId()); + MapEntry const* entry = sMapStore.LookupEntry(GetMapId()); if (!entry || entry->map_type == MAP_RAID || GetDifficulty() == DUNGEON_DIFFICULTY_HEROIC) return 0; else @@ -298,7 +300,7 @@ void InstanceSaveManager::LoadInstances() void InstanceSaveManager::LoadResetTimes() { - time_t now = time(NULL); + time_t now = time(nullptr); time_t today = (now / DAY) * DAY; // NOTE: Use DirectPExecute for tables that will be queried later @@ -457,6 +459,13 @@ time_t InstanceSaveManager::GetSubsequentResetTime(uint32 mapid, Difficulty diff return ((resetTime + MINUTE) / DAY * DAY) + period + diff; } +void InstanceSaveManager::SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) +{ + ResetTimeByMapDifficultyMap::iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); + ASSERT(itr != m_resetTimeByMapDifficulty.end()); + itr->second = t; +} + void InstanceSaveManager::ScheduleReset(bool add, time_t time, InstResetEvent event) { if (!add) @@ -507,7 +516,7 @@ void InstanceSaveManager::ForceGlobalReset(uint32 mapId, Difficulty difficulty) void InstanceSaveManager::Update() { - time_t now = time(NULL); + time_t now = time(nullptr); time_t t; while (!m_resetTimeQueue.empty()) @@ -624,7 +633,7 @@ void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, b return; TC_LOG_DEBUG("misc", "InstanceSaveManager::ResetOrWarnAll: Processing map %s (%u) on difficulty %u (warn? %u)", mapEntry->name[0], mapid, uint8(difficulty), warn); - time_t now = time(NULL); + time_t now = time(nullptr); if (!warn) { diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index 6d3728e4fc5..81c10ac83cc 100644 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -25,7 +25,7 @@ #include #include "Define.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "DBCEnums.h" #include "ObjectDefines.h" @@ -174,7 +174,7 @@ class TC_GAME_API InstanceSaveManager InstResetEvent() : type(0), difficulty(DUNGEON_DIFFICULTY_NORMAL), mapid(0), instanceId(0) { } InstResetEvent(uint8 t, uint32 _mapid, Difficulty d, uint16 _instanceid) : type(t), difficulty(d), mapid(_mapid), instanceId(_instanceid) { } - bool operator == (const InstResetEvent& e) const { return e.instanceId == instanceId; } + bool operator==(InstResetEvent const& e) const { return e.instanceId == instanceId; } }; typedef std::multimap ResetTimeQueue; @@ -195,12 +195,7 @@ class TC_GAME_API InstanceSaveManager } // Use this only when updating existing reset times - void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) - { - ResetTimeByMapDifficultyMap::iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); - ASSERT(itr != m_resetTimeByMapDifficulty.end()); - itr->second = t; - } + void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t); ResetTimeByMapDifficultyMap const& GetResetTimeMap() const { diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index c66e1b3d5e8..3fa7eb52d6e 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -16,21 +16,29 @@ * with this program. If not, see . */ +#include "InstanceScript.h" +#include "AreaBoundary.h" #include "Creature.h" #include "CreatureAI.h" +#include "CreatureAIImpl.h" #include "DatabaseEnv.h" +#include "DBCStructure.h" #include "GameObject.h" #include "Group.h" -#include "InstanceScript.h" #include "LFGMgr.h" #include "Log.h" #include "Map.h" -#include "Player.h" -#include "Pet.h" -#include "WorldSession.h" +#include "ObjectMgr.h" #include "Opcodes.h" -#include "ScriptReloadMgr.h" +#include "Pet.h" +#include "Player.h" +#include "RBAC.h" #include "ScriptMgr.h" +#include "ScriptReloadMgr.h" +#include "World.h" +#include "WorldSession.h" +#include +#include BossBoundaryData::~BossBoundaryData() { @@ -109,6 +117,16 @@ ObjectGuid InstanceScript::GetGuidData(uint32 type) const return GetObjectGuid(type); } +Creature* InstanceScript::GetCreature(uint32 type) +{ + return instance->GetCreature(GetObjectGuid(type)); +} + +GameObject* InstanceScript::GetGameObject(uint32 type) +{ + return instance->GetGameObject(GetObjectGuid(type)); +} + void InstanceScript::SetHeaders(std::string const& dataHeaders) { for (char header : dataHeaders) @@ -116,14 +134,14 @@ void InstanceScript::SetHeaders(std::string const& dataHeaders) headers.push_back(header); } -void InstanceScript::LoadBossBoundaries(const BossBoundaryData& data) +void InstanceScript::LoadBossBoundaries(BossBoundaryData const& data) { for (BossBoundaryEntry const& entry : data) if (entry.BossId < bosses.size()) bosses[entry.BossId].boundary.push_back(entry.Boundary); } -void InstanceScript::LoadMinionData(const MinionData* data) +void InstanceScript::LoadMinionData(MinionData const* data) { while (data->entry) { @@ -135,7 +153,7 @@ void InstanceScript::LoadMinionData(const MinionData* data) TC_LOG_DEBUG("scripts", "InstanceScript::LoadMinionData: " UI64FMTD " minions loaded.", uint64(minions.size())); } -void InstanceScript::LoadDoorData(const DoorData* data) +void InstanceScript::LoadDoorData(DoorData const* data) { while (data->entry) { @@ -518,9 +536,9 @@ void InstanceScript::DoSendNotifyToInstance(char const* format, ...) } // Update Achievement Criteria for all players in instance -void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) +void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= nullptr*/) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -531,7 +549,7 @@ void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, // Start timed achievement for all players in instance void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -542,7 +560,7 @@ void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, // Stop timed achievement for all players in instance void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -571,7 +589,7 @@ void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell) // Cast spell on all players in instance void InstanceScript::DoCastSpellOnPlayers(uint32 spell) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -579,14 +597,19 @@ void InstanceScript::DoCastSpellOnPlayers(uint32 spell) player->CastSpell(player, spell, true); } -bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/) +bool InstanceScript::ServerAllowsTwoSideGroups() +{ + return sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP); +} + +bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= nullptr*/, uint32 /*miscvalue1*/ /*= 0*/) { TC_LOG_ERROR("misc", "Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u", instance->GetId(), criteria_id); return false; } -void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= NULL*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) +void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= nullptr*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) { // size of this packet is at most 15 (usually less) WorldPacket data(SMSG_UPDATE_INSTANCE_ENCOUNTER_UNIT, 15); @@ -658,6 +681,16 @@ void InstanceScript::UpdateEncounterState(EncounterCreditType type, uint32 credi } } +void InstanceScript::UpdateEncounterStateForKilledCreature(uint32 creatureId, Unit* source) +{ + UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, creatureId, source); +} + +void InstanceScript::UpdateEncounterStateForSpellCast(uint32 spellId, Unit* source) +{ + UpdateEncounterState(ENCOUNTER_CREDIT_CAST_SPELL, spellId, source); +} + std::string InstanceScript::GetBossStateName(uint8 state) { // See enum EncounterState in InstanceScript.h @@ -679,3 +712,11 @@ std::string InstanceScript::GetBossStateName(uint8 state) return "INVALID"; } } + +bool InstanceHasScript(WorldObject const* obj, char const* scriptName) +{ + if (InstanceMap* instance = obj->GetMap()->ToInstanceMap()) + return instance->GetScriptName() == scriptName; + + return false; +} diff --git a/src/server/game/Instances/InstanceScript.h b/src/server/game/Instances/InstanceScript.h index 864ee007a5e..55452ebf3c1 100644 --- a/src/server/game/Instances/InstanceScript.h +++ b/src/server/game/Instances/InstanceScript.h @@ -19,11 +19,11 @@ #ifndef TRINITY_INSTANCE_DATA_H #define TRINITY_INSTANCE_DATA_H -#include #include "ZoneScript.h" -#include "World.h" -#include "ObjectMgr.h" -#include "CreatureAI.h" +#include "Common.h" +#include +#include +#include #define OUT_SAVE_INST_DATA TC_LOG_DEBUG("scripts", "Saving Instance Data for Instance %s (Map %d, Instance Id %d)", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) #define OUT_SAVE_INST_DATA_COMPLETE TC_LOG_DEBUG("scripts", "Saving Instance Data for Instance %s (Map %d, Instance Id %d) completed.", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) @@ -31,12 +31,17 @@ #define OUT_LOAD_INST_DATA_COMPLETE TC_LOG_DEBUG("scripts", "Instance Data Load for Instance %s (Map %d, Instance Id: %d) is complete.", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) #define OUT_LOAD_INST_DATA_FAIL TC_LOG_ERROR("scripts", "Unable to load Instance Data for Instance %s (Map %d, Instance Id: %d).", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) -class Map; -class Unit; -class Player; -class GameObject; +class AreaBoundary; class Creature; +class GameObject; +class Map; class ModuleReference; +class Player; +class Unit; +class WorldPacket; +enum AchievementCriteriaTypes : uint8; +enum AchievementCriteriaTimedTypes : uint8; +enum EncounterCreditType : uint8; enum EncounterFrameType { @@ -105,6 +110,8 @@ struct ObjectData uint32 type; }; +typedef std::vector CreatureBoundary; + struct BossInfo { BossInfo() : state(TO_BE_DECIDED) { } @@ -174,21 +181,15 @@ class TC_GAME_API InstanceScript : public ZoneScript ObjectGuid GetObjectGuid(uint32 type) const; virtual ObjectGuid GetGuidData(uint32 type) const override; - inline Creature* GetCreature(uint32 type) - { - return instance->GetCreature(GetObjectGuid(type)); - } - inline GameObject* GetGameObject(uint32 type) - { - return instance->GetGameObject(GetObjectGuid(type)); - } + Creature* GetCreature(uint32 type); + GameObject* GetGameObject(uint32 type); // Called when a player successfully enters the instance. virtual void OnPlayerEnter(Player* /*player*/) { } // Handle open / close objects // * use HandleGameObject(0, boolen, GO); in OnObjectCreate in instance scripts - // * use HandleGameObject(GUID, boolen, NULL); in any other script + // * use HandleGameObject(GUID, boolen, nullptr); in any other script void HandleGameObject(ObjectGuid guid, bool open, GameObject* go = nullptr); // Change active state of doors or buttons @@ -205,7 +206,7 @@ class TC_GAME_API InstanceScript : public ZoneScript void DoSendNotifyToInstance(char const* format, ...); // Update Achievement Criteria for all players in instance - void DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = NULL); + void DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); // Start/Stop Timed Achievement Criteria for all players in instance void DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); @@ -218,22 +219,23 @@ class TC_GAME_API InstanceScript : public ZoneScript void DoCastSpellOnPlayers(uint32 spell); // Return wether server allow two side groups or not - bool ServerAllowsTwoSideGroups() { return sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP); } + static bool ServerAllowsTwoSideGroups(); virtual bool SetBossState(uint32 id, EncounterState state); EncounterState GetBossState(uint32 id) const { return id < bosses.size() ? bosses[id].state : TO_BE_DECIDED; } static std::string GetBossStateName(uint8 state); - CreatureBoundary const* GetBossBoundary(uint32 id) const { return id < bosses.size() ? &bosses[id].boundary : NULL; } + CreatureBoundary const* GetBossBoundary(uint32 id) const { return id < bosses.size() ? &bosses[id].boundary : nullptr; } // Achievement criteria additional requirements check // NOTE: not use this if same can be checked existed requirement types from AchievementCriteriaRequirementType - virtual bool CheckAchievementCriteriaMeet(uint32 /*criteria_id*/, Player const* /*source*/, Unit const* /*target*/ = NULL, uint32 /*miscvalue1*/ = 0); + virtual bool CheckAchievementCriteriaMeet(uint32 /*criteria_id*/, Player const* /*source*/, Unit const* /*target*/ = nullptr, uint32 /*miscvalue1*/ = 0); // Checks boss requirements (one boss required to kill other) virtual bool CheckRequiredBosses(uint32 /*bossId*/, Player const* /*player*/ = nullptr) const { return true; } // Checks encounter state at kill/spellcast - void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source); + void UpdateEncounterStateForKilledCreature(uint32 creatureId, Unit* source); + void UpdateEncounterStateForSpellCast(uint32 spellId, Unit* source); // Used only during loading void SetCompletedEncountersMask(uint32 newMask) { completedEncounters = newMask; } @@ -241,7 +243,7 @@ class TC_GAME_API InstanceScript : public ZoneScript // Returns completed encounters mask for packets uint32 GetCompletedEncounterMask() const { return completedEncounters; } - void SendEncounterUnit(uint32 type, Unit* unit = NULL, uint8 param1 = 0, uint8 param2 = 0); + void SendEncounterUnit(uint32 type, Unit* unit = nullptr, uint8 param1 = 0, uint8 param2 = 0); virtual void FillInitialWorldStates(WorldPacket& /*data*/) { } @@ -281,6 +283,7 @@ class TC_GAME_API InstanceScript : public ZoneScript private: static void LoadObjectData(ObjectData const* creatureData, ObjectInfoMap& objectInfo); + void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source); std::vector headers; std::vector bosses; @@ -297,25 +300,4 @@ class TC_GAME_API InstanceScript : public ZoneScript #endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING }; -template -AI* GetInstanceAI(T* obj, char const* scriptName) -{ - if (InstanceMap* instance = obj->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(scriptName)) - return new AI(obj); - - return NULL; -} - -template -AI* GetInstanceAI(T* obj) -{ - if (InstanceMap* instance = obj->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - return new AI(obj); - - return NULL; -} - #endif // TRINITY_INSTANCE_DATA_H diff --git a/src/server/game/Loot/Loot.cpp b/src/server/game/Loot/Loot.cpp new file mode 100644 index 00000000000..7f6aaf24169 --- /dev/null +++ b/src/server/game/Loot/Loot.cpp @@ -0,0 +1,777 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "Loot.h" +#include "Group.h" +#include "ItemEnchantmentMgr.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Random.h" +#include "World.h" + + // + // --------- LootItem --------- + // + + // Constructor, copies most fields from LootStoreItem and generates random count +LootItem::LootItem(LootStoreItem const& li) +{ + itemid = li.itemid; + conditions = li.conditions; + + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid); + freeforall = proto && (proto->Flags & ITEM_FLAG_MULTI_DROP); + follow_loot_rules = proto && (proto->FlagsCu & ITEM_FLAGS_CU_FOLLOW_LOOT_RULES); + + needs_quest = li.needs_quest; + + randomSuffix = GenerateEnchSuffixFactor(itemid); + randomPropertyId = GenerateItemRandomPropertyId(itemid); + count = 0; + is_looted = 0; + is_blocked = 0; + is_underthreshold = 0; + is_counted = 0; + rollWinnerGUID = ObjectGuid::Empty; +} + +// Basic checks for player/item compatibility - if false no chance to see the item in the loot +bool LootItem::AllowedForPlayer(Player const* player) const +{ + // DB conditions check + if (!sConditionMgr->IsObjectMeetToConditions(const_cast(player), conditions)) + return false; + + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid); + if (!pProto) + return false; + + // not show loot for players without profession or those who already know the recipe + if ((pProto->Flags & ITEM_FLAG_HIDE_UNUSABLE_RECIPE) && (!player->HasSkill(pProto->RequiredSkill) || player->HasSpell(pProto->Spells[1].SpellId))) + return false; + + // not show loot for not own team + if ((pProto->Flags2 & ITEM_FLAG2_FACTION_HORDE) && player->GetTeam() != HORDE) + return false; + + if ((pProto->Flags2 & ITEM_FLAG2_FACTION_ALLIANCE) && player->GetTeam() != ALLIANCE) + return false; + + // check quest requirements + if (!(pProto->FlagsCu & ITEM_FLAGS_CU_IGNORE_QUEST_STATUS) && ((needs_quest || (pProto->StartQuest && player->GetQuestStatus(pProto->StartQuest) != QUEST_STATUS_NONE)) && !player->HasQuestForItem(itemid))) + return false; + + return true; +} + +void LootItem::AddAllowedLooter(Player const* player) +{ + allowedGUIDs.insert(player->GetGUID()); +} + +// +// --------- Loot --------- +// + +Loot::Loot(uint32 _gold /*= 0*/) : gold(_gold), unlootedCount(0), roundRobinPlayer(), loot_type(LOOT_NONE), maxDuplicates(1), containerID(0) +{ +} + +Loot::~Loot() +{ + clear(); +} + +void Loot::clear() +{ + for (NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.begin(); itr != PlayerQuestItems.end(); ++itr) + delete itr->second; + PlayerQuestItems.clear(); + + for (NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.begin(); itr != PlayerFFAItems.end(); ++itr) + delete itr->second; + PlayerFFAItems.clear(); + + for (NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.begin(); itr != PlayerNonQuestNonFFAConditionalItems.end(); ++itr) + delete itr->second; + PlayerNonQuestNonFFAConditionalItems.clear(); + + PlayersLooting.clear(); + items.clear(); + quest_items.clear(); + gold = 0; + unlootedCount = 0; + roundRobinPlayer.Clear(); + loot_type = LOOT_NONE; + i_LootValidatorRefManager.clearReferences(); +} + +// Inserts the item into the loot (called by LootTemplate processors) +void Loot::AddItem(LootStoreItem const& item) +{ + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item.itemid); + if (!proto) + return; + + uint32 count = urand(item.mincount, item.maxcount); + uint32 stacks = count / proto->GetMaxStackSize() + ((count % proto->GetMaxStackSize()) ? 1 : 0); + + std::vector& lootItems = item.needs_quest ? quest_items : items; + uint32 limit = item.needs_quest ? MAX_NR_QUEST_ITEMS : MAX_NR_LOOT_ITEMS; + + for (uint32 i = 0; i < stacks && lootItems.size() < limit; ++i) + { + LootItem generatedLoot(item); + generatedLoot.count = std::min(count, proto->GetMaxStackSize()); + lootItems.push_back(generatedLoot); + count -= proto->GetMaxStackSize(); + + // non-conditional one-player only items are counted here, + // free for all items are counted in FillFFALoot(), + // non-ffa conditionals are counted in FillNonQuestNonFFAConditionalLoot() + if (!item.needs_quest && item.conditions.empty() && !(proto->Flags & ITEM_FLAG_MULTI_DROP)) + ++unlootedCount; + } +} + +// Calls processor of corresponding LootTemplate (which handles everything including references) +bool Loot::FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError, uint16 lootMode /*= LOOT_MODE_DEFAULT*/) +{ + // Must be provided + if (!lootOwner) + return false; + + LootTemplate const* tab = store.GetLootFor(lootId); + + if (!tab) + { + if (!noEmptyError) + TC_LOG_ERROR("sql.sql", "Table '%s' loot id #%u used but it doesn't have records.", store.GetName(), lootId); + return false; + } + + items.reserve(MAX_NR_LOOT_ITEMS); + quest_items.reserve(MAX_NR_QUEST_ITEMS); + + tab->Process(*this, store.IsRatesAllowed(), lootMode); // Processing is done there, callback via Loot::AddItem() + + // Setting access rights for group loot case + Group* group = lootOwner->GetGroup(); + if (!personal && group) + { + roundRobinPlayer = lootOwner->GetGUID(); + + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) + if (Player* player = itr->GetSource()) // should actually be looted object instead of lootOwner but looter has to be really close so doesnt really matter + if (player->IsInMap(lootOwner)) + FillNotNormalLootFor(player, player->IsAtGroupRewardDistance(lootOwner)); + + for (uint8 i = 0; i < items.size(); ++i) + { + if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(items[i].itemid)) + if (proto->Quality < uint32(group->GetLootThreshold())) + items[i].is_underthreshold = true; + } + } + // ... for personal loot + else + FillNotNormalLootFor(lootOwner, true); + + return true; +} + +void Loot::FillNotNormalLootFor(Player* player, bool presentAtLooting) +{ + ObjectGuid plguid = player->GetGUID(); + + NotNormalLootItemMap::const_iterator qmapitr = PlayerQuestItems.find(plguid); + if (qmapitr == PlayerQuestItems.end()) + FillQuestLoot(player); + + qmapitr = PlayerFFAItems.find(plguid); + if (qmapitr == PlayerFFAItems.end()) + FillFFALoot(player); + + qmapitr = PlayerNonQuestNonFFAConditionalItems.find(plguid); + if (qmapitr == PlayerNonQuestNonFFAConditionalItems.end()) + FillNonQuestNonFFAConditionalLoot(player, presentAtLooting); + + // if not auto-processed player will have to come and pick it up manually + if (!presentAtLooting) + return; + + // Process currency items + uint32 max_slot = GetMaxSlotInLootFor(player); + LootItem const* item = nullptr; + uint32 itemsSize = uint32(items.size()); + for (uint32 i = 0; i < max_slot; ++i) + { + if (i < items.size()) + item = &items[i]; + else + item = &quest_items[i - itemsSize]; + + if (!item->is_looted && item->freeforall && item->AllowedForPlayer(player)) + if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item->itemid)) + if (proto->IsCurrencyToken()) + player->StoreLootItem(i, this); + } +} + +NotNormalLootItemList* Loot::FillFFALoot(Player* player) +{ + NotNormalLootItemList* ql = new NotNormalLootItemList(); + + for (uint8 i = 0; i < items.size(); ++i) + { + LootItem &item = items[i]; + if (!item.is_looted && item.freeforall && item.AllowedForPlayer(player)) + { + ql->push_back(NotNormalLootItem(i)); + ++unlootedCount; + } + } + if (ql->empty()) + { + delete ql; + return nullptr; + } + + PlayerFFAItems[player->GetGUID()] = ql; + return ql; +} + +NotNormalLootItemList* Loot::FillQuestLoot(Player* player) +{ + if (items.size() == MAX_NR_LOOT_ITEMS) + return nullptr; + + NotNormalLootItemList* ql = new NotNormalLootItemList(); + + for (uint8 i = 0; i < quest_items.size(); ++i) + { + LootItem &item = quest_items[i]; + + if (!item.is_looted && (item.AllowedForPlayer(player) || (item.follow_loot_rules && player->GetGroup() && ((player->GetGroup()->GetLootMethod() == MASTER_LOOT && player->GetGroup()->GetMasterLooterGuid() == player->GetGUID()) || player->GetGroup()->GetLootMethod() != MASTER_LOOT)))) + { + ql->push_back(NotNormalLootItem(i)); + + // quest items get blocked when they first appear in a + // player's quest vector + // + // increase once if one looter only, looter-times if free for all + if (item.freeforall || !item.is_blocked) + ++unlootedCount; + if (!player->GetGroup() || (player->GetGroup()->GetLootMethod() != GROUP_LOOT && player->GetGroup()->GetLootMethod() != ROUND_ROBIN)) + item.is_blocked = true; + + if (items.size() + ql->size() == MAX_NR_LOOT_ITEMS) + break; + } + } + if (ql->empty()) + { + delete ql; + return nullptr; + } + + PlayerQuestItems[player->GetGUID()] = ql; + return ql; +} + +NotNormalLootItemList* Loot::FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting) +{ + NotNormalLootItemList* ql = new NotNormalLootItemList(); + + for (uint8 i = 0; i < items.size(); ++i) + { + LootItem &item = items[i]; + if (!item.is_looted && !item.freeforall && (item.AllowedForPlayer(player))) + { + if (presentAtLooting) + item.AddAllowedLooter(player); + if (!item.conditions.empty()) + { + ql->push_back(NotNormalLootItem(i)); + if (!item.is_counted) + { + ++unlootedCount; + item.is_counted = true; + } + } + } + } + if (ql->empty()) + { + delete ql; + return nullptr; + } + + PlayerNonQuestNonFFAConditionalItems[player->GetGUID()] = ql; + return ql; +} + +//=================================================== + +void Loot::NotifyItemRemoved(uint8 lootIndex) +{ + // notify all players that are looting this that the item was removed + // convert the index to the slot the player sees + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + player->SendNotifyLootItemRemoved(lootIndex); + else + PlayersLooting.erase(i); + } +} + +void Loot::NotifyMoneyRemoved() +{ + // notify all players that are looting this that the money was removed + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + player->SendNotifyLootMoneyRemoved(); + else + PlayersLooting.erase(i); + } +} + +void Loot::NotifyQuestItemRemoved(uint8 questIndex) +{ + // when a free for all questitem is looted + // all players will get notified of it being removed + // (other questitems can be looted by each group member) + // bit inefficient but isn't called often + + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + { + NotNormalLootItemMap::const_iterator pq = PlayerQuestItems.find(player->GetGUID()); + if (pq != PlayerQuestItems.end() && pq->second) + { + // find where/if the player has the given item in it's vector + NotNormalLootItemList& pql = *pq->second; + + uint8 j; + for (j = 0; j < pql.size(); ++j) + if (pql[j].index == questIndex) + break; + + if (j < pql.size()) + player->SendNotifyLootItemRemoved(items.size() + j); + } + } + else + PlayersLooting.erase(i); + } +} + +void Loot::generateMoneyLoot(uint32 minAmount, uint32 maxAmount) +{ + if (maxAmount > 0) + { + if (maxAmount <= minAmount) + gold = uint32(maxAmount * sWorld->getRate(RATE_DROP_MONEY)); + else if ((maxAmount - minAmount) < 32700) + gold = uint32(urand(minAmount, maxAmount) * sWorld->getRate(RATE_DROP_MONEY)); + else + gold = uint32(urand(minAmount >> 8, maxAmount >> 8) * sWorld->getRate(RATE_DROP_MONEY)) << 8; + } +} + +LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, NotNormalLootItem* *qitem, NotNormalLootItem* *ffaitem, NotNormalLootItem* *conditem) +{ + LootItem* item = nullptr; + bool is_looted = true; + if (lootSlot >= items.size()) + { + uint32 questSlot = lootSlot - items.size(); + NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID()); + if (itr != PlayerQuestItems.end() && questSlot < itr->second->size()) + { + NotNormalLootItem* qitem2 = &itr->second->at(questSlot); + if (qitem) + *qitem = qitem2; + item = &quest_items[qitem2->index]; + is_looted = qitem2->is_looted; + } + } + else + { + item = &items[lootSlot]; + is_looted = item->is_looted; + if (item->freeforall) + { + NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.find(player->GetGUID()); + if (itr != PlayerFFAItems.end()) + { + for (NotNormalLootItemList::const_iterator iter = itr->second->begin(); iter != itr->second->end(); ++iter) + if (iter->index == lootSlot) + { + NotNormalLootItem* ffaitem2 = (NotNormalLootItem*)&(*iter); + if (ffaitem) + *ffaitem = ffaitem2; + is_looted = ffaitem2->is_looted; + break; + } + } + } + else if (!item->conditions.empty()) + { + NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.find(player->GetGUID()); + if (itr != PlayerNonQuestNonFFAConditionalItems.end()) + { + for (NotNormalLootItemList::const_iterator iter = itr->second->begin(); iter != itr->second->end(); ++iter) + { + if (iter->index == lootSlot) + { + NotNormalLootItem* conditem2 = (NotNormalLootItem*)&(*iter); + if (conditem) + *conditem = conditem2; + is_looted = conditem2->is_looted; + break; + } + } + } + } + } + + if (is_looted) + return nullptr; + + return item; +} + +uint32 Loot::GetMaxSlotInLootFor(Player* player) const +{ + NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID()); + return items.size() + (itr != PlayerQuestItems.end() ? itr->second->size() : 0); +} + +// return true if there is any item that is lootable for any player (not quest item, FFA or conditional) +bool Loot::hasItemForAll() const +{ + // Gold is always lootable + if (gold) + return true; + + for (LootItem const& item : items) + if (!item.is_looted && !item.freeforall && item.conditions.empty()) + return true; + return false; +} + +// return true if there is any FFA, quest or conditional item for the player. +bool Loot::hasItemFor(Player* player) const +{ + NotNormalLootItemMap const& lootPlayerQuestItems = GetPlayerQuestItems(); + NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(player->GetGUID()); + if (q_itr != lootPlayerQuestItems.end()) + { + NotNormalLootItemList* q_list = q_itr->second; + for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) + { + LootItem const& item = quest_items[qi->index]; + if (!qi->is_looted && !item.is_looted) + return true; + } + } + + NotNormalLootItemMap const& lootPlayerFFAItems = GetPlayerFFAItems(); + NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(player->GetGUID()); + if (ffa_itr != lootPlayerFFAItems.end()) + { + NotNormalLootItemList* ffa_list = ffa_itr->second; + for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) + { + LootItem const& item = items[fi->index]; + if (!fi->is_looted && !item.is_looted) + return true; + } + } + + NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = GetPlayerNonQuestNonFFAConditionalItems(); + NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(player->GetGUID()); + if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) + { + NotNormalLootItemList* conditional_list = nn_itr->second; + for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) + { + LootItem const& item = items[ci->index]; + if (!ci->is_looted && !item.is_looted) + return true; + } + } + + return false; +} + +// return true if there is any item over the group threshold (i.e. not underthreshold). +bool Loot::hasOverThresholdItem() const +{ + for (uint8 i = 0; i < items.size(); ++i) + { + if (!items[i].is_looted && !items[i].is_underthreshold && !items[i].freeforall) + return true; + } + + return false; +} + +ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li) +{ + b << uint32(li.itemid); + b << uint32(li.count); // nr of items of this type + b << uint32(ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(li.itemid))->DisplayInfoID); + b << uint32(li.randomSuffix); + b << uint32(li.randomPropertyId); + //b << uint8(0); // slot type - will send after this function call + return b; +} + +ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) +{ + if (lv.permission == NONE_PERMISSION) + { + b << uint32(0); // gold + b << uint8(0); // item count + return b; + } + + Loot &l = lv.loot; + + uint8 itemsShown = 0; + + b << uint32(l.gold); //gold + + size_t count_pos = b.wpos(); // pos of item count byte + b << uint8(0); // item count placeholder + + switch (lv.permission) + { + case GROUP_PERMISSION: + case MASTER_PERMISSION: + case RESTRICTED_PERMISSION: + { + // if you are not the round-robin group looter, you can only see + // blocked rolled items and quest items, and !ffa items + for (uint8 i = 0; i < l.items.size(); ++i) + { + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + uint8 slot_type; + + if (l.items[i].is_blocked) // for ML & restricted is_blocked = !is_underthreshold + { + switch (lv.permission) + { + case GROUP_PERMISSION: + slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; + break; + case MASTER_PERMISSION: + { + if (lv.viewer->GetGroup() && lv.viewer->GetGroup()->GetMasterLooterGuid() == lv.viewer->GetGUID()) + slot_type = LOOT_SLOT_TYPE_MASTER; + else + slot_type = LOOT_SLOT_TYPE_LOCKED; + break; + } + case RESTRICTED_PERMISSION: + slot_type = LOOT_SLOT_TYPE_LOCKED; + break; + default: + continue; + } + } + else if (!l.items[i].rollWinnerGUID.IsEmpty()) + { + if (l.items[i].rollWinnerGUID == lv.viewer->GetGUID()) + slot_type = LOOT_SLOT_TYPE_OWNER; + else + continue; + } + else if (l.roundRobinPlayer.IsEmpty() || lv.viewer->GetGUID() == l.roundRobinPlayer || !l.items[i].is_underthreshold) + { + // no round robin owner or he has released the loot + // or it IS the round robin group owner + // => item is lootable + slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; + } + else + // item shall not be displayed. + continue; + + b << uint8(i) << l.items[i]; + b << uint8(slot_type); + ++itemsShown; + } + } + break; + } + case ROUND_ROBIN_PERMISSION: + { + for (uint8 i = 0; i < l.items.size(); ++i) + { + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + if (!l.roundRobinPlayer.IsEmpty() && lv.viewer->GetGUID() != l.roundRobinPlayer) + // item shall not be displayed. + continue; + + b << uint8(i) << l.items[i]; + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + ++itemsShown; + } + } + break; + } + case ALL_PERMISSION: + case OWNER_PERMISSION: + { + uint8 slot_type = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; + for (uint8 i = 0; i < l.items.size(); ++i) + { + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + b << uint8(i) << l.items[i]; + b << uint8(slot_type); + ++itemsShown; + } + } + break; + } + default: + return b; + } + + LootSlotType slotType = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; + NotNormalLootItemMap const& lootPlayerQuestItems = l.GetPlayerQuestItems(); + NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(lv.viewer->GetGUID()); + if (q_itr != lootPlayerQuestItems.end()) + { + NotNormalLootItemList* q_list = q_itr->second; + for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) + { + LootItem &item = l.quest_items[qi->index]; + if (!qi->is_looted && !item.is_looted) + { + b << uint8(l.items.size() + (qi - q_list->begin())); + b << item; + if (item.follow_loot_rules) + { + switch (lv.permission) + { + case MASTER_PERMISSION: + b << uint8(LOOT_SLOT_TYPE_MASTER); + break; + case RESTRICTED_PERMISSION: + b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); + break; + case GROUP_PERMISSION: + case ROUND_ROBIN_PERMISSION: + if (!item.is_blocked) + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + else + b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); + break; + default: + b << uint8(slotType); + break; + } + } + else + b << uint8(slotType); + ++itemsShown; + } + } + } + + NotNormalLootItemMap const& lootPlayerFFAItems = l.GetPlayerFFAItems(); + NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(lv.viewer->GetGUID()); + if (ffa_itr != lootPlayerFFAItems.end()) + { + NotNormalLootItemList* ffa_list = ffa_itr->second; + for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) + { + LootItem &item = l.items[fi->index]; + if (!fi->is_looted && !item.is_looted) + { + b << uint8(fi->index); + b << item; + b << uint8(slotType); + ++itemsShown; + } + } + } + + NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = l.GetPlayerNonQuestNonFFAConditionalItems(); + NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(lv.viewer->GetGUID()); + if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) + { + NotNormalLootItemList* conditional_list = nn_itr->second; + for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) + { + LootItem &item = l.items[ci->index]; + if (!ci->is_looted && !item.is_looted) + { + b << uint8(ci->index); + b << item; + switch (lv.permission) + { + case MASTER_PERMISSION: + b << uint8(LOOT_SLOT_TYPE_MASTER); + break; + case RESTRICTED_PERMISSION: + b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); + break; + case GROUP_PERMISSION: + case ROUND_ROBIN_PERMISSION: + if (!item.is_blocked) + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + else + b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); + break; + default: + b << uint8(slotType); + break; + } + ++itemsShown; + } + } + } + + //update number of items shown + b.put(count_pos, itemsShown); + + return b; +} diff --git a/src/server/game/Loot/Loot.h b/src/server/game/Loot/Loot.h new file mode 100644 index 00000000000..33477c4e853 --- /dev/null +++ b/src/server/game/Loot/Loot.h @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef Loot_h__ +#define Loot_h__ + +#include "Define.h" +#include "ConditionMgr.h" +#include "ObjectGuid.h" +#include "RefManager.h" +#include "SharedDefines.h" +#include +#include + +class Item; +class LootStore; +class Player; +struct Loot; +struct LootStoreItem; + +enum RollType +{ + ROLL_PASS = 0, + ROLL_NEED = 1, + ROLL_GREED = 2, + ROLL_DISENCHANT = 3, + MAX_ROLL_TYPE = 4 +}; + +enum RollMask +{ + ROLL_FLAG_TYPE_PASS = 0x01, + ROLL_FLAG_TYPE_NEED = 0x02, + ROLL_FLAG_TYPE_GREED = 0x04, + ROLL_FLAG_TYPE_DISENCHANT = 0x08, + + ROLL_ALL_TYPE_NO_DISENCHANT = 0x07, + ROLL_ALL_TYPE_MASK = 0x0F +}; + +#define MAX_NR_LOOT_ITEMS 16 +// note: the client cannot show more than 16 items total +#define MAX_NR_QUEST_ITEMS 32 +// unrelated to the number of quest items shown, just for reserve + +enum LootMethod : uint8 +{ + FREE_FOR_ALL = 0, + ROUND_ROBIN = 1, + MASTER_LOOT = 2, + GROUP_LOOT = 3, + NEED_BEFORE_GREED = 4 +}; + +enum PermissionTypes +{ + ALL_PERMISSION = 0, + GROUP_PERMISSION = 1, + MASTER_PERMISSION = 2, + RESTRICTED_PERMISSION = 3, + ROUND_ROBIN_PERMISSION = 4, + OWNER_PERMISSION = 5, + NONE_PERMISSION = 6 +}; + +enum LootType : uint8 +{ + LOOT_NONE = 0, + + LOOT_CORPSE = 1, + LOOT_PICKPOCKETING = 2, + LOOT_FISHING = 3, + LOOT_DISENCHANTING = 4, + // ignored always by client + LOOT_SKINNING = 6, + LOOT_PROSPECTING = 7, + LOOT_MILLING = 8, + + LOOT_FISHINGHOLE = 20, // unsupported by client, sending LOOT_FISHING instead + LOOT_INSIGNIA = 21, // unsupported by client, sending LOOT_CORPSE instead + LOOT_FISHING_JUNK = 22 // unsupported by client, sending LOOT_FISHING instead +}; + +enum LootError : uint8 +{ + LOOT_ERROR_DIDNT_KILL = 0, // You don't have permission to loot that corpse. + LOOT_ERROR_TOO_FAR = 4, // You are too far away to loot that corpse. + LOOT_ERROR_BAD_FACING = 5, // You must be facing the corpse to loot it. + LOOT_ERROR_LOCKED = 6, // Someone is already looting that corpse. + LOOT_ERROR_NOTSTANDING = 8, // You need to be standing up to loot something! + LOOT_ERROR_STUNNED = 9, // You can't loot anything while stunned! + LOOT_ERROR_PLAYER_NOT_FOUND = 10, // Player not found + LOOT_ERROR_PLAY_TIME_EXCEEDED = 11, // Maximum play time exceeded + LOOT_ERROR_MASTER_INV_FULL = 12, // That player's inventory is full + LOOT_ERROR_MASTER_UNIQUE_ITEM = 13, // Player has too many of that item already + LOOT_ERROR_MASTER_OTHER = 14, // Can't assign item to that player + LOOT_ERROR_ALREADY_PICKPOCKETED = 15, // Your target has already had its pockets picked + LOOT_ERROR_NOT_WHILE_SHAPESHIFTED = 16 // You can't do that while shapeshifted. +}; + +// type of Loot Item in Loot View +enum LootSlotType +{ + LOOT_SLOT_TYPE_ALLOW_LOOT = 0, // player can loot the item. + LOOT_SLOT_TYPE_ROLL_ONGOING = 1, // roll is ongoing. player cannot loot. + LOOT_SLOT_TYPE_MASTER = 2, // item can only be distributed by group loot master. + LOOT_SLOT_TYPE_LOCKED = 3, // item is shown in red. player cannot loot. + LOOT_SLOT_TYPE_OWNER = 4 // ignore binding confirmation and etc, for single player looting +}; + +struct TC_GAME_API LootItem +{ + uint32 itemid; + uint32 randomSuffix; + int32 randomPropertyId; + ConditionContainer conditions; // additional loot condition + GuidSet allowedGUIDs; + ObjectGuid rollWinnerGUID; // Stores the guid of person who won loot, if his bags are full only he can see the item in loot list! + uint8 count : 8; + bool is_looted : 1; + bool is_blocked : 1; + bool freeforall : 1; // free for all + bool is_underthreshold : 1; + bool is_counted : 1; + bool needs_quest : 1; // quest drop + bool follow_loot_rules : 1; + + // Constructor, copies most fields from LootStoreItem, generates random count and random suffixes/properties + // Should be called for non-reference LootStoreItem entries only (reference = 0) + explicit LootItem(LootStoreItem const& li); + + // Empty constructor for creating an empty LootItem to be filled in with DB data + LootItem() : itemid(0), randomSuffix(0), randomPropertyId(0), count(0), is_looted(false), is_blocked(false), + freeforall(false), is_underthreshold(false), is_counted(false), needs_quest(false), follow_loot_rules(false) + { }; + + // Basic checks for player/item compatibility - if false no chance to see the item in the loot + bool AllowedForPlayer(Player const* player) const; + void AddAllowedLooter(Player const* player); + GuidSet const& GetAllowedLooters() const { return allowedGUIDs; } +}; + +struct NotNormalLootItem +{ + uint8 index; // position in quest_items or items; + bool is_looted; + + NotNormalLootItem() + : index(0), is_looted(false) { } + + NotNormalLootItem(uint8 _index, bool _islooted = false) + : index(_index), is_looted(_islooted) { } +}; + +struct Loot; +class LootTemplate; + +typedef std::vector NotNormalLootItemList; +typedef std::vector LootItemList; +typedef std::unordered_map NotNormalLootItemMap; + +class LootValidatorRef : public Reference +{ + public: + LootValidatorRef() { } + void targetObjectDestroyLink() override { } + void sourceObjectDestroyLink() override { } +}; + +//===================================================== + +class LootValidatorRefManager : public RefManager +{ + public: + typedef LinkedListHead::Iterator< LootValidatorRef > iterator; + + LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager::getFirst(); } + + iterator begin() { return iterator(getFirst()); } + iterator end() { return iterator(nullptr); } +}; + +//===================================================== +struct LootView; + +ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li); +ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); + +struct TC_GAME_API Loot +{ + friend ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); + + NotNormalLootItemMap const& GetPlayerQuestItems() const { return PlayerQuestItems; } + NotNormalLootItemMap const& GetPlayerFFAItems() const { return PlayerFFAItems; } + NotNormalLootItemMap const& GetPlayerNonQuestNonFFAConditionalItems() const { return PlayerNonQuestNonFFAConditionalItems; } + + std::vector items; + std::vector quest_items; + uint32 gold; + uint8 unlootedCount; + ObjectGuid roundRobinPlayer; // GUID of the player having the Round-Robin ownership for the loot. If 0, round robin owner has released. + LootType loot_type; // required for achievement system + uint8 maxDuplicates; // Max amount of items with the same entry that can drop (default is 1; on 25 man raid mode 3) + + // GUIDLow of container that holds this loot (item_instance.entry) + // Only set for inventory items that can be right-click looted + uint32 containerID; + + Loot(uint32 _gold = 0); + ~Loot(); + + // if loot becomes invalid this reference is used to inform the listener + void addLootValidatorRef(LootValidatorRef* pLootValidatorRef) + { + i_LootValidatorRefManager.insertFirst(pLootValidatorRef); + } + + void clear(); + + bool empty() const { return items.empty() && gold == 0; } + bool isLooted() const { return gold == 0 && unlootedCount == 0; } + + void NotifyItemRemoved(uint8 lootIndex); + void NotifyQuestItemRemoved(uint8 questIndex); + void NotifyMoneyRemoved(); + void AddLooter(ObjectGuid GUID) { PlayersLooting.insert(GUID); } + void RemoveLooter(ObjectGuid GUID) { PlayersLooting.erase(GUID); } + + void generateMoneyLoot(uint32 minAmount, uint32 maxAmount); + bool FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError = false, uint16 lootMode = LOOT_MODE_DEFAULT); + + // Inserts the item into the loot (called by LootTemplate processors) + void AddItem(LootStoreItem const & item); + + LootItem* LootItemInSlot(uint32 lootslot, Player* player, NotNormalLootItem** qitem = nullptr, NotNormalLootItem** ffaitem = nullptr, NotNormalLootItem** conditem = nullptr); + uint32 GetMaxSlotInLootFor(Player* player) const; + bool hasItemForAll() const; + bool hasItemFor(Player* player) const; + bool hasOverThresholdItem() const; + + private: + void FillNotNormalLootFor(Player* player, bool presentAtLooting); + NotNormalLootItemList* FillFFALoot(Player* player); + NotNormalLootItemList* FillQuestLoot(Player* player); + NotNormalLootItemList* FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting); + + GuidSet PlayersLooting; + NotNormalLootItemMap PlayerQuestItems; + NotNormalLootItemMap PlayerFFAItems; + NotNormalLootItemMap PlayerNonQuestNonFFAConditionalItems; + + // All rolls are registered here. They need to know, when the loot is not valid anymore + LootValidatorRefManager i_LootValidatorRefManager; +}; + +struct LootView +{ + Loot &loot; + Player* viewer; + PermissionTypes permission; + LootView(Loot &_loot, Player* _viewer, PermissionTypes _permission = ALL_PERMISSION) + : loot(_loot), viewer(_viewer), permission(_permission) { } +}; + +#endif // Loot_h__ diff --git a/src/server/game/Loot/LootItemStorage.cpp b/src/server/game/Loot/LootItemStorage.cpp index 45f1027932b..07b01379904 100644 --- a/src/server/game/Loot/LootItemStorage.cpp +++ b/src/server/game/Loot/LootItemStorage.cpp @@ -16,8 +16,11 @@ */ #include "LootItemStorage.h" +#include "DatabaseEnv.h" +#include "Item.h" #include "ItemTemplate.h" #include "Log.h" +#include "Loot.h" #include "LootMgr.h" #include "ObjectMgr.h" #include "Player.h" diff --git a/src/server/game/Loot/LootItemStorage.h b/src/server/game/Loot/LootItemStorage.h index e98831a5ecf..aeda684d705 100644 --- a/src/server/game/Loot/LootItemStorage.h +++ b/src/server/game/Loot/LootItemStorage.h @@ -19,7 +19,7 @@ #define __LOOTITEMSTORAGE_H #include "Define.h" -#include "Transaction.h" +#include "DatabaseEnvFwd.h" #include diff --git a/src/server/game/Loot/LootMgr.cpp b/src/server/game/Loot/LootMgr.cpp index 34712308070..7c6cc28fb48 100644 --- a/src/server/game/Loot/LootMgr.cpp +++ b/src/server/game/Loot/LootMgr.cpp @@ -17,16 +17,19 @@ */ #include "LootMgr.h" +#include "Containers.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Group.h" #include "Log.h" +#include "Loot.h" #include "ObjectMgr.h" -#include "World.h" -#include "Util.h" +#include "Player.h" #include "SharedDefines.h" -#include "SpellMgr.h" #include "SpellInfo.h" -#include "Group.h" -#include "Player.h" -#include "Containers.h" +#include "SpellMgr.h" +#include "Util.h" +#include "World.h" static Rates const qualityToRate[MAX_ITEM_QUALITY] = { @@ -91,7 +94,6 @@ class LootTemplate::LootGroup // A set of loot def float TotalChance() const; // Overall chance for the group void Verify(LootStore const& lootstore, uint32 id, uint8 group_id) const; - void CollectLootIds(LootIdSet& set) const; void CheckLootRefs(LootTemplateMap const& store, LootIdSet* ref_set) const; LootStoreItemList* GetExplicitlyChancedItemList() { return &ExplicitlyChanced; } LootStoreItemList* GetEqualChancedItemList() { return &EqualChanced; } @@ -103,14 +105,14 @@ class LootTemplate::LootGroup // A set of loot def LootStoreItem const* Roll(Loot& loot, uint16 lootMode) const; // Rolls an item from the group, returns NULL if all miss their chances // This class must never be copied - storing pointers - LootGroup(LootGroup const&); - LootGroup& operator=(LootGroup const&); + LootGroup(LootGroup const&) = delete; + LootGroup& operator=(LootGroup const&) = delete; }; //Remove all data and free all memory void LootStore::Clear() { - for (LootTemplateMap::const_iterator itr=m_LootTemplates.begin(); itr != m_LootTemplates.end(); ++itr) + for (LootTemplateMap::const_iterator itr = m_LootTemplates.begin(); itr != m_LootTemplates.end(); ++itr) delete itr->second; m_LootTemplates.clear(); } @@ -228,7 +230,7 @@ LootTemplate const* LootStore::GetLootFor(uint32 loot_id) const LootTemplateMap::const_iterator tab = m_LootTemplates.find(loot_id); if (tab == m_LootTemplates.end()) - return NULL; + return nullptr; return tab->second; } @@ -238,7 +240,7 @@ LootTemplate* LootStore::GetLootForConditionFill(uint32 loot_id) LootTemplateMap::iterator tab = m_LootTemplates.find(loot_id); if (tab == m_LootTemplates.end()) - return NULL; + return nullptr; return tab->second; } @@ -266,7 +268,7 @@ void LootStore::ReportUnusedIds(LootIdSet const& lootIdSet) const TC_LOG_ERROR("sql.sql", "Table '%s' Entry %d isn't %s and not referenced from loot, and thus useless.", GetName(), *itr, GetEntryName()); } -void LootStore::ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const +void LootStore::ReportNonExistingId(uint32 lootId, char const* ownerType, uint32 ownerId) const { TC_LOG_ERROR("sql.sql", "Table '%s' Entry %d does not exist but it is used by %s %d", GetName(), lootId, ownerType, ownerId); } @@ -342,722 +344,6 @@ bool LootStoreItem::IsValid(LootStore const& store, uint32 entry) const return true; // Referenced template existence is checked at whole store level } -// -// --------- LootItem --------- -// - -// Constructor, copies most fields from LootStoreItem and generates random count -LootItem::LootItem(LootStoreItem const& li) -{ - itemid = li.itemid; - conditions = li.conditions; - - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid); - freeforall = proto && (proto->Flags & ITEM_FLAG_MULTI_DROP); - follow_loot_rules = proto && (proto->FlagsCu & ITEM_FLAGS_CU_FOLLOW_LOOT_RULES); - - needs_quest = li.needs_quest; - - randomSuffix = GenerateEnchSuffixFactor(itemid); - randomPropertyId = Item::GenerateItemRandomPropertyId(itemid); - count = 0; - is_looted = 0; - is_blocked = 0; - is_underthreshold = 0; - is_counted = 0; - rollWinnerGUID = ObjectGuid::Empty; -} - -// Basic checks for player/item compatibility - if false no chance to see the item in the loot -bool LootItem::AllowedForPlayer(Player const* player) const -{ - // DB conditions check - if (!sConditionMgr->IsObjectMeetToConditions(const_cast(player), conditions)) - return false; - - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid); - if (!pProto) - return false; - - // not show loot for players without profession or those who already know the recipe - if ((pProto->Flags & ITEM_FLAG_HIDE_UNUSABLE_RECIPE) && (!player->HasSkill(pProto->RequiredSkill) || player->HasSpell(pProto->Spells[1].SpellId))) - return false; - - // not show loot for not own team - if ((pProto->Flags2 & ITEM_FLAG2_FACTION_HORDE) && player->GetTeam() != HORDE) - return false; - - if ((pProto->Flags2 & ITEM_FLAG2_FACTION_ALLIANCE) && player->GetTeam() != ALLIANCE) - return false; - - // check quest requirements - if (!(pProto->FlagsCu & ITEM_FLAGS_CU_IGNORE_QUEST_STATUS) && ((needs_quest || (pProto->StartQuest && player->GetQuestStatus(pProto->StartQuest) != QUEST_STATUS_NONE)) && !player->HasQuestForItem(itemid))) - return false; - - return true; -} - -void LootItem::AddAllowedLooter(const Player* player) -{ - allowedGUIDs.insert(player->GetGUID().GetCounter()); -} - -// -// --------- Loot --------- -// - -// Inserts the item into the loot (called by LootTemplate processors) -void Loot::AddItem(LootStoreItem const& item) -{ - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item.itemid); - if (!proto) - return; - - uint32 count = urand(item.mincount, item.maxcount); - uint32 stacks = count / proto->GetMaxStackSize() + ((count % proto->GetMaxStackSize()) ? 1 : 0); - - std::vector& lootItems = item.needs_quest ? quest_items : items; - uint32 limit = item.needs_quest ? MAX_NR_QUEST_ITEMS : MAX_NR_LOOT_ITEMS; - - for (uint32 i = 0; i < stacks && lootItems.size() < limit; ++i) - { - LootItem generatedLoot(item); - generatedLoot.count = std::min(count, proto->GetMaxStackSize()); - lootItems.push_back(generatedLoot); - count -= proto->GetMaxStackSize(); - - // non-conditional one-player only items are counted here, - // free for all items are counted in FillFFALoot(), - // non-ffa conditionals are counted in FillNonQuestNonFFAConditionalLoot() - if (!item.needs_quest && item.conditions.empty() && !(proto->Flags & ITEM_FLAG_MULTI_DROP)) - ++unlootedCount; - } -} - -// Calls processor of corresponding LootTemplate (which handles everything including references) -bool Loot::FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError, uint16 lootMode /*= LOOT_MODE_DEFAULT*/) -{ - // Must be provided - if (!lootOwner) - return false; - - LootTemplate const* tab = store.GetLootFor(lootId); - - if (!tab) - { - if (!noEmptyError) - TC_LOG_ERROR("sql.sql", "Table '%s' loot id #%u used but it doesn't have records.", store.GetName(), lootId); - return false; - } - - items.reserve(MAX_NR_LOOT_ITEMS); - quest_items.reserve(MAX_NR_QUEST_ITEMS); - - tab->Process(*this, store.IsRatesAllowed(), lootMode); // Processing is done there, callback via Loot::AddItem() - - // Setting access rights for group loot case - Group* group = lootOwner->GetGroup(); - if (!personal && group) - { - roundRobinPlayer = lootOwner->GetGUID(); - - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) - if (Player* player = itr->GetSource()) // should actually be looted object instead of lootOwner but looter has to be really close so doesnt really matter - if (player->IsInMap(lootOwner)) - FillNotNormalLootFor(player, player->IsAtGroupRewardDistance(lootOwner)); - - for (uint8 i = 0; i < items.size(); ++i) - { - if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(items[i].itemid)) - if (proto->Quality < uint32(group->GetLootThreshold())) - items[i].is_underthreshold = true; - } - } - // ... for personal loot - else - FillNotNormalLootFor(lootOwner, true); - - return true; -} - -void Loot::FillNotNormalLootFor(Player* player, bool presentAtLooting) -{ - ObjectGuid::LowType plguid = player->GetGUID().GetCounter(); - - NotNormalLootItemMap::const_iterator qmapitr = PlayerQuestItems.find(plguid); - if (qmapitr == PlayerQuestItems.end()) - FillQuestLoot(player); - - qmapitr = PlayerFFAItems.find(plguid); - if (qmapitr == PlayerFFAItems.end()) - FillFFALoot(player); - - qmapitr = PlayerNonQuestNonFFAConditionalItems.find(plguid); - if (qmapitr == PlayerNonQuestNonFFAConditionalItems.end()) - FillNonQuestNonFFAConditionalLoot(player, presentAtLooting); - - // if not auto-processed player will have to come and pick it up manually - if (!presentAtLooting) - return; - - // Process currency items - uint32 max_slot = GetMaxSlotInLootFor(player); - LootItem const* item = NULL; - uint32 itemsSize = uint32(items.size()); - for (uint32 i = 0; i < max_slot; ++i) - { - if (i < items.size()) - item = &items[i]; - else - item = &quest_items[i-itemsSize]; - - if (!item->is_looted && item->freeforall && item->AllowedForPlayer(player)) - if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item->itemid)) - if (proto->IsCurrencyToken()) - player->StoreLootItem(i, this); - } -} - -NotNormalLootItemList* Loot::FillFFALoot(Player* player) -{ - NotNormalLootItemList* ql = new NotNormalLootItemList(); - - for (uint8 i = 0; i < items.size(); ++i) - { - LootItem &item = items[i]; - if (!item.is_looted && item.freeforall && item.AllowedForPlayer(player)) - { - ql->push_back(NotNormalLootItem(i)); - ++unlootedCount; - } - } - if (ql->empty()) - { - delete ql; - return NULL; - } - - PlayerFFAItems[player->GetGUID().GetCounter()] = ql; - return ql; -} - -NotNormalLootItemList* Loot::FillQuestLoot(Player* player) -{ - if (items.size() == MAX_NR_LOOT_ITEMS) - return NULL; - - NotNormalLootItemList* ql = new NotNormalLootItemList(); - - for (uint8 i = 0; i < quest_items.size(); ++i) - { - LootItem &item = quest_items[i]; - - if (!item.is_looted && (item.AllowedForPlayer(player) || (item.follow_loot_rules && player->GetGroup() && ((player->GetGroup()->GetLootMethod() == MASTER_LOOT && player->GetGroup()->GetMasterLooterGuid() == player->GetGUID()) || player->GetGroup()->GetLootMethod() != MASTER_LOOT)))) - { - ql->push_back(NotNormalLootItem(i)); - - // quest items get blocked when they first appear in a - // player's quest vector - // - // increase once if one looter only, looter-times if free for all - if (item.freeforall || !item.is_blocked) - ++unlootedCount; - if (!player->GetGroup() || (player->GetGroup()->GetLootMethod() != GROUP_LOOT && player->GetGroup()->GetLootMethod() != ROUND_ROBIN)) - item.is_blocked = true; - - if (items.size() + ql->size() == MAX_NR_LOOT_ITEMS) - break; - } - } - if (ql->empty()) - { - delete ql; - return NULL; - } - - PlayerQuestItems[player->GetGUID().GetCounter()] = ql; - return ql; -} - -NotNormalLootItemList* Loot::FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting) -{ - NotNormalLootItemList* ql = new NotNormalLootItemList(); - - for (uint8 i = 0; i < items.size(); ++i) - { - LootItem &item = items[i]; - if (!item.is_looted && !item.freeforall && (item.AllowedForPlayer(player))) - { - if (presentAtLooting) - item.AddAllowedLooter(player); - if (!item.conditions.empty()) - { - ql->push_back(NotNormalLootItem(i)); - if (!item.is_counted) - { - ++unlootedCount; - item.is_counted = true; - } - } - } - } - if (ql->empty()) - { - delete ql; - return NULL; - } - - PlayerNonQuestNonFFAConditionalItems[player->GetGUID().GetCounter()] = ql; - return ql; -} - -//=================================================== - -void Loot::NotifyItemRemoved(uint8 lootIndex) -{ - // notify all players that are looting this that the item was removed - // convert the index to the slot the player sees - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - player->SendNotifyLootItemRemoved(lootIndex); - else - PlayersLooting.erase(i); - } -} - -void Loot::NotifyMoneyRemoved() -{ - // notify all players that are looting this that the money was removed - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - player->SendNotifyLootMoneyRemoved(); - else - PlayersLooting.erase(i); - } -} - -void Loot::NotifyQuestItemRemoved(uint8 questIndex) -{ - // when a free for all questitem is looted - // all players will get notified of it being removed - // (other questitems can be looted by each group member) - // bit inefficient but isn't called often - - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - { - NotNormalLootItemMap::const_iterator pq = PlayerQuestItems.find(player->GetGUID().GetCounter()); - if (pq != PlayerQuestItems.end() && pq->second) - { - // find where/if the player has the given item in it's vector - NotNormalLootItemList& pql = *pq->second; - - uint8 j; - for (j = 0; j < pql.size(); ++j) - if (pql[j].index == questIndex) - break; - - if (j < pql.size()) - player->SendNotifyLootItemRemoved(items.size()+j); - } - } - else - PlayersLooting.erase(i); - } -} - -void Loot::generateMoneyLoot(uint32 minAmount, uint32 maxAmount) -{ - if (maxAmount > 0) - { - if (maxAmount <= minAmount) - gold = uint32(maxAmount * sWorld->getRate(RATE_DROP_MONEY)); - else if ((maxAmount - minAmount) < 32700) - gold = uint32(urand(minAmount, maxAmount) * sWorld->getRate(RATE_DROP_MONEY)); - else - gold = uint32(urand(minAmount >> 8, maxAmount >> 8) * sWorld->getRate(RATE_DROP_MONEY)) << 8; - } -} - -LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, NotNormalLootItem* *qitem, NotNormalLootItem* *ffaitem, NotNormalLootItem* *conditem) -{ - LootItem* item = NULL; - bool is_looted = true; - if (lootSlot >= items.size()) - { - uint32 questSlot = lootSlot - items.size(); - NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID().GetCounter()); - if (itr != PlayerQuestItems.end() && questSlot < itr->second->size()) - { - NotNormalLootItem* qitem2 = &itr->second->at(questSlot); - if (qitem) - *qitem = qitem2; - item = &quest_items[qitem2->index]; - is_looted = qitem2->is_looted; - } - } - else - { - item = &items[lootSlot]; - is_looted = item->is_looted; - if (item->freeforall) - { - NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.find(player->GetGUID().GetCounter()); - if (itr != PlayerFFAItems.end()) - { - for (NotNormalLootItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) - if (iter->index == lootSlot) - { - NotNormalLootItem* ffaitem2 = (NotNormalLootItem*)&(*iter); - if (ffaitem) - *ffaitem = ffaitem2; - is_looted = ffaitem2->is_looted; - break; - } - } - } - else if (!item->conditions.empty()) - { - NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.find(player->GetGUID().GetCounter()); - if (itr != PlayerNonQuestNonFFAConditionalItems.end()) - { - for (NotNormalLootItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) - { - if (iter->index == lootSlot) - { - NotNormalLootItem* conditem2 = (NotNormalLootItem*)&(*iter); - if (conditem) - *conditem = conditem2; - is_looted = conditem2->is_looted; - break; - } - } - } - } - } - - if (is_looted) - return NULL; - - return item; -} - -uint32 Loot::GetMaxSlotInLootFor(Player* player) const -{ - NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID().GetCounter()); - return items.size() + (itr != PlayerQuestItems.end() ? itr->second->size() : 0); -} - -// return true if there is any item that is lootable for any player (not quest item, FFA or conditional) -bool Loot::hasItemForAll() const -{ - // Gold is always lootable - if (gold) - return true; - - for (LootItem const& item : items) - if (!item.is_looted && !item.freeforall && item.conditions.empty()) - return true; - return false; -} - -// return true if there is any FFA, quest or conditional item for the player. -bool Loot::hasItemFor(Player* player) const -{ - NotNormalLootItemMap const& lootPlayerQuestItems = GetPlayerQuestItems(); - NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(player->GetGUID().GetCounter()); - if (q_itr != lootPlayerQuestItems.end()) - { - NotNormalLootItemList* q_list = q_itr->second; - for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) - { - const LootItem &item = quest_items[qi->index]; - if (!qi->is_looted && !item.is_looted) - return true; - } - } - - NotNormalLootItemMap const& lootPlayerFFAItems = GetPlayerFFAItems(); - NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(player->GetGUID().GetCounter()); - if (ffa_itr != lootPlayerFFAItems.end()) - { - NotNormalLootItemList* ffa_list = ffa_itr->second; - for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) - { - const LootItem &item = items[fi->index]; - if (!fi->is_looted && !item.is_looted) - return true; - } - } - - NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = GetPlayerNonQuestNonFFAConditionalItems(); - NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(player->GetGUID().GetCounter()); - if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) - { - NotNormalLootItemList* conditional_list = nn_itr->second; - for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) - { - const LootItem &item = items[ci->index]; - if (!ci->is_looted && !item.is_looted) - return true; - } - } - - return false; -} - -// return true if there is any item over the group threshold (i.e. not underthreshold). -bool Loot::hasOverThresholdItem() const -{ - for (uint8 i = 0; i < items.size(); ++i) - { - if (!items[i].is_looted && !items[i].is_underthreshold && !items[i].freeforall) - return true; - } - - return false; -} - -ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li) -{ - b << uint32(li.itemid); - b << uint32(li.count); // nr of items of this type - b << uint32(ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(li.itemid))->DisplayInfoID); - b << uint32(li.randomSuffix); - b << uint32(li.randomPropertyId); - //b << uint8(0); // slot type - will send after this function call - return b; -} - -ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) -{ - if (lv.permission == NONE_PERMISSION) - { - b << uint32(0); // gold - b << uint8(0); // item count - return b; - } - - Loot &l = lv.loot; - - uint8 itemsShown = 0; - - b << uint32(l.gold); //gold - - size_t count_pos = b.wpos(); // pos of item count byte - b << uint8(0); // item count placeholder - - switch (lv.permission) - { - case GROUP_PERMISSION: - case MASTER_PERMISSION: - case RESTRICTED_PERMISSION: - { - // if you are not the round-robin group looter, you can only see - // blocked rolled items and quest items, and !ffa items - for (uint8 i = 0; i < l.items.size(); ++i) - { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) - { - uint8 slot_type; - - if (l.items[i].is_blocked) // for ML & restricted is_blocked = !is_underthreshold - { - switch (lv.permission) - { - case GROUP_PERMISSION: - slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; - break; - case MASTER_PERMISSION: - { - if (lv.viewer->GetGroup() && lv.viewer->GetGroup()->GetMasterLooterGuid() == lv.viewer->GetGUID()) - slot_type = LOOT_SLOT_TYPE_MASTER; - else - slot_type = LOOT_SLOT_TYPE_LOCKED; - break; - } - case RESTRICTED_PERMISSION: - slot_type = LOOT_SLOT_TYPE_LOCKED; - break; - default: - continue; - } - } - else if (!l.items[i].rollWinnerGUID.IsEmpty()) - { - if (l.items[i].rollWinnerGUID == lv.viewer->GetGUID()) - slot_type = LOOT_SLOT_TYPE_OWNER; - else - continue; - } - else if (l.roundRobinPlayer.IsEmpty() || lv.viewer->GetGUID() == l.roundRobinPlayer || !l.items[i].is_underthreshold) - { - // no round robin owner or he has released the loot - // or it IS the round robin group owner - // => item is lootable - slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; - } - else - // item shall not be displayed. - continue; - - b << uint8(i) << l.items[i]; - b << uint8(slot_type); - ++itemsShown; - } - } - break; - } - case ROUND_ROBIN_PERMISSION: - { - for (uint8 i = 0; i < l.items.size(); ++i) - { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) - { - if (!l.roundRobinPlayer.IsEmpty() && lv.viewer->GetGUID() != l.roundRobinPlayer) - // item shall not be displayed. - continue; - - b << uint8(i) << l.items[i]; - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - ++itemsShown; - } - } - break; - } - case ALL_PERMISSION: - case OWNER_PERMISSION: - { - uint8 slot_type = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; - for (uint8 i = 0; i < l.items.size(); ++i) - { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) - { - b << uint8(i) << l.items[i]; - b << uint8(slot_type); - ++itemsShown; - } - } - break; - } - default: - return b; - } - - LootSlotType slotType = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; - NotNormalLootItemMap const& lootPlayerQuestItems = l.GetPlayerQuestItems(); - NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(lv.viewer->GetGUID().GetCounter()); - if (q_itr != lootPlayerQuestItems.end()) - { - NotNormalLootItemList* q_list = q_itr->second; - for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) - { - LootItem &item = l.quest_items[qi->index]; - if (!qi->is_looted && !item.is_looted) - { - b << uint8(l.items.size() + (qi - q_list->begin())); - b << item; - if (item.follow_loot_rules) - { - switch (lv.permission) - { - case MASTER_PERMISSION: - b << uint8(LOOT_SLOT_TYPE_MASTER); - break; - case RESTRICTED_PERMISSION: - b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); - break; - case GROUP_PERMISSION: - case ROUND_ROBIN_PERMISSION: - if (!item.is_blocked) - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - else - b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); - break; - default: - b << uint8(slotType); - break; - } - } - else - b << uint8(slotType); - ++itemsShown; - } - } - } - - NotNormalLootItemMap const& lootPlayerFFAItems = l.GetPlayerFFAItems(); - NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(lv.viewer->GetGUID().GetCounter()); - if (ffa_itr != lootPlayerFFAItems.end()) - { - NotNormalLootItemList* ffa_list = ffa_itr->second; - for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) - { - LootItem &item = l.items[fi->index]; - if (!fi->is_looted && !item.is_looted) - { - b << uint8(fi->index); - b << item; - b << uint8(slotType); - ++itemsShown; - } - } - } - - NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = l.GetPlayerNonQuestNonFFAConditionalItems(); - NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(lv.viewer->GetGUID().GetCounter()); - if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) - { - NotNormalLootItemList* conditional_list = nn_itr->second; - for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) - { - LootItem &item = l.items[ci->index]; - if (!ci->is_looted && !item.is_looted) - { - b << uint8(ci->index); - b << item; - switch (lv.permission) - { - case MASTER_PERMISSION: - b << uint8(LOOT_SLOT_TYPE_MASTER); - break; - case RESTRICTED_PERMISSION: - b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); - break; - case GROUP_PERMISSION: - case ROUND_ROBIN_PERMISSION: - if (!item.is_blocked) - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - else - b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); - break; - default: - b << uint8(slotType); - break; - } - ++itemsShown; - } - } - } - - //update number of items shown - b.put(count_pos, itemsShown); - - return b; -} - // // --------- LootTemplate::LootGroup --------- // @@ -1113,7 +399,7 @@ LootStoreItem const* LootTemplate::LootGroup::Roll(Loot& loot, uint16 lootMode) if (!possibleLoot.empty()) // If nothing selected yet - an item is taken from equal-chanced part return Trinity::Containers::SelectRandomContainerElement(possibleLoot); - return NULL; // Empty drop from the group + return nullptr; // Empty drop from the group } // True if group includes at least 1 quest drop entry @@ -1239,7 +525,7 @@ void LootTemplate::AddEntry(LootStoreItem* item) if (item->groupid > 0 && item->reference == 0) // Group { if (item->groupid >= Groups.size()) - Groups.resize(item->groupid, NULL); // Adds new group the the loot template if needed + Groups.resize(item->groupid, nullptr); // Adds new group the the loot template if needed if (!Groups[item->groupid - 1]) Groups[item->groupid - 1] = new LootGroup(); @@ -1249,7 +535,7 @@ void LootTemplate::AddEntry(LootStoreItem* item) Entries.push_back(item); } -void LootTemplate::CopyConditions(const ConditionContainer& conditions) +void LootTemplate::CopyConditions(ConditionContainer const& conditions) { for (LootStoreItemList::iterator i = Entries.begin(); i != Entries.end(); ++i) (*i)->conditions.clear(); @@ -1572,10 +858,9 @@ void LoadLootTemplates_Fishing() uint32 count = LootTemplates_Fishing.LoadAndCollectLootIds(lootIdSet); // remove real entries and check existence loot - for (uint32 i = 1; i < sAreaTableStore.GetNumRows(); ++i) - if (AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(i)) - if (lootIdSet.find(areaEntry->ID) != lootIdSet.end()) - lootIdSet.erase(areaEntry->ID); + for (AreaTableEntry const* areaTable : sAreaTableStore) + if (lootIdSet.find(areaTable->ID) != lootIdSet.end()) + lootIdSet.erase(areaTable->ID); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Fishing.ReportUnusedIds(lootIdSet); @@ -1819,9 +1104,7 @@ void LoadLootTemplates_Spell() // not report about not trainable spells (optionally supported by DB) // ignore 61756 (Northrend Inscription Research (FAST QA VERSION) for example if (!spellInfo->HasAttribute(SPELL_ATTR0_NOT_SHAPESHIFT) || spellInfo->HasAttribute(SPELL_ATTR0_TRADESPELL)) - { LootTemplates_Spell.ReportNonExistingId(spell_id, "Spell", spellInfo->Id); - } } else lootIdSet.erase(spell_id); diff --git a/src/server/game/Loot/LootMgr.h b/src/server/game/Loot/LootMgr.h index 4069d5731b5..6d9d160149f 100644 --- a/src/server/game/Loot/LootMgr.h +++ b/src/server/game/Loot/LootMgr.h @@ -19,108 +19,18 @@ #ifndef TRINITY_LOOTMGR_H #define TRINITY_LOOTMGR_H -#include "ItemEnchantmentMgr.h" -#include "ByteBuffer.h" -#include "RefManager.h" -#include "SharedDefines.h" +#include "Define.h" #include "ConditionMgr.h" #include "ObjectGuid.h" -#include -#include +#include "SharedDefines.h" #include +#include -enum RollType -{ - ROLL_PASS = 0, - ROLL_NEED = 1, - ROLL_GREED = 2, - ROLL_DISENCHANT = 3, - MAX_ROLL_TYPE = 4 -}; - -enum RollMask -{ - ROLL_FLAG_TYPE_PASS = 0x01, - ROLL_FLAG_TYPE_NEED = 0x02, - ROLL_FLAG_TYPE_GREED = 0x04, - ROLL_FLAG_TYPE_DISENCHANT = 0x08, - - ROLL_ALL_TYPE_NO_DISENCHANT = 0x07, - ROLL_ALL_TYPE_MASK = 0x0F -}; - -#define MAX_NR_LOOT_ITEMS 16 -// note: the client cannot show more than 16 items total -#define MAX_NR_QUEST_ITEMS 32 -// unrelated to the number of quest items shown, just for reserve - -enum LootMethod : uint8 -{ - FREE_FOR_ALL = 0, - ROUND_ROBIN = 1, - MASTER_LOOT = 2, - GROUP_LOOT = 3, - NEED_BEFORE_GREED = 4 -}; - -enum PermissionTypes -{ - ALL_PERMISSION = 0, - GROUP_PERMISSION = 1, - MASTER_PERMISSION = 2, - RESTRICTED_PERMISSION = 3, - ROUND_ROBIN_PERMISSION = 4, - OWNER_PERMISSION = 5, - NONE_PERMISSION = 6 -}; - -enum LootType : uint8 -{ - LOOT_NONE = 0, - - LOOT_CORPSE = 1, - LOOT_PICKPOCKETING = 2, - LOOT_FISHING = 3, - LOOT_DISENCHANTING = 4, - // ignored always by client - LOOT_SKINNING = 6, - LOOT_PROSPECTING = 7, - LOOT_MILLING = 8, - - LOOT_FISHINGHOLE = 20, // unsupported by client, sending LOOT_FISHING instead - LOOT_INSIGNIA = 21, // unsupported by client, sending LOOT_CORPSE instead - LOOT_FISHING_JUNK = 22 // unsupported by client, sending LOOT_FISHING instead -}; - -enum LootError -{ - LOOT_ERROR_DIDNT_KILL = 0, // You don't have permission to loot that corpse. - LOOT_ERROR_TOO_FAR = 4, // You are too far away to loot that corpse. - LOOT_ERROR_BAD_FACING = 5, // You must be facing the corpse to loot it. - LOOT_ERROR_LOCKED = 6, // Someone is already looting that corpse. - LOOT_ERROR_NOTSTANDING = 8, // You need to be standing up to loot something! - LOOT_ERROR_STUNNED = 9, // You can't loot anything while stunned! - LOOT_ERROR_PLAYER_NOT_FOUND = 10, // Player not found - LOOT_ERROR_PLAY_TIME_EXCEEDED = 11, // Maximum play time exceeded - LOOT_ERROR_MASTER_INV_FULL = 12, // That player's inventory is full - LOOT_ERROR_MASTER_UNIQUE_ITEM = 13, // Player has too many of that item already - LOOT_ERROR_MASTER_OTHER = 14, // Can't assign item to that player - LOOT_ERROR_ALREADY_PICKPOCKETED = 15, // Your target has already had its pockets picked - LOOT_ERROR_NOT_WHILE_SHAPESHIFTED = 16 // You can't do that while shapeshifted. -}; - -// type of Loot Item in Loot View -enum LootSlotType -{ - LOOT_SLOT_TYPE_ALLOW_LOOT = 0, // player can loot the item. - LOOT_SLOT_TYPE_ROLL_ONGOING = 1, // roll is ongoing. player cannot loot. - LOOT_SLOT_TYPE_MASTER = 2, // item can only be distributed by group loot master. - LOOT_SLOT_TYPE_LOCKED = 3, // item is shown in red. player cannot loot. - LOOT_SLOT_TYPE_OWNER = 4 // ignore binding confirmation and etc, for single player looting -}; - -class Player; class LootStore; +class LootTemplate; +class Player; +struct Loot; +struct LootItem; struct TC_GAME_API LootStoreItem { @@ -128,8 +38,8 @@ struct TC_GAME_API LootStoreItem uint32 reference; // referenced TemplateleId float chance; // chance to drop for both quest and non-quest items, chance to be used for refs uint16 lootmode; - bool needs_quest : 1; // quest drop (quest is required for item to drop) - uint8 groupid : 7; + bool needs_quest; // quest drop (quest is required for item to drop) + uint8 groupid; uint8 mincount; // mincount for drop items uint8 maxcount; // max drop count for the item mincount or Ref multiplicator ConditionContainer conditions; // additional loot condition @@ -146,58 +56,6 @@ struct TC_GAME_API LootStoreItem // Checks correctness of values }; -typedef std::set AllowedLooterSet; - -struct TC_GAME_API LootItem -{ - uint32 itemid; - uint32 randomSuffix; - int32 randomPropertyId; - ConditionContainer conditions; // additional loot condition - AllowedLooterSet allowedGUIDs; - ObjectGuid rollWinnerGUID; // Stores the guid of person who won loot, if his bags are full only he can see the item in loot list! - uint8 count : 8; - bool is_looted : 1; - bool is_blocked : 1; - bool freeforall : 1; // free for all - bool is_underthreshold : 1; - bool is_counted : 1; - bool needs_quest : 1; // quest drop - bool follow_loot_rules : 1; - - // Constructor, copies most fields from LootStoreItem, generates random count and random suffixes/properties - // Should be called for non-reference LootStoreItem entries only (reference = 0) - explicit LootItem(LootStoreItem const& li); - - // Empty constructor for creating an empty LootItem to be filled in with DB data - LootItem() : itemid(0), randomSuffix(0), randomPropertyId(0), count(0), is_looted(false), is_blocked(false), - freeforall(false), is_underthreshold(false), is_counted(false), needs_quest(false), follow_loot_rules(false) - { }; - - // Basic checks for player/item compatibility - if false no chance to see the item in the loot - bool AllowedForPlayer(Player const* player) const; - void AddAllowedLooter(Player const* player); - const AllowedLooterSet & GetAllowedLooters() const { return allowedGUIDs; } -}; - -struct NotNormalLootItem -{ - uint8 index; // position in quest_items or items; - bool is_looted; - - NotNormalLootItem() - : index(0), is_looted(false) { } - - NotNormalLootItem(uint8 _index, bool _islooted = false) - : index(_index), is_looted(_islooted) { } -}; - -struct Loot; -class LootTemplate; - -typedef std::vector NotNormalLootItemList; -typedef std::vector LootItemList; -typedef std::map NotNormalLootItemMap; typedef std::list LootStoreItemList; typedef std::unordered_map LootTemplateMap; @@ -214,9 +72,9 @@ class TC_GAME_API LootStore void Verify() const; uint32 LoadAndCollectLootIds(LootIdSet& ids_set); - void CheckLootRefs(LootIdSet* ref_set = NULL) const; // check existence reference and remove it from ref_set + void CheckLootRefs(LootIdSet* ref_set = nullptr) const; // check existence reference and remove it from ref_set void ReportUnusedIds(LootIdSet const& ids_set) const; - void ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const; + void ReportNonExistingId(uint32 lootId, char const* ownerType, uint32 ownerId) const; bool HaveLootFor(uint32 loot_id) const { return m_LootTemplates.find(loot_id) != m_LootTemplates.end(); } bool HaveQuestLootFor(uint32 loot_id) const; @@ -252,7 +110,7 @@ class TC_GAME_API LootTemplate void AddEntry(LootStoreItem* item); // Rolls for every item in the template and adds the rolled items the the loot void Process(Loot& loot, bool rate, uint16 lootMode, uint8 groupId = 0) const; - void CopyConditions(const ConditionContainer& conditions); + void CopyConditions(ConditionContainer const& conditions); void CopyConditions(LootItem* li) const; // True if template includes at least 1 quest drop entry @@ -277,132 +135,6 @@ class TC_GAME_API LootTemplate //===================================================== -class LootValidatorRef : public Reference -{ - public: - LootValidatorRef() { } - void targetObjectDestroyLink() override { } - void sourceObjectDestroyLink() override { } -}; - -//===================================================== - -class LootValidatorRefManager : public RefManager -{ - public: - typedef LinkedListHead::Iterator< LootValidatorRef > iterator; - - LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager::getFirst(); } - - iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(nullptr); } -}; - -//===================================================== -struct LootView; - -ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li); -ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); - -struct TC_GAME_API Loot -{ - friend ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); - - NotNormalLootItemMap const& GetPlayerQuestItems() const { return PlayerQuestItems; } - NotNormalLootItemMap const& GetPlayerFFAItems() const { return PlayerFFAItems; } - NotNormalLootItemMap const& GetPlayerNonQuestNonFFAConditionalItems() const { return PlayerNonQuestNonFFAConditionalItems; } - - std::vector items; - std::vector quest_items; - uint32 gold; - uint8 unlootedCount; - ObjectGuid roundRobinPlayer; // GUID of the player having the Round-Robin ownership for the loot. If 0, round robin owner has released. - LootType loot_type; // required for achievement system - uint8 maxDuplicates; // Max amount of items with the same entry that can drop (default is 1; on 25 man raid mode 3) - - // GUIDLow of container that holds this loot (item_instance.entry) - // Only set for inventory items that can be right-click looted - uint32 containerID; - - Loot(uint32 _gold = 0) : gold(_gold), unlootedCount(0), roundRobinPlayer(), loot_type(LOOT_NONE), maxDuplicates(1), containerID(0) { } - ~Loot() { clear(); } - - // if loot becomes invalid this reference is used to inform the listener - void addLootValidatorRef(LootValidatorRef* pLootValidatorRef) - { - i_LootValidatorRefManager.insertFirst(pLootValidatorRef); - } - - // void clear(); - void clear() - { - for (NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.begin(); itr != PlayerQuestItems.end(); ++itr) - delete itr->second; - PlayerQuestItems.clear(); - - for (NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.begin(); itr != PlayerFFAItems.end(); ++itr) - delete itr->second; - PlayerFFAItems.clear(); - - for (NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.begin(); itr != PlayerNonQuestNonFFAConditionalItems.end(); ++itr) - delete itr->second; - PlayerNonQuestNonFFAConditionalItems.clear(); - - PlayersLooting.clear(); - items.clear(); - quest_items.clear(); - gold = 0; - unlootedCount = 0; - roundRobinPlayer.Clear(); - loot_type = LOOT_NONE; - i_LootValidatorRefManager.clearReferences(); - } - - bool empty() const { return items.empty() && gold == 0; } - bool isLooted() const { return gold == 0 && unlootedCount == 0; } - - void NotifyItemRemoved(uint8 lootIndex); - void NotifyQuestItemRemoved(uint8 questIndex); - void NotifyMoneyRemoved(); - void AddLooter(ObjectGuid GUID) { PlayersLooting.insert(GUID); } - void RemoveLooter(ObjectGuid GUID) { PlayersLooting.erase(GUID); } - - void generateMoneyLoot(uint32 minAmount, uint32 maxAmount); - bool FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError = false, uint16 lootMode = LOOT_MODE_DEFAULT); - - // Inserts the item into the loot (called by LootTemplate processors) - void AddItem(LootStoreItem const & item); - - LootItem* LootItemInSlot(uint32 lootslot, Player* player, NotNormalLootItem** qitem = NULL, NotNormalLootItem** ffaitem = NULL, NotNormalLootItem** conditem = NULL); - uint32 GetMaxSlotInLootFor(Player* player) const; - bool hasItemForAll() const; - bool hasItemFor(Player* player) const; - bool hasOverThresholdItem() const; - - private: - void FillNotNormalLootFor(Player* player, bool presentAtLooting); - NotNormalLootItemList* FillFFALoot(Player* player); - NotNormalLootItemList* FillQuestLoot(Player* player); - NotNormalLootItemList* FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting); - - GuidSet PlayersLooting; - NotNormalLootItemMap PlayerQuestItems; - NotNormalLootItemMap PlayerFFAItems; - NotNormalLootItemMap PlayerNonQuestNonFFAConditionalItems; - - // All rolls are registered here. They need to know, when the loot is not valid anymore - LootValidatorRefManager i_LootValidatorRefManager; -}; - -struct LootView -{ - Loot &loot; - Player* viewer; - PermissionTypes permission; - LootView(Loot &_loot, Player* _viewer, PermissionTypes _permission = ALL_PERMISSION) - : loot(_loot), viewer(_viewer), permission(_permission) { } -}; - TC_GAME_API extern LootStore LootTemplates_Creature; TC_GAME_API extern LootStore LootTemplates_Fishing; TC_GAME_API extern LootStore LootTemplates_Gameobject; diff --git a/src/server/game/Mails/Mail.cpp b/src/server/game/Mails/Mail.cpp index fe642aae1e6..780b98346ac 100644 --- a/src/server/game/Mails/Mail.cpp +++ b/src/server/game/Mails/Mail.cpp @@ -16,17 +16,19 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "Mail.h" -#include "Log.h" -#include "World.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "BattlegroundMgr.h" -#include "Item.h" #include "AuctionHouseMgr.h" +#include "BattlegroundMgr.h" #include "CalendarMgr.h" #include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "Item.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "World.h" MailSender::MailSender(Object* sender, MailStationery stationery) : m_stationery(stationery) { @@ -188,7 +190,7 @@ void MailDraft::SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, uint32 mailId = sObjectMgr->GenerateMailID(); - time_t deliver_time = time(NULL) + deliver_delay; + time_t deliver_time = time(nullptr) + deliver_delay; //expire time if COD 3 days, if no COD 30 days, if auction sale pending 1 hour uint32 expire_delay; @@ -279,13 +281,13 @@ void MailDraft::SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, } else if (!m_items.empty()) { - SQLTransaction temp = SQLTransaction(NULL); + SQLTransaction temp = SQLTransaction(nullptr); deleteIncludedItems(temp); } } else if (!m_items.empty()) { - SQLTransaction temp = SQLTransaction(NULL); + SQLTransaction temp = SQLTransaction(nullptr); deleteIncludedItems(temp); } } diff --git a/src/server/game/Mails/Mail.h b/src/server/game/Mails/Mail.h index a7b46eef570..7a71867958e 100644 --- a/src/server/game/Mails/Mail.h +++ b/src/server/game/Mails/Mail.h @@ -20,6 +20,7 @@ #define TRINITY_MAIL_H #include "Common.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" #include @@ -104,7 +105,7 @@ class TC_GAME_API MailSender class TC_GAME_API MailReceiver { public: // Constructors - explicit MailReceiver(ObjectGuid::LowType receiver_lowguid) : m_receiver(NULL), m_receiver_lowguid(receiver_lowguid) { } + explicit MailReceiver(ObjectGuid::LowType receiver_lowguid) : m_receiver(nullptr), m_receiver_lowguid(receiver_lowguid) { } MailReceiver(Player* receiver); MailReceiver(Player* receiver, ObjectGuid::LowType receiver_lowguid); public: // Accessors diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index 4e9f9e27862..0793422f8ad 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -17,25 +17,31 @@ */ #include "Map.h" -#include "MapManager.h" #include "Battleground.h" -#include "MMapFactory.h" #include "CellImpl.h" +#include "DatabaseEnv.h" #include "DisableMgr.h" #include "DynamicTree.h" +#include "GameObjectModel.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "GridStates.h" #include "Group.h" #include "InstanceScript.h" +#include "Log.h" #include "MapInstanced.h" +#include "MapManager.h" +#include "MMapFactory.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" +#include "ObjectGridLoader.h" #include "ObjectMgr.h" #include "Pet.h" #include "ScriptMgr.h" #include "Transport.h" #include "Vehicle.h" #include "VMapFactory.h" +#include "World.h" u_map_magic MapMagic = { {'M','A','P','S'} }; u_map_magic MapVersionMagic = { {'v','1','.','8'} }; @@ -188,11 +194,11 @@ void Map::LoadMap(int gx, int gy, bool reload) sScriptMgr->OnUnloadGridMap(this, GridMaps[gx][gy], gx, gy); delete (GridMaps[gx][gy]); - GridMaps[gx][gy]=NULL; + GridMaps[gx][gy]=nullptr; } // map file name - char* tmp = NULL; + char* tmp = nullptr; int len = sWorld->GetDataPath().length() + strlen("maps/%03u%02u%02u.map") + 1; tmp = new char[len]; snprintf(tmp, len, (char *)(sWorld->GetDataPath() + "maps/%03u%02u%02u.map").c_str(), GetId(), gx, gy); @@ -255,8 +261,8 @@ i_scriptLock(false), _defaultLight(GetDefaultMapLight(id)) for (unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j) { //z code - GridMaps[idx][j] =NULL; - setNGrid(NULL, idx, j); + GridMaps[idx][j] =nullptr; + setNGrid(nullptr, idx, j); } } @@ -361,7 +367,7 @@ void Map::SwitchGridContainers(Creature* obj, bool on) } NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(ngrid != NULL); + ASSERT(ngrid != nullptr); GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); @@ -406,7 +412,7 @@ void Map::SwitchGridContainers(GameObject* obj, bool on) } NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(ngrid != NULL); + ASSERT(ngrid != nullptr); GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); @@ -446,7 +452,7 @@ void Map::DeleteFromWorld(Transport* transport) delete transport; } -void Map::EnsureGridCreated(const GridCoord &p) +void Map::EnsureGridCreated(GridCoord const& p) { std::lock_guard lock(_gridLock); EnsureGridCreated_i(p); @@ -454,7 +460,7 @@ void Map::EnsureGridCreated(const GridCoord &p) //Create NGrid so the object can be added to it //But object data is not loaded here -void Map::EnsureGridCreated_i(const GridCoord &p) +void Map::EnsureGridCreated_i(GridCoord const& p) { if (!getNGrid(p.x_coord, p.y_coord)) { @@ -478,11 +484,11 @@ void Map::EnsureGridCreated_i(const GridCoord &p) } //Load NGrid and make it active -void Map::EnsureGridLoadedForActiveObject(const Cell &cell, WorldObject* object) +void Map::EnsureGridLoadedForActiveObject(Cell const& cell, WorldObject* object) { EnsureGridLoaded(cell); NGridType *grid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(grid != NULL); + ASSERT(grid != nullptr); // refresh grid state & timer if (grid->GetGridState() != GRID_STATE_ACTIVE) @@ -494,12 +500,12 @@ void Map::EnsureGridLoadedForActiveObject(const Cell &cell, WorldObject* object) } //Create NGrid and load the object data in it -bool Map::EnsureGridLoaded(const Cell &cell) +bool Map::EnsureGridLoaded(Cell const& cell) { EnsureGridCreated(GridCoord(cell.GridX(), cell.GridY())); NGridType *grid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(grid != NULL); + ASSERT(grid != nullptr); if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY())) { TC_LOG_DEBUG("maps", "Loading grid[%u, %u] for map %u instance %u", cell.GridX(), cell.GridY(), GetId(), i_InstanceId); @@ -649,7 +655,7 @@ bool Map::AddToMap(Transport* obj) return true; } -bool Map::IsGridLoaded(const GridCoord &p) const +bool Map::IsGridLoaded(GridCoord const& p) const { return (getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord)); } @@ -683,7 +689,7 @@ void Map::VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitorRemoveGridMapReference(GridCoord(gx, gy)); - GridMaps[gx][gy] = NULL; + GridMaps[gx][gy] = nullptr; } TC_LOG_DEBUG("maps", "Unloading grid[%u, %u] for map %u finished", x, y, GetId()); return true; @@ -1707,7 +1713,7 @@ GridMap::~GridMap() unloadData(); } -bool GridMap::loadData(const char* filename) +bool GridMap::loadData(char const* filename) { // Unload old data if exist unloadData(); @@ -2319,7 +2325,7 @@ inline GridMap* Map::GetGrid(float x, float y) return GridMaps[gx][gy]; } -float Map::GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground /*= NULL*/, bool /*swim = false*/) const +float Map::GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground /*= nullptr*/, bool /*swim = false*/) const { if (const_cast(this)->GetGrid(x, y)) { @@ -2800,7 +2806,7 @@ void Map::SendInitSelf(Player* player) WorldPacket packet; data.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Map::SendInitTransports(Player* player) @@ -2813,7 +2819,7 @@ void Map::SendInitTransports(Player* player) WorldPacket packet; transData.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Map::SendRemoveTransports(Player* player) @@ -2826,7 +2832,7 @@ void Map::SendRemoveTransports(Player* player) WorldPacket packet; transData.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y) @@ -2856,12 +2862,12 @@ void Map::SendObjectUpdates() for (UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter) { iter->second.BuildPacket(&packet); - iter->first->GetSession()->SendPacket(&packet); + iter->first->SendDirectMessage(&packet); packet.clear(); // clean the string } } -void Map::DelayedUpdate(const uint32 t_diff) +void Map::DelayedUpdate(uint32 t_diff) { for (_transportsUpdateIter = _transports.begin(); _transportsUpdateIter != _transports.end();) { @@ -3001,7 +3007,7 @@ uint32 Map::GetPlayersCountExceptGMs() const void Map::SendToPlayers(WorldPacket* data) const { for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); } bool Map::ActiveObjectsNearGrid(NGridType const& ngrid) const @@ -3121,7 +3127,7 @@ template TC_GAME_API void Map::RemoveFromMap(DynamicObject*, bool); InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent) : Map(id, expiry, InstanceId, SpawnMode, _parent), m_resetAfterUnload(false), m_unloadWhenEmpty(false), - i_data(NULL), i_script_id(0) + i_data(nullptr), i_script_id(0) { //lets initialize visibility distance for dungeons InstanceMap::InitVisibilityDistance(); @@ -3134,7 +3140,7 @@ InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 Spaw InstanceMap::~InstanceMap() { delete i_data; - i_data = NULL; + i_data = nullptr; } void InstanceMap::InitVisibilityDistance() @@ -3203,7 +3209,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) // increase current instances (hourly limit) if (!group || !group->isLFGGroup()) - player->AddInstanceEnterTime(GetInstanceId(), time(NULL)); + player->AddInstanceEnterTime(GetInstanceId(), time(nullptr)); // get or create an instance save for the map InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(GetInstanceId()); @@ -3264,7 +3270,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) data << uint32(60000); data << uint32(i_data ? i_data->GetCompletedEncounterMask() : 0); data << uint8(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); player->SetPendingBind(mapSave->GetInstanceId(), 60000); } } @@ -3301,7 +3307,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) return true; } -void InstanceMap::Update(const uint32 t_diff) +void InstanceMap::Update(uint32 t_diff) { Map::Update(t_diff); @@ -3323,7 +3329,7 @@ void InstanceMap::RemovePlayerFromMap(Player* player, bool remove) void InstanceMap::CreateInstanceData(bool load) { - if (i_data != NULL) + if (i_data != nullptr) return; InstanceTemplate const* mInstance = sObjectMgr->GetInstanceTemplate(GetId()); @@ -3414,6 +3420,11 @@ bool InstanceMap::Reset(uint8 method) return m_mapRefManager.isEmpty(); } +std::string const& InstanceMap::GetScriptName() const +{ + return sObjectMgr->GetScriptName(i_script_id); +} + void InstanceMap::PermBindAllPlayers() { if (!IsDungeon()) @@ -3451,7 +3462,7 @@ void InstanceMap::PermBindAllPlayers() player->BindToInstance(save, true); WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4); data << uint32(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); player->GetSession()->SendCalendarRaidLockout(save, true); // if group leader is in instance, group also gets bound @@ -3501,6 +3512,74 @@ MapDifficulty const* Map::GetMapDifficulty() const return GetMapDifficultyData(GetId(), GetDifficulty()); } +uint32 Map::GetId() const +{ + return i_mapEntry->MapID; +} + +bool Map::IsRegularDifficulty() const +{ + return GetDifficulty() == REGULAR_DIFFICULTY; +} + +bool Map::Instanceable() const +{ + return i_mapEntry && i_mapEntry->Instanceable(); +} + +bool Map::IsDungeon() const +{ + return i_mapEntry && i_mapEntry->IsDungeon(); +} + +bool Map::IsNonRaidDungeon() const +{ + return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); +} + +bool Map::IsRaid() const +{ + return i_mapEntry && i_mapEntry->IsRaid(); +} + +bool Map::IsRaidOrHeroicDungeon() const +{ + return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; +} + +bool Map::IsHeroic() const +{ + return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; +} + +bool Map::Is25ManRaid() const +{ + // since 25man difficulties are 1 and 3, we can check them like that + return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; +} + +bool Map::IsBattleground() const +{ + return i_mapEntry && i_mapEntry->IsBattleground(); +} + +bool Map::IsBattleArena() const +{ + return i_mapEntry && i_mapEntry->IsBattleArena(); +} + +bool Map::IsBattlegroundOrArena() const +{ + return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); +} + +bool Map::GetEntrancePos(int32& mapid, float& x, float& y) const +{ + if (!i_mapEntry) + return false; + return i_mapEntry->GetEntrancePos(mapid, x, y); +} + bool InstanceMap::HasPermBoundPlayers() const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PERM_BIND_BY_INSTANCE); @@ -3526,7 +3605,7 @@ uint32 InstanceMap::GetMaxResetDelay() const /* ******* Battleground Instance Maps ******* */ BattlegroundMap::BattlegroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode) - : Map(id, expiry, InstanceId, spawnMode, _parent), m_bg(NULL) + : Map(id, expiry, InstanceId, spawnMode, _parent), m_bg(nullptr) { //lets initialize visibility distance for BG/Arenas BattlegroundMap::InitVisibilityDistance(); @@ -3537,8 +3616,8 @@ BattlegroundMap::~BattlegroundMap() if (m_bg) { //unlink to prevent crash, always unlink all pointer reference before destruction - m_bg->SetBgMap(NULL); - m_bg = NULL; + m_bg->SetBgMap(nullptr); + m_bg = nullptr; } } @@ -3627,10 +3706,10 @@ Pet* Map::GetPet(ObjectGuid const& guid) Transport* Map::GetTransport(ObjectGuid const& guid) { if (!guid.IsMOTransport()) - return NULL; + return nullptr; GameObject* go = GetGameObject(guid); - return go ? go->ToTransport() : NULL; + return go ? go->ToTransport() : nullptr; } DynamicObject* Map::GetDynamicObject(ObjectGuid const& guid) @@ -3863,7 +3942,7 @@ Corpse* Map::ConvertCorpseToBones(ObjectGuid const& ownerGuid, bool insignia /*= corpse->DeleteFromDB(trans); CharacterDatabase.CommitTransaction(trans); - Corpse* bones = NULL; + Corpse* bones = nullptr; // create the bones only if the map and the grid is loaded at the corpse's location // ignore bones creating option in case insignia @@ -4032,10 +4111,14 @@ void Map::UpdateAreaDependentAuras() { Map::PlayerList const& players = GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + { if (Player* player = itr->GetSource()) + { if (player->IsInWorld()) { player->UpdateAreaDependentAuras(player->GetAreaId()); player->UpdateZoneDependentAuras(player->GetZoneId()); } + } + } } diff --git a/src/server/game/Maps/Map.h b/src/server/game/Maps/Map.h index 1a61e65bade..dd0e43158c1 100644 --- a/src/server/game/Maps/Map.h +++ b/src/server/game/Maps/Map.h @@ -21,7 +21,6 @@ #include "Define.h" -#include "DBCStructure.h" #include "GridDefines.h" #include "Cell.h" #include "Timer.h" @@ -29,31 +28,37 @@ #include "GridRefManager.h" #include "MapRefManager.h" #include "DynamicTree.h" -#include "GameObjectModel.h" #include "ObjectGuid.h" +#include "Optional.h" #include #include #include +#include -class Unit; -class WorldPacket; -class InstanceScript; +class Battleground; +class BattlegroundMap; +class CreatureGroup; +class GameObjectModel; class Group; +class InstanceMap; class InstanceSave; +class InstanceScript; +class MapInstanced; class Object; -class WorldObject; -class TempSummon; class Player; -class CreatureGroup; -struct ScriptInfo; -struct ScriptAction; -struct Position; -class Battleground; -class MapInstanced; -class BattlegroundMap; -class InstanceMap; +class TempSummon; class Transport; +class Unit; +class WorldObject; +class WorldPacket; +struct MapDifficulty; +struct MapEntry; +struct Position; +struct ScriptAction; +struct ScriptInfo; +struct SummonPropertiesEntry; +enum Difficulty : uint8; namespace Trinity { struct ObjectUpdater; } namespace VMAP { enum class ModelIgnoreFlags : uint32; } @@ -127,7 +132,7 @@ struct map_liquidHeader float liquidLevel; }; -enum ZLiquidStatus +enum ZLiquidStatus : uint32 { LIQUID_MAP_NO_WATER = 0x00000000, LIQUID_MAP_ABOVE_WATER = 0x00000001, @@ -176,14 +181,6 @@ struct PositionFullTerrainStatus Optional liquidInfo; }; -enum LineOfSightChecks -{ - LINEOFSIGHT_CHECK_VMAP = 0x1, // check static floor layout data - LINEOFSIGHT_CHECK_GOBJECT = 0x2, // check dynamic game object data - - LINEOFSIGHT_ALL_CHECKS = (LINEOFSIGHT_CHECK_VMAP | LINEOFSIGHT_CHECK_GOBJECT) -}; - class TC_GAME_API GridMap { uint32 _flags; @@ -234,7 +231,7 @@ class TC_GAME_API GridMap public: GridMap(); ~GridMap(); - bool loadData(const char* filename); + bool loadData(char const* filename); void unloadData(); uint16 getArea(float x, float y) const; @@ -247,13 +244,6 @@ public: #pragma pack(push, 1) -struct InstanceTemplate -{ - uint32 Parent; - uint32 ScriptId; - bool AllowMount; -}; - enum LevelRequirementVsMode { LEVELREQUIREMENT_HEROIC = 70 @@ -287,7 +277,7 @@ class TC_GAME_API Map : public GridRefManager { friend class MapReference; public: - Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent = NULL); + Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent = nullptr); virtual ~Map(); MapEntry const* GetEntry() const { return i_mapEntry; } @@ -312,7 +302,7 @@ class TC_GAME_API Map : public GridRefManager template void RemoveFromMap(T *, bool); void VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor &gridVisitor, TypeContainerVisitor &worldVisitor); - virtual void Update(const uint32); + virtual void Update(uint32); float GetVisibilityRange() const { return m_VisibleDistance; } //function for setting up visibility distance for maps on per-type/per-Id basis @@ -324,7 +314,7 @@ class TC_GAME_API Map : public GridRefManager void DynamicObjectRelocation(DynamicObject* go, float x, float y, float z, float orientation); template - void Visit(const Cell& cell, TypeContainerVisitor &visitor); + void Visit(Cell const& cell, TypeContainerVisitor& visitor); bool IsRemovalGrid(float x, float y) const { @@ -337,8 +327,8 @@ class TC_GAME_API Map : public GridRefManager return IsGridLoaded(Trinity::ComputeGridCoord(x, y)); } - bool GetUnloadLock(const GridCoord &p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadLock(); } - void SetUnloadLock(const GridCoord &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadExplicitLock(on); } + bool GetUnloadLock(GridCoord const& p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadLock(); } + void SetUnloadLock(GridCoord const& p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadExplicitLock(on); } void LoadGrid(float x, float y); void LoadAllCells(); bool UnloadGrid(NGridType& ngrid, bool pForce); @@ -350,7 +340,7 @@ class TC_GAME_API Map : public GridRefManager } time_t GetGridExpiry(void) const { return i_gridExpiry; } - uint32 GetId(void) const { return i_mapEntry->MapID; } + uint32 GetId() const; static bool ExistMap(uint32 mapid, int gx, int gy); static bool ExistVMap(uint32 mapid, int gx, int gy); @@ -412,33 +402,28 @@ class TC_GAME_API Map : public GridRefManager CANNOT_ENTER_UNSPECIFIED_REASON }; virtual EnterState CannotEnter(Player* /*player*/) { return CAN_ENTER; } - const char* GetMapName() const; + char const* GetMapName() const; // have meaning only for instanced map (that have set real difficulty) Difficulty GetDifficulty() const { return Difficulty(GetSpawnMode()); } - bool IsRegularDifficulty() const { return GetDifficulty() == REGULAR_DIFFICULTY; } + bool IsRegularDifficulty() const; MapDifficulty const* GetMapDifficulty() const; - bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); } - bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); } - bool IsNonRaidDungeon() const { return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); } - bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); } - bool IsRaidOrHeroicDungeon() const { return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; } - bool IsHeroic() const { return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; } - bool Is25ManRaid() const { return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; } // since 25man difficulties are 1 and 3, we can check them like that - bool IsBattleground() const { return i_mapEntry && i_mapEntry->IsBattleground(); } - bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); } - bool IsBattlegroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); } - bool GetEntrancePos(int32 &mapid, float &x, float &y) - { - if (!i_mapEntry) - return false; - return i_mapEntry->GetEntrancePos(mapid, x, y); - } + bool Instanceable() const; + bool IsDungeon() const; + bool IsNonRaidDungeon() const; + bool IsRaid() const; + bool IsRaidOrHeroicDungeon() const; + bool IsHeroic() const; + bool Is25ManRaid() const; + bool IsBattleground() const; + bool IsBattleArena() const; + bool IsBattlegroundOrArena() const; + bool GetEntrancePos(int32& mapid, float& x, float& y) const; void AddObjectToRemoveList(WorldObject* obj); void AddObjectToSwitchList(WorldObject* obj, bool on); - virtual void DelayedUpdate(const uint32 diff); + virtual void DelayedUpdate(uint32 diff); void resetMarkedCells() { marked_cells.reset(); } bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); } @@ -509,22 +494,22 @@ class TC_GAME_API Map : public GridRefManager return nullptr; } - MapInstanced* ToMapInstanced() { if (Instanceable()) return reinterpret_cast(this); return NULL; } - MapInstanced const* ToMapInstanced() const { if (Instanceable()) return reinterpret_cast(this); return NULL; } + MapInstanced* ToMapInstanced() { if (Instanceable()) return reinterpret_cast(this); return nullptr; } + MapInstanced const* ToMapInstanced() const { if (Instanceable()) return reinterpret_cast(this); return nullptr; } - InstanceMap* ToInstanceMap() { if (IsDungeon()) return reinterpret_cast(this); else return NULL; } - InstanceMap const* ToInstanceMap() const { if (IsDungeon()) return reinterpret_cast(this); return NULL; } + InstanceMap* ToInstanceMap() { if (IsDungeon()) return reinterpret_cast(this); else return nullptr; } + InstanceMap const* ToInstanceMap() const { if (IsDungeon()) return reinterpret_cast(this); return nullptr; } - BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast(this); else return NULL; } - BattlegroundMap const* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast(this); return NULL; } + BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast(this); else return nullptr; } + BattlegroundMap const* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast(this); return nullptr; } - float GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground = NULL, bool swim = false) const; + float GetWaterOrGroundLevel(uint32 phasemask, float x, float y, float z, float* ground = nullptr, bool swim = false) const; float GetHeight(uint32 phasemask, float x, float y, float z, bool vmap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; bool isInLineOfSight(float x1, float y1, float z1, float x2, float y2, float z2, uint32 phasemask, LineOfSightChecks checks, VMAP::ModelIgnoreFlags ignoreFlags) const; void Balance() { _dynamicTree.balance(); } - void RemoveGameObjectModel(const GameObjectModel& model) { _dynamicTree.remove(model); } - void InsertGameObjectModel(const GameObjectModel& model) { _dynamicTree.insert(model); } - bool ContainsGameObjectModel(const GameObjectModel& model) const { return _dynamicTree.contains(model);} + void RemoveGameObjectModel(GameObjectModel const& model) { _dynamicTree.remove(model); } + void InsertGameObjectModel(GameObjectModel const& model) { _dynamicTree.insert(model); } + bool ContainsGameObjectModel(GameObjectModel const& model) const { return _dynamicTree.contains(model);} float GetGameObjectFloor(uint32 phasemask, float x, float y, float z, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const { return _dynamicTree.getHeight(x, y, z, maxSearchDist, phasemask); @@ -636,9 +621,9 @@ class TC_GAME_API Map : public GridRefManager bool _dynamicObjectsToMoveLock; std::vector _dynamicObjectsToMove; - bool IsGridLoaded(const GridCoord &) const; - void EnsureGridCreated(const GridCoord &); - void EnsureGridCreated_i(const GridCoord &); + bool IsGridLoaded(GridCoord const&) const; + void EnsureGridCreated(GridCoord const&); + void EnsureGridCreated_i(GridCoord const&); bool EnsureGridLoaded(Cell const&); void EnsureGridLoadedForActiveObject(Cell const&, WorldObject* object); @@ -656,12 +641,10 @@ class TC_GAME_API Map : public GridRefManager void setNGrid(NGridType* grid, uint32 x, uint32 y); void ScriptsProcess(); - void UpdateActiveCells(const float &x, const float &y, const uint32 t_diff); - void SendObjectUpdates(); protected: - void SetUnloadReferenceLock(const GridCoord &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadReferenceLock(on); } + void SetUnloadReferenceLock(GridCoord const& p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadReferenceLock(on); } std::mutex _mapLock; std::mutex _gridLock; @@ -688,13 +671,13 @@ class TC_GAME_API Map : public GridRefManager TransportsContainer::iterator _transportsUpdateIter; private: - Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const; - Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse = false) const; - Unit* _GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - Player* _GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - Creature* _GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - void _ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const; + Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo) const; + Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo, bool bReverse = false) const; + Unit* _GetScriptUnit(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + Player* _GetScriptPlayer(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + Creature* _GetScriptCreature(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + void _ScriptProcessDoor(Object* source, Object* target, ScriptInfo const* scriptInfo) const; GameObject* _FindGameObject(WorldObject* pWorldObject, ObjectGuid::LowType guid) const; time_t i_gridExpiry; @@ -791,10 +774,11 @@ class TC_GAME_API InstanceMap : public Map ~InstanceMap(); bool AddPlayerToMap(Player*) override; void RemovePlayerFromMap(Player*, bool) override; - void Update(const uint32) override; + void Update(uint32) override; void CreateInstanceData(bool load); bool Reset(uint8 method); uint32 GetScriptId() const { return i_script_id; } + std::string const& GetScriptName() const; InstanceScript* GetInstanceScript() { return i_data; } InstanceScript const* GetInstanceScript() const { return i_data; } void PermBindAllPlayers(); diff --git a/src/server/game/Maps/MapInstanced.cpp b/src/server/game/Maps/MapInstanced.cpp index d54e758e581..4b8863889a1 100644 --- a/src/server/game/Maps/MapInstanced.cpp +++ b/src/server/game/Maps/MapInstanced.cpp @@ -17,15 +17,17 @@ */ #include "MapInstanced.h" -#include "ObjectMgr.h" -#include "MapManager.h" #include "Battleground.h" -#include "VMapFactory.h" -#include "MMapFactory.h" -#include "InstanceSaveMgr.h" -#include "World.h" +#include "DBCStores.h" #include "Group.h" +#include "InstanceSaveMgr.h" +#include "Log.h" +#include "MapManager.h" +#include "MMapFactory.h" +#include "ObjectMgr.h" #include "Player.h" +#include "VMapFactory.h" +#include "World.h" MapInstanced::MapInstanced(uint32 id, time_t expiry) : Map(id, expiry, 0, DUNGEON_DIFFICULTY_NORMAL) { @@ -44,7 +46,7 @@ void MapInstanced::InitVisibilityDistance() } } -void MapInstanced::Update(const uint32 t) +void MapInstanced::Update(uint32 t) { // take care of loaded GridMaps (when unused, unload it!) Map::Update(t); @@ -73,7 +75,7 @@ void MapInstanced::Update(const uint32 t) } } -void MapInstanced::DelayedUpdate(const uint32 diff) +void MapInstanced::DelayedUpdate(uint32 diff) { for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i) i->second->DelayedUpdate(diff); @@ -110,7 +112,7 @@ void MapInstanced::UnloadAll() - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ -Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player, uint32 loginInstanceId) +Map* MapInstanced::CreateInstanceForPlayer(uint32 mapId, Player* player, uint32 loginInstanceId /*= 0*/) { if (GetId() != mapId || !player) return nullptr; @@ -190,7 +192,7 @@ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player, u //ASSERT(!FindInstanceMap(NewInstanceId)); map = FindInstanceMap(newInstanceId); if (!map) - map = CreateInstance(newInstanceId, NULL, diff); + map = CreateInstance(newInstanceId, nullptr, diff); } } @@ -203,13 +205,13 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, std::lock_guard lock(_mapLock); // make sure we have a valid map id - const MapEntry* entry = sMapStore.LookupEntry(GetId()); + MapEntry const* entry = sMapStore.LookupEntry(GetId()); if (!entry) { TC_LOG_ERROR("maps", "CreateInstance: no entry for map %d", GetId()); ABORT(); } - const InstanceTemplate* iTemplate = sObjectMgr->GetInstanceTemplate(GetId()); + InstanceTemplate const* iTemplate = sObjectMgr->GetInstanceTemplate(GetId()); if (!iTemplate) { TC_LOG_ERROR("maps", "CreateInstance: no instance template for map %d", GetId()); @@ -227,7 +229,7 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, map->LoadRespawnTimes(); map->LoadCorpseData(); - bool load_data = save != NULL; + bool load_data = save != nullptr; map->CreateInstanceData(load_data); if (sWorld->getBoolConfig(CONFIG_INSTANCEMAP_LOAD_GRIDS)) diff --git a/src/server/game/Maps/MapInstanced.h b/src/server/game/Maps/MapInstanced.h index 2394aa2035a..7f4184fca3b 100644 --- a/src/server/game/Maps/MapInstanced.h +++ b/src/server/game/Maps/MapInstanced.h @@ -33,13 +33,13 @@ class TC_GAME_API MapInstanced : public Map ~MapInstanced() { } // functions overwrite Map versions - void Update(const uint32) override; - void DelayedUpdate(const uint32 diff) override; + void Update(uint32 diff) override; + void DelayedUpdate(uint32 diff) override; //void RelocationNotify(); void UnloadAll() override; EnterState CannotEnter(Player* /*player*/) override; - Map* CreateInstanceForPlayer(const uint32 mapId, Player* player, uint32 loginInstanceId=0); + Map* CreateInstanceForPlayer(uint32 mapId, Player* player, uint32 loginInstanceId = 0); Map* FindInstanceMap(uint32 instanceId) const { InstancedMaps::const_iterator i = m_InstancedMaps.find(instanceId); @@ -47,7 +47,7 @@ class TC_GAME_API MapInstanced : public Map } bool DestroyInstance(InstancedMaps::iterator &itr); - void AddGridMapReference(const GridCoord &p) + void AddGridMapReference(GridCoord const& p) { ++GridMapReference[p.x_coord][p.y_coord]; SetUnloadReferenceLock(GridCoord((MAX_NUMBER_OF_GRIDS - 1) - p.x_coord, (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord), true); diff --git a/src/server/game/Maps/MapManager.cpp b/src/server/game/Maps/MapManager.cpp index a0317013d3e..8026f944c2a 100644 --- a/src/server/game/Maps/MapManager.cpp +++ b/src/server/game/Maps/MapManager.cpp @@ -57,7 +57,7 @@ void MapManager::Initialize() void MapManager::InitializeVisibilityDistanceInfo() { - for (MapMapType::iterator iter=i_maps.begin(); iter != i_maps.end(); ++iter) + for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end(); ++iter) (*iter).second->InitVisibilityDistance(); } @@ -71,7 +71,7 @@ Map* MapManager::CreateBaseMap(uint32 id) { Map* map = FindBaseMap(id); - if (map == NULL) + if (map == nullptr) { std::lock_guard lock(_mapsLock); @@ -98,7 +98,7 @@ Map* MapManager::FindBaseNonInstanceMap(uint32 mapId) const { Map* map = FindBaseMap(mapId); if (map && map->Instanceable()) - return NULL; + return nullptr; return map; } @@ -116,10 +116,10 @@ Map* MapManager::FindMap(uint32 mapid, uint32 instanceId) const { Map* map = FindBaseMap(mapid); if (!map) - return NULL; + return nullptr; if (!map->Instanceable()) - return instanceId == 0 ? map : NULL; + return instanceId == 0 ? map : nullptr; return ((MapInstanced*)map)->FindInstanceMap(instanceId); } diff --git a/src/server/game/Maps/MapManager.h b/src/server/game/Maps/MapManager.h index 0882efd1e31..e628a7030ae 100644 --- a/src/server/game/Maps/MapManager.h +++ b/src/server/game/Maps/MapManager.h @@ -75,7 +75,7 @@ class TC_GAME_API MapManager i_timer.Reset(); } - //void LoadGrid(int mapid, int instId, float x, float y, const WorldObject* obj, bool no_unload = false); + //void LoadGrid(int mapid, int instId, float x, float y, WorldObject const* obj, bool no_unload = false); void UnloadAll(); static bool ExistMapAndVMap(uint32 mapid, float x, float y); @@ -139,11 +139,11 @@ class TC_GAME_API MapManager Map* FindBaseMap(uint32 mapId) const { MapMapType::const_iterator iter = i_maps.find(mapId); - return (iter == i_maps.end() ? NULL : iter->second); + return (iter == i_maps.end() ? nullptr : iter->second); } - MapManager(const MapManager &); - MapManager& operator=(const MapManager &); + MapManager(MapManager const&) = delete; + MapManager& operator=(MapManager const&) = delete; std::mutex _mapsLock; uint32 i_gridCleanUpDelay; diff --git a/src/server/game/Maps/MapObject.h b/src/server/game/Maps/MapObject.h new file mode 100644 index 00000000000..22e920994c8 --- /dev/null +++ b/src/server/game/Maps/MapObject.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef MapObject_h__ +#define MapObject_h__ + +#include "Define.h" +#include "Cell.h" +#include "Position.h" + +class Map; +class ObjectGridLoader; + +enum MapObjectCellMoveState +{ + MAP_OBJECT_CELL_MOVE_NONE, //not in move list + MAP_OBJECT_CELL_MOVE_ACTIVE, //in move list + MAP_OBJECT_CELL_MOVE_INACTIVE, //in move list but should not move +}; + +class TC_GAME_API MapObject +{ + friend class Map; //map for moving creatures + friend class ObjectGridLoader; //grid loader for loading creatures + +protected: + MapObject() : _moveState(MAP_OBJECT_CELL_MOVE_NONE) + { + _newPosition.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + } + +private: + Cell _currentCell; + Cell const& GetCurrentCell() const { return _currentCell; } + void SetCurrentCell(Cell const& cell) { _currentCell = cell; } + + MapObjectCellMoveState _moveState; + Position _newPosition; + void SetNewCellPosition(float x, float y, float z, float o) + { + _moveState = MAP_OBJECT_CELL_MOVE_ACTIVE; + _newPosition.Relocate(x, y, z, o); + } +}; + +#endif // MapObject_h__ diff --git a/src/server/game/Maps/MapReference.cpp b/src/server/game/Maps/MapReference.cpp new file mode 100644 index 00000000000..ca8169129e2 --- /dev/null +++ b/src/server/game/Maps/MapReference.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "MapReference.h" +#include "Map.h" + +void MapReference::targetObjectBuildLink() +{ + // called from link() + getTarget()->m_mapRefManager.insertFirst(this); + getTarget()->m_mapRefManager.incSize(); +} + +void MapReference::targetObjectDestroyLink() +{ + // called from unlink() + if (isValid()) + getTarget()->m_mapRefManager.decSize(); +} + +void MapReference::sourceObjectDestroyLink() +{ + // called from invalidate() + getTarget()->m_mapRefManager.decSize(); +} diff --git a/src/server/game/Maps/MapReference.h b/src/server/game/Maps/MapReference.h index 11a97b6f44b..73b0635390e 100644 --- a/src/server/game/Maps/MapReference.h +++ b/src/server/game/Maps/MapReference.h @@ -20,27 +20,16 @@ #define _MAPREFERENCE_H #include "Reference.h" -#include "Map.h" + +class Map; +class Player; class MapReference : public Reference { protected: - void targetObjectBuildLink() override - { - // called from link() - getTarget()->m_mapRefManager.insertFirst(this); - getTarget()->m_mapRefManager.incSize(); - } - void targetObjectDestroyLink() override - { - // called from unlink() - if (isValid()) getTarget()->m_mapRefManager.decSize(); - } - void sourceObjectDestroyLink() override - { - // called from invalidate() - getTarget()->m_mapRefManager.decSize(); - } + void targetObjectBuildLink() override; + void targetObjectDestroyLink() override; + void sourceObjectDestroyLink() override; public: MapReference() : Reference() { } ~MapReference() { unlink(); } diff --git a/src/server/game/Maps/MapScripts.cpp b/src/server/game/Maps/MapScripts.cpp index f5c8cd971b9..e365a54c594 100644 --- a/src/server/game/Maps/MapScripts.cpp +++ b/src/server/game/Maps/MapScripts.cpp @@ -16,17 +16,17 @@ * with this program. If not, see . */ +#include "Map.h" #include "CellImpl.h" #include "GameTime.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "GossipDef.h" -#include "Map.h" +#include "GridNotifiers.h" +#include "Item.h" +#include "Log.h" #include "MapManager.h" +#include "MotionMaster.h" #include "ObjectMgr.h" #include "Pet.h" -#include "Item.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "Transport.h" #include "WaypointManager.h" @@ -100,9 +100,9 @@ void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* sou } // Helpers for ScriptProcess method. -inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const +inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo) const { - Player* player = NULL; + Player* player = nullptr; if (!source && !target) TC_LOG_ERROR("scripts", "%s source and target objects are NULL.", scriptInfo->GetDebugInfo().c_str()); else @@ -122,9 +122,9 @@ inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* targe return player; } -inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse) const +inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo, bool bReverse) const { - Creature* creature = NULL; + Creature* creature = nullptr; if (!source && !target) TC_LOG_ERROR("scripts", "%s source and target objects are NULL.", scriptInfo->GetDebugInfo().c_str()); else @@ -155,9 +155,9 @@ inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* t return creature; } -inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - Unit* unit = NULL; + Unit* unit = nullptr; if (!obj) TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else if (!obj->isType(TYPEMASK_UNIT)) @@ -173,9 +173,9 @@ inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* s return unit; } -inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - Player* player = NULL; + Player* player = nullptr; if (!obj) TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else @@ -188,9 +188,9 @@ inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, const ScriptInf return player; } -inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - Creature* creature = NULL; + Creature* creature = nullptr; if (!obj) TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else @@ -203,9 +203,9 @@ inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, const Scrip return creature; } -inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - WorldObject* pWorldObject = NULL; + WorldObject* pWorldObject = nullptr; if (!obj) TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); @@ -219,7 +219,7 @@ inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, const return pWorldObject; } -inline void Map::_ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const +inline void Map::_ScriptProcessDoor(Object* source, Object* target, ScriptInfo const* scriptInfo) const { bool bOpen = false; ObjectGuid::LowType guid = scriptInfo->ToggleDoor.GOGuid; @@ -290,7 +290,7 @@ void Map::ScriptsProcess() { ScriptAction const& step = iter->second; - Object* source = NULL; + Object* source = nullptr; if (step.sourceGUID) { switch (step.sourceGUID.GetHigh()) @@ -326,7 +326,7 @@ void Map::ScriptsProcess() } } - WorldObject* target = NULL; + WorldObject* target = nullptr; if (step.targetGUID) { switch (step.targetGUID.GetHigh()) @@ -669,30 +669,30 @@ void Map::ScriptsProcess() break; } - Unit* uSource = NULL; - Unit* uTarget = NULL; + Unit* uSource = nullptr; + Unit* uTarget = nullptr; // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s switch (step.script->CastSpell.Flags) { case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target - uSource = source ? source->ToUnit() : NULL; - uTarget = target ? target->ToUnit() : NULL; + uSource = source ? source->ToUnit() : nullptr; + uTarget = target ? target->ToUnit() : nullptr; break; case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source - uSource = source ? source->ToUnit() : NULL; + uSource = source ? source->ToUnit() : nullptr; uTarget = uSource; break; case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target - uSource = target ? target->ToUnit() : NULL; + uSource = target ? target->ToUnit() : nullptr; uTarget = uSource; break; case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source - uSource = target ? target->ToUnit() : NULL; - uTarget = source ? source->ToUnit() : NULL; + uSource = target ? target->ToUnit() : nullptr; + uTarget = source ? source->ToUnit() : nullptr; break; case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry - uSource = source ? source->ToUnit() : NULL; - uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : NULL; + uSource = source ? source->ToUnit() : nullptr; + uTarget = uSource ? uSource->FindNearestCreature(abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : nullptr; break; } @@ -720,7 +720,7 @@ void Map::ScriptsProcess() if (WorldObject* object = _GetScriptWorldObject(source, true, step.script)) { // PlaySound.Flags bitmask: 0/1=anyone/target - Player* player = NULL; + Player* player = nullptr; if (step.script->PlaySound.Flags & SF_PLAYSOUND_TARGET_PLAYER) { // Target must be Player. @@ -749,7 +749,7 @@ void Map::ScriptsProcess() pReceiver->SendNewItem(item, step.script->CreateItem.Amount, false, true); } else - pReceiver->SendEquipError(msg, NULL, NULL, step.script->CreateItem.ItemEntry); + pReceiver->SendEquipError(msg, nullptr, nullptr, step.script->CreateItem.ItemEntry); } break; @@ -783,7 +783,7 @@ void Map::ScriptsProcess() break; } - Creature* cTarget = NULL; + Creature* cTarget = nullptr; auto creatureBounds = _creatureBySpawnIdStore.equal_range(step.script->CallScript.CreatureEntry); if (creatureBounds.first != creatureBounds.second) { @@ -811,7 +811,7 @@ void Map::ScriptsProcess() } // Insert script into schedule but do not start it - ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, NULL); + ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, nullptr); break; } diff --git a/src/server/game/Maps/TransportMgr.cpp b/src/server/game/Maps/TransportMgr.cpp index 3eb09166ac9..b6bcfde3723 100644 --- a/src/server/game/Maps/TransportMgr.cpp +++ b/src/server/game/Maps/TransportMgr.cpp @@ -16,20 +16,18 @@ */ #include "TransportMgr.h" -#include "Transport.h" +#include "DatabaseEnv.h" #include "InstanceScript.h" -#include "MoveSpline.h" +#include "Log.h" #include "MapManager.h" +#include "MoveSplineInitArgs.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Spline.h" +#include "Transport.h" TransportTemplate::~TransportTemplate() { - // Collect shared pointers into a set to avoid deleting the same memory more than once - std::set splines; - for (size_t i = 0; i < keyFrames.size(); ++i) - splines.insert(keyFrames[i].Spline); - - for (std::set::iterator itr = splines.begin(); itr != splines.end(); ++itr) - delete *itr; } TransportMgr::TransportMgr() { } @@ -66,7 +64,7 @@ void TransportMgr::LoadTransportTemplates() Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); GameObjectTemplate const* goInfo = sObjectMgr->GetGameObjectTemplate(entry); - if (goInfo == NULL) + if (goInfo == nullptr) { TC_LOG_ERROR("sql.sql", "Transport %u has no associated GameObjectTemplate from `gameobject_template` , skipped.", entry); continue; @@ -93,6 +91,17 @@ void TransportMgr::LoadTransportTemplates() TC_LOG_INFO("server.loading", ">> Loaded %u transport templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } +void TransportMgr::LoadTransportAnimationAndRotation() +{ + for (uint32 i = 0; i < sTransportAnimationStore.GetNumRows(); ++i) + if (TransportAnimationEntry const* anim = sTransportAnimationStore.LookupEntry(i)) + AddPathNodeToTransport(anim->TransportEntry, anim->TimeSeg, anim); + + for (uint32 i = 0; i < sTransportRotationStore.GetNumRows(); ++i) + if (TransportRotationEntry const* rot = sTransportRotationStore.LookupEntry(i)) + AddPathRotationToTransport(rot->TransportEntry, rot->TimeSeg, rot); +} + class SplineRawInitializer { public: @@ -213,7 +222,7 @@ void TransportMgr::GeneratePath(GameObjectTemplate const* goInfo, TransportTempl if (keyFrames[i - 1].Teleport || i + 1 == keyFrames.size()) { size_t extra = !keyFrames[i - 1].Teleport ? 1 : 0; - TransportSpline* spline = new TransportSpline(); + std::shared_ptr spline = std::make_shared(); spline->init_spline(&splinePath[start], i - start + extra, Movement::SplineBase::ModeCatmullrom); spline->initLengths(); for (size_t j = start; j < i + extra; ++j) @@ -354,7 +363,7 @@ void TransportMgr::AddPathNodeToTransport(uint32 transportEntry, uint32 timeSeg, animNode.Path[timeSeg] = node; } -Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid /*= 0*/, Map* map /*= NULL*/) +Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid /*= 0*/, Map* map /*= nullptr*/) { // instance case, execute GetGameObjectEntry hook if (map) @@ -365,14 +374,14 @@ Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid entry = instance->GetGameObjectEntry(0, entry); if (!entry) - return NULL; + return nullptr; } TransportTemplate const* tInfo = GetTransportTemplate(entry); if (!tInfo) { TC_LOG_ERROR("sql.sql", "Transport %u will not be loaded, `transport_template` missing", entry); - return NULL; + return nullptr; } // create transport... @@ -392,7 +401,7 @@ Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid if (!trans->Create(guidLow, entry, mapId, x, y, z, o, 255)) { delete trans; - return NULL; + return nullptr; } if (MapEntry const* mapEntry = sMapStore.LookupEntry(mapId)) @@ -401,12 +410,12 @@ Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid { TC_LOG_ERROR("entities.transport", "Transport %u (name: %s) attempted creation in instance map (id: %u) but it is not an instanced transport!", entry, trans->GetName().c_str(), mapId); delete trans; - return NULL; + return nullptr; } } // use preset map for instances (need to know which instance) - trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, NULL)); + trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, nullptr)); if (map && map->IsDungeon()) trans->m_zoneScript = map->ToInstanceMap()->GetInstanceScript(); @@ -460,30 +469,18 @@ void TransportMgr::CreateInstanceTransports(Map* map) TransportAnimationEntry const* TransportAnimation::GetAnimNode(uint32 time) const { - if (Path.empty()) - return NULL; - - for (TransportPathContainer::const_reverse_iterator itr2 = Path.rbegin(); itr2 != Path.rend(); ++itr2) - if (time >= itr2->first) - return itr2->second; + auto itr = Path.lower_bound(time); + if (itr != Path.end()) + return itr->second; - return Path.begin()->second; + return nullptr; } -G3D::Quat TransportAnimation::GetAnimRotation(uint32 time) const +TransportRotationEntry const* TransportAnimation::GetAnimRotation(uint32 time) const { - if (Rotations.empty()) - return G3D::Quat(0.0f, 0.0f, 0.0f, 1.0f); - - TransportRotationEntry const* rot = Rotations.begin()->second; - for (TransportPathRotationContainer::const_reverse_iterator itr2 = Rotations.rbegin(); itr2 != Rotations.rend(); ++itr2) - { - if (time >= itr2->first) - { - rot = itr2->second; - break; - } - } + auto itr = Rotations.lower_bound(time); + if (itr != Rotations.end()) + return itr->second; - return G3D::Quat(rot->X, rot->Y, rot->Z, rot->W); + return nullptr; } diff --git a/src/server/game/Maps/TransportMgr.h b/src/server/game/Maps/TransportMgr.h index abb86572766..86a38b3303a 100644 --- a/src/server/game/Maps/TransportMgr.h +++ b/src/server/game/Maps/TransportMgr.h @@ -18,10 +18,9 @@ #ifndef TRANSPORTMGR_H #define TRANSPORTMGR_H -#include -#include "Spline.h" #include "DBCStores.h" #include "ObjectGuid.h" +#include struct KeyFrame; struct GameObjectTemplate; @@ -29,6 +28,11 @@ struct TransportTemplate; class Transport; class Map; +namespace Movement +{ + template class Spline; +} + typedef Movement::Spline TransportSpline; typedef std::vector KeyFrameVec; typedef std::unordered_map TransportTemplates; @@ -40,7 +44,7 @@ struct KeyFrame { explicit KeyFrame(TaxiPathNodeEntry const* node) : Index(0), Node(node), InitialOrientation(0.0f), DistSinceStop(-1.0f), DistUntilStop(-1.0f), DistFromPrev(-1.0f), TimeFrom(0.0f), TimeTo(0.0f), - Teleport(false), ArriveTime(0), DepartureTime(0), Spline(NULL), NextDistFromPrev(0.0f), NextArriveTime(0) + Teleport(false), ArriveTime(0), DepartureTime(0), Spline(nullptr), NextDistFromPrev(0.0f), NextArriveTime(0) { } @@ -55,7 +59,7 @@ struct KeyFrame bool Teleport; uint32 ArriveTime; uint32 DepartureTime; - TransportSpline* Spline; + std::shared_ptr Spline; // Data needed for next frame float NextDistFromPrev; @@ -91,15 +95,13 @@ struct TC_GAME_API TransportAnimation uint32 TotalTime; TransportAnimationEntry const* GetAnimNode(uint32 time) const; - G3D::Quat GetAnimRotation(uint32 time) const; + TransportRotationEntry const* GetAnimRotation(uint32 time) const; }; typedef std::map TransportAnimationContainer; class TC_GAME_API TransportMgr { - friend TC_GAME_API void LoadDBCStores(std::string const&); - public: static TransportMgr* instance(); @@ -107,8 +109,10 @@ class TC_GAME_API TransportMgr void LoadTransportTemplates(); + void LoadTransportAnimationAndRotation(); + // Creates a transport using given GameObject template entry - Transport* CreateTransport(uint32 entry, ObjectGuid::LowType guid = 0, Map* map = NULL); + Transport* CreateTransport(uint32 entry, ObjectGuid::LowType guid = 0, Map* map = nullptr); // Spawns all continent transports, used at core startup void SpawnContinentTransports(); @@ -121,7 +125,7 @@ class TC_GAME_API TransportMgr TransportTemplates::const_iterator itr = _transportTemplates.find(entry); if (itr != _transportTemplates.end()) return &itr->second; - return NULL; + return nullptr; } TransportAnimation const* GetTransportAnimInfo(uint32 entry) const @@ -130,14 +134,14 @@ class TC_GAME_API TransportMgr if (itr != _transportAnimations.end()) return &itr->second; - return NULL; + return nullptr; } private: TransportMgr(); ~TransportMgr(); - TransportMgr(TransportMgr const&); - TransportMgr& operator=(TransportMgr const&); + TransportMgr(TransportMgr const&) = delete; + TransportMgr& operator=(TransportMgr const&) = delete; // Generates and precaches a path for transport to avoid generation each time transport instance is created void GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport); diff --git a/src/server/game/Maps/ZoneScript.cpp b/src/server/game/Maps/ZoneScript.cpp new file mode 100644 index 00000000000..e16007a34f3 --- /dev/null +++ b/src/server/game/Maps/ZoneScript.cpp @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ZoneScript.h" +#include "Creature.h" + +uint32 ZoneScript::GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data) +{ + return data->id; +} diff --git a/src/server/game/Maps/ZoneScript.h b/src/server/game/Maps/ZoneScript.h index 75fb56e555c..9c957022bc9 100644 --- a/src/server/game/Maps/ZoneScript.h +++ b/src/server/game/Maps/ZoneScript.h @@ -18,18 +18,22 @@ #ifndef ZONE_SCRIPT_H_ #define ZONE_SCRIPT_H_ -#include "Common.h" -#include "Creature.h" +#include "Define.h" +#include "ObjectGuid.h" +class Creature; class GameObject; +class Unit; +class WorldObject; +struct CreatureData; -class ZoneScript +class TC_GAME_API ZoneScript { public: ZoneScript() { } virtual ~ZoneScript() { } - virtual uint32 GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data) { return data->id; } + virtual uint32 GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data); virtual uint32 GetGameObjectEntry(ObjectGuid::LowType /*guidLow*/, uint32 entry) { return entry; } virtual void OnCreatureCreate(Creature* ) { } diff --git a/src/server/game/Miscellaneous/Formulas.h b/src/server/game/Miscellaneous/Formulas.h index 3787c9ba601..81e906ed47d 100644 --- a/src/server/game/Miscellaneous/Formulas.h +++ b/src/server/game/Miscellaneous/Formulas.h @@ -19,10 +19,14 @@ #ifndef TRINITY_FORMULAS_H #define TRINITY_FORMULAS_H -#include "World.h" -#include "SharedDefines.h" -#include "ScriptMgr.h" +#include "DBCStores.h" +#include "Creature.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "ScriptMgr.h" +#include "SharedDefines.h" +#include "World.h" namespace Trinity { @@ -185,7 +189,7 @@ namespace Trinity xpMod *= isBattleGround ? sWorld->getRate(RATE_XP_BG_KILL) : sWorld->getRate(RATE_XP_KILL); if (creature && creature->m_PlayerDamageReq) // if players dealt less than 50% of the damage and were credited anyway (due to CREATURE_FLAG_EXTRA_NO_PLAYER_DAMAGE_REQ), scale XP gained appropriately (linear scaling) - xpMod *= 1.0f - 2.0f*creature->m_PlayerDamageReq / creature->GetMaxHealth(); + xpMod *= 1.0f - 2.0f * creature->m_PlayerDamageReq / creature->GetMaxHealth(); gain = uint32(gain * xpMod); } diff --git a/src/server/game/Miscellaneous/SharedDefines.h b/src/server/game/Miscellaneous/SharedDefines.h index 9e42b516c47..7ea78f14ca4 100644 --- a/src/server/game/Miscellaneous/SharedDefines.h +++ b/src/server/game/Miscellaneous/SharedDefines.h @@ -21,7 +21,6 @@ #include "Define.h" #include "DetourNavMesh.h" -#include enum SpellEffIndex : uint8 { @@ -1555,6 +1554,16 @@ enum GameObjectDynamicLowFlags GO_DYNFLAG_LO_STOPPED = 0x10 // Transport is stopped }; +// client side GO show states +enum GOState : uint8 +{ + GO_STATE_ACTIVE = 0, // show in world as used and not reset (closed door open) + GO_STATE_READY = 1, // show in world as ready (closed door close) + GO_STATE_ACTIVE_ALTERNATIVE = 2 // show in world as used in alt way and not reset (closed door open by cannon fire) +}; + +#define MAX_GO_STATE 3 + enum GameObjectDestructibleState { GO_DESTRUCTIBLE_INTACT = 0, @@ -3371,7 +3380,7 @@ enum BattlegroundTeamId #define BG_TEAMS_COUNT 2 // indexes of BattlemasterList.dbc -enum BattlegroundTypeId +enum BattlegroundTypeId : uint32 { BATTLEGROUND_TYPE_NONE = 0, // None BATTLEGROUND_AV = 1, // Alterac Valley @@ -3469,7 +3478,7 @@ enum TradeStatus TRADE_STATUS_NOT_ON_TAPLIST = 23 // Related to trading soulbound loot items }; -enum XPColorChar +enum XPColorChar : uint8 { XP_RED, XP_ORANGE, @@ -3478,7 +3487,7 @@ enum XPColorChar XP_GRAY }; -enum RemoveMethod +enum RemoveMethod : uint8 { GROUP_REMOVEMETHOD_DEFAULT = 0, GROUP_REMOVEMETHOD_KICK = 1, @@ -3503,7 +3512,7 @@ enum ActivateTaxiReply ERR_TAXINOTSTANDING = 12 }; -enum DuelCompleteType +enum DuelCompleteType : uint8 { DUEL_INTERRUPTED = 0, DUEL_WON = 1, @@ -3622,14 +3631,6 @@ enum DiminishingLevels DIMINISHING_LEVEL_TAUNT_IMMUNE = 4 }; -/// Spell cooldown flags sent in SMSG_SPELL_COOLDOWN -enum SpellCooldownFlags -{ - SPELL_COOLDOWN_FLAG_NONE = 0x0, - SPELL_COOLDOWN_FLAG_INCLUDE_GCD = 0x1, ///< Starts GCD in addition to normal cooldown specified in the packet - SPELL_COOLDOWN_FLAG_INCLUDE_EVENT_COOLDOWNS = 0x2 ///< Starts GCD for spells that should start their cooldown on events, requires SPELL_COOLDOWN_FLAG_INCLUDE_GCD set -}; - enum WeaponAttackType : uint8 { BASE_ATTACK = 0, @@ -3649,4 +3650,14 @@ enum CharterTypes ARENA_TEAM_CHARTER_5v5_TYPE = 5 }; +enum LineOfSightChecks +{ + LINEOFSIGHT_CHECK_VMAP = 0x1, // check static floor layout data + LINEOFSIGHT_CHECK_GOBJECT = 0x2, // check dynamic game object data + + LINEOFSIGHT_ALL_CHECKS = (LINEOFSIGHT_CHECK_VMAP | LINEOFSIGHT_CHECK_GOBJECT) +}; + +#define MAX_CREATURE_SPELL_DATA_SLOT 4 + #endif diff --git a/src/server/game/Motd/ServerMotd.cpp b/src/server/game/Motd/ServerMotd.cpp index 3baaaf7a1c0..0f6587b60f2 100644 --- a/src/server/game/Motd/ServerMotd.cpp +++ b/src/server/game/Motd/ServerMotd.cpp @@ -15,11 +15,13 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "ServerMotd.h" - +#include "Common.h" #include "ScriptMgr.h" +#include "Util.h" +#include "WorldPacket.h" +#include +#include namespace { diff --git a/src/server/game/Motd/ServerMotd.h b/src/server/game/Motd/ServerMotd.h index 1e3c5edf231..21c7d461282 100644 --- a/src/server/game/Motd/ServerMotd.h +++ b/src/server/game/Motd/ServerMotd.h @@ -18,6 +18,7 @@ #ifndef ServerMotd_h__ #define ServerMotd_h__ +#include "Define.h" #include class WorldPacket; diff --git a/src/server/game/Movement/MotionMaster.cpp b/src/server/game/Movement/MotionMaster.cpp index 6f4c198f44d..6e771a29979 100644 --- a/src/server/game/Movement/MotionMaster.cpp +++ b/src/server/game/Movement/MotionMaster.cpp @@ -17,8 +17,12 @@ */ #include "MotionMaster.h" -#include "CreatureAISelector.h" #include "Creature.h" +#include "CreatureAISelector.h" +#include "DBCStores.h" +#include "Log.h" +#include "Map.h" +#include "PathGenerator.h" #include "ScriptSystem.h" #include "ConfusedMovementGenerator.h" #include "FleeingMovementGenerator.h" @@ -510,15 +514,16 @@ void MotionMaster::MoveCirclePath(float x, float y, float z, float radius, bool init.Launch(); } -void MotionMaster::MoveSmoothPath(uint32 pointId, G3D::Vector3 const* pathPoints, size_t pathSize, bool walk) -{ - Movement::PointsArray path(pathPoints, pathPoints + pathSize); - MoveSmoothPath(pointId, path, walk); -} - -void MotionMaster::MoveSmoothPath(uint32 pointId, Movement::PointsArray const& path, bool walk) +void MotionMaster::MoveSmoothPath(uint32 pointId, Position const* pathPoints, size_t pathSize, bool walk) { Movement::MoveSplineInit init(_owner); + Movement::PointsArray path; + path.reserve(pathSize); + std::transform(pathPoints, pathPoints + pathSize, std::back_inserter(path), [](Position const& point) + { + return G3D::Vector3(point.GetPositionX(), point.GetPositionY(), point.GetPositionZ()); + }); + init.MovebyPath(path); init.SetSmooth(); init.SetWalk(walk); @@ -540,7 +545,7 @@ void MotionMaster::MoveAlongSplineChain(uint32 pointId, uint16 dbChainId, bool w TC_LOG_ERROR("misc", "MotionMaster::MoveAlongSplineChain: non-creature %s tried to walk along DB spline chain. Ignoring.", _owner->GetGUID().ToString().c_str()); return; } - SplineChain const* chain = sScriptSystemMgr->GetSplineChain(owner, dbChainId); + std::vector const* chain = sScriptSystemMgr->GetSplineChain(owner, dbChainId); if (!chain) { TC_LOG_ERROR("misc", "MotionMaster::MoveAlongSplineChain: creature with entry %u tried to walk along non-existing spline chain with DB id %u.", owner->GetEntry(), dbChainId); @@ -549,7 +554,7 @@ void MotionMaster::MoveAlongSplineChain(uint32 pointId, uint16 dbChainId, bool w MoveAlongSplineChain(pointId, *chain, walk); } -void MotionMaster::MoveAlongSplineChain(uint32 pointId, SplineChain const& chain, bool walk) +void MotionMaster::MoveAlongSplineChain(uint32 pointId, std::vector const& chain, bool walk) { Mutate(new SplineChainMovementGenerator(pointId, chain, walk), MOTION_SLOT_ACTIVE); } diff --git a/src/server/game/Movement/MotionMaster.h b/src/server/game/Movement/MotionMaster.h index d73c9464cf5..4e20f9ab814 100644 --- a/src/server/game/Movement/MotionMaster.h +++ b/src/server/game/Movement/MotionMaster.h @@ -20,22 +20,24 @@ #define MOTIONMASTER_H #include "Common.h" -#include +#include "Errors.h" +#include "ObjectGuid.h" +#include "Position.h" #include "SharedDefines.h" -#include "Object.h" -#include "MoveSplineInitArgs.h" -#include "SplineChain.h" +#include class MovementGenerator; class Unit; class PathGenerator; +struct SplineChainLink; +struct SplineChainResumeInfo; // Creature Entry ID used for waypoints show, visible only for GMs #define VISUAL_WAYPOINT 1 // assume it is 25 yard per 0.6 second #define SPEED_CHARGE 42.0f -enum MovementGeneratorType +enum MovementGeneratorType : uint8 { IDLE_MOTION_TYPE = 0, // IdleMovementGenerator.h RANDOM_MOTION_TYPE = 1, // RandomMovementGenerator.h @@ -146,11 +148,10 @@ class TC_GAME_API MotionMaster } void MoveJump(float x, float y, float z, float o, float speedXY, float speedZ, uint32 id = EVENT_JUMP, bool hasOrientation = false); void MoveCirclePath(float x, float y, float z, float radius, bool clockwise, uint8 stepCount); - void MoveSmoothPath(uint32 pointId, G3D::Vector3 const* pathPoints, size_t pathSize, bool walk); - void MoveSmoothPath(uint32 pointId, Movement::PointsArray const& points, bool walk); + void MoveSmoothPath(uint32 pointId, Position const* pathPoints, size_t pathSize, bool walk); // Walk along spline chain stored in DB (script_spline_chain_meta and script_spline_chain_waypoints) void MoveAlongSplineChain(uint32 pointId, uint16 dbChainId, bool walk); - void MoveAlongSplineChain(uint32 pointId, SplineChain const& chain, bool walk); + void MoveAlongSplineChain(uint32 pointId, std::vector const& chain, bool walk); void ResumeSplineChain(SplineChainResumeInfo const& info); void MoveFall(uint32 id = 0); diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp index 48524d9c663..20633056e4e 100755 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp @@ -16,12 +16,13 @@ * with this program. If not, see . */ +#include "ConfusedMovementGenerator.h" #include "Creature.h" -#include "Player.h" -#include "PathGenerator.h" -#include "MoveSplineInit.h" #include "MoveSpline.h" -#include "ConfusedMovementGenerator.h" +#include "MoveSplineInit.h" +#include "PathGenerator.h" +#include "Player.h" +#include "Random.h" template ConfusedMovementGenerator::~ConfusedMovementGenerator() @@ -40,7 +41,7 @@ void ConfusedMovementGenerator::DoInitialize(T* owner) owner->StopMoving(); _timer.Reset(0); - owner->GetPosition(_reference.x, _reference.y, _reference.z); + owner->GetPosition(_x, _y, _z); } template @@ -71,7 +72,7 @@ bool ConfusedMovementGenerator::DoUpdate(T* owner, uint32 diff) // start moving owner->AddUnitState(UNIT_STATE_CONFUSED_MOVE); - Position destination(_reference); + Position destination(_x, _y, _z); float distance = 4.0f * frand(0.0f, 1.0f) - 2.0f; float angle = frand(0.0f, 1.0f) * float(M_PI) * 2.0f; owner->MovePositionToFirstCollision(destination, distance, angle); diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h index 95ba375de27..c4886c76bc3 100755 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h @@ -26,7 +26,7 @@ template class ConfusedMovementGenerator : public MovementGeneratorMedium< T, ConfusedMovementGenerator > { public: - explicit ConfusedMovementGenerator() : _path(nullptr), _timer(0), _reference(0.f, 0.f, 0.f), _interrupt(false) { } + explicit ConfusedMovementGenerator() : _path(nullptr), _timer(0), _x(0.f), _y(0.f), _z(0.f), _interrupt(false) { } ~ConfusedMovementGenerator(); MovementGeneratorType GetMovementGeneratorType() const override { return CONFUSED_MOTION_TYPE; } @@ -39,7 +39,7 @@ class ConfusedMovementGenerator : public MovementGeneratorMedium< T, ConfusedMov private: PathGenerator* _path; TimeTracker _timer; - G3D::Vector3 _reference; + float _x, _y, _z; bool _interrupt; }; diff --git a/src/server/game/Movement/MovementGenerators/FormationMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/FormationMovementGenerator.cpp index 2714027fc85..275a6ab0db2 100644 --- a/src/server/game/Movement/MovementGenerators/FormationMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/FormationMovementGenerator.cpp @@ -35,7 +35,7 @@ void FormationMovementGenerator::DoInitialize(Creature* owner) owner->AddUnitState(UNIT_STATE_ROAMING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(_destination); + init.MoveTo(_destination.GetPositionX(), _destination.GetPositionY(), _destination.GetPositionZ()); if (_orientation) init.SetFacing(_destination.GetOrientation()); @@ -81,7 +81,7 @@ bool FormationMovementGenerator::DoUpdate(Creature* owner, uint32 /*diff*/) owner->AddUnitState(UNIT_STATE_ROAMING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(_destination); + init.MoveTo(_destination.GetPositionX(), _destination.GetPositionY(), _destination.GetPositionZ()); if (_orientation) init.SetFacing(_destination.GetOrientation()); diff --git a/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp index 66e9b360daf..498cdf04876 100644 --- a/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp @@ -16,11 +16,12 @@ * with this program. If not, see . */ +#include "HomeMovementGenerator.h" #include "Creature.h" #include "CreatureAI.h" -#include "MoveSplineInit.h" #include "MoveSpline.h" -#include "HomeMovementGenerator.h" +#include "MoveSplineInit.h" +#include "PathGenerator.h" template HomeMovementGenerator::~HomeMovementGenerator() { } diff --git a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp index 36d9e17caf3..a952421833d 100755 --- a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp @@ -48,7 +48,7 @@ void PointMovementGenerator::DoInitialize(T* owner) owner->AddUnitState(UNIT_STATE_ROAMING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(_destination, _generatePath); + init.MoveTo(_x, _y, _z , _generatePath); if (_speed > 0.0f) init.SetVelocity(_speed); init.Launch(); @@ -56,7 +56,7 @@ void PointMovementGenerator::DoInitialize(T* owner) // Call for creature group update if (Creature* creature = owner->ToCreature()) if (creature->GetFormation() && creature->GetFormation()->getLeader() == creature) - creature->GetFormation()->LeaderMoveTo(Position(_destination), _movementId); + creature->GetFormation()->LeaderMoveTo(Position(_x, _y, _z), _movementId); } template @@ -83,7 +83,7 @@ bool PointMovementGenerator::DoUpdate(T* owner, uint32 /*diff*/) owner->AddUnitState(UNIT_STATE_ROAMING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(_destination, _generatePath); + init.MoveTo(_x, _y, _z, _generatePath); if (_speed > 0.0f) // Default value for point motion type is 0.0, if 0.0 spline will use GetSpeed on unit init.SetVelocity(_speed); init.Launch(); @@ -91,7 +91,7 @@ bool PointMovementGenerator::DoUpdate(T* owner, uint32 /*diff*/) // Call for creature group update if (Creature* creature = owner->ToCreature()) if (creature->GetFormation() && creature->GetFormation()->getLeader() == creature) - creature->GetFormation()->LeaderMoveTo(Position(_destination), _movementId); + creature->GetFormation()->LeaderMoveTo(Position(_x, _y, _z), _movementId); } return !owner->movespline->Finalized(); diff --git a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h index f68021c51c4..8f4970566a3 100644 --- a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h @@ -21,11 +21,13 @@ #include "MovementGenerator.h" +class Creature; + template class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementGenerator > { public: - explicit PointMovementGenerator(uint32 id, float x, float y, float z, bool generatePath, float speed = 0.0f) : _movementId(id), _destination(x, y, z), _speed(speed), _generatePath(generatePath), _recalculateSpeed(false), _interrupt(false) { } + PointMovementGenerator(uint32 id, float x, float y, float z, bool generatePath, float speed = 0.0f) : _movementId(id), _x(x), _y(y), _z(z), _speed(speed), _generatePath(generatePath), _recalculateSpeed(false), _interrupt(false) { } MovementGeneratorType GetMovementGeneratorType() const override { return POINT_MOTION_TYPE; } @@ -40,7 +42,7 @@ class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementG void MovementInform(T*); uint32 _movementId; - G3D::Vector3 _destination; + float _x, _y, _z; float _speed; bool _generatePath; bool _recalculateSpeed; @@ -50,7 +52,7 @@ class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementG class AssistanceMovementGenerator : public PointMovementGenerator { public: - explicit AssistanceMovementGenerator(float _x, float _y, float _z) : PointMovementGenerator(0, _x, _y, _z, true) { } + AssistanceMovementGenerator(float x, float y, float z) : PointMovementGenerator(0, x, y, z, true) { } MovementGeneratorType GetMovementGeneratorType() const override { return ASSISTANCE_MOTION_TYPE; } void Finalize(Unit*) override; diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp index 8a21ac683cd..0a1972c0972 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp @@ -16,12 +16,14 @@ * with this program. If not, see . */ +#include "RandomMovementGenerator.h" #include "Creature.h" #include "CreatureGroups.h" #include "Map.h" #include "MoveSplineInit.h" #include "MoveSpline.h" -#include "RandomMovementGenerator.h" +#include "PathGenerator.h" +#include "Random.h" template RandomMovementGenerator::~RandomMovementGenerator() { } @@ -42,7 +44,7 @@ void RandomMovementGenerator::DoInitialize(Creature* owner) return; owner->AddUnitState(UNIT_STATE_ROAMING); - owner->GetPosition(_reference.x, _reference.y, _reference.z); + _reference = owner->GetPosition(); owner->StopMoving(); if (!_wanderDistance) diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h index 5bf0eb03f32..845af1c1748 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h @@ -26,7 +26,7 @@ template class RandomMovementGenerator : public MovementGeneratorMedium< T, RandomMovementGenerator > { public: - explicit RandomMovementGenerator(float distance = 0.0f) : _path(nullptr), _timer(0), _reference(0.f, 0.f, 0.f), _wanderDistance(distance), _interrupt(false) { } + explicit RandomMovementGenerator(float distance = 0.0f) : _path(nullptr), _timer(0), _reference(), _wanderDistance(distance), _interrupt(false) { } ~RandomMovementGenerator(); MovementGeneratorType GetMovementGeneratorType() const override { return RANDOM_MOTION_TYPE; } @@ -41,7 +41,7 @@ class RandomMovementGenerator : public MovementGeneratorMedium< T, RandomMovemen PathGenerator* _path; TimeTracker _timer; - G3D::Vector3 _reference; + Position _reference; float _wanderDistance; bool _interrupt; }; diff --git a/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h b/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h index ef0f0cf384d..8b7ce6fd69a 100644 --- a/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h @@ -24,7 +24,7 @@ class TC_GAME_API SplineChainMovementGenerator : public MovementGenerator { public: - explicit SplineChainMovementGenerator(uint32 id, SplineChain const& chain, bool walk = false) : _id(id), _chain(chain), _chainSize(chain.size()), _walk(walk), finished(false), _nextIndex(0), _nextFirstWP(0), _msToNext(0) { } + explicit SplineChainMovementGenerator(uint32 id, std::vector const& chain, bool walk = false) : _id(id), _chain(chain), _chainSize(chain.size()), _walk(walk), finished(false), _nextIndex(0), _nextFirstWP(0), _msToNext(0) { } explicit SplineChainMovementGenerator(SplineChainResumeInfo const& info) : _id(info.PointID), _chain(*info.Chain), _chainSize(info.Chain->size()), _walk(info.IsWalkMode), finished(info.SplineIndex >= info.Chain->size()), _nextIndex(info.SplineIndex), _nextFirstWP(info.PointIndex), _msToNext(info.TimeToNext) { } void Initialize(Unit* me) override; void Finalize(Unit* me) override; @@ -41,7 +41,7 @@ class TC_GAME_API SplineChainMovementGenerator : public MovementGenerator void SendSplineFor(Unit* me, uint32 index, uint32& toNext); uint32 SendPathSpline(Unit* me, Movement::PointsArray const& wp) const; uint32 const _id; - SplineChain const& _chain; + std::vector const& _chain; uint8 const _chainSize; bool const _walk; bool finished; diff --git a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp index db1960ab72d..ef54cc83bff 100644 --- a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ -#include "CreatureAI.h" +#include "TargetedMovementGenerator.h" #include "Creature.h" +#include "CreatureAI.h" +#include "MoveSpline.h" +#include "MoveSplineInit.h" +#include "PathGenerator.h" #include "Player.h" #include "VehicleDefines.h" -#include "MoveSplineInit.h" -#include "MoveSpline.h" #include "World.h" -#include "TargetedMovementGenerator.h" template TargetedMovementGenerator::~TargetedMovementGenerator() diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp index 57c831c2e44..f292c0a8091 100755 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp @@ -15,21 +15,17 @@ * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ -//Basic headers + #include "WaypointMovementGenerator.h" -//Extended headers -#include "ObjectMgr.h" -#include "Transport.h" -//Flightmaster grid preloading -#include "MapManager.h" -//Creature-specific headers -#include "Creature.h" #include "CreatureAI.h" #include "CreatureGroups.h" -//Player-specific -#include "Player.h" -#include "MoveSplineInit.h" +#include "Log.h" +#include "MapManager.h" #include "MoveSpline.h" +#include "MoveSplineInit.h" +#include "ObjectMgr.h" +#include "Transport.h" +#include "World.h" void WaypointMovementGenerator::LoadPath(Creature* creature) { @@ -79,7 +75,7 @@ void WaypointMovementGenerator::OnArrived(Creature* creature) { TC_LOG_DEBUG("maps.script", "Creature movement start script %u at point %u for %s.", i_path->at(i_currentNode)->event_id, i_currentNode, creature->GetGUID().ToString().c_str()); creature->ClearUnitState(UNIT_STATE_ROAMING_MOVE); - creature->GetMap()->ScriptsStart(sWaypointScripts, i_path->at(i_currentNode)->event_id, creature, NULL); + creature->GetMap()->ScriptsStart(sWaypointScripts, i_path->at(i_currentNode)->event_id, creature, nullptr); } // Inform script @@ -240,7 +236,7 @@ bool WaypointMovementGenerator::GetResetPos(Creature*, float& x, float if (!i_path || i_path->empty()) return false; - const WaypointData* node = i_path->at(i_currentNode); + WaypointData const* node = i_path->at(i_currentNode); x = node->x; y = node->y; z = node->z; return true; } diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h index 726d41ffcae..7426a166ea1 100755 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h @@ -26,9 +26,11 @@ */ #include "MovementGenerator.h" -#include "WaypointManager.h" +#include "Creature.h" +#include "DBCStructure.h" #include "Player.h" -#include "World.h" +#include "Timer.h" +#include "WaypointManager.h" #define FLIGHT_TRAVEL_UPDATE 100 #define TIMEDIFF_NEXT_WP 250 @@ -57,7 +59,7 @@ class WaypointMovementGenerator : public MovementGeneratorMedium< Crea public: WaypointMovementGenerator(uint32 _path_id = 0, bool _repeating = true) : i_nextMoveTime(0), m_isArrivalDone(false), path_id(_path_id), repeating(_repeating) { } - ~WaypointMovementGenerator() { i_path = NULL; } + ~WaypointMovementGenerator() { i_path = nullptr; } void DoInitialize(Creature*); void DoFinalize(Creature*); void DoReset(Creature*); @@ -148,4 +150,5 @@ class FlightPathMovementGenerator : public MovementGeneratorMedium< Player, Flig std::deque _pointsForPathSwitch; //! node indexes and costs where TaxiPath changes }; + #endif diff --git a/src/server/game/Movement/PathGenerator.cpp b/src/server/game/Movement/PathGenerator.cpp index 6075b9352e8..ecf84d51b94 100644 --- a/src/server/game/Movement/PathGenerator.cpp +++ b/src/server/game/Movement/PathGenerator.cpp @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #include "PathGenerator.h" @@ -28,11 +28,11 @@ #include "Metric.h" ////////////////// PathGenerator ////////////////// -PathGenerator::PathGenerator(const Unit* owner) : +PathGenerator::PathGenerator(Unit const* owner) : _polyLength(0), _type(PATHFIND_BLANK), _useStraightPath(false), _forceDestination(false), _pointPathLimit(MAX_POINT_PATH_LENGTH), _straightLine(false), - _endPosition(G3D::Vector3::zero()), _sourceUnit(owner), _navMesh(NULL), - _navMeshQuery(NULL) + _endPosition(G3D::Vector3::zero()), _sourceUnit(owner), _navMesh(nullptr), + _navMeshQuery(nullptr) { memset(_pathPolyRefs, 0, sizeof(_pathPolyRefs)); @@ -103,7 +103,7 @@ dtPolyRef PathGenerator::GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 for (uint32 i = 0; i < polyPathSize; ++i) { float closestPoint[VERTEX_SIZE]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint, NULL))) + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint, nullptr))) continue; float d = dtVdist2DSqr(point, closestPoint); @@ -184,7 +184,7 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con // Check both start and end points, if they're both in water, then we can *safely* let the creature move for (uint32 i = 0; i < _pathPoints.size(); ++i) { - ZLiquidStatus status = _sourceUnit->GetBaseMap()->GetLiquidStatus(_pathPoints[i].x, _pathPoints[i].y, _pathPoints[i].z, MAP_ALL_LIQUIDS, NULL); + ZLiquidStatus status = _sourceUnit->GetBaseMap()->GetLiquidStatus(_pathPoints[i].x, _pathPoints[i].y, _pathPoints[i].z, MAP_ALL_LIQUIDS, nullptr); // One of the points is not in the water, cancel movement. if (status == LIQUID_MAP_NO_WATER) { @@ -234,7 +234,7 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con { float closestPoint[VERTEX_SIZE]; // we may want to use closestPointOnPolyBoundary instead - if (dtStatusSucceed(_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint, NULL))) + if (dtStatusSucceed(_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint, nullptr))) { dtVcopy(endPoint, closestPoint); SetActualEndPosition(G3D::Vector3(endPoint[2], endPoint[0], endPoint[1])); @@ -333,13 +333,13 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data float suffixEndPoint[VERTEX_SIZE]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, NULL))) + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, nullptr))) { // we can hit offmesh connection as last poly - closestPointOnPoly() don't like that // try to recover by using prev polyref --prefixPolyLength; suffixStartPoly = _pathPolyRefs[prefixPolyLength-1]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, NULL))) + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, nullptr))) { // suffixStartPoly is still invalid, error state BuildShortcut(); @@ -512,8 +512,8 @@ void PathGenerator::BuildPointPath(const float *startPoint, const float *endPoin _pathPolyRefs, // current path _polyLength, // lenth of current path pathPoints, // [out] path corner points - NULL, // [out] flags - NULL, // [out] shortened path + nullptr, // [out] flags + nullptr, // [out] shortened path (int*)&pointCount, _pointPathLimit); // maximum number of points/polygons to use } @@ -678,7 +678,7 @@ bool PathGenerator::HaveTile(const G3D::Vector3& p) const if (tx < 0 || ty < 0) return false; - return (_navMesh->getTileAt(tx, ty, 0) != NULL); + return (_navMesh->getTileAt(tx, ty, 0) != nullptr); } uint32 PathGenerator::FixupCorridor(dtPolyRef* path, uint32 npath, uint32 maxPath, dtPolyRef const* visited, uint32 nvisited) @@ -885,7 +885,7 @@ dtStatus PathGenerator::FindSmoothPath(float const* startPos, float const* endPo return nsmoothPath < MAX_POINT_PATH_LENGTH ? DT_SUCCESS : DT_FAILURE; } -bool PathGenerator::InRangeYZX(const float* v1, const float* v2, float r, float h) const +bool PathGenerator::InRangeYZX(float const* v1, float const* v2, float r, float h) const { const float dx = v2[0] - v1[0]; const float dy = v2[1] - v1[1]; // elevation diff --git a/src/server/game/Movement/PathGenerator.h b/src/server/game/Movement/PathGenerator.h index a3e88b8a705..b840f5eb2c3 100644 --- a/src/server/game/Movement/PathGenerator.h +++ b/src/server/game/Movement/PathGenerator.h @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef _PATH_GENERATOR_H @@ -23,6 +23,7 @@ #include "DetourNavMesh.h" #include "DetourNavMeshQuery.h" #include "MoveSplineInitArgs.h" +#include class Unit; @@ -113,7 +114,7 @@ class TC_GAME_API PathGenerator float Dist3DSqr(G3D::Vector3 const& p1, G3D::Vector3 const& p2) const; bool InRangeYZX(float const* v1, float const* v2, float r, float h) const; - dtPolyRef GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 polyPathSize, float const* Point, float* Distance = NULL) const; + dtPolyRef GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 polyPathSize, float const* Point, float* Distance = nullptr) const; dtPolyRef GetPolyByLocation(float const* Point, float* Distance) const; bool HaveTile(G3D::Vector3 const& p) const; diff --git a/src/server/game/Movement/Spline/MoveSpline.cpp b/src/server/game/Movement/Spline/MoveSpline.cpp index e0ba41728c2..1d454f11b9c 100644 --- a/src/server/game/Movement/Spline/MoveSpline.cpp +++ b/src/server/game/Movement/Spline/MoveSpline.cpp @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #include "MoveSpline.h" @@ -117,9 +117,9 @@ struct CommonInitializer } }; -void MoveSpline::init_spline(const MoveSplineInitArgs& args) +void MoveSpline::init_spline(MoveSplineInitArgs const& args) { - const SplineBase::EvaluationMode modes[2] = {SplineBase::ModeLinear, SplineBase::ModeCatmullrom}; + static SplineBase::EvaluationMode const modes[2] = { SplineBase::ModeLinear, SplineBase::ModeCatmullrom }; if (args.flags.cyclic) { uint32 cyclic_point = 0; @@ -129,9 +129,7 @@ void MoveSpline::init_spline(const MoveSplineInitArgs& args) spline.init_cyclic_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()], cyclic_point); } else - { spline.init_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()]); - } // init spline timestamps if (splineflags.falling) @@ -237,6 +235,15 @@ bool MoveSplineInitArgs::_checkPathBounds() const return true; } +MoveSplineInitArgs::MoveSplineInitArgs(size_t path_capacity /*= 16*/) : path_Idx_offset(0), velocity(0.f), +parabolic_amplitude(0.f), time_perc(0.f), splineId(0), initialOrientation(0.f), +HasVelocity(false), TransformForTransport(true) +{ + path.reserve(path_capacity); +} + +MoveSplineInitArgs::~MoveSplineInitArgs() = default; + /// ============================================================================================ MoveSpline::UpdateResult MoveSpline::_updateState(int32& ms_time_diff) diff --git a/src/server/game/Movement/Spline/MoveSpline.h b/src/server/game/Movement/Spline/MoveSpline.h index 0e62862cecc..ac3c5e397dd 100644 --- a/src/server/game/Movement/Spline/MoveSpline.h +++ b/src/server/game/Movement/Spline/MoveSpline.h @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef TRINITYSERVER_MOVEPLINE_H @@ -21,6 +21,7 @@ #include "Spline.h" #include "MoveSplineInitArgs.h" +#include namespace Movement { @@ -28,8 +29,8 @@ namespace Movement { Location() : orientation(0) { } Location(float x, float y, float z, float o) : Vector3(x, y, z), orientation(o) { } - Location(const Vector3& v) : Vector3(v), orientation(0) { } - Location(const Vector3& v, float o) : Vector3(v), orientation(o) { } + Location(Vector3 const& v) : Vector3(v), orientation(0) { } + Location(Vector3 const& v, float o) : Vector3(v), orientation(o) { } float orientation; }; @@ -69,7 +70,7 @@ namespace Movement int32 point_Idx; int32 point_Idx_offset; - void init_spline(const MoveSplineInitArgs& args); + void init_spline(MoveSplineInitArgs const& args); protected: MySpline::ControlArray const& getPath() const { return spline.getPoints(); } @@ -90,7 +91,7 @@ namespace Movement void _Interrupt() { splineflags.done = true; } public: - void Initialize(const MoveSplineInitArgs&); + void Initialize(MoveSplineInitArgs const&); bool Initialized() const { return !spline.empty(); } MoveSpline(); diff --git a/src/server/game/Movement/Spline/MoveSplineFlag.h b/src/server/game/Movement/Spline/MoveSplineFlag.h index 0a3b41d412a..5630349812f 100644 --- a/src/server/game/Movement/Spline/MoveSplineFlag.h +++ b/src/server/game/Movement/Spline/MoveSplineFlag.h @@ -1,26 +1,25 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef TRINITYSERVER_MOVESPLINEFLAG_H #define TRINITYSERVER_MOVESPLINEFLAG_H -#include "MovementTypedefs.h" -#include +#include "MovementTypedefs.h" namespace Movement { @@ -71,11 +70,11 @@ namespace Movement }; inline uint32& raw() { return (uint32&)*this; } - inline const uint32& raw() const { return (const uint32&)*this; } + inline uint32 const& raw() const { return (uint32 const&)*this; } MoveSplineFlag() { raw() = 0; } MoveSplineFlag(uint32 f) { raw() = f; } - MoveSplineFlag(const MoveSplineFlag& f) { raw() = f.raw(); } + MoveSplineFlag(MoveSplineFlag const& f) { raw() = f.raw(); } // Constant interface diff --git a/src/server/game/Movement/Spline/MoveSplineInit.cpp b/src/server/game/Movement/Spline/MoveSplineInit.cpp index 180ecf23079..5e307eea35c 100644 --- a/src/server/game/Movement/Spline/MoveSplineInit.cpp +++ b/src/server/game/Movement/Spline/MoveSplineInit.cpp @@ -1,28 +1,29 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #include "MoveSplineInit.h" #include "MoveSpline.h" #include "MovementPacketBuilder.h" #include "Unit.h" +#include "PathGenerator.h" #include "Transport.h" -#include "WorldPacket.h" #include "Opcodes.h" +#include "WorldPacket.h" namespace Movement { @@ -184,7 +185,19 @@ namespace Movement args.flags.flying = unit->m_movementInfo.HasMovementFlag((MovementFlags)(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_DISABLE_GRAVITY)); } - void MoveSplineInit::SetFacing(const Unit* target) + MoveSplineInit::~MoveSplineInit() = default; + + void MoveSplineInit::SetFacing(Vector3 const& spot) + { + TransportPathTransform transform(unit, args.TransformForTransport); + Vector3 finalSpot = transform(spot); + args.facing.f.x = finalSpot.x; + args.facing.f.y = finalSpot.y; + args.facing.f.z = finalSpot.z; + args.flags.EnableFacingPoint(); + } + + void MoveSplineInit::SetFacing(Unit const* target) { args.flags.EnableFacingTarget(); args.facing.target = target->GetGUID().GetRawValue(); @@ -204,7 +217,19 @@ namespace Movement args.flags.EnableFacingAngle(); } - void MoveSplineInit::MoveTo(const Vector3& dest, bool generatePath, bool forceDestination) + void MoveSplineInit::MovebyPath(PointsArray const& controls, int32 path_offset) + { + args.path_Idx_offset = path_offset; + args.path.resize(controls.size()); + std::transform(controls.begin(), controls.end(), args.path.begin(), TransportPathTransform(unit, args.TransformForTransport)); + } + + void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination) + { + MoveTo(G3D::Vector3(x, y, z), generatePath, forceDestination); + } + + void MoveSplineInit::MoveTo(Vector3 const& dest, bool generatePath, bool forceDestination) { if (generatePath) { diff --git a/src/server/game/Movement/Spline/MoveSplineInit.h b/src/server/game/Movement/Spline/MoveSplineInit.h index 3f38da97916..f726af6487f 100644 --- a/src/server/game/Movement/Spline/MoveSplineInit.h +++ b/src/server/game/Movement/Spline/MoveSplineInit.h @@ -1,26 +1,25 @@ /* - * Copyright (C) 2005-2011 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ +* Copyright (C) 2008-2017 TrinityCore +* Copyright (C) 2005-2009 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 the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see . +*/ #ifndef TRINITYSERVER_MOVESPLINEINIT_H #define TRINITYSERVER_MOVESPLINEINIT_H #include "MoveSplineInitArgs.h" -#include "PathGenerator.h" class Unit; @@ -54,6 +53,9 @@ namespace Movement public: explicit MoveSplineInit(Unit* m); + ~MoveSplineInit(); + MoveSplineInit(MoveSplineInit const&) = delete; + MoveSplineInit& operator=(MoveSplineInit const&) = delete; /* Final pass of initialization that launches spline movement. */ @@ -80,17 +82,17 @@ namespace Movement */ void SetFacing(float angle); void SetFacing(Vector3 const& point); - void SetFacing(const Unit* target); + void SetFacing(Unit const* target); /* Initializes movement by path * @param path - array of points, shouldn't be empty * @param pointId - Id of fisrt point of the path. Example: when third path point will be done it will notify that pointId + 3 done */ - void MovebyPath(const PointsArray& path, int32 pointId = 0); + void MovebyPath(PointsArray const& path, int32 pointId = 0); /* Initializes simple A to B motion, A is current unit's position, B is destination */ - void MoveTo(const Vector3& destination, bool generatePath = true, bool forceDestination = false); + void MoveTo(Vector3 const& destination, bool generatePath = true, bool forceDestination = false); void MoveTo(float x, float y, float z, bool generatePath = true, bool forceDestination = false); /* Sets Id of fisrt point of the path. When N-th path point will be done ILisener will notify that pointId + N done @@ -156,18 +158,6 @@ namespace Movement inline void MoveSplineInit::SetTransportExit() { args.flags.EnableTransportExit(); } inline void MoveSplineInit::SetOrientationFixed(bool enable) { args.flags.orientationFixed = enable; } - inline void MoveSplineInit::MovebyPath(const PointsArray& controls, int32 path_offset) - { - args.path_Idx_offset = path_offset; - args.path.resize(controls.size()); - std::transform(controls.begin(), controls.end(), args.path.begin(), TransportPathTransform(unit, args.TransformForTransport)); - } - - inline void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination) - { - MoveTo(G3D::Vector3(x, y, z), generatePath, forceDestination); - } - inline void MoveSplineInit::SetParabolic(float amplitude, float time_shift) { args.time_perc = time_shift; @@ -181,16 +171,6 @@ namespace Movement args.flags.EnableAnimation((uint8)anim); } - inline void MoveSplineInit::SetFacing(Vector3 const& spot) - { - TransportPathTransform transform(unit, args.TransformForTransport); - Vector3 finalSpot = transform(spot); - args.facing.f.x = finalSpot.x; - args.facing.f.y = finalSpot.y; - args.facing.f.z = finalSpot.z; - args.flags.EnableFacingPoint(); - } - inline void MoveSplineInit::DisableTransportPathTransformations() { args.TransformForTransport = false; } } #endif // TRINITYSERVER_MOVESPLINEINIT_H diff --git a/src/server/game/Movement/Spline/MoveSplineInitArgs.h b/src/server/game/Movement/Spline/MoveSplineInitArgs.h index 12c22898b6d..d3ce9e66bc4 100644 --- a/src/server/game/Movement/Spline/MoveSplineInitArgs.h +++ b/src/server/game/Movement/Spline/MoveSplineInitArgs.h @@ -1,26 +1,26 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef TRINITYSERVER_MOVESPLINEINIT_ARGS_H #define TRINITYSERVER_MOVESPLINEINIT_ARGS_H #include "MoveSplineFlag.h" -#include +#include class Unit; @@ -43,12 +43,8 @@ namespace Movement struct MoveSplineInitArgs { - MoveSplineInitArgs(size_t path_capacity = 16) : path_Idx_offset(0), velocity(0.f), - parabolic_amplitude(0.f), time_perc(0.f), splineId(0), initialOrientation(0.f), - HasVelocity(false), TransformForTransport(true) - { - path.reserve(path_capacity); - } + MoveSplineInitArgs(size_t path_capacity = 16); + ~MoveSplineInitArgs(); PointsArray path; FacingInfo facing; diff --git a/src/server/game/Movement/Spline/MovementPacketBuilder.cpp b/src/server/game/Movement/Spline/MovementPacketBuilder.cpp index e6a02ec5ce7..d747f33082f 100644 --- a/src/server/game/Movement/Spline/MovementPacketBuilder.cpp +++ b/src/server/game/Movement/Spline/MovementPacketBuilder.cpp @@ -1,34 +1,34 @@ /* * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #include "MovementPacketBuilder.h" -#include "MoveSpline.h" #include "ByteBuffer.h" +#include "MoveSpline.h" +#include "Position.h" namespace Movement { - inline void operator << (ByteBuffer& b, const Vector3& v) + inline void operator<<(ByteBuffer& b, Vector3 const& v) { b << v.x << v.y << v.z; } - inline void operator >> (ByteBuffer& b, Vector3& v) + inline void operator>>(ByteBuffer& b, Vector3& v) { b >> v.x >> v.y >> v.z; } @@ -42,7 +42,7 @@ namespace Movement MonsterMoveFacingAngle = 4 }; - void PacketBuilder::WriteCommonMonsterMovePart(const MoveSpline& move_spline, ByteBuffer& data) + void PacketBuilder::WriteCommonMonsterMovePart(MoveSpline const& move_spline, ByteBuffer& data) { MoveSplineFlag splineflags = move_spline.splineflags; @@ -88,7 +88,7 @@ namespace Movement } } - void PacketBuilder::WriteStopMovement(Vector3 const& pos, uint32 splineId, ByteBuffer& data) + void PacketBuilder::WriteStopMovement(G3D::Vector3 const& pos, uint32 splineId, ByteBuffer& data) { data << uint8(0); // sets/unsets MOVEMENTFLAG2_UNK7 (0x40) data << pos; @@ -96,42 +96,42 @@ namespace Movement data << uint8(MonsterMoveStop); } - void WriteLinearPath(const Spline& spline, ByteBuffer& data) + void WriteLinearPath(Spline const& spline, ByteBuffer& data) { uint32 last_idx = spline.getPointCount() - 3; - const Vector3 * real_path = &spline.getPoint(1); + G3D::Vector3 const* real_path = &spline.getPoint(1); data << last_idx; data << real_path[last_idx]; // destination if (last_idx > 1) { - Vector3 middle = (real_path[0] + real_path[last_idx]) / 2.f; - Vector3 offset; + G3D::Vector3 middle = (real_path[0] + real_path[last_idx]) / 2.f; + G3D::Vector3 offset; // first and last points already appended for (uint32 i = 1; i < last_idx; ++i) { offset = middle - real_path[i]; - data.appendPackXYZ(offset.x, offset.y, offset.z); + data << TaggedPosition(offset.x, offset.y, offset.z); } } } - void WriteCatmullRomPath(const Spline& spline, ByteBuffer& data) + void WriteCatmullRomPath(Spline const& spline, ByteBuffer& data) { uint32 count = spline.getPointCount() - 3; data << count; - data.append(&spline.getPoint(2), count); + data.append(&spline.getPoint(2), count); } - void WriteCatmullRomCyclicPath(const Spline& spline, ByteBuffer& data) + void WriteCatmullRomCyclicPath(Spline const& spline, ByteBuffer& data) { uint32 count = spline.getPointCount() - 3; data << uint32(count + 1); data << spline.getPoint(1); // fake point, client will erase it from the spline after first cycle done - data.append(&spline.getPoint(1), count); + data.append(&spline.getPoint(1), count); } - void PacketBuilder::WriteMonsterMove(const MoveSpline& move_spline, ByteBuffer& data) + void PacketBuilder::WriteMonsterMove(MoveSpline const& move_spline, ByteBuffer& data) { WriteCommonMonsterMovePart(move_spline, data); @@ -148,7 +148,7 @@ namespace Movement WriteLinearPath(spline, data); } - void PacketBuilder::WriteCreate(const MoveSpline& move_spline, ByteBuffer& data) + void PacketBuilder::WriteCreate(MoveSpline const& move_spline, ByteBuffer& data) { //WriteClientStatus(mov, data); //data.append(&mov.m_float_values[SpeedWalk], SpeedMaxCount); @@ -183,9 +183,9 @@ namespace Movement uint32 nodes = move_spline.getPath().size(); data << nodes; - data.append(&move_spline.getPath()[0], nodes); + data.append(&move_spline.getPath()[0], nodes); data << uint8(move_spline.spline.mode()); // added in 3.1 - data << (move_spline.isCyclic() ? Vector3::zero() : move_spline.FinalDestination()); + data << (move_spline.isCyclic() ? G3D::Vector3::zero() : move_spline.FinalDestination()); } } } diff --git a/src/server/game/Movement/Spline/MovementPacketBuilder.h b/src/server/game/Movement/Spline/MovementPacketBuilder.h index 4a078904424..2648ca46dd3 100644 --- a/src/server/game/Movement/Spline/MovementPacketBuilder.h +++ b/src/server/game/Movement/Spline/MovementPacketBuilder.h @@ -1,20 +1,19 @@ /* * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef TRINITYSERVER_PACKET_BUILDER_H @@ -30,17 +29,15 @@ namespace G3D namespace Movement { - using G3D::Vector3; - class MoveSpline; class PacketBuilder { - static void WriteCommonMonsterMovePart(const MoveSpline& mov, ByteBuffer& data); + static void WriteCommonMonsterMovePart(MoveSpline const& mov, ByteBuffer& data); public: - static void WriteMonsterMove(const MoveSpline& mov, ByteBuffer& data); - static void WriteStopMovement(Vector3 const& loc, uint32 splineId, ByteBuffer& data); - static void WriteCreate(const MoveSpline& mov, ByteBuffer& data); + static void WriteMonsterMove(MoveSpline const& mov, ByteBuffer& data); + static void WriteStopMovement(G3D::Vector3 const& loc, uint32 splineId, ByteBuffer& data); + static void WriteCreate(MoveSpline const& mov, ByteBuffer& data); }; } #endif // TRINITYSERVER_PACKET_BUILDER_H diff --git a/src/server/game/Movement/Spline/MovementTypedefs.h b/src/server/game/Movement/Spline/MovementTypedefs.h index c87fea47a82..6a06bde0f49 100644 --- a/src/server/game/Movement/Spline/MovementTypedefs.h +++ b/src/server/game/Movement/Spline/MovementTypedefs.h @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef TRINITYSERVER_TYPEDEFS_H diff --git a/src/server/game/Movement/Spline/MovementUtil.cpp b/src/server/game/Movement/Spline/MovementUtil.cpp index 4f7e1d6a7a4..8105d886384 100644 --- a/src/server/game/Movement/Spline/MovementUtil.cpp +++ b/src/server/game/Movement/Spline/MovementUtil.cpp @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #include "MoveSplineFlag.h" @@ -180,7 +180,7 @@ namespace Movement { for (int i = 0; i < N; ++i) { - if ((t & Flags(1 << i)) && names[i] != NULL) + if ((t & Flags(1 << i)) && names[i] != nullptr) str.append(" ").append(names[i]); } } diff --git a/src/server/game/Movement/Spline/Spline.cpp b/src/server/game/Movement/Spline/Spline.cpp index fff83b788f9..308c14973c6 100644 --- a/src/server/game/Movement/Spline/Spline.cpp +++ b/src/server/game/Movement/Spline/Spline.cpp @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #include "Spline.h" @@ -94,7 +94,7 @@ inline void C_Evaluate(const Vector3 *vertice, float t, const float (&matrix)[4] position.z = z; }*/ -inline void C_Evaluate(const Vector3 *vertice, float t, const Matrix4& matr, Vector3 &result) +inline void C_Evaluate(Vector3 const* vertice, float t, Matrix4 const& matr, Vector3 &result) { Vector4 tvec(t*t*t, t*t, t, 1.f); Vector4 weights(tvec * matr); @@ -103,7 +103,7 @@ inline void C_Evaluate(const Vector3 *vertice, float t, const Matrix4& matr, Vec + vertice[2] * weights[2] + vertice[3] * weights[3]; } -inline void C_Evaluate_Derivative(const Vector3 *vertice, float t, const Matrix4& matr, Vector3 &result) +inline void C_Evaluate_Derivative(Vector3 const* vertice, float t, Matrix4 const& matr, Vector3 &result) { Vector4 tvec(3.f*t*t, 2.f*t, 1.f, 0.f); Vector4 weights(tvec * matr); @@ -215,7 +215,7 @@ void SplineBase::init_cyclic_spline(const Vector3 * controls, index_type count, (this->*initializers[m_mode])(controls, count, cyclic_point); } -void SplineBase::InitLinear(const Vector3* controls, index_type count, index_type cyclic_point) +void SplineBase::InitLinear(Vector3 const* controls, index_type count, index_type cyclic_point) { ASSERT(count >= 2); const int real_size = count + 1; @@ -235,7 +235,7 @@ void SplineBase::InitLinear(const Vector3* controls, index_type count, index_typ index_hi = cyclic ? count : (count - 1); } -void SplineBase::InitCatmullRom(const Vector3* controls, index_type count, index_type cyclic_point) +void SplineBase::InitCatmullRom(Vector3 const* controls, index_type count, index_type cyclic_point) { const int real_size = count + (cyclic ? (1+2) : (1+1)); @@ -268,7 +268,7 @@ void SplineBase::InitCatmullRom(const Vector3* controls, index_type count, index index_hi = high_index + (cyclic ? 1 : 0); } -void SplineBase::InitBezier3(const Vector3* controls, index_type count, index_type /*cyclic_point*/) +void SplineBase::InitBezier3(Vector3 const* controls, index_type count, index_type /*cyclic_point*/) { index_type c = count / 3u * 3u; index_type t = c / 3u; diff --git a/src/server/game/Movement/Spline/Spline.h b/src/server/game/Movement/Spline/Spline.h index 59f514bed75..9155369afed 100644 --- a/src/server/game/Movement/Spline/Spline.h +++ b/src/server/game/Movement/Spline/Spline.h @@ -1,27 +1,29 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ #ifndef TRINITYSERVER_SPLINE_H #define TRINITYSERVER_SPLINE_H #include "MovementTypedefs.h" +#include "Errors.h" #include #include +#include namespace Movement { @@ -76,10 +78,10 @@ protected: typedef float (SplineBase::*SegLenghtMethtod)(index_type) const; static SegLenghtMethtod seglengths[ModesEnd]; - void InitLinear(const Vector3*, index_type, index_type); - void InitCatmullRom(const Vector3*, index_type, index_type); - void InitBezier3(const Vector3*, index_type, index_type); - typedef void (SplineBase::*InitMethtod)(const Vector3*, index_type, index_type); + void InitLinear(Vector3 const*, index_type, index_type); + void InitCatmullRom(Vector3 const*, index_type, index_type); + void InitBezier3(Vector3 const*, index_type, index_type); + typedef void (SplineBase::*InitMethtod)(Vector3 const*, index_type, index_type); static InitMethtod initializers[ModesEnd]; void UninitializedSpline() const { ABORT();} @@ -108,9 +110,9 @@ public: EvaluationMode mode() const { return (EvaluationMode)m_mode;} bool isCyclic() const { return cyclic;} - const ControlArray& getPoints() const { return points;} + ControlArray const& getPoints() const { return points;} index_type getPointCount() const { return points.size();} - const Vector3& getPoint(index_type i) const { return points[i];} + Vector3 const& getPoint(index_type i) const { return points[i];} /** Initializes spline. Don't call other methods while spline not initialized. */ void init_spline(const Vector3 * controls, index_type count, EvaluationMode m); diff --git a/src/server/game/Movement/Spline/SplineChain.h b/src/server/game/Movement/Spline/SplineChain.h index 51e0d0a1a2e..8256838718a 100644 --- a/src/server/game/Movement/Spline/SplineChain.h +++ b/src/server/game/Movement/Spline/SplineChain.h @@ -19,6 +19,7 @@ #define TRINITY_SPLINECHAIN_H #include "MoveSplineInitArgs.h" +#include struct TC_GAME_API SplineChainLink { @@ -29,17 +30,16 @@ struct TC_GAME_API SplineChainLink uint32 ExpectedDuration; uint32 TimeToNext; }; -typedef std::vector SplineChain; struct TC_GAME_API SplineChainResumeInfo { SplineChainResumeInfo() : PointID(0), Chain(nullptr), IsWalkMode(false), SplineIndex(0), PointIndex(0), TimeToNext(0) { } - SplineChainResumeInfo(uint32 id, SplineChain const* chain, bool walk, uint8 splineIndex, uint8 wpIndex, uint32 msToNext) : + SplineChainResumeInfo(uint32 id, std::vector const* chain, bool walk, uint8 splineIndex, uint8 wpIndex, uint32 msToNext) : PointID(id), Chain(chain), IsWalkMode(walk), SplineIndex(splineIndex), PointIndex(wpIndex), TimeToNext(msToNext) { } bool Empty() const { return Chain == nullptr; } void Clear() { Chain = nullptr; } uint32 PointID; - SplineChain const* Chain; + std::vector const* Chain; bool IsWalkMode; uint8 SplineIndex; uint8 PointIndex; diff --git a/src/server/game/Movement/Spline/SplineImpl.h b/src/server/game/Movement/Spline/SplineImpl.h index 98f3f5fe079..1502fcc1022 100644 --- a/src/server/game/Movement/Spline/SplineImpl.h +++ b/src/server/game/Movement/Spline/SplineImpl.h @@ -1,19 +1,19 @@ /* - * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2005-2009 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 - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ namespace Movement diff --git a/src/server/game/Movement/Waypoints/WaypointManager.h b/src/server/game/Movement/Waypoints/WaypointManager.h index 97227becbc1..f62805594ef 100644 --- a/src/server/game/Movement/Waypoints/WaypointManager.h +++ b/src/server/game/Movement/Waypoints/WaypointManager.h @@ -19,7 +19,9 @@ #ifndef TRINITY_WAYPOINTMANAGER_H #define TRINITY_WAYPOINTMANAGER_H +#include "Define.h" #include +#include enum WaypointMoveType { @@ -62,7 +64,7 @@ class TC_GAME_API WaypointMgr if (itr != _waypointStore.end()) return &itr->second; - return NULL; + return nullptr; } private: diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index bb2d9f539bf..a2d195bea20 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -16,16 +16,18 @@ */ #include "OutdoorPvP.h" -#include "OutdoorPvPMgr.h" +#include "CellImpl.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MapManager.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "Map.h" -#include "Group.h" +#include "OutdoorPvPMgr.h" #include "WorldPacket.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" -#include "MapManager.h" class DefenseMessageBuilder { @@ -49,7 +51,7 @@ class DefenseMessageBuilder }; OPvPCapturePoint::OPvPCapturePoint(OutdoorPvP* pvp): - m_capturePointSpawnId(), m_capturePoint(NULL), m_maxValue(0.0f), m_minValue(0.0f), m_maxSpeed(0), + m_capturePointSpawnId(), m_capturePoint(nullptr), m_maxValue(0.0f), m_minValue(0.0f), m_maxSpeed(0), m_value(0), m_team(TEAM_NEUTRAL), m_OldState(OBJECTIVESTATE_NEUTRAL), m_State(OBJECTIVESTATE_NEUTRAL), m_neutralValuePct(0), m_PvP(pvp) { } @@ -113,7 +115,7 @@ void OPvPCapturePoint::AddCre(uint32 type, ObjectGuid::LowType guid, uint32 entr m_CreatureTypes[m_Creatures[type]] = type; } -bool OPvPCapturePoint::AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot) +bool OPvPCapturePoint::AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot) { if (ObjectGuid::LowType guid = sObjectMgr->AddGOData(entry, map, pos, rot, 0)) { @@ -135,7 +137,7 @@ bool OPvPCapturePoint::AddCreature(uint32 type, uint32 entry, uint32 map, Positi return false; } -bool OPvPCapturePoint::SetCapturePointData(uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot) +bool OPvPCapturePoint::SetCapturePointData(uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot) { TC_LOG_DEBUG("outdoorpvp", "Creating capture point %u", entry); @@ -473,7 +475,7 @@ void OutdoorPvP::HandleKill(Player* killer, Unit* killed) { if (Group* group = killer->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupGuy = itr->GetSource(); @@ -509,7 +511,7 @@ bool OutdoorPvP::IsInsideObjective(Player* player) const bool OPvPCapturePoint::IsInsideObjective(Player* player) const { - GuidSet const &plSet = m_activePlayers[player->GetTeamId()]; + GuidSet const& plSet = m_activePlayers[player->GetTeamId()]; return plSet.find(player->GetGUID()) != plSet.end(); } @@ -600,7 +602,7 @@ void OutdoorPvP::BroadcastPacket(WorldPacket &data) const for (uint32 team = 0; team < BG_TEAMS_COUNT; ++team) for (GuidSet::const_iterator itr = m_players[team].begin(); itr != m_players[team].end(); ++itr) if (Player* const player = ObjectAccessor::FindPlayer(*itr)) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void OutdoorPvP::RegisterZone(uint32 zoneId) @@ -610,7 +612,7 @@ void OutdoorPvP::RegisterZone(uint32 zoneId) bool OutdoorPvP::HasPlayer(Player const* player) const { - GuidSet const &plSet = m_players[player->GetTeamId()]; + GuidSet const& plSet = m_players[player->GetTeamId()]; return plSet.find(player->GetGUID()) != plSet.end(); } @@ -655,7 +657,7 @@ void OutdoorPvP::OnGameObjectRemove(GameObject* go) return; if (OPvPCapturePoint *cp = GetCapturePoint(go->GetSpawnId())) - cp->m_capturePoint = NULL; + cp->m_capturePoint = nullptr; } void OutdoorPvP::OnCreatureCreate(Creature* creature) @@ -688,8 +690,7 @@ void OutdoorPvP::BroadcastWorker(Worker& _worker, uint32 zoneId) void OutdoorPvP::SetMapFromZone(uint32 zone) { - AreaTableEntry const* areaTable = sAreaTableStore.LookupEntry(zone); - ASSERT(areaTable); + AreaTableEntry const* areaTable = sAreaTableStore.AssertEntry(zone); Map* map = sMapMgr->CreateBaseMap(areaTable->mapid); ASSERT(!map->Instanceable()); m_map = map; diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.h b/src/server/game/OutdoorPvP/OutdoorPvP.h index a918365b11d..39348155798 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.h +++ b/src/server/game/OutdoorPvP/OutdoorPvP.h @@ -18,11 +18,11 @@ #ifndef OUTDOOR_PVP_H_ #define OUTDOOR_PVP_H_ -#include "Util.h" +#include "GameObjectData.h" +#include "Position.h" #include "SharedDefines.h" #include "ZoneScript.h" - -#include +#include enum OutdoorPvPTypes { @@ -55,7 +55,7 @@ struct go_type uint32 entry; uint32 map; Position pos; - G3D::Quat rot; + QuaternionData rot; }; // struct for creature spawning @@ -66,14 +66,14 @@ struct creature_type Position pos; }; -// some class predefs -class Player; -class GameObject; -class WorldPacket; class Creature; +class GameObject; +class Map; +class OutdoorPvP; +class Player; class Unit; +class WorldPacket; struct GossipMenuItems; -class OutdoorPvP; class TC_GAME_API OPvPCapturePoint { @@ -126,11 +126,11 @@ class TC_GAME_API OPvPCapturePoint void AddGO(uint32 type, ObjectGuid::LowType guid, uint32 entry = 0); void AddCre(uint32 type, ObjectGuid::LowType guid, uint32 entry = 0); - bool SetCapturePointData(uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot); + bool SetCapturePointData(uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot); protected: - bool AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot); + bool AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot); bool AddCreature(uint32 type, uint32 entry, uint32 map, Position const& pos, TeamId teamId = TEAM_NEUTRAL, uint32 spawntimedelay = 0); bool DelObject(uint32 type); diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp index a1de152d9ae..ebe3d568beb 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp @@ -16,9 +16,11 @@ */ #include "OutdoorPvPMgr.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" +#include "Log.h" #include "ObjectMgr.h" #include "Player.h" -#include "DisableMgr.h" #include "ScriptMgr.h" OutdoorPvPMgr::OutdoorPvPMgr() @@ -33,8 +35,7 @@ void OutdoorPvPMgr::Die() m_OutdoorPvPSet.clear(); - for (uint32 i = 0; i < MAX_OUTDOORPVP_TYPES; ++i) - m_OutdoorPvPDatas[i] = 0; + m_OutdoorPvPDatas.fill(0); m_OutdoorPvPMap.clear(); } @@ -66,7 +67,7 @@ void OutdoorPvPMgr::InitOutdoorPvP() typeId = fields[0].GetUInt8(); - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, typeId, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, typeId, nullptr)) continue; if (typeId >= MAX_OUTDOORPVP_TYPES) @@ -149,7 +150,7 @@ OutdoorPvP* OutdoorPvPMgr::GetOutdoorPvPToZoneId(uint32 zoneid) if (itr == m_OutdoorPvPMap.end()) { // no handle for this zone, return - return NULL; + return nullptr; } return itr->second; } @@ -181,7 +182,7 @@ ZoneScript* OutdoorPvPMgr::GetZoneScript(uint32 zoneId) if (itr != m_OutdoorPvPMap.end()) return itr->second; else - return NULL; + return nullptr; } bool OutdoorPvPMgr::HandleOpenGo(Player* player, GameObject* go) diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h index e69d9482edd..9cd1dcf61c7 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h @@ -21,12 +21,15 @@ #define OUTDOORPVP_OBJECTIVE_UPDATE_INTERVAL 1000 #include "OutdoorPvP.h" +#include +#include class Player; class GameObject; class Creature; class ZoneScript; struct GossipMenuItems; +enum LocaleConstant : uint8; // class to handle player enter / leave / areatrigger / GO use events class TC_GAME_API OutdoorPvPMgr @@ -78,7 +81,7 @@ class TC_GAME_API OutdoorPvPMgr private: typedef std::vector OutdoorPvPSet; - typedef std::unordered_map OutdoorPvPMap; + typedef std::unordered_map OutdoorPvPMap; typedef std::array OutdoorPvPScriptIds; // contains all initiated outdoor pvp events diff --git a/src/server/game/Petitions/PetitionMgr.cpp b/src/server/game/Petitions/PetitionMgr.cpp index d249d3a8f87..ec583353e3e 100644 --- a/src/server/game/Petitions/PetitionMgr.cpp +++ b/src/server/game/Petitions/PetitionMgr.cpp @@ -17,11 +17,12 @@ #include "PetitionMgr.h" #include "DatabaseEnv.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "WorldSession.h" #include "Timer.h" - +#include "WorldSession.h" #include namespace diff --git a/src/server/game/Petitions/PetitionMgr.h b/src/server/game/Petitions/PetitionMgr.h index 119f24ac255..401f09aab5a 100644 --- a/src/server/game/Petitions/PetitionMgr.h +++ b/src/server/game/Petitions/PetitionMgr.h @@ -21,7 +21,6 @@ #include "Define.h" #include "ObjectGuid.h" #include "SharedDefines.h" - #include #include #include diff --git a/src/server/game/Pools/PoolMgr.cpp b/src/server/game/Pools/PoolMgr.cpp index 76ea5eb5015..9305e226421 100644 --- a/src/server/game/Pools/PoolMgr.cpp +++ b/src/server/game/Pools/PoolMgr.cpp @@ -18,9 +18,10 @@ #include "PoolMgr.h" #include "Containers.h" -#include "ObjectMgr.h" +#include "DatabaseEnv.h" #include "Log.h" #include "MapManager.h" +#include "ObjectMgr.h" //////////////////////////////////////////////////////////// // template class ActivePoolData @@ -177,7 +178,7 @@ PoolObject* PoolGroup::RollOne(ActivePoolData& spawns, uint32 triggerFrom) return &EqualChanced[index]; } - return NULL; + return nullptr; } // Main method to despawn a creature or gameobject in a pool @@ -797,8 +798,8 @@ void PoolMgr::LoadFromDB() if (checkedPools.find(poolItr->second) != checkedPools.end()) { std::ostringstream ss; - ss<< "The pool(s) "; - for (std::set::const_iterator itr=checkedPools.begin(); itr != checkedPools.end(); ++itr) + ss << "The pool(s) "; + for (std::set::const_iterator itr = checkedPools.begin(); itr != checkedPools.end(); ++itr) ss << *itr << ' '; ss << "create(s) a circular reference, which can cause the server to freeze.\nRemoving the last link between mother pool " << poolItr->first << " and child pool " << poolItr->second; @@ -909,8 +910,8 @@ void PoolMgr::LoadFromDB() uint32 oldMSTime = getMSTime(); QueryResult result = WorldDatabase.Query("SELECT DISTINCT pool_template.entry, pool_pool.pool_id, pool_pool.mother_pool FROM pool_template" - " LEFT JOIN game_event_pool ON pool_template.entry=game_event_pool.pool_entry" - " LEFT JOIN pool_pool ON pool_template.entry=pool_pool.pool_id WHERE game_event_pool.pool_entry IS NULL"); + " LEFT JOIN game_event_pool ON pool_template.entry = game_event_pool.pool_entry" + " LEFT JOIN pool_pool ON pool_template.entry = pool_pool.pool_id WHERE game_event_pool.pool_entry IS NULL"); if (!result) { diff --git a/src/server/game/PrecompiledHeaders/gamePCH.cpp b/src/server/game/PrecompiledHeaders/gamePCH.cpp index 11e501ec7f2..b073230fd25 100644 --- a/src/server/game/PrecompiledHeaders/gamePCH.cpp +++ b/src/server/game/PrecompiledHeaders/gamePCH.cpp @@ -1 +1,18 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "gamePCH.h" diff --git a/src/server/game/PrecompiledHeaders/gamePCH.h b/src/server/game/PrecompiledHeaders/gamePCH.h index c7c6ca5d2d6..ba103d21906 100644 --- a/src/server/game/PrecompiledHeaders/gamePCH.h +++ b/src/server/game/PrecompiledHeaders/gamePCH.h @@ -1,10 +1,32 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + //add here most rarely modified headers to speed up debug build compilation -#include "Common.h" -#include "MapManager.h" +#include "Creature.h" +#include "DBCStores.h" +#include "DatabaseEnv.h" +#include "Errors.h" +#include "GameObject.h" #include "Log.h" #include "ObjectAccessor.h" -#include "ObjectDefines.h" -#include "Opcodes.h" -#include "SharedDefines.h" #include "ObjectMgr.h" +#include "PacketUtilities.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" diff --git a/src/server/game/Quests/QuestDef.cpp b/src/server/game/Quests/QuestDef.cpp index 44ba68bcfb3..55100ca7396 100644 --- a/src/server/game/Quests/QuestDef.cpp +++ b/src/server/game/Quests/QuestDef.cpp @@ -17,12 +17,14 @@ */ #include "QuestDef.h" -#include "Player.h" -#include "World.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Log.h" #include "ObjectMgr.h" #include "Opcodes.h" - -#include "Packets/QuestPackets.h" +#include "Player.h" +#include "QuestPackets.h" +#include "World.h" Quest::Quest(Field* questRecord) { diff --git a/src/server/game/Quests/QuestDef.h b/src/server/game/Quests/QuestDef.h index eb653ccf096..d2a5e0d5d84 100644 --- a/src/server/game/Quests/QuestDef.h +++ b/src/server/game/Quests/QuestDef.h @@ -19,19 +19,15 @@ #ifndef TRINITYCORE_QUEST_H #define TRINITYCORE_QUEST_H -#include "Define.h" -#include "DatabaseEnv.h" -#include "SharedDefines.h" +#include "Common.h" #include "DBCEnums.h" +#include "DatabaseEnvFwd.h" +#include "SharedDefines.h" #include "WorldPacket.h" - -#include #include class Player; -class ObjectMgr; - #define MAX_QUEST_LOG_SIZE 25 #define QUEST_OBJECTIVES_COUNT 4 @@ -96,7 +92,7 @@ enum QuestTradeSkill QUEST_TRSKILL_JEWELCRAFTING = 14 }; -enum QuestStatus +enum QuestStatus : uint8 { QUEST_STATUS_NONE = 0, QUEST_STATUS_COMPLETE = 1, @@ -180,14 +176,14 @@ struct QuestLocale { QuestLocale() { ObjectiveText.resize(QUEST_OBJECTIVES_COUNT); } - StringVector Title; - StringVector Details; - StringVector Objectives; - StringVector OfferRewardText; - StringVector RequestItemsText; - StringVector AreaDescription; - StringVector CompletedText; - std::vector< StringVector > ObjectiveText; + std::vector Title; + std::vector Details; + std::vector Objectives; + std::vector OfferRewardText; + std::vector RequestItemsText; + std::vector AreaDescription; + std::vector CompletedText; + std::vector> ObjectiveText; }; // This Quest class provides a convenient way to access a few pretotaled (cached) quest details, diff --git a/src/server/game/Reputation/ReputationMgr.cpp b/src/server/game/Reputation/ReputationMgr.cpp index 9b290df79ee..b688a212464 100644 --- a/src/server/game/Reputation/ReputationMgr.cpp +++ b/src/server/game/Reputation/ReputationMgr.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "ReputationMgr.h" +#include "DatabaseEnv.h" #include "DBCStores.h" -#include "Player.h" -#include "WorldPacket.h" -#include "World.h" +#include "Log.h" #include "ObjectMgr.h" +#include "Player.h" #include "ScriptMgr.h" +#include "World.h" +#include "WorldPacket.h" #include "WorldSession.h" const int32 ReputationMgr::PointsInRank[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000}; @@ -287,7 +288,7 @@ bool ReputationMgr::SetReputation(FactionEntry const* factionEntry, int32 standi sScriptMgr->OnPlayerReputationChange(_player, factionEntry->ID, standing, incremental); bool res = false; // if spillover definition exists in DB, override DBC - if (const RepSpilloverTemplate* repTemplate = sObjectMgr->GetRepSpilloverTemplate(factionEntry->ID)) + if (RepSpilloverTemplate const* repTemplate = sObjectMgr->GetRepSpilloverTemplate(factionEntry->ID)) { for (uint32 i = 0; i < MAX_SPILLOVER_FACTIONS; ++i) { diff --git a/src/server/game/Reputation/ReputationMgr.h b/src/server/game/Reputation/ReputationMgr.h index b9241bbb10d..1a97d1972af 100644 --- a/src/server/game/Reputation/ReputationMgr.h +++ b/src/server/game/Reputation/ReputationMgr.h @@ -86,13 +86,13 @@ class TC_GAME_API ReputationMgr FactionState const* GetState(FactionEntry const* factionEntry) const { - return factionEntry->CanHaveReputation() ? GetState(factionEntry->reputationListID) : NULL; + return factionEntry->CanHaveReputation() ? GetState(factionEntry->reputationListID) : nullptr; } FactionState const* GetState(RepListID id) const { FactionStateList::const_iterator repItr = _factions.find (id); - return repItr != _factions.end() ? &repItr->second : NULL; + return repItr != _factions.end() ? &repItr->second : nullptr; } bool IsAtWar(uint32 faction_id) const; @@ -112,7 +112,7 @@ class TC_GAME_API ReputationMgr ReputationRank const* GetForcedRankIfAny(FactionTemplateEntry const* factionTemplateEntry) const { ForcedReactions::const_iterator forceItr = _forcedReactions.find(factionTemplateEntry->faction); - return forceItr != _forcedReactions.end() ? &forceItr->second : NULL; + return forceItr != _forcedReactions.end() ? &forceItr->second : nullptr; } public: // modifiers diff --git a/src/server/game/Scripting/ScriptMgr.cpp b/src/server/game/Scripting/ScriptMgr.cpp index 5d71b0ed33e..9f42ded8cc6 100644 --- a/src/server/game/Scripting/ScriptMgr.cpp +++ b/src/server/game/Scripting/ScriptMgr.cpp @@ -17,27 +17,32 @@ */ #include "ScriptMgr.h" -#include "ScriptReloadMgr.h" +#include "Chat.h" #include "Config.h" +#include "Creature.h" +#include "CreatureAIImpl.h" #include "DatabaseEnv.h" #include "DBCStores.h" +#include "GossipDef.h" +#include "InstanceScript.h" +#include "Item.h" +#include "LFGScripts.h" +#include "Log.h" +#include "MapManager.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" +#include "Player.h" +#include "ScriptReloadMgr.h" #include "ScriptSystem.h" -#include "Transport.h" -#include "Vehicle.h" #include "SmartAI.h" #include "SpellInfo.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "GossipDef.h" -#include "CreatureAIImpl.h" -#include "Player.h" +#include "Transport.h" +#include "Vehicle.h" +#include "Weather.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "Chat.h" -#include "MapManager.h" -#include "LFGScripts.h" -#include "InstanceScript.h" // Trait which indicates whether this script type // must be assigned in the database. @@ -984,7 +989,7 @@ struct TSpellSummary uint8 Effects; // set of enum SelectEffect } *SpellSummary; -ScriptObject::ScriptObject(const char* name) : _name(name) +ScriptObject::ScriptObject(char const* name) : _name(name) { sScriptMgr->IncreaseScriptCount(); } @@ -1508,7 +1513,7 @@ InstanceScript* ScriptMgr::CreateInstanceData(InstanceMap* map) { ASSERT(map); - GET_SCRIPT_RET(InstanceMapScript, map->GetScriptId(), tmpscript, NULL); + GET_SCRIPT_RET(InstanceMapScript, map->GetScriptId(), tmpscript, nullptr); return tmpscript->GetInstanceScript(map); } @@ -1579,7 +1584,7 @@ CreatureAI* ScriptMgr::GetCreatureAI(Creature* creature) { ASSERT(creature); - GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, NULL); + GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, nullptr); return tmpscript->GetAI(creature); } @@ -1587,7 +1592,7 @@ GameObjectAI* ScriptMgr::GetGameObjectAI(GameObject* gameobject) { ASSERT(gameobject); - GET_SCRIPT_RET(GameObjectScript, gameobject->GetScriptId(), tmpscript, NULL); + GET_SCRIPT_RET(GameObjectScript, gameobject->GetScriptId(), tmpscript, nullptr); return tmpscript->GetAI(gameobject); } @@ -1604,12 +1609,12 @@ Battleground* ScriptMgr::CreateBattleground(BattlegroundTypeId /*typeId*/) { /// @todo Implement script-side battlegrounds. ABORT(); - return NULL; + return nullptr; } OutdoorPvP* ScriptMgr::CreateOutdoorPvP(uint32 scriptId) { - GET_SCRIPT_RET(OutdoorPvPScript, scriptId, tmpscript, NULL); + GET_SCRIPT_RET(OutdoorPvPScript, scriptId, tmpscript, nullptr); return tmpscript->GetOutdoorPvP(); } @@ -1624,7 +1629,7 @@ std::vector ScriptMgr::GetChatCommands() } // Sort commands in alphabetical order - std::sort(table.begin(), table.end(), [](const ChatCommand& a, const ChatCommand&b) + std::sort(table.begin(), table.end(), [](ChatCommand const& a, ChatCommand const& b) { return strcmp(a.Name, b.Name) < 0; }); @@ -2070,7 +2075,7 @@ void ScriptMgr::OnGroupInviteMember(Group* group, ObjectGuid guid) FOREACH_SCRIPT(GroupScript)->OnInviteMember(group, guid); } -void ScriptMgr::OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, const char* reason) +void ScriptMgr::OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, char const* reason) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnRemoveMember(group, guid, method, kicker, reason); @@ -2119,167 +2124,176 @@ void ScriptMgr::ModifySpellDamageTaken(Unit* target, Unit* attacker, int32& dama FOREACH_SCRIPT(PlayerScript)->ModifySpellDamageTaken(target, attacker, damage); } -SpellScriptLoader::SpellScriptLoader(const char* name) +SpellScriptLoader::SpellScriptLoader(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -ServerScript::ServerScript(const char* name) +ServerScript::ServerScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -WorldScript::WorldScript(const char* name) +WorldScript::WorldScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -FormulaScript::FormulaScript(const char* name) +FormulaScript::FormulaScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -UnitScript::UnitScript(const char* name, bool addToScripts) +UnitScript::UnitScript(char const* name, bool addToScripts) : ScriptObject(name) { if (addToScripts) ScriptRegistry::Instance()->AddScript(this); } -WorldMapScript::WorldMapScript(const char* name, uint32 mapId) - : ScriptObject(name), MapScript(mapId) +WorldMapScript::WorldMapScript(char const* name, uint32 mapId) + : ScriptObject(name), MapScript(sMapStore.LookupEntry(mapId)) { + if (!GetEntry()) + TC_LOG_ERROR("scripts", "Invalid WorldMapScript for %u; no such map ID.", mapId); + if (GetEntry() && !GetEntry()->IsWorldMap()) TC_LOG_ERROR("scripts", "WorldMapScript for map %u is invalid.", mapId); ScriptRegistry::Instance()->AddScript(this); } -InstanceMapScript::InstanceMapScript(const char* name, uint32 mapId) - : ScriptObject(name), MapScript(mapId) +InstanceMapScript::InstanceMapScript(char const* name, uint32 mapId) + : ScriptObject(name), MapScript(sMapStore.LookupEntry(mapId)) { + if (!GetEntry()) + TC_LOG_ERROR("scripts", "Invalid InstanceMapScript for %u; no such map ID.", mapId); + if (GetEntry() && !GetEntry()->IsDungeon()) TC_LOG_ERROR("scripts", "InstanceMapScript for map %u is invalid.", mapId); ScriptRegistry::Instance()->AddScript(this); } -BattlegroundMapScript::BattlegroundMapScript(const char* name, uint32 mapId) - : ScriptObject(name), MapScript(mapId) +BattlegroundMapScript::BattlegroundMapScript(char const* name, uint32 mapId) + : ScriptObject(name), MapScript(sMapStore.LookupEntry(mapId)) { + if (!GetEntry()) + TC_LOG_ERROR("scripts", "Invalid BattlegroundMapScript for %u; no such map ID.", mapId); + if (GetEntry() && !GetEntry()->IsBattleground()) TC_LOG_ERROR("scripts", "BattlegroundMapScript for map %u is invalid.", mapId); ScriptRegistry::Instance()->AddScript(this); } -ItemScript::ItemScript(const char* name) +ItemScript::ItemScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -CreatureScript::CreatureScript(const char* name) +CreatureScript::CreatureScript(char const* name) : UnitScript(name, false) { ScriptRegistry::Instance()->AddScript(this); } -GameObjectScript::GameObjectScript(const char* name) +GameObjectScript::GameObjectScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -AreaTriggerScript::AreaTriggerScript(const char* name) +AreaTriggerScript::AreaTriggerScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -BattlegroundScript::BattlegroundScript(const char* name) +BattlegroundScript::BattlegroundScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -OutdoorPvPScript::OutdoorPvPScript(const char* name) +OutdoorPvPScript::OutdoorPvPScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -CommandScript::CommandScript(const char* name) +CommandScript::CommandScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -WeatherScript::WeatherScript(const char* name) +WeatherScript::WeatherScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -AuctionHouseScript::AuctionHouseScript(const char* name) +AuctionHouseScript::AuctionHouseScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -ConditionScript::ConditionScript(const char* name) +ConditionScript::ConditionScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -VehicleScript::VehicleScript(const char* name) +VehicleScript::VehicleScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -DynamicObjectScript::DynamicObjectScript(const char* name) +DynamicObjectScript::DynamicObjectScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -TransportScript::TransportScript(const char* name) +TransportScript::TransportScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -AchievementCriteriaScript::AchievementCriteriaScript(const char* name) +AchievementCriteriaScript::AchievementCriteriaScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -PlayerScript::PlayerScript(const char* name) +PlayerScript::PlayerScript(char const* name) : UnitScript(name, false) { ScriptRegistry::Instance()->AddScript(this); } -AccountScript::AccountScript(const char* name) +AccountScript::AccountScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -GuildScript::GuildScript(const char* name) +GuildScript::GuildScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -GroupScript::GroupScript(const char* name) +GroupScript::GroupScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); diff --git a/src/server/game/Scripting/ScriptMgr.h b/src/server/game/Scripting/ScriptMgr.h index ff89a1314a2..311a7faf911 100644 --- a/src/server/game/Scripting/ScriptMgr.h +++ b/src/server/game/Scripting/ScriptMgr.h @@ -20,12 +20,8 @@ #define SC_SCRIPTMGR_H #include "Common.h" -#include -#include "DBCStores.h" -#include "QuestDef.h" -#include "SharedDefines.h" -#include "World.h" -#include "Weather.h" +#include "ObjectGuid.h" +#include class AccountMgr; class AuctionHouseObject; @@ -59,18 +55,33 @@ class SpellCastTargets; class Transport; class Unit; class Vehicle; +class Weather; class WorldPacket; class WorldSocket; class WorldObject; class WorldSession; struct AchievementCriteriaData; +struct AreaTriggerEntry; struct AuctionEntry; struct ConditionSourceInfo; struct Condition; struct CreatureTemplate; struct CreatureData; struct ItemTemplate; +struct MapEntry; + +enum BattlegroundTypeId : uint32; +enum ContentLevels : uint8; +enum Difficulty : uint8; +enum DuelCompleteType : uint8; +enum QuestStatus : uint8; +enum RemoveMethod : uint8; +enum ShutdownExitCode : uint32; +enum ShutdownMask : uint32; +enum SpellEffIndex : uint8; +enum WeatherState : uint32; +enum XPColorChar : uint8; #define VISIBLE_RANGE 166.0f //MAX visible range (size of grid) @@ -100,7 +111,7 @@ struct ItemTemplate; protected: - MyScriptType(const char* name, uint32 someId) + MyScriptType(char const* name, uint32 someId) : ScriptObject(name), _someId(someId) { ScriptRegistry::AddScript(this); @@ -161,7 +172,7 @@ class TC_GAME_API ScriptObject protected: - ScriptObject(const char* name); + ScriptObject(char const* name); virtual ~ScriptObject(); private: @@ -188,22 +199,22 @@ class TC_GAME_API SpellScriptLoader : public ScriptObject { protected: - SpellScriptLoader(const char* name); + SpellScriptLoader(char const* name); public: // Should return a fully valid SpellScript pointer. - virtual SpellScript* GetSpellScript() const { return NULL; } + virtual SpellScript* GetSpellScript() const { return nullptr; } // Should return a fully valid AuraScript pointer. - virtual AuraScript* GetAuraScript() const { return NULL; } + virtual AuraScript* GetAuraScript() const { return nullptr; } }; class TC_GAME_API ServerScript : public ScriptObject { protected: - ServerScript(const char* name); + ServerScript(char const* name); public: @@ -233,7 +244,7 @@ class TC_GAME_API WorldScript : public ScriptObject { protected: - WorldScript(const char* name); + WorldScript(char const* name); public: @@ -266,7 +277,7 @@ class TC_GAME_API FormulaScript : public ScriptObject { protected: - FormulaScript(const char* name); + FormulaScript(char const* name); public: @@ -298,12 +309,7 @@ template class MapScript : public UpdatableScript protected: - MapScript(uint32 mapId) - : _mapEntry(sMapStore.LookupEntry(mapId)) - { - if (!_mapEntry) - TC_LOG_ERROR("scripts", "Invalid MapScript for %u; no such map ID.", mapId); - } + MapScript(MapEntry const* mapEntry) : _mapEntry(mapEntry) { } public: @@ -333,7 +339,7 @@ class TC_GAME_API WorldMapScript : public ScriptObject, public MapScript { protected: - WorldMapScript(const char* name, uint32 mapId); + WorldMapScript(char const* name, uint32 mapId); }; class TC_GAME_API InstanceMapScript @@ -341,26 +347,26 @@ class TC_GAME_API InstanceMapScript { protected: - InstanceMapScript(const char* name, uint32 mapId); + InstanceMapScript(char const* name, uint32 mapId); public: // Gets an InstanceScript object for this instance. - virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return NULL; } + virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return nullptr; } }; class TC_GAME_API BattlegroundMapScript : public ScriptObject, public MapScript { protected: - BattlegroundMapScript(const char* name, uint32 mapId); + BattlegroundMapScript(char const* name, uint32 mapId); }; class TC_GAME_API ItemScript : public ScriptObject { protected: - ItemScript(const char* name); + ItemScript(char const* name); public: @@ -384,7 +390,7 @@ class TC_GAME_API UnitScript : public ScriptObject { protected: - UnitScript(const char* name, bool addToScripts = true); + UnitScript(char const* name, bool addToScripts = true); public: // Called when a unit deals healing to another unit @@ -407,7 +413,7 @@ class TC_GAME_API CreatureScript : public UnitScript { protected: - CreatureScript(const char* name); + CreatureScript(char const* name); public: @@ -422,7 +428,7 @@ class TC_GAME_API GameObjectScript : public ScriptObject { protected: - GameObjectScript(const char* name); + GameObjectScript(char const* name); public: @@ -434,7 +440,7 @@ class TC_GAME_API AreaTriggerScript : public ScriptObject { protected: - AreaTriggerScript(const char* name); + AreaTriggerScript(char const* name); public: @@ -446,7 +452,7 @@ class TC_GAME_API BattlegroundScript : public ScriptObject { protected: - BattlegroundScript(const char* name); + BattlegroundScript(char const* name); public: @@ -458,7 +464,7 @@ class TC_GAME_API OutdoorPvPScript : public ScriptObject { protected: - OutdoorPvPScript(const char* name); + OutdoorPvPScript(char const* name); public: @@ -470,7 +476,7 @@ class TC_GAME_API CommandScript : public ScriptObject { protected: - CommandScript(const char* name); + CommandScript(char const* name); public: @@ -482,7 +488,7 @@ class TC_GAME_API WeatherScript : public ScriptObject, public UpdatableScript { protected: - TransportScript(const char* name); + TransportScript(char const* name); public: @@ -582,7 +588,7 @@ class TC_GAME_API AchievementCriteriaScript : public ScriptObject { protected: - AchievementCriteriaScript(const char* name); + AchievementCriteriaScript(char const* name); public: @@ -594,7 +600,7 @@ class TC_GAME_API PlayerScript : public UnitScript { protected: - PlayerScript(const char* name); + PlayerScript(char const* name); public: @@ -694,7 +700,7 @@ class TC_GAME_API AccountScript : public ScriptObject { protected: - AccountScript(const char* name); + AccountScript(char const* name); public: @@ -721,7 +727,7 @@ class TC_GAME_API GuildScript : public ScriptObject { protected: - GuildScript(const char* name); + GuildScript(char const* name); public: @@ -762,7 +768,7 @@ class TC_GAME_API GroupScript : public ScriptObject { protected: - GroupScript(const char* name); + GroupScript(char const* name); public: @@ -773,7 +779,7 @@ class TC_GAME_API GroupScript : public ScriptObject virtual void OnInviteMember(Group* /*group*/, ObjectGuid /*guid*/) { } // Called when a member is removed from a group. - virtual void OnRemoveMember(Group* /*group*/, ObjectGuid /*guid*/, RemoveMethod /*method*/, ObjectGuid /*kicker*/, const char* /*reason*/) { } + virtual void OnRemoveMember(Group* /*group*/, ObjectGuid /*guid*/, RemoveMethod /*method*/, ObjectGuid /*kicker*/, char const* /*reason*/) { } // Called when the leader of a group is changed. virtual void OnChangeLeader(Group* /*group*/, ObjectGuid /*newLeaderGuid*/, ObjectGuid /*oldLeaderGuid*/) { } @@ -1027,7 +1033,7 @@ class TC_GAME_API ScriptMgr void OnGroupAddMember(Group* group, ObjectGuid guid); void OnGroupInviteMember(Group* group, ObjectGuid guid); - void OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, const char* reason); + void OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, char const* reason); void OnGroupChangeLeader(Group* group, ObjectGuid newLeaderGuid, ObjectGuid oldLeaderGuid); void OnGroupDisband(Group* group); diff --git a/src/server/game/Scripting/ScriptReloadMgr.cpp b/src/server/game/Scripting/ScriptReloadMgr.cpp index 18b910420b1..04c15b67c86 100644 --- a/src/server/game/Scripting/ScriptReloadMgr.cpp +++ b/src/server/game/Scripting/ScriptReloadMgr.cpp @@ -17,6 +17,7 @@ #include "ScriptReloadMgr.h" #include "Errors.h" +#include "Optional.h" #ifndef TRINITY_API_USE_DYNAMIC_LINKING @@ -36,31 +37,30 @@ ScriptReloadMgr* ScriptReloadMgr::instance() #else +#include "BuiltInConfig.h" +#include "Config.h" +#include "GitRevision.h" +#include "Log.h" +#include "MPSCQueue.h" +#include "Regex.h" +#include "ScriptMgr.h" +#include "SHA1.h" +#include "StartProcess.h" +#include "Timer.h" +#include "World.h" +#include +#include +#include +#include #include -#include +#include #include #include -#include +#include #include -#include #include - -#include "Regex.h" - -#include -#include -#include - -#include "efsw/efsw.hpp" - -#include "Log.h" -#include "Config.h" -#include "BuiltInConfig.h" -#include "ScriptMgr.h" -#include "SHA1.h" -#include "StartProcess.h" -#include "MPSCQueue.h" -#include "GitRevision.h" +#include +#include namespace fs = boost::filesystem; diff --git a/src/server/game/Scripting/ScriptSystem.cpp b/src/server/game/Scripting/ScriptSystem.cpp index a310d4d6ee0..1b4ad6b98d5 100644 --- a/src/server/game/Scripting/ScriptSystem.cpp +++ b/src/server/game/Scripting/ScriptSystem.cpp @@ -17,10 +17,15 @@ */ #include "ScriptSystem.h" -#include "ObjectMgr.h" +#include "Creature.h" #include "DatabaseEnv.h" +#include "Log.h" +#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "Creature.h" +#include "SplineChain.h" + +SystemMgr::SystemMgr() = default; +SystemMgr::~SystemMgr() = default; SystemMgr* SystemMgr::instance() { @@ -108,7 +113,7 @@ void SystemMgr::LoadScriptSplineChains() uint32 entry = fieldsMeta[0].GetUInt32(); uint16 chainId = fieldsMeta[1].GetUInt16(); uint8 splineId = fieldsMeta[2].GetUInt8(); - SplineChain& chain = m_mSplineChainsMap[{entry,chainId}]; + std::vector& chain = m_mSplineChainsMap[{entry, chainId}]; if (splineId != chain.size()) { @@ -116,8 +121,9 @@ void SystemMgr::LoadScriptSplineChains() continue; } - uint32 expectedDuration = fieldsMeta[3].GetUInt32(), msUntilNext = fieldsMeta[4].GetUInt32(); - chain.push_back(SplineChainLink(expectedDuration, msUntilNext)); + uint32 expectedDuration = fieldsMeta[3].GetUInt32(); + uint32 msUntilNext = fieldsMeta[4].GetUInt32(); + chain.emplace_back(expectedDuration, msUntilNext); if (splineId == 0) ++chainCount; @@ -137,7 +143,7 @@ void SystemMgr::LoadScriptSplineChains() TC_LOG_WARN("server.loading", "Creature #%u has waypoint data for spline chain %u. No such chain exists - entry skipped.", entry, chainId); continue; } - SplineChain& chain = it->second; + std::vector& chain = it->second; if (splineId >= chain.size()) { TC_LOG_WARN("server.loading", "Creature #%u has waypoint data for spline (%u,%u). The specified chain does not have a spline with this index - entry skipped.", entry, chainId, splineId); @@ -157,7 +163,15 @@ void SystemMgr::LoadScriptSplineChains() } } -SplineChain const* SystemMgr::GetSplineChain(Creature const* who, uint16 id) const +std::vector const* SystemMgr::GetSplineChain(uint32 entry, uint16 chainId) const +{ + auto it = m_mSplineChainsMap.find({ entry, chainId }); + if (it == m_mSplineChainsMap.end()) + return nullptr; + return &it->second; +} + +std::vector const* SystemMgr::GetSplineChain(Creature const* who, uint16 id) const { return GetSplineChain(who->GetEntry(), id); } diff --git a/src/server/game/Scripting/ScriptSystem.h b/src/server/game/Scripting/ScriptSystem.h index c67316eb64b..7828c24d680 100644 --- a/src/server/game/Scripting/ScriptSystem.h +++ b/src/server/game/Scripting/ScriptSystem.h @@ -1,14 +1,31 @@ -/* Copyright (C) 2006 - 2009 ScriptDev2 -* This program is free software licensed under GPL version 2 -* Please see the included DOCS/LICENSE.TXT for more information */ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ #ifndef SC_SYSTEM_H #define SC_SYSTEM_H -#include "ScriptMgr.h" -#include "SplineChain.h" +#include "Define.h" +#include "Hash.h" +#include +#include class Creature; +struct SplineChainLink; #define TEXT_SOURCE_RANGE -1000000 //the amount of entries each text source has available @@ -27,8 +44,10 @@ typedef std::vector ScriptPointVector; class TC_GAME_API SystemMgr { private: - SystemMgr() { } - ~SystemMgr() { } + SystemMgr(); + ~SystemMgr(); + SystemMgr(SystemMgr const&) = delete; + SystemMgr& operator=(SystemMgr const&) = delete; public: static SystemMgr* instance(); @@ -49,20 +68,13 @@ class TC_GAME_API SystemMgr return &itr->second; } - SplineChain const* GetSplineChain(uint32 entry, uint16 chainId) const - { - auto it = m_mSplineChainsMap.find({ entry, chainId }); - if (it == m_mSplineChainsMap.end()) - return nullptr; - return &it->second; - } - - SplineChain const* GetSplineChain(Creature const* who, uint16 id) const; + std::vector const* GetSplineChain(uint32 entry, uint16 chainId) const; + std::vector const* GetSplineChain(Creature const* who, uint16 id) const; protected: PointMoveMap m_mPointMoveMap; //coordinates for waypoints typedef std::pair ChainKeyType; // creature entry + chain ID - std::unordered_map m_mSplineChainsMap; // spline chains + std::unordered_map> m_mSplineChainsMap; // spline chains }; #define sScriptSystemMgr SystemMgr::instance() diff --git a/src/server/game/Server/Packet.cpp b/src/server/game/Server/Packet.cpp new file mode 100644 index 00000000000..bc4812a765d --- /dev/null +++ b/src/server/game/Server/Packet.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "Packet.h" +#include "Errors.h" + +WorldPackets::Packet::Packet(WorldPacket&& worldPacket) : _worldPacket(std::move(worldPacket)) +{ +} + +WorldPackets::ServerPacket::ServerPacket(OpcodeServer opcode, size_t initialSize /*= 200*/) : Packet(WorldPacket(opcode, initialSize)) +{ +} + +void WorldPackets::ServerPacket::Read() +{ + ASSERT(!"Read not implemented for server packets."); +} + +WorldPackets::ClientPacket::ClientPacket(OpcodeClient expectedOpcode, WorldPacket&& packet) : Packet(std::move(packet)) +{ + ASSERT(GetOpcode() == expectedOpcode); +} + +WorldPackets::ClientPacket::ClientPacket(WorldPacket&& packet) + : Packet(std::move(packet)) +{ +} + +WorldPacket const* WorldPackets::ClientPacket::Write() +{ + ASSERT(!"Write not allowed for client packets."); + // Shut up some compilers + return nullptr; +} diff --git a/src/server/game/Server/Packet.h b/src/server/game/Server/Packet.h index 780e3850a27..8302e6b1353 100644 --- a/src/server/game/Server/Packet.h +++ b/src/server/game/Server/Packet.h @@ -25,7 +25,7 @@ namespace WorldPackets class TC_GAME_API Packet { public: - Packet(WorldPacket&& worldPacket) : _worldPacket(std::move(worldPacket)) { } + Packet(WorldPacket&& worldPacket); virtual ~Packet() = default; @@ -42,12 +42,12 @@ namespace WorldPackets WorldPacket _worldPacket; }; - class ServerPacket : public Packet + class TC_GAME_API ServerPacket : public Packet { public: - ServerPacket(OpcodeServer opcode, size_t initialSize = 200) : Packet(WorldPacket(opcode, initialSize)) { } + ServerPacket(OpcodeServer opcode, size_t initialSize = 200); - void Read() override final { ASSERT(!"Read not implemented for server packets."); } + void Read() override final; void Clear() { _worldPacket.clear(); } WorldPacket&& Move() { return std::move(_worldPacket); } @@ -55,18 +55,13 @@ namespace WorldPackets OpcodeServer GetOpcode() const { return OpcodeServer(_worldPacket.GetOpcode()); } }; - class ClientPacket : public Packet + class TC_GAME_API ClientPacket : public Packet { public: - ClientPacket(WorldPacket&& packet) : Packet(std::move(packet)) { } - ClientPacket(OpcodeClient expectedOpcode, WorldPacket&& packet) : Packet(std::move(packet)) { ASSERT(GetOpcode() == expectedOpcode); } - - WorldPacket const* Write() override final - { - ASSERT(!"Write not allowed for client packets."); - // Shut up some compilers - return nullptr; - } + ClientPacket(WorldPacket&& packet); + ClientPacket(OpcodeClient expectedOpcode, WorldPacket&& packet); + + WorldPacket const* Write() override final; OpcodeClient GetOpcode() const { return OpcodeClient(_worldPacket.GetOpcode()); } }; diff --git a/src/server/game/Server/Packets/PacketUtilities.cpp b/src/server/game/Server/Packets/PacketUtilities.cpp new file mode 100644 index 00000000000..4d87feaabc5 --- /dev/null +++ b/src/server/game/Server/Packets/PacketUtilities.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "PacketUtilities.h" +#include "Errors.h" +#include +#include + +WorldPackets::PacketArrayMaxCapacityException::PacketArrayMaxCapacityException(std::size_t requestedSize, std::size_t sizeLimit) +{ + std::ostringstream builder; + builder << "Attempted to read more array elements from packet " << requestedSize << " than allowed " << sizeLimit; + message().assign(builder.str()); +} + +void WorldPackets::CheckCompactArrayMaskOverflow(std::size_t index, std::size_t limit) +{ + ASSERT(index < limit, "Attempted to insert " SZFMTD " values into CompactArray but it can only hold " SZFMTD, index, limit); +} diff --git a/src/server/game/Server/Packets/PacketUtilities.h b/src/server/game/Server/Packets/PacketUtilities.h index e4f40580a30..e1229e1ae1c 100644 --- a/src/server/game/Server/Packets/PacketUtilities.h +++ b/src/server/game/Server/Packets/PacketUtilities.h @@ -19,46 +19,13 @@ #define PacketUtilities_h__ #include "ByteBuffer.h" -#include -#include -#include -#include - -inline ByteBuffer& operator<<(ByteBuffer& data, G3D::Vector2 const& v) -{ - data << v.x << v.y; - return data; -} - -inline ByteBuffer& operator>>(ByteBuffer& data, G3D::Vector2& v) -{ - data >> v.x >> v.y; - return data; -} - -inline ByteBuffer& operator<<(ByteBuffer& data, G3D::Vector3 const& v) -{ - data << v.x << v.y << v.z; - return data; -} - -inline ByteBuffer& operator>>(ByteBuffer& data, G3D::Vector3& v) -{ - data >> v.x >> v.y >> v.z; - return data; -} namespace WorldPackets { class PacketArrayMaxCapacityException : public ByteBufferException { public: - PacketArrayMaxCapacityException(std::size_t requestedSize, std::size_t sizeLimit) - { - std::ostringstream builder; - builder << "Attempted to read more array elements from packet " << requestedSize << " than allowed " << sizeLimit; - message().assign(builder.str()); - } + PacketArrayMaxCapacityException(std::size_t requestedSize, std::size_t sizeLimit); }; /** @@ -129,6 +96,8 @@ namespace WorldPackets size_type _limit; }; + void CheckCompactArrayMaskOverflow(std::size_t index, std::size_t limit); + template class CompactArray { @@ -144,14 +113,14 @@ namespace WorldPackets right._mask = 0; } - CompactArray& operator= (CompactArray const& right) + CompactArray& operator=(CompactArray const& right) { _mask = right._mask; _contents = right._contents; return *this; } - CompactArray& operator= (CompactArray&& right) + CompactArray& operator=(CompactArray&& right) { _mask = right._mask; right._mask = 0; @@ -160,12 +129,12 @@ namespace WorldPackets } uint32 GetMask() const { return _mask; } - T const& operator[](size_t index) const { return _contents.at(index); } - size_t GetSize() const { return _contents.size(); } + T const& operator[](std::size_t index) const { return _contents.at(index); } + std::size_t GetSize() const { return _contents.size(); } - void Insert(size_t index, T const& value) + void Insert(std::size_t index, T const& value) { - ASSERT(index < 0x20); + CheckCompactArrayMaskOverflow(index, sizeof(_mask) * 8); _mask |= 1 << index; if (_contents.size() <= index) @@ -199,11 +168,9 @@ namespace WorldPackets { uint32 mask = v.GetMask(); data << uint32(mask); - for (size_t i = 0; i < v.GetSize(); ++i) - { + for (std::size_t i = 0; i < v.GetSize(); ++i) if (mask & (1 << i)) data << v[i]; - } return data; } @@ -214,15 +181,9 @@ namespace WorldPackets uint32 mask; data >> mask; - for (size_t index = 0; mask != 0; mask >>= 1, ++index) - { + for (std::size_t index = 0; mask != 0; mask >>= 1, ++index) if ((mask & 1) != 0) - { - T value; - data >> value; - v.Insert(index, value); - } - } + v.Insert(index, data.read()); return data; } diff --git a/src/server/game/Server/Protocol/Opcodes.cpp b/src/server/game/Server/Protocol/Opcodes.cpp index 316335ffd47..ce095d36a72 100644 --- a/src/server/game/Server/Protocol/Opcodes.cpp +++ b/src/server/game/Server/Protocol/Opcodes.cpp @@ -17,8 +17,11 @@ */ #include "Opcodes.h" +#include "Log.h" #include "WorldSession.h" #include "Packets/AllPackets.h" +#include +#include template class PacketHandler : public ClientOpcodeHandler @@ -59,6 +62,17 @@ struct get_packet_class using type = PacketClass; }; +OpcodeTable::OpcodeTable() +{ + memset(_internalTableClient, 0, sizeof(_internalTableClient)); +} + +OpcodeTable::~OpcodeTable() +{ + for (uint16 i = 0; i < NUM_OPCODE_HANDLERS; ++i) + delete _internalTableClient[i]; +} + template void OpcodeTable::ValidateAndSetClientOpcode(OpcodeClient opcode, char const* name, SessionStatus status, PacketProcessing processing) { @@ -74,7 +88,7 @@ void OpcodeTable::ValidateAndSetClientOpcode(OpcodeClient opcode, char const* na return; } - if (_internalTableClient[opcode] != NULL) + if (_internalTableClient[opcode] != nullptr) { TC_LOG_ERROR("network", "Tried to override client handler of %s with %s (opcode %u)", opcodeTable[opcode]->Name, name, opcode); return; @@ -97,7 +111,7 @@ void OpcodeTable::ValidateAndSetServerOpcode(OpcodeServer opcode, char const* na return; } - if (_internalTableClient[opcode] != NULL) + if (_internalTableClient[opcode] != nullptr) { TC_LOG_ERROR("network", "Tried to override server handler of %s with %s (opcode %u)", opcodeTable[opcode]->Name, name, opcode); return; @@ -1430,4 +1444,30 @@ void OpcodeTable::Initialize() #undef DEFINE_HANDLER #undef DEFINE_SERVER_OPCODE_HANDLER -}; \ No newline at end of file +} + +template +inline std::string GetOpcodeNameForLoggingImpl(T id) +{ + uint16 opcode = uint16(id); + std::ostringstream ss; + ss << '['; + + if (static_cast(id) < NUM_OPCODE_HANDLERS) + { + if (OpcodeHandler const* handler = opcodeTable[id]) + ss << handler->Name; + else + ss << "UNKNOWN OPCODE"; + } + else + ss << "INVALID OPCODE"; + + ss << " 0x" << std::hex << std::setw(4) << std::setfill('0') << std::uppercase << opcode << std::nouppercase << std::dec << " (" << opcode << ")]"; + return ss.str(); +} + +std::string GetOpcodeNameForLogging(Opcodes opcode) +{ + return GetOpcodeNameForLoggingImpl(opcode); +} diff --git a/src/server/game/Server/Protocol/Opcodes.h b/src/server/game/Server/Protocol/Opcodes.h index 9437da07d0b..85e9b395f56 100644 --- a/src/server/game/Server/Protocol/Opcodes.h +++ b/src/server/game/Server/Protocol/Opcodes.h @@ -23,8 +23,8 @@ #ifndef _OPCODES_H #define _OPCODES_H -#include "Common.h" -#include +#include "Define.h" +#include enum Opcodes : uint16 { @@ -1371,8 +1371,6 @@ enum PacketProcessing class WorldSession; class WorldPacket; -#pragma pack(push, 1) - class OpcodeHandler { public: @@ -1404,21 +1402,12 @@ public: class OpcodeTable { public: - OpcodeTable() - { - memset(_internalTableClient, 0, sizeof(_internalTableClient)); - } + OpcodeTable(); OpcodeTable(OpcodeTable const&) = delete; OpcodeTable& operator=(OpcodeTable const&) = delete; - ~OpcodeTable() - { - for (uint16 i = 0; i < NUM_OPCODE_HANDLERS; ++i) - { - delete _internalTableClient[i]; - } - } + ~OpcodeTable(); void Initialize(); @@ -1438,29 +1427,8 @@ class OpcodeTable extern OpcodeTable opcodeTable; -#pragma pack(pop) - -/// Lookup opcode name for human understandable logging (T = OpcodeClient|OpcodeServer) -template -inline std::string GetOpcodeNameForLogging(T id) -{ - uint16 opcode = uint16(id); - std::ostringstream ss; - ss << '['; - - if (static_cast(id) < NUM_OPCODE_HANDLERS) - { - if (OpcodeHandler const* handler = opcodeTable[id]) - ss << handler->Name; - else - ss << "UNKNOWN OPCODE"; - } - else - ss << "INVALID OPCODE"; - - ss << " 0x" << std::hex << std::setw(4) << std::setfill('0') << std::uppercase << opcode << std::nouppercase << std::dec << " (" << opcode << ")]"; - return ss.str(); -} +/// Lookup opcode name for human understandable logging +std::string GetOpcodeNameForLogging(Opcodes opcode); #endif /// @} diff --git a/src/server/game/Server/Protocol/PacketLog.cpp b/src/server/game/Server/Protocol/PacketLog.cpp index 0bbaf9c6e98..50e8786defa 100644 --- a/src/server/game/Server/Protocol/PacketLog.cpp +++ b/src/server/game/Server/Protocol/PacketLog.cpp @@ -56,7 +56,7 @@ struct PacketHeader #pragma pack(pop) -PacketLog::PacketLog() : _file(NULL) +PacketLog::PacketLog() : _file(nullptr) { std::call_once(_initializeFlag, &PacketLog::Initialize, this); } @@ -66,7 +66,7 @@ PacketLog::~PacketLog() if (_file) fclose(_file); - _file = NULL; + _file = nullptr; } PacketLog* PacketLog::instance() @@ -95,7 +95,7 @@ void PacketLog::Initialize() header.Build = 12340; header.Locale[0] = 'e'; header.Locale[1] = 'n'; header.Locale[2] = 'U'; header.Locale[3] = 'S'; std::memset(header.SessionKey, 0, sizeof(header.SessionKey)); - header.SniffStartUnixtime = time(NULL); + header.SniffStartUnixtime = time(nullptr); header.SniffStartTicks = getMSTime(); header.OptionalDataSize = 0; diff --git a/src/server/game/Server/Protocol/PacketLog.h b/src/server/game/Server/Protocol/PacketLog.h index e6082940197..0830f5a583b 100644 --- a/src/server/game/Server/Protocol/PacketLog.h +++ b/src/server/game/Server/Protocol/PacketLog.h @@ -43,7 +43,7 @@ class TC_GAME_API PacketLog static PacketLog* instance(); void Initialize(); - bool CanLogPacket() const { return (_file != NULL); } + bool CanLogPacket() const { return (_file != nullptr); } void LogPacket(WorldPacket const& packet, Direction direction, boost::asio::ip::address const& addr, uint16 port); private: diff --git a/src/server/game/Server/WorldSession.cpp b/src/server/game/Server/WorldSession.cpp index 7eda06aefec..a7a959bd0ea 100644 --- a/src/server/game/Server/WorldSession.cpp +++ b/src/server/game/Server/WorldSession.cpp @@ -20,33 +20,36 @@ \ingroup u2w */ -#include "WorldSocket.h" +#include "WorldSession.h" +#include "AccountMgr.h" +#include "AddonMgr.h" +#include "BattlegroundMgr.h" #include "Config.h" #include "Common.h" #include "DatabaseEnv.h" -#include "QueryCallback.h" -#include "AccountMgr.h" -#include "Log.h" -#include "Opcodes.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Player.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "GuildMgr.h" +#include "DBCStructure.h" #include "Group.h" #include "Guild.h" -#include "World.h" -#include "BattlegroundMgr.h" +#include "GuildMgr.h" +#include "Log.h" +#include "Map.h" +#include "Metric.h" +#include "MoveSpline.h" +#include "ObjectMgr.h" +#include "Opcodes.h" #include "OutdoorPvPMgr.h" -#include "SocialMgr.h" +#include "PacketUtilities.h" +#include "Player.h" +#include "Realm.h" #include "ScriptMgr.h" -#include "WardenWin.h" -#include "MoveSpline.h" +#include "SocialMgr.h" +#include "QueryHolder.h" +#include "Vehicle.h" #include "WardenMac.h" -#include "PacketUtilities.h" -#include "Metric.h" - +#include "WardenWin.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSocket.h" #include namespace { @@ -104,13 +107,13 @@ WorldSession::WorldSession(uint32 id, std::string&& name, std::shared_ptrGetName() : DefaultPlayerName; + return _player != nullptr ? _player->GetName() : DefaultPlayerName; } std::string WorldSession::GetPlayerInfo() const @@ -202,21 +205,21 @@ void WorldSession::SendPacket(WorldPacket const* packet) static uint64 sendPacketCount = 0; static uint64 sendPacketBytes = 0; - static time_t firstTime = time(NULL); + static time_t firstTime = time(nullptr); static time_t lastTime = firstTime; // next 60 secs start time static uint64 sendLastPacketCount = 0; static uint64 sendLastPacketBytes = 0; - time_t cur_time = time(NULL); + time_t cur_time = time(nullptr); if ((cur_time - lastTime) < 60) { - sendPacketCount+=1; - sendPacketBytes+=packet->size(); + sendPacketCount += 1; + sendPacketBytes += packet->size(); - sendLastPacketCount+=1; - sendLastPacketBytes+=packet->size(); + sendLastPacketCount += 1; + sendLastPacketBytes += packet->size(); } else { @@ -244,7 +247,7 @@ void WorldSession::QueuePacket(WorldPacket* new_packet) } /// Logging helper for unexpected opcodes -void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason) +void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, char const* status, const char *reason) { TC_LOG_ERROR("network.opcode", "Received unexpected opcode %s Status: %s Reason: %s from %s", GetOpcodeNameForLogging(static_cast(packet->GetOpcode())).c_str(), status, reason, GetPlayerInfo().c_str()); @@ -274,12 +277,12 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) ///- Retrieve packets from the receive queue and call the appropriate handlers /// not process packets if socket already closed - WorldPacket* packet = NULL; + WorldPacket* packet = nullptr; //! Delete packet after processing by default bool deletePacket = true; std::vector requeuePackets; uint32 processedPackets = 0; - time_t currentTime = time(NULL); + time_t currentTime = time(nullptr); while (m_Socket && _recvQueue.next(packet, updater)) { @@ -403,7 +406,7 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) //logout procedure should happen only in World::UpdateSessions() method!!! if (updater.ProcessLogout()) { - time_t currTime = time(NULL); + time_t currTime = time(nullptr); ///- If necessary, log the player out if (ShouldLogOut(currTime) && !m_playerLoading) LogoutPlayer(true); @@ -493,7 +496,7 @@ void WorldSession::LogoutPlayer(bool save) } } - // Repop at GraveYard or other player far teleport will prevent saving player because of not present map + // Repop at Graveyard or other player far teleport will prevent saving player because of not present map // Teleport player immediately for correct player save while (_player->IsBeingTeleportedFar()) HandleMoveWorldportAck(); @@ -503,7 +506,7 @@ void WorldSession::LogoutPlayer(bool save) guild->HandleMemberLogout(this); ///- Remove pet - _player->RemovePet(NULL, PET_SAVE_AS_CURRENT, true); + _player->RemovePet(nullptr, PET_SAVE_AS_CURRENT, true); ///- Clear whisper whitelist _player->ClearWhisperWhiteList(); @@ -560,7 +563,7 @@ void WorldSession::LogoutPlayer(bool save) if (Map* _map = _player->FindMap()) _map->RemovePlayerFromMap(_player, true); - SetPlayer(NULL); //! Pointer already deleted during RemovePlayerFromMap + SetPlayer(nullptr); //! Pointer already deleted during RemovePlayerFromMap //! Send the 'logout complete' packet to the client //! Client will respond by sending 3x CMSG_CANCEL_TRADE, which we currently dont handle @@ -630,6 +633,11 @@ char const* WorldSession::GetTrinityString(uint32 entry) const return sObjectMgr->GetTrinityString(entry, GetSessionDbLocaleIndex()); } +void WorldSession::ResetTimeOutTime() +{ + m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME)); +} + void WorldSession::Handle_NULL(WorldPacket& null) { TC_LOG_ERROR("network.opcode", "Received unhandled opcode %s from %s", GetOpcodeNameForLogging(static_cast(null.GetOpcode())).c_str(), GetPlayerInfo().c_str()); @@ -737,7 +745,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string c void WorldSession::SendAccountDataTimes(uint32 mask) { WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4 + 1 + 4 + NUM_ACCOUNT_DATA_TYPES * 4); - data << uint32(time(NULL)); // Server time + data << uint32(time(nullptr)); // Server time data << uint8(1); data << uint32(mask); // type mask for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i) @@ -1221,7 +1229,7 @@ void WorldSession::InvalidateRBACData() TC_LOG_DEBUG("rbac", "WorldSession::Invalidaterbac::RBACData [AccountId: %u, Name: %s, realmId: %d]", _RBACData->GetId(), _RBACData->GetName().c_str(), realm.Id.Realm); delete _RBACData; - _RBACData = NULL; + _RBACData = nullptr; } bool WorldSession::DosProtection::EvaluateOpcode(WorldPacket& p, time_t time) const @@ -1515,3 +1523,7 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co return maxPacketCounterAllowed; } + +WorldSession::DosProtection::DosProtection(WorldSession* s) : Session(s), _policy((Policy)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_POLICY)) +{ +} diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index eea430ac1b5..9271fb06e06 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -24,15 +24,15 @@ #define __WORLDSESSION_H #include "Common.h" -#include "SharedDefines.h" -#include "AddonMgr.h" -#include "DatabaseEnv.h" -#include "World.h" +#include "DatabaseEnvFwd.h" +#include "LockedQueue.h" +#include "ObjectGuid.h" #include "Packet.h" -#include "Cryptography/BigNumber.h" -#include "AccountMgr.h" -#include +#include "QueryCallbackProcessor.h" +#include "SharedDefines.h" +#include +class BigNumber; class Creature; class GameObject; class InstanceSave; @@ -46,6 +46,7 @@ class Unit; class Warden; class WorldPacket; class WorldSocket; +struct AddonInfo; struct AreaTableEntry; struct AuctionEntry; struct DeclinedName; @@ -284,7 +285,7 @@ class TC_GAME_API WorldSession void SendNotification(uint32 string_id, ...); void SendPetNameInvalid(uint32 error, std::string const& name, DeclinedName *declinedName); void SendPartyResult(PartyOperation operation, std::string const& member, PartyResult res, uint32 val = 0); - void SendAreaTriggerMessage(const char* Text, ...) ATTR_PRINTF(2, 3); + void SendAreaTriggerMessage(char const* Text, ...) ATTR_PRINTF(2, 3); void SendSetPhaseShift(uint32 phaseShift); void SendQueryTimeResponse(); @@ -438,10 +439,7 @@ class TC_GAME_API WorldSession m_timeOutTime -= int32(diff); } - void ResetTimeOutTime() - { - m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME)); - } + void ResetTimeOutTime(); bool IsConnectionIdle() const { @@ -999,7 +997,7 @@ class TC_GAME_API WorldSession { friend class World; public: - DosProtection(WorldSession* s) : Session(s), _policy((Policy)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_POLICY)) { } + DosProtection(WorldSession* s); bool EvaluateOpcode(WorldPacket& p, time_t time) const; protected: enum Policy @@ -1030,7 +1028,7 @@ class TC_GAME_API WorldSession bool CanUseBank(ObjectGuid bankerGUID = ObjectGuid::Empty) const; // logging helper - void LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason); + void LogUnexpectedOpcode(WorldPacket* packet, char const* status, const char *reason); void LogUnprocessedTail(WorldPacket* packet); // EnumData helpers diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index ae8b3fd0998..699c5a38a92 100644 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -18,12 +18,16 @@ #include "WorldSocket.h" #include "BigNumber.h" +#include "DatabaseEnv.h" #include "Opcodes.h" -#include "QueryCallback.h" +#include "PacketLog.h" +#include "Random.h" +#include "RBAC.h" +#include "Realm.h" #include "ScriptMgr.h" #include "SHA1.h" -#include "PacketLog.h" - +#include "World.h" +#include "WorldSession.h" #include class EncryptablePacket : public WorldPacket @@ -505,7 +509,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr authSes sha.UpdateData((uint8*)&t, 4); sha.UpdateData((uint8*)&authSession->LocalChallenge, 4); sha.UpdateData((uint8*)&_authSeed, 4); - sha.UpdateBigNumbers(&account.SessionKey, NULL); + sha.UpdateBigNumbers(&account.SessionKey, nullptr); sha.Finalize(); if (memcmp(sha.GetDigest(), authSession->Digest, SHA_DIGEST_LENGTH) != 0) @@ -546,7 +550,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr authSes //! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now. if (mutetime < 0) { - mutetime = time(NULL) + llabs(mutetime); + mutetime = time(nullptr) + llabs(mutetime); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN); stmt->setInt64(0, mutetime); diff --git a/src/server/game/Server/WorldSocketMgr.h b/src/server/game/Server/WorldSocketMgr.h index ce81acfea78..e409f8d2ea8 100644 --- a/src/server/game/Server/WorldSocketMgr.h +++ b/src/server/game/Server/WorldSocketMgr.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2013 TrinityCore + * Copyright (C) 2008-2017 TrinityCore * Copyright (C) 2005-2009 MaNGOS * * This program is free software; you can redistribute it and/or modify it diff --git a/src/server/game/Skills/SkillDiscovery.cpp b/src/server/game/Skills/SkillDiscovery.cpp index 2c17d3c7530..44d9a6a153f 100644 --- a/src/server/game/Skills/SkillDiscovery.cpp +++ b/src/server/game/Skills/SkillDiscovery.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ +#include "SkillDiscovery.h" #include "DatabaseEnv.h" #include "Log.h" -#include "World.h" -#include "Util.h" -#include "SkillDiscovery.h" -#include "SpellMgr.h" #include "Player.h" +#include "Random.h" +#include "SpellMgr.h" #include "SpellInfo.h" +#include "Util.h" +#include "World.h" #include struct SkillDiscoveryEntry diff --git a/src/server/game/Skills/SkillExtraItems.cpp b/src/server/game/Skills/SkillExtraItems.cpp index 5d5ea4396fb..3b066e71b8b 100644 --- a/src/server/game/Skills/SkillExtraItems.cpp +++ b/src/server/game/Skills/SkillExtraItems.cpp @@ -19,8 +19,9 @@ #include "SkillExtraItems.h" #include "DatabaseEnv.h" #include "Log.h" -#include "Player.h" #include "ObjectMgr.h" +#include "Player.h" +#include "SpellMgr.h" #include // some type definitions diff --git a/src/server/game/Spells/Auras/SpellAuraDefines.h b/src/server/game/Spells/Auras/SpellAuraDefines.h index 62602ac4a63..4fac4728b6c 100644 --- a/src/server/game/Spells/Auras/SpellAuraDefines.h +++ b/src/server/game/Spells/Auras/SpellAuraDefines.h @@ -18,6 +18,8 @@ #ifndef TRINITY_SPELLAURADEFINES_H #define TRINITY_SPELLAURADEFINES_H +#include "Define.h" + #define MAX_AURAS 255 // Client-side limit #define MAX_AURAS_GROUP_UPDATE 64 // Limit of SMSG_PARY_MEMBER_STATS_FULL and SMSG_PARTY_MEMBER_STATS @@ -51,6 +53,16 @@ enum AuraEffectHandleModes AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK = (AURA_EFFECT_HANDLE_REAPPLY | AURA_EFFECT_HANDLE_REAL) }; +enum AuraRemoveMode +{ + AURA_REMOVE_NONE = 0, + AURA_REMOVE_BY_DEFAULT = 1, // scripted remove, remove by stack with aura with different ids and sc aura remove + AURA_REMOVE_BY_CANCEL, + AURA_REMOVE_BY_ENEMY_SPELL, // dispel and absorb aura destroy + AURA_REMOVE_BY_EXPIRE, // aura duration has ended + AURA_REMOVE_BY_DEATH +}; + //m_schoolAbsorb enum DAMAGE_ABSORB_TYPE { @@ -58,7 +70,7 @@ enum DAMAGE_ABSORB_TYPE ONLY_MAGIC_ABSORB = -1 }; -enum AuraType +enum AuraType : uint32 { SPELL_AURA_NONE = 0, SPELL_AURA_BIND_SIGHT = 1, diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index 2fc4d83b767..5347d056eba 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -16,32 +16,34 @@ * with this program. If not, see . */ +#include "SpellAuraEffects.h" +#include "Battlefield.h" +#include "BattlefieldMgr.h" +#include "Battleground.h" +#include "CellImpl.h" #include "Common.h" -#include "WorldPacket.h" -#include "Opcodes.h" +#include "DBCStores.h" +#include "GridNotifiersImpl.h" +#include "Item.h" #include "Log.h" +#include "LootMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "SpellMgr.h" +#include "Opcodes.h" +#include "OutdoorPvPMgr.h" +#include "Pet.h" #include "Player.h" -#include "Unit.h" -#include "ObjectAccessor.h" -#include "CellImpl.h" -#include "Util.h" +#include "ReputationMgr.h" +#include "ScriptMgr.h" #include "Spell.h" #include "SpellHistory.h" -#include "SpellAuraEffects.h" -#include "Battleground.h" -#include "OutdoorPvPMgr.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "ScriptMgr.h" +#include "SpellMgr.h" +#include "Unit.h" +#include "Util.h" #include "Vehicle.h" -#include "Battlefield.h" -#include "BattlefieldMgr.h" -#include "Pet.h" -#include "ReputationMgr.h" +#include "WorldPacket.h" -class Aura; // // EFFECT HANDLER NOTES // @@ -380,7 +382,7 @@ AuraEffect::AuraEffect(Aura* base, uint8 effIndex, int32 *baseAmount, Unit* cast m_base(base), m_spellInfo(base->GetSpellInfo()), m_baseAmount(baseAmount ? *baseAmount : m_spellInfo->Effects[effIndex].BasePoints), m_bonusAmount(0), m_critChance(0.0f), m_donePct(1.0f), -m_spellmod(NULL), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex), +m_spellmod(nullptr), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex), m_canBeRecalculated(true), m_isPeriodic(false) { CalculatePeriodic(caster, true, false); @@ -421,7 +423,7 @@ void AuraEffect::GetApplicationList(Container& applicationContainer) const int32 AuraEffect::CalculateAmount(Unit* caster) { // default amount calculation - int32 amount = m_spellInfo->Effects[m_effIndex].CalcValue(caster, &m_baseAmount, NULL); + int32 amount = m_spellInfo->Effects[m_effIndex].CalcValue(caster, &m_baseAmount, nullptr); // check item enchant aura cast if (!amount && caster) @@ -536,7 +538,7 @@ void AuraEffect::CalculatePeriodic(Unit* caster, bool resetPeriodicTimer /*= tru { // Apply periodic time mod if (modOwner) - modOwner->ApplySpellMod(GetId(), m_amplitude); + modOwner->ApplySpellMod(GetId(), SPELLMOD_ACTIVATION_TIME, m_amplitude); if (caster) { @@ -1760,7 +1762,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo { int32 basePoints = int32(std::min(oldPower, FurorChance)); target->SetPower(POWER_ENERGY, 0); - target->CastCustomSpell(target, 17099, &basePoints, NULL, NULL, true, NULL, this); + target->CastCustomSpell(target, 17099, &basePoints, nullptr, nullptr, true, nullptr, this); break; } case FORM_BEAR: @@ -1823,12 +1825,12 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo case FORM_DIREBEAR: case FORM_CAT: if (AuraEffect* dummy = target->GetAuraEffect(37315, 0)) - target->CastSpell(target, 37316, true, NULL, dummy); + target->CastSpell(target, 37316, true, nullptr, dummy); break; // Nordrassil Regalia - bonus case FORM_MOONKIN: if (AuraEffect* dummy = target->GetAuraEffect(37324, 0)) - target->CastSpell(target, 37325, true, NULL, dummy); + target->CastSpell(target, 37325, true, nullptr, dummy); break; case FORM_BATTLESTANCE: case FORM_DEFENSIVESTANCE: @@ -1883,7 +1885,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo { if (Item* pItem = target->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)) { - target->ToPlayer()->_ApplyWeaponDamage(EQUIPMENT_SLOT_MAINHAND, pItem->GetTemplate(), NULL, apply); + target->ToPlayer()->_ApplyWeaponDamage(EQUIPMENT_SLOT_MAINHAND, pItem->GetTemplate(), nullptr, apply); } } } @@ -2321,7 +2323,7 @@ void AuraEffect::HandleAuraModDisarm(AuraApplication const* aurApp, uint8 mode, player->ApplyItemDependentAuras(item, !apply); if (attackType != MAX_ATTACK) { - player->_ApplyWeaponDamage(slot, item->GetTemplate(), NULL, !apply); + player->_ApplyWeaponDamage(slot, item->GetTemplate(), nullptr, !apply); if (!apply) // apply case already handled on item dependent aura removal (if any) player->UpdateWeaponDependentAuras(attackType); } @@ -4375,7 +4377,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool case 13139: // net-o-matic // root to self part of (root_target->charge->root_self sequence if (caster) - caster->CastSpell(caster, 13138, true, NULL, this); + caster->CastSpell(caster, 13138, true, nullptr, this); break; case 34026: // kill command { @@ -4383,7 +4385,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool if (!pet) break; - target->CastSpell(target, 34027, true, NULL, this); + target->CastSpell(target, 34027, true, nullptr, this); // set 3 stacks and 3 charges (to make all auras not disappear at once) Aura* owner_aura = target->GetAura(34027, GetCasterGUID()); @@ -4404,15 +4406,15 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool if (caster) { if (caster->getGender() == GENDER_FEMALE) - caster->CastSpell(target, 37095, true, NULL, this); // Blood Elf Disguise + caster->CastSpell(target, 37095, true, nullptr, this); // Blood Elf Disguise else - caster->CastSpell(target, 37093, true, NULL, this); + caster->CastSpell(target, 37093, true, nullptr, this); } break; } case 55198: // Tidal Force { - target->CastSpell(target, 55166, true, NULL, this); + target->CastSpell(target, 55166, true, nullptr, this); // set 3 stacks and 3 charges (to make all auras not disappear at once) Aura* owner_aura = target->GetAura(55166, GetCasterGUID()); if (owner_aura) @@ -4428,7 +4430,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool } case 39850: // Rocket Blast if (roll_chance_i(20)) // backfire stun - target->CastSpell(target, 51581, true, NULL, this); + target->CastSpell(target, 51581, true, nullptr, this); break; case 43873: // Headless Horseman Laugh target->PlayDistanceSound(11965); @@ -4437,9 +4439,9 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool if (caster) { if (caster->getGender() == GENDER_FEMALE) - caster->CastSpell(target, 46356, true, NULL, this); + caster->CastSpell(target, 46356, true, nullptr, this); else - caster->CastSpell(target, 46355, true, NULL, this); + caster->CastSpell(target, 46355, true, nullptr, this); } break; case 46361: // Reinforced Net @@ -4481,7 +4483,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool } if (finalSpelId) - caster->CastSpell(target, finalSpelId, true, NULL, this); + caster->CastSpell(target, finalSpelId, true, nullptr, this); } switch (m_spellInfo->SpellFamilyName) @@ -4501,7 +4503,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool break; case 36730: // Flame Strike { - target->CastSpell(target, 36731, true, NULL, this); + target->CastSpell(target, 36731, true, nullptr, this); break; } case 44191: // Flame Strike @@ -4510,7 +4512,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool { uint32 spellId = target->GetMap()->IsHeroic() ? 46163 : 44190; - target->CastSpell(target, spellId, true, NULL, this); + target->CastSpell(target, spellId, true, nullptr, this); } break; } @@ -4524,14 +4526,14 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool break; } case 42783: // Wrath of the Astromancer - target->CastSpell(target, GetAmount(), true, NULL, this); + target->CastSpell(target, GetAmount(), true, nullptr, this); break; case 46308: // Burning Winds cast only at creatures at spawn - target->CastSpell(target, 47287, true, NULL, this); + target->CastSpell(target, 47287, true, nullptr, this); break; case 52172: // Coyote Spirit Despawn Aura case 60244: // Blood Parrot Despawn Aura - target->CastSpell((Unit*)NULL, GetAmount(), true, NULL, this); + target->CastSpell((Unit*)nullptr, GetAmount(), true, nullptr, this); break; case 58600: // Restricted Flight Area case 58730: // Restricted Flight Area @@ -4574,7 +4576,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool SpellInfo const* spell = sSpellMgr->AssertSpellInfo(spellId); for (uint32 i = 0; i < spell->StackAmount; ++i) - caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID()); + caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); break; } target->RemoveAurasDueToSpell(spellId); @@ -4588,7 +4590,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool { SpellInfo const* spell = sSpellMgr->AssertSpellInfo(spellId); for (uint32 i = 0; i < spell->StackAmount; ++i) - caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID()); + caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); break; } target->RemoveAurasDueToSpell(spellId); @@ -4761,8 +4763,8 @@ void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mod InventoryResult msg = plCaster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, GetSpellInfo()->Effects[m_effIndex].ItemType, count, &noSpaceForCount); if (msg != EQUIP_ERR_OK) { - count-=noSpaceForCount; - plCaster->SendEquipError(msg, NULL, NULL, GetSpellInfo()->Effects[m_effIndex].ItemType); + count -= noSpaceForCount; + plCaster->SendEquipError(msg, nullptr, nullptr, GetSpellInfo()->Effects[m_effIndex].ItemType); if (count == 0) return; } @@ -4770,7 +4772,7 @@ void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mod Item* newitem = plCaster->StoreNewItem(dest, GetSpellInfo()->Effects[m_effIndex].ItemType, true); if (!newitem) { - plCaster->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + plCaster->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } plCaster->SendNewItem(newitem, count, true, true); @@ -4921,9 +4923,9 @@ void AuraEffect::HandleAuraLinked(AuraApplication const* aurApp, uint8 mode, boo return; // If amount avalible cast with basepoints (Crypt Fever for example) if (GetAmount()) - caster->CastCustomSpell(target, triggeredSpellId, &m_amount, NULL, NULL, true, NULL, this); + caster->CastCustomSpell(target, triggeredSpellId, &m_amount, nullptr, nullptr, true, nullptr, this); else - caster->CastSpell(target, triggeredSpellId, true, NULL, this); + caster->CastSpell(target, triggeredSpellId, true, nullptr, this); } else { @@ -5089,7 +5091,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const } case 62292: // Blaze (Pool of Tar) // should we use custom damage? - target->CastSpell((Unit*)NULL, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); + target->CastSpell((Unit*)nullptr, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); break; case 62399: // Overload Circuit if (target->GetMap()->IsDungeon() && int(target->GetAppliedAuras().count(62399)) >= (target->GetMap()->IsHeroic() ? 4 : 2)) @@ -5102,7 +5104,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const case 64821: // Fuse Armor (Razorscale) if (GetBase()->GetStackAmount() == GetSpellInfo()->StackAmount) { - target->CastSpell(target, 64774, true, NULL, NULL, GetCasterGUID()); + target->CastSpell(target, 64774, true, nullptr, nullptr, GetCasterGUID()); target->RemoveAura(64821); } break; @@ -5113,7 +5115,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const // Mirror Image if (GetId() == 55342) // Set name of summons to name of caster - target->CastSpell((Unit*)NULL, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); + target->CastSpell((Unit*)nullptr, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); break; } case SPELLFAMILY_DRUID: @@ -5162,7 +5164,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const if (GetSpellInfo()->SpellFamilyFlags[1] & 0x80000000) { if (caster) - caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, NULL, this); + caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, nullptr, this); break; } switch (GetSpellInfo()->Id) @@ -5196,7 +5198,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const { case 49016: // Hysteria uint32 damage = uint32(target->CountPctFromMaxHealth(1)); - target->DealDamage(target, damage, NULL, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + target->DealDamage(target, damage, nullptr, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); break; } // Blood of the North @@ -5228,7 +5230,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) uint32 auraId = auraSpellInfo->Id; // specific code for cases with no trigger spell provided in field - if (triggeredSpellInfo == NULL) + if (triggeredSpellInfo == nullptr) { switch (auraSpellInfo->SpellFamilyName) { @@ -5272,7 +5274,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) // Frost Blast case 27808: if (caster) - caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, NULL, this); + caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, nullptr, this); return; // Inoculate Nestlewood Owlkin case 29528: @@ -5312,7 +5314,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) // so instakill will be naturally done before trigger spell case 31347: { - target->CastSpell(target, 31350, true, NULL, this); + target->CastSpell(target, 31350, true, nullptr, this); target->KillSelf(); return; } @@ -5328,9 +5330,9 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) { // cast 24 spells 34269-34289, 34314-34316 for (uint32 spell_id = 34269; spell_id != 34290; ++spell_id) - target->CastSpell(target, spell_id, true, NULL, this); + target->CastSpell(target, spell_id, true, nullptr, this); for (uint32 spell_id = 34314; spell_id != 34317; ++spell_id) - target->CastSpell(target, spell_id, true, NULL, this); + target->CastSpell(target, spell_id, true, nullptr, this); return; } // Remote Toy @@ -5347,7 +5349,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) if (!caster || target->GetTypeId() != TYPEID_UNIT) return; - caster->CastSpell(caster, 38495, true, NULL, this); + caster->CastSpell(caster, 38495, true, nullptr, this); Creature* creatureTarget = target->ToCreature(); @@ -5394,7 +5396,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) case 65922: case 65923: { - Unit* permafrostCaster = NULL; + Unit* permafrostCaster = nullptr; Aura* permafrostAura = target->GetAura(66193); if (!permafrostAura) permafrostAura = target->GetAura(67855); @@ -5420,15 +5422,15 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) } // Mana Tide case 16191: - target->CastCustomSpell(target, triggerSpellId, &m_amount, NULL, NULL, true, NULL, this); + target->CastCustomSpell(target, triggerSpellId, &m_amount, nullptr, nullptr, true, nullptr, this); return; // Negative Energy Periodic case 46284: - target->CastCustomSpell(triggerSpellId, SPELLVALUE_MAX_TARGETS, m_tickNumber / 10 + 1, NULL, true, NULL, this); + target->CastCustomSpell(triggerSpellId, SPELLVALUE_MAX_TARGETS, m_tickNumber / 10 + 1, nullptr, true, nullptr, this); return; // Slime Pool (Dreadscale & Acidmaw) case 66882: - target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)((((float)m_tickNumber / 60) * 0.9f + 0.1f) * 10000 * 2 / 3), NULL, true, NULL, this); + target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)((((float)m_tickNumber / 60) * 0.9f + 0.1f) * 10000 * 2 / 3), nullptr, true, nullptr, this); return; // Beacon of Light case 53563: @@ -5442,7 +5444,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) case 69508: { if (caster) - caster->CastSpell(target, triggerSpellId, true, NULL, NULL, caster->GetGUID()); + caster->CastSpell(target, triggerSpellId, true, nullptr, nullptr, caster->GetGUID()); return; } case 24745: // Summon Templar, Trigger @@ -5477,7 +5479,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) { if (Unit* triggerCaster = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo) ? caster : target) { - triggerCaster->CastSpell(target, triggeredSpellInfo, true, NULL, this); + triggerCaster->CastSpell(target, triggeredSpellInfo, true, nullptr, this); TC_LOG_DEBUG("spells", "AuraEffect::HandlePeriodicTriggerSpellAuraTick: Spell %u Trigger %u", GetId(), triggeredSpellInfo->Id); } } @@ -5561,7 +5563,7 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const damage = std::max(int32(damage * GetDonePct()), 0); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); @@ -5704,7 +5706,7 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c damage = std::max(int32(damage * GetDonePct()), 0); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); @@ -5875,7 +5877,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const damage = std::max(int32(damage * GetDonePct()), 0); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellHealingBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); } @@ -5997,7 +5999,7 @@ void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) con if (manaFeedVal > 0) { int32 feedAmount = CalculatePct(gainedAmount, manaFeedVal); - caster->CastCustomSpell(caster, 32554, &feedAmount, NULL, NULL, true, NULL, this); + caster->CastCustomSpell(caster, 32554, &feedAmount, nullptr, nullptr, true, nullptr, this); } } } @@ -6142,7 +6144,7 @@ void AuraEffect::HandleProcTriggerSpellAuraProc(AuraApplication* aurApp, ProcEve if (SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId)) { TC_LOG_DEBUG("spells", "AuraEffect::HandleProcTriggerSpellAuraProc: Triggering spell %u from aura %u proc", triggeredSpellInfo->Id, GetId()); - triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this); + triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, nullptr, this); } else TC_LOG_ERROR("spells","AuraEffect::HandleProcTriggerSpellAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); @@ -6158,7 +6160,7 @@ void AuraEffect::HandleProcTriggerSpellWithValueAuraProc(AuraApplication* aurApp { int32 basepoints0 = GetAmount(); TC_LOG_DEBUG("spells", "AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Triggering spell %u with value %d from aura %u proc", triggeredSpellInfo->Id, basepoints0, GetId()); - triggerCaster->CastCustomSpell(triggerTarget, triggerSpellId, &basepoints0, NULL, NULL, true, NULL, this); + triggerCaster->CastCustomSpell(triggerTarget, triggerSpellId, &basepoints0, nullptr, nullptr, true, nullptr, this); } else TC_LOG_ERROR("spells","AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); @@ -6224,7 +6226,7 @@ void AuraEffect::HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcE if (Unit* triggerTarget = target->GetNextRandomRaidMemberOrPet(radius)) { - target->CastSpell(triggerTarget, GetSpellInfo(), true, NULL, this, GetCasterGUID()); + target->CastSpell(triggerTarget, GetSpellInfo(), true, nullptr, this, GetCasterGUID()); if (Aura* aura = triggerTarget->GetAura(GetId(), GetCasterGUID())) aura->SetCharges(jumps); } @@ -6232,7 +6234,7 @@ void AuraEffect::HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcE } TC_LOG_DEBUG("spells", "AuraEffect::HandleRaidProcFromChargeAuraProc: Triggering spell %u from aura %u proc", triggerSpellId, GetId()); - target->CastSpell(target, triggerSpellId, true, NULL, this, GetCasterGUID()); + target->CastSpell(target, triggerSpellId, true, nullptr, this, GetCasterGUID()); } @@ -6265,7 +6267,7 @@ void AuraEffect::HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurA if (Unit* triggerTarget = target->GetNextRandomRaidMemberOrPet(radius)) { - target->CastCustomSpell(triggerTarget, GetId(), &value, NULL, NULL, true, NULL, this, GetCasterGUID()); + target->CastCustomSpell(triggerTarget, GetId(), &value, nullptr, nullptr, true, nullptr, this, GetCasterGUID()); if (Aura* aura = triggerTarget->GetAura(GetId(), GetCasterGUID())) aura->SetCharges(jumps); } @@ -6273,7 +6275,7 @@ void AuraEffect::HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurA } TC_LOG_DEBUG("spells", "AuraEffect::HandleRaidProcFromChargeWithValueAuraProc: Triggering spell %u from aura %u proc", triggerSpellId, GetId()); - target->CastCustomSpell(target, triggerSpellId, &value, NULL, NULL, true, NULL, this, GetCasterGUID()); + target->CastCustomSpell(target, triggerSpellId, &value, nullptr, nullptr, true, nullptr, this, GetCasterGUID()); } template TC_GAME_API void AuraEffect::GetTargetList(std::list&) const; diff --git a/src/server/game/Spells/Auras/SpellAuras.cpp b/src/server/game/Spells/Auras/SpellAuras.cpp index 6a24a73ac1a..cff25bc8e2c 100644 --- a/src/server/game/Spells/Auras/SpellAuras.cpp +++ b/src/server/game/Spells/Auras/SpellAuras.cpp @@ -17,26 +17,27 @@ */ #include "Common.h" -#include "WorldPacket.h" -#include "Opcodes.h" +#include "CellImpl.h" +#include "Config.h" +#include "DynamicObject.h" +#include "GridNotifiersImpl.h" +#include "Item.h" #include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "SpellMgr.h" +#include "Opcodes.h" #include "Player.h" -#include "Unit.h" +#include "ScriptMgr.h" #include "Spell.h" -#include "SpellHistory.h" #include "SpellAuraEffects.h" -#include "DynamicObject.h" -#include "ObjectAccessor.h" -#include "Util.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" -#include "ScriptMgr.h" +#include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" +#include "Unit.h" +#include "Util.h" #include "Vehicle.h" -#include "Config.h" +#include "World.h" +#include "WorldPacket.h" AuraApplication::AuraApplication(Unit* target, Unit* caster, Aura* aura, uint8 effMask): _target(target), _base(aura), _removeMode(AURA_REMOVE_NONE), _slot(MAX_AURAS), @@ -341,7 +342,7 @@ Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owne Aura::Aura(SpellInfo const* spellproto, WorldObject* owner, Unit* caster, Item* castItem, ObjectGuid casterGUID) : m_spellInfo(spellproto), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), -m_castItemGuid(castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_applyTime(time(NULL)), +m_castItemGuid(castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_applyTime(time(nullptr)), m_owner(owner), m_timeCla(0), m_updateTargetMapInterval(0), m_casterLevel(caster ? caster->getLevel() : m_spellInfo->SpellLevel), m_procCharges(0), m_stackAmount(1), m_isRemoved(false), m_isSingleTarget(false), m_isUsingCharges(false), m_dropEvent(nullptr), @@ -363,7 +364,7 @@ AuraScript* Aura::GetScriptByName(std::string const& scriptName) const for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr) if ((*itr)->_GetScriptName()->compare(scriptName) == 0) return *itr; - return NULL; + return nullptr; } void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount) @@ -372,9 +373,9 @@ void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount) for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (effMask & (uint8(1) << i)) - m_effects[i] = new AuraEffect(this, i, baseAmount ? baseAmount + i : NULL, caster); + m_effects[i] = new AuraEffect(this, i, baseAmount ? baseAmount + i : nullptr, caster); else - m_effects[i] = NULL; + m_effects[i] = nullptr; } } @@ -424,7 +425,7 @@ void Aura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp { if (m_spellInfo->IsCooldownStartedOnEvent()) { - Item* castItem = m_castItemGuid ? caster->ToPlayer()->GetItemByGuid(m_castItemGuid) : NULL; + Item* castItem = m_castItemGuid ? caster->ToPlayer()->GetItemByGuid(m_castItemGuid) : nullptr; caster->GetSpellHistory()->StartCooldown(m_spellInfo, castItem ? castItem->GetEntry() : 0, nullptr, true); } } @@ -647,8 +648,8 @@ void Aura::UpdateOwner(uint32 diff, WorldObject* owner) Unit* caster = GetCaster(); // Apply spellmods for channeled auras // used for example when triggered spell of spell:10 is modded - Spell* modSpell = NULL; - Player* modOwner = NULL; + Spell* modSpell = nullptr; + Player* modOwner = nullptr; if (caster) { modOwner = caster->GetSpellModOwner(); @@ -718,7 +719,7 @@ void Aura::Update(uint32 diff, Unit* caster) int32 Aura::CalcMaxDuration(Unit* caster) const { - Player* modOwner = NULL; + Player* modOwner = nullptr; int32 maxDuration; if (caster) @@ -734,7 +735,7 @@ int32 Aura::CalcMaxDuration(Unit* caster) const // IsPermanent() checks max duration (which we are supposed to calculate here) if (maxDuration != -1 && modOwner) - modOwner->ApplySpellMod(GetId(), maxDuration); + modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, maxDuration); return maxDuration; } @@ -744,7 +745,7 @@ void Aura::SetDuration(int32 duration, bool withMods) if (withMods) if (Unit* caster = GetCaster()) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), duration); + modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, duration); m_duration = duration; SetNeedClientUpdateForTargets(); @@ -799,7 +800,7 @@ uint8 Aura::CalcMaxCharges(Unit* caster) const if (caster) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), maxProcCharges); + modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, maxProcCharges); return maxProcCharges; } @@ -1047,7 +1048,7 @@ int32 Aura::CalcDispelChance(Unit const* auraTarget, bool offensive) const // Apply dispel mod from aura caster if (Unit* caster = GetCaster()) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), resistChance); + modOwner->ApplySpellMod(GetId(), SPELLMOD_RESIST_DISPEL_CHANCE, resistChance); // Dispel resistance from target SPELL_AURA_MOD_DISPEL_RESIST // Only affects offensive dispels @@ -1174,7 +1175,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (*itr < 0) target->RemoveAurasDueToSpell(-(*itr)); else if (removeMode != AURA_REMOVE_BY_DEATH) - target->CastSpell(target, *itr, true, NULL, NULL, GetCasterGUID()); + target->CastSpell(target, *itr, true, nullptr, nullptr, GetCasterGUID()); } } if (std::vector const* spellTriggered = sSpellMgr->GetSpellLinked(GetId() + SPELL_LINK_AURA)) @@ -1237,7 +1238,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (caster->HasAura(64760)) { int32 heal = GetEffect(EFFECT_0)->GetAmount(); - caster->CastCustomSpell(target, 64801, &heal, NULL, NULL, true, NULL, GetEffect(EFFECT_0)); + caster->CastCustomSpell(target, 64801, &heal, nullptr, nullptr, true, nullptr, GetEffect(EFFECT_0)); } } break; @@ -1295,7 +1296,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b { int32 damage = (devouringPlague->GetAmount() + devouringPlague->GetBonusAmount()) * devouringPlague->GetDonePct(); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT); @@ -1334,7 +1335,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (GetCasterGUID() == target->GetGUID()) break; - AuraEffect* aurEff = NULL; + AuraEffect* aurEff = nullptr; // Ebon Plaguebringer / Crypt Fever Unit::AuraEffectList const& TalentAuras = caster->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (Unit::AuraEffectList::const_iterator itr = TalentAuras.begin(); itr != TalentAuras.end(); ++itr) @@ -1392,7 +1393,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b case 66: // Invisibility if (removeMode != AURA_REMOVE_BY_EXPIRE) break; - target->CastSpell(target, 32612, true, NULL, GetEffect(1)); + target->CastSpell(target, 32612, true, nullptr, GetEffect(1)); target->CombatStop(); break; default: @@ -1453,7 +1454,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 178, 1)) { int32 basepoints0 = aurEff->GetAmount() * caster->GetCreateMana() / 100; - caster->CastCustomSpell(caster, 64103, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); + caster->CastCustomSpell(caster, 64103, &basepoints0, nullptr, nullptr, true, nullptr, GetEffect(0)); } } // Power word: shield @@ -1486,7 +1487,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b multiplier += 0.5f; int32 basepoints0 = int32(CalculatePct(caster->GetMaxPower(POWER_MANA), multiplier)); - caster->CastCustomSpell(caster, 47755, &basepoints0, NULL, NULL, true); + caster->CastCustomSpell(caster, 47755, &basepoints0, nullptr, nullptr, true); } // effect on aura target if (AuraEffect const* aurEff = aura->GetEffect(1)) @@ -1500,7 +1501,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b case POWER_MANA: { int32 basepoints0 = int32(CalculatePct(target->GetMaxPower(POWER_MANA), 2)); - caster->CastCustomSpell(target, 63654, &basepoints0, NULL, NULL, true); + caster->CastCustomSpell(target, 63654, &basepoints0, nullptr, nullptr, true); break; } case POWER_RAGE: triggeredSpellId = 63653; break; @@ -1593,7 +1594,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b target->RemoveAurasDueToSpell(31666); int32 basepoints0 = aurEff->GetAmount(); - target->CastCustomSpell(target, 31665, &basepoints0, NULL, NULL, true); + target->CastCustomSpell(target, 31665, &basepoints0, nullptr, nullptr, true); } } // Overkill @@ -1812,7 +1813,7 @@ bool Aura::CanStackWith(Aura const* existingAura) const if (HasEffectType(SPELL_AURA_CONTROL_VEHICLE) && existingAura->HasEffectType(SPELL_AURA_CONTROL_VEHICLE)) { - Vehicle* veh = NULL; + Vehicle* veh = nullptr; if (GetOwner()->ToUnit()) veh = GetOwner()->ToUnit()->GetVehicleKit(); @@ -2005,7 +2006,7 @@ float Aura::CalcProcChance(SpellProcEntry const& procEntry, ProcEventInfo& event } // apply chance modifer aura, applies also to ppm chance (see improved judgement of light spell) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), chance); + modOwner->ApplySpellMod(GetId(), SPELLMOD_CHANCE_OF_SUCCESS, chance); } // proc chance is reduced by an additional 3.333% per level past 60 diff --git a/src/server/game/Spells/Auras/SpellAuras.h b/src/server/game/Spells/Auras/SpellAuras.h index 32eaf8585e8..ee28ee2fd94 100644 --- a/src/server/game/Spells/Auras/SpellAuras.h +++ b/src/server/game/Spells/Auras/SpellAuras.h @@ -176,7 +176,7 @@ class TC_GAME_API Aura void SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32 * amount); // helpers for aura effects - bool HasEffect(uint8 effIndex) const { return GetEffect(effIndex) != NULL; } + bool HasEffect(uint8 effIndex) const { return GetEffect(effIndex) != nullptr; } bool HasEffectType(AuraType type) const; AuraEffect* GetEffect(uint8 effIndex) const { ASSERT (effIndex < MAX_SPELL_EFFECTS); return m_effects[effIndex]; } uint8 GetEffectMask() const { uint8 effMask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) effMask |= 1<second; return NULL; } - AuraApplication* GetApplicationOfTarget(ObjectGuid guid) { ApplicationMap::iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return NULL; } + AuraApplication const* GetApplicationOfTarget(ObjectGuid guid) const { ApplicationMap::const_iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } + AuraApplication* GetApplicationOfTarget(ObjectGuid guid) { ApplicationMap::iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } bool IsAppliedOnTarget(ObjectGuid guid) const { return m_applications.find(guid) != m_applications.end(); } void SetNeedClientUpdateForTargets() const; @@ -234,11 +234,16 @@ class TC_GAME_API Aura bool CallScriptEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); void CallScriptAfterEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); - AuraScript* GetScriptByName(std::string const& scriptName) const; + template + Script* GetScript(std::string const& scriptName) const + { + return dynamic_cast(GetScriptByName(scriptName)); + } std::vector m_loadedScripts; private: + AuraScript* GetScriptByName(std::string const& scriptName) const; void _DeleteRemovedApplications(); protected: diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index d8baf713926..ae65161538b 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -16,46 +16,49 @@ * with this program. If not, see . */ +#include "Spell.h" +#include "Battlefield.h" +#include "BattlefieldMgr.h" +#include "Battleground.h" +#include "CellImpl.h" #include "Common.h" +#include "ConditionMgr.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "GameTime.h" +#include "DBCStores.h" +#include "DisableMgr.h" +#include "DynamicObject.h" +#include "GameObjectAI.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "Opcodes.h" +#include "GameTime.h" +#include "InstanceScript.h" +#include "Item.h" #include "Log.h" -#include "UpdateMask.h" -#include "World.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Player.h" +#include "Opcodes.h" +#include "PathGenerator.h" #include "Pet.h" -#include "Unit.h" -#include "Spell.h" -#include "DynamicObject.h" -#include "UpdateData.h" -#include "ObjectAccessor.h" -#include "CellImpl.h" +#include "Player.h" +#include "ScriptMgr.h" #include "SharedDefines.h" -#include "LootMgr.h" -#include "VMapFactory.h" -#include "Battleground.h" -#include "Util.h" -#include "TemporarySummon.h" -#include "Vehicle.h" #include "SpellAuraEffects.h" -#include "ScriptMgr.h" -#include "ConditionMgr.h" -#include "DisableMgr.h" -#include "SpellScript.h" -#include "InstanceScript.h" -#include "SpellInfo.h" #include "SpellHistory.h" -#include "Battlefield.h" -#include "BattlefieldMgr.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "TradeData.h" -#include "GameObjectAI.h" +#include "Unit.h" +#include "UpdateData.h" +#include "UpdateMask.h" +#include "Util.h" +#include "Vehicle.h" +#include "VMapFactory.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS]; @@ -109,8 +112,8 @@ void SpellDestination::RelocateOffset(Position const& offset) SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0), m_strTarget() { - m_objectTarget = NULL; - m_itemTarget = NULL; + m_objectTarget = nullptr; + m_itemTarget = nullptr; m_itemTargetEntry = 0; @@ -244,7 +247,7 @@ Unit* SpellCastTargets::GetUnitTarget() const if (m_objectTarget) return m_objectTarget->ToUnit(); - return NULL; + return nullptr; } void SpellCastTargets::SetUnitTarget(Unit* target) @@ -270,7 +273,7 @@ GameObject* SpellCastTargets::GetGOTarget() const if (m_objectTarget) return m_objectTarget->ToGameObject(); - return NULL; + return nullptr; } void SpellCastTargets::SetGOTarget(GameObject* target) @@ -296,7 +299,7 @@ Corpse* SpellCastTargets::GetCorpseTarget() const if (m_objectTarget) return m_objectTarget->ToCorpse(); - return NULL; + return nullptr; } WorldObject* SpellCastTargets::GetObjectTarget() const @@ -311,7 +314,7 @@ ObjectGuid SpellCastTargets::GetObjectTargetGUID() const void SpellCastTargets::RemoveObjectTarget() { - m_objectTarget = NULL; + m_objectTarget = nullptr; m_objectTargetGUID.Clear(); m_targetMask &= ~(TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK); } @@ -441,11 +444,21 @@ void SpellCastTargets::RemoveDst() m_targetMask &= ~(TARGET_FLAG_DEST_LOCATION); } +bool SpellCastTargets::HasSrc() const +{ + return (GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) != 0; +} + +bool SpellCastTargets::HasDst() const +{ + return (GetTargetMask() & TARGET_FLAG_DEST_LOCATION) != 0; +} + void SpellCastTargets::Update(Unit* caster) { - m_objectTarget = m_objectTargetGUID ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : NULL; + m_objectTarget = m_objectTargetGUID ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : nullptr; - m_itemTarget = NULL; + m_itemTarget = nullptr; if (caster->GetTypeId() == TYPEID_PLAYER) { Player* player = caster->ToPlayer(); @@ -511,14 +524,28 @@ SpellValue::SpellValue(SpellInfo const* proto) AuraStackAmount = 1; } +class TC_GAME_API SpellEvent : public BasicEvent +{ + public: + SpellEvent(Spell* spell); + virtual ~SpellEvent(); + + bool Execute(uint64 e_time, uint32 p_time) override; + void Abort(uint64 e_time) override; + bool IsDeletable() const override; + + protected: + Spell* m_Spell; +}; + Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, ObjectGuid originalCasterGUID, bool skipCheck) : m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)), m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster) -, m_spellValue(new SpellValue(m_spellInfo)), _spellEvent(nullptr), m_preGeneratedPath(PathGenerator(m_caster)) +, m_spellValue(new SpellValue(m_spellInfo)), _spellEvent(nullptr) { m_customError = SPELL_CUSTOM_ERROR_NONE; m_skipCheck = skipCheck; - m_selfContainer = NULL; + m_selfContainer = nullptr; m_referencedFromCurrentSpell = false; m_executedCurrently = false; m_needComboPoints = m_spellInfo->NeedsComboPoints(); @@ -552,7 +579,7 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) - m_originalCaster = NULL; + m_originalCaster = nullptr; } m_spellState = SPELL_STATE_NULL; @@ -560,14 +587,14 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO if (info->HasAttribute(SPELL_ATTR4_CAN_CAST_WHILE_CASTING)) _triggeredCastFlags = TriggerCastFlags(uint32(_triggeredCastFlags) | TRIGGERED_IGNORE_CAST_IN_PROGRESS | TRIGGERED_CAST_DIRECTLY); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; - unitTarget = NULL; - itemTarget = NULL; - gameObjTarget = NULL; - destTarget = NULL; + unitTarget = nullptr; + itemTarget = nullptr; + gameObjTarget = nullptr; + destTarget = nullptr; damage = 0; targetMissInfo = SPELL_MISS_NONE; effectHandleMode = SPELL_EFFECT_HANDLE_LAUNCH; @@ -576,12 +603,12 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO m_procAttacker = 0; m_procVictim = 0; m_hitMask = 0; - focusObject = NULL; + focusObject = nullptr; m_cast_count = 0; m_glyphIndex = 0; m_preCastSpell = 0; - m_triggeredByAuraSpell = NULL; - m_spellAura = NULL; + m_triggeredByAuraSpell = nullptr; + m_spellAura = nullptr; //Auto Shot & Shoot (wand) m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell(); @@ -622,7 +649,7 @@ Spell::~Spell() // Clean the reference to avoid later crash. // If this error is repeating, we may have to add an ASSERT to better track down how we get into this case. TC_LOG_ERROR("spells", "SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id); - *m_selfContainer = NULL; + *m_selfContainer = nullptr; } if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER) @@ -657,7 +684,7 @@ void Spell::InitExplicitTargets(SpellCastTargets const& targets) // try to select correct unit target if not provided by client or by serverside cast if (neededTargets & (TARGET_FLAG_UNIT_MASK)) { - Unit* unit = NULL; + Unit* unit = nullptr; // try to use player selection as a target if (Player* playerCaster = m_caster->ToPlayer()) { @@ -724,7 +751,7 @@ void Spell::SelectExplicitTargets() redirect = m_caster->GetMeleeHitRedirectTarget(target, m_spellInfo); break; default: - redirect = NULL; + redirect = nullptr; break; } if (redirect && (redirect != target)) @@ -1171,7 +1198,7 @@ void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTarge void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { - Unit* referer = NULL; + Unit* referer = nullptr; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: @@ -1202,7 +1229,7 @@ void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTarge if (!referer) return; - Position const* center = NULL; + Position const* center = nullptr; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: @@ -1429,7 +1456,7 @@ void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitT void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { - WorldObject* target = NULL; + WorldObject* target = nullptr; bool checkIfValid = true; switch (targetType.GetTarget()) @@ -1498,7 +1525,7 @@ void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTarg { uint32 maxTargets = m_spellInfo->Effects[effIndex].ChainTarget; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, maxTargets, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); if (maxTargets > 1) { @@ -1646,7 +1673,7 @@ void Spell::SelectEffectTypeImplicitTargets(uint8 effIndex) if (!targetMask) return; - WorldObject* target = NULL; + WorldObject* target = nullptr; switch (m_spellInfo->Effects[effIndex].GetImplicitTargetType()) { @@ -1759,10 +1786,10 @@ void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* refere WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList) { - WorldObject* target = NULL; + WorldObject* target = nullptr; uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); if (!containerTypeMask) - return NULL; + return nullptr; Trinity::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList); Trinity::WorldObjectLastSearcher searcher(m_caster, target, check, containerTypeMask); SearchTargets > (searcher, containerTypeMask, m_caster, m_caster, range); @@ -1877,7 +1904,7 @@ void Spell::SearchChainTargets(std::list& targets, uint32 chainTar GameObject* Spell::SearchSpellFocus() { - GameObject* focus = NULL; + GameObject* focus = nullptr; Trinity::GameObjectFocusCheck check(m_caster, m_spellInfo->RequiresSpellFocus); Trinity::GameObjectSearcher searcher(m_caster, focus, check); SearchTargets > (searcher, GRID_MAP_TYPE_MASK_GAMEOBJECT, m_caster, m_caster, m_caster->GetVisibilityRange()); @@ -2217,7 +2244,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // can't use default call because of threading, do stuff as fast as possible for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (farMask & (1 << i)) - HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(unit, nullptr, nullptr, i, SPELL_EFFECT_HANDLE_HIT_TARGET); return; } @@ -2656,7 +2683,7 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleA for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) - HandleEffects(unit, NULL, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(unit, nullptr, nullptr, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); return SPELL_MISS_NONE; } @@ -2752,7 +2779,7 @@ void Spell::DoAllEffectOnTarget(GOTargetInfo* target) for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) - HandleEffects(NULL, NULL, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(nullptr, nullptr, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); if (go->AI()) go->AI()->SpellHit(m_caster, m_spellInfo); @@ -2772,7 +2799,7 @@ void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) - HandleEffects(NULL, target->item, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(nullptr, target->item, nullptr, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); CallScriptOnHitHandlers(); @@ -2798,7 +2825,7 @@ bool Spell::UpdateChanneledTargetList() { range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive()); if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, range, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); // add little tolerance level range += std::min(MAX_SPELL_RANGE_TOLERANCE, range*0.1f); // 10% but no more than MAX_SPELL_RANGE_TOLERANCE @@ -3051,7 +3078,7 @@ void Spell::cancel() SetReferencedFromCurrent(false); if (m_selfContainer && *m_selfContainer == this) - *m_selfContainer = NULL; + *m_selfContainer = nullptr; m_caster->RemoveDynObject(m_spellInfo->Id); if (m_spellInfo->IsChanneled()) // if not channeled then the object for the current cast wasn't summoned yet @@ -3106,7 +3133,7 @@ void Spell::_cast(bool skipCheck) // As of 3.0.2 pets begin attacking their owner's target immediately // Let any pets know we've attacked something. Check DmgClass for harmful spells only // This prevents spells such as Hunter's Mark from triggering pet attack - if (this->GetSpellInfo()->DmgClass != SPELL_DAMAGE_CLASS_NONE) + if (GetSpellInfo()->DmgClass != SPELL_DAMAGE_CLASS_NONE) if (Unit* unitTarget = m_targets.GetUnitTarget()) for (Unit* controlled : playerCaster->m_Controlled) if (Creature* cControlled = controlled->ToCreature()) @@ -3317,7 +3344,7 @@ void Spell::handle_immediate() // First mod_duration then haste - see Missile Barrage // Apply duration mod if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, duration); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); // Apply haste mods m_caster->ModSpellDurationTime(m_spellInfo, duration, this); @@ -3445,7 +3472,7 @@ uint64 Spell::handle_delayed(uint64 t_offset) void Spell::_handle_immediate_phase() { - m_spellAura = NULL; + m_spellAura = nullptr; // handle some immediate features of the spell here HandleThreatSpells(); @@ -3460,7 +3487,7 @@ void Spell::_handle_immediate_phase() continue; // call effect handlers to handle destination hit - HandleEffects(NULL, NULL, NULL, j, SPELL_EFFECT_HANDLE_HIT); + HandleEffects(nullptr, nullptr, nullptr, j, SPELL_EFFECT_HANDLE_HIT); } // process items @@ -3897,7 +3924,7 @@ void Spell::SendPetCastResult(SpellCastResult result) WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1); WriteCastResultInfo(data, player, m_spellInfo, m_cast_count, result, m_customError); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Spell::SendSpellStart() @@ -4221,7 +4248,7 @@ void Spell::SendLogExecute() data.append(*m_effectExecuteData[i]); delete m_effectExecuteData[i]; - m_effectExecuteData[i] = NULL; + m_effectExecuteData[i] = nullptr; } m_caster->SendMessageToSet(&data, true); } @@ -4367,7 +4394,7 @@ void Spell::SendResurrectRequest(Player* target) data << uint8(m_caster->IsSpiritHealer()); // "you'll be afflicted with resurrection sickness" // override delay sent with SMSG_CORPSE_RECLAIM_DELAY, set instant resurrection for spells with this attribute data << uint8(!m_spellInfo->HasAttribute(SPELL_ATTR3_IGNORE_RESURRECTION_TIMER)); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); } void Spell::TakeCastItem() @@ -4430,9 +4457,9 @@ void Spell::TakeCastItem() // prevent crash at access to deleted m_targets.GetItemTarget if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; } @@ -4455,8 +4482,11 @@ void Spell::TakePower() if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNE) + { if (ObjectGuid targetGUID = m_targets.GetUnitTargetGUID()) - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + { + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + { if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE) @@ -4464,10 +4494,13 @@ void Spell::TakePower() hit = false; //lower spell cost on fail (by talent aura) if (Player* modOwner = m_caster->ToPlayer()->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, m_powerCost); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost); } break; } + } + } + } } if (powerType == POWER_RUNE) @@ -4556,7 +4589,7 @@ SpellCastResult Spell::CheckRuneCost(uint32 runeCostID) const { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, runeCost[i], const_cast(this)); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], const_cast(this)); } runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later @@ -4596,7 +4629,7 @@ void Spell::TakeRunePower(bool didHit) { runeCost[i] = runeCostData->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, runeCost[i], this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this); } // Let's say we use a skill that requires a Frost rune. This is the order: @@ -4673,7 +4706,7 @@ void Spell::TakeReagents() if (m_caster->GetTypeId() != TYPEID_PLAYER) return; - ItemTemplate const* castItemTemplate = m_CastItem ? m_CastItem->GetTemplate() : NULL; + ItemTemplate const* castItemTemplate = m_CastItem ? m_CastItem->GetTemplate() : nullptr; // do not take reagents for these item casts if (castItemTemplate && castItemTemplate->Flags & ITEM_FLAG_NO_REAGENT_COST) @@ -4705,14 +4738,14 @@ void Spell::TakeReagents() } } - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; } // if GetItemTarget is also spell reagent if (m_targets.GetItemTargetEntry() == itemid) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); p_caster->DestroyItemCount(itemid, itemcount, true); } @@ -4782,7 +4815,7 @@ void Spell::HandleEffects(Unit* pUnitTarget, Item* pItemTarget, GameObject* pGOT TC_LOG_DEBUG("spells", "Spell: %u Effect : %u", m_spellInfo->Id, eff); // we do not need DamageMultiplier here. - damage = CalculateDamage(i, NULL); + damage = CalculateDamage(i, nullptr); bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i, mode); @@ -4888,7 +4921,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint m_needComboPoints = false; if ((*j)->GetMiscValue() == 1) { - reqCombat=false; + reqCombat = false; break; } } @@ -4989,7 +5022,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint if (DynamicObject* dynObj = m_caster->GetDynObject(m_triggeredByAuraSpell->Id)) losTarget = dynObj; - if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !target->IsWithinLOSInMap(losTarget, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) + if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, nullptr, SPELL_DISABLE_LOS) && !target->IsWithinLOSInMap(losTarget, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) return SPELL_FAILED_LINE_OF_SIGHT; } } @@ -5001,7 +5034,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint float x, y, z; m_targets.GetDstPos()->GetPosition(x, y, z); - if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS) && !m_caster->IsWithinLOS(x, y, z, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) + if (!m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, nullptr, SPELL_DISABLE_LOS) && !m_caster->IsWithinLOS(x, y, z, LINEOFSIGHT_ALL_CHECKS, VMAP::ModelIgnoreFlags::M2)) return SPELL_FAILED_LINE_OF_SIGHT; } @@ -5262,26 +5295,27 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint float objSize = target->GetCombatReach(); float range = m_spellInfo->GetMaxRange(true, m_caster, this) * 1.5f + objSize; // can't be overly strict - m_preGeneratedPath.SetPathLengthLimit(range); + m_preGeneratedPath = Trinity::make_unique(m_caster); + m_preGeneratedPath->SetPathLengthLimit(range); // first try with raycast, if it fails fall back to normal path float targetObjectSize = std::min(target->GetCombatReach(), 4.0f); - bool result = m_preGeneratedPath.CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, true); - if (m_preGeneratedPath.GetPathType() & PATHFIND_SHORT) + bool result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, true); + if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT) return SPELL_FAILED_OUT_OF_RANGE; - else if (!result || m_preGeneratedPath.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) + else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) { - result = m_preGeneratedPath.CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, false); - if (m_preGeneratedPath.GetPathType() & PATHFIND_SHORT) + result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, false); + if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT) return SPELL_FAILED_OUT_OF_RANGE; - else if (!result || m_preGeneratedPath.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) + else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) return SPELL_FAILED_NOPATH; - else if (m_preGeneratedPath.IsInvalidDestinationZ(target)) // Check position z, if not in a straight line + else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if not in a straight line return SPELL_FAILED_NOPATH; } - else if (m_preGeneratedPath.IsInvalidDestinationZ(target)) // Check position z, if in a straight line + else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if in a straight line return SPELL_FAILED_NOPATH; - m_preGeneratedPath.ReducePathLenghtByDist(objSize); // move back + m_preGeneratedPath->ReducePathLenghtByDist(objSize); // move back } break; } @@ -5324,7 +5358,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget())) return SPELL_FAILED_BAD_TARGETS; - Item* pTempItem = NULL; + Item* pTempItem = nullptr; if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) @@ -5424,7 +5458,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint { if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player) if (Pet* pet = m_caster->ToPlayer()->GetPet()) - pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID()); + pet->CastSpell(pet, 32752, true, nullptr, nullptr, pet->GetGUID()); } else if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) return SPELL_FAILED_ALREADY_HAVE_SUMMON; @@ -5938,6 +5972,11 @@ bool Spell::CheckSpellCancelsConfuse(uint32* param1) const return CheckSpellCancelsAuraEffect(SPELL_AURA_MOD_CONFUSE, param1); } +int32 Spell::CalculateDamage(uint8 i, Unit const* target) const +{ + return m_caster->CalculateSpellDamage(target, m_spellInfo, i, &m_spellValue->EffectBasePoints[i]); +} + bool Spell::CanAutoCast(Unit* target) { if (!target) @@ -5994,6 +6033,18 @@ bool Spell::CanAutoCast(Unit* target) return false; } +void Spell::CheckSrc() +{ + if (!m_targets.HasSrc()) + m_targets.SetSrc(*m_caster); +} + +void Spell::CheckDst() +{ + if (!m_targets.HasDst()) + m_targets.SetDst(*m_caster); +} + SpellCastResult Spell::CheckRange(bool strict) const { // Don't check for instant cast spells @@ -6083,7 +6134,7 @@ std::pair Spell::GetMinMaxRange(bool strict) const maxRange *= ranged->GetTemplate()->RangedModRange * 0.01f; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, maxRange, const_cast(this)); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, maxRange, const_cast(this)); maxRange += rangeMod; @@ -6693,7 +6744,7 @@ void Spell::Delayed() // only called in DealDamage() //check pushback reduce int32 delaytime = 500; // spellcasting delay is normally 500ms int32 delayReduce = 100; // must be initialized to 100 for percent modifiers - m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, delayReduce, this); + m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; @@ -6731,7 +6782,7 @@ void Spell::DelayedChannel() int32 delaytime = CalculatePct(duration, 25); // channeling delay is normally 25% of its time per hit int32 delayReduce = 100; // must be initialized to 100 for percent modifiers - m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, delayReduce, this); + m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; @@ -6768,7 +6819,7 @@ bool Spell::UpdatePointers() { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) - m_originalCaster = NULL; + m_originalCaster = nullptr; } if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER) @@ -6790,7 +6841,7 @@ bool Spell::UpdatePointers() return true; // cache last transport - WorldObject* transport = NULL; + WorldObject* transport = nullptr; // update effect destinations (in case of moved transport dest target) for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) @@ -6847,11 +6898,11 @@ bool Spell::CheckEffectTarget(Unit const* target, uint32 eff, Position const* lo } // check for ignore LOS on the effect itself - if (m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS)) + if (m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, nullptr, SPELL_DISABLE_LOS)) return true; // if spell is triggered, need to check for LOS disable on the aura triggering it and inherit that behaviour - if (IsTriggered() && m_triggeredByAuraSpell && (m_triggeredByAuraSpell->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_triggeredByAuraSpell->Id, NULL, SPELL_DISABLE_LOS))) + if (IsTriggered() && m_triggeredByAuraSpell && (m_triggeredByAuraSpell->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_triggeredByAuraSpell->Id, nullptr, SPELL_DISABLE_LOS))) return true; /// @todo shit below shouldn't be here, but it's temporary @@ -6910,7 +6961,7 @@ bool Spell::CheckEffectTarget(Unit const* target, uint32 eff, Position const* lo else { // Get GO cast coordinates if original caster -> GO - WorldObject* caster = NULL; + WorldObject* caster = nullptr; if (m_originalCasterGUID.IsGameObject()) caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID); if (!caster) @@ -6925,6 +6976,26 @@ bool Spell::CheckEffectTarget(Unit const* target, uint32 eff, Position const* lo return true; } +bool Spell::IsTriggered() const +{ + return (_triggeredCastFlags & TRIGGERED_FULL_MASK) != 0; +} + +bool Spell::IsIgnoringCooldowns() const +{ + return (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD) != 0; +} + +bool Spell::IsProcDisabled() const +{ + return (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) != 0; +} + +bool Spell::IsChannelActive() const +{ + return m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != 0; +} + bool Spell::IsAutoActionResetSpell() const { /// @todo changed SPELL_INTERRUPT_FLAG_AUTOATTACK -> SPELL_INTERRUPT_FLAG_INTERRUPT to fix compile - is this check correct at all? @@ -7099,7 +7170,7 @@ void Spell::HandleLaunchPhase() if (!m_spellInfo->Effects[i].IsEffect()) continue; - HandleEffects(NULL, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH); + HandleEffects(nullptr, nullptr, nullptr, i, SPELL_EFFECT_HANDLE_LAUNCH); } float multiplier[MAX_SPELL_EFFECTS]; @@ -7155,7 +7226,7 @@ void Spell::HandleLaunchPhase() void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier) { - Unit* unit = NULL; + Unit* unit = nullptr; // In case spell hit target, do all effect on that target if (targetInfo.missCondition == SPELL_MISS_NONE) unit = m_caster->GetGUID() == targetInfo.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, targetInfo.targetGUID); @@ -7172,7 +7243,7 @@ void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier) m_damage = 0; m_healing = 0; - HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH_TARGET); + HandleEffects(unit, nullptr, nullptr, i, SPELL_EFFECT_HANDLE_LAUNCH_TARGET); if (m_damage > 0) { @@ -7662,7 +7733,7 @@ void Spell::TriggerGlobalCooldown() { // gcd modifier auras are applied only to own spells and only players have such mods if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, gcd, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this); // Apply haste rating gcd = int32(float(gcd) * m_caster->GetFloatValue(UNIT_MOD_CAST_SPEED)); diff --git a/src/server/game/Spells/Spell.h b/src/server/game/Spells/Spell.h index 7cea09d5c21..6d9bd44e9f1 100644 --- a/src/server/game/Spells/Spell.h +++ b/src/server/game/Spells/Spell.h @@ -19,21 +19,39 @@ #ifndef __SPELL_H #define __SPELL_H -#include "GridDefines.h" +#include "ConditionMgr.h" +#include "DBCEnums.h" +#include "ObjectGuid.h" +#include "Position.h" #include "SharedDefines.h" -#include "ObjectMgr.h" -#include "SpellInfo.h" -#include "PathGenerator.h" +#include -class Unit; -class Player; -class GameObject; -class DynamicObject; -class WorldObject; class Aura; -class SpellScript; -class ByteBuffer; +class AuraEffect; +class Corpse; +class DynamicObject; +class GameObject; +class Item; +class Object; +class PathGenerator; +class Player; class SpellEvent; +class SpellImplicitTargetInfo; +class SpellInfo; +class SpellScript; +class Unit; +class WorldObject; +class WorldPacket; +struct SummonPropertiesEntry; +enum AuraType : uint32; +enum CurrentSpellTypes : uint8; +enum LootType : uint8; +enum SpellCastTargetFlags : uint32; +enum SpellTargetCheckTypes : uint8; +enum SpellTargetObjectTypes : uint8; +enum SpellValueMod : uint8; +enum TriggerCastFlags : uint32; +enum WeaponAttackType : uint8; #define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILLISECONDS) #define MAX_SPELL_RANGE_TOLERANCE 3.0f @@ -156,8 +174,8 @@ class TC_GAME_API SpellCastTargets void ModDst(SpellDestination const& spellDest); void RemoveDst(); - bool HasSrc() const { return (GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) != 0; } - bool HasDst() const { return (GetTargetMask() & TARGET_FLAG_DEST_LOCATION) != 0; } + bool HasSrc() const; + bool HasDst() const; bool HasTraj() const { return m_speed != 0; } float GetElevation() const { return m_elevation; } @@ -225,7 +243,6 @@ static const uint32 SPELL_INTERRUPT_NONPLAYER = 32747; class TC_GAME_API Spell { - friend void Unit::SetCurrentCastSpell(Spell* pSpell); friend class SpellScript; public: @@ -382,13 +399,13 @@ class TC_GAME_API Spell uint32 GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionContainer* condList); template void SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius); - WorldObject* SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList = NULL); + WorldObject* SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList = nullptr); void SearchAreaTargets(std::list& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList); void SearchChainTargets(std::list& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionContainer* condList, bool isChainHeal); GameObject* SearchSpellFocus(); - void prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura = NULL); + void prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura = nullptr); void cancel(); void update(uint32 difftime); void cast(bool skipCheck = false); @@ -424,7 +441,7 @@ class TC_GAME_API Spell bool CheckSpellCancelsFear(uint32* param1) const; bool CheckSpellCancelsConfuse(uint32* param1) const; - int32 CalculateDamage(uint8 i, Unit const* target) const { return m_caster->CalculateSpellDamage(target, m_spellInfo, i, &m_spellValue->EffectBasePoints[i]); } + int32 CalculateDamage(uint8 i, Unit const* target) const; bool HaveTargetsForEffect(uint8 effect) const; void Delayed(); @@ -438,8 +455,8 @@ class TC_GAME_API Spell bool CheckEffectTarget(Unit const* target, uint32 eff, Position const* losPosition) const; bool CanAutoCast(Unit* target); - void CheckSrc() { if (!m_targets.HasSrc()) m_targets.SetSrc(*m_caster); } - void CheckDst() { if (!m_targets.HasDst()) m_targets.SetDst(*m_caster); } + void CheckSrc(); + void CheckDst(); static void WriteCastResultInfo(WorldPacket& data, Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError, uint32* param1 = nullptr, uint32* param2 = nullptr); static void SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError = SPELL_CUSTOM_ERROR_NONE, uint32* param1 = nullptr, uint32* param2 = nullptr); @@ -484,10 +501,10 @@ class TC_GAME_API Spell bool IsAutoRepeat() const { return m_autoRepeat; } void SetAutoRepeat(bool rep) { m_autoRepeat = rep; } void ReSetTimer() { m_timer = m_casttime > 0 ? m_casttime : 0; } - bool IsTriggered() const { return (_triggeredCastFlags & TRIGGERED_FULL_MASK) != 0; } - bool IsIgnoringCooldowns() const { return (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD) != 0; } - bool IsProcDisabled() const { return (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) != 0; } - bool IsChannelActive() const { return m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != 0; } + bool IsTriggered() const; + bool IsIgnoringCooldowns() const; + bool IsProcDisabled() const; + bool IsChannelActive() const; bool IsAutoActionResetSpell() const; bool IsTriggeredByAura(SpellInfo const* auraSpellInfo) const { return (auraSpellInfo == m_triggeredByAuraSpell); } @@ -516,6 +533,9 @@ class TC_GAME_API Spell void CleanupTargetList(); void SetSpellValue(SpellValueMod mod, int32 value); + + Spell** m_selfContainer; // pointer to our spell container (if applicable) + protected: bool HasGlobalCooldown() const; void TriggerGlobalCooldown(); @@ -533,8 +553,6 @@ class TC_GAME_API Spell // e.g. damage around area spell trigered by victim aura and damage enemies of aura caster Unit* m_originalCaster; // cached pointer for m_originalCaster, updated at Spell::UpdatePointers() - Spell** m_selfContainer; // pointer to our spell container (if applicable) - //Spell data SpellSchoolMask m_spellSchoolMask; // Spell school (can be overwrite for some spells (wand shoot for example) WeaponAttackType m_attackType; // For weapon based attack @@ -684,7 +702,7 @@ class TC_GAME_API Spell int32 chance; }; - bool CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByAura = NULL) const; + bool CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByAura = nullptr) const; void PrepareTriggersExecutedOnHit(); typedef std::vector HitTriggerSpellList; HitTriggerSpellList m_hitTriggerSpells; @@ -709,7 +727,7 @@ class TC_GAME_API Spell bool m_skipCheck; uint8 m_auraScaleMask; - PathGenerator m_preGeneratedPath; + std::unique_ptr m_preGeneratedPath; ByteBuffer * m_effectExecuteData[MAX_SPELL_EFFECTS]; @@ -772,16 +790,4 @@ namespace Trinity typedef void(Spell::*pEffect)(SpellEffIndex effIndex); -class TC_GAME_API SpellEvent : public BasicEvent -{ - public: - SpellEvent(Spell* spell); - virtual ~SpellEvent(); - - virtual bool Execute(uint64 e_time, uint32 p_time) override; - virtual void Abort(uint64 e_time) override; - virtual bool IsDeletable() const override; - protected: - Spell* m_Spell; -}; #endif diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index 3dee9ae956b..21ed4ceec23 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -16,45 +16,49 @@ * with this program. If not, see . */ +#include "Spell.h" +#include "AccountMgr.h" +#include "Battleground.h" +#include "CellImpl.h" #include "Common.h" +#include "Creature.h" +#include "CreatureAI.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "UpdateMask.h" -#include "World.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Player.h" -#include "SkillExtraItems.h" -#include "Unit.h" -#include "Spell.h" #include "DynamicObject.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" -#include "SharedDefines.h" -#include "Pet.h" +#include "Formulas.h" #include "GameObject.h" +#include "GameObjectAI.h" #include "GossipDef.h" -#include "Creature.h" -#include "Totem.h" -#include "CreatureAI.h" -#include "Battleground.h" -#include "OutdoorPvPMgr.h" -#include "Language.h" -#include "SocialMgr.h" -#include "Util.h" -#include "TemporarySummon.h" #include "GridNotifiers.h" -#include "CellImpl.h" -#include "Formulas.h" -#include "ScriptMgr.h" -#include "SpellHistory.h" -#include "GameObjectAI.h" -#include "AccountMgr.h" #include "InstanceScript.h" +#include "Item.h" +#include "Language.h" +#include "Log.h" +#include "LootMgr.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "OutdoorPvPMgr.h" #include "PathGenerator.h" +#include "Pet.h" +#include "Player.h" #include "ReputationMgr.h" +#include "ScriptMgr.h" +#include "SkillExtraItems.h" +#include "SharedDefines.h" +#include "SocialMgr.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" +#include "Totem.h" +#include "UpdateMask.h" +#include "Unit.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" pEffect SpellEffects[TOTAL_SPELL_EFFECTS]= { @@ -282,7 +286,7 @@ void Spell::EffectInstaKill(SpellEffIndex /*effIndex*/) data << uint32(m_spellInfo->Id); m_caster->SendMessageToSet(&data, true); - m_caster->DealDamage(unitTarget, unitTarget->GetHealth(), NULL, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + m_caster->DealDamage(unitTarget, unitTarget->GetHealth(), nullptr, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } void Spell::EffectEnvironmentalDMG(SpellEffIndex /*effIndex*/) @@ -428,7 +432,7 @@ void Spell::EffectSchoolDMG(SpellEffIndex effIndex) // Calculate damage of Immolate/Shadowflame tick int32 pdamage = (aura->GetAmount() + aura->GetBonusAmount()) * aura->GetDonePct(); if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, pdamage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, pdamage); pdamage = unitTarget->SpellDamageBonusTaken(m_caster, aura->GetSpellInfo(), pdamage, DOT); @@ -460,7 +464,7 @@ void Spell::EffectSchoolDMG(SpellEffIndex effIndex) if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 214, 0)) { int32 bp0 = aurEff->GetId() == 54037 ? 4 : 8; - m_caster->CastCustomSpell(m_caster, 54425, &bp0, NULL, NULL, true); + m_caster->CastCustomSpell(m_caster, 54425, &bp0, nullptr, nullptr, true); } } } @@ -880,7 +884,7 @@ void Spell::EffectTriggerSpell(SpellEffIndex effIndex) } // original caster guid only for GO cast - m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, NULL, NULL, m_originalCasterGUID); + m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, nullptr, nullptr, m_originalCasterGUID); } void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) @@ -928,7 +932,7 @@ void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) } // original caster guid only for GO cast - m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, NULL, NULL, m_originalCasterGUID); + m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, nullptr, nullptr, m_originalCasterGUID); } void Spell::EffectForceCast(SpellEffIndex effIndex) @@ -960,7 +964,7 @@ void Spell::EffectForceCast(SpellEffIndex effIndex) break; case 52463: // Hide In Mine Car case 52349: // Overtake - unitTarget->CastCustomSpell(unitTarget, spellInfo->Id, &damage, NULL, NULL, true, NULL, NULL, m_originalCasterGUID); + unitTarget->CastCustomSpell(unitTarget, spellInfo->Id, &damage, nullptr, nullptr, true, nullptr, nullptr, m_originalCasterGUID); return; } } @@ -968,7 +972,7 @@ void Spell::EffectForceCast(SpellEffIndex effIndex) switch (spellInfo->Id) { case 72298: // Malleable Goo Summon - unitTarget->CastSpell(unitTarget, spellInfo->Id, true, NULL, NULL, m_originalCasterGUID); + unitTarget->CastSpell(unitTarget, spellInfo->Id, true, nullptr, nullptr, m_originalCasterGUID); return; } @@ -1004,7 +1008,7 @@ void Spell::EffectTriggerRitualOfSummoning(SpellEffIndex effIndex) finish(); - m_caster->CastSpell((Unit*)NULL, spellInfo, false); + m_caster->CastSpell((Unit*)nullptr, spellInfo, false); } void Spell::EffectJump(SpellEffIndex effIndex) @@ -1265,7 +1269,7 @@ void Spell::EffectSendEvent(SpellEffIndex effIndex) && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; - WorldObject* target = NULL; + WorldObject* target = nullptr; // call events for object target if present if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) @@ -1379,7 +1383,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) { Unit::AuraEffectList const& RejorRegr = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); // find most short by duration - AuraEffect* targetAura = NULL; + AuraEffect* targetAura = nullptr; for (Unit::AuraEffectList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i) { if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID @@ -1398,7 +1402,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) int32 tickheal = (targetAura->GetAmount() + targetAura->GetBonusAmount()) * targetAura->GetDonePct(); if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(targetAura->GetId(), tickheal); + modOwner->ApplySpellMod(targetAura->GetId(), SPELLMOD_DOT, tickheal); unitTarget->SpellHealingBonusTaken(m_caster, targetAura->GetSpellInfo(), tickheal, DOT); @@ -1529,7 +1533,7 @@ void Spell::DoCreateItem(uint32 /*i*/, uint32 itemtype) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(newitemid); if (!pProto) { - player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -1606,7 +1610,7 @@ void Spell::DoCreateItem(uint32 /*i*/, uint32 itemtype) else { // if not created by another reason from full inventory or unique items amount limitation - player->SendEquipError(msg, NULL, NULL, newitemid); + player->SendEquipError(msg, nullptr, nullptr, newitemid); return; } } @@ -1614,12 +1618,12 @@ void Spell::DoCreateItem(uint32 /*i*/, uint32 itemtype) if (num_to_add) { // create the new item and store it - Item* pItem = player->StoreNewItem(dest, newitemid, true, Item::GenerateItemRandomPropertyId(newitemid)); + Item* pItem = player->StoreNewItem(dest, newitemid, true, GenerateItemRandomPropertyId(newitemid)); // was it successful? return error if not if (!pItem) { - player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -2054,9 +2058,9 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; @@ -2075,9 +2079,9 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; @@ -2099,9 +2103,9 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; @@ -2160,9 +2164,9 @@ void Spell::EffectSummonType(SpellEffIndex effIndex) int32 duration = m_spellInfo->GetDuration(); if (Player* modOwner = m_originalCaster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, duration); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); - TempSummon* summon = NULL; + TempSummon* summon = nullptr; // determine how many units should be summoned uint32 numSummons; @@ -2444,11 +2448,11 @@ void Spell::EffectDispel(SpellEffIndex effIndex) if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->GetCategory() == SPELLCATEGORY_DEVOUR_MAGIC) { int32 heal_amount = m_spellInfo->Effects[EFFECT_1].CalcValue(); - m_caster->CastCustomSpell(m_caster, 19658, &heal_amount, NULL, NULL, true); + m_caster->CastCustomSpell(m_caster, 19658, &heal_amount, nullptr, nullptr, true); // Glyph of Felhunter if (Unit* owner = m_caster->GetOwner()) if (owner->GetAura(56249)) - owner->CastCustomSpell(owner, 19658, &heal_amount, NULL, NULL, true); + owner->CastCustomSpell(owner, 19658, &heal_amount, nullptr, nullptr, true); } } @@ -2594,7 +2598,7 @@ void Spell::EffectAddHonor(SpellEffIndex /*effIndex*/) // not scale value for item based reward (/10 value expected) if (m_CastItem) { - unitTarget->ToPlayer()->RewardHonor(NULL, 1, damage/10); + unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage/10); TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %d honor points (item %u) for player: %u", m_spellInfo->Id, damage/10, m_CastItem->GetEntry(), unitTarget->ToPlayer()->GetGUID().GetCounter()); return; } @@ -2603,13 +2607,13 @@ void Spell::EffectAddHonor(SpellEffIndex /*effIndex*/) if (damage <= 50) { uint32 honor_reward = Trinity::Honor::hk_honor_at_level(unitTarget->getLevel(), float(damage)); - unitTarget->ToPlayer()->RewardHonor(NULL, 1, honor_reward); + unitTarget->ToPlayer()->RewardHonor(nullptr, 1, honor_reward); TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %u honor points (scale) to player: %u", m_spellInfo->Id, honor_reward, unitTarget->ToPlayer()->GetGUID().GetCounter()); } else { //maybe we have correct honor_gain in damage already - unitTarget->ToPlayer()->RewardHonor(NULL, 1, damage); + unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage); TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %u honor points (non scale) for player: %u", m_spellInfo->Id, damage, unitTarget->ToPlayer()->GetGUID().GetCounter()); } } @@ -2647,8 +2651,8 @@ void Spell::EffectEnchantItemPerm(SpellEffIndex effIndex) unitTarget = player; // and add a scroll DoCreateItem(effIndex, m_spellInfo->Effects[effIndex].ItemType); - itemTarget = NULL; - m_targets.SetItemTarget(NULL); + itemTarget = nullptr; + m_targets.SetItemTarget(nullptr); } else { @@ -2945,7 +2949,7 @@ void Spell::EffectSummonPet(SpellEffIndex effIndex) if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; - Player* owner = NULL; + Player* owner = nullptr; if (m_originalCaster) { owner = m_originalCaster->ToPlayer(); @@ -3021,7 +3025,7 @@ void Spell::EffectSummonPet(SpellEffIndex effIndex) pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); // generate new name for summon pet - std::string new_name=sObjectMgr->GeneratePetName(petentry); + std::string new_name = sObjectMgr->GeneratePetName(petentry); if (!new_name.empty()) pet->SetName(new_name); @@ -3200,7 +3204,7 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) // Skyshatter Harness item set bonus // Stormstrike if (AuraEffect* aurEff = m_caster->IsScriptOverriden(m_spellInfo, 5634)) - m_caster->CastSpell(m_caster, 38430, true, NULL, aurEff); + m_caster->CastSpell(m_caster, 38430, true, nullptr, aurEff); break; } case SPELLFAMILY_DRUID: @@ -3463,7 +3467,7 @@ void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) Map* map = target->GetMap(); - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(target->GetOrientation(), 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(target->GetOrientation(), 0.f, 0.f); if (!pGameObj->Create(map->GenerateLowGuid(), gameobject_id, map, m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), rot, 255, GO_STATE_READY)) { delete pGameObj; @@ -3550,7 +3554,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) uint32 spell_id = roll_chance_i(20) ? 8854 : 8855; - m_caster->CastSpell(m_caster, spell_id, true, NULL); + m_caster->CastSpell(m_caster, spell_id, true, nullptr); return; } // Brittle Armor - need remove one 24575 Brittle Armor aura @@ -3631,7 +3635,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) uint8 bag = 19; uint8 slot = 0; - Item* item = NULL; + Item* item = nullptr; while (bag) // 256 = 0 due to var type { @@ -3859,7 +3863,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) // proc a spellcast if (Aura* chargesAura = m_caster->GetAura(59907)) { - m_caster->CastSpell(unitTarget, spell_heal, true, NULL, NULL, m_caster->ToTempSummon()->GetSummonerGUID()); + m_caster->CastSpell(unitTarget, spell_heal, true, nullptr, nullptr, m_caster->ToTempSummon()->GetSummonerGUID()); if (chargesAura->ModCharges(-1)) m_caster->ToTempSummon()->UnSummon(); } @@ -3888,14 +3892,14 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) Creature* totem = unitTarget->GetMap()->GetCreature(unitTarget->m_SummonSlot[slot]); if (totem && totem->IsTotem()) { - m_caster->CastCustomSpell(totem, 55277, &basepoints0, NULL, NULL, true); + m_caster->CastCustomSpell(totem, 55277, &basepoints0, nullptr, nullptr, true); } } // Glyph of Stoneclaw Totem - if (AuraEffect* aur=unitTarget->GetAuraEffect(63298, 0)) + if (AuraEffect* aur = unitTarget->GetAuraEffect(63298, 0)) { basepoints0 *= aur->GetAmount(); - m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, NULL, NULL, true); + m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, nullptr, nullptr, true); } break; } @@ -4033,7 +4037,7 @@ void Spell::EffectDuel(SpellEffIndex effIndex) }; Map* map = m_caster->GetMap(); - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f); if (!pGameObj->Create(map->GenerateLowGuid(), gameobject_id, map, m_caster->GetPhaseMask(), pos, rot, 0, GO_STATE_READY)) { delete pGameObj; @@ -4056,8 +4060,8 @@ void Spell::EffectDuel(SpellEffIndex effIndex) WorldPacket data(SMSG_DUEL_REQUESTED, 8 + 8); data << uint64(pGameObj->GetGUID()); data << uint64(caster->GetGUID()); - caster->GetSession()->SendPacket(&data); - target->GetSession()->SendPacket(&data); + caster->SendDirectMessage(&data); + target->SendDirectMessage(&data); // create duel-info DuelInfo* duel = new DuelInfo; @@ -4334,7 +4338,7 @@ void Spell::EffectFeedPet(SpellEffIndex effIndex) player->DestroyItemCount(foodItem, count, true); /// @todo fix crash when a spell has two effects, both pointed at the same item target - m_caster->CastCustomSpell(pet, m_spellInfo->Effects[effIndex].TriggerSpell, &benefit, NULL, NULL, true); + m_caster->CastCustomSpell(pet, m_spellInfo->Effects[effIndex].TriggerSpell, &benefit, nullptr, nullptr, true); } void Spell::EffectDismissPet(SpellEffIndex effIndex) @@ -4382,7 +4386,7 @@ void Spell::EffectSummonObject(SpellEffIndex effIndex) m_caster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS); Map* map = m_caster->GetMap(); - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(m_caster->GetOrientation(), 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(m_caster->GetOrientation(), 0.f, 0.f); if (!go->Create(map->GenerateLowGuid(), go_id, map, m_caster->GetPhaseMask(), Position(x, y, z, m_caster->GetOrientation()), rot, 255, GO_STATE_READY)) { delete go; @@ -4633,14 +4637,14 @@ void Spell::EffectCharge(SpellEffIndex /*effIndex*/) float speed = G3D::fuzzyGt(m_spellInfo->Speed, 0.0f) ? m_spellInfo->Speed : SPEED_CHARGE; // Spell is not using explicit target - no generated path - if (m_preGeneratedPath.GetPathType() == PATHFIND_BLANK) + if (m_preGeneratedPath->GetPathType() == PATHFIND_BLANK) { //unitTarget->GetContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ); Position pos = unitTarget->GetFirstCollisionPosition(unitTarget->GetCombatReach(), unitTarget->GetRelativeAngle(m_caster)); m_caster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speed); } else - m_caster->GetMotionMaster()->MoveCharge(m_preGeneratedPath, speed); + m_caster->GetMotionMaster()->MoveCharge(*m_preGeneratedPath, speed); } if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) @@ -4924,7 +4928,7 @@ void Spell::EffectDestroyAllTotems(SpellEffIndex /*effIndex*/) } ApplyPct(mana, damage); if (mana) - m_caster->CastCustomSpell(m_caster, 39104, &mana, NULL, NULL, true); + m_caster->CastCustomSpell(m_caster, 39104, &mana, nullptr, nullptr, true); } void Spell::EffectDurabilityDamage(SpellEffIndex effIndex) @@ -5039,7 +5043,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) GameObject* pGameObj = new GameObject; Position pos = { fx, fy, fz, m_caster->GetOrientation() }; - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(m_caster->GetOrientation(), 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(m_caster->GetOrientation(), 0.f, 0.f); if (!pGameObj->Create(cMap->GenerateLowGuid(), name_id, cMap, m_caster->GetPhaseMask(), pos, rot, 255, GO_STATE_READY)) { delete pGameObj; @@ -5569,7 +5573,7 @@ void Spell::SummonGuardian(uint32 i, uint32 entry, SummonPropertiesEntry const* int32 duration = m_spellInfo->GetDuration(); if (Player* modOwner = m_originalCaster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, duration); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); //TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; Map* map = caster->GetMap(); @@ -5643,7 +5647,7 @@ void Spell::EffectPlayMusic(SpellEffIndex effIndex) WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(soundid); - unitTarget->ToPlayer()->GetSession()->SendPacket(&data); + unitTarget->ToPlayer()->SendDirectMessage(&data); } void Spell::EffectSpecCount(SpellEffIndex /*effIndex*/) @@ -5773,7 +5777,7 @@ void Spell::EffectRechargeManaGem(SpellEffIndex /*effIndex*/) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id); if (!pProto) { - player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -5809,10 +5813,8 @@ void Spell::EffectBind(SpellEffIndex effIndex) player->SetHomebind(homeLoc, areaId); // binding - WorldPacket data(SMSG_BINDPOINTUPDATE, 4 + 4 + 4 + 4 + 4); - data << float(homeLoc.GetPositionX()); - data << float(homeLoc.GetPositionY()); - data << float(homeLoc.GetPositionZ()); + WorldPacket data(SMSG_BINDPOINTUPDATE, 4 * 3 + 4 + 4); + data << TaggedPosition(homeLoc); data << uint32(homeLoc.GetMapId()); data << uint32(areaId); player->SendDirectMessage(&data); diff --git a/src/server/game/Spells/SpellHistory.cpp b/src/server/game/Spells/SpellHistory.cpp index 599314e2ec4..5401687e3d5 100644 --- a/src/server/game/Spells/SpellHistory.cpp +++ b/src/server/game/Spells/SpellHistory.cpp @@ -15,13 +15,17 @@ * with this program. If not, see . */ -#include "WorldPacket.h" #include "SpellHistory.h" +#include "DatabaseEnv.h" +#include "Item.h" +#include "ObjectMgr.h" +#include "Opcodes.h" #include "Pet.h" #include "Player.h" -#include "SpellInfo.h" #include "Spell.h" -#include "Opcodes.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "WorldPacket.h" SpellHistory::Clock::duration const SpellHistory::InfinityCooldownDelay = std::chrono::duration_cast(std::chrono::seconds(MONTH)); SpellHistory::Clock::duration const SpellHistory::InfinityCooldownDelayCheck = std::chrono::duration_cast(std::chrono::seconds(MONTH / 2)); @@ -308,10 +312,10 @@ void SpellHistory::StartCooldown(SpellInfo const* spellInfo, uint32 itemId, Spel if (Player* modOwner = _owner->GetSpellModOwner()) { if (cooldown >= 0) - modOwner->ApplySpellMod(spellInfo->Id, cooldown, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown, spell); if (categoryCooldown >= 0 && !spellInfo->HasAttribute(SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS)) - modOwner->ApplySpellMod(spellInfo->Id, categoryCooldown, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, categoryCooldown, spell); } if (int32 cooldownMod = _owner->GetTotalAuraModifier(SPELL_AURA_MOD_COOLDOWN)) diff --git a/src/server/game/Spells/SpellHistory.h b/src/server/game/Spells/SpellHistory.h index ed1ba883c5b..f45982ced93 100644 --- a/src/server/game/Spells/SpellHistory.h +++ b/src/server/game/Spells/SpellHistory.h @@ -19,18 +19,28 @@ #define SpellHistory_h__ #include "SharedDefines.h" -#include "QueryResult.h" -#include "Transaction.h" +#include "DatabaseEnvFwd.h" #include "GameTime.h" #include +#include +#include class Item; class Player; class Spell; class SpellInfo; class Unit; +class WorldPacket; struct SpellCategoryEntry; +/// Spell cooldown flags sent in SMSG_SPELL_COOLDOWN +enum SpellCooldownFlags +{ + SPELL_COOLDOWN_FLAG_NONE = 0x0, + SPELL_COOLDOWN_FLAG_INCLUDE_GCD = 0x1, ///< Starts GCD in addition to normal cooldown specified in the packet + SPELL_COOLDOWN_FLAG_INCLUDE_EVENT_COOLDOWNS = 0x2 ///< Starts GCD for spells that should start their cooldown on events, requires SPELL_COOLDOWN_FLAG_INCLUDE_GCD set +}; + class TC_GAME_API SpellHistory { public: diff --git a/src/server/game/Spells/SpellInfo.cpp b/src/server/game/Spells/SpellInfo.cpp index 8f4f534e076..2a0b972e631 100644 --- a/src/server/game/Spells/SpellInfo.cpp +++ b/src/server/game/Spells/SpellInfo.cpp @@ -15,17 +15,21 @@ * with this program. If not, see . */ -#include "SpellAuraDefines.h" -#include "SpellAuras.h" #include "SpellInfo.h" -#include "SpellMgr.h" -#include "Spell.h" +#include "Battleground.h" +#include "Corpse.h" +#include "Creature.h" #include "DBCStores.h" -#include "ConditionMgr.h" +#include "Item.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "Battleground.h" +#include "Random.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" #include "Vehicle.h" -#include "Pet.h" uint32 GetTargetFlagMask(SpellTargetObjectTypes objType) { @@ -341,12 +345,12 @@ SpellEffectInfo::SpellEffectInfo(SpellEntry const* spellEntry, SpellInfo const* Mechanic = Mechanics(spellEntry->EffectMechanic[effIndex]); TargetA = SpellImplicitTargetInfo(spellEntry->EffectImplicitTargetA[effIndex]); TargetB = SpellImplicitTargetInfo(spellEntry->EffectImplicitTargetB[effIndex]); - RadiusEntry = spellEntry->EffectRadiusIndex[effIndex] ? sSpellRadiusStore.LookupEntry(spellEntry->EffectRadiusIndex[effIndex]) : NULL; + RadiusEntry = spellEntry->EffectRadiusIndex[effIndex] ? sSpellRadiusStore.LookupEntry(spellEntry->EffectRadiusIndex[effIndex]) : nullptr; ChainTarget = spellEntry->EffectChainTarget[effIndex]; ItemType = spellEntry->EffectItemType[effIndex]; TriggerSpell = spellEntry->EffectTriggerSpell[effIndex]; SpellClassMask = spellEntry->EffectSpellClassMask[effIndex]; - ImplicitTargetConditions = NULL; + ImplicitTargetConditions = nullptr; } bool SpellEffectInfo::IsEffect() const @@ -519,22 +523,24 @@ int32 SpellEffectInfo::CalcBaseValue(int32 value) const float SpellEffectInfo::CalcValueMultiplier(Unit* caster, Spell* spell) const { float multiplier = ValueMultiplier; - if (Player* modOwner = (caster ? caster->GetSpellModOwner() : NULL)) - modOwner->ApplySpellMod(_spellInfo->Id, multiplier, spell); + if (Player* modOwner = (caster ? caster->GetSpellModOwner() : nullptr)) + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_VALUE_MULTIPLIER, multiplier, spell); + return multiplier; } float SpellEffectInfo::CalcDamageMultiplier(Unit* caster, Spell* spell) const { float multiplierPercent = DamageMultiplier * 100.0f; - if (Player* modOwner = (caster ? caster->GetSpellModOwner() : NULL)) - modOwner->ApplySpellMod(_spellInfo->Id, multiplierPercent, spell); + if (Player* modOwner = (caster ? caster->GetSpellModOwner() : nullptr)) + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_DAMAGE_MULTIPLIER, multiplierPercent, spell); + return multiplierPercent / 100.0f; } bool SpellEffectInfo::HasRadius() const { - return RadiusEntry != NULL; + return RadiusEntry != nullptr; } float SpellEffectInfo::CalcRadius(Unit* caster, Spell* spell) const @@ -548,7 +554,7 @@ float SpellEffectInfo::CalcRadius(Unit* caster, Spell* spell) const radius += RadiusEntry->RadiusPerLevel * caster->getLevel(); radius = std::min(radius, RadiusEntry->RadiusMax); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(_spellInfo->Id, radius, spell); + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_RADIUS, radius, spell); } return radius; @@ -766,7 +772,7 @@ SpellEffectInfo::StaticData SpellEffectInfo::_data[TOTAL_SPELL_EFFECTS] = SpellInfo::SpellInfo(SpellEntry const* spellEntry) { Id = spellEntry->Id; - CategoryEntry = spellEntry->Category ? sSpellCategoryStore.LookupEntry(spellEntry->Category) : NULL; + CategoryEntry = spellEntry->Category ? sSpellCategoryStore.LookupEntry(spellEntry->Category) : nullptr; Dispel = spellEntry->Dispel; Mechanic = spellEntry->Mechanic; Attributes = spellEntry->Attributes; @@ -792,7 +798,7 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry) TargetAuraSpell = spellEntry->targetAuraSpell; ExcludeCasterAuraSpell = spellEntry->excludeCasterAuraSpell; ExcludeTargetAuraSpell = spellEntry->excludeTargetAuraSpell; - CastTimeEntry = spellEntry->CastingTimeIndex ? sSpellCastTimesStore.LookupEntry(spellEntry->CastingTimeIndex) : NULL; + CastTimeEntry = spellEntry->CastingTimeIndex ? sSpellCastTimesStore.LookupEntry(spellEntry->CastingTimeIndex) : nullptr; RecoveryTime = spellEntry->RecoveryTime; CategoryRecoveryTime = spellEntry->CategoryRecoveryTime; StartRecoveryCategory = spellEntry->StartRecoveryCategory; @@ -806,7 +812,7 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry) MaxLevel = spellEntry->maxLevel; BaseLevel = spellEntry->baseLevel; SpellLevel = spellEntry->spellLevel; - DurationEntry = spellEntry->DurationIndex ? sSpellDurationStore.LookupEntry(spellEntry->DurationIndex) : NULL; + DurationEntry = spellEntry->DurationIndex ? sSpellDurationStore.LookupEntry(spellEntry->DurationIndex) : nullptr; PowerType = spellEntry->powerType; ManaCost = spellEntry->manaCost; ManaCostPerlevel = spellEntry->manaCostPerlevel; @@ -814,7 +820,7 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry) ManaPerSecondPerLevel = spellEntry->manaPerSecondPerLevel; ManaCostPercentage = spellEntry->ManaCostPercentage; RuneCostID = spellEntry->runeCostID; - RangeEntry = spellEntry->rangeIndex ? sSpellRangeStore.LookupEntry(spellEntry->rangeIndex) : NULL; + RangeEntry = spellEntry->rangeIndex ? sSpellRangeStore.LookupEntry(spellEntry->rangeIndex) : nullptr; Speed = spellEntry->speed; StackAmount = spellEntry->StackAmount; for (uint8 i = 0; i < 2; ++i) @@ -854,7 +860,7 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry) for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) Effects[i] = SpellEffectInfo(spellEntry, this, i); - ChainEntry = NULL; + ChainEntry = nullptr; ExplicitTargetMask = 0; _spellSpecific = SPELL_SPECIFIC_NORMAL; @@ -1458,7 +1464,7 @@ SpellCastResult SpellInfo::CheckShapeshift(uint32 form) const return SPELL_CAST_OK; bool actAsShifted = false; - SpellShapeshiftEntry const* shapeInfo = NULL; + SpellShapeshiftEntry const* shapeInfo = nullptr; if (form > 0) { shapeInfo = sSpellShapeshiftStore.LookupEntry(form); @@ -3064,7 +3070,8 @@ float SpellInfo::GetMaxRange(bool positive, Unit* caster, Spell* spell) const range = RangeEntry->maxRangeHostile; if (caster) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(Id, range, spell); + modOwner->ApplySpellMod(Id, SPELLMOD_RANGE, range, spell); + return range; } @@ -3082,7 +3089,7 @@ int32 SpellInfo::GetMaxDuration() const return (DurationEntry->Duration[2] == -1) ? -1 : abs(DurationEntry->Duration[2]); } -uint32 SpellInfo::CalcCastTime(Spell* spell /*= NULL*/) const +uint32 SpellInfo::CalcCastTime(Spell* spell /*= nullptr*/) const { // not all spells have cast time index and this is all is pasiive abilities if (!CastTimeEntry) @@ -3204,7 +3211,7 @@ int32 SpellInfo::CalcPowerCost(Unit const* caster, SpellSchoolMask schoolMask, S // Apply cost mod by spell if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(Id, powerCost, spell); + modOwner->ApplySpellMod(Id, SPELLMOD_COST, powerCost, spell); if (!caster->IsControlledByPlayer()) { @@ -3226,7 +3233,7 @@ int32 SpellInfo::CalcPowerCost(Unit const* caster, SpellSchoolMask schoolMask, S bool SpellInfo::IsRanked() const { - return ChainEntry != NULL; + return ChainEntry != nullptr; } uint8 SpellInfo::GetRank() const @@ -3245,19 +3252,19 @@ SpellInfo const* SpellInfo::GetFirstRankSpell() const SpellInfo const* SpellInfo::GetLastRankSpell() const { if (!ChainEntry) - return NULL; + return nullptr; return ChainEntry->last; } SpellInfo const* SpellInfo::GetNextRankSpell() const { if (!ChainEntry) - return NULL; + return nullptr; return ChainEntry->next; } SpellInfo const* SpellInfo::GetPrevRankSpell() const { if (!ChainEntry) - return NULL; + return nullptr; return ChainEntry->prev; } @@ -3288,7 +3295,7 @@ SpellInfo const* SpellInfo::GetAuraRankForLevel(uint8 level) const if (!needRankSelection) return this; - for (SpellInfo const* nextSpellInfo = this; nextSpellInfo != NULL; nextSpellInfo = nextSpellInfo->GetPrevRankSpell()) + for (SpellInfo const* nextSpellInfo = this; nextSpellInfo != nullptr; nextSpellInfo = nextSpellInfo->GetPrevRankSpell()) { // if found appropriate level if (uint32(level + 10) >= nextSpellInfo->SpellLevel) @@ -3298,7 +3305,7 @@ SpellInfo const* SpellInfo::GetAuraRankForLevel(uint8 level) const } // not found - return NULL; + return nullptr; } bool SpellInfo::IsRankOf(SpellInfo const* spellInfo) const @@ -3670,7 +3677,7 @@ void SpellInfo::_UnloadImplicitTargetConditionLists() for (uint8 j = i; j < MAX_SPELL_EFFECTS; ++j) { if (Effects[j].ImplicitTargetConditions == cur) - Effects[j].ImplicitTargetConditions = NULL; + Effects[j].ImplicitTargetConditions = nullptr; } delete cur; } diff --git a/src/server/game/Spells/SpellInfo.h b/src/server/game/Spells/SpellInfo.h index 483605a1212..8f2f97722df 100644 --- a/src/server/game/Spells/SpellInfo.h +++ b/src/server/game/Spells/SpellInfo.h @@ -42,7 +42,7 @@ struct SpellEntry; struct SpellCastTimesEntry; struct Condition; -enum SpellCastTargetFlags +enum SpellCastTargetFlags : uint32 { TARGET_FLAG_NONE = 0x00000000, TARGET_FLAG_UNUSED_1 = 0x00000001, // not used @@ -95,7 +95,7 @@ enum SpellTargetReferenceTypes TARGET_REFERENCE_TYPE_DEST }; -enum SpellTargetObjectTypes +enum SpellTargetObjectTypes : uint8 { TARGET_OBJECT_TYPE_NONE = 0, TARGET_OBJECT_TYPE_SRC, @@ -111,7 +111,7 @@ enum SpellTargetObjectTypes TARGET_OBJECT_TYPE_CORPSE_ALLY }; -enum SpellTargetCheckTypes +enum SpellTargetCheckTypes : uint8 { TARGET_CHECK_DEFAULT, TARGET_CHECK_ENTRY, @@ -259,10 +259,10 @@ public: flag96 SpellClassMask; std::vector* ImplicitTargetConditions; - SpellEffectInfo() : _spellInfo(NULL), _effIndex(0), Effect(0), ApplyAuraName(0), Amplitude(0), DieSides(0), + SpellEffectInfo() : _spellInfo(nullptr), _effIndex(0), Effect(0), ApplyAuraName(0), Amplitude(0), DieSides(0), RealPointsPerLevel(0), BasePoints(0), PointsPerComboPoint(0), ValueMultiplier(0), DamageMultiplier(0), - BonusMultiplier(0), MiscValue(0), MiscValueB(0), Mechanic(MECHANIC_NONE), RadiusEntry(NULL), ChainTarget(0), - ItemType(0), TriggerSpell(0), ImplicitTargetConditions(NULL) {} + BonusMultiplier(0), MiscValue(0), MiscValueB(0), Mechanic(MECHANIC_NONE), RadiusEntry(nullptr), ChainTarget(0), + ItemType(0), TriggerSpell(0), ImplicitTargetConditions(nullptr) {} SpellEffectInfo(SpellEntry const* spellEntry, SpellInfo const* spellInfo, uint8 effIndex); bool IsEffect() const; @@ -275,13 +275,13 @@ public: bool IsFarDestTargetEffect() const; bool IsUnitOwnedAuraEffect() const; - int32 CalcValue(Unit const* caster = NULL, int32 const* basePoints = NULL, Unit const* target = NULL) const; + int32 CalcValue(Unit const* caster = nullptr, int32 const* basePoints = nullptr, Unit const* target = nullptr) const; int32 CalcBaseValue(int32 value) const; - float CalcValueMultiplier(Unit* caster, Spell* spell = NULL) const; - float CalcDamageMultiplier(Unit* caster, Spell* spell = NULL) const; + float CalcValueMultiplier(Unit* caster, Spell* spell = nullptr) const; + float CalcDamageMultiplier(Unit* caster, Spell* spell = nullptr) const; bool HasRadius() const; - float CalcRadius(Unit* caster = NULL, Spell* = NULL) const; + float CalcRadius(Unit* caster = nullptr, Spell* = nullptr) const; uint32 GetProvidedTargetMask() const; uint32 GetMissingTargetMask(bool srcSet = false, bool destSet = false, uint32 mask = 0) const; @@ -476,7 +476,7 @@ class TC_GAME_API SpellInfo SpellCastResult CheckShapeshift(uint32 form) const; SpellCastResult CheckLocation(uint32 map_id, uint32 zone_id, uint32 area_id, Player const* player = nullptr, bool strict = true) const; SpellCastResult CheckTarget(Unit const* caster, WorldObject const* target, bool implicit = true) const; - SpellCastResult CheckExplicitTarget(Unit const* caster, WorldObject const* target, Item const* itemTarget = NULL) const; + SpellCastResult CheckExplicitTarget(Unit const* caster, WorldObject const* target, Item const* itemTarget = nullptr) const; SpellCastResult CheckVehicle(Unit const* caster) const; bool CheckTargetCreatureType(Unit const* target) const; diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index a14eddcc383..e0800b2782d 100644 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -17,17 +17,21 @@ */ #include "SpellMgr.h" -#include "SpellInfo.h" -#include "Spell.h" -#include "ObjectMgr.h" -#include "SpellAuraDefines.h" -#include "SharedDefines.h" -#include "DBCStores.h" -#include "Chat.h" -#include "BattlegroundMgr.h" -#include "BattlefieldWG.h" #include "BattlefieldMgr.h" +#include "BattlefieldWG.h" +#include "BattlegroundMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "Player.h" +#include "SharedDefines.h" +#include "Spell.h" +#include "SpellAuraDefines.h" +#include "SpellInfo.h" bool IsPrimaryProfessionSkill(uint32 skill) { @@ -215,7 +219,7 @@ uint32 SpellMgr::GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) con SpellInfo const* SpellMgr::GetSpellForDifficultyFromSpell(SpellInfo const* spell, Unit const* caster) const { if (!spell) - return NULL; + return nullptr; uint32 newSpellId = GetSpellIdForDifficulty(spell->Id, caster); SpellInfo const* newSpell = GetSpellInfo(newSpellId); @@ -233,7 +237,7 @@ SpellChainNode const* SpellMgr::GetSpellChainNode(uint32 spell_id) const { SpellChainMap::const_iterator itr = mSpellChains.find(spell_id); if (itr == mSpellChains.end()) - return NULL; + return nullptr; return &itr->second; } @@ -319,7 +323,7 @@ SpellLearnSkillNode const* SpellMgr::GetSpellLearnSkill(uint32 spell_id) const if (itr != mSpellLearnSkills.end()) return &itr->second; else - return NULL; + return nullptr; } SpellLearnSpellMapBounds SpellMgr::GetSpellLearnSpellMapBounds(uint32 spell_id) const @@ -346,7 +350,7 @@ SpellTargetPosition const* SpellMgr::GetSpellTargetPosition(uint32 spell_id, Spe SpellTargetPositionMap::const_iterator itr = mSpellTargetPositions.find(std::make_pair(spell_id, effIndex)); if (itr != mSpellTargetPositions.end()) return &itr->second; - return NULL; + return nullptr; } SpellSpellGroupMapBounds SpellMgr::GetSpellSpellGroupMapBounds(uint32 spell_id) const @@ -493,7 +497,7 @@ SpellProcEntry const* SpellMgr::GetSpellProcEntry(uint32 spellId) const SpellProcMap::const_iterator itr = mSpellProcMap.find(spellId); if (itr != mSpellProcMap.end()) return &itr->second; - return NULL; + return nullptr; } bool SpellMgr::CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) @@ -591,7 +595,7 @@ SpellBonusEntry const* SpellMgr::GetSpellBonusData(uint32 spellId) const if (itr2 != mSpellBonusMap.end()) return &itr2->second; } - return NULL; + return nullptr; } SpellThreatEntry const* SpellMgr::GetSpellThreatEntry(uint32 spellID) const @@ -606,7 +610,7 @@ SpellThreatEntry const* SpellMgr::GetSpellThreatEntry(uint32 spellID) const if (itr != mSpellThreatMap.end()) return &itr->second; } - return NULL; + return nullptr; } SkillLineAbilityMapBounds SpellMgr::GetSkillLineAbilityMapBounds(uint32 spell_id) const @@ -620,7 +624,7 @@ PetAura const* SpellMgr::GetPetAura(uint32 spell_id, uint8 eff) const if (itr != mSpellPetAuraMap.end()) return &itr->second; else - return NULL; + return nullptr; } SpellEnchantProcEntry const* SpellMgr::GetSpellEnchantProcEvent(uint32 enchId) const @@ -628,7 +632,7 @@ SpellEnchantProcEntry const* SpellMgr::GetSpellEnchantProcEvent(uint32 enchId) c SpellEnchantProcEventMap::const_iterator itr = mSpellEnchantProcEventMap.find(enchId); if (itr != mSpellEnchantProcEventMap.end()) return &itr->second; - return NULL; + return nullptr; } bool SpellMgr::IsArenaAllowedEnchancment(uint32 ench_id) const @@ -639,7 +643,7 @@ bool SpellMgr::IsArenaAllowedEnchancment(uint32 ench_id) const const std::vector* SpellMgr::GetSpellLinked(int32 spell_id) const { SpellLinkedMap::const_iterator itr = mSpellLinkedMap.find(spell_id); - return itr != mSpellLinkedMap.end() ? &(itr->second) : NULL; + return itr != mSpellLinkedMap.end() ? &(itr->second) : nullptr; } PetLevelupSpellSet const* SpellMgr::GetPetLevelupSpellList(uint32 petFamily) const @@ -648,7 +652,7 @@ PetLevelupSpellSet const* SpellMgr::GetPetLevelupSpellList(uint32 petFamily) con if (itr != mPetLevelupSpellMap.end()) return &itr->second; else - return NULL; + return nullptr; } PetDefaultSpellsEntry const* SpellMgr::GetPetDefaultSpellsEntry(int32 id) const @@ -656,7 +660,7 @@ PetDefaultSpellsEntry const* SpellMgr::GetPetDefaultSpellsEntry(int32 id) const PetDefaultSpellsMap::const_iterator itr = mPetDefaultSpellsMap.find(id); if (itr != mPetDefaultSpellsMap.end()) return &itr->second; - return NULL; + return nullptr; } SpellAreaMapBounds SpellMgr::GetSpellAreaMapBounds(uint32 spell_id) const @@ -794,7 +798,7 @@ bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 void SpellMgr::UnloadSpellInfoChains() { for (SpellChainMap::iterator itr = mSpellChains.begin(); itr != mSpellChains.end(); ++itr) - mSpellInfoMap[itr->first]->ChainEntry = NULL; + mSpellInfoMap[itr->first]->ChainEntry = nullptr; mSpellChains.clear(); } @@ -810,7 +814,7 @@ void SpellMgr::LoadSpellTalentRanks() if (!talentInfo) continue; - SpellInfo const* lastSpell = NULL; + SpellInfo const* lastSpell = nullptr; for (uint8 rank = MAX_TALENT_RANK - 1; rank > 0; --rank) { if (talentInfo->RankID[rank]) @@ -830,7 +834,7 @@ void SpellMgr::LoadSpellTalentRanks() continue; } - SpellInfo const* prevSpell = NULL; + SpellInfo const* prevSpell = nullptr; for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank) { uint32 spellId = talentInfo->RankID[rank]; @@ -850,7 +854,7 @@ void SpellMgr::LoadSpellTalentRanks() node.rank = rank + 1; node.prev = prevSpell; - node.next = node.rank < MAX_TALENT_RANK ? GetSpellInfo(talentInfo->RankID[node.rank]) : NULL; + node.next = node.rank < MAX_TALENT_RANK ? GetSpellInfo(talentInfo->RankID[node.rank]) : nullptr; mSpellChains[spellId] = node; mSpellInfoMap[spellId]->ChainEntry = &mSpellChains[spellId]; @@ -963,7 +967,7 @@ void SpellMgr::LoadSpellRanks() if (itr == rankChain.end()) { - mSpellChains[addedSpell].next = NULL; + mSpellChains[addedSpell].next = nullptr; break; } else @@ -2224,7 +2228,7 @@ bool LoadPetDefaultSpells_helper(CreatureTemplate const* cInfo, PetDefaultSpells return false; // remove duplicates with levelupSpells if any - if (PetLevelupSpellSet const* levelupSpells = cInfo->family ? sSpellMgr->GetPetLevelupSpellList(cInfo->family) : NULL) + if (PetLevelupSpellSet const* levelupSpells = cInfo->family ? sSpellMgr->GetPetLevelupSpellList(cInfo->family) : nullptr) { for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) { @@ -2533,11 +2537,10 @@ void SpellMgr::LoadSpellInfoStore() uint32 oldMSTime = getMSTime(); UnloadSpellInfoStore(); - mSpellInfoMap.resize(sSpellStore.GetNumRows(), NULL); + mSpellInfoMap.resize(sSpellStore.GetNumRows(), nullptr); - for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i) - if (SpellEntry const* spellEntry = sSpellStore.LookupEntry(i)) - mSpellInfoMap[i] = new SpellInfo(spellEntry); + for (SpellEntry const* spellEntry : sSpellStore) + mSpellInfoMap[spellEntry->Id] = new SpellInfo(spellEntry); TC_LOG_INFO("server.loading", ">> Loaded SpellInfo store in %u ms", GetMSTimeDiffToNow(oldMSTime)); } @@ -2561,7 +2564,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() { uint32 oldMSTime = getMSTime(); uint32 oldMSTime2 = oldMSTime; - SpellInfo* spellInfo = NULL; + SpellInfo* spellInfo = nullptr; QueryResult result = WorldDatabase.Query("SELECT entry, attributes FROM spell_custom_attr"); diff --git a/src/server/game/Spells/SpellMgr.h b/src/server/game/Spells/SpellMgr.h index 1696a353ee0..c9fb69a8eb2 100644 --- a/src/server/game/Spells/SpellMgr.h +++ b/src/server/game/Spells/SpellMgr.h @@ -22,7 +22,7 @@ // For static or at-server-startup loaded spell data #include "Define.h" -#include "DBCStructure.h" +#include "Duration.h" #include "SharedDefines.h" #include "Util.h" @@ -30,6 +30,7 @@ #include #include #include +#include class SpellInfo; class Player; @@ -586,7 +587,7 @@ class TC_GAME_API SpellMgr static SpellMgr* instance(); // Spell correctness for client using - static bool IsSpellValid(SpellInfo const* spellInfo, Player* player = NULL, bool msg = true); + static bool IsSpellValid(SpellInfo const* spellInfo, Player* player = nullptr, bool msg = true); // Spell difficulty uint32 GetSpellDifficultyId(uint32 spellId) const; @@ -662,7 +663,7 @@ class TC_GAME_API SpellMgr SpellAreaForQuestAreaMapBounds GetSpellAreaForQuestAreaMapBounds(uint32 area_id, uint32 quest_id) const; // SpellInfo object management - SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : NULL; } + SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } // Use this only with 100% valid spellIds SpellInfo const* AssertSpellInfo(uint32 spellId) const { @@ -674,7 +675,7 @@ class TC_GAME_API SpellMgr uint32 GetSpellInfoStoreSize() const { return mSpellInfoMap.size(); } private: - SpellInfo* _GetSpellInfo(uint32 spellId) { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : NULL; } + SpellInfo* _GetSpellInfo(uint32 spellId) { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } // Modifiers public: diff --git a/src/server/game/Spells/SpellScript.cpp b/src/server/game/Spells/SpellScript.cpp index 32aad8a11ed..3750cae08ef 100644 --- a/src/server/game/Spells/SpellScript.cpp +++ b/src/server/game/Spells/SpellScript.cpp @@ -15,12 +15,14 @@ * with this program. If not, see . */ +#include "SpellScript.h" +#include "Log.h" #include "Spell.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "SpellMgr.h" -#include "SpellScript.h" #include "SpellMgr.h" +#include #include bool _SpellScript::_Validate(SpellInfo const* entry) @@ -33,18 +35,20 @@ bool _SpellScript::_Validate(SpellInfo const* entry) return true; } -bool _SpellScript::ValidateSpellInfo(std::vector const& spellIds) +bool _SpellScript::_ValidateSpellInfo(uint32 const* begin, uint32 const* end) { - for (uint32 spellId : spellIds) + bool allValid = true; + while (begin != end) { - if (!sSpellMgr->GetSpellInfo(spellId)) + if (!sSpellMgr->GetSpellInfo(*begin)) { - TC_LOG_ERROR("scripts.spells", "_SpellScript::ValidateSpellInfo: Spell %u does not exist.", spellId); - return false; + TC_LOG_ERROR("scripts.spells", "_SpellScript::ValidateSpellInfo: Spell %u does not exist.", *begin); + allValid = false; } - } - return true; + ++begin; + } + return allValid; } void _SpellScript::_Register() @@ -422,7 +426,7 @@ WorldLocation const* SpellScript::GetExplTargetDest() { if (m_spell->m_targets.HasDst()) return m_spell->m_targets.GetDstPos(); - return NULL; + return nullptr; } void SpellScript::SetExplTargetDest(WorldLocation& loc) @@ -455,7 +459,7 @@ Unit* SpellScript::GetHitUnit() if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitUnit was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->unitTarget; } @@ -465,12 +469,12 @@ Creature* SpellScript::GetHitCreature() if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitCreature was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } if (m_spell->unitTarget) return m_spell->unitTarget->ToCreature(); else - return NULL; + return nullptr; } Player* SpellScript::GetHitPlayer() @@ -478,12 +482,12 @@ Player* SpellScript::GetHitPlayer() if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitPlayer was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } if (m_spell->unitTarget) return m_spell->unitTarget->ToPlayer(); else - return NULL; + return nullptr; } Item* SpellScript::GetHitItem() @@ -491,7 +495,7 @@ Item* SpellScript::GetHitItem() if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitItem was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->itemTarget; } @@ -501,7 +505,7 @@ GameObject* SpellScript::GetHitGObj() if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitGObj was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->gameObjTarget; } @@ -511,7 +515,7 @@ WorldLocation* SpellScript::GetHitDest() if (!IsInEffectHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitDest was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->destTarget; } @@ -561,12 +565,12 @@ Aura* SpellScript::GetHitAura() if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitAura was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } if (!m_spell->m_spellAura) - return NULL; + return nullptr; if (m_spell->m_spellAura->IsRemoved()) - return NULL; + return nullptr; return m_spell->m_spellAura; } @@ -941,7 +945,7 @@ void AuraScript::EffectProcHandler::Call(AuraScript* auraScript, AuraEffect cons bool AuraScript::_Load(Aura* aura) { m_aura = aura; - _PrepareScriptCall((AuraScriptHookType)SPELL_SCRIPT_STATE_LOADING, NULL); + _PrepareScriptCall((AuraScriptHookType)SPELL_SCRIPT_STATE_LOADING, nullptr); bool load = Load(); _FinishScriptCall(); return load; @@ -1189,7 +1193,7 @@ Unit* AuraScript::GetTarget() const TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u` AuraScript::GetTarget called in a hook in which the call won't have effect!", m_scriptName->c_str(), m_scriptSpellId); } - return NULL; + return nullptr; } AuraApplication const* AuraScript::GetTargetApplication() const diff --git a/src/server/game/Spells/SpellScript.h b/src/server/game/Spells/SpellScript.h index 330727cdc1e..03f06961a4b 100644 --- a/src/server/game/Spells/SpellScript.h +++ b/src/server/game/Spells/SpellScript.h @@ -18,27 +18,34 @@ #ifndef __SPELL_SCRIPT_H #define __SPELL_SCRIPT_H -#include "Util.h" +#include "ObjectGuid.h" #include "SharedDefines.h" #include "SpellAuraDefines.h" -#include "Spell.h" -#include "ScriptReloadMgr.h" +#include "Util.h" +#include #include -class Unit; -class SpellInfo; -class SpellScript; -class Spell; class Aura; +class AuraApplication; class AuraEffect; -struct SpellModifier; class Creature; -class GameObject; +class DamageInfo; +class DispelInfo; class DynamicObject; -class Player; +class GameObject; class Item; +class ModuleReference; +class Player; +class ProcEventInfo; +class Spell; +class SpellInfo; +class SpellScript; +class Unit; class WorldLocation; class WorldObject; +struct SpellDestination; +struct SpellModifier; +struct SpellValue; #define SPELL_EFFECT_ANY (uint16)-1 #define SPELL_AURA_ANY (uint16)-1 @@ -61,7 +68,7 @@ class TC_GAME_API _SpellScript virtual bool _Validate(SpellInfo const* entry); public: - _SpellScript() : m_currentScriptState(SPELL_SCRIPT_STATE_NONE), m_scriptName(NULL), m_scriptSpellId(0) {} + _SpellScript() : m_currentScriptState(SPELL_SCRIPT_STATE_NONE), m_scriptName(nullptr), m_scriptSpellId(0) {} virtual ~_SpellScript() { } void _Register(); void _Unload(); @@ -133,7 +140,19 @@ class TC_GAME_API _SpellScript // use for: deallocating memory allocated by script virtual void Unload() { } // Helpers - static bool ValidateSpellInfo(std::vector const& spellIds); + static bool ValidateSpellInfo(std::initializer_list spellIds) + { + return _ValidateSpellInfo(spellIds.begin(), spellIds.end()); + } + + template + static bool ValidateSpellInfo(T const& spellIds) + { + return _ValidateSpellInfo(std::begin(spellIds), std::end(spellIds)); + } + + private: + static bool _ValidateSpellInfo(uint32 const* begin, uint32 const* end); }; // SpellScript interface - enum used for runtime checks of script function calls @@ -657,11 +676,11 @@ class TC_GAME_API AuraScript : public _SpellScript #define PrepareAuraScript(CLASSNAME) AURASCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) AURASCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) public: - AuraScript() : _SpellScript(), m_aura(NULL), m_auraApplication(NULL), m_defaultActionPrevented(false) + AuraScript() : _SpellScript(), m_aura(nullptr), m_auraApplication(nullptr), m_defaultActionPrevented(false) { } bool _Validate(SpellInfo const* entry) override; bool _Load(Aura* aura); - void _PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp = NULL); + void _PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp = nullptr); void _FinishScriptCall(); bool _IsDefaultActionPrevented(); private: diff --git a/src/server/game/Texts/ChatTextBuilder.cpp b/src/server/game/Texts/ChatTextBuilder.cpp new file mode 100644 index 00000000000..8328e7f8bbf --- /dev/null +++ b/src/server/game/Texts/ChatTextBuilder.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ChatTextBuilder.h" +#include "Chat.h" +#include "ObjectMgr.h" +#include "Unit.h" + +void Trinity::BroadcastTextBuilder::operator()(WorldPacket& data, LocaleConstant locale) const +{ + BroadcastText const* bct = sObjectMgr->GetBroadcastText(_textId); + ChatHandler::BuildChatPacket(data, _msgType, bct ? Language(bct->Language) : LANG_UNIVERSAL, _source, _target, bct ? bct->GetText(locale, _source->getGender()) : "", _achievementId, "", locale); +} + +size_t Trinity::BroadcastTextBuilder::operator()(WorldPacket* data, LocaleConstant locale) const +{ + BroadcastText const* bct = sObjectMgr->GetBroadcastText(_textId); + return ChatHandler::BuildChatPacket(*data, _msgType, bct ? Language(bct->Language) : LANG_UNIVERSAL, _source, _target, bct ? bct->GetText(locale, _source->getGender()) : "", _achievementId, "", locale); +} + +void Trinity::CustomChatTextBuilder::operator()(WorldPacket& data, LocaleConstant locale) const +{ + ChatHandler::BuildChatPacket(data, _msgType, _language, _source, _target, _text, 0, "", locale); +} diff --git a/src/server/game/Texts/ChatTextBuilder.h b/src/server/game/Texts/ChatTextBuilder.h index c913e177894..1fe51dc7258 100644 --- a/src/server/game/Texts/ChatTextBuilder.h +++ b/src/server/game/Texts/ChatTextBuilder.h @@ -18,8 +18,13 @@ #ifndef __CHATTEXT_BUILDER_H #define __CHATTEXT_BUILDER_H -#include "Chat.h" -#include "ObjectMgr.h" +#include "Common.h" +#include "SharedDefines.h" +#include + +class Unit; +class WorldObject; +class WorldPacket; namespace Trinity { @@ -29,17 +34,8 @@ namespace Trinity BroadcastTextBuilder(Unit const* obj, ChatMsg msgType, uint32 textId, WorldObject const* target = nullptr, uint32 achievementId = 0) : _source(obj), _msgType(msgType), _textId(textId), _target(target), _achievementId(achievementId) { } - void operator()(WorldPacket& data, LocaleConstant locale) - { - BroadcastText const* bct = sObjectMgr->GetBroadcastText(_textId); - ChatHandler::BuildChatPacket(data, _msgType, bct ? Language(bct->Language) : LANG_UNIVERSAL, _source, _target, bct ? bct->GetText(locale, _source->getGender()) : "", _achievementId, "", locale); - } - - size_t operator()(WorldPacket* data, LocaleConstant locale) const - { - BroadcastText const* bct = sObjectMgr->GetBroadcastText(_textId); - return ChatHandler::BuildChatPacket(*data, _msgType, bct ? Language(bct->Language) : LANG_UNIVERSAL, _source, _target, bct ? bct->GetText(locale, _source->getGender()) : "", _achievementId, "", locale); - } + void operator()(WorldPacket& data, LocaleConstant locale) const; + size_t operator()(WorldPacket* data, LocaleConstant locale) const; private: Unit const* _source; @@ -55,10 +51,7 @@ namespace Trinity CustomChatTextBuilder(WorldObject const* obj, ChatMsg msgType, std::string const& text, Language language = LANG_UNIVERSAL, WorldObject const* target = nullptr) : _source(obj), _msgType(msgType), _text(text), _language(language), _target(target) { } - void operator()(WorldPacket& data, LocaleConstant locale) - { - ChatHandler::BuildChatPacket(data, _msgType, _language, _source, _target, _text, 0, "", locale); - } + void operator()(WorldPacket& data, LocaleConstant locale) const; private: WorldObject const* _source; diff --git a/src/server/game/Texts/CreatureTextMgr.cpp b/src/server/game/Texts/CreatureTextMgr.cpp index 77a886af3e5..9d2c7d6769f 100644 --- a/src/server/game/Texts/CreatureTextMgr.cpp +++ b/src/server/game/Texts/CreatureTextMgr.cpp @@ -15,15 +15,17 @@ * with this program. If not, see . */ -#include "Common.h" -#include "DatabaseEnv.h" -#include "ObjectMgr.h" -#include "Cell.h" +#include "CreatureTextMgr.h" +#include "CreatureTextMgrImpl.h" #include "CellImpl.h" #include "Chat.h" -#include "GridNotifiers.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" -#include "CreatureTextMgr.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "World.h" class CreatureTextBuilder { @@ -224,7 +226,7 @@ uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject } CreatureTextGroup const& textGroupContainer = itr->second; //has all texts in the group - CreatureTextRepeatIds repeatGroup = GetRepeatGroup(source, textGroup);//has all textIDs from the group that were already said + CreatureTextRepeatIds repeatGroup = source->GetTextRepeatGroup(textGroup);//has all textIDs from the group that were already said CreatureTextGroup tempGroup;//will use this to talk after sorting repeatGroup for (CreatureTextGroup::const_iterator giter = textGroupContainer.begin(); giter != textGroupContainer.end(); ++giter) @@ -270,7 +272,7 @@ uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject SendChatPacket(finalSource, builder, finalType, whisperTarget, range, team, gmOnly); } - SetRepeatId(source, textGroup, iter->id); + source->SetTextRepeatId(textGroup, iter->id); return iter->duration; } @@ -327,7 +329,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) return; - whisperTarget->ToPlayer()->GetSession()->SendPacket(data); + whisperTarget->ToPlayer()->SendDirectMessage(data); return; } break; @@ -344,7 +346,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, Map::PlayerList const& players = source->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); return; } case TEXT_RANGE_ZONE: @@ -353,7 +355,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, Map::PlayerList const& players = source->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); return; } case TEXT_RANGE_MAP: @@ -361,7 +363,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, Map::PlayerList const& players = source->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); return; } case TEXT_RANGE_WORLD: @@ -369,8 +371,8 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, SessionMap const& smap = sWorld->GetAllSessions(); for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) if (Player* player = iter->second->GetPlayer()) - if (player->GetSession() && (!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) - player->GetSession()->SendPacket(data); + if ((!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) + player->SendDirectMessage(data); return; } case TEXT_RANGE_NORMAL: @@ -390,21 +392,6 @@ void CreatureTextMgr::SendEmote(Unit* source, uint32 emote) source->HandleEmoteCommand(emote); } -void CreatureTextMgr::SetRepeatId(Creature* source, uint8 textGroup, uint8 id) -{ - if (!source) - return; - - source->SetTextRepeatId(textGroup, id); -} - -CreatureTextRepeatIds CreatureTextMgr::GetRepeatGroup(Creature* source, uint8 textGroup) -{ - ASSERT(source);//should never happen - - return source->GetTextRepeatGroup(textGroup); -} - bool CreatureTextMgr::TextExist(uint32 sourceEntry, uint8 textGroup) { if (!sourceEntry) diff --git a/src/server/game/Texts/CreatureTextMgr.h b/src/server/game/Texts/CreatureTextMgr.h index 70825f75307..08040882461 100644 --- a/src/server/game/Texts/CreatureTextMgr.h +++ b/src/server/game/Texts/CreatureTextMgr.h @@ -18,12 +18,17 @@ #ifndef TRINITY_CREATURE_TEXT_MGR_H #define TRINITY_CREATURE_TEXT_MGR_H -#include "Creature.h" -#include "GridNotifiers.h" -#include "ObjectAccessor.h" +#include "Common.h" #include "SharedDefines.h" -#include "Opcodes.h" -#include "Group.h" +#include +#include +#include + +class Creature; +class Player; +class Unit; +class WorldObject; +class WorldPacket; enum CreatureTextRange { @@ -52,7 +57,7 @@ struct CreatureTextEntry struct CreatureTextLocale { - StringVector Text; + std::vector Text; }; struct CreatureTextId @@ -61,7 +66,7 @@ struct CreatureTextId bool operator<(CreatureTextId const& right) const { - return memcmp(this, &right, sizeof(CreatureTextId)) < 0; + return std::tie(entry, textGroup, textId) < std::tie(right.entry, right.textGroup, right.textId); } uint32 entry; @@ -96,12 +101,10 @@ class TC_GAME_API CreatureTextMgr bool TextExist(uint32 sourceEntry, uint8 textGroup); std::string GetLocalizedChatString(uint32 entry, uint8 gender, uint8 textGroup, uint32 id, LocaleConstant locale) const; - template void SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget = nullptr, CreatureTextRange range = TEXT_RANGE_NORMAL, Team team = TEAM_OTHER, bool gmOnly = false) const; + template + void SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget = nullptr, CreatureTextRange range = TEXT_RANGE_NORMAL, Team team = TEAM_OTHER, bool gmOnly = false) const; private: - CreatureTextRepeatIds GetRepeatGroup(Creature* source, uint8 textGroup); - void SetRepeatId(Creature* source, uint8 textGroup, uint8 id); - void SendNonChatPacket(WorldObject* source, WorldPacket* data, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, Team team, bool gmOnly) const; float GetRangeForChatType(ChatMsg msgType) const; @@ -111,148 +114,4 @@ class TC_GAME_API CreatureTextMgr #define sCreatureTextMgr CreatureTextMgr::instance() -template -class CreatureTextLocalizer -{ - public: - CreatureTextLocalizer(Builder const& builder, ChatMsg msgType) : _builder(builder), _msgType(msgType) - { - _packetCache.resize(TOTAL_LOCALES, NULL); - } - - ~CreatureTextLocalizer() - { - for (size_t i = 0; i < _packetCache.size(); ++i) - { - if (_packetCache[i]) - delete _packetCache[i]->first; - delete _packetCache[i]; - } - } - - void operator()(Player* player) - { - LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); - WorldPacket* messageTemplate; - size_t whisperGUIDpos; - - // create if not cached yet - if (!_packetCache[loc_idx]) - { - messageTemplate = new WorldPacket(); - whisperGUIDpos = _builder(messageTemplate, loc_idx); - _packetCache[loc_idx] = new std::pair(messageTemplate, whisperGUIDpos); - } - else - { - messageTemplate = _packetCache[loc_idx]->first; - whisperGUIDpos = _packetCache[loc_idx]->second; - } - - WorldPacket data(*messageTemplate); - switch (_msgType) - { - case CHAT_MSG_MONSTER_WHISPER: - case CHAT_MSG_RAID_BOSS_WHISPER: - data.put(whisperGUIDpos, player->GetGUID().GetRawValue()); - break; - default: - break; - } - - player->SendDirectMessage(&data); - } - - private: - std::vector* > _packetCache; - Builder const& _builder; - ChatMsg _msgType; -}; - -template -void CreatureTextMgr::SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget /*= nullptr*/, CreatureTextRange range /*= TEXT_RANGE_NORMAL*/, Team team /*= TEAM_OTHER*/, bool gmOnly /*= false*/) const -{ - if (!source) - return; - - CreatureTextLocalizer localizer(builder, msgType); - - switch (msgType) - { - case CHAT_MSG_MONSTER_PARTY: - { - if (!whisperTarget) - return; - - if (Player* whisperPlayer = const_cast(whisperTarget->ToPlayer())) - { - if (Group* group = whisperPlayer->GetGroup()) - group->BroadcastWorker(localizer); - } - return; - } - case CHAT_MSG_MONSTER_WHISPER: - case CHAT_MSG_RAID_BOSS_WHISPER: - { - if (range == TEXT_RANGE_NORMAL) // ignores team and gmOnly - { - if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) - return; - - localizer(const_cast(whisperTarget->ToPlayer())); - return; - } - break; - } - default: - break; - } - - switch (range) - { - case TEXT_RANGE_AREA: - { - uint32 areaId = source->GetAreaId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } - case TEXT_RANGE_ZONE: - { - uint32 zoneId = source->GetZoneId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } - case TEXT_RANGE_MAP: - { - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } - case TEXT_RANGE_WORLD: - { - SessionMap const& smap = sWorld->GetAllSessions(); - for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) - if (Player* player = iter->second->GetPlayer()) - if ((!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) - localizer(player); - return; - } - case TEXT_RANGE_NORMAL: - default: - break; - } - - float dist = GetRangeForChatType(msgType); - Trinity::PlayerDistWorker> worker(source, dist, localizer); - Cell::VisitWorldObjects(source, worker, dist); -} - #endif diff --git a/src/server/game/Texts/CreatureTextMgrImpl.h b/src/server/game/Texts/CreatureTextMgrImpl.h new file mode 100644 index 00000000000..219c257a7e4 --- /dev/null +++ b/src/server/game/Texts/CreatureTextMgrImpl.h @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef CreatureTextMgrImpl_h__ +#define CreatureTextMgrImpl_h__ + +#include "CreatureTextMgr.h" +#include "CellImpl.h" +#include "Group.h" +#include "GridNotifiers.h" +#include "World.h" +#include "WorldSession.h" + +template +class CreatureTextLocalizer +{ +public: + CreatureTextLocalizer(Builder const& builder, ChatMsg msgType) : _builder(builder), _msgType(msgType) + { + _packetCache.resize(TOTAL_LOCALES, nullptr); + } + + ~CreatureTextLocalizer() + { + for (size_t i = 0; i < _packetCache.size(); ++i) + { + if (_packetCache[i]) + delete _packetCache[i]->first; + delete _packetCache[i]; + } + } + + void operator()(Player const* player) const + { + LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); + WorldPacket* messageTemplate; + size_t whisperGUIDpos; + + // create if not cached yet + if (!_packetCache[loc_idx]) + { + messageTemplate = new WorldPacket(); + whisperGUIDpos = _builder(messageTemplate, loc_idx); + _packetCache[loc_idx] = new std::pair(messageTemplate, whisperGUIDpos); + } + else + { + messageTemplate = _packetCache[loc_idx]->first; + whisperGUIDpos = _packetCache[loc_idx]->second; + } + + WorldPacket data(*messageTemplate); + switch (_msgType) + { + case CHAT_MSG_MONSTER_WHISPER: + case CHAT_MSG_RAID_BOSS_WHISPER: + data.put(whisperGUIDpos, player->GetGUID().GetRawValue()); + break; + default: + break; + } + + player->SendDirectMessage(&data); + } + +private: + mutable std::vector*> _packetCache; + Builder const& _builder; + ChatMsg _msgType; +}; + +template +void CreatureTextMgr::SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget /*= nullptr*/, CreatureTextRange range /*= TEXT_RANGE_NORMAL*/, Team team /*= TEAM_OTHER*/, bool gmOnly /*= false*/) const +{ + if (!source) + return; + + CreatureTextLocalizer localizer(builder, msgType); + + switch (msgType) + { + case CHAT_MSG_MONSTER_PARTY: + { + if (!whisperTarget) + return; + + if (Player const* whisperPlayer = whisperTarget->ToPlayer()) + if (Group const* group = whisperPlayer->GetGroup()) + group->BroadcastWorker(localizer); + return; + } + case CHAT_MSG_MONSTER_WHISPER: + case CHAT_MSG_RAID_BOSS_WHISPER: + { + if (range == TEXT_RANGE_NORMAL) // ignores team and gmOnly + { + if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) + return; + + localizer(const_cast(whisperTarget->ToPlayer())); + return; + } + break; + } + default: + break; + } + + switch (range) + { + case TEXT_RANGE_AREA: + { + uint32 areaId = source->GetAreaId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } + case TEXT_RANGE_ZONE: + { + uint32 zoneId = source->GetZoneId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } + case TEXT_RANGE_MAP: + { + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } + case TEXT_RANGE_WORLD: + { + SessionMap const& smap = sWorld->GetAllSessions(); + for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) + if (Player* player = iter->second->GetPlayer()) + if ((!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) + localizer(player); + return; + } + case TEXT_RANGE_NORMAL: + default: + break; + } + + float dist = GetRangeForChatType(msgType); + Trinity::PlayerDistWorker> worker(source, dist, localizer); + Cell::VisitWorldObjects(source, worker, dist); +} + +#endif // CreatureTextMgrImpl_h__ diff --git a/src/server/game/Tickets/TicketMgr.cpp b/src/server/game/Tickets/TicketMgr.cpp index 360e5cec886..1260ff6937b 100644 --- a/src/server/game/Tickets/TicketMgr.cpp +++ b/src/server/game/Tickets/TicketMgr.cpp @@ -16,20 +16,21 @@ * with this program. If not, see . */ +#include "TicketMgr.h" #include "CharacterCache.h" +#include "Chat.h" #include "Common.h" -#include "TicketMgr.h" #include "DatabaseEnv.h" -#include "Log.h" #include "Language.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Opcodes.h" +#include "Player.h" +#include "World.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "Chat.h" -#include "World.h" -#include "Player.h" -#include "Opcodes.h" -inline float GetAge(uint64 t) { return float(time(NULL) - t) / DAY; } +inline float GetAge(uint64 t) { return float(time(nullptr) - t) / DAY; } /////////////////////////////////////////////////////////////////////////////////////////////////// // GM ticket @@ -37,7 +38,7 @@ GmTicket::GmTicket() : _id(0), _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _pos _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needResponse(false), _needMoreHelp(false) { } -GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _posZ(0), _mapId(0), _createTime(time(NULL)), _lastModifiedTime(time(NULL)), +GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _posZ(0), _mapId(0), _createTime(time(nullptr)), _lastModifiedTime(time(nullptr)), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needResponse(false), _needMoreHelp(false) { @@ -46,7 +47,19 @@ GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _posX(0), _posY(0) _playerGuid = player->GetGUID(); } -GmTicket::~GmTicket() { } +GmTicket::~GmTicket() +{ +} + +Player* GmTicket::GetPlayer() const +{ + return ObjectAccessor::FindPlayer(_playerGuid); +} + +Player* GmTicket::GetAssignedPlayer() const +{ + return ObjectAccessor::FindPlayer(_assignedTo); +} bool GmTicket::LoadFromDB(Field* fields) { @@ -160,7 +173,7 @@ void GmTicket::SendResponse(WorldSession* session) const std::string GmTicket::FormatMessageString(ChatHandler& handler, bool detailed) const { - time_t curTime = time(NULL); + time_t curTime = time(nullptr); std::stringstream ss; ss << handler.PGetParseString(LANG_COMMAND_TICKETLISTGUID, _id); @@ -183,7 +196,7 @@ std::string GmTicket::FormatMessageString(ChatHandler& handler, bool detailed) c return ss.str(); } -std::string GmTicket::FormatMessageString(ChatHandler& handler, const char* szClosedName, const char* szAssignedToName, const char* szUnassignedName, const char* szDeletedName, const char* szCompletedName) const +std::string GmTicket::FormatMessageString(ChatHandler& handler, char const* szClosedName, char const* szAssignedToName, char const* szUnassignedName, char const* szDeletedName, char const* szCompletedName) const { std::stringstream ss; ss << handler.PGetParseString(LANG_COMMAND_TICKETLISTGUID, _id); @@ -251,7 +264,7 @@ void GmTicket::SetChatLog(std::list time, std::string const& log) /////////////////////////////////////////////////////////////////////////////////////////////////// // Ticket manager TicketMgr::TicketMgr() : _status(true), _lastTicketId(0), _lastSurveyId(0), _openTicketCount(0), - _lastChange(time(NULL)) { } + _lastChange(time(nullptr)) { } TicketMgr::~TicketMgr() { @@ -355,7 +368,7 @@ void TicketMgr::AddTicket(GmTicket* ticket) _ticketList[ticket->GetId()] = ticket; if (!ticket->IsClosed()) ++_openTicketCount; - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SaveToDB(trans); } @@ -363,7 +376,7 @@ void TicketMgr::CloseTicket(uint32 ticketId, ObjectGuid source) { if (GmTicket* ticket = GetTicket(ticketId)) { - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetClosedBy(source); if (source) --_openTicketCount; diff --git a/src/server/game/Tickets/TicketMgr.h b/src/server/game/Tickets/TicketMgr.h index 5aab1f4ed94..199265b1aec 100644 --- a/src/server/game/Tickets/TicketMgr.h +++ b/src/server/game/Tickets/TicketMgr.h @@ -18,11 +18,14 @@ #ifndef _TICKETMGR_H #define _TICKETMGR_H -#include - -#include "ObjectMgr.h" +#include "ObjectGuid.h" +#include "DatabaseEnvFwd.h" +#include class ChatHandler; +class Player; +class WorldPacket; +class WorldSession; // from blizzard lua enum GMTicketSystemStatus @@ -99,10 +102,10 @@ public: bool IsAssignedNotTo(ObjectGuid guid) const { return IsAssigned() && !IsAssignedTo(guid); } uint32 GetId() const { return _id; } - Player* GetPlayer() const { return ObjectAccessor::FindPlayer(_playerGuid); } + Player* GetPlayer() const; std::string const& GetPlayerName() const { return _playerName; } std::string const& GetMessage() const { return _message; } - Player* GetAssignedPlayer() const { return ObjectAccessor::FindPlayer(_assignedTo); } + Player* GetAssignedPlayer() const; ObjectGuid GetAssignedToGUID() const { return _assignedTo; } std::string GetAssignedToName() const; uint64 GetLastModifiedTime() const { return _lastModifiedTime; } @@ -123,7 +126,7 @@ public: void SetMessage(std::string const& message) { _message = message; - _lastModifiedTime = uint64(time(NULL)); + _lastModifiedTime = uint64(time(nullptr)); } void SetComment(std::string const& comment) { _comment = comment; } void SetViewed() { _viewed = true; } @@ -142,7 +145,7 @@ public: void TeleportTo(Player* player) const; std::string FormatMessageString(ChatHandler& handler, bool detailed = false) const; - std::string FormatMessageString(ChatHandler& handler, const char* szClosedName, const char* szAssignedToName, const char* szUnassignedName, const char* szDeletedName, const char* szCompletedName) const; + std::string FormatMessageString(ChatHandler& handler, char const* szClosedName, char const* szAssignedToName, char const* szUnassignedName, char const* szDeletedName, char const* szCompletedName) const; void SetChatLog(std::list time, std::string const& log); std::string const& GetChatLog() const { return _chatLog; } @@ -191,7 +194,7 @@ public: if (itr != _ticketList.end()) return itr->second; - return NULL; + return nullptr; } GmTicket* GetTicketByPlayer(ObjectGuid playerGuid) @@ -200,7 +203,7 @@ public: if (itr->second && itr->second->IsFromPlayer(playerGuid) && !itr->second->IsClosed()) return itr->second; - return NULL; + return nullptr; } GmTicket* GetOldestOpenTicket() @@ -209,7 +212,7 @@ public: if (itr->second && !itr->second->IsClosed() && !itr->second->IsCompleted()) return itr->second; - return NULL; + return nullptr; } void AddTicket(GmTicket* ticket); @@ -221,7 +224,7 @@ public: void SetStatus(bool status) { _status = status; } uint64 GetLastChange() const { return _lastChange; } - void UpdateLastChange() { _lastChange = uint64(time(NULL)); } + void UpdateLastChange() { _lastChange = uint64(time(nullptr)); } uint32 GenerateTicketId() { return ++_lastTicketId; } uint32 GetOpenTicketCount() const { return _openTicketCount; } @@ -236,9 +239,7 @@ public: void SendTicket(WorldSession* session, GmTicket* ticket) const; -protected: - void _RemoveTicket(uint32 ticketId, int64 source = -1, bool permanently = false); - +private: GmTicketList _ticketList; bool _status; diff --git a/src/server/game/Time/GameTime.h b/src/server/game/Time/GameTime.h index efe73a6a0b7..565ffc51c18 100644 --- a/src/server/game/Time/GameTime.h +++ b/src/server/game/Time/GameTime.h @@ -19,7 +19,6 @@ #define __GAMETIME_H #include "Define.h" - #include namespace GameTime diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.cpp b/src/server/game/Tools/CharacterDatabaseCleaner.cpp index c03851fdbdf..030f1d170d8 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.cpp +++ b/src/server/game/Tools/CharacterDatabaseCleaner.cpp @@ -19,10 +19,11 @@ #include "Common.h" #include "AchievementMgr.h" #include "CharacterDatabaseCleaner.h" -#include "World.h" -#include "Database/DatabaseEnv.h" -#include "SpellMgr.h" +#include "DatabaseEnv.h" #include "DBCStores.h" +#include "Log.h" +#include "SpellMgr.h" +#include "World.h" void CharacterDatabaseCleaner::CleanDatabase() { @@ -67,7 +68,7 @@ void CharacterDatabaseCleaner::CleanDatabase() TC_LOG_INFO("server.loading", ">> Cleaned character database in %u ms", GetMSTimeDiffToNow(oldMSTime)); } -void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table, bool (*check)(uint32)) +void CharacterDatabaseCleaner::CheckUnique(char const* column, char const* table, bool (*check)(uint32)) { QueryResult result = CharacterDatabase.PQuery("SELECT DISTINCT %s FROM %s", column, table); if (!result) diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.h b/src/server/game/Tools/CharacterDatabaseCleaner.h index e6db1e54c8f..c43d5229bac 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.h +++ b/src/server/game/Tools/CharacterDatabaseCleaner.h @@ -32,7 +32,7 @@ namespace CharacterDatabaseCleaner TC_GAME_API void CleanDatabase(); - TC_GAME_API void CheckUnique(const char* column, const char* table, bool (*check)(uint32)); + TC_GAME_API void CheckUnique(char const* column, char const* table, bool (*check)(uint32)); TC_GAME_API bool AchievementProgressCheck(uint32 criteria); TC_GAME_API bool SkillCheck(uint32 skill); diff --git a/src/server/game/Tools/PlayerDump.cpp b/src/server/game/Tools/PlayerDump.cpp index e4bf6b2a171..0357fcc4e15 100644 --- a/src/server/game/Tools/PlayerDump.cpp +++ b/src/server/game/Tools/PlayerDump.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ -#include "Common.h" #include "PlayerDump.h" +#include "AccountMgr.h" +#include "CharacterCache.h" +#include "Common.h" #include "DatabaseEnv.h" -#include "UpdateFields.h" +#include "Log.h" #include "ObjectMgr.h" #include "Player.h" -#include "AccountMgr.h" -#include "CharacterCache.h" +#include "UpdateFields.h" #include "World.h" // static data @@ -414,7 +415,7 @@ inline std::string GetTableName(std::string const& str) { // length of "INSERT INTO `" static std::string::size_type const s = 13; - std::string::size_type e = str.find(_TABLE_SIM_, s); + std::string::size_type e = str.find('`', s); if (e == std::string::npos) return ""; @@ -437,7 +438,7 @@ inline bool ValidateFields(TableStruct const& ts, std::string const& str, size_t s += 4; std::string::size_type valPos = str.find("VALUES ('"); - std::string::size_type e = str.find(_TABLE_SIM_, s); + std::string::size_type e = str.find('`', s); if (e == std::string::npos || valPos == std::string::npos) { TC_LOG_ERROR("misc", "LoadPlayerDump: (line " UI64FMTD ") unexpected end of line", lineNumber); @@ -456,7 +457,7 @@ inline bool ValidateFields(TableStruct const& ts, std::string const& str, size_t // length of "`, `" s = e + 4; - e = str.find(_TABLE_SIM_, s); + e = str.find('`', s); } while (e < valPos); return true; @@ -518,10 +519,10 @@ inline void AppendTableDump(StringTransaction& trans, TableStruct const& tableSt do { std::ostringstream ss; - ss << "INSERT INTO " << _TABLE_SIM_ << tableStruct.TableName << _TABLE_SIM_ << " ("; + ss << "INSERT INTO `" << tableStruct.TableName << "` ("; for (auto itr = tableStruct.TableFields.begin(); itr != tableStruct.TableFields.end();) { - ss << _TABLE_SIM_ << itr->FieldName << _TABLE_SIM_; + ss << '`' << itr->FieldName << '`'; ++itr; if (itr != tableStruct.TableFields.end()) diff --git a/src/server/game/Warden/Warden.cpp b/src/server/game/Warden/Warden.cpp index fae8198e092..8107a73158f 100644 --- a/src/server/game/Warden/Warden.cpp +++ b/src/server/game/Warden/Warden.cpp @@ -23,14 +23,15 @@ #include "Opcodes.h" #include "ByteBuffer.h" #include "GameTime.h" +#include "World.h" #include "Util.h" #include "Warden.h" #include "AccountMgr.h" #include -Warden::Warden() : _session(NULL), _inputCrypto(16), _outputCrypto(16), _checkTimer(10000/*10 sec*/), _clientResponseTimer(0), - _dataSent(false), _previousTimestamp(0), _module(NULL), _initialized(false) +Warden::Warden() : _session(nullptr), _inputCrypto(16), _outputCrypto(16), _checkTimer(10000/*10 sec*/), _clientResponseTimer(0), + _dataSent(false), _previousTimestamp(0), _module(nullptr), _initialized(false) { memset(_inputKey, 0, sizeof(_inputKey)); memset(_outputKey, 0, sizeof(_outputKey)); @@ -41,7 +42,7 @@ Warden::~Warden() { delete[] _module->CompressedData; delete _module; - _module = NULL; + _module = nullptr; _initialized = false; } @@ -138,7 +139,7 @@ void Warden::EncryptData(uint8* buffer, uint32 length) _outputCrypto.UpdateData(length, buffer); } -bool Warden::IsValidCheckSum(uint32 checksum, const uint8* data, const uint16 length) +bool Warden::IsValidCheckSum(uint32 checksum, uint8 const* data, const uint16 length) { uint32 newChecksum = BuildChecksum(data, length); @@ -169,7 +170,7 @@ struct keyData { }; }; -uint32 Warden::BuildChecksum(const uint8* data, uint32 length) +uint32 Warden::BuildChecksum(uint8 const* data, uint32 length) { keyData hash; SHA1(data, length, hash.bytes.bytes); @@ -180,7 +181,7 @@ uint32 Warden::BuildChecksum(const uint8* data, uint32 length) return checkSum; } -std::string Warden::Penalty(WardenCheck* check /*= NULL*/) +std::string Warden::Penalty(WardenCheck* check /*= nullptr*/) { WardenActions action; diff --git a/src/server/game/Warden/Warden.h b/src/server/game/Warden/Warden.h index 8f851181f0f..42d60442d27 100644 --- a/src/server/game/Warden/Warden.h +++ b/src/server/game/Warden/Warden.h @@ -119,7 +119,7 @@ class TC_GAME_API Warden static uint32 BuildChecksum(const uint8 *data, uint32 length); // If no check is passed, the default action from config is executed - std::string Penalty(WardenCheck* check = NULL); + std::string Penalty(WardenCheck* check = nullptr); private: WorldSession* _session; diff --git a/src/server/game/Warden/WardenCheckMgr.cpp b/src/server/game/Warden/WardenCheckMgr.cpp index bd0746ea207..3b8387e3381 100644 --- a/src/server/game/Warden/WardenCheckMgr.cpp +++ b/src/server/game/Warden/WardenCheckMgr.cpp @@ -23,6 +23,7 @@ #include "Database/DatabaseEnv.h" #include "WardenCheckMgr.h" #include "Warden.h" +#include "World.h" WardenCheckMgr::WardenCheckMgr() { } @@ -200,7 +201,7 @@ WardenCheck* WardenCheckMgr::GetWardenDataById(uint16 Id) if (Id < CheckStore.size()) return CheckStore[Id]; - return NULL; + return nullptr; } WardenCheckResult* WardenCheckMgr::GetWardenResultById(uint16 Id) @@ -208,5 +209,5 @@ WardenCheckResult* WardenCheckMgr::GetWardenResultById(uint16 Id) CheckResultContainer::const_iterator itr = CheckResultStore.find(Id); if (itr != CheckResultStore.end()) return itr->second; - return NULL; + return nullptr; } diff --git a/src/server/game/Warden/WardenWin.cpp b/src/server/game/Warden/WardenWin.cpp index 3336b4c01ba..6d8fd9dea76 100644 --- a/src/server/game/Warden/WardenWin.cpp +++ b/src/server/game/Warden/WardenWin.cpp @@ -26,11 +26,13 @@ #include "ByteBuffer.h" #include "Database/DatabaseEnv.h" #include "GameTime.h" +#include "World.h" #include "Player.h" #include "Util.h" #include "WardenWin.h" #include "WardenModuleWin.h" #include "WardenCheckMgr.h" +#include "Random.h" #include WardenWin::WardenWin() : Warden(), _serverTicks(0) {} diff --git a/src/server/game/Weather/Weather.cpp b/src/server/game/Weather/Weather.cpp index 91125282496..fb26ae61a12 100644 --- a/src/server/game/Weather/Weather.cpp +++ b/src/server/game/Weather/Weather.cpp @@ -21,12 +21,14 @@ */ #include "Weather.h" -#include "WorldPacket.h" -#include "Player.h" #include "GameTime.h" #include "Log.h" -#include "Util.h" +#include "Player.h" +#include "Random.h" #include "ScriptMgr.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" #include "WorldSession.h" /// Create the Weather object @@ -196,7 +198,7 @@ void Weather::SendWeatherUpdateToPlayer(Player* player) data << uint32(GetWeatherState()); data << (float)m_grade; data << uint8(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } /// Send the new weather to all players in the zone diff --git a/src/server/game/Weather/Weather.h b/src/server/game/Weather/Weather.h index beb9610cdf9..51702ea2b65 100644 --- a/src/server/game/Weather/Weather.h +++ b/src/server/game/Weather/Weather.h @@ -43,7 +43,7 @@ struct WeatherData uint32 ScriptId; }; -enum WeatherState +enum WeatherState : uint32 { WEATHER_STATE_FINE = 0, WEATHER_STATE_FOG = 1, diff --git a/src/server/game/Weather/WeatherMgr.cpp b/src/server/game/Weather/WeatherMgr.cpp index 6a7e60a2bc0..95728b7e8ae 100644 --- a/src/server/game/Weather/WeatherMgr.cpp +++ b/src/server/game/Weather/WeatherMgr.cpp @@ -21,10 +21,11 @@ */ #include "WeatherMgr.h" -#include "Weather.h" +#include "DatabaseEnv.h" #include "Log.h" #include "ObjectMgr.h" #include "Player.h" +#include "Weather.h" #include "WorldSession.h" namespace WeatherMgr @@ -41,7 +42,7 @@ namespace WeatherData const* GetWeatherData(uint32 zone_id) { WeatherZoneMap::const_iterator itr = mWeatherZoneMap.find(zone_id); - return (itr != mWeatherZoneMap.end()) ? &itr->second : NULL; + return (itr != mWeatherZoneMap.end()) ? &itr->second : nullptr; } } @@ -69,7 +70,7 @@ Weather* AddWeather(uint32 zone_id) // zone does not have weather, ignore if (!weatherChances) - return NULL; + return nullptr; Weather* w = new Weather(zone_id, weatherChances); m_weathers[w->GetZone()].reset(w); @@ -146,7 +147,7 @@ void SendFineWeatherUpdateToPlayer(Player* player) data << (uint32)WEATHER_STATE_FINE; data << (float)0.0f; data << uint8(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Update(uint32 diff) diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 2f09d03893f..6f5f987e9aa 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -21,7 +21,9 @@ */ #include "World.h" +#include "AccountMgr.h" #include "AchievementMgr.h" +#include "AddonMgr.h" #include "ArenaTeamMgr.h" #include "AuctionHouseBot.h" #include "AuctionHouseMgr.h" @@ -40,6 +42,7 @@ #include "DisableMgr.h" #include "GameEventMgr.h" #include "GameObjectModel.h" +#include "GameTime.h" #include "GitRevision.h" #include "GridNotifiersImpl.h" #include "GroupMgr.h" @@ -47,10 +50,15 @@ #include "InstanceSaveMgr.h" #include "Language.h" #include "LFGMgr.h" +#include "Log.h" #include "LootItemStorage.h" +#include "LootMgr.h" +#include "M2Stores.h" #include "MapManager.h" #include "Memory.h" +#include "Metric.h" #include "MMapFactory.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" #include "PetitionMgr.h" @@ -58,25 +66,27 @@ #include "PlayerDump.h" #include "PoolMgr.h" #include "QueryCallback.h" +#include "Realm.h" #include "ScriptMgr.h" #include "ScriptReloadMgr.h" #include "ServerMotd.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" -#include "SmartAI.h" -#include "Metric.h" +#include "SmartScriptMgr.h" +#include "SpellMgr.h" #include "TicketMgr.h" #include "TransportMgr.h" #include "Unit.h" +#include "UpdateTime.h" #include "VMapFactory.h" +#include "VMapManager2.h" #include "WardenCheckMgr.h" #include "WaypointMovementGenerator.h" #include "WeatherMgr.h" -#include "WorldSession.h" -#include "M2Stores.h" #include "WhoListStorage.h" -#include "GameTime.h" -#include "UpdateTime.h" +#include "WorldSession.h" + +#include TC_GAME_API std::atomic World::m_stopEvent(false); TC_GAME_API uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE; @@ -137,7 +147,7 @@ World::~World() m_sessions.erase(m_sessions.begin()); } - CliCommandHolder* command = NULL; + CliCommandHolder* command = nullptr; while (cliCmdQueue.next(command)) delete command; @@ -170,7 +180,7 @@ Player* World::FindPlayerInZone(uint32 zone) if (player->IsInWorld() && player->GetZoneId() == zone) return player; } - return NULL; + return nullptr; } bool World::IsClosed() const @@ -192,9 +202,9 @@ WorldSession* World::FindSession(uint32 id) const SessionMap::const_iterator itr = m_sessions.find(id); if (itr != m_sessions.end()) - return itr->second; // also can return NULL for kicked session + return itr->second; // also can return nullptr for kicked session else - return NULL; + return nullptr; } /// Remove a given session @@ -294,7 +304,7 @@ bool World::HasRecentlyDisconnected(WorldSession* session) { for (DisconnectMap::iterator i = m_disconnects.begin(); i != m_disconnects.end();) { - if (difftime(i->second, time(NULL)) < tolerance) + if (difftime(i->second, time(nullptr)) < tolerance) { if (i->first == session->GetAccountId()) return true; @@ -1189,7 +1199,7 @@ void World::LoadConfigSettings(bool reload) #if TRINITY_PLATFORM == TRINITY_PLATFORM_UNIX || TRINITY_PLATFORM == TRINITY_PLATFORM_APPLE if (dataPath[0] == '~') { - const char* home = getenv("HOME"); + char const* home = getenv("HOME"); if (home) dataPath.replace(0, 1, home); } @@ -1361,7 +1371,7 @@ void World::SetInitialWorldSettings() uint32 startupBegin = getMSTime(); ///- Initialize the random number generator - srand((unsigned int)time(NULL)); + srand((unsigned int)time(nullptr)); ///- Initialize detour memory management dtAllocSetCustom(dtCustomAlloc, dtCustomFree); @@ -1512,6 +1522,9 @@ void World::SetInitialWorldSettings() TC_LOG_INFO("server.loading", "Loading Transport templates..."); sTransportMgr->LoadTransportTemplates(); + TC_LOG_INFO("server.loading", "Loading Transport animations and rotations..."); + sTransportMgr->LoadTransportAnimationAndRotation(); + TC_LOG_INFO("server.loading", "Loading Spell Rank Data..."); sSpellMgr->LoadSpellRanks(); @@ -2337,7 +2350,7 @@ namespace Trinity { public: typedef std::vector WorldPacketList; - explicit WorldWorldTextBuilder(uint32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) { } + explicit WorldWorldTextBuilder(uint32 textId, va_list* args = nullptr) : i_textId(textId), i_args(args) { } void operator()(WorldPacketList& data_list, LocaleConstant loc_idx) { char const* text = sObjectMgr->GetTrinityString(i_textId, loc_idx); @@ -2358,14 +2371,14 @@ namespace Trinity do_helper(data_list, (char*)text); } private: - char* lineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = NULL; return start; } + char* lineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } void do_helper(WorldPacketList& data_list, char* text) { char* pos = text; while (char* line = lineFromMessage(pos)) { WorldPacket* data = new WorldPacket(); - ChatHandler::BuildChatPacket(*data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + ChatHandler::BuildChatPacket(*data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); data_list.push_back(data); } } @@ -2421,7 +2434,7 @@ void World::SendGMText(uint32 string_id, ...) } /// DEPRECATED, only for debug purpose. Send a System Message to all players (except self if mentioned) -void World::SendGlobalText(const char* text, WorldSession* self) +void World::SendGlobalText(char const* text, WorldSession* self) { WorldPacket data; @@ -2431,7 +2444,7 @@ void World::SendGlobalText(const char* text, WorldSession* self) while (char* line = ChatHandler::LineFromMessage(pos)) { - ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); SendGlobalMessage(&data, self); } @@ -2462,10 +2475,10 @@ bool World::SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self } /// Send a System Message to all players in the zone (except self if mentioned) -void World::SendZoneText(uint32 zone, const char* text, WorldSession* self, uint32 team) +void World::SendZoneText(uint32 zone, char const* text, WorldSession* self, uint32 team) { WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, text); + ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, text); SendZoneMessage(zone, &data, self, team); } @@ -2498,8 +2511,8 @@ BanReturn World::BanAccount(BanMode mode, std::string const& nameOrIP, std::stri /// Ban an account or ban an IP address, duration is in seconds if positive, otherwise permban BanReturn World::BanAccount(BanMode mode, std::string const& nameOrIP, uint32 duration_secs, std::string const& reason, std::string const& author) { - PreparedQueryResult resultAccounts = PreparedQueryResult(NULL); //used for kicking - PreparedStatement* stmt = NULL; + PreparedQueryResult resultAccounts = PreparedQueryResult(nullptr); //used for kicking + PreparedStatement* stmt = nullptr; ///- Update the database with ban information switch (mode) @@ -2575,7 +2588,7 @@ BanReturn World::BanAccount(BanMode mode, std::string const& nameOrIP, uint32 du /// Remove a ban from an account or IP address bool World::RemoveBanAccount(BanMode mode, std::string const& nameOrIP) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; if (mode == BAN_IP) { stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_IP_NOT_BANNED); @@ -2780,7 +2793,7 @@ void World::SendServerMessage(ServerMessageType type, const char *text, Player* data << text; if (player) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); else SendGlobalMessage(&data); } @@ -2788,7 +2801,7 @@ void World::SendServerMessage(ServerMessageType type, const char *text, Player* void World::UpdateSessions(uint32 diff) { ///- Add new sessions - WorldSession* sess = NULL; + WorldSession* sess = nullptr; while (addSessQueue.next(sess)) AddSession_ (sess); @@ -2805,7 +2818,7 @@ void World::UpdateSessions(uint32 diff) if (!pSession->Update(diff, updater)) // As interval = 0 { if (!RemoveQueuedPlayer(itr->second) && itr->second && getIntConfig(CONFIG_INTERVAL_DISCONNECT_TOLERANCE)) - m_disconnects[itr->second->GetAccountId()] = time(NULL); + m_disconnects[itr->second->GetAccountId()] = time(nullptr); RemoveQueuedPlayer(pSession); m_sessions.erase(itr); delete pSession; @@ -2817,9 +2830,9 @@ void World::UpdateSessions(uint32 diff) // This handles the issued and queued CLI commands void World::ProcessCliCommands() { - CliCommandHolder::Print* zprint = NULL; - void* callbackArg = NULL; - CliCommandHolder* command = NULL; + CliCommandHolder::Print zprint = nullptr; + void* callbackArg = nullptr; + CliCommandHolder* command = nullptr; while (cliCmdQueue.next(command)) { TC_LOG_INFO("misc", "CLI command under processing..."); @@ -2925,7 +2938,7 @@ void World::_UpdateRealmCharCount(PreparedQueryResult resultCharCount) void World::InitWeeklyQuestResetTime() { time_t wstime = uint64(sWorld->getWorldState(WS_WEEKLY_QUEST_RESET_TIME)); - time_t curtime = time(NULL); + time_t curtime = time(nullptr); m_NextWeeklyQuestReset = wstime < curtime ? curtime : time_t(wstime); } @@ -2944,7 +2957,7 @@ void World::InitDailyQuestResetTime(bool loading) } // FIX ME: client not show day start time - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); localTm.tm_hour = getIntConfig(CONFIG_DAILY_QUEST_RESET_TIME_HOUR); @@ -2967,7 +2980,7 @@ void World::InitDailyQuestResetTime(bool loading) void World::InitMonthlyQuestResetTime() { time_t wstime = uint64(sWorld->getWorldState(WS_MONTHLY_QUEST_RESET_TIME)); - time_t curtime = time(NULL); + time_t curtime = time(nullptr); m_NextMonthlyQuestReset = wstime < curtime ? curtime : time_t(wstime); } @@ -2975,10 +2988,10 @@ void World::InitRandomBGResetTime() { time_t bgtime = uint64(sWorld->getWorldState(WS_BG_DAILY_RESET_TIME)); if (!bgtime) - m_NextRandomBGReset = time_t(time(NULL)); // game time not yet init + m_NextRandomBGReset = time_t(time(nullptr)); // game time not yet init // generate time by config - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); localTm.tm_hour = getIntConfig(CONFIG_RANDOM_BG_RESET_HOUR); @@ -3003,10 +3016,10 @@ void World::InitGuildResetTime() { time_t gtime = uint64(getWorldState(WS_GUILD_DAILY_RESET_TIME)); if (!gtime) - m_NextGuildReset = time_t(time(NULL)); // game time not yet init + m_NextGuildReset = time_t(time(nullptr)); // game time not yet init // generate time by config - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); localTm.tm_hour = getIntConfig(CONFIG_GUILD_RESET_HOUR); @@ -3091,7 +3104,7 @@ void World::ResetMonthlyQuests() itr->second->GetPlayer()->ResetMonthlyQuestStatus(); // generate time - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); @@ -3220,6 +3233,16 @@ void World::LoadWorldStates() } +bool World::IsPvPRealm() const +{ + return (getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP); +} + +bool World::IsFFAPvPRealm() const +{ + return getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP; +} + // Setting a worldstate will save it to DB void World::setWorldState(uint32 index, uint64 value) { @@ -3274,3 +3297,13 @@ void World::RemoveOldCorpses() } Realm realm; + +CliCommandHolder::CliCommandHolder(void* callbackArg, char const* command, Print zprint, CommandFinished commandFinished) + : m_callbackArg(callbackArg), m_command(strdup(command)), m_print(zprint), m_commandFinished(commandFinished) +{ +} + +CliCommandHolder::~CliCommandHolder() +{ + free(m_command); +} diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index cdf3703a67a..6b9e21dcf69 100644 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -24,24 +24,23 @@ #define __WORLD_H #include "Common.h" +#include "DatabaseEnvFwd.h" +#include "LockedQueue.h" #include "ObjectGuid.h" -#include "Timer.h" -#include "SharedDefines.h" -#include "QueryResult.h" #include "QueryCallbackProcessor.h" -#include "Realm/Realm.h" +#include "SharedDefines.h" +#include "Timer.h" #include -#include -#include #include +#include +#include -class Object; +class Player; class WorldPacket; class WorldSession; -class Player; class WorldSocket; -class SystemMgr; +struct Realm; // ServerMessages.dbc enum ServerMessageType @@ -53,14 +52,14 @@ enum ServerMessageType SERVER_MSG_RESTART_CANCELLED = 5 }; -enum ShutdownMask +enum ShutdownMask : uint32 { SHUTDOWN_MASK_RESTART = 1, SHUTDOWN_MASK_IDLE = 2, SHUTDOWN_MASK_FORCE = 4 }; -enum ShutdownExitCode +enum ShutdownExitCode : uint32 { SHUTDOWN_EXIT_CODE = 0, ERROR_EXIT_CODE = 1, @@ -531,23 +530,18 @@ enum WorldStates }; /// Storage class for commands issued for delayed execution -struct CliCommandHolder +struct TC_GAME_API CliCommandHolder { - typedef void Print(void*, const char*); - typedef void CommandFinished(void*, bool success); + typedef void(*Print)(void*, char const*); + typedef void(*CommandFinished)(void*, bool success); void* m_callbackArg; - char *m_command; - Print* m_print; - - CommandFinished* m_commandFinished; - - CliCommandHolder(void* callbackArg, const char *command, Print* zprint, CommandFinished* commandFinished) - : m_callbackArg(callbackArg), m_command(strdup(command)), m_print(zprint), m_commandFinished(commandFinished) - { - } + char* m_command; + Print m_print; + CommandFinished m_commandFinished; - ~CliCommandHolder() { free(m_command); } + CliCommandHolder(void* callbackArg, char const* command, Print zprint, CommandFinished commandFinished); + ~CliCommandHolder(); private: CliCommandHolder(CliCommandHolder const& right) = delete; @@ -582,7 +576,7 @@ class TC_GAME_API World bool RemoveSession(uint32 id); /// Get the number of current active sessions void UpdateMaxSessionCounters(); - const SessionMap& GetAllSessions() const { return m_sessions; } + SessionMap const& GetAllSessions() const { return m_sessions; } uint32 GetActiveAndQueuedSessionCount() const { return m_sessions.size(); } uint32 GetActiveSessionCount() const { return m_sessions.size() - m_QueuedPlayer.size(); } uint32 GetQueuedSessionCount() const { return m_QueuedPlayer.size(); } @@ -656,9 +650,9 @@ class TC_GAME_API World void LoadConfigSettings(bool reload = false); void SendWorldText(uint32 string_id, ...); - void SendGlobalText(const char* text, WorldSession* self); + void SendGlobalText(char const* text, WorldSession* self); void SendGMText(uint32 string_id, ...); - void SendServerMessage(ServerMessageType type, const char *text = "", Player* player = NULL); + void SendServerMessage(ServerMessageType type, const char *text = "", Player* player = nullptr); void SendGlobalMessage(WorldPacket* packet, WorldSession* self = nullptr, uint32 team = 0); void SendGlobalGMMessage(WorldPacket* packet, WorldSession* self = nullptr, uint32 team = 0); bool SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self = nullptr, uint32 team = 0); @@ -669,7 +663,7 @@ class TC_GAME_API World uint32 GetShutDownTimeLeft() const { return m_ShutdownTimer; } void ShutdownServ(uint32 time, uint32 options, uint8 exitcode, const std::string& reason = std::string()); uint32 ShutdownCancel(); - void ShutdownMsg(bool show = false, Player* player = NULL, const std::string& reason = std::string()); + void ShutdownMsg(bool show = false, Player* player = nullptr, const std::string& reason = std::string()); static uint8 GetExitCode() { return m_ExitCode; } static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; } static bool IsStopped() { return m_stopEvent; } @@ -726,8 +720,8 @@ class TC_GAME_API World void LoadWorldStates(); /// Are we on a "Player versus Player" server? - bool IsPvPRealm() const { return (getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP); } - bool IsFFAPvPRealm() const { return getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP; } + bool IsPvPRealm() const; + bool IsFFAPvPRealm() const; void KickAll(); void KickAllLess(AccountTypes sec); diff --git a/src/server/scripts/Commands/cs_account.cpp b/src/server/scripts/Commands/cs_account.cpp index 0b8dc77cba2..82c3e716a8d 100644 --- a/src/server/scripts/Commands/cs_account.cpp +++ b/src/server/scripts/Commands/cs_account.cpp @@ -24,9 +24,14 @@ EndScriptData */ #include "AccountMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "Log.h" #include "Player.h" #include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" +#include class account_commandscript : public CommandScript { @@ -43,7 +48,7 @@ public: static std::vector accountSetCommandTable = { { "addon", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_ADDON, true, &HandleAccountSetAddonCommand, "" }, - { "sec", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_SEC, true, NULL, "", accountSetSecTable }, + { "sec", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_SEC, true, nullptr, "", accountSetSecTable }, { "gmlevel", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_GMLEVEL, true, &HandleAccountSetGmLevelCommand, "" }, { "password", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_PASSWORD, true, &HandleAccountSetPasswordCommand, "" }, }; @@ -59,14 +64,14 @@ public: { "delete", rbac::RBAC_PERM_COMMAND_ACCOUNT_DELETE, true, &HandleAccountDeleteCommand, "" }, { "email", rbac::RBAC_PERM_COMMAND_ACCOUNT_EMAIL, false, &HandleAccountEmailCommand, "" }, { "onlinelist", rbac::RBAC_PERM_COMMAND_ACCOUNT_ONLINE_LIST, true, &HandleAccountOnlineListCommand, "" }, - { "lock", rbac::RBAC_PERM_COMMAND_ACCOUNT_LOCK, false, NULL, "", accountLockCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET, true, NULL, "", accountSetCommandTable }, + { "lock", rbac::RBAC_PERM_COMMAND_ACCOUNT_LOCK, false, nullptr, "", accountLockCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET, true, nullptr, "", accountSetCommandTable }, { "password", rbac::RBAC_PERM_COMMAND_ACCOUNT_PASSWORD, false, &HandleAccountPasswordCommand, "" }, { "", rbac::RBAC_PERM_COMMAND_ACCOUNT, false, &HandleAccountCommand, "" }, }; static std::vector commandTable = { - { "account", rbac::RBAC_PERM_COMMAND_ACCOUNT, true, NULL, "", accountCommandTable }, + { "account", rbac::RBAC_PERM_COMMAND_ACCOUNT, true, nullptr, "", accountCommandTable }, }; return commandTable; } @@ -113,8 +118,8 @@ public: ///- %Parse the command line arguments char* accountName = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* possibleEmail = strtok(NULL, " ' "); + char* password = strtok(nullptr, " "); + char* possibleEmail = strtok(nullptr, " ' "); if (possibleEmail) email = possibleEmail; @@ -196,7 +201,7 @@ public: /// Commands not recommended call from chat, but support anyway /// can delete only for account with less security /// This is also reject self apply in fact - if (handler->HasLowerSecurityAccount(NULL, accountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, accountId, true)) return false; AccountOpResult result = AccountMgr::DeleteAccount(accountId); @@ -286,7 +291,7 @@ public: if (param == "on") { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGON_COUNTRY); - uint32 ip = inet_addr(handler->GetSession()->GetRemoteAddress().c_str()); + uint32 ip = boost::asio::ip::address_v4::from_string(handler->GetSession()->GetRemoteAddress()).to_ulong(); EndianConvertReverse(ip); stmt->setUInt32(0, ip); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -368,9 +373,9 @@ public: } char* oldEmail = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* email = strtok(NULL, " "); - char* emailConfirmation = strtok(NULL, " "); + char* password = strtok(nullptr, " "); + char* email = strtok(nullptr, " "); + char* emailConfirmation = strtok(nullptr, " "); if (!oldEmail || !password || !email || !emailConfirmation) { @@ -462,9 +467,9 @@ public: // Command is supposed to be: .account password [$oldpassword] [$newpassword] [$newpasswordconfirmation] [$emailconfirmation] char* oldPassword = strtok((char*)args, " "); // This extracts [$oldpassword] - char* newPassword = strtok(NULL, " "); // This extracts [$newpassword] - char* passwordConfirmation = strtok(NULL, " "); // This extracts [$newpasswordconfirmation] - char const* emailConfirmation = strtok(NULL, " "); // This defines the emailConfirmation variable, which is optional depending on sec type. + char* newPassword = strtok(nullptr, " "); // This extracts [$newpassword] + char* passwordConfirmation = strtok(nullptr, " "); // This extracts [$newpasswordconfirmation] + char const* emailConfirmation = strtok(nullptr, " "); // This defines the emailConfirmation variable, which is optional depending on sec type. if (!emailConfirmation) // This extracts [$emailconfirmation]. If it doesn't exist, however... emailConfirmation = ""; // ... it's simply "" for emailConfirmation. @@ -580,7 +585,7 @@ public: { ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* exp = strtok(NULL, " "); + char* exp = strtok(nullptr, " "); if (!account) return false; @@ -621,7 +626,7 @@ public: // Let set addon state only for lesser (strong) security level // or to self account if (handler->GetSession() && handler->GetSession()->GetAccountId() != accountId && - handler->HasLowerSecurityAccount(NULL, accountId, true)) + handler->HasLowerSecurityAccount(nullptr, accountId, true)) return false; int expansion = atoi(exp); //get int anyway (0 if error) @@ -653,8 +658,8 @@ public: uint32 targetSecurity = 0; uint32 gm = 0; char* arg1 = strtok((char*)args, " "); - char* arg2 = strtok(NULL, " "); - char* arg3 = strtok(NULL, " "); + char* arg2 = strtok(nullptr, " "); + char* arg3 = strtok(nullptr, " "); bool isAccountNameGiven = true; if (!arg3) @@ -689,7 +694,7 @@ public: return false; } - // handler->getSession() == NULL only for console + // handler->getSession() == nullptr only for console targetAccountId = (isAccountNameGiven) ? AccountMgr::GetId(targetAccountName) : handler->getSelectedPlayer()->GetSession()->GetAccountId(); int32 gmRealmID = (isAccountNameGiven) ? atoi(arg3) : atoi(arg2); uint32 playerSecurity; @@ -734,7 +739,7 @@ public: return false; } - rbac::RBACData* rbac = isAccountNameGiven ? NULL : handler->getSelectedPlayer()->GetSession()->GetRBACData(); + rbac::RBACData* rbac = isAccountNameGiven ? nullptr : handler->getSelectedPlayer()->GetSession()->GetRBACData(); sAccountMgr->UpdateAccountAccess(rbac, targetAccountId, uint8(gm), gmRealmID); handler->PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm); @@ -753,8 +758,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* passwordConfirmation = strtok(NULL, " "); + char* password = strtok(nullptr, " "); + char* passwordConfirmation = strtok(nullptr, " "); if (!account || !password || !passwordConfirmation) return false; @@ -777,7 +782,7 @@ public: /// can set password only for target with less security /// This also restricts setting handler's own password - if (handler->HasLowerSecurityAccount(NULL, targetAccountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, targetAccountId, true)) return false; if (strcmp(password, passwordConfirmation) != 0) @@ -818,8 +823,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* email = strtok(NULL, " "); - char* emailConfirmation = strtok(NULL, " "); + char* email = strtok(nullptr, " "); + char* emailConfirmation = strtok(nullptr, " "); if (!account || !email || !emailConfirmation) { @@ -846,7 +851,7 @@ public: /// can set email only for target with less security /// This also restricts setting handler's own email. - if (handler->HasLowerSecurityAccount(NULL, targetAccountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, targetAccountId, true)) return false; if (strcmp(email, emailConfirmation) != 0) @@ -894,8 +899,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* email = strtok(NULL, " "); - char* emailConfirmation = strtok(NULL, " "); + char* email = strtok(nullptr, " "); + char* emailConfirmation = strtok(nullptr, " "); if (!account || !email || !emailConfirmation) { @@ -922,7 +927,7 @@ public: /// can set email only for target with less security /// This also restricts setting handler's own email. - if (handler->HasLowerSecurityAccount(NULL, targetAccountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, targetAccountId, true)) return false; if (strcmp(email, emailConfirmation) != 0) diff --git a/src/server/scripts/Commands/cs_achievement.cpp b/src/server/scripts/Commands/cs_achievement.cpp index ddfd35e17e4..8b84a598708 100644 --- a/src/server/scripts/Commands/cs_achievement.cpp +++ b/src/server/scripts/Commands/cs_achievement.cpp @@ -22,11 +22,12 @@ Comment: All achievement related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AchievementMgr.h" #include "Chat.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" class achievement_commandscript : public CommandScript { @@ -41,7 +42,7 @@ public: }; static std::vector commandTable = { - { "achievement", rbac::RBAC_PERM_COMMAND_ACHIEVEMENT, false, NULL, "", achievementCommandTable }, + { "achievement", rbac::RBAC_PERM_COMMAND_ACHIEVEMENT, false, nullptr, "", achievementCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_ahbot.cpp b/src/server/scripts/Commands/cs_ahbot.cpp index 08fa562cdb6..fcbca458539 100644 --- a/src/server/scripts/Commands/cs_ahbot.cpp +++ b/src/server/scripts/Commands/cs_ahbot.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" +#include "AuctionHouseBot.h" #include "Chat.h" #include "Language.h" -#include "AuctionHouseBot.h" +#include "RBAC.h" -static const uint32 ahbotQualityIds[MAX_AUCTION_QUALITY] = +uint32 const ahbotQualityIds[MAX_AUCTION_QUALITY] = { LANG_AHBOT_QUALITY_GRAY, LANG_AHBOT_QUALITY_WHITE, LANG_AHBOT_QUALITY_GREEN, LANG_AHBOT_QUALITY_BLUE, @@ -57,8 +58,8 @@ public: static std::vector ahbotCommandTable = { - { "items", rbac::RBAC_PERM_COMMAND_AHBOT_ITEMS, true, NULL, "", ahbotItemsAmountCommandTable }, - { "ratio", rbac::RBAC_PERM_COMMAND_AHBOT_RATIO, true, NULL, "", ahbotItemsRatioCommandTable }, + { "items", rbac::RBAC_PERM_COMMAND_AHBOT_ITEMS, true, nullptr, "", ahbotItemsAmountCommandTable }, + { "ratio", rbac::RBAC_PERM_COMMAND_AHBOT_RATIO, true, nullptr, "", ahbotItemsRatioCommandTable }, { "rebuild", rbac::RBAC_PERM_COMMAND_AHBOT_REBUILD, true, &HandleAHBotRebuildCommand, "" }, { "reload", rbac::RBAC_PERM_COMMAND_AHBOT_RELOAD, true, &HandleAHBotReloadCommand, "" }, { "status", rbac::RBAC_PERM_COMMAND_AHBOT_STATUS, true, &HandleAHBotStatusCommand, "" }, @@ -66,13 +67,13 @@ public: static std::vector commandTable = { - { "ahbot", rbac::RBAC_PERM_COMMAND_AHBOT, false, NULL, "", ahbotCommandTable }, + { "ahbot", rbac::RBAC_PERM_COMMAND_AHBOT, false, nullptr, "", ahbotCommandTable }, }; return commandTable; } - static bool HandleAHBotItemsAmountCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsAmountCommand(ChatHandler* handler, char const* args) { uint32 qVals[MAX_AUCTION_QUALITY]; char* arg = strtok((char*)args, " "); @@ -81,7 +82,7 @@ public: if (!arg) return false; qVals[i] = atoi(arg); - arg = strtok(NULL, " "); + arg = strtok(nullptr, " "); } sAuctionBot->SetItemsAmount(qVals); @@ -93,7 +94,7 @@ public: } template - static bool HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const* args) { char* arg = strtok((char*)args, " "); if (!arg) @@ -107,7 +108,7 @@ public: return true; } - static bool HandleAHBotItemsRatioCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsRatioCommand(ChatHandler* handler, char const* args) { uint32 rVal[MAX_AUCTION_QUALITY]; char* arg = strtok((char*)args, " "); @@ -116,7 +117,7 @@ public: if (!arg) return false; rVal[i] = atoi(arg); - arg = strtok(NULL, " "); + arg = strtok(nullptr, " "); } sAuctionBot->SetItemsRatio(rVal[0], rVal[1], rVal[2]); @@ -127,7 +128,7 @@ public: } template - static bool HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const* args) { char* arg = strtok((char*)args, " "); if (!arg) @@ -139,7 +140,7 @@ public: return true; } - static bool HandleAHBotRebuildCommand(ChatHandler* /*handler*/, const char* args) + static bool HandleAHBotRebuildCommand(ChatHandler* /*handler*/, char const* args) { char* arg = strtok((char*)args, " "); @@ -151,14 +152,14 @@ public: return true; } - static bool HandleAHBotReloadCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleAHBotReloadCommand(ChatHandler* handler, char const* /*args*/) { sAuctionBot->ReloadAllConfig(); handler->SendSysMessage(LANG_AHBOT_RELOAD_OK); return true; } - static bool HandleAHBotStatusCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotStatusCommand(ChatHandler* handler, char const* args) { char* arg = strtok((char*)args, " "); if (!arg) @@ -227,17 +228,17 @@ public: }; -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); - -template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); + +template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const*); void AddSC_ahbot_commandscript() { diff --git a/src/server/scripts/Commands/cs_arena.cpp b/src/server/scripts/Commands/cs_arena.cpp index bfcb82d3eba..eef0b3c44f5 100644 --- a/src/server/scripts/Commands/cs_arena.cpp +++ b/src/server/scripts/Commands/cs_arena.cpp @@ -22,13 +22,16 @@ Comment: All arena team related commands Category: commandscripts EndScriptData */ -#include "ObjectMgr.h" +#include "ScriptMgr.h" +#include "ArenaTeamMgr.h" +#include "CharacterCache.h" #include "Chat.h" #include "Language.h" -#include "ArenaTeamMgr.h" +#include "Log.h" +#include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" -#include "CharacterCache.h" +#include "RBAC.h" +#include "WorldSession.h" class arena_commandscript : public CommandScript { @@ -48,7 +51,7 @@ public: }; static std::vector commandTable = { - { "arena", rbac::RBAC_PERM_COMMAND_ARENA, false, NULL, "", arenaCommandTable }, + { "arena", rbac::RBAC_PERM_COMMAND_ARENA, false, nullptr, "", arenaCommandTable }, }; return commandTable; } @@ -59,10 +62,10 @@ public: return false; Player* target; - if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : NULL, &target)) + if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : nullptr, &target)) return false; - char* tailStr = *args != '"' ? strtok(NULL, "") : (char*)args; + char* tailStr = *args != '"' ? strtok(nullptr, "") : (char*)args; if (!tailStr) return false; @@ -70,7 +73,7 @@ public: if (!name) return false; - char* typeStr = strtok(NULL, ""); + char* typeStr = strtok(nullptr, ""); if (!typeStr) return false; @@ -168,7 +171,7 @@ public: return false; } - char const* newArenaStr = handler->extractQuotedArg(strtok(NULL, "")); + char const* newArenaStr = handler->extractQuotedArg(strtok(nullptr, "")); if (!newArenaStr) { handler->SendSysMessage(LANG_BAD_VALUE); diff --git a/src/server/scripts/Commands/cs_ban.cpp b/src/server/scripts/Commands/cs_ban.cpp index 9ccb904f7b4..5c390a34e11 100644 --- a/src/server/scripts/Commands/cs_ban.cpp +++ b/src/server/scripts/Commands/cs_ban.cpp @@ -22,14 +22,17 @@ Comment: All ban related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" class ban_commandscript : public CommandScript { @@ -66,10 +69,10 @@ public: }; static std::vector commandTable = { - { "ban", rbac::RBAC_PERM_COMMAND_BAN, true, NULL, "", banCommandTable }, - { "baninfo", rbac::RBAC_PERM_COMMAND_BANINFO, true, NULL, "", baninfoCommandTable }, - { "banlist", rbac::RBAC_PERM_COMMAND_BANLIST, true, NULL, "", banlistCommandTable }, - { "unban", rbac::RBAC_PERM_COMMAND_UNBAN, true, NULL, "", unbanCommandTable }, + { "ban", rbac::RBAC_PERM_COMMAND_BAN, true, nullptr, "", banCommandTable }, + { "baninfo", rbac::RBAC_PERM_COMMAND_BANINFO, true, nullptr, "", baninfoCommandTable }, + { "banlist", rbac::RBAC_PERM_COMMAND_BANLIST, true, nullptr, "", banlistCommandTable }, + { "unban", rbac::RBAC_PERM_COMMAND_UNBAN, true, nullptr, "", unbanCommandTable }, }; return commandTable; } @@ -90,11 +93,11 @@ public: std::string name = nameStr; - char* durationStr = strtok(NULL, " "); + char* durationStr = strtok(nullptr, " "); if (!durationStr || !atoi(durationStr)) return false; - char* reasonStr = strtok(NULL, ""); + char* reasonStr = strtok(nullptr, ""); if (!reasonStr) return false; @@ -161,11 +164,11 @@ public: std::string nameOrIP = cnameOrIP; - char* durationStr = strtok(NULL, " "); + char* durationStr = strtok(nullptr, " "); if (!durationStr || !atoi(durationStr)) return false; - char* reasonStr = strtok(NULL, ""); + char* reasonStr = strtok(nullptr, ""); if (!reasonStr) return false; @@ -278,7 +281,7 @@ public: time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; - if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= time(NULL))) + if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= time(nullptr))) active = true; bool permanent = (fields[1].GetUInt64() == uint64(0)); std::string banTime = permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); @@ -336,7 +339,7 @@ public: Field* fields = result->Fetch(); time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; - if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= time(NULL))) + if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= time(nullptr))) active = true; bool permanent = (fields[1].GetUInt32() == uint32(0)); std::string banTime = permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt32(), true); @@ -382,7 +385,7 @@ public: static bool HandleBanListAccountCommand(ChatHandler* handler, char const* args) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); @@ -425,7 +428,7 @@ public: Field* fields = result->Fetch(); uint32 accountid = fields[0].GetUInt32(); - QueryResult banResult = LoginDatabase.PQuery("SELECT account.username FROM account, account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id", accountid); + QueryResult banResult = LoginDatabase.PQuery("SELECT account.username FROM account, account_banned WHERE account_banned.id='%u' AND account_banned.id = account.id", accountid); if (banResult) { Field* fields2 = banResult->Fetch(); @@ -584,7 +587,7 @@ public: static bool HandleBanListIPCommand(ChatHandler* handler, char const* args) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); diff --git a/src/server/scripts/Commands/cs_bf.cpp b/src/server/scripts/Commands/cs_bf.cpp index 6c4097a79b6..c2bcf60523d 100644 --- a/src/server/scripts/Commands/cs_bf.cpp +++ b/src/server/scripts/Commands/cs_bf.cpp @@ -23,8 +23,9 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "Chat.h" #include "BattlefieldMgr.h" +#include "Chat.h" +#include "RBAC.h" class bf_commandscript : public CommandScript { @@ -43,12 +44,12 @@ public: }; static std::vector commandTable = { - { "bf", rbac::RBAC_PERM_COMMAND_BF, false, NULL, "", battlefieldcommandTable }, + { "bf", rbac::RBAC_PERM_COMMAND_BF, false, nullptr, "", battlefieldcommandTable }, }; return commandTable; } - static bool HandleBattlefieldStart(ChatHandler* handler, const char* args) + static bool HandleBattlefieldStart(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -70,7 +71,7 @@ public: return true; } - static bool HandleBattlefieldEnd(ChatHandler* handler, const char* args) + static bool HandleBattlefieldEnd(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -92,7 +93,7 @@ public: return true; } - static bool HandleBattlefieldEnable(ChatHandler* handler, const char* args) + static bool HandleBattlefieldEnable(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -122,7 +123,7 @@ public: return true; } - static bool HandleBattlefieldSwitch(ChatHandler* handler, const char* args) + static bool HandleBattlefieldSwitch(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -143,14 +144,14 @@ public: return true; } - static bool HandleBattlefieldTimer(ChatHandler* handler, const char* args) + static bool HandleBattlefieldTimer(ChatHandler* handler, char const* args) { uint32 battleid = 0; uint32 time = 0; char* battleid_str = strtok((char*)args, " "); if (!battleid_str) return false; - char* time_str = strtok(NULL, " "); + char* time_str = strtok(nullptr, " "); if (!time_str) return false; diff --git a/src/server/scripts/Commands/cs_cast.cpp b/src/server/scripts/Commands/cs_cast.cpp index 7806c1e42cd..3143c44d567 100644 --- a/src/server/scripts/Commands/cs_cast.cpp +++ b/src/server/scripts/Commands/cs_cast.cpp @@ -27,6 +27,9 @@ EndScriptData */ #include "Creature.h" #include "Language.h" #include "Player.h" +#include "RBAC.h" +#include "SpellMgr.h" +#include "WorldSession.h" class cast_commandscript : public CommandScript { @@ -46,7 +49,7 @@ public: }; static std::vector commandTable = { - { "cast", rbac::RBAC_PERM_COMMAND_CAST, false, NULL, "", castCommandTable }, + { "cast", rbac::RBAC_PERM_COMMAND_CAST, false, nullptr, "", castCommandTable }, }; return commandTable; } @@ -91,7 +94,7 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -99,7 +102,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; handler->GetSession()->GetPlayer()->CastSpell(target, spellId, triggered); return true; @@ -123,7 +126,7 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -131,7 +134,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; caster->CastSpell(handler->GetSession()->GetPlayer(), spellId, triggered); return true; @@ -150,14 +153,14 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* distStr = strtok(NULL, " "); + char* distStr = strtok(nullptr, " "); float dist = 0; if (distStr) sscanf(distStr, "%f", &dist); - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -165,7 +168,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; float x, y, z; handler->GetSession()->GetPlayer()->GetClosePoint(x, y, z, dist); @@ -219,7 +222,7 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -227,7 +230,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; caster->CastSpell(caster->GetVictim(), spellId, triggered); return true; @@ -251,9 +254,9 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* posX = strtok(NULL, " "); - char* posY = strtok(NULL, " "); - char* posZ = strtok(NULL, " "); + char* posX = strtok(nullptr, " "); + char* posY = strtok(nullptr, " "); + char* posZ = strtok(nullptr, " "); if (!posX || !posY || !posZ) return false; @@ -262,7 +265,7 @@ public: float y = float(atof(posY)); float z = float(atof(posZ)); - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -270,7 +273,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; caster->CastSpell(x, y, z, spellId, triggered); return true; diff --git a/src/server/scripts/Commands/cs_character.cpp b/src/server/scripts/Commands/cs_character.cpp index 726e40db497..be11143c675 100644 --- a/src/server/scripts/Commands/cs_character.cpp +++ b/src/server/scripts/Commands/cs_character.cpp @@ -22,14 +22,20 @@ Comment: All character related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "PlayerDump.h" #include "Player.h" +#include "PlayerDump.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" class character_commandscript : public CommandScript { @@ -57,7 +63,7 @@ public: { "changefaction", rbac::RBAC_PERM_COMMAND_CHARACTER_CHANGEFACTION, true, &HandleCharacterChangeFactionCommand, "", }, { "changerace", rbac::RBAC_PERM_COMMAND_CHARACTER_CHANGERACE, true, &HandleCharacterChangeRaceCommand, "", }, { "changeaccount", rbac::RBAC_PERM_COMMAND_CHARACTER_CHANGEACCOUNT, true, &HandleCharacterChangeAccountCommand, "", }, - { "deleted", rbac::RBAC_PERM_COMMAND_CHARACTER_DELETED, true, NULL, "", characterDeletedCommandTable }, + { "deleted", rbac::RBAC_PERM_COMMAND_CHARACTER_DELETED, true, nullptr, "", characterDeletedCommandTable }, { "erase", rbac::RBAC_PERM_COMMAND_CHARACTER_ERASE, true, &HandleCharacterEraseCommand, "", }, { "level", rbac::RBAC_PERM_COMMAND_CHARACTER_LEVEL, true, &HandleCharacterLevelCommand, "", }, { "rename", rbac::RBAC_PERM_COMMAND_CHARACTER_RENAME, true, &HandleCharacterRenameCommand, "", }, @@ -67,9 +73,9 @@ public: static std::vector commandTable = { - { "character", rbac::RBAC_PERM_COMMAND_CHARACTER, true, NULL, "", characterCommandTable }, + { "character", rbac::RBAC_PERM_COMMAND_CHARACTER, true, nullptr, "", characterCommandTable }, { "levelup", rbac::RBAC_PERM_COMMAND_LEVELUP, false, &HandleLevelUpCommand, "" }, - { "pdump", rbac::RBAC_PERM_COMMAND_PDUMP, true, NULL, "", pdumpCommandTable }, + { "pdump", rbac::RBAC_PERM_COMMAND_PDUMP, true, nullptr, "", pdumpCommandTable }, }; return commandTable; } @@ -306,7 +312,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &target, &targetGuid, &targetName)) return false; - char const* newNameStr = strtok(NULL, " "); + char const* newNameStr = strtok(nullptr, " "); if (newNameStr) { @@ -324,7 +330,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; sCharacterCache->GetCharacterNameByGuid(targetGuid, playerOldName); @@ -410,7 +416,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; std::string oldNameLink = handler->playerLink(targetName); @@ -892,7 +898,7 @@ public: if (levelStr && isalpha(levelStr[0])) { nameStr = levelStr; - levelStr = NULL; // current level will be used + levelStr = nullptr; // current level will be used } Player* target; @@ -931,7 +937,7 @@ public: if (!fileStr) return false; - char* accountStr = strtok(NULL, " "); + char* accountStr = strtok(nullptr, " "); if (!accountStr) return false; @@ -962,8 +968,8 @@ public: return false; } - char* guidStr = NULL; - char* nameStr = strtok(NULL, " "); + char* guidStr = nullptr; + char* nameStr = strtok(nullptr, " "); std::string name; if (nameStr) @@ -984,7 +990,7 @@ public: return false; } - guidStr = strtok(NULL, " "); + guidStr = strtok(nullptr, " "); } ObjectGuid::LowType guid = 0; @@ -1039,7 +1045,7 @@ public: return false; char* fileStr = strtok((char*)args, " "); - char* playerStr = strtok(NULL, " "); + char* playerStr = strtok(nullptr, " "); if (!fileStr || !playerStr) return false; diff --git a/src/server/scripts/Commands/cs_cheat.cpp b/src/server/scripts/Commands/cs_cheat.cpp index 3e2a0bb2541..c37f5ea1372 100644 --- a/src/server/scripts/Commands/cs_cheat.cpp +++ b/src/server/scripts/Commands/cs_cheat.cpp @@ -22,10 +22,12 @@ Comment: All cheat related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class cheat_commandscript : public CommandScript { @@ -49,12 +51,12 @@ public: static std::vector commandTable = { - { "cheat", rbac::RBAC_PERM_COMMAND_CHEAT, false, NULL, "", cheatCommandTable }, + { "cheat", rbac::RBAC_PERM_COMMAND_CHEAT, false, nullptr, "", cheatCommandTable }, }; return commandTable; } - static bool HandleGodModeCheatCommand(ChatHandler* handler, const char* args) + static bool HandleGodModeCheatCommand(ChatHandler* handler, char const* args) { if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) return false; @@ -80,7 +82,7 @@ public: return false; } - static bool HandleCasttimeCheatCommand(ChatHandler* handler, const char* args) + static bool HandleCasttimeCheatCommand(ChatHandler* handler, char const* args) { if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) return false; @@ -106,7 +108,7 @@ public: return false; } - static bool HandleCoolDownCheatCommand(ChatHandler* handler, const char* args) + static bool HandleCoolDownCheatCommand(ChatHandler* handler, char const* args) { if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) return false; @@ -132,7 +134,7 @@ public: return false; } - static bool HandlePowerCheatCommand(ChatHandler* handler, const char* args) + static bool HandlePowerCheatCommand(ChatHandler* handler, char const* args) { if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) return false; @@ -158,12 +160,12 @@ public: return false; } - static bool HandleCheatStatusCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleCheatStatusCommand(ChatHandler* handler, char const* /*args*/) { Player* player = handler->GetSession()->GetPlayer(); - const char* enabled = "ON"; - const char* disabled = "OFF"; + char const* enabled = "ON"; + char const* disabled = "OFF"; handler->SendSysMessage(LANG_COMMAND_CHEAT_STATUS); handler->PSendSysMessage(LANG_COMMAND_CHEAT_GOD, player->GetCommandStatus(CHEAT_GOD) ? enabled : disabled); @@ -176,7 +178,7 @@ public: return true; } - static bool HandleWaterWalkCheatCommand(ChatHandler* handler, const char* args) + static bool HandleWaterWalkCheatCommand(ChatHandler* handler, char const* args) { if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) return false; @@ -204,7 +206,7 @@ public: return false; } - static bool HandleTaxiCheatCommand(ChatHandler* handler, const char* args) + static bool HandleTaxiCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; Player* chr = handler->getSelectedPlayer(); diff --git a/src/server/scripts/Commands/cs_debug.cpp b/src/server/scripts/Commands/cs_debug.cpp index 3e3215232fb..c7319760bc7 100644 --- a/src/server/scripts/Commands/cs_debug.cpp +++ b/src/server/scripts/Commands/cs_debug.cpp @@ -23,20 +23,20 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" +#include "Bag.h" +#include "BattlefieldMgr.h" #include "BattlegroundMgr.h" -#include "Chat.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "Chat.h" #include "GossipDef.h" -#include "Transport.h" +#include "GridNotifiersImpl.h" #include "Language.h" -#include "MapManager.h" +#include "Log.h" #include "M2Stores.h" -#include "BattlefieldMgr.h" - +#include "MapManager.h" +#include "ObjectMgr.h" +#include "RBAC.h" +#include "Transport.h" #include #include @@ -121,28 +121,27 @@ public: } uint32 cinematicId = atoul(args); - if (!sCinematicSequencesStore.LookupEntry(cinematicId)) + + CinematicSequencesEntry const* cineSeq = sCinematicSequencesStore.LookupEntry(cinematicId); + if (!cineSeq) { handler->PSendSysMessage(LANG_CINEMATIC_NOT_EXIST, cinematicId); handler->SetSentErrorMessage(true); return false; } + // Dump camera locations - if (CinematicSequencesEntry const* cineSeq = sCinematicSequencesStore.LookupEntry(cinematicId)) + if (std::vector const* flyByCameras = GetFlyByCameras(cineSeq->cinematicCamera)) { - std::unordered_map::const_iterator itr = sFlyByCameraStore.find(cineSeq->cinematicCamera); - if (itr != sFlyByCameraStore.end()) + handler->PSendSysMessage("Waypoints for sequence %u, camera %u", cinematicId, cineSeq->cinematicCamera); + uint32 count = 1; + for (FlyByCamera const& cam : *flyByCameras) { - handler->PSendSysMessage("Waypoints for sequence %u, camera %u", cinematicId, cineSeq->cinematicCamera); - uint32 count = 1 ; - for (FlyByCamera cam : itr->second) - { - handler->PSendSysMessage("%02u - %7ums [%f, %f, %f] Facing %f (%f degrees)", count, cam.timeStamp, cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w, cam.locations.w * (180 / M_PI)); - count++; - } - handler->PSendSysMessage("%u waypoints dumped", itr->second.size()); + handler->PSendSysMessage("%02u - %7ums [%s (%f degrees)]", count, cam.timeStamp, cam.locations.ToString().c_str(), cam.locations.GetOrientation() * (180 / M_PI)); + ++count; } + handler->PSendSysMessage("%u waypoints dumped", flyByCameras->size()); } handler->GetSession()->GetPlayer()->SendCinematicStart(cinematicId); @@ -250,10 +249,10 @@ public: if (failNum == 0 && *result != '0') return false; - char* fail1 = strtok(NULL, " "); + char* fail1 = strtok(nullptr, " "); uint8 failArg1 = fail1 ? (uint8)atoi(fail1) : 0; - char* fail2 = strtok(NULL, " "); + char* fail2 = strtok(nullptr, " "); uint8 failArg2 = fail2 ? (uint8)atoi(fail2) : 0; WorldPacket data(SMSG_CAST_FAILED, 5); @@ -266,7 +265,6 @@ public: data << uint32(failArg2); handler->GetSession()->SendPacket(&data); - return true; } @@ -276,7 +274,7 @@ public: return false; InventoryResult msg = InventoryResult(atoi(args)); - handler->GetSession()->GetPlayer()->SendEquipError(msg, NULL, NULL); + handler->GetSession()->GetPlayer()->SendEquipError(msg, nullptr, nullptr); return true; } @@ -303,7 +301,7 @@ public: static bool HandleDebugSendOpcodeCommand(ChatHandler* handler, char const* /*args*/) { Unit* unit = handler->getSelectedUnit(); - Player* player = NULL; + Player* player = nullptr; if (!unit || (unit->GetTypeId() != TYPEID_PLAYER)) player = handler->GetSession()->GetPlayer(); else @@ -466,7 +464,7 @@ public: } TC_LOG_DEBUG("network", "Sending opcode %u", data.GetOpcode()); data.hexlike(); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); handler->PSendSysMessage(LANG_COMMAND_OPCODESENT, data.GetOpcode(), unit->GetName().c_str()); return true; } @@ -474,7 +472,7 @@ public: static bool HandleDebugUpdateWorldStateCommand(ChatHandler* handler, char const* args) { char* w = strtok((char*)args, " "); - char* s = strtok(NULL, " "); + char* s = strtok(nullptr, " "); if (!w || !s) return false; @@ -692,7 +690,7 @@ public: continue; } - if (updateQueue[qp] == NULL) + if (updateQueue[qp] == nullptr) { handler->PSendSysMessage("The item with slot %d and guid %d has its queuepos (%d) pointing to NULL in the queue!", item->GetSlot(), item->GetGUID().GetCounter(), qp); error = true; @@ -760,7 +758,7 @@ public: continue; } - if (updateQueue[qp] == NULL) + if (updateQueue[qp] == nullptr) { handler->PSendSysMessage("The item in bag %d at slot %d having guid %d has a queuepos (%d) that points to NULL in the queue!", bag->GetSlot(), item2->GetSlot(), item2->GetGUID().GetCounter(), qp); error = true; @@ -809,7 +807,7 @@ public: Item* test = player->GetItemByPos(item->GetBagSlot(), item->GetSlot()); - if (test == NULL) + if (test == nullptr) { handler->PSendSysMessage("queue(%zu): The bag(%d) and slot(%d) values for %s are incorrect, the player doesn't have any item at that position!", i, item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString().c_str()); error = true; @@ -848,7 +846,7 @@ public: if (!target || target->IsTotem() || target->IsPet()) return false; - ThreatContainer::StorageType const &threatList = target->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatList = target->getThreatManager().getThreatList(); ThreatContainer::StorageType::const_iterator itr; uint32 count = 0; handler->PSendSysMessage("Threat list of %s (guid %u)", target->GetName().c_str(), target->GetGUID().GetCounter()); @@ -917,7 +915,7 @@ public: if (!i) return false; - char* j = strtok(NULL, " "); + char* j = strtok(nullptr, " "); uint32 entry = (uint32)atoi(i); int8 seatId = j ? (int8)atoi(j) : -1; @@ -926,7 +924,7 @@ public: handler->GetSession()->GetPlayer()->EnterVehicle(target, seatId); else { - Creature* passenger = NULL; + Creature* passenger = nullptr; Trinity::AllCreaturesOfEntryInRange check(handler->GetSession()->GetPlayer(), entry, 20.0f); Trinity::CreatureSearcher searcher(handler->GetSession()->GetPlayer(), passenger, check); Cell::VisitAllObjects(handler->GetSession()->GetPlayer(), searcher, 30.0f); @@ -945,7 +943,7 @@ public: return false; char* e = strtok((char*)args, " "); - char* i = strtok(NULL, " "); + char* i = strtok(nullptr, " "); if (!e) return false; @@ -987,7 +985,7 @@ public: static bool HandleDebugSendLargePacketCommand(ChatHandler* handler, char const* /*args*/) { - const char* stuffingString = "This is a dummy string to push the packet's size beyond 128000 bytes. "; + char const* stuffingString = "This is a dummy string to push the packet's size beyond 128000 bytes. "; std::ostringstream ss; while (ss.str().size() < 128000) ss << stuffingString; @@ -1011,7 +1009,7 @@ public: return false; char* e = strtok((char*)args, " "); - char* f = strtok(NULL, " "); + char* f = strtok(nullptr, " "); if (!e || !f) return false; @@ -1040,8 +1038,8 @@ public: return false; char* e = strtok((char*)args, " "); - char* f = strtok(NULL, " "); - char* g = strtok(NULL, " "); + char* f = strtok(nullptr, " "); + char* g = strtok(nullptr, " "); if (!e || !f || !g) return false; @@ -1147,8 +1145,8 @@ public: return false; char* x = strtok((char*)args, " "); - char* y = strtok(NULL, " "); - char* z = strtok(NULL, " "); + char* y = strtok(nullptr, " "); + char* z = strtok(nullptr, " "); if (!x || !y) return false; @@ -1196,7 +1194,7 @@ public: return false; char* x = strtok((char*)args, " "); - char* z = strtok(NULL, " "); + char* z = strtok(nullptr, " "); if (!x) return false; @@ -1242,7 +1240,7 @@ public: return false; char* x = strtok((char*)args, " "); - char* y = strtok(NULL, " "); + char* y = strtok(nullptr, " "); if (!x || !y) return false; @@ -1297,7 +1295,7 @@ public: else if (updateIndex >= UNIT_END) return true; - char* val = strtok(NULL, " "); + char* val = strtok(nullptr, " "); if (!val) { value = unit->GetUInt32Value(updateIndex); @@ -1329,7 +1327,7 @@ public: } char* x = strtok((char*)args, " "); - char* y = strtok(NULL, " "); + char* y = strtok(nullptr, " "); if (!x || !y) return false; @@ -1363,7 +1361,7 @@ public: if (!mask1) return false; - char* mask2 = strtok(NULL, " \n"); + char* mask2 = strtok(nullptr, " \n"); uint32 moveFlags = (uint32)atoi(mask1); @@ -1552,18 +1550,18 @@ public: static bool HandleDebugNearGraveyard(ChatHandler* handler, char const* args) { Player* player = handler->GetSession()->GetPlayer(); - const WorldSafeLocsEntry* nearestLoc = nullptr; + WorldSafeLocsEntry const* nearestLoc = nullptr; if (stricmp(args, "linked")) { if (Battleground* bg = player->GetBattleground()) - nearestLoc = bg->GetClosestGraveYard(player); + nearestLoc = bg->GetClosestGraveyard(player); else { if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId())) - nearestLoc = bf->GetClosestGraveYard(player); + nearestLoc = bf->GetClosestGraveyard(player); else - nearestLoc = sObjectMgr->GetClosestGraveYard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), player->GetTeam()); + nearestLoc = sObjectMgr->GetClosestGraveyard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), player->GetTeam()); } } else @@ -1575,7 +1573,7 @@ public: for (uint32 i = 0; i < sWorldSafeLocsStore.GetNumRows(); ++i) { - const WorldSafeLocsEntry* loc = sWorldSafeLocsStore.LookupEntry(i); + WorldSafeLocsEntry const* loc = sWorldSafeLocsStore.LookupEntry(i); if (loc && loc->map_id == player->GetMapId()) { float dist = (loc->x - x) * (loc->x - x) + (loc->y - y) * (loc->y - y) + (loc->z - z) * (loc->z - z); diff --git a/src/server/scripts/Commands/cs_deserter.cpp b/src/server/scripts/Commands/cs_deserter.cpp index d1778d14999..d3f298deaf7 100644 --- a/src/server/scripts/Commands/cs_deserter.cpp +++ b/src/server/scripts/Commands/cs_deserter.cpp @@ -22,10 +22,11 @@ * This file contains the CommandScripts for all deserter sub-commands */ +#include "ScriptMgr.h" #include "Chat.h" -#include "Player.h" #include "Language.h" -#include "ScriptMgr.h" +#include "Player.h" +#include "RBAC.h" #include "SpellAuras.h" enum Spells @@ -58,12 +59,12 @@ public: static std::vector deserterCommandTable = { - { "instance", rbac::RBAC_PERM_COMMAND_DESERTER_INSTANCE, false, NULL, "", deserterInstanceCommandTable }, - { "bg", rbac::RBAC_PERM_COMMAND_DESERTER_BG, false, NULL, "", deserterBGCommandTable }, + { "instance", rbac::RBAC_PERM_COMMAND_DESERTER_INSTANCE, false, nullptr, "", deserterInstanceCommandTable }, + { "bg", rbac::RBAC_PERM_COMMAND_DESERTER_BG, false, nullptr, "", deserterBGCommandTable }, }; static std::vector commandTable = { - { "deserter", rbac::RBAC_PERM_COMMAND_DESERTER, false, NULL, "", deserterCommandTable }, + { "deserter", rbac::RBAC_PERM_COMMAND_DESERTER, false, nullptr, "", deserterCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_disable.cpp b/src/server/scripts/Commands/cs_disable.cpp index 5863c2adebe..bc80d3d6fd0 100644 --- a/src/server/scripts/Commands/cs_disable.cpp +++ b/src/server/scripts/Commands/cs_disable.cpp @@ -22,14 +22,16 @@ Comment: All disable related commands Category: commandscripts EndScriptData */ -#include "DisableMgr.h" +#include "ScriptMgr.h" #include "AchievementMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" #include "Language.h" #include "ObjectMgr.h" #include "OutdoorPvP.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" #include "SpellMgr.h" class disable_commandscript : public CommandScript @@ -63,12 +65,12 @@ public: }; static std::vector disableCommandTable = { - { "add", rbac::RBAC_PERM_COMMAND_DISABLE_ADD, true, NULL, "", addDisableCommandTable }, - { "remove", rbac::RBAC_PERM_COMMAND_DISABLE_REMOVE, true, NULL, "", removeDisableCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_DISABLE_ADD, true, nullptr, "", addDisableCommandTable }, + { "remove", rbac::RBAC_PERM_COMMAND_DISABLE_REMOVE, true, nullptr, "", removeDisableCommandTable }, }; static std::vector commandTable = { - { "disable", rbac::RBAC_PERM_COMMAND_DISABLE, false, NULL, "", disableCommandTable }, + { "disable", rbac::RBAC_PERM_COMMAND_DISABLE, false, nullptr, "", disableCommandTable }, }; return commandTable; } @@ -79,10 +81,10 @@ public: if (!entryStr || !atoi(entryStr)) return false; - char* flagsStr = strtok(NULL, " "); + char* flagsStr = strtok(nullptr, " "); uint8 flags = flagsStr ? uint8(atoi(flagsStr)) : 0; - char* commentStr = strtok(NULL, ""); + char* commentStr = strtok(nullptr, ""); if (!commentStr) return false; @@ -185,7 +187,7 @@ public: break; } - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_DISABLES); stmt->setUInt32(0, entry); stmt->setUInt8(1, disableType); @@ -311,7 +313,7 @@ public: break; } - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_DISABLES); stmt->setUInt32(0, entry); stmt->setUInt8(1, disableType); diff --git a/src/server/scripts/Commands/cs_event.cpp b/src/server/scripts/Commands/cs_event.cpp index 05b49f9b4e7..3612bc17e66 100644 --- a/src/server/scripts/Commands/cs_event.cpp +++ b/src/server/scripts/Commands/cs_event.cpp @@ -22,11 +22,12 @@ Comment: All event related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "GameEventMgr.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" class event_commandscript : public CommandScript { @@ -44,7 +45,7 @@ public: }; static std::vector commandTable = { - { "event", rbac::RBAC_PERM_COMMAND_EVENT, false, NULL, "", eventCommandTable }, + { "event", rbac::RBAC_PERM_COMMAND_EVENT, false, nullptr, "", eventCommandTable }, }; return commandTable; } @@ -115,8 +116,8 @@ public: std::string endTimeStr = TimeToTimestampStr(eventData.end); uint32 delay = sGameEventMgr->NextCheck(eventId); - time_t nextTime = time(NULL) + delay; - std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(NULL) + delay) : "-"; + time_t nextTime = time(nullptr) + delay; + std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(nullptr) + delay) : "-"; std::string occurenceStr = secsToTimeString(eventData.occurence * MINUTE); std::string lengthStr = secsToTimeString(eventData.length * MINUTE); diff --git a/src/server/scripts/Commands/cs_gm.cpp b/src/server/scripts/Commands/cs_gm.cpp index 09048305449..0e514680552 100644 --- a/src/server/scripts/Commands/cs_gm.cpp +++ b/src/server/scripts/Commands/cs_gm.cpp @@ -23,13 +23,18 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" -#include "Chat.h" #include "AccountMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" -#include "World.h" -#include "Player.h" +#include "ObjectAccessor.h" #include "Opcodes.h" +#include "Player.h" +#include "Realm.h" +#include "World.h" +#include "WorldSession.h" +#include +#include class gm_commandscript : public CommandScript { @@ -49,7 +54,7 @@ public: }; static std::vector commandTable = { - { "gm", rbac::RBAC_PERM_COMMAND_GM, false, NULL, "", gmCommandTable }, + { "gm", rbac::RBAC_PERM_COMMAND_GM, false, nullptr, "", gmCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_go.cpp b/src/server/scripts/Commands/cs_go.cpp index cdeb07ee844..6a27060c2ed 100644 --- a/src/server/scripts/Commands/cs_go.cpp +++ b/src/server/scripts/Commands/cs_go.cpp @@ -23,13 +23,17 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" -#include "MapManager.h" -#include "TicketMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "MapManager.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "Player.h" +#include "RBAC.h" +#include "TicketMgr.h" #include "Transport.h" +#include "WorldSession.h" class go_commandscript : public CommandScript { @@ -54,7 +58,7 @@ public: static std::vector commandTable = { - { "go", rbac::RBAC_PERM_COMMAND_GO, false, NULL, "", goCommandTable }, + { "go", rbac::RBAC_PERM_COMMAND_GO, false, nullptr, "", goCommandTable }, }; return commandTable; } @@ -89,7 +93,7 @@ public: { // Get the "creature_template.entry" // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r - char* tail = strtok(NULL, ""); + char* tail = strtok(nullptr, ""); if (!tail) return false; char* id = handler->extractKeyFromLink(tail, "Hcreature_entry"); @@ -111,7 +115,7 @@ public: { std::string name = param1; WorldDatabase.EscapeString(name); - whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name " _LIKE_" '" << name << '\''; + whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name LIKE '" << name << '\''; } else whereClause << "WHERE guid = '" << guidLow << '\''; @@ -134,7 +138,7 @@ public: float o = fields[3].GetFloat(); uint32 mapId = fields[4].GetUInt16(); - Transport* transport = NULL; + Transport* transport = nullptr; if (!MapManager::IsValidMapCoord(mapId, x, y, z, o) || sObjectMgr->IsTransportMap(mapId)) { @@ -215,8 +219,8 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* gridX = strtok((char*)args, " "); - char* gridY = strtok(NULL, " "); - char* id = strtok(NULL, " "); + char* gridY = strtok(nullptr, " "); + char* id = strtok(nullptr, " "); if (!gridX || !gridY) return false; @@ -407,8 +411,8 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* zoneX = strtok((char*)args, " "); - char* zoneY = strtok(NULL, " "); - char* tail = strtok(NULL, ""); + char* zoneY = strtok(nullptr, " "); + char* tail = strtok(nullptr, ""); char* id = handler->extractKeyFromLink(tail, "Harea"); // string or [name] Shift-click form |color|Harea:area_id|h[name]|h|r @@ -480,10 +484,10 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* goX = strtok((char*)args, " "); - char* goY = strtok(NULL, " "); - char* goZ = strtok(NULL, " "); - char* id = strtok(NULL, " "); - char* port = strtok(NULL, " "); + char* goY = strtok(nullptr, " "); + char* goZ = strtok(nullptr, " "); + char* id = strtok(nullptr, " "); + char* port = strtok(nullptr, " "); if (!goX || !goY) return false; @@ -571,9 +575,9 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* goX = strtok((char*)args, " "); - char* goY = strtok(NULL, " "); - char* goZ = strtok(NULL, " "); - char* port = strtok(NULL, " "); + char* goY = strtok(nullptr, " "); + char* goZ = strtok(nullptr, " "); + char* port = strtok(nullptr, " "); float x, y, z, o; player->GetPosition(x, y, z, o); diff --git a/src/server/scripts/Commands/cs_gobject.cpp b/src/server/scripts/Commands/cs_gobject.cpp index dd636aa52da..a315355ff44 100644 --- a/src/server/scripts/Commands/cs_gobject.cpp +++ b/src/server/scripts/Commands/cs_gobject.cpp @@ -23,14 +23,20 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "GameEventMgr.h" -#include "ObjectMgr.h" -#include "PoolMgr.h" -#include "MapManager.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameEventMgr.h" #include "Language.h" -#include "Player.h" +#include "Log.h" +#include "MapManager.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" +#include "Player.h" +#include "PoolMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class gobject_commandscript : public CommandScript { @@ -58,12 +64,12 @@ public: { "near", rbac::RBAC_PERM_COMMAND_GOBJECT_NEAR, false, &HandleGameObjectNearCommand, "" }, { "target", rbac::RBAC_PERM_COMMAND_GOBJECT_TARGET, false, &HandleGameObjectTargetCommand, "" }, { "turn", rbac::RBAC_PERM_COMMAND_GOBJECT_TURN, false, &HandleGameObjectTurnCommand, "" }, - { "add", rbac::RBAC_PERM_COMMAND_GOBJECT_ADD, false, NULL, "", gobjectAddCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_GOBJECT_SET, false, NULL, "", gobjectSetCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_GOBJECT_ADD, false, nullptr, "", gobjectAddCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_GOBJECT_SET, false, nullptr, "", gobjectSetCommandTable }, }; static std::vector commandTable = { - { "gobject", rbac::RBAC_PERM_COMMAND_GOBJECT, false, NULL, "", gobjectCommandTable }, + { "gobject", rbac::RBAC_PERM_COMMAND_GOBJECT, false, nullptr, "", gobjectCommandTable }, }; return commandTable; } @@ -140,7 +146,7 @@ public: GameObject* object = new GameObject(); ObjectGuid::LowType guidLow = map->GenerateLowGuid(); - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); if (!object->Create(guidLow, objectInfo->entry, map, player->GetPhaseMaskForSpawn(), *player, rot, 255, GO_STATE_READY)) { delete object; @@ -188,13 +194,13 @@ public: Player* player = handler->GetSession()->GetPlayer(); - char* spawntime = strtok(NULL, " "); + char* spawntime = strtok(nullptr, " "); uint32 spawntm = 300; if (spawntime) spawntm = atoul(spawntime); - G3D::Quat rotation = G3D::Matrix3::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); + QuaternionData rotation = QuaternionData::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); uint32 objectId = atoul(id); if (!sObjectMgr->GetGameObjectTemplate(objectId)) @@ -233,7 +239,7 @@ public: WorldDatabase.EscapeString(name); result = WorldDatabase.PQuery( "SELECT guid, id, position_x, position_y, position_z, orientation, map, phaseMask, (POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ " - "FROM gameobject, gameobject_template WHERE gameobject_template.entry = gameobject.id AND map = %i AND name " _LIKE_" " _CONCAT3_("'%%'", "'%s'", "'%%'")" ORDER BY order_ ASC LIMIT 1", + "FROM gameobject LEFT JOIN gameobject_template ON gameobject_template.entry = gameobject.id WHERE map = %i AND name LIKE '%%%s%%' ORDER BY order_ ASC LIMIT 1", player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), name.c_str()); } } @@ -315,7 +321,7 @@ public: if (target) { - int32 curRespawnDelay = int32(target->GetRespawnTimeEx() - time(NULL)); + int32 curRespawnDelay = int32(target->GetRespawnTimeEx() - time(nullptr)); if (curRespawnDelay < 0) curRespawnDelay = 0; @@ -390,18 +396,18 @@ public: return false; } - char* orientation = strtok(NULL, " "); + char* orientation = strtok(nullptr, " "); float oz = 0.f, oy = 0.f, ox = 0.f; if (orientation) { oz = float(atof(orientation)); - orientation = strtok(NULL, " "); + orientation = strtok(nullptr, " "); if (orientation) { oy = float(atof(orientation)); - orientation = strtok(NULL, " "); + orientation = strtok(nullptr, " "); if (orientation) ox = float(atof(orientation)); } @@ -454,9 +460,9 @@ public: return false; } - char* toX = strtok(NULL, " "); - char* toY = strtok(NULL, " "); - char* toZ = strtok(NULL, " "); + char* toX = strtok(nullptr, " "); + char* toY = strtok(nullptr, " "); + char* toZ = strtok(nullptr, " "); float x, y, z; if (!toX) @@ -523,7 +529,7 @@ public: return false; } - char* phase = strtok (NULL, " "); + char* phase = strtok (nullptr, " "); uint32 phaseMask = phase ? atoul(phase) : 0; if (phaseMask == 0) { @@ -605,7 +611,7 @@ public: if (!cValue) return false; ObjectGuid::LowType guidLow = atoul(cValue); - const GameObjectData* data = sObjectMgr->GetGOData(guidLow); + GameObjectData const* data = sObjectMgr->GetGOData(guidLow); if (!data) return false; entry = data->id; @@ -663,7 +669,7 @@ public: return false; } - char* type = strtok(NULL, " "); + char* type = strtok(nullptr, " "); if (!type) return false; @@ -677,7 +683,7 @@ public: return true; } - char* state = strtok(NULL, " "); + char* state = strtok(nullptr, " "); if (!state) return false; diff --git a/src/server/scripts/Commands/cs_group.cpp b/src/server/scripts/Commands/cs_group.cpp index 49bb13f4786..ed69c88ee21 100644 --- a/src/server/scripts/Commands/cs_group.cpp +++ b/src/server/scripts/Commands/cs_group.cpp @@ -15,14 +15,20 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GroupMgr.h" #include "Language.h" #include "LFG.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "ObjectMgr.h" -#include "GroupMgr.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class group_commandscript : public CommandScript { @@ -292,7 +298,7 @@ public: ObjectGuid guidSource; ObjectGuid guidTarget; char* nameplgrStr = strtok((char*)args, " "); - char* nameplStr = strtok(NULL, " "); + char* nameplStr = strtok(nullptr, " "); if (!handler->GetPlayerGroupAndGUIDByName(nameplgrStr, playerSource, groupSource, guidSource, true)) return false; @@ -335,7 +341,7 @@ public: ObjectGuid guidTarget; std::string nameTarget; std::string zoneName; - const char* onlineState = ""; + char const* onlineState = ""; // Parse the guid to uint32... ObjectGuid parseGUID(HighGuid::Player, uint32(atoul(args))); diff --git a/src/server/scripts/Commands/cs_guild.cpp b/src/server/scripts/Commands/cs_guild.cpp index 6c47cbbc02f..95503183821 100644 --- a/src/server/scripts/Commands/cs_guild.cpp +++ b/src/server/scripts/Commands/cs_guild.cpp @@ -22,13 +22,15 @@ Comment: All guild related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" +#include "CharacterCache.h" #include "Chat.h" -#include "Language.h" #include "Guild.h" #include "GuildMgr.h" +#include "Language.h" #include "ObjectAccessor.h" -#include "ScriptMgr.h" -#include "CharacterCache.h" +#include "Player.h" +#include "RBAC.h" class guild_commandscript : public CommandScript { @@ -49,7 +51,7 @@ public: }; static std::vector commandTable = { - { "guild", rbac::RBAC_PERM_COMMAND_GUILD, true, NULL, "", guildCommandTable }, + { "guild", rbac::RBAC_PERM_COMMAND_GUILD, true, nullptr, "", guildCommandTable }, }; return commandTable; } @@ -69,10 +71,10 @@ public: // if not guild name only (in "") then player name Player* target; - if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : NULL, &target)) + if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : nullptr, &target)) return false; - char* tailStr = *args != '"' ? strtok(NULL, "") : (char*)args; + char* tailStr = *args != '"' ? strtok(nullptr, "") : (char*)args; if (!tailStr) return false; @@ -130,10 +132,10 @@ public: // if not guild name only (in "") then player name ObjectGuid targetGuid; - if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : NULL, NULL, &targetGuid)) + if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : nullptr, nullptr, &targetGuid)) return false; - char* tailStr = *args != '"' ? strtok(NULL, "") : (char*)args; + char* tailStr = *args != '"' ? strtok(nullptr, "") : (char*)args; if (!tailStr) return false; @@ -213,7 +215,7 @@ public: return false; } - char const* newGuildStr = handler->extractQuotedArg(strtok(NULL, "")); + char const* newGuildStr = handler->extractQuotedArg(strtok(nullptr, "")); if (!newGuildStr) { handler->SendSysMessage(LANG_INSERT_GUILD_NAME); diff --git a/src/server/scripts/Commands/cs_honor.cpp b/src/server/scripts/Commands/cs_honor.cpp index 4cff715fd2c..e0fc316ab70 100644 --- a/src/server/scripts/Commands/cs_honor.cpp +++ b/src/server/scripts/Commands/cs_honor.cpp @@ -22,11 +22,12 @@ Comment: All honor related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "Language.h" -#include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class honor_commandscript : public CommandScript { @@ -43,13 +44,13 @@ public: static std::vector honorCommandTable = { - { "add", rbac::RBAC_PERM_COMMAND_HONOR_ADD, false, NULL, "", honorAddCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_HONOR_ADD, false, nullptr, "", honorAddCommandTable }, { "update", rbac::RBAC_PERM_COMMAND_HONOR_UPDATE, false, &HandleHonorUpdateCommand, "" }, }; static std::vector commandTable = { - { "honor", rbac::RBAC_PERM_COMMAND_HONOR, false, NULL, "", honorCommandTable }, + { "honor", rbac::RBAC_PERM_COMMAND_HONOR, false, nullptr, "", honorCommandTable }, }; return commandTable; } @@ -72,7 +73,7 @@ public: return false; uint32 amount = (uint32)atoi(args); - target->RewardHonor(NULL, 1, amount); + target->RewardHonor(nullptr, 1, amount); return true; } diff --git a/src/server/scripts/Commands/cs_instance.cpp b/src/server/scripts/Commands/cs_instance.cpp index ff1a1c4da88..682976ba897 100644 --- a/src/server/scripts/Commands/cs_instance.cpp +++ b/src/server/scripts/Commands/cs_instance.cpp @@ -27,9 +27,13 @@ EndScriptData */ #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" +#include "Language.h" #include "MapManager.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" -#include "Language.h" +#include "RBAC.h" +#include "WorldSession.h" class instance_commandscript : public CommandScript { @@ -50,7 +54,7 @@ public: static std::vector commandTable = { - { "instance", rbac::RBAC_PERM_COMMAND_INSTANCE, true, NULL, "", instanceCommandTable }, + { "instance", rbac::RBAC_PERM_COMMAND_INSTANCE, true, nullptr, "", instanceCommandTable }, }; return commandTable; @@ -81,7 +85,7 @@ public: for (Player::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { InstanceSave* save = itr->second.save; - std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL)); + std::string timeleft = GetTimeString(save->GetResetTime() - time(nullptr)); handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", itr->second.extendState == EXTEND_STATE_EXPIRED ? "expired" : itr->second.extendState == EXTEND_STATE_EXTENDED ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); counter++; } @@ -97,7 +101,7 @@ public: for (Group::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { InstanceSave* save = itr->second.save; - std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL)); + std::string timeleft = GetTimeString(save->GetResetTime() - time(nullptr)); handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", "-", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); counter++; } @@ -118,7 +122,7 @@ public: player = handler->GetSession()->GetPlayer(); char* map = strtok((char*)args, " "); - char* pDiff = strtok(NULL, " "); + char* pDiff = strtok(nullptr, " "); int8 diff = -1; if (pDiff) diff = atoi(pDiff); @@ -140,7 +144,7 @@ public: InstanceSave* save = itr->second.save; if (itr->first != player->GetMapId() && (!MapId || MapId == itr->first) && (diff == -1 || diff == save->GetDifficulty())) { - std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL)); + std::string timeleft = GetTimeString(save->GetResetTime() - time(nullptr)); handler->PSendSysMessage(LANG_COMMAND_INST_UNBIND_UNBINDING, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); player->UnbindInstance(itr, Difficulty(i)); counter++; diff --git a/src/server/scripts/Commands/cs_learn.cpp b/src/server/scripts/Commands/cs_learn.cpp index 0e286357915..66e5865ee23 100644 --- a/src/server/scripts/Commands/cs_learn.cpp +++ b/src/server/scripts/Commands/cs_learn.cpp @@ -22,14 +22,17 @@ Comment: All learn related commands Category: commandscripts EndScriptData */ -#include "Chat.h" #include "ScriptMgr.h" -#include "ObjectMgr.h" +#include "Chat.h" +#include "DBCStores.h" #include "Language.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "Player.h" +#include "ObjectMgr.h" #include "Pet.h" +#include "Player.h" +#include "RBAC.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "WorldSession.h" class learn_commandscript : public CommandScript { @@ -48,7 +51,7 @@ public: static std::vector learnAllCommandTable = { - { "my", rbac::RBAC_PERM_COMMAND_LEARN_ALL_MY, false, NULL, "", learnAllMyCommandTable }, + { "my", rbac::RBAC_PERM_COMMAND_LEARN_ALL_MY, false, nullptr, "", learnAllMyCommandTable }, { "gm", rbac::RBAC_PERM_COMMAND_LEARN_ALL_GM, false, &HandleLearnAllGMCommand, "" }, { "crafts", rbac::RBAC_PERM_COMMAND_LEARN_ALL_CRAFTS, false, &HandleLearnAllCraftsCommand, "" }, { "default", rbac::RBAC_PERM_COMMAND_LEARN_ALL_DEFAULT, false, &HandleLearnAllDefaultCommand, "" }, @@ -58,13 +61,13 @@ public: static std::vector learnCommandTable = { - { "all", rbac::RBAC_PERM_COMMAND_LEARN_ALL, false, NULL, "", learnAllCommandTable }, + { "all", rbac::RBAC_PERM_COMMAND_LEARN_ALL, false, nullptr, "", learnAllCommandTable }, { "", rbac::RBAC_PERM_COMMAND_LEARN, false, &HandleLearnCommand, "" }, }; static std::vector commandTable = { - { "learn", rbac::RBAC_PERM_COMMAND_LEARN, false, NULL, "", learnCommandTable }, + { "learn", rbac::RBAC_PERM_COMMAND_LEARN, false, nullptr, "", learnCommandTable }, { "unlearn", rbac::RBAC_PERM_COMMAND_UNLEARN, false, &HandleUnLearnCommand, "" }, }; return commandTable; @@ -86,7 +89,7 @@ public: if (!spell || !sSpellMgr->GetSpellInfo(spell)) return false; - char const* all = strtok(NULL, " "); + char const* all = strtok(nullptr, " "); bool allRanks = all ? (strncmp(all, "all", strlen(all)) == 0) : false; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell); @@ -314,9 +317,9 @@ public: static bool HandleLearnAllLangCommand(ChatHandler* handler, char const* /*args*/) { - // skipping UNIVERSAL language (0) - for (uint8 i = 1; i < LANGUAGES_COUNT; ++i) - handler->GetSession()->GetPlayer()->LearnSpell(lang_description[i].spell_id, false); + for (LanguageDesc const& langDesc : lang_description) + if (uint32 langSpellId = langDesc.spell_id) + handler->GetSession()->GetPlayer()->LearnSpell(langSpellId, false); handler->SendSysMessage(LANG_COMMAND_LEARN_ALL_LANG); return true; @@ -384,7 +387,7 @@ public: std::string name; - SkillLineEntry const* targetSkillInfo = NULL; + SkillLineEntry const* targetSkillInfo = nullptr; for (uint32 i = 1; i < sSkillLineStore.GetNumRows(); ++i) { SkillLineEntry const* skillInfo = sSkillLineStore.LookupEntry(i); @@ -480,7 +483,7 @@ public: if (!spellId) return false; - char const* allStr = strtok(NULL, " "); + char const* allStr = strtok(nullptr, " "); bool allRanks = allStr ? (strncmp(allStr, "all", strlen(allStr)) == 0) : false; Player* target = handler->getSelectedPlayer(); diff --git a/src/server/scripts/Commands/cs_lfg.cpp b/src/server/scripts/Commands/cs_lfg.cpp index 56836ebf1e9..1e71c6c676d 100644 --- a/src/server/scripts/Commands/cs_lfg.cpp +++ b/src/server/scripts/Commands/cs_lfg.cpp @@ -18,12 +18,14 @@ #include "ScriptMgr.h" #include "CharacterCache.h" #include "Chat.h" -#include "Language.h" -#include "LFGMgr.h" -#include "ObjectMgr.h" +#include "DatabaseEnv.h" #include "Group.h" #include "GroupMgr.h" +#include "Language.h" +#include "LFGMgr.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "RBAC.h" void GetPlayerInfo(ChatHandler* handler, Player* player) { @@ -57,16 +59,16 @@ public: static std::vector commandTable = { - { "lfg", rbac::RBAC_PERM_COMMAND_LFG, true, NULL, "", lfgCommandTable }, + { "lfg", rbac::RBAC_PERM_COMMAND_LFG, true, nullptr, "", lfgCommandTable }, }; return commandTable; } static bool HandleLfgPlayerInfoCommand(ChatHandler* handler, char const* args) { - Player* target = NULL; + Player* target = nullptr; std::string playerName; - if (!handler->extractPlayerTarget((char*)args, &target, NULL, &playerName)) + if (!handler->extractPlayerTarget((char*)args, &target, nullptr, &playerName)) return false; GetPlayerInfo(handler, target); @@ -89,7 +91,7 @@ public: else if (!handler->extractPlayerTarget((char*)args, &playerTarget, &guidTarget, &nameTarget)) return false; - Group* groupTarget = NULL; + Group* groupTarget = nullptr; if (playerTarget) groupTarget = playerTarget->GetGroup(); diff --git a/src/server/scripts/Commands/cs_list.cpp b/src/server/scripts/Commands/cs_list.cpp index 299364aa998..8b502f60e11 100644 --- a/src/server/scripts/Commands/cs_list.cpp +++ b/src/server/scripts/Commands/cs_list.cpp @@ -23,14 +23,18 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" +#include "CharacterCache.h" #include "Chat.h" -#include "SpellAuraEffects.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "CharacterCache.h" -#include +#include "Random.h" +#include "RBAC.h" +#include "SpellAuraEffects.h" +#include "WorldSession.h" class list_commandscript : public CommandScript { @@ -49,7 +53,7 @@ public: }; static std::vector commandTable = { - { "list", rbac::RBAC_PERM_COMMAND_LIST,true, NULL, "", listCommandTable }, + { "list", rbac::RBAC_PERM_COMMAND_LIST,true, nullptr, "", listCommandTable }, }; return commandTable; } @@ -80,7 +84,7 @@ public: return false; } - char* countStr = strtok(NULL, " "); + char* countStr = strtok(nullptr, " "); uint32 count = countStr ? atoul(countStr) : 10; if (count == 0) @@ -152,7 +156,7 @@ public: return false; } - char* countStr = strtok(NULL, " "); + char* countStr = strtok(nullptr, " "); uint32 count = countStr ? atoul(countStr) : 10; if (count == 0) @@ -227,7 +231,7 @@ public: result = CharacterDatabase.Query(stmt); } else - result = PreparedQueryResult(NULL); + result = PreparedQueryResult(nullptr); if (result) { @@ -274,7 +278,7 @@ public: result = CharacterDatabase.Query(stmt); } else - result = PreparedQueryResult(NULL); + result = PreparedQueryResult(nullptr); if (result) { @@ -369,7 +373,7 @@ public: return false; } - char* countStr = strtok(NULL, " "); + char* countStr = strtok(nullptr, " "); uint32 count = countStr ? atoul(countStr) : 10; if (count == 0) @@ -470,7 +474,7 @@ public: Player* target; ObjectGuid targetGuid; std::string targetName; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; if (!*args) return false; diff --git a/src/server/scripts/Commands/cs_lookup.cpp b/src/server/scripts/Commands/cs_lookup.cpp index c507b4d607d..8250b5b5e80 100644 --- a/src/server/scripts/Commands/cs_lookup.cpp +++ b/src/server/scripts/Commands/cs_lookup.cpp @@ -22,15 +22,20 @@ Comment: All lookup related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GameEventMgr.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "World.h" +#include "WorldSession.h" class lookup_commandscript : public CommandScript { @@ -62,9 +67,9 @@ public: { "itemset", rbac::RBAC_PERM_COMMAND_LOOKUP_ITEMSET, true, &HandleLookupItemSetCommand, "" }, { "object", rbac::RBAC_PERM_COMMAND_LOOKUP_OBJECT, true, &HandleLookupObjectCommand, "" }, { "quest", rbac::RBAC_PERM_COMMAND_LOOKUP_QUEST, true, &HandleLookupQuestCommand, "" }, - { "player", rbac::RBAC_PERM_COMMAND_LOOKUP_PLAYER, true, NULL, "", lookupPlayerCommandTable }, + { "player", rbac::RBAC_PERM_COMMAND_LOOKUP_PLAYER, true, nullptr, "", lookupPlayerCommandTable }, { "skill", rbac::RBAC_PERM_COMMAND_LOOKUP_SKILL, true, &HandleLookupSkillCommand, "" }, - { "spell", rbac::RBAC_PERM_COMMAND_LOOKUP_SPELL, true, NULL, "", lookupSpellCommandTable }, + { "spell", rbac::RBAC_PERM_COMMAND_LOOKUP_SPELL, true, nullptr, "", lookupSpellCommandTable }, { "taxinode", rbac::RBAC_PERM_COMMAND_LOOKUP_TAXINODE, true, &HandleLookupTaxiNodeCommand, "" }, { "tele", rbac::RBAC_PERM_COMMAND_LOOKUP_TELE, true, &HandleLookupTeleCommand, "" }, { "title", rbac::RBAC_PERM_COMMAND_LOOKUP_TITLE, true, &HandleLookupTitleCommand, "" }, @@ -73,7 +78,7 @@ public: static std::vector commandTable = { - { "lookup", rbac::RBAC_PERM_COMMAND_LOOKUP, true, NULL, "", lookupCommandTable }, + { "lookup", rbac::RBAC_PERM_COMMAND_LOOKUP, true, nullptr, "", lookupCommandTable }, }; return commandTable; } @@ -312,7 +317,7 @@ public: FactionEntry const* factionEntry = sFactionStore.LookupEntry(id); if (factionEntry) { - FactionState const* factionState = target ? target->GetReputationMgr().GetState(factionEntry) : NULL; + FactionState const* factionState = target ? target->GetReputationMgr().GetState(factionEntry) : nullptr; int locale = handler->GetSessionDbcLocale(); std::string name = factionEntry->name[locale]; @@ -858,7 +863,7 @@ public: uint32 maxResults = sWorld->getIntConfig(CONFIG_MAX_RESULTS_LOOKUP_COMMANDS); // Search in Spell.dbc - for (uint32 id = 0; id < sSpellMgr->GetSpellInfoStoreSize(); id++) + for (uint32 id = 0; id < sSpellMgr->GetSpellInfoStoreSize(); ++id) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(id); if (spellInfo) @@ -1323,7 +1328,7 @@ public: else { ip = strtok((char*)args, " "); - limitStr = strtok(NULL, " "); + limitStr = strtok(nullptr, " "); limit = limitStr ? atoi(limitStr) : -1; } @@ -1340,7 +1345,7 @@ public: return false; std::string account = strtok((char*)args, " "); - char* limitStr = strtok(NULL, " "); + char* limitStr = strtok(nullptr, " "); int32 limit = limitStr ? atoi(limitStr) : -1; if (!Utf8ToUpperOnlyLatin @@ -1360,7 +1365,7 @@ public: return false; std::string email = strtok((char*)args, " "); - char* limitStr = strtok(NULL, " "); + char* limitStr = strtok(nullptr, " "); int32 limit = limitStr ? atoi(limitStr) : -1; PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL); diff --git a/src/server/scripts/Commands/cs_message.cpp b/src/server/scripts/Commands/cs_message.cpp index fe52ffc4a9a..f91155b949e 100644 --- a/src/server/scripts/Commands/cs_message.cpp +++ b/src/server/scripts/Commands/cs_message.cpp @@ -23,12 +23,18 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "Chat.h" #include "Channel.h" #include "ChannelMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Language.h" -#include "Player.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" +#include "Player.h" +#include "RBAC.h" +#include "World.h" +#include "WorldSession.h" class message_commandscript : public CommandScript { @@ -43,11 +49,11 @@ public: }; static std::vector channelCommandTable = { - { "set", rbac::RBAC_PERM_COMMAND_CHANNEL_SET, true, NULL, "", channelSetCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_CHANNEL_SET, true, nullptr, "", channelSetCommandTable }, }; static std::vector commandTable = { - { "channel", rbac::RBAC_PERM_COMMAND_CHANNEL, true, NULL, "", channelCommandTable }, + { "channel", rbac::RBAC_PERM_COMMAND_CHANNEL, true, nullptr, "", channelCommandTable }, { "nameannounce", rbac::RBAC_PERM_COMMAND_NAMEANNOUNCE, true, &HandleNameAnnounceCommand, "" }, { "gmnameannounce", rbac::RBAC_PERM_COMMAND_GMNAMEANNOUNCE, true, &HandleGMNameAnnounceCommand, "" }, { "announce", rbac::RBAC_PERM_COMMAND_ANNOUNCE, true, &HandleAnnounceCommand, "" }, @@ -232,7 +238,7 @@ public: if (argStr == "remove") { - std::string name = strtok(NULL, " "); + std::string name = strtok(nullptr, " "); if (normalizePlayerName(name)) { if (Player* player = ObjectAccessor::FindPlayerByName(name)) diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index 0a1b0f75a7b..29f1a0763fb 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -15,29 +15,45 @@ * with this program. If not, see . */ -#include "CharacterCache.h" -#include "Chat.h" #include "ScriptMgr.h" #include "AccountMgr.h" #include "ArenaTeamMgr.h" #include "CellImpl.h" +#include "CharacterCache.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" #include "GridNotifiers.h" #include "Group.h" +#include "GroupMgr.h" #include "InstanceSaveMgr.h" +#include "Item.h" #include "Language.h" +#include "LFG.h" +#include "Log.h" +#include "MMapFactory.h" #include "MovementGenerator.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" -#include "SpellAuras.h" -#include "TargetedMovementGenerator.h" -#include "WeatherMgr.h" -#include "Player.h" #include "Pet.h" -#include "LFG.h" -#include "GroupMgr.h" -#include "MMapFactory.h" -#include "DisableMgr.h" +#include "Player.h" +#include "Realm.h" +#include "SpellAuras.h" #include "SpellHistory.h" +#include "SpellMgr.h" +#include "TargetedMovementGenerator.h" #include "Transport.h" +#include "Weather.h" +#include "WeatherMgr.h" +#include "World.h" +#include "WorldSession.h" +#include + +// temporary hack until includes are sorted out (don't want to pull in Windows.h) +#ifdef GetClassName +#undef GetClassName +#endif class misc_commandscript : public CommandScript { @@ -410,7 +426,7 @@ public: { Group* group = _player->GetGroup(); // if no bind exists, create a solo bind - InstanceGroupBind* gBind = group ? group->GetBoundInstance(target) : NULL; // if no bind exists, create a solo bind + InstanceGroupBind* gBind = group ? group->GetBoundInstance(target) : nullptr; // if no bind exists, create a solo bind if (!gBind) if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(target->GetInstanceId())) _player->BindToInstance(save, !save->CanReset()); @@ -444,7 +460,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; std::string nameLink = handler->playerLink(targetName); @@ -573,7 +589,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; std::string nameLink = handler->playerLink(targetName); @@ -620,7 +636,7 @@ public: if (sWorld->getBoolConfig(CONFIG_DIE_COMMAND_MODE)) handler->GetSession()->GetPlayer()->Kill(target); else - handler->GetSession()->GetPlayer()->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + handler->GetSession()->GetPlayer()->DealDamage(target, target->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } return true; @@ -713,7 +729,7 @@ public: if (!param1) return false; - char const* param2 = strtok(NULL, " "); + char const* param2 = strtok(nullptr, " "); if (!param2) return false; @@ -906,9 +922,9 @@ public: // kick player static bool HandleKickPlayerCommand(ChatHandler* handler, char const* args) { - Player* target = NULL; + Player* target = nullptr; std::string playerName; - if (!handler->extractPlayerTarget((char*)args, &target, NULL, &playerName)) + if (!handler->extractPlayerTarget((char*)args, &target, nullptr, &playerName)) return false; if (handler->GetSession() && target == handler->GetSession()->GetPlayer()) @@ -925,8 +941,8 @@ public: std::string kickReasonStr = handler->GetTrinityString(LANG_NO_REASON); if (*args != '\0') { - char const* kickReason = strtok(NULL, "\r"); - if (kickReason != NULL) + char const* kickReason = strtok(nullptr, "\r"); + if (kickReason != nullptr) kickReasonStr = kickReason; } @@ -959,10 +975,10 @@ public: return false; std::string location_str = "inn"; - if (char const* loc = strtok(NULL, " ")) + if (char const* loc = strtok(nullptr, " ")) location_str = loc; - Player* player = NULL; + Player* player = nullptr; if (!handler->extractPlayerTarget(player_str, &player)) return false; @@ -1014,7 +1030,7 @@ public: uint32 team; - char* px2 = strtok(NULL, " "); + char* px2 = strtok(nullptr, " "); if (!px2) team = 0; @@ -1046,7 +1062,7 @@ public: return false; } - if (sObjectMgr->AddGraveYardLink(graveyardId, zoneId, team)) + if (sObjectMgr->AddGraveyardLink(graveyardId, zoneId, team)) handler->PSendSysMessage(LANG_COMMAND_GRAVEYARDLINKED, graveyardId, zoneId); else handler->PSendSysMessage(LANG_COMMAND_GRAVEYARDALRLINKED, graveyardId, zoneId); @@ -1072,12 +1088,12 @@ public: Player* player = handler->GetSession()->GetPlayer(); uint32 zone_id = player->GetZoneId(); - WorldSafeLocsEntry const* graveyard = sObjectMgr->GetClosestGraveYard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), team); + WorldSafeLocsEntry const* graveyard = sObjectMgr->GetClosestGraveyard(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), team); if (graveyard) { uint32 graveyardId = graveyard->ID; - GraveYardData const* data = sObjectMgr->FindGraveYardData(graveyardId, zone_id); + GraveyardData const* data = sObjectMgr->FindGraveyardData(graveyardId, zone_id); if (!data) { handler->PSendSysMessage(LANG_COMMAND_GRAVEYARDERROR, graveyardId); @@ -1229,12 +1245,12 @@ public: itemId = atoul(id); } - char const* ccount = strtok(NULL, " "); + char const* ccount = strtok(nullptr, " "); int32 count = 1; if (ccount) - count = strtol(ccount, NULL, 10); + count = strtol(ccount, nullptr, 10); if (count == 0) count = 1; @@ -1278,7 +1294,7 @@ public: return false; } - Item* item = playerTarget->StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = playerTarget->StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); // remove binding (let GM give it to another player later) if (player == playerTarget) @@ -1348,7 +1364,7 @@ public: } else { - player->SendEquipError(msg, NULL, NULL, itr->second.ItemId); + player->SendEquipError(msg, nullptr, nullptr, itr->second.ItemId); handler->PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itr->second.ItemId, 1); } } @@ -1385,7 +1401,7 @@ public: // *Change the weather of a cell char const* px = strtok((char*)args, " "); - char const* py = strtok(NULL, " "); + char const* py = strtok(nullptr, " "); if (!px || !py) return false; @@ -1435,11 +1451,11 @@ public: if (!skillStr) return false; - char const* levelStr = strtok(NULL, " "); + char const* levelStr = strtok(nullptr, " "); if (!levelStr) return false; - char const* maxPureSkill = strtok(NULL, " "); + char const* maxPureSkill = strtok(nullptr, " "); int32 skill = atoi(skillStr); if (skill <= 0) @@ -1508,7 +1524,7 @@ public: Player* target; ObjectGuid targetGuid; std::string targetName; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // To make sure we get a target, we convert our guid to an omniversal... ObjectGuid parseGUID(HighGuid::Player, uint32(atoul(args))); @@ -1633,7 +1649,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; // Query informations from the DB @@ -1684,7 +1700,7 @@ public: lastIp = fields[4].GetString(); lastLogin = fields[5].GetString(); - uint32 ip = inet_addr(lastIp.c_str()); + uint32 ip = boost::asio::ip::address_v4::from_string(lastIp).to_ulong(); EndianConvertReverse(ip); // If ip2nation table is populated, it displays the country @@ -1779,7 +1795,7 @@ public: // Output III. LANG_PINFO_BANNED if ban exists and is applied if (banTime >= 0) - handler->PSendSysMessage(LANG_PINFO_BANNED, banType.c_str(), banReason.c_str(), banTime > 0 ? secsToTimeString(banTime - time(NULL), true).c_str() : handler->GetTrinityString(LANG_PERMANENTLY), bannedBy.c_str()); + handler->PSendSysMessage(LANG_PINFO_BANNED, banType.c_str(), banReason.c_str(), banTime > 0 ? secsToTimeString(banTime - time(nullptr), true).c_str() : handler->GetTrinityString(LANG_PERMANENTLY), bannedBy.c_str()); // Output IV. LANG_PINFO_MUTED if mute is applied if (muteTime > 0) @@ -1910,9 +1926,9 @@ public: if (!delayStr) return false; - char const* muteReason = strtok(NULL, "\r"); + char const* muteReason = strtok(nullptr, "\r"); std::string muteReasonStr = handler->GetTrinityString(LANG_NO_REASON); - if (muteReason != NULL) + if (muteReason != nullptr) muteReasonStr = muteReason; Player* target; @@ -1944,7 +1960,7 @@ public: if (target) { // Target is online, mute will be in effect right away. - int64 muteTime = time(NULL) + notSpeakTime * MINUTE; + int64 muteTime = time(nullptr) + notSpeakTime * MINUTE; target->GetSession()->m_muteTime = muteTime; stmt->setInt64(0, muteTime); std::string nameLink = handler->playerLink(targetName); @@ -2131,7 +2147,7 @@ public: break; case CHASE_MOTION_TYPE: { - Unit* target = NULL; + Unit* target = nullptr; if (unit->GetTypeId() == TYPEID_PLAYER) target = static_cast const*>(movementGenerator)->GetTarget(); else @@ -2147,7 +2163,7 @@ public: } case FOLLOW_MOTION_TYPE: { - Unit* target = NULL; + Unit* target = nullptr; if (unit->GetTypeId() == TYPEID_PLAYER) target = static_cast const*>(movementGenerator)->GetTarget(); else @@ -2220,7 +2236,7 @@ public: if (strcmp(str, "go") == 0) { - char* guidStr = strtok(NULL, " "); + char* guidStr = strtok(nullptr, " "); if (!guidStr) { handler->SendSysMessage(LANG_BAD_VALUE); @@ -2236,7 +2252,7 @@ public: return false; } - char* damageStr = strtok(NULL, " "); + char* damageStr = strtok(nullptr, " "); if (!damageStr) { handler->SendSysMessage(LANG_BAD_VALUE); @@ -2301,12 +2317,12 @@ public: uint32 damage = damage_int; - char* schoolStr = strtok((char*)NULL, " "); + char* schoolStr = strtok((char*)nullptr, " "); // flat melee damage without resistence/etc reduction if (!schoolStr) { - handler->GetSession()->GetPlayer()->DealDamage(target, damage, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + handler->GetSession()->GetPlayer()->DealDamage(target, damage, nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); if (target != handler->GetSession()->GetPlayer()) handler->GetSession()->GetPlayer()->SendAttackStateUpdate (HITINFO_AFFECTS_VICTIM, target, 1, SPELL_SCHOOL_MASK_NORMAL, damage, 0, 0, VICTIMSTATE_HIT, 0); return true; @@ -2319,9 +2335,9 @@ public: SpellSchoolMask schoolmask = SpellSchoolMask(1 << school); if (Unit::IsDamageReducedByArmor(schoolmask)) - damage = handler->GetSession()->GetPlayer()->CalcArmorReducedDamage(target, damage, NULL, BASE_ATTACK); + damage = handler->GetSession()->GetPlayer()->CalcArmorReducedDamage(target, damage, nullptr, BASE_ATTACK); - char* spellStr = strtok((char*)NULL, " "); + char* spellStr = strtok((char*)nullptr, " "); // melee damage by specific school if (!spellStr) @@ -2368,7 +2384,7 @@ public: static bool HandleCombatStopCommand(ChatHandler* handler, char const* args) { - Player* target = NULL; + Player* target = nullptr; if (args && args[0] != '\0') { @@ -2448,7 +2464,7 @@ public: { // Get the args that we might have (up to 2) char const* arg1 = strtok((char*)args, " "); - char const* arg2 = strtok(NULL, " "); + char const* arg2 = strtok(nullptr, " "); // Analyze them to see if we got either a playerName or duration or both if (arg1) diff --git a/src/server/scripts/Commands/cs_mmaps.cpp b/src/server/scripts/Commands/cs_mmaps.cpp index acee88ce4d5..4a709de2560 100644 --- a/src/server/scripts/Commands/cs_mmaps.cpp +++ b/src/server/scripts/Commands/cs_mmaps.cpp @@ -24,18 +24,17 @@ */ #include "ScriptMgr.h" +#include "CellImpl.h" #include "Chat.h" #include "DisableMgr.h" -#include "ObjectMgr.h" +#include "GridNotifiersImpl.h" +#include "Map.h" +#include "MMapFactory.h" +#include "PathGenerator.h" #include "Player.h" #include "PointMovementGenerator.h" -#include "PathGenerator.h" -#include "MMapFactory.h" -#include "Map.h" +#include "RBAC.h" #include "TargetedMovementGenerator.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" class mmaps_commandscript : public CommandScript { @@ -55,7 +54,7 @@ public: static std::vector commandTable = { - { "mmap", rbac::RBAC_PERM_COMMAND_MMAP, true, NULL, "", mmapCommandTable }, + { "mmap", rbac::RBAC_PERM_COMMAND_MMAP, true, nullptr, "", mmapCommandTable }, }; return commandTable; } @@ -103,9 +102,9 @@ public: handler->PSendSysMessage("Building: %s", useStraightPath ? "StraightPath" : useStraightLine ? "Raycast" : "SmoothPath"); handler->PSendSysMessage("Result: %s - Length: %zu - Type: %u", (result ? "true" : "false"), pointPath.size(), path.GetPathType()); - G3D::Vector3 const &start = path.GetStartPosition(); - G3D::Vector3 const &end = path.GetEndPosition(); - G3D::Vector3 const &actualEnd = path.GetActualEndPosition(); + G3D::Vector3 const& start = path.GetStartPosition(); + G3D::Vector3 const& end = path.GetEndPosition(); + G3D::Vector3 const& actualEnd = path.GetActualEndPosition(); handler->PSendSysMessage("StartPosition (%.3f, %.3f, %.3f)", start.x, start.y, start.z); handler->PSendSysMessage("EndPosition (%.3f, %.3f, %.3f)", end.x, end.y, end.z); @@ -156,7 +155,7 @@ public: // navmesh poly -> navmesh tile location dtQueryFilter filter = dtQueryFilter(); dtPolyRef polyRef = INVALID_POLYREF; - if (dtStatusFailed(navmeshquery->findNearestPoly(location, extents, &filter, &polyRef, NULL))) + if (dtStatusFailed(navmeshquery->findNearestPoly(location, extents, &filter, &polyRef, nullptr))) { handler->PSendSysMessage("Dt [??,??] (invalid poly, probably no tile loaded)"); return true; diff --git a/src/server/scripts/Commands/cs_modify.cpp b/src/server/scripts/Commands/cs_modify.cpp index 5b2507482dd..af8e5c12268 100644 --- a/src/server/scripts/Commands/cs_modify.cpp +++ b/src/server/scripts/Commands/cs_modify.cpp @@ -22,14 +22,17 @@ Comment: All modify related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DBCStores.h" +#include "Log.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Pet.h" #include "Player.h" +#include "RBAC.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" - +#include "WorldSession.h" class modify_commandscript : public CommandScript { @@ -65,7 +68,7 @@ public: { "reputation", rbac::RBAC_PERM_COMMAND_MODIFY_REPUTATION, false, &HandleModifyRepCommand, "" }, { "runicpower", rbac::RBAC_PERM_COMMAND_MODIFY_RUNICPOWER, false, &HandleModifyRunicPowerCommand, "" }, { "scale", rbac::RBAC_PERM_COMMAND_MODIFY_SCALE, false, &HandleModifyScaleCommand, "" }, - { "speed", rbac::RBAC_PERM_COMMAND_MODIFY_SPEED, false, NULL, "", modifyspeedCommandTable }, + { "speed", rbac::RBAC_PERM_COMMAND_MODIFY_SPEED, false, nullptr, "", modifyspeedCommandTable }, { "spell", rbac::RBAC_PERM_COMMAND_MODIFY_SPELL, false, &HandleModifySpellCommand, "" }, { "standstate", rbac::RBAC_PERM_COMMAND_MODIFY_STANDSTATE, false, &HandleModifyStandStateCommand, "" }, { "talentpoints", rbac::RBAC_PERM_COMMAND_MODIFY_TALENTPOINTS, false, &HandleModifyTalentCommand, "" }, @@ -75,7 +78,7 @@ public: { { "morph", rbac::RBAC_PERM_COMMAND_MORPH, false, &HandleModifyMorphCommand, "" }, { "demorph", rbac::RBAC_PERM_COMMAND_DEMORPH, false, &HandleDeMorphCommand, "" }, - { "modify", rbac::RBAC_PERM_COMMAND_MODIFY, false, NULL, "", modifyCommandTable }, + { "modify", rbac::RBAC_PERM_COMMAND_MODIFY, false, nullptr, "", modifyCommandTable }, }; return commandTable; } @@ -91,7 +94,7 @@ public: } } - static bool CheckModifyResources(ChatHandler* handler, const char* args, Player* target, int32& res, int32& resmax, int8 const multiplier = 1) + static bool CheckModifyResources(ChatHandler* handler, char const* args, Player* target, int32& res, int32& resmax, int8 const multiplier = 1) { if (!*args) return false; @@ -120,7 +123,7 @@ public: } //Edit Player HP - static bool HandleModifyHPCommand(ChatHandler* handler, const char* args) + static bool HandleModifyHPCommand(ChatHandler* handler, char const* args) { int32 hp, hpmax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -135,7 +138,7 @@ public: } //Edit Player Mana - static bool HandleModifyManaCommand(ChatHandler* handler, const char* args) + static bool HandleModifyManaCommand(ChatHandler* handler, char const* args) { int32 mana, manamax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -151,7 +154,7 @@ public: } //Edit Player Energy - static bool HandleModifyEnergyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyEnergyCommand(ChatHandler* handler, char const* args) { int32 energy, energymax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -168,7 +171,7 @@ public: } //Edit Player Rage - static bool HandleModifyRageCommand(ChatHandler* handler, const char* args) + static bool HandleModifyRageCommand(ChatHandler* handler, char const* args) { int32 rage, ragemax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -184,7 +187,7 @@ public: } // Edit Player Runic Power - static bool HandleModifyRunicPowerCommand(ChatHandler* handler, const char* args) + static bool HandleModifyRunicPowerCommand(ChatHandler* handler, char const* args) { int32 rune, runemax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -200,7 +203,7 @@ public: } //Edit Player Faction - static bool HandleModifyFactionCommand(ChatHandler* handler, const char* args) + static bool HandleModifyFactionCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -228,13 +231,13 @@ public: uint32 factionid = atoi(pfactionid); uint32 flag; - char *pflag = strtok(NULL, " "); + char *pflag = strtok(nullptr, " "); if (!pflag) flag = target->GetUInt32Value(UNIT_FIELD_FLAGS); else flag = atoi(pflag); - char* pnpcflag = strtok(NULL, " "); + char* pnpcflag = strtok(nullptr, " "); uint32 npcflag; if (!pnpcflag) @@ -242,7 +245,7 @@ public: else npcflag = atoi(pnpcflag); - char* pdyflag = strtok(NULL, " "); + char* pdyflag = strtok(nullptr, " "); uint32 dyflag; if (!pdyflag) @@ -268,7 +271,7 @@ public: } //Edit Player Spell - static bool HandleModifySpellCommand(ChatHandler* handler, const char* args) + static bool HandleModifySpellCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -277,17 +280,17 @@ public: if (!pspellflatid) return false; - char* pop = strtok(NULL, " "); + char* pop = strtok(nullptr, " "); if (!pop) return false; - char* pval = strtok(NULL, " "); + char* pval = strtok(nullptr, " "); if (!pval) return false; uint16 mark; - char* pmark = strtok(NULL, " "); + char* pmark = strtok(nullptr, " "); uint8 spellflatid = atoi(pspellflatid); uint8 op = atoi(pop); @@ -298,7 +301,7 @@ public: mark = atoi(pmark); Player* target = handler->getSelectedPlayerOrSelf(); - if (target == NULL) + if (target == nullptr) { handler->SendSysMessage(LANG_NO_CHAR_SELECTED); handler->SetSentErrorMessage(true); @@ -318,13 +321,13 @@ public: data << uint8(op); data << uint16(val); data << uint16(mark); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); return true; } //Edit Player TP - static bool HandleModifyTalentCommand (ChatHandler* handler, const char* args) + static bool HandleModifyTalentCommand (ChatHandler* handler, char const* args) { if (!*args) return false; @@ -369,7 +372,7 @@ public: return false; } - static bool CheckModifySpeed(ChatHandler* handler, const char* args, Unit* target, float& speed, float minimumBound, float maximumBound, bool checkInFlight = true) + static bool CheckModifySpeed(ChatHandler* handler, char const* args, Unit* target, float& speed, float minimumBound, float maximumBound, bool checkInFlight = true) { if (!*args) return false; @@ -407,7 +410,7 @@ public: } //Edit Player Aspeed - static bool HandleModifyASpeedCommand(ChatHandler* handler, const char* args) + static bool HandleModifyASpeedCommand(ChatHandler* handler, char const* args) { float allSpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -424,7 +427,7 @@ public: } //Edit Player Speed - static bool HandleModifySpeedCommand(ChatHandler* handler, const char* args) + static bool HandleModifySpeedCommand(ChatHandler* handler, char const* args) { float Speed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -438,7 +441,7 @@ public: } //Edit Player Swim Speed - static bool HandleModifySwimCommand(ChatHandler* handler, const char* args) + static bool HandleModifySwimCommand(ChatHandler* handler, char const* args) { float swimSpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -452,7 +455,7 @@ public: } //Edit Player Backwards Walk Speed - static bool HandleModifyBWalkCommand(ChatHandler* handler, const char* args) + static bool HandleModifyBWalkCommand(ChatHandler* handler, char const* args) { float backSpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -466,7 +469,7 @@ public: } //Edit Player Fly - static bool HandleModifyFlyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyFlyCommand(ChatHandler* handler, char const* args) { float flySpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -480,7 +483,7 @@ public: } //Edit Player or Creature Scale - static bool HandleModifyScaleCommand(ChatHandler* handler, const char* args) + static bool HandleModifyScaleCommand(ChatHandler* handler, char const* args) { float Scale; Unit* target = handler->getSelectedUnit(); @@ -494,7 +497,7 @@ public: } //Enable Player mount - static bool HandleModifyMountCommand(ChatHandler* handler, const char* args) + static bool HandleModifyMountCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -753,7 +756,7 @@ public: } //Edit Player money - static bool HandleModifyMoneyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyMoneyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -817,7 +820,7 @@ public: } //Edit Unit field - static bool HandleModifyBitCommand(ChatHandler* handler, const char* args) + static bool HandleModifyBitCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -838,7 +841,7 @@ public: if (!pField) return false; - char* pBit = strtok(NULL, " "); + char* pBit = strtok(nullptr, " "); if (!pBit) return false; @@ -871,7 +874,7 @@ public: return true; } - static bool HandleModifyHonorCommand (ChatHandler* handler, const char* args) + static bool HandleModifyHonorCommand (ChatHandler* handler, char const* args) { if (!*args) return false; @@ -897,7 +900,7 @@ public: return true; } - static bool HandleModifyDrunkCommand(ChatHandler* handler, const char* args) + static bool HandleModifyDrunkCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -912,7 +915,7 @@ public: return true; } - static bool HandleModifyRepCommand(ChatHandler* handler, const char* args) + static bool HandleModifyRepCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -936,7 +939,7 @@ public: uint32 factionId = atoi(factionTxt); int32 amount = 0; - char *rankTxt = strtok(NULL, " "); + char *rankTxt = strtok(nullptr, " "); if (!factionId || !rankTxt) return false; @@ -965,7 +968,7 @@ public: if (wrank.substr(0, wrankStr.size()) == wrankStr) { - char *deltaTxt = strtok(NULL, " "); + char *deltaTxt = strtok(nullptr, " "); if (deltaTxt) { int32 delta = atoi(deltaTxt); @@ -1013,7 +1016,7 @@ public: } //morph creature or player - static bool HandleModifyMorphCommand(ChatHandler* handler, const char* args) + static bool HandleModifyMorphCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -1034,7 +1037,7 @@ public: } //set temporary phase mask for player - static bool HandleModifyPhaseCommand(ChatHandler* handler, const char* args) + static bool HandleModifyPhaseCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -1055,7 +1058,7 @@ public: } //change standstate - static bool HandleModifyStandStateCommand(ChatHandler* handler, const char* args) + static bool HandleModifyStandStateCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -1066,7 +1069,7 @@ public: return true; } - static bool HandleModifyArenaCommand(ChatHandler* handler, const char* args) + static bool HandleModifyArenaCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -1088,7 +1091,7 @@ public: return true; } - static bool HandleModifyGenderCommand(ChatHandler* handler, const char* args) + static bool HandleModifyGenderCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -1149,7 +1152,7 @@ public: return true; } //demorph player or unit - static bool HandleDeMorphCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleDeMorphCommand(ChatHandler* handler, char const* /*args*/) { Unit* target = handler->getSelectedUnit(); if (!target) @@ -1165,7 +1168,7 @@ public: } // mod xp command - static bool HandleModifyXPCommand(ChatHandler *handler, const char* args) + static bool HandleModifyXPCommand(ChatHandler *handler, char const* args) { if (!*args) return false; diff --git a/src/server/scripts/Commands/cs_npc.cpp b/src/server/scripts/Commands/cs_npc.cpp index 5eea88f13c8..dfb9ddb66a6 100644 --- a/src/server/scripts/Commands/cs_npc.cpp +++ b/src/server/scripts/Commands/cs_npc.cpp @@ -23,15 +23,22 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" #include "Chat.h" -#include "Transport.h" +#include "CreatureAI.h" #include "CreatureGroups.h" +#include "DatabaseEnv.h" #include "Language.h" -#include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand -#include "CreatureAI.h" -#include "Player.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Pet.h" +#include "Player.h" +#include "RBAC.h" +#include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand +#include "Transport.h" +#include "World.h" +#include "WorldSession.h" template struct EnumName @@ -683,7 +690,7 @@ public: uint32 nativeid = target->GetNativeDisplayId(); uint32 Entry = target->GetEntry(); - int64 curRespawnDelay = target->GetRespawnTimeEx()-time(NULL); + int64 curRespawnDelay = target->GetRespawnTimeEx()-time(nullptr); if (curRespawnDelay < 0) curRespawnDelay = 0; std::string curRespawnDelayStr = secsToTimeString(uint64(curRespawnDelay), true); @@ -1457,7 +1464,7 @@ public: if (!name) name = "Unknown item"; handler->PSendSysMessage(alternateString ? LANG_COMMAND_NPC_SHOWLOOT_ENTRY_2 : LANG_COMMAND_NPC_SHOWLOOT_ENTRY, - itemCount, ItemQualityColors[itemTemplate ? itemTemplate->Quality : ITEM_QUALITY_POOR], itemId, name, itemId); + itemCount, ItemQualityColors[itemTemplate ? itemTemplate->Quality : uint32(ITEM_QUALITY_POOR)], itemId, name, itemId); } static void _IterateNotNormalLootMap(ChatHandler* handler, NotNormalLootItemMap const& map, std::vector const& items) { diff --git a/src/server/scripts/Commands/cs_pet.cpp b/src/server/scripts/Commands/cs_pet.cpp index 552bf15d0c4..3f75e44b5ca 100644 --- a/src/server/scripts/Commands/cs_pet.cpp +++ b/src/server/scripts/Commands/cs_pet.cpp @@ -15,14 +15,19 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "Chat.h" #include "Language.h" +#include "Log.h" +#include "Map.h" +#include "ObjectMgr.h" #include "Pet.h" #include "Player.h" -#include "ObjectMgr.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "SpellMgr.h" +#include "WorldSession.h" -static inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) +inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) { if (Unit* target = handler->getSelectedUnit()) { @@ -35,6 +40,7 @@ static inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) Player* player = handler->GetSession()->GetPlayer(); return player ? player->GetPet() : nullptr; } + class pet_commandscript : public CommandScript { public: @@ -52,7 +58,7 @@ public: static std::vector commandTable = { - { "pet", rbac::RBAC_PERM_COMMAND_PET, false, NULL, "", petCommandTable }, + { "pet", rbac::RBAC_PERM_COMMAND_PET, false, nullptr, "", petCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_quest.cpp b/src/server/scripts/Commands/cs_quest.cpp index 36134848d81..cd21909a872 100644 --- a/src/server/scripts/Commands/cs_quest.cpp +++ b/src/server/scripts/Commands/cs_quest.cpp @@ -22,11 +22,15 @@ Comment: All quest related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "ObjectMgr.h" #include "Player.h" +#include "RBAC.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" +#include "World.h" class quest_commandscript : public CommandScript { @@ -44,12 +48,12 @@ public: }; static std::vector commandTable = { - { "quest", rbac::RBAC_PERM_COMMAND_QUEST, false, NULL, "", questCommandTable }, + { "quest", rbac::RBAC_PERM_COMMAND_QUEST, false, nullptr, "", questCommandTable }, }; return commandTable; } - static bool HandleQuestAdd(ChatHandler* handler, const char* args) + static bool HandleQuestAdd(ChatHandler* handler, char const* args) { Player* player = handler->getSelectedPlayerOrSelf(); if (!player) @@ -78,7 +82,10 @@ public: // check item starting quest (it can work incorrectly if added without item in inventory) ItemTemplateContainer const* itc = sObjectMgr->GetItemTemplateStore(); - ItemTemplateContainer::const_iterator result = find_if (itc->begin(), itc->end(), Finder(entry, &ItemTemplate::StartQuest)); + ItemTemplateContainer::const_iterator result = std::find_if(itc->begin(), itc->end(), [quest](ItemTemplateContainer::value_type const& value) + { + return value.second.StartQuest == quest->GetQuestId(); + }); if (result != itc->end()) { @@ -89,12 +96,12 @@ public: // ok, normal (creature/GO starting) quest if (player->CanAddQuest(quest, true)) - player->AddQuestAndCheckCompletion(quest, NULL); + player->AddQuestAndCheckCompletion(quest, nullptr); return true; } - static bool HandleQuestRemove(ChatHandler* handler, const char* args) + static bool HandleQuestRemove(ChatHandler* handler, char const* args) { Player* player = handler->getSelectedPlayer(); if (!player) @@ -149,7 +156,7 @@ public: return true; } - static bool HandleQuestComplete(ChatHandler* handler, const char* args) + static bool HandleQuestComplete(ChatHandler* handler, char const* args) { Player* player = handler->getSelectedPlayerOrSelf(); if (!player) diff --git a/src/server/scripts/Commands/cs_rbac.cpp b/src/server/scripts/Commands/cs_rbac.cpp index eb646d8bcd8..bfc01c0bc47 100644 --- a/src/server/scripts/Commands/cs_rbac.cpp +++ b/src/server/scripts/Commands/cs_rbac.cpp @@ -22,16 +22,19 @@ Comment: All role based access control related commands (including account relat Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" -#include "Config.h" #include "Chat.h" +#include "Config.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "Realm.h" +#include "World.h" +#include "WorldSession.h" struct RBACCommandData { - RBACCommandData(): id(0), realmId(0), rbac(NULL), needDelete(false) { } + RBACCommandData(): id(0), realmId(0), rbac(nullptr), needDelete(false) { } ~RBACCommandData() { if (needDelete) @@ -61,13 +64,13 @@ public: static std::vector rbacCommandTable = { - { "account", rbac::RBAC_PERM_COMMAND_RBAC_ACC, true, NULL, "", rbacAccountCommandTable }, + { "account", rbac::RBAC_PERM_COMMAND_RBAC_ACC, true, nullptr, "", rbacAccountCommandTable }, { "list", rbac::RBAC_PERM_COMMAND_RBAC_LIST, true, &HandleRBACListPermissionsCommand, "" }, }; static std::vector commandTable = { - { "rbac", rbac::RBAC_PERM_COMMAND_RBAC, true, NULL, "", rbacCommandTable }, + { "rbac", rbac::RBAC_PERM_COMMAND_RBAC, true, nullptr, "", rbacCommandTable }, }; return commandTable; @@ -76,18 +79,18 @@ public: static RBACCommandData* ReadParams(ChatHandler* handler, char const* args, bool checkParams = true) { if (!args) - return NULL; + return nullptr; char* param1 = strtok((char*)args, " "); - char* param2 = strtok(NULL, " "); - char* param3 = strtok(NULL, " "); + char* param2 = strtok(nullptr, " "); + char* param3 = strtok(nullptr, " "); int32 realmId = -1; uint32 accountId = 0; std::string accountName; uint32 id = 0; - RBACCommandData* data = NULL; - rbac::RBACData* rdata = NULL; + RBACCommandData* data = nullptr; + rbac::RBACData* rdata = nullptr; bool useSelectedPlayer = false; if (checkParams) @@ -112,14 +115,14 @@ public: { handler->PSendSysMessage(LANG_RBAC_WRONG_PARAMETER_ID, id); handler->SetSentErrorMessage(true); - return NULL; + return nullptr; } if (realmId < -1 || !realmId) { handler->PSendSysMessage(LANG_RBAC_WRONG_PARAMETER_REALM, realmId); handler->SetSentErrorMessage(true); - return NULL; + return nullptr; } } else if (!param1) @@ -129,7 +132,7 @@ public: { Player* player = handler->getSelectedPlayer(); if (!player) - return NULL; + return nullptr; rdata = player->GetSession()->GetRBACData(); accountId = rdata->GetId(); @@ -146,12 +149,12 @@ public: { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); - return NULL; + return nullptr; } } - if (checkParams && handler->HasLowerSecurityAccount(NULL, accountId, true)) - return NULL; + if (checkParams && handler->HasLowerSecurityAccount(nullptr, accountId, true)) + return nullptr; data = new RBACCommandData(); diff --git a/src/server/scripts/Commands/cs_reload.cpp b/src/server/scripts/Commands/cs_reload.cpp index 46f71972242..faeb77cccec 100644 --- a/src/server/scripts/Commands/cs_reload.cpp +++ b/src/server/scripts/Commands/cs_reload.cpp @@ -22,18 +22,22 @@ Comment: All reload related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "AchievementMgr.h" #include "AuctionHouseMgr.h" #include "BattlegroundMgr.h" #include "Chat.h" #include "CreatureTextMgr.h" +#include "DatabaseEnv.h" #include "DisableMgr.h" +#include "ItemEnchantmentMgr.h" #include "Language.h" #include "LFGMgr.h" +#include "Log.h" +#include "LootMgr.h" #include "MapManager.h" #include "ObjectMgr.h" -#include "ScriptMgr.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" #include "SmartAI.h" @@ -41,6 +45,7 @@ EndScriptData */ #include "TicketMgr.h" #include "WardenCheckMgr.h" #include "WaypointManager.h" +#include "World.h" class reload_commandscript : public CommandScript { @@ -69,7 +74,7 @@ public: { "access_requirement", rbac::RBAC_PERM_COMMAND_RELOAD_ACCESS_REQUIREMENT, true, &HandleReloadAccessRequirementCommand, "" }, { "achievement_criteria_data", rbac::RBAC_PERM_COMMAND_RELOAD_ACHIEVEMENT_CRITERIA_DATA, true, &HandleReloadAchievementCriteriaDataCommand, "" }, { "achievement_reward", rbac::RBAC_PERM_COMMAND_RELOAD_ACHIEVEMENT_REWARD, true, &HandleReloadAchievementRewardCommand, "" }, - { "all", rbac::RBAC_PERM_COMMAND_RELOAD_ALL, true, NULL, "", reloadAllCommandTable }, + { "all", rbac::RBAC_PERM_COMMAND_RELOAD_ALL, true, nullptr, "", reloadAllCommandTable }, { "areatrigger_involvedrelation", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_INVOLVEDRELATION, true, &HandleReloadQuestAreaTriggersCommand, "" }, { "areatrigger_tavern", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_TAVERN, true, &HandleReloadAreaTriggerTavernCommand, "" }, { "areatrigger_teleport", rbac::RBAC_PERM_COMMAND_RELOAD_AREATRIGGER_TELEPORT, true, &HandleReloadAreaTriggerTeleportCommand, "" }, @@ -158,19 +163,19 @@ public: }; static std::vector commandTable = { - { "reload", rbac::RBAC_PERM_COMMAND_RELOAD, true, NULL, "", reloadCommandTable }, + { "reload", rbac::RBAC_PERM_COMMAND_RELOAD, true, nullptr, "", reloadCommandTable }, }; return commandTable; } //reload commands - static bool HandleReloadGMTicketsCommand(ChatHandler* /*handler*/, const char* /*args*/) + static bool HandleReloadGMTicketsCommand(ChatHandler* /*handler*/, char const* /*args*/) { sTicketMgr->LoadTickets(); return true; } - static bool HandleReloadAllCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadSkillFishingBaseLevelCommand(handler, ""); @@ -201,14 +206,14 @@ public: return true; } - static bool HandleReloadAllAchievementCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllAchievementCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadAchievementCriteriaDataCommand(handler, ""); HandleReloadAchievementRewardCommand(handler, ""); return true; } - static bool HandleReloadAllAreaCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllAreaCommand(ChatHandler* handler, char const* /*args*/) { //HandleReloadQuestAreaTriggersCommand(handler, ""); -- reloaded in HandleReloadAllQuestCommand HandleReloadAreaTriggerTeleportCommand(handler, ""); @@ -217,7 +222,7 @@ public: return true; } - static bool HandleReloadAllLootCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllLootCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables..."); LoadLootTables(); @@ -226,7 +231,7 @@ public: return true; } - static bool HandleReloadAllNpcCommand(ChatHandler* handler, const char* args) + static bool HandleReloadAllNpcCommand(ChatHandler* handler, char const* args) { if (*args != 'a') // will be reloaded from all_gossips HandleReloadNpcTrainerCommand(handler, "a"); @@ -236,7 +241,7 @@ public: return true; } - static bool HandleReloadAllQuestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllQuestCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadQuestAreaTriggersCommand(handler, "a"); HandleReloadQuestPOICommand(handler, "a"); @@ -248,7 +253,7 @@ public: return true; } - static bool HandleReloadAllScriptsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllScriptsCommand(ChatHandler* handler, char const* /*args*/) { if (sMapMgr->IsScriptScheduled()) { @@ -266,7 +271,7 @@ public: return true; } - static bool HandleReloadAllSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllSpellCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadSkillDiscoveryTemplateCommand(handler, "a"); HandleReloadSkillExtraItemTemplateCommand(handler, "a"); @@ -284,7 +289,7 @@ public: return true; } - static bool HandleReloadAllGossipsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadAllGossipsCommand(ChatHandler* handler, char const* args) { HandleReloadGossipMenuCommand(handler, "a"); HandleReloadGossipMenuOptionCommand(handler, "a"); @@ -293,14 +298,14 @@ public: return true; } - static bool HandleReloadAllItemCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllItemCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadPageTextsCommand(handler, "a"); HandleReloadItemEnchantementsCommand(handler, "a"); return true; } - static bool HandleReloadAllLocalesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllLocalesCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadLocalesAchievementRewardCommand(handler, "a"); HandleReloadLocalesCreatureCommand(handler, "a"); @@ -315,7 +320,7 @@ public: return true; } - static bool HandleReloadConfigCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadConfigCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading config settings..."); sWorld->LoadConfigSettings(true); @@ -324,7 +329,7 @@ public: return true; } - static bool HandleReloadAccessRequirementCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAccessRequirementCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Access Requirement definitions..."); sObjectMgr->LoadAccessRequirements(); @@ -332,7 +337,7 @@ public: return true; } - static bool HandleReloadAchievementCriteriaDataCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAchievementCriteriaDataCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Additional Achievement Criteria Data..."); sAchievementMgr->LoadAchievementCriteriaData(); @@ -340,7 +345,7 @@ public: return true; } - static bool HandleReloadAchievementRewardCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAchievementRewardCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Achievement Reward Data..."); sAchievementMgr->LoadRewards(); @@ -348,7 +353,7 @@ public: return true; } - static bool HandleReloadAreaTriggerTavernCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAreaTriggerTavernCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Tavern Area Triggers..."); sObjectMgr->LoadTavernAreaTriggers(); @@ -356,7 +361,7 @@ public: return true; } - static bool HandleReloadAreaTriggerTeleportCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAreaTriggerTeleportCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading AreaTrigger teleport definitions..."); sObjectMgr->LoadAreaTriggerTeleports(); @@ -364,7 +369,7 @@ public: return true; } - static bool HandleReloadAutobroadcastCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAutobroadcastCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Autobroadcasts..."); sWorld->LoadAutobroadcasts(); @@ -380,7 +385,7 @@ public: return true; } - static bool HandleReloadBroadcastTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadBroadcastTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Broadcast texts..."); sObjectMgr->LoadBroadcastTexts(); @@ -389,14 +394,14 @@ public: return true; } - static bool HandleReloadCommandCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCommandCommand(ChatHandler* handler, char const* /*args*/) { ChatHandler::invalidateCommandTable(); handler->SendGlobalGMSysMessage("DB table `command` will be reloaded at next chat command use."); return true; } - static bool HandleReloadOnKillReputationCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadOnKillReputationCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading creature award reputation definitions..."); sObjectMgr->LoadReputationOnKill(); @@ -404,7 +409,7 @@ public: return true; } - static bool HandleReloadCreatureSummonGroupsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureSummonGroupsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading creature summon groups..."); sObjectMgr->LoadTempSummons(); @@ -412,7 +417,7 @@ public: return true; } - static bool HandleReloadCreatureTemplateCommand(ChatHandler* handler, const char* args) + static bool HandleReloadCreatureTemplateCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -452,7 +457,7 @@ public: return true; } - static bool HandleReloadCreatureQuestStarterCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureQuestStarterCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`creature_queststarter`)"); sObjectMgr->LoadCreatureQuestStarters(); @@ -460,7 +465,7 @@ public: return true; } - static bool HandleReloadLinkedRespawnCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLinkedRespawnCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Linked Respawns... (`creature_linked_respawn`)"); sObjectMgr->LoadLinkedRespawn(); @@ -468,7 +473,7 @@ public: return true; } - static bool HandleReloadCreatureQuestEnderCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureQuestEnderCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`creature_questender`)"); sObjectMgr->LoadCreatureQuestEnders(); @@ -476,7 +481,7 @@ public: return true; } - static bool HandleReloadGossipMenuCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGossipMenuCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `gossip_menu` Table!"); sObjectMgr->LoadGossipMenu(); @@ -485,7 +490,7 @@ public: return true; } - static bool HandleReloadGossipMenuOptionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGossipMenuOptionCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `gossip_menu_option` Table!"); sObjectMgr->LoadGossipMenuItems(); @@ -494,7 +499,7 @@ public: return true; } - static bool HandleReloadGOQuestStarterCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGOQuestStarterCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`gameobject_queststarter`)"); sObjectMgr->LoadGameobjectQuestStarters(); @@ -502,7 +507,7 @@ public: return true; } - static bool HandleReloadGOQuestEnderCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGOQuestEnderCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`gameobject_questender`)"); sObjectMgr->LoadGameobjectQuestEnders(); @@ -510,7 +515,7 @@ public: return true; } - static bool HandleReloadQuestAreaTriggersCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadQuestAreaTriggersCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Area Triggers..."); sObjectMgr->LoadQuestAreaTriggers(); @@ -518,7 +523,7 @@ public: return true; } - static bool HandleReloadQuestTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadQuestTemplateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Templates..."); sObjectMgr->LoadQuests(); @@ -532,7 +537,7 @@ public: return true; } - static bool HandleReloadLootTemplatesCreatureCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesCreatureCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`creature_loot_template`)"); LoadLootTemplates_Creature(); @@ -542,7 +547,7 @@ public: return true; } - static bool HandleReloadLootTemplatesDisenchantCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesDisenchantCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`disenchant_loot_template`)"); LoadLootTemplates_Disenchant(); @@ -552,7 +557,7 @@ public: return true; } - static bool HandleReloadLootTemplatesFishingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesFishingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`fishing_loot_template`)"); LoadLootTemplates_Fishing(); @@ -562,7 +567,7 @@ public: return true; } - static bool HandleReloadLootTemplatesGameobjectCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesGameobjectCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`gameobject_loot_template`)"); LoadLootTemplates_Gameobject(); @@ -572,7 +577,7 @@ public: return true; } - static bool HandleReloadLootTemplatesItemCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesItemCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`item_loot_template`)"); LoadLootTemplates_Item(); @@ -582,7 +587,7 @@ public: return true; } - static bool HandleReloadLootTemplatesMillingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesMillingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`milling_loot_template`)"); LoadLootTemplates_Milling(); @@ -592,7 +597,7 @@ public: return true; } - static bool HandleReloadLootTemplatesPickpocketingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesPickpocketingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`pickpocketing_loot_template`)"); LoadLootTemplates_Pickpocketing(); @@ -602,7 +607,7 @@ public: return true; } - static bool HandleReloadLootTemplatesProspectingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesProspectingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`prospecting_loot_template`)"); LoadLootTemplates_Prospecting(); @@ -612,7 +617,7 @@ public: return true; } - static bool HandleReloadLootTemplatesMailCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesMailCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`mail_loot_template`)"); LoadLootTemplates_Mail(); @@ -622,7 +627,7 @@ public: return true; } - static bool HandleReloadLootTemplatesReferenceCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesReferenceCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`reference_loot_template`)"); LoadLootTemplates_Reference(); @@ -631,7 +636,7 @@ public: return true; } - static bool HandleReloadLootTemplatesSkinningCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesSkinningCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`skinning_loot_template`)"); LoadLootTemplates_Skinning(); @@ -641,7 +646,7 @@ public: return true; } - static bool HandleReloadLootTemplatesSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesSpellCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`spell_loot_template`)"); LoadLootTemplates_Spell(); @@ -651,7 +656,7 @@ public: return true; } - static bool HandleReloadTrinityStringCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadTrinityStringCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading trinity_string Table!"); sObjectMgr->LoadTrinityStrings(); @@ -659,7 +664,7 @@ public: return true; } - static bool HandleReloadWardenactionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadWardenactionCommand(ChatHandler* handler, char const* /*args*/) { if (!sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED)) { @@ -674,7 +679,7 @@ public: return true; } - static bool HandleReloadNpcTrainerCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadNpcTrainerCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_trainer` Table!"); sObjectMgr->LoadTrainerSpell(); @@ -682,7 +687,7 @@ public: return true; } - static bool HandleReloadNpcVendorCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadNpcVendorCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_vendor` Table!"); sObjectMgr->LoadVendors(); @@ -690,7 +695,7 @@ public: return true; } - static bool HandleReloadPointsOfInterestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadPointsOfInterestCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `points_of_interest` Table!"); sObjectMgr->LoadPointsOfInterest(); @@ -698,7 +703,7 @@ public: return true; } - static bool HandleReloadQuestPOICommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadQuestPOICommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest POI ..." ); sObjectMgr->LoadQuestPOI(); @@ -707,7 +712,7 @@ public: return true; } - static bool HandleReloadSpellClickSpellsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellClickSpellsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_spellclick_spells` Table!"); sObjectMgr->LoadNPCSpellClickSpells(); @@ -715,7 +720,7 @@ public: return true; } - static bool HandleReloadReservedNameCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadReservedNameCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading ReservedNames... (`reserved_name`)"); sObjectMgr->LoadReservedPlayersNames(); @@ -723,7 +728,7 @@ public: return true; } - static bool HandleReloadReputationRewardRateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadReputationRewardRateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `reputation_reward_rate` Table!" ); sObjectMgr->LoadReputationRewardRate(); @@ -731,7 +736,7 @@ public: return true; } - static bool HandleReloadReputationSpilloverTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadReputationSpilloverTemplateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `reputation_spillover_template` Table!" ); sObjectMgr->LoadReputationSpilloverTemplate(); @@ -739,7 +744,7 @@ public: return true; } - static bool HandleReloadSkillDiscoveryTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSkillDiscoveryTemplateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Skill Discovery Table..."); LoadSkillDiscoveryTable(); @@ -747,7 +752,7 @@ public: return true; } - static bool HandleReloadSkillPerfectItemTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSkillPerfectItemTemplateCommand(ChatHandler* handler, char const* /*args*/) { // latched onto HandleReloadSkillExtraItemTemplateCommand as it's part of that table group (and i don't want to chance all the command IDs) TC_LOG_INFO("misc", "Re-Loading Skill Perfection Data Table..."); LoadSkillPerfectItemTable(); @@ -755,7 +760,7 @@ public: return true; } - static bool HandleReloadSkillExtraItemTemplateCommand(ChatHandler* handler, const char* args) + static bool HandleReloadSkillExtraItemTemplateCommand(ChatHandler* handler, char const* args) { TC_LOG_INFO("misc", "Re-Loading Skill Extra Item Table..."); LoadSkillExtraItemTable(); @@ -764,7 +769,7 @@ public: return HandleReloadSkillPerfectItemTemplateCommand(handler, args); } - static bool HandleReloadSkillFishingBaseLevelCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSkillFishingBaseLevelCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Skill Fishing base level requirements..."); sObjectMgr->LoadFishingBaseSkillLevel(); @@ -772,7 +777,7 @@ public: return true; } - static bool HandleReloadSpellAreaCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellAreaCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading SpellArea Data..."); sSpellMgr->LoadSpellAreas(); @@ -780,7 +785,7 @@ public: return true; } - static bool HandleReloadSpellRequiredCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellRequiredCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Required Data... "); sSpellMgr->LoadSpellRequired(); @@ -788,7 +793,7 @@ public: return true; } - static bool HandleReloadSpellGroupsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellGroupsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Groups..."); sSpellMgr->LoadSpellGroups(); @@ -796,7 +801,7 @@ public: return true; } - static bool HandleReloadSpellLearnSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellLearnSpellCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Learn Spells..."); sSpellMgr->LoadSpellLearnSpells(); @@ -804,7 +809,7 @@ public: return true; } - static bool HandleReloadSpellLinkedSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellLinkedSpellCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Linked Spells..."); sSpellMgr->LoadSpellLinked(); @@ -812,7 +817,7 @@ public: return true; } - static bool HandleReloadSpellProcsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellProcsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Proc conditions and data..."); sSpellMgr->LoadSpellProcs(); @@ -820,7 +825,7 @@ public: return true; } - static bool HandleReloadSpellBonusesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellBonusesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Bonus Data..."); sSpellMgr->LoadSpellBonusess(); @@ -828,7 +833,7 @@ public: return true; } - static bool HandleReloadSpellTargetPositionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellTargetPositionCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell target coordinates..."); sSpellMgr->LoadSpellTargetPositions(); @@ -836,7 +841,7 @@ public: return true; } - static bool HandleReloadSpellThreatsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellThreatsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Aggro Spells Definitions..."); sSpellMgr->LoadSpellThreats(); @@ -844,7 +849,7 @@ public: return true; } - static bool HandleReloadSpellGroupStackRulesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellGroupStackRulesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Group Stack Rules..."); sSpellMgr->LoadSpellGroupStackRules(); @@ -852,7 +857,7 @@ public: return true; } - static bool HandleReloadSpellPetAurasCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellPetAurasCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell pet auras..."); sSpellMgr->LoadSpellPetAuras(); @@ -860,7 +865,7 @@ public: return true; } - static bool HandleReloadPageTextsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadPageTextsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Page Text..."); sObjectMgr->LoadPageTexts(); @@ -868,7 +873,7 @@ public: return true; } - static bool HandleReloadItemEnchantementsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadItemEnchantementsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Item Random Enchantments Table..."); LoadRandomEnchantmentsTable(); @@ -876,7 +881,7 @@ public: return true; } - static bool HandleReloadItemSetNamesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadItemSetNamesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Item set names..."); sObjectMgr->LoadItemSetNames(); @@ -884,7 +889,7 @@ public: return true; } - static bool HandleReloadEventScriptsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadEventScriptsCommand(ChatHandler* handler, char const* args) { if (sMapMgr->IsScriptScheduled()) { @@ -904,7 +909,7 @@ public: return true; } - static bool HandleReloadWpScriptsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadWpScriptsCommand(ChatHandler* handler, char const* args) { if (sMapMgr->IsScriptScheduled()) { @@ -924,7 +929,7 @@ public: return true; } - static bool HandleReloadWpCommand(ChatHandler* handler, const char* args) + static bool HandleReloadWpCommand(ChatHandler* handler, char const* args) { if (*args != 'a') TC_LOG_INFO("misc", "Re-Loading Waypoints data from 'waypoints_data'"); @@ -937,7 +942,7 @@ public: return true; } - static bool HandleReloadSpellScriptsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadSpellScriptsCommand(ChatHandler* handler, char const* args) { if (sMapMgr->IsScriptScheduled()) { @@ -957,7 +962,7 @@ public: return true; } - static bool HandleReloadGameGraveyardZoneCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGameGraveyardZoneCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Graveyard-zone links..."); @@ -968,7 +973,7 @@ public: return true; } - static bool HandleReloadGameTeleCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGameTeleCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Game Tele coordinates..."); @@ -979,7 +984,7 @@ public: return true; } - static bool HandleReloadDisablesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadDisablesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading disables table..."); DisableMgr::LoadDisables(); @@ -989,7 +994,7 @@ public: return true; } - static bool HandleReloadLocalesAchievementRewardCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesAchievementRewardCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Achievement Reward Data Locale..."); sAchievementMgr->LoadRewardLocales(); @@ -997,7 +1002,7 @@ public: return true; } - static bool HandleReloadLfgRewardsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLfgRewardsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading lfg dungeon rewards..."); sLFGMgr->LoadRewards(); @@ -1005,7 +1010,7 @@ public: return true; } - static bool HandleReloadLocalesCreatureCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesCreatureCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Template Locale..."); sObjectMgr->LoadCreatureLocales(); @@ -1013,7 +1018,7 @@ public: return true; } - static bool HandleReloadLocalesCreatureTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesCreatureTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Texts Locale..."); sCreatureTextMgr->LoadCreatureTextLocales(); @@ -1021,7 +1026,7 @@ public: return true; } - static bool HandleReloadLocalesGameobjectCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesGameobjectCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Gameobject Template Locale... "); sObjectMgr->LoadGameObjectLocales(); @@ -1029,7 +1034,7 @@ public: return true; } - static bool HandleReloadLocalesGossipMenuOptionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesGossipMenuOptionCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Gossip Menu Option Locale... "); sObjectMgr->LoadGossipMenuItemsLocales(); @@ -1037,7 +1042,7 @@ public: return true; } - static bool HandleReloadLocalesItemCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesItemCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Item Template Locale... "); sObjectMgr->LoadItemLocales(); @@ -1045,7 +1050,7 @@ public: return true; } - static bool HandleReloadLocalesItemSetNameCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesItemSetNameCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Item set name Locale... "); sObjectMgr->LoadItemSetNameLocales(); @@ -1053,7 +1058,7 @@ public: return true; } - static bool HandleReloadLocalesNpcTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesNpcTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading NPC Text Locale... "); sObjectMgr->LoadNpcTextLocales(); @@ -1061,7 +1066,7 @@ public: return true; } - static bool HandleReloadLocalesPageTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesPageTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Page Text Locale... "); sObjectMgr->LoadPageTextLocales(); @@ -1069,7 +1074,7 @@ public: return true; } - static bool HandleReloadLocalesPointsOfInterestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesPointsOfInterestCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Points Of Interest Locale... "); sObjectMgr->LoadPointOfInterestLocales(); @@ -1077,7 +1082,7 @@ public: return true; } - static bool HandleReloadLocalesQuestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesQuestCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Template Locale... "); sObjectMgr->LoadQuestLocales(); @@ -1085,7 +1090,7 @@ public: return true; } - static bool HandleReloadMailLevelRewardCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadMailLevelRewardCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Player level dependent mail rewards..."); sObjectMgr->LoadMailLevelRewards(); @@ -1093,7 +1098,7 @@ public: return true; } - static bool HandleReloadAuctionsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAuctionsCommand(ChatHandler* handler, char const* /*args*/) { ///- Reload dynamic data tables from the database TC_LOG_INFO("misc", "Re-Loading Auctions..."); @@ -1103,7 +1108,7 @@ public: return true; } - static bool HandleReloadConditions(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadConditions(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Conditions..."); sConditionMgr->LoadConditions(true); @@ -1111,7 +1116,7 @@ public: return true; } - static bool HandleReloadCreatureText(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureText(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Texts..."); sCreatureTextMgr->LoadCreatureTexts(); @@ -1119,7 +1124,7 @@ public: return true; } - static bool HandleReloadSmartScripts(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSmartScripts(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Smart Scripts..."); sSmartScriptMgr->LoadSmartAIFromDB(); @@ -1127,7 +1132,7 @@ public: return true; } - static bool HandleReloadVehicleAccessoryCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadVehicleAccessoryCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading vehicle_accessory table..."); sObjectMgr->LoadVehicleAccessories(); @@ -1135,7 +1140,7 @@ public: return true; } - static bool HandleReloadVehicleTemplateAccessoryCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadVehicleTemplateAccessoryCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading vehicle_template_accessory table..."); sObjectMgr->LoadVehicleTemplateAccessories(); @@ -1143,7 +1148,7 @@ public: return true; } - static bool HandleReloadRBACCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadRBACCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading RBAC tables..."); sAccountMgr->LoadRBAC(); diff --git a/src/server/scripts/Commands/cs_reset.cpp b/src/server/scripts/Commands/cs_reset.cpp index 40399e8f309..fd6694c1099 100644 --- a/src/server/scripts/Commands/cs_reset.cpp +++ b/src/server/scripts/Commands/cs_reset.cpp @@ -22,13 +22,20 @@ Comment: All reset related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AchievementMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "Log.h" #include "ObjectAccessor.h" -#include "Player.h" #include "Pet.h" -#include "ScriptMgr.h" +#include "Player.h" +#include "RBAC.h" +#include "World.h" +#include "WorldSession.h" +#include +#include class reset_commandscript : public CommandScript { @@ -49,7 +56,7 @@ public: }; static std::vector commandTable = { - { "reset", rbac::RBAC_PERM_COMMAND_RESET, true, NULL, "", resetCommandTable }, + { "reset", rbac::RBAC_PERM_COMMAND_RESET, true, nullptr, "", resetCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_send.cpp b/src/server/scripts/Commands/cs_send.cpp index 0289b713c6f..2e2fb383a07 100644 --- a/src/server/scripts/Commands/cs_send.cpp +++ b/src/server/scripts/Commands/cs_send.cpp @@ -15,12 +15,17 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "Item.h" #include "Language.h" +#include "Mail.h" +#include "ObjectMgr.h" #include "Pet.h" #include "Player.h" -#include "ObjectMgr.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class send_commandscript : public CommandScript { @@ -39,7 +44,7 @@ public: static std::vector commandTable = { - { "send", rbac::RBAC_PERM_COMMAND_SEND, false, NULL, "", sendCommandTable }, + { "send", rbac::RBAC_PERM_COMMAND_SEND, false, nullptr, "", sendCommandTable }, }; return commandTable; } @@ -54,7 +59,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &target, &targetGuid, &targetName)) return false; - char* tail1 = strtok(NULL, ""); + char* tail1 = strtok(nullptr, ""); if (!tail1) return false; @@ -62,7 +67,7 @@ public: if (!msgSubject) return false; - char* tail2 = strtok(NULL, ""); + char* tail2 = strtok(nullptr, ""); if (!tail2) return false; @@ -99,7 +104,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName)) return false; - char* tail1 = strtok(NULL, ""); + char* tail1 = strtok(nullptr, ""); if (!tail1) return false; @@ -107,7 +112,7 @@ public: if (!msgSubject) return false; - char* tail2 = strtok(NULL, ""); + char* tail2 = strtok(nullptr, ""); if (!tail2) return false; @@ -125,17 +130,17 @@ public: ItemPairs items; // get all tail string - char* tail = strtok(NULL, ""); + char* tail = strtok(nullptr, ""); // get from tail next item str while (char* itemStr = strtok(tail, " ")) { // and get new tail - tail = strtok(NULL, ""); + tail = strtok(nullptr, ""); // parse item str char const* itemIdStr = strtok(itemStr, ":"); - char const* itemCountStr = strtok(NULL, " "); + char const* itemCountStr = strtok(nullptr, " "); uint32 itemId = atoi(itemIdStr); if (!itemId) @@ -208,7 +213,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName)) return false; - char* tail1 = strtok(NULL, ""); + char* tail1 = strtok(nullptr, ""); if (!tail1) return false; @@ -216,7 +221,7 @@ public: if (!msgSubject) return false; - char* tail2 = strtok(NULL, ""); + char* tail2 = strtok(nullptr, ""); if (!tail2) return false; @@ -224,7 +229,7 @@ public: if (!msgText) return false; - char* moneyStr = strtok(NULL, ""); + char* moneyStr = strtok(nullptr, ""); int32 money = moneyStr ? atoi(moneyStr) : 0; if (money <= 0) return false; @@ -256,7 +261,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &player)) return false; - char* msgStr = strtok(NULL, ""); + char* msgStr = strtok(nullptr, ""); if (!msgStr) return false; diff --git a/src/server/scripts/Commands/cs_server.cpp b/src/server/scripts/Commands/cs_server.cpp index 620c70599e5..9be78607c62 100644 --- a/src/server/scripts/Commands/cs_server.cpp +++ b/src/server/scripts/Commands/cs_server.cpp @@ -22,17 +22,21 @@ Comment: All server related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "Config.h" +#include "GameTime.h" +#include "GitRevision.h" #include "Language.h" +#include "Log.h" #include "ObjectAccessor.h" #include "Player.h" -#include "ScriptMgr.h" -#include "GitRevision.h" -#include "Util.h" +#include "RBAC.h" #include "ServerMotd.h" -#include "GameTime.h" #include "UpdateTime.h" +#include "Util.h" +#include "World.h" +#include "WorldSession.h" class server_commandscript : public CommandScript { diff --git a/src/server/scripts/Commands/cs_tele.cpp b/src/server/scripts/Commands/cs_tele.cpp index b880b1130c1..7a5d7e61fcf 100644 --- a/src/server/scripts/Commands/cs_tele.cpp +++ b/src/server/scripts/Commands/cs_tele.cpp @@ -22,13 +22,18 @@ Comment: All tele related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Group.h" #include "Language.h" #include "MapManager.h" +#include "MotionMaster.h" #include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class tele_commandscript : public CommandScript { @@ -47,12 +52,12 @@ public: }; static std::vector commandTable = { - { "tele", rbac::RBAC_PERM_COMMAND_TELE, false, NULL, "", teleCommandTable }, + { "tele", rbac::RBAC_PERM_COMMAND_TELE, false, nullptr, "", teleCommandTable }, }; return commandTable; } - static bool HandleTeleAddCommand(ChatHandler* handler, const char* args) + static bool HandleTeleAddCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -92,7 +97,7 @@ public: return true; } - static bool HandleTeleDelCommand(ChatHandler* handler, const char* args) + static bool HandleTeleDelCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -112,7 +117,7 @@ public: } // teleport player to given game_tele.entry - static bool HandleTeleNameCommand(ChatHandler* handler, const char* args) + static bool HandleTeleNameCommand(ChatHandler* handler, char const* args) { char* nameStr; char* teleStr; @@ -193,7 +198,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, target_guid)) + if (handler->HasLowerSecurity(nullptr, target_guid)) return false; std::string nameLink = handler->playerLink(target_name); @@ -209,7 +214,7 @@ public: } //Teleport group to given game_tele.entry - static bool HandleTeleGroupCommand(ChatHandler* handler, const char* args) + static bool HandleTeleGroupCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -253,7 +258,7 @@ public: return false; } - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); @@ -292,7 +297,7 @@ public: return true; } - static bool HandleTeleCommand(ChatHandler* handler, const char* args) + static bool HandleTeleCommand(ChatHandler* handler, char const* args) { if (!*args) return false; diff --git a/src/server/scripts/Commands/cs_ticket.cpp b/src/server/scripts/Commands/cs_ticket.cpp index a8ed1d20a0b..31d0897493d 100644 --- a/src/server/scripts/Commands/cs_ticket.cpp +++ b/src/server/scripts/Commands/cs_ticket.cpp @@ -22,15 +22,19 @@ Comment: All ticket related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "CharacterCache.h" #include "Chat.h" #include "Language.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "Realm.h" #include "TicketMgr.h" -#include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" class ticket_commandscript : public CommandScript { @@ -57,7 +61,7 @@ public: { "list", rbac::RBAC_PERM_COMMAND_TICKET_LIST, true, &HandleGMTicketListCommand, "" }, { "onlinelist", rbac::RBAC_PERM_COMMAND_TICKET_ONLINELIST, true, &HandleGMTicketListOnlineCommand, "" }, { "reset", rbac::RBAC_PERM_COMMAND_TICKET_RESET, true, &HandleGMTicketResetCommand, "" }, - { "response", rbac::RBAC_PERM_COMMAND_TICKET_RESPONSE, true, NULL, "", ticketResponseCommandTable }, + { "response", rbac::RBAC_PERM_COMMAND_TICKET_RESPONSE, true, nullptr, "", ticketResponseCommandTable }, { "togglesystem", rbac::RBAC_PERM_COMMAND_TICKET_TOGGLESYSTEM, true, &HandleToggleGMTicketSystem, "" }, { "unassign", rbac::RBAC_PERM_COMMAND_TICKET_UNASSIGN, true, &HandleGMTicketUnAssignCommand, "" }, { "viewid", rbac::RBAC_PERM_COMMAND_TICKET_VIEWID, true, &HandleGMTicketGetByIdCommand, "" }, @@ -65,7 +69,7 @@ public: }; static std::vector commandTable = { - { "ticket", rbac::RBAC_PERM_COMMAND_TICKET, false, NULL, "", ticketCommandTable }, + { "ticket", rbac::RBAC_PERM_COMMAND_TICKET, false, nullptr, "", ticketCommandTable }, }; return commandTable; } @@ -78,7 +82,7 @@ public: char* ticketIdStr = strtok((char*)args, " "); uint32 ticketId = atoi(ticketIdStr); - char* targetStr = strtok(NULL, " "); + char* targetStr = strtok(nullptr, " "); if (!targetStr) return false; @@ -119,12 +123,12 @@ public: } // Assign ticket - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetAssignedTo(targetGuid, AccountMgr::IsAdminAccount(AccountMgr::GetSecurity(accountId, realm.Id.Realm))); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, NULL, target.c_str(), NULL, NULL, NULL); + std::string msg = ticket->FormatMessageString(*handler, nullptr, target.c_str(), nullptr, nullptr, nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); return true; } @@ -154,7 +158,7 @@ public: sTicketMgr->ResolveAndCloseTicket(ticket->GetId(), player ? player->GetGUID() : ObjectGuid(uint64(0))); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, player ? player->GetName().c_str() : "Console", NULL, NULL, NULL, NULL); + std::string msg = ticket->FormatMessageString(*handler, player ? player->GetName().c_str() : "Console", nullptr, nullptr, nullptr, nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); // Inform player, who submitted this ticket, that it is closed @@ -162,7 +166,7 @@ public: { WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4); data << uint32(GMTICKET_RESPONSE_TICKET_DELETED); - submitter->GetSession()->SendPacket(&data); + submitter->SendDirectMessage(&data); } return true; } @@ -175,7 +179,7 @@ public: char* ticketIdStr = strtok((char*)args, " "); uint32 ticketId = atoi(ticketIdStr); - char* comment = strtok(NULL, "\n"); + char* comment = strtok(nullptr, "\n"); if (!comment) return false; @@ -195,7 +199,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetComment(comment); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); @@ -233,7 +237,7 @@ public: return true; } - char* response = strtok(NULL, "\n"); + char* response = strtok(nullptr, "\n"); if (response) { // Cannot add response to ticket, assigned to someone else @@ -253,13 +257,13 @@ public: Player* gm = handler->GetSession() ? handler->GetSession()->GetPlayer() : nullptr; - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetResolvedBy(gm ? gm->GetGUID() : ObjectGuid(uint64(0))); ticket->SetCompleted(); ticket->SaveToDB(trans); - std::string msg = ticket->FormatMessageString(*handler, NULL, NULL, - NULL, NULL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console"); + std::string msg = ticket->FormatMessageString(*handler, nullptr, nullptr, + nullptr, nullptr, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console"); handler->SendGlobalGMSysMessage(msg.c_str()); sTicketMgr->UpdateLastChange(); return true; @@ -284,7 +288,7 @@ public: return true; } - std::string msg = ticket->FormatMessageString(*handler, NULL, NULL, NULL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", NULL); + std::string msg = ticket->FormatMessageString(*handler, nullptr, nullptr, nullptr, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); sTicketMgr->RemoveTicket(ticket->GetId()); @@ -295,7 +299,7 @@ public: // Force abandon ticket WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4); data << uint32(GMTICKET_RESPONSE_TICKET_DELETED); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } return true; @@ -406,13 +410,13 @@ public: } std::string assignedTo = ticket->GetAssignedToName(); // copy assignedto name because we need it after the ticket has been unnassigned - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetUnassigned(); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, NULL, assignedTo.c_str(), - handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", NULL, NULL); + std::string msg = ticket->FormatMessageString(*handler, nullptr, assignedTo.c_str(), + handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", nullptr, nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); return true; @@ -431,7 +435,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetViewed(); ticket->SaveToDB(trans); @@ -470,7 +474,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetViewed(); ticket->SaveToDB(trans); @@ -486,7 +490,7 @@ public: char* ticketIdStr = strtok((char*)args, " "); uint32 ticketId = atoi(ticketIdStr); - char* response = strtok(NULL, "\n"); + char* response = strtok(nullptr, "\n"); if (!response) return false; @@ -506,7 +510,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->AppendResponse(response); if (newLine) ticket->AppendResponse("\n"); diff --git a/src/server/scripts/Commands/cs_titles.cpp b/src/server/scripts/Commands/cs_titles.cpp index d5d6e6ce8db..0a074f6390f 100644 --- a/src/server/scripts/Commands/cs_titles.cpp +++ b/src/server/scripts/Commands/cs_titles.cpp @@ -22,11 +22,12 @@ Comment: All titles related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DBCStores.h" #include "Language.h" -#include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" class titles_commandscript : public CommandScript { @@ -44,11 +45,11 @@ public: { "add", rbac::RBAC_PERM_COMMAND_TITLES_ADD, false, &HandleTitlesAddCommand, "" }, { "current", rbac::RBAC_PERM_COMMAND_TITLES_CURRENT, false, &HandleTitlesCurrentCommand, "" }, { "remove", rbac::RBAC_PERM_COMMAND_TITLES_REMOVE, false, &HandleTitlesRemoveCommand, "" }, - { "set", rbac::RBAC_PERM_COMMAND_TITLES_SET, false, NULL, "", titlesSetCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_TITLES_SET, false, nullptr, "", titlesSetCommandTable }, }; static std::vector commandTable = { - { "titles", rbac::RBAC_PERM_COMMAND_TITLES, false, NULL, "", titlesCommandTable }, + { "titles", rbac::RBAC_PERM_COMMAND_TITLES, false, nullptr, "", titlesCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_wp.cpp b/src/server/scripts/Commands/cs_wp.cpp index ffbc4da5d57..efd02314d0e 100644 --- a/src/server/scripts/Commands/cs_wp.cpp +++ b/src/server/scripts/Commands/cs_wp.cpp @@ -22,12 +22,17 @@ Comment: All wp related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "Creature.h" +#include "DatabaseEnv.h" #include "Language.h" -#include "ObjectMgr.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" #include "WaypointManager.h" +#include "WorldSession.h" class wp_commandscript : public CommandScript { @@ -48,7 +53,7 @@ public: }; static std::vector commandTable = { - { "wp", rbac::RBAC_PERM_COMMAND_WP, false, NULL, "", wpCommandTable }, + { "wp", rbac::RBAC_PERM_COMMAND_WP, false, nullptr, "", wpCommandTable }, }; return commandTable; } @@ -73,10 +78,10 @@ public: * * @return true - command did succeed, false - something went wrong */ - static bool HandleWpAddCommand(ChatHandler* handler, const char* args) + static bool HandleWpAddCommand(ChatHandler* handler, char const* args) { // optional - char* path_number = NULL; + char* path_number = nullptr; uint32 pathid = 0; if (*args) @@ -136,13 +141,13 @@ public: return true; } // HandleWpAddCommand - static bool HandleWpLoadCommand(ChatHandler* handler, const char* args) + static bool HandleWpLoadCommand(ChatHandler* handler, char const* args) { if (!*args) return false; // optional - char* path_number = NULL; + char* path_number = nullptr; if (*args) path_number = strtok((char*)args, " "); @@ -217,7 +222,7 @@ public: return true; } - static bool HandleWpReloadCommand(ChatHandler* handler, const char* args) + static bool HandleWpReloadCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -232,11 +237,11 @@ public: return true; } - static bool HandleWpUnLoadCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleWpUnLoadCommand(ChatHandler* handler, char const* /*args*/) { Creature* target = handler->getSelectedCreature(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; if (!target) { @@ -274,20 +279,20 @@ public: return true; } - static bool HandleWpEventCommand(ChatHandler* handler, const char* args) + static bool HandleWpEventCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* show_str = strtok((char*)args, " "); std::string show = show_str; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // Check if ((show != "add") && (show != "mod") && (show != "del") && (show != "listid")) return false; - char* arg_id = strtok(NULL, " "); + char* arg_id = strtok(nullptr, " "); uint32 id = 0; if (show == "add") @@ -416,7 +421,7 @@ public: return true; } - char* arg_2 = strtok(NULL, " "); + char* arg_2 = strtok(nullptr, " "); if (!arg_2) { @@ -436,7 +441,7 @@ public: char* arg_3; std::string arg_str_2 = arg_2; - arg_3 = strtok(NULL, " "); + arg_3 = strtok(nullptr, " "); if (!arg_3) { @@ -531,7 +536,7 @@ public: return true; } - static bool HandleWpModifyCommand(ChatHandler* handler, const char* args) + static bool HandleWpModifyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -554,7 +559,7 @@ public: } // Next arg is: - char* arg_str = NULL; + char* arg_str = nullptr; // Did user provide a GUID // or did the user select a creature? @@ -562,7 +567,7 @@ public: uint32 pathid = 0; uint32 point = 0; Creature* target = handler->getSelectedCreature(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // User did select a visual waypoint? if (!target || target->GetEntry() != VISUAL_WAYPOINT) @@ -613,10 +618,10 @@ public: // We have the waypoint number and the GUID of the "master npc" // Text is enclosed in "<>", all other arguments not - arg_str = strtok((char*)NULL, " "); + arg_str = strtok((char*)nullptr, " "); // Check for argument - if (show != "del" && show != "move" && arg_str == NULL) + if (show != "del" && show != "move" && arg_str == nullptr) { handler->PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, show_str); return false; @@ -705,7 +710,7 @@ public: return true; } - static bool HandleWpShowCommand(ChatHandler* handler, const char* args) + static bool HandleWpShowCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -716,11 +721,11 @@ public: return false; // second arg: GUID (optional, if a creature is selected) - char* guid_str = strtok((char*)NULL, " "); + char* guid_str = strtok((char*)nullptr, " "); uint32 pathid = 0; Creature* target = handler->getSelectedCreature(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // Did player provide a PathID? diff --git a/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp b/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp index 9b18098417f..cc0ff3fd650 100644 --- a/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp +++ b/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" enum Spells diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp index 3b727fd1bc1..bcd4a915595 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "ScriptedGossip.h" -#include "GameObjectAI.h" #include "blackrock_depths.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "WorldSession.h" //go_shadowforge_brazier @@ -54,7 +58,7 @@ class go_shadowforge_brazier : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetBlackrockDepthsAI(go); } }; @@ -93,7 +97,7 @@ class at_ring_of_law : public AreaTriggerScript public: at_ring_of_law() : AreaTriggerScript("at_ring_of_law") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (InstanceScript* instance = player->GetInstanceScript()) { @@ -128,7 +132,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } struct npc_grimstoneAI : public npc_escortAI @@ -224,7 +228,7 @@ public: Event_Timer = 5000; break; case 5: - instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_GRIMSTONE, me); + instance->UpdateEncounterStateForKilledCreature(NPC_GRIMSTONE, me); instance->SetData(TYPE_RING_OF_LAW, DONE); TC_LOG_DEBUG("scripts", "npc_grimstone: event reached end and set complete."); break; @@ -365,7 +369,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_phalanxAI(creature); + return GetBlackrockDepthsAI(creature); } struct npc_phalanxAI : public ScriptedAI @@ -489,7 +493,7 @@ class npc_lokhtos_darkbargainer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_lokhtos_darkbargainerAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -535,7 +539,7 @@ public: void DoGo(uint32 id, uint32 state) { - if (GameObject* go = instance->instance->GetGameObject(instance->GetGuidData(id))) + if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(id))) go->SetGoState((GOState)state); } @@ -622,7 +626,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h index 9944300d7f1..5102c58b9b6 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h @@ -19,6 +19,9 @@ #ifndef DEF_BRD_H #define DEF_BRD_H +#include "CreatureAIImpl.h" + +#define BRDScriptName "instance_blackrock_depths" #define DataHeader "BRD" enum BRDFactionIds @@ -64,4 +67,10 @@ enum BRDDataTypes DATA_COREN = 28 }; +template +inline AI* GetBlackrockDepthsAI(T* obj) +{ + return GetInstanceAI(obj, BRDScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_ambassador_flamelash.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_ambassador_flamelash.cpp index 41beda843e4..83c3f7037c4 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_ambassador_flamelash.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_ambassador_flamelash.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "blackrock_depths.h" #include "ScriptedCreature.h" enum Spells @@ -89,7 +90,7 @@ class boss_ambassador_flamelash : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_ambassador_flamelashAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp index 37b7e892ae5..7d3d77f52b1 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp @@ -16,16 +16,20 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "blackrock_depths.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "Group.h" +#include "InstanceScript.h" +#include "LFGMgr.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "SpellScript.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "SpellAuras.h" -#include "LFGMgr.h" -#include "Group.h" -#include "GridNotifiers.h" -#include "GameObjectAI.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum DirebrewSays { @@ -274,7 +278,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -338,7 +342,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -370,7 +374,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -412,7 +416,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -455,7 +459,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetBlackrockDepthsAI(go); } }; @@ -471,10 +475,7 @@ class spell_direbrew_disarm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DIREBREW_DISARM) - || !sSpellMgr->GetSpellInfo(SPELL_DIREBREW_DISARM_GROW)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DIREBREW_DISARM, SPELL_DIREBREW_DISARM_GROW }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -517,9 +518,7 @@ class spell_direbrew_summon_mole_machine_target_picker : public SpellScriptLoade bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOLE_MACHINE_MINION_SUMMONER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MOLE_MACHINE_MINION_SUMMONER }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -603,9 +602,7 @@ class spell_request_second_mug : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SEND_SECOND_MUG)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SEND_SECOND_MUG }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -637,9 +634,7 @@ class spell_send_mug_control_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SEND_MUG_TARGET_PICKER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SEND_MUG_TARGET_PICKER }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp index b3b3a0f2b4c..0f518a8284a 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_depths.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Yells { @@ -112,7 +114,7 @@ class boss_emperor_dagran_thaurissan : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_general_angerforge.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_general_angerforge.cpp index c17de75a6cf..b9883a1e9f0 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_general_angerforge.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_general_angerforge.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "blackrock_depths.h" #include "ScriptedCreature.h" enum Spells @@ -130,7 +131,7 @@ class boss_general_angerforge : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_general_angerforgeAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_high_interrogator_gerstahn.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_high_interrogator_gerstahn.cpp index 691df9b587d..277af244871 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_high_interrogator_gerstahn.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_high_interrogator_gerstahn.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "blackrock_depths.h" #include "ScriptedCreature.h" enum Spells @@ -99,7 +100,7 @@ class boss_high_interrogator_gerstahn : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_high_interrogator_gerstahnAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp index fe432438811..68441159eaa 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_depths.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Spells { @@ -105,7 +106,7 @@ class boss_magmus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_magmusAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_moira_bronzebeard.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_moira_bronzebeard.cpp index b1cc51e37a9..461322596cc 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_moira_bronzebeard.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_moira_bronzebeard.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "blackrock_depths.h" #include "ScriptedCreature.h" enum Spells @@ -93,7 +94,7 @@ class boss_moira_bronzebeard : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_moira_bronzebeardAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp index 31dd2ffd487..787de8711f2 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp @@ -17,10 +17,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "blackrock_depths.h" +#include "InstanceScript.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" enum Spells { @@ -102,7 +103,7 @@ class boss_gloomrel : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -265,7 +266,7 @@ class boss_doomrel : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp index 1bc8d78b79a..1ac6dfd542c 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp @@ -17,9 +17,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "blackrock_depths.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" #define TIMER_TOMBOFTHESEVEN 15000 #define MAX_ENCOUNTER 6 @@ -68,7 +73,7 @@ enum GameObjects class instance_blackrock_depths : public InstanceMapScript { public: - instance_blackrock_depths() : InstanceMapScript("instance_blackrock_depths", 230) { } + instance_blackrock_depths() : InstanceMapScript(BRDScriptName, 230) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -130,22 +135,22 @@ public: { switch (creature->GetEntry()) { - case NPC_EMPEROR: EmperorGUID = creature->GetGUID(); break; - case NPC_PHALANX: PhalanxGUID = creature->GetGUID(); break; - case NPC_MOIRA: MoiraGUID = creature->GetGUID(); break; - case NPC_COREN: CorenGUID = creature->GetGUID(); break; - case NPC_DOOMREL: TombBossGUIDs[0] = creature->GetGUID(); break; - case NPC_DOPEREL: TombBossGUIDs[1] = creature->GetGUID(); break; - case NPC_HATEREL: TombBossGUIDs[2] = creature->GetGUID(); break; - case NPC_VILEREL: TombBossGUIDs[3] = creature->GetGUID(); break; - case NPC_SEETHREL: TombBossGUIDs[4] = creature->GetGUID(); break; - case NPC_GLOOMREL: TombBossGUIDs[5] = creature->GetGUID(); break; - case NPC_ANGERREL: TombBossGUIDs[6] = creature->GetGUID(); break; - case NPC_MAGMUS: - MagmusGUID = creature->GetGUID(); - if (!creature->IsAlive()) - HandleGameObject(GetGuidData(DATA_THRONE_DOOR), true); // if Magmus is dead open door to last boss - break; + case NPC_EMPEROR: EmperorGUID = creature->GetGUID(); break; + case NPC_PHALANX: PhalanxGUID = creature->GetGUID(); break; + case NPC_MOIRA: MoiraGUID = creature->GetGUID(); break; + case NPC_COREN: CorenGUID = creature->GetGUID(); break; + case NPC_DOOMREL: TombBossGUIDs[0] = creature->GetGUID(); break; + case NPC_DOPEREL: TombBossGUIDs[1] = creature->GetGUID(); break; + case NPC_HATEREL: TombBossGUIDs[2] = creature->GetGUID(); break; + case NPC_VILEREL: TombBossGUIDs[3] = creature->GetGUID(); break; + case NPC_SEETHREL: TombBossGUIDs[4] = creature->GetGUID(); break; + case NPC_GLOOMREL: TombBossGUIDs[5] = creature->GetGUID(); break; + case NPC_ANGERREL: TombBossGUIDs[6] = creature->GetGUID(); break; + case NPC_MAGMUS: + MagmusGUID = creature->GetGUID(); + if (!creature->IsAlive()) + HandleGameObject(GetGuidData(DATA_THRONE_DOOR), true); // if Magmus is dead open door to last boss + break; } } @@ -153,33 +158,33 @@ public: { switch (go->GetEntry()) { - case GO_ARENA1: GoArena1GUID = go->GetGUID(); break; - case GO_ARENA2: GoArena2GUID = go->GetGUID(); break; - case GO_ARENA3: GoArena3GUID = go->GetGUID(); break; - case GO_ARENA4: GoArena4GUID = go->GetGUID(); break; - case GO_SHADOW_LOCK: GoShadowLockGUID = go->GetGUID(); break; - case GO_SHADOW_MECHANISM: GoShadowMechGUID = go->GetGUID(); break; - case GO_SHADOW_GIANT_DOOR: GoShadowGiantGUID = go->GetGUID(); break; - case GO_SHADOW_DUMMY: GoShadowDummyGUID = go->GetGUID(); break; - case GO_BAR_KEG_SHOT: GoBarKegGUID = go->GetGUID(); break; - case GO_BAR_KEG_TRAP: GoBarKegTrapGUID = go->GetGUID(); break; - case GO_BAR_DOOR: GoBarDoorGUID = go->GetGUID(); break; - case GO_TOMB_ENTER: GoTombEnterGUID = go->GetGUID(); break; - case GO_TOMB_EXIT: - GoTombExitGUID = go->GetGUID(); - if (GhostKillCount >= 7) - HandleGameObject(ObjectGuid::Empty, true, go); - else - HandleGameObject(ObjectGuid::Empty, false, go); - break; - case GO_LYCEUM: GoLyceumGUID = go->GetGUID(); break; - case GO_SF_S: GoSFSGUID = go->GetGUID(); break; - case GO_SF_N: GoSFNGUID = go->GetGUID(); break; - case GO_GOLEM_ROOM_N: GoGolemNGUID = go->GetGUID(); break; - case GO_GOLEM_ROOM_S: GoGolemSGUID = go->GetGUID(); break; - case GO_THRONE_ROOM: GoThroneGUID = go->GetGUID(); break; - case GO_CHEST_SEVEN: GoChestGUID = go->GetGUID(); break; - case GO_SPECTRAL_CHALICE: GoSpectralChaliceGUID = go->GetGUID(); break; + case GO_ARENA1: GoArena1GUID = go->GetGUID(); break; + case GO_ARENA2: GoArena2GUID = go->GetGUID(); break; + case GO_ARENA3: GoArena3GUID = go->GetGUID(); break; + case GO_ARENA4: GoArena4GUID = go->GetGUID(); break; + case GO_SHADOW_LOCK: GoShadowLockGUID = go->GetGUID(); break; + case GO_SHADOW_MECHANISM: GoShadowMechGUID = go->GetGUID(); break; + case GO_SHADOW_GIANT_DOOR: GoShadowGiantGUID = go->GetGUID(); break; + case GO_SHADOW_DUMMY: GoShadowDummyGUID = go->GetGUID(); break; + case GO_BAR_KEG_SHOT: GoBarKegGUID = go->GetGUID(); break; + case GO_BAR_KEG_TRAP: GoBarKegTrapGUID = go->GetGUID(); break; + case GO_BAR_DOOR: GoBarDoorGUID = go->GetGUID(); break; + case GO_TOMB_ENTER: GoTombEnterGUID = go->GetGUID(); break; + case GO_TOMB_EXIT: + GoTombExitGUID = go->GetGUID(); + if (GhostKillCount >= 7) + HandleGameObject(ObjectGuid::Empty, true, go); + else + HandleGameObject(ObjectGuid::Empty, false, go); + break; + case GO_LYCEUM: GoLyceumGUID = go->GetGUID(); break; + case GO_SF_S: GoSFSGUID = go->GetGUID(); break; + case GO_SF_N: GoSFNGUID = go->GetGUID(); break; + case GO_GOLEM_ROOM_N: GoGolemNGUID = go->GetGUID(); break; + case GO_GOLEM_ROOM_S: GoGolemSGUID = go->GetGUID(); break; + case GO_THRONE_ROOM: GoThroneGUID = go->GetGUID(); break; + case GO_CHEST_SEVEN: GoChestGUID = go->GetGUID(); break; + case GO_SPECTRAL_CHALICE: GoSpectralChaliceGUID = go->GetGUID(); break; } } @@ -205,30 +210,30 @@ public: switch (type) { - case TYPE_RING_OF_LAW: - encounter[0] = data; - break; - case TYPE_VAULT: - encounter[1] = data; - break; - case TYPE_BAR: - if (data == SPECIAL) - ++BarAleCount; - else - encounter[2] = data; - break; - case TYPE_TOMB_OF_SEVEN: - encounter[3] = data; - break; - case TYPE_LYCEUM: - encounter[4] = data; - break; - case TYPE_IRON_HALL: - encounter[5] = data; - break; - case DATA_GHOSTKILL: - GhostKillCount += data; - break; + case TYPE_RING_OF_LAW: + encounter[0] = data; + break; + case TYPE_VAULT: + encounter[1] = data; + break; + case TYPE_BAR: + if (data == SPECIAL) + ++BarAleCount; + else + encounter[2] = data; + break; + case TYPE_TOMB_OF_SEVEN: + encounter[3] = data; + break; + case TYPE_LYCEUM: + encounter[4] = data; + break; + case TYPE_IRON_HALL: + encounter[5] = data; + break; + case DATA_GHOSTKILL: + GhostKillCount += data; + break; } if (data == DONE || GhostKillCount >= 7) @@ -250,23 +255,23 @@ public: { switch (type) { - case TYPE_RING_OF_LAW: - return encounter[0]; - case TYPE_VAULT: - return encounter[1]; - case TYPE_BAR: - if (encounter[2] == IN_PROGRESS && BarAleCount == 3) - return SPECIAL; - else - return encounter[2]; - case TYPE_TOMB_OF_SEVEN: - return encounter[3]; - case TYPE_LYCEUM: - return encounter[4]; - case TYPE_IRON_HALL: - return encounter[5]; - case DATA_GHOSTKILL: - return GhostKillCount; + case TYPE_RING_OF_LAW: + return encounter[0]; + case TYPE_VAULT: + return encounter[1]; + case TYPE_BAR: + if (encounter[2] == IN_PROGRESS && BarAleCount == 3) + return SPECIAL; + else + return encounter[2]; + case TYPE_TOMB_OF_SEVEN: + return encounter[3]; + case TYPE_LYCEUM: + return encounter[4]; + case TYPE_IRON_HALL: + return encounter[5]; + case DATA_GHOSTKILL: + return GhostKillCount; } return 0; } @@ -275,42 +280,42 @@ public: { switch (data) { - case DATA_EMPEROR: - return EmperorGUID; - case DATA_PHALANX: - return PhalanxGUID; - case DATA_MOIRA: - return MoiraGUID; - case DATA_COREN: - return CorenGUID; - case DATA_ARENA1: - return GoArena1GUID; - case DATA_ARENA2: - return GoArena2GUID; - case DATA_ARENA3: - return GoArena3GUID; - case DATA_ARENA4: - return GoArena4GUID; - case DATA_GO_BAR_KEG: - return GoBarKegGUID; - case DATA_GO_BAR_KEG_TRAP: - return GoBarKegTrapGUID; - case DATA_GO_BAR_DOOR: - return GoBarDoorGUID; - case DATA_EVENSTARTER: - return TombEventStarterGUID; - case DATA_SF_BRAZIER_N: - return GoSFNGUID; - case DATA_SF_BRAZIER_S: - return GoSFSGUID; - case DATA_THRONE_DOOR: - return GoThroneGUID; - case DATA_GOLEM_DOOR_N: - return GoGolemNGUID; - case DATA_GOLEM_DOOR_S: - return GoGolemSGUID; - case DATA_GO_CHALICE: - return GoSpectralChaliceGUID; + case DATA_EMPEROR: + return EmperorGUID; + case DATA_PHALANX: + return PhalanxGUID; + case DATA_MOIRA: + return MoiraGUID; + case DATA_COREN: + return CorenGUID; + case DATA_ARENA1: + return GoArena1GUID; + case DATA_ARENA2: + return GoArena2GUID; + case DATA_ARENA3: + return GoArena3GUID; + case DATA_ARENA4: + return GoArena4GUID; + case DATA_GO_BAR_KEG: + return GoBarKegGUID; + case DATA_GO_BAR_KEG_TRAP: + return GoBarKegTrapGUID; + case DATA_GO_BAR_DOOR: + return GoBarDoorGUID; + case DATA_EVENSTARTER: + return TombEventStarterGUID; + case DATA_SF_BRAZIER_N: + return GoSFNGUID; + case DATA_SF_BRAZIER_S: + return GoSFSGUID; + case DATA_THRONE_DOOR: + return GoThroneGUID; + case DATA_GOLEM_DOOR_N: + return GoGolemNGUID; + case DATA_GOLEM_DOOR_S: + return GoGolemSGUID; + case DATA_GO_CHALICE: + return GoSpectralChaliceGUID; } return ObjectGuid::Empty; } @@ -320,7 +325,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { @@ -375,7 +380,7 @@ public: boss->CombatStop(true); boss->LoadCreaturesAddon(); boss->GetMotionMaster()->MoveTargetedHome(); - boss->SetLootRecipient(NULL); + boss->SetLootRecipient(nullptr); } boss->SetFaction(FACTION_FRIENDLY); } diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h index 8251d96dc58..8d9b2c393bb 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h @@ -18,6 +18,8 @@ #ifndef DEF_BLACKROCK_SPIRE_H #define DEF_BLACKROCK_SPIRE_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 23; #define BRSScriptName "instance_blackrock_spire" @@ -120,4 +122,10 @@ enum BRSGameObjectsIds GO_PORTCULLIS_TOBOSSROOMS = 175186 }; +template +inline AI* GetBlackrockSpireAI(T* obj) +{ + return GetInstanceAI(obj, BRSScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_drakkisath.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_drakkisath.cpp index 56f5580daa0..6dac4937a8a 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_drakkisath.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_drakkisath.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -105,7 +105,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_drakkisathAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp index 5e76a4e020b..a62da8ea9ed 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" #include "TemporarySummon.h" enum Spells @@ -105,7 +106,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_gizrul_the_slavenerAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp index 34eae895bae..4a469a3b716 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Spells { @@ -176,7 +179,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_halycon.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_halycon.cpp index 7626afd3fff..591cb75ecc7 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_halycon.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_halycon.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -112,7 +112,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_halyconAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_highlord_omokk.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_highlord_omokk.cpp index a8766ac625b..39742ea6a3f 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_highlord_omokk.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_highlord_omokk.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -39,7 +39,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_highlordomokkAI(creature); + return GetBlackrockSpireAI(creature); } struct boss_highlordomokkAI : public BossAI diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp index 17ae664c816..576b9e5e3eb 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Spells { @@ -138,7 +139,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_mother_smolderweb.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_mother_smolderweb.cpp index aaf86640eb7..92df2fa0d74 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_mother_smolderweb.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_mother_smolderweb.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -40,7 +40,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_mothersmolderwebAI(creature); + return GetBlackrockSpireAI(creature); } struct boss_mothersmolderwebAI : public BossAI diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp index 18689249237..eb77fa7bf5e 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp @@ -17,8 +17,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -52,7 +53,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_overlordwyrmthalakAI(creature); + return GetBlackrockSpireAI(creature); } struct boss_overlordwyrmthalakAI : public BossAI diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp index 9dcaf290cb8..61aa94b4d02 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp @@ -15,12 +15,15 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" -#include "Spell.h" #include "blackrock_spire.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" enum Text { @@ -104,10 +107,10 @@ public: break; case 2: // Close these two doors on Blackhand Incarcerators aggro - if (GameObject* door1 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_IN))) + if (GameObject* door1 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_IN))) if (door1->GetGoState() == GO_STATE_ACTIVE) door1->SetGoState(GO_STATE_READY); - if (GameObject* door2 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_DOORS))) + if (GameObject* door2 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_DOORS))) if (door2->GetGoState() == GO_STATE_ACTIVE) door2->SetGoState(GO_STATE_READY); break; @@ -166,33 +169,33 @@ public: void OpenDoors(bool Boss_Killed) { // These two doors reopen on reset or boss kill - if (GameObject* door1 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_IN))) + if (GameObject* door1 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_IN))) door1->SetGoState(GO_STATE_ACTIVE); - if (GameObject* door2 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_DOORS))) + if (GameObject* door2 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_DOORS))) door2->SetGoState(GO_STATE_ACTIVE); // This door opens on boss kill if (Boss_Killed) - if (GameObject* door3 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_OUT))) + if (GameObject* door3 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_OUT))) door3->SetGoState(GO_STATE_ACTIVE); } void UpdateRunes(GOState state) { // update all runes - if (GameObject* rune1 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_1))) + if (GameObject* rune1 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_1))) rune1->SetGoState(state); - if (GameObject* rune2 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_2))) + if (GameObject* rune2 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_2))) rune2->SetGoState(state); - if (GameObject* rune3 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_3))) + if (GameObject* rune3 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_3))) rune3->SetGoState(state); - if (GameObject* rune4 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_4))) + if (GameObject* rune4 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_4))) rune4->SetGoState(state); - if (GameObject* rune5 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_5))) + if (GameObject* rune5 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_5))) rune5->SetGoState(state); - if (GameObject* rune6 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_6))) + if (GameObject* rune6 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_6))) rune6->SetGoState(state); - if (GameObject* rune7 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_7))) + if (GameObject* rune7 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_7))) rune7->SetGoState(state); } @@ -250,7 +253,7 @@ public: { // Check to see if all players in instance have aura SPELL_EMBERSEER_START before starting event bool _hasAura = true; - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (Player* player = itr->GetSource()->ToPlayer()) if (!player->HasAura(SPELL_EMBERSEER_OBJECT_VISUAL)) @@ -312,7 +315,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; @@ -436,7 +439,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_blackhand_incarceratorAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_quartermaster_zigris.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_quartermaster_zigris.cpp index aff9775b795..9ca38215d2d 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_quartermaster_zigris.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_quartermaster_zigris.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -92,7 +92,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_quatermasterzigrisAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp index 1e99e07f9e0..1f5bd2a4cd0 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" #include "blackrock_spire.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Spells { @@ -372,37 +375,37 @@ public: me->SummonCreature(NPC_GYTH, 211.762f, -397.5885f, 111.1817f, 4.747295f); break; case EVENT_WAVE_1: - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_2: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_3: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_4: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_5: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_6: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; @@ -452,7 +455,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_shadow_hunter_voshgajin.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_shadow_hunter_voshgajin.cpp index 79d556fc51d..3b3dd5c1892 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_shadow_hunter_voshgajin.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_shadow_hunter_voshgajin.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -41,7 +41,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_shadowvoshAI(creature); + return GetBlackrockSpireAI(creature); } struct boss_shadowvoshAI : public BossAI diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_the_beast.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_the_beast.cpp index 5cd6e60a186..6b1c72cb715 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_the_beast.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_the_beast.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -41,7 +41,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_thebeastAI(creature); + return GetBlackrockSpireAI(creature); } struct boss_thebeastAI : public BossAI diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_urok_doomhowl.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_urok_doomhowl.cpp index 0b4e238a8b1..fb0fc3e20d8 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_urok_doomhowl.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_urok_doomhowl.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -101,7 +101,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_urok_doomhowlAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_warmaster_voone.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_warmaster_voone.cpp index b1db789dcb3..6b627e97a8d 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_warmaster_voone.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_warmaster_voone.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" enum Spells { @@ -119,7 +119,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_warmastervooneAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp index bf6197110fa..21fe1450a3b 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp @@ -15,15 +15,14 @@ * with this program. If not, see . */ -#include "Cell.h" +#include "ScriptMgr.h" +#include "blackrock_spire.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "InstanceScript.h" +#include "ObjectAccessor.h" #include "Player.h" #include "ScriptedCreature.h" -#include "ScriptMgr.h" -#include "blackrock_spire.h" //uint32 const DragonspireRunes[7] = { GO_HALL_RUNE_1, GO_HALL_RUNE_2, GO_HALL_RUNE_3, GO_HALL_RUNE_4, GO_HALL_RUNE_5, GO_HALL_RUNE_6, GO_HALL_RUNE_7 }; @@ -120,7 +119,7 @@ public: switch (go->GetEntry()) { case GO_WHELP_SPAWNER: - go->CastSpell(NULL, SPELL_SUMMON_ROOKERY_WHELP); + go->CastSpell(nullptr, SPELL_SUMMON_ROOKERY_WHELP); break; case GO_EMBERSEER_IN: go_emberseerin = go->GetGUID(); @@ -419,8 +418,8 @@ public: void Dragonspireroomcheck() { - Creature* mob = NULL; - GameObject* rune = NULL; + Creature* mob = nullptr; + GameObject* rune = nullptr; for (uint8 i = 0; i < 7; ++i) { @@ -528,7 +527,7 @@ class at_dragonspire_hall : public AreaTriggerScript public: at_dragonspire_hall() : AreaTriggerScript("at_dragonspire_hall") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player && player->IsAlive()) { @@ -552,7 +551,7 @@ class at_blackrock_stadium : public AreaTriggerScript public: at_blackrock_stadium() : AreaTriggerScript("at_blackrock_stadium") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player && player->IsAlive()) { @@ -576,10 +575,12 @@ class at_nearby_scarshield_infiltrator : public AreaTriggerScript public: at_nearby_scarshield_infiltrator() : AreaTriggerScript("at_nearby_scarshield_infiltrator") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player->IsAlive()) + { if (InstanceScript* instance = player->GetInstanceScript()) + { if (Creature* infiltrator = ObjectAccessor::GetCreature(*player, instance->GetGuidData(DATA_SCARSHIELD_INFILTRATOR))) { if (player->getLevel() >= 57) @@ -589,6 +590,8 @@ public: return true; } + } + } return false; } diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h index 79f47eeb412..ce31344222d 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h @@ -18,9 +18,11 @@ #ifndef DEF_BLACKWING_LAIR_H #define DEF_BLACKWING_LAIR_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 8; -#define BRLScriptName "instance_blackwing_lair" +#define BWLScriptName "instance_blackwing_lair" #define DataHeader "BWL" enum BWLEncounter @@ -80,4 +82,10 @@ enum BWLMisc DATA_EGG_EVENT }; +template +inline AI* GetBlackwingLairAI(T* obj) +{ + return GetInstanceAI(obj, BWLScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp index 2973622d842..d8403641dfa 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Say { @@ -110,7 +110,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp index 7198bd276e6..26619a9b730 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp @@ -17,9 +17,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" #include "blackwing_lair.h" +#include "Map.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Emotes { @@ -240,7 +241,7 @@ public: break; case EVENT_AFFLICTION: { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if (Player* player = itr->GetSource()->ToPlayer()) @@ -290,7 +291,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp index 44332ac7663..d31b9f84778 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Spells { @@ -90,7 +90,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp index 958ff2ef3fa..024fc54e6a0 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Spells { @@ -92,7 +92,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp index 9161c6bb4ca..31d606975bb 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Emotes { @@ -98,7 +98,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp index 1d4ce755908..f213a2be37c 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp @@ -17,10 +17,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedGossip.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" enum Events { @@ -351,7 +355,7 @@ public: nefarian->setActive(true); nefarian->SetCanFly(true); nefarian->SetDisableGravity(true); - nefarian->CastSpell((Unit*)NULL, SPELL_SHADOWFLAME_INITIAL); + nefarian->CastSpell((Unit*)nullptr, SPELL_SHADOWFLAME_INITIAL); nefarian->GetMotionMaster()->MovePoint(1, NefarianLoc[1]); } events.CancelEvent(EVENT_MIND_CONTROL); @@ -388,7 +392,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; @@ -594,7 +598,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp index b425f234df9..b7c4e32188d 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp @@ -17,11 +17,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "GameObjectAI.h" #include "blackwing_lair.h" +#include "InstanceScript.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" enum Say { @@ -169,7 +171,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; @@ -200,7 +202,7 @@ class go_orb_of_domination : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetBlackwingLairAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp index b8993354501..491d37f59c4 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp @@ -17,12 +17,13 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" -#include "ScriptedGossip.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -239,7 +240,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_vaelAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp index a65620d7dca..bfd3d2ef3be 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp @@ -15,10 +15,15 @@ * with this program. If not, see . */ -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "blackwing_lair.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" DoorData const doorData[] = { @@ -63,7 +68,7 @@ uint32 const Entry[5] = {12422, 12458, 12416, 12420, 12459}; class instance_blackwing_lair : public InstanceMapScript { public: - instance_blackwing_lair() : InstanceMapScript(BRLScriptName, 469) { } + instance_blackwing_lair() : InstanceMapScript(BWLScriptName, 469) { } struct instance_blackwing_lair_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp index 7f473c00f53..ef9378df968 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_baron_geddon.cpp @@ -23,12 +23,12 @@ SDComment: SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "molten_core.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" #include "SpellScript.h" +#include "ObjectMgr.h" enum Emotes { @@ -121,7 +121,7 @@ class boss_baron_geddon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_baron_geddonAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_garr.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_garr.cpp index 64e59f480bf..580495bd6c7 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_garr.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_garr.cpp @@ -23,10 +23,10 @@ SDComment: Adds NYI SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "molten_core.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Spells { @@ -100,7 +100,7 @@ class boss_garr : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_garrAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -160,7 +160,7 @@ class npc_firesworn : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_fireswornAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_gehennas.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_gehennas.cpp index b55c939bfec..43454e9b840 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_gehennas.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_gehennas.cpp @@ -23,10 +23,10 @@ SDComment: Adds MC NYI SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "molten_core.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Spells { @@ -103,7 +103,7 @@ class boss_gehennas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_gehennasAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp index 1fa97bdecdb..c05454daea7 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp @@ -23,10 +23,12 @@ SDComment: Timers need to be confirmed, Golemagg's Trust need to be checked SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "molten_core.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Texts { @@ -121,7 +123,7 @@ class boss_golemagg : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_golemaggAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -188,7 +190,7 @@ class npc_core_rager : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_lucifron.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_lucifron.cpp index 190aa91aa6d..5a5baf50b79 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_lucifron.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_lucifron.cpp @@ -23,10 +23,10 @@ SDComment: SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "molten_core.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Spells { @@ -101,7 +101,7 @@ class boss_lucifron : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_lucifronAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_magmadar.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_magmadar.cpp index 6ed123d465b..1fa9bfeec25 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_magmadar.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_magmadar.cpp @@ -23,10 +23,10 @@ SDComment: Conflag on ground nyi SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "molten_core.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Texts { @@ -115,7 +115,7 @@ class boss_magmadar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_magmadarAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp index 7bf91173432..73c1664e71f 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp @@ -23,12 +23,14 @@ SDComment: Correct spawning and Event NYI SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "InstanceScript.h" +#include "Map.h" #include "molten_core.h" +#include "ObjectMgr.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" enum Texts { @@ -108,7 +110,7 @@ class boss_majordomo : public CreatureScript if (!me->FindNearestCreature(NPC_FLAMEWAKER_HEALER, 100.0f) && !me->FindNearestCreature(NPC_FLAMEWAKER_ELITE, 100.0f)) { - instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, me->GetEntry(), me); + instance->UpdateEncounterStateForKilledCreature(me->GetEntry(), me); me->SetFaction(FACTION_FRIENDLY); EnterEvadeMode(); Talk(SAY_DEFEAT); @@ -208,7 +210,7 @@ class boss_majordomo : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp index 481472f854e..49bb5f11ecc 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp @@ -24,8 +24,11 @@ SDCategory: Molten Core EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "molten_core.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Texts { @@ -309,7 +312,7 @@ class boss_ragnaros : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -344,7 +347,7 @@ class npc_son_of_flame : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp index 1ea9a069588..bf7e1d8a213 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" +#include "molten_core.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "molten_core.h" enum Spells { @@ -115,7 +115,7 @@ class boss_shazzrah : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_shazzrahAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -131,9 +131,7 @@ class spell_shazzrah_gate_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAZZRAH_GATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAZZRAH_GATE }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_sulfuron_harbinger.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_sulfuron_harbinger.cpp index 6f1cfa94114..778e4bd9069 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_sulfuron_harbinger.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_sulfuron_harbinger.cpp @@ -23,10 +23,10 @@ SDComment: Adds NYI SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "molten_core.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Spells { @@ -132,7 +132,7 @@ class boss_sulfuron : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_sulfuronAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -211,7 +211,7 @@ class npc_flamewaker_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_flamewaker_priestAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp index 47797d09332..a3f990ea34d 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp @@ -15,10 +15,13 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "molten_core.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" Position const SummonPositions[10] = { @@ -34,10 +37,13 @@ Position const SummonPositions[10] = {838.510f, -829.840f, -232.000f, 2.00000f}, }; +Position const RagnarosTelePos = {829.159f, -815.773f, -228.972f, 5.30500f}; +Position const RagnarosSummonPos = {838.510f, -829.840f, -232.000f, 2.00000f}; + class instance_molten_core : public InstanceMapScript { public: - instance_molten_core() : InstanceMapScript("instance_molten_core", 409) { } + instance_molten_core() : InstanceMapScript(MCScriptName, 409) { } struct instance_molten_core_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h index 45037170b7e..9e582985088 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h @@ -19,6 +19,11 @@ #ifndef DEF_MOLTEN_CORE_H #define DEF_MOLTEN_CORE_H +#include "CreatureAIImpl.h" + +struct Position; + +#define MCScriptName "instance_molten_core" #define DataHeader "MC" enum MCEncounters @@ -42,8 +47,8 @@ enum MCActions ACTION_START_RAGNAROS_ALT = 1, }; -Position const RagnarosTelePos = {829.159f, -815.773f, -228.972f, 5.30500f}; -Position const RagnarosSummonPos = {838.510f, -829.840f, -232.000f, 2.00000f}; +extern Position const RagnarosTelePos; +extern Position const RagnarosSummonPos; enum MCCreatures { @@ -71,4 +76,10 @@ enum MCData DATA_RAGNAROS_ADDS = 0, }; +template +inline AI* GetMoltenCoreAI(T* obj) +{ + return GetInstanceAI(obj, MCScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp b/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp index b9d3a96f338..89239a8fb24 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp @@ -22,8 +22,12 @@ SDComment: Timers and say taken from acid script EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "deadmines.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { @@ -53,7 +57,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetDeadminesAI(creature); } struct boss_mr_smiteAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp index c9e83cf2bfe..d8887dea5a7 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp @@ -24,10 +24,13 @@ SDCategory: Deadmines EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "deadmines.h" -#include "Spell.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Item.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" #include "WorldSession.h" /*##### diff --git a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h index 33abf4b8eee..a2778fb38c0 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h +++ b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h @@ -18,6 +18,9 @@ #ifndef DEF_DEADMINES_H #define DEF_DEADMINES_H +#include "CreatureAIImpl.h" + +#define DMScriptName "instance_deadmines" #define DataHeader "DM" enum DMCannonState @@ -61,4 +64,10 @@ enum DMInstanceTexts SAY_ALARM2 = 1 }; +template +inline AI* GetDeadminesAI(T* obj) +{ + return GetInstanceAI(obj, DMScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp index 877ffd70a1b..d87274818b1 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp @@ -24,10 +24,13 @@ SDCategory: Deadmines EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "CreatureAI.h" #include "deadmines.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "TemporarySummon.h" -#include "WorldPacket.h" enum Sounds { @@ -45,8 +48,7 @@ enum Misc class instance_deadmines : public InstanceMapScript { public: - instance_deadmines() - : InstanceMapScript("instance_deadmines", 36) + instance_deadmines() : InstanceMapScript(DMScriptName, 36) { } @@ -213,15 +215,15 @@ class instance_deadmines : public InstanceMapScript { switch (type) { - case EVENT_STATE: - if (DefiasCannonGUID && IronCladDoorGUID) - State=data; - break; - case EVENT_RHAHKZOR: - if (data == DONE) - if (GameObject* go = instance->GetGameObject(FactoryDoorGUID)) - go->SetGoState(GO_STATE_ACTIVE); - break; + case EVENT_STATE: + if (DefiasCannonGUID && IronCladDoorGUID) + State = data; + break; + case EVENT_RHAHKZOR: + if (data == DONE) + if (GameObject* go = instance->GetGameObject(FactoryDoorGUID)) + go->SetGoState(GO_STATE_ACTIVE); + break; } } diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp index bf781c171e5..f787da07308 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp @@ -23,12 +23,16 @@ SDComment: Some visual effects are not implemented. Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "gnomeregan.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" #include "SpellScript.h" -#include "Player.h" -#include "gnomeregan.h" +#include "TemporarySummon.h" enum BlastmasterEmi { @@ -87,7 +91,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetGnomereganAI(creature); } struct npc_blastmaster_emi_shortfuseAI : public npc_escortAI @@ -201,7 +205,7 @@ public: void AggroAllPlayers(Creature* temp) { - Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i) { if (Player* player = i->GetSource()) @@ -304,7 +308,7 @@ public: me->SummonCreature(NPC_CAVERNDEEP_AMBUSHER, SpawnPosition[9], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 2: - if (GameObject* go = me->SummonGameObject(183410, -533.140f, -105.322f, -156.016f, 0.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -533.140f, -105.322f, -156.016f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -319,7 +323,7 @@ public: Talk(SAY_BLASTMASTER_7); break; case 4: - if (GameObject* go = me->SummonGameObject(183410, -542.199f, -96.854f, -155.790f, 0.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -542.199f, -96.854f, -155.790f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); @@ -333,7 +337,7 @@ public: me->SummonCreature(NPC_CAVERNDEEP_AMBUSHER, SpawnPosition[14], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 6: - if (GameObject* go = me->SummonGameObject(183410, -507.820f, -103.333f, -151.353f, 0.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -507.820f, -103.333f, -151.353f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -341,7 +345,7 @@ public: } break; case 7: - if (GameObject* go = me->SummonGameObject(183410, -511.829f, -86.249f, -151.431f, 0.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -511.829f, -86.249f, -151.431f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -353,9 +357,9 @@ public: me->SummonCreature(NPC_CHOMPER, SpawnPosition[16], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 9: - me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[17], G3D::Quat(), 7200); - me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[18], G3D::Quat(), 7200); - me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[19], G3D::Quat(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[17], QuaternionData(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[18], QuaternionData(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[19], QuaternionData(), 7200); break; } } @@ -503,7 +507,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_grubbisAI(creature); + return GetGnomereganAI(creature); } struct boss_grubbisAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h index 4cf4fcd0a1d..ad64a301e0a 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h @@ -18,6 +18,9 @@ #ifndef DEF_GNOMEREGAN_H #define DEF_GNOMEREGAN_H +#include "CreatureAIImpl.h" + +#define GNOScriptName "instance_gnomeregan" #define DataHeader "GNO" enum GNOGameObjectIds @@ -47,4 +50,10 @@ enum GNOData64 DATA_NPC_BASTMASTER_EMI_SHORTFUSE }; +template +inline AI* GetGnomereganAI(T* obj) +{ + return GetInstanceAI(obj, GNOScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp b/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp index 9a8ec451232..2f5f80d0f0d 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp @@ -16,8 +16,12 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" +#include "GameObject.h" #include "gnomeregan.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "Player.h" #define MAX_ENCOUNTER 1 @@ -25,7 +29,7 @@ class instance_gnomeregan : public InstanceMapScript { public: - instance_gnomeregan() : InstanceMapScript("instance_gnomeregan", 90) { } + instance_gnomeregan() : InstanceMapScript(GNOScriptName, 90) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -47,7 +51,7 @@ public: ObjectGuid uiBastmasterEmiShortfuseGUID; - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_curator.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_curator.cpp index 3c4025084d2..8676bbe9520 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_curator.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_curator.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "ScriptedCreature.h" enum CuratorSays { diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp index 2adb2d445e6..ef9dc5e2e98 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_maiden_of_virtue.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "ScriptedCreature.h" enum Spells { diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp index 55b089842e0..fa7a27082d8 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp @@ -24,9 +24,11 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" +#include "karazhan.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" -#include "karazhan.h" enum Texts { @@ -171,7 +173,7 @@ public: scheduler.Schedule(Seconds(10), Seconds(25), [this](TaskContext task) { Unit* target = nullptr; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); std::vector target_list; for (ThreatContainer::StorageType::const_iterator itr = t_list.begin(); itr != t_list.end(); ++itr) @@ -222,7 +224,7 @@ public: std::bind(&BossAI::DoMeleeAttackIfReady, this)); } - void SpellHit(Unit* /*source*/, const SpellInfo* spell) override + void SpellHit(Unit* /*source*/, SpellInfo const* spell) override { if (spell->Mechanic == MECHANIC_DISARM) Talk(SAY_DISARMED); @@ -275,7 +277,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_attumenAI(creature); + return GetKarazhanAI(creature); } }; @@ -377,7 +379,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_midnightAI(creature); + return GetKarazhanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp index 1adbbec120f..8b0f5a7a150 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp @@ -24,8 +24,11 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Yells { @@ -98,7 +101,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_moroesAI : public ScriptedAI @@ -381,7 +384,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_baroness_dorothea_millstipeAI : public boss_moroes_guestAI @@ -452,7 +455,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_baron_rafe_dreugerAI : public boss_moroes_guestAI @@ -517,7 +520,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_lady_catriona_von_indiAI : public boss_moroes_guestAI @@ -595,7 +598,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_lady_keira_berrybuckAI : public boss_moroes_guestAI @@ -677,7 +680,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_lord_robin_darisAI : public boss_moroes_guestAI @@ -741,7 +744,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_lord_crispin_ferenceAI : public boss_moroes_guestAI diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp index d026182fcb5..36777a5670c 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp @@ -24,9 +24,14 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "InstanceScript.h" #include "karazhan.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Netherspite { @@ -71,7 +76,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_netherspiteAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp index a5c968ce55a..95510202610 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" #include "karazhan.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum NightbaneSpells { @@ -375,7 +379,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } }; @@ -391,9 +395,7 @@ class spell_rain_of_bones : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SKELETON }); } void OnTrigger(AuraEffect const* aurEff) diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp index 3fc3dd1c8f8..e2843844076 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp @@ -24,9 +24,13 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" // 18 Coordinates for Infernal spawns struct InfernalPoint @@ -104,13 +108,13 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new netherspite_infernalAI(creature); + return GetKarazhanAI(creature); } struct netherspite_infernalAI : public ScriptedAI { netherspite_infernalAI(Creature* creature) : ScriptedAI(creature), - HellfireTimer(0), CleanupTimer(0), point(NULL) { } + HellfireTimer(0), CleanupTimer(0), point(nullptr) { } uint32 HellfireTimer; uint32 CleanupTimer; @@ -151,7 +155,7 @@ public: creature->AI()->KilledUnit(who); } - void SpellHit(Unit* /*who*/, const SpellInfo* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { if (spell->Id == SPELL_INFERNAL_RELAY) { @@ -179,7 +183,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_malchezaarAI : public ScriptedAI @@ -308,11 +312,11 @@ public: void EnfeebleHealthEffect() { - const SpellInfo* info = sSpellMgr->GetSpellInfo(SPELL_ENFEEBLE_EFFECT); + SpellInfo const* info = sSpellMgr->GetSpellInfo(SPELL_ENFEEBLE_EFFECT); if (!info) return; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); std::vector targets; if (t_list.empty()) @@ -356,7 +360,7 @@ public: void SummonInfernal(const uint32 /*diff*/) { - InfernalPoint *point = NULL; + InfernalPoint *point = nullptr; Position pos; if ((me->GetMapId() != 532) || positions.empty()) pos = me->GetRandomNearPosition(60); @@ -524,7 +528,7 @@ public: { if (SWPainTimer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; if (phase == 1) target = me->GetVictim(); // the tank else // anyone but the tank diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp index d3a580f5159..0f44933caeb 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp @@ -24,10 +24,13 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "InstanceScript.h" #include "GameObject.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "TemporarySummon.h" enum ShadeOfAran { @@ -86,7 +89,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_aranAI : public ScriptedAI @@ -182,7 +185,7 @@ public: void FlameWreathEffect() { std::vector targets; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); if (t_list.empty()) return; @@ -482,7 +485,7 @@ public: DrinkInturrupted = true; } - void SpellHit(Unit* /*pAttacker*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*pAttacker*/, SpellInfo const* Spell) override { //We only care about interrupt effects and only if they are durring a spell currently being cast if ((Spell->Effects[0].Effect != SPELL_EFFECT_INTERRUPT_CAST && @@ -513,7 +516,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new water_elementalAI(creature); + return GetKarazhanAI(creature); } struct water_elementalAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp index d1743771363..37c944500e5 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum TerestianSays diff --git a/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp b/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp index 589fa02f1a2..9a01970f68b 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp @@ -24,11 +24,16 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "InstanceScript.h" #include "karazhan.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /***********************************/ /*** OPERA WIZARD OF OZ EVENT *****/ @@ -118,7 +123,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_dorotheeAI : public ScriptedAI @@ -238,7 +243,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_titoAI(creature); + return GetKarazhanAI(creature); } struct npc_titoAI : public ScriptedAI @@ -312,7 +317,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_strawmanAI : public ScriptedAI @@ -368,7 +373,7 @@ public: me->DespawnOrUnsummon(); } - void SpellHit(Unit* /*caster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* Spell) override { if ((Spell->SchoolMask == SPELL_SCHOOL_MASK_FIRE) && (!(rand32() % 10))) { @@ -432,7 +437,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_tinheadAI : public ScriptedAI @@ -547,7 +552,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_roarAI : public ScriptedAI @@ -661,7 +666,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_croneAI : public ScriptedAI @@ -745,7 +750,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_cycloneAI(creature); + return GetKarazhanAI(creature); } struct npc_cycloneAI : public ScriptedAI @@ -833,7 +838,7 @@ class npc_grandmother : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_grandmotherAI(creature); + return GetKarazhanAI(creature); } }; @@ -844,7 +849,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_bigbadwolfAI : public ScriptedAI @@ -1043,7 +1048,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_julianneAI : public ScriptedAI @@ -1131,7 +1136,7 @@ public: me->DespawnOrUnsummon(); } - void SpellHit(Unit* /*caster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* Spell) override { if (Spell->Id == SPELL_DRINK_POISON) { @@ -1164,7 +1169,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct boss_romuloAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp index 6e0dd3b1ee5..9daf041e54e 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp @@ -24,8 +24,11 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" #include "karazhan.h" +#include "Map.h" /* 0 - Attumen + Midnight (optional) @@ -52,7 +55,7 @@ const Position OptionalSpawn[] = class instance_karazhan : public InstanceMapScript { public: - instance_karazhan() : InstanceMapScript("instance_karazhan", 532) { } + instance_karazhan() : InstanceMapScript(KZScriptName, 532) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -161,7 +164,7 @@ public: HandleGameObject(StageDoorRightGUID, true); if (GameObject* sideEntrance = instance->GetGameObject(SideEntranceDoor)) sideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, 16812, NULL); + UpdateEncounterStateForKilledCreature(16812, nullptr); } break; case DATA_CHESS: diff --git a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp index 09dff7b6f0f..8c5f57e9a8e 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp @@ -29,11 +29,16 @@ npc_image_of_medivh EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "InstanceScript.h" #include "karazhan.h" -#include "ScriptedEscortAI.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" enum Spells { @@ -309,7 +314,7 @@ public: { if (WipeTimer <= diff) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (PlayerList.isEmpty()) return; @@ -429,7 +434,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } struct npc_image_of_medivhAI : public ScriptedAI @@ -566,7 +571,7 @@ public: me->SetVisible(false); me->ClearInCombat(); - InstanceMap::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + InstanceMap::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (InstanceMap::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->GetSource()->IsAlive()) @@ -579,7 +584,7 @@ public: } case 15: if (Creature* arca = ObjectAccessor::GetCreature(*me, ArcanagosGUID)) - arca->DealDamage(arca, arca->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + arca->DealDamage(arca, arca->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); return 5000; default: return 9999999; diff --git a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h index c36b99e6e49..e13e108eb4b 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h +++ b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h @@ -19,6 +19,8 @@ #ifndef DEF_KARAZHAN_H #define DEF_KARAZHAN_H +#include "CreatureAIImpl.h" + #define KZScriptName "instance_karazhan" #define DataHeader "KZ" @@ -111,7 +113,7 @@ enum KZMisc OPTIONAL_BOSS_REQUIRED_DEATH_COUNT = 50 }; -template +template inline AI* GetKarazhanAI(T* obj) { return GetInstanceAI(obj, KZScriptName); diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp index 11e4fc35fdf..600ab5d379b 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp @@ -24,10 +24,13 @@ SDCategory: Magisters' Terrace EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "InstanceScript.h" #include "magisters_terrace.h" -#include "WorldPacket.h" -#include "Opcodes.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Says { @@ -69,8 +72,6 @@ enum Spells SPELL_POWER_FEEDBACK = 44233 // Stuns him, making him take 50% more damage for 10 seconds. Cast after Gravity Lapse }; - - enum Creatures { CREATURE_PHOENIX = 24674, @@ -96,7 +97,7 @@ public: CreatureAI* GetAI(Creature* c) const override { - return GetInstanceAI(c); + return GetMagistersTerraceAI(c); } struct boss_felblood_kaelthasAI : public ScriptedAI @@ -198,7 +199,7 @@ public: if (!summonedUnit) return; - ThreatContainer::StorageType const &threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); ThreatContainer::StorageType::const_iterator i = threatlist.begin(); for (i = threatlist.begin(); i != threatlist.end(); ++i) { @@ -251,11 +252,7 @@ public: { // Also needs an exception in spell system. unit->CastSpell(unit, SPELL_GRAVITY_LAPSE_FLY, true, 0, 0, me->GetGUID()); - // Use packet hack - WorldPacket data(SMSG_MOVE_SET_CAN_FLY, 12); - data << unit->GetPackGUID(); - data << uint32(0); - unit->SendMessageToSet(&data, true); + unit->SetCanFly(true); } } } @@ -271,11 +268,7 @@ public: { unit->RemoveAurasDueToSpell(SPELL_GRAVITY_LAPSE_FLY); unit->RemoveAurasDueToSpell(SPELL_GRAVITY_LAPSE_DOT); - - WorldPacket data(SMSG_MOVE_UNSET_CAN_FLY, 12); - data << unit->GetPackGUID(); - data << uint32(0); - unit->SendMessageToSet(&data, true); + unit->SetCanFly(false); } } } @@ -399,7 +392,7 @@ public: for (uint8 i = 0; i < 3; ++i) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); Creature* Orb = DoSpawnCreature(CREATURE_ARCANE_SPHERE, 5, 5, 0, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 30000); @@ -438,7 +431,7 @@ public: CreatureAI* GetAI(Creature* c) const override { - return new npc_felkael_flamestrikeAI(c); + return GetMagistersTerraceAI(c); } struct npc_felkael_flamestrikeAI : public ScriptedAI @@ -486,7 +479,7 @@ public: CreatureAI* GetAI(Creature* c) const override { - return GetInstanceAI(c); + return GetMagistersTerraceAI(c); } struct npc_felkael_phoenixAI : public ScriptedAI @@ -589,7 +582,7 @@ public: { //spell Burn should possible do this, but it doesn't, so do this for now. uint16 dmg = urand(1650, 2050); - me->DealDamage(me, dmg, 0, DOT, SPELL_SCHOOL_MASK_FIRE, NULL, false); + me->DealDamage(me, dmg, 0, DOT, SPELL_SCHOOL_MASK_FIRE, nullptr, false); BurnTimer += 2000; } BurnTimer -= diff; @@ -605,7 +598,7 @@ public: CreatureAI* GetAI(Creature* c) const override { - return new npc_felkael_phoenix_eggAI(c); + return GetMagistersTerraceAI(c); } struct npc_felkael_phoenix_eggAI : public ScriptedAI @@ -649,7 +642,7 @@ public: CreatureAI* GetAI(Creature* c) const override { - return new npc_arcane_sphereAI(c); + return GetMagistersTerraceAI(c); } struct npc_arcane_sphereAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp index ca816e8f512..8cddec4b58f 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp @@ -24,8 +24,11 @@ SDCategory: Magister's Terrace EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "magisters_terrace.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" struct Speech { @@ -110,7 +113,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_priestess_delrissaAI : public ScriptedAI @@ -315,7 +318,7 @@ public: if (DispelTimer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; if (urand(0, 1)) target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); @@ -497,7 +500,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_kagani_nightstrikeAI : public boss_priestess_lackey_commonAI @@ -609,7 +612,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_ellris_duskhallowAI : public boss_priestess_lackey_commonAI @@ -708,7 +711,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_eramas_brightblazeAI : public boss_priestess_lackey_commonAI @@ -777,7 +780,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_yazzaiAI : public boss_priestess_lackey_commonAI @@ -871,7 +874,7 @@ public: if (Blink_Timer <= diff) { bool InMeleeRange = false; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) { if (Unit* target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid())) @@ -915,7 +918,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_warlord_salarisAI : public boss_priestess_lackey_commonAI @@ -965,7 +968,7 @@ public: if (Intercept_Stun_Timer <= diff) { bool InMeleeRange = false; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) { if (Unit* target = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid())) @@ -1043,7 +1046,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_garaxxasAI : public boss_priestess_lackey_commonAI @@ -1159,7 +1162,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_apokoAI : public boss_priestess_lackey_commonAI @@ -1256,7 +1259,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); } struct boss_zelfanAI : public boss_priestess_lackey_commonAI @@ -1349,7 +1352,7 @@ public: //CreatureAI* GetAI(Creature* creature) const override //{ - // return new npc_high_explosive_sheepAI(creature); + // return GetMagistersTerraceAI(creature); //}; }; */ diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp index 1d738d56984..86592f5677c 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "magisters_terrace.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Says { @@ -263,7 +266,7 @@ class boss_selin_fireheart : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); }; }; @@ -289,7 +292,7 @@ class npc_fel_crystal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); }; }; diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp index 421c5ac45af..cf45d54cc22 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "magisters_terrace.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Yells { @@ -182,7 +183,7 @@ class boss_vexallus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); }; }; @@ -214,7 +215,7 @@ class npc_pure_energy : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_pure_energyAI(creature); + return GetMagistersTerraceAI(creature); }; }; diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp index d145944bf35..8428762b109 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "EventMap.h" +#include "GameObject.h" #include "InstanceScript.h" #include "magisters_terrace.h" -#include "EventMap.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" /* 0 - Selin Fireheart @@ -43,7 +47,7 @@ Position const KalecgosSpawnPos = { 164.3747f, -397.1197f, 2.151798f, 1.66219f } class instance_magisters_terrace : public InstanceMapScript { public: - instance_magisters_terrace() : InstanceMapScript("instance_magisters_terrace", 585) { } + instance_magisters_terrace() : InstanceMapScript(MGTScriptName, 585) { } struct instance_magisters_terrace_InstanceMapScript : public InstanceScript { @@ -147,10 +151,10 @@ class instance_magisters_terrace : public InstanceMapScript } } - void ProcessEvent(WorldObject* obj, uint32 eventId) override + void ProcessEvent(WorldObject* /*obj*/, uint32 eventId) override { if (eventId == EVENT_SPAWN_KALECGOS) - if (!ObjectAccessor::GetCreature(*obj, KalecgosGUID) && Events.Empty()) + if (!instance->GetCreature(KalecgosGUID) && Events.Empty()) Events.ScheduleEvent(EVENT_SPAWN_KALECGOS, Minutes(1)); } @@ -159,11 +163,13 @@ class instance_magisters_terrace : public InstanceMapScript Events.Update(diff); if (Events.ExecuteEvent() == EVENT_SPAWN_KALECGOS) + { if (Creature* kalecgos = instance->SummonCreature(NPC_KALECGOS, KalecgosSpawnPos)) { kalecgos->GetMotionMaster()->MovePath(PATH_KALECGOS_FLIGHT, false); kalecgos->AI()->Talk(SAY_KALECGOS_SPAWN); } + } } bool SetBossState(uint32 type, EncounterState state) override diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp index 21e90d9a24d..8dd266c5613 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp @@ -28,11 +28,11 @@ npc_kalecgos EndContentData */ #include "ScriptMgr.h" +#include "magisters_terrace.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" -#include "magisters_terrace.h" -#include "EventMap.h" /*###### ## npc_kalecgos @@ -155,7 +155,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_kalecgosAI(creature); + return GetMagistersTerraceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h index cfdee423ef1..31716bcd478 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h @@ -19,6 +19,9 @@ #ifndef DEF_MAGISTERS_TERRACE_H #define DEF_MAGISTERS_TERRACE_H +#include "CreatureAIImpl.h" + +#define MGTScriptName "instance_magisters_terrace" #define DataHeader "MT" uint32 const EncounterCount = 4; @@ -74,4 +77,10 @@ enum MTMovementData PATH_KALECGOS_FLIGHT = 248440 }; +template +inline AI* GetMagistersTerraceAI(T* obj) +{ + return GetInstanceAI(obj, MGTScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp index c384419db06..630e362957b 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp @@ -16,18 +16,21 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "ScriptedEscortAI.h" #include "CombatAI.h" -#include "PassiveAI.h" +#include "CreatureTextMgr.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Log.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "PassiveAI.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" -#include "CreatureTextMgr.h" -#include "MoveSplineInit.h" +#include "Vehicle.h" /*###### ##Quest 12848 @@ -191,7 +194,7 @@ public: TC_LOG_ERROR("scripts", "npc_unworthy_initiateAI: unable to find anchor!"); float dist = 99.0f; - GameObject* prison = NULL; + GameObject* prison = nullptr; for (uint8 i = 0; i < 12; ++i) { @@ -512,7 +515,7 @@ public: me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15); } - void SpellHit(Unit* pCaster, const SpellInfo* pSpell) override + void SpellHit(Unit* pCaster, SpellInfo const* pSpell) override { if (!m_bIsDuelInProgress && pSpell->Id == SPELL_DUEL) { @@ -767,7 +770,7 @@ public: return false; } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_DELIVER_STOLEN_HORSE) { @@ -1068,7 +1071,7 @@ class npc_scarlet_miner_cart : public CreatureScript if (apply) { _playerGUID = who->GetGUID(); - me->CastSpell((Unit*)NULL, SPELL_SUMMON_MINER, true); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_MINER, true); } else { diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp index 8ee7049398e..2378d8ddad2 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp @@ -16,11 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "CreatureTextMgr.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" #include "SpellInfo.h" -#include "CreatureTextMgr.h" //How to win friends and influence enemies // texts signed for creature 28939 but used for 28939, 28940, 28610 @@ -74,7 +76,7 @@ public: me->RestoreFaction(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_PERSUASIVE_STRIKE && caster->GetTypeId() == TYPEID_PLAYER && me->IsAlive() && !speechCounter) { @@ -91,7 +93,7 @@ public: me->SetReactState(REACT_PASSIVE); DoCastAOE(SPELL_THREAT_PULSE, true); - sCreatureTextMgr->SendChat(me, SAY_PERSUADE_RAND, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(me, SAY_PERSUADE_RAND, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); Talk(SAY_CRUSADER); } } @@ -134,7 +136,7 @@ public: break; case 5: - sCreatureTextMgr->SendChat(me, SAY_PERSUADED5, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(me, SAY_PERSUADED5, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); speechTimer = 8000; break; diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp index 319ac6b8ad3..bc950388ec7 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" #define LESS_MOB // if you do not have a good server and do not want it to be laggy as hell //Light of Dawn @@ -1084,7 +1088,7 @@ public: case 48: // Show the cleansing effect (dawn of light) //if (GameObject* go = me->GetMap()->GetGameObject(uiDawnofLightGUID)) // go->SetPhaseMask(128, true); - me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0.f, G3D::Quat(), 30); + me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0.f, QuaternionData(), 30); if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID)) { if (temp->HasAura(SPELL_REBIRTH_OF_THE_ASHBRINGER)) @@ -1262,7 +1266,7 @@ public: // go->SetPhaseMask(0, true); { // search players with in 50 yards for quest credit - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -1494,7 +1498,7 @@ public: void SpawnNPC() { - Unit* temp = NULL; + Unit* temp = nullptr; // Death for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i) diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp index 6eb25dbd8f0..2adfea2f577 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "MotionMaster.h" #include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" /*#### ## npc_valkyr_battle_maiden @@ -83,7 +85,7 @@ public: { if (FlyBackTimer <= diff) { - Player* player = NULL; + Player* player = nullptr; if (me->IsSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) player = summoner->ToPlayer(); @@ -129,10 +131,11 @@ public: break; } ++phase; - } else FlyBackTimer-=diff; + } + else + FlyBackTimer -= diff; } }; - }; void AddSC_the_scarlet_enclave() diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp index 697ff3b454e..5dcbf9490ec 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp @@ -24,14 +24,20 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "SpellMgr.h" -#include "scarlet_monastery.h" +#include "Group.h" +#include "InstanceScript.h" #include "LFGMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "Group.h" +#include "scarlet_monastery.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" //this texts are already used by 3975 and 3976 enum Says @@ -96,7 +102,7 @@ enum Spells SPELL_DEATH = 42566 //not correct spell }; -G3D::Vector3 const FlightPoint[]= +Position const FlightPoint[]= { {1754.00f, 1346.00f, 17.50f}, {1765.00f, 1347.00f, 19.00f}, @@ -121,7 +127,7 @@ G3D::Vector3 const FlightPoint[]= {1758.00f, 1367.00f, 19.51f} }; -G3D::Vector3 const Spawn[]= +Position const Spawn[]= { {1776.27f, 1348.74f, 19.20f}, //spawn point for pumpkin shrine mob {1765.28f, 1347.46f, 17.55f} //spawn point for smoke @@ -142,7 +148,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_wisp_invisAI(creature); + return GetScarletMonasteryAI(creature); } struct npc_wisp_invisAI : public ScriptedAI @@ -183,7 +189,7 @@ public: DoCast(me, _spell); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_WISP_FLIGHT_PORT && Creaturetype == 4) me->SetDisplayId(2027); @@ -221,7 +227,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_headAI(creature); + return GetScarletMonasteryAI(creature); } struct npc_headAI : public ScriptedAI @@ -298,7 +304,7 @@ public: } } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (!withbody) return; @@ -374,7 +380,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScarletMonasteryAI(creature); } struct boss_headless_horsemanAI : public ScriptedAI @@ -473,7 +479,7 @@ public: break; case 1: { - if (Creature* smoke = me->SummonCreature(HELPER, Spawn[1].x, Spawn[1].y, Spawn[1].z, 0, TEMPSUMMON_TIMED_DESPAWN, 20000)) + if (Creature* smoke = me->SummonCreature(HELPER, Spawn[1], TEMPSUMMON_TIMED_DESPAWN, 20000)) ENSURE_AI(npc_wisp_invis::npc_wisp_invisAI, smoke->AI())->SetType(3); DoCast(me, SPELL_RHYME_BIG); break; @@ -536,9 +542,9 @@ public: Player* SelectRandomPlayer(float range = 0.0f, bool checkLoS = true) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (PlayerList.isEmpty()) - return NULL; + return nullptr; std::list temp; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -552,10 +558,10 @@ public: advance(j, rand32() % temp.size()); return (*j); } - return NULL; + return nullptr; } - void SpellHitTarget(Unit* unit, const SpellInfo* spell) override + void SpellHitTarget(Unit* unit, SpellInfo const* spell) override { if (spell->Id == SPELL_CONFLAGRATION && unit->HasAura(SPELL_CONFLAGRATION)) SaySound(SAY_CONFLAGRATION, unit); @@ -581,7 +587,7 @@ public: } } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (withhead) return; @@ -682,7 +688,7 @@ public: { wp_reached = false; me->GetMotionMaster()->Clear(false); - me->GetMotionMaster()->MovePoint(id, FlightPoint[id].x, FlightPoint[id].y, FlightPoint[id].z); + me->GetMotionMaster()->MovePoint(id, FlightPoint[id]); } } } @@ -692,7 +698,7 @@ public: break; if (burn <= diff) { - if (Creature* flame = me->SummonCreature(HELPER, Spawn[0].x, Spawn[0].y, Spawn[0].z, 0, TEMPSUMMON_TIMED_DESPAWN, 17000)) + if (Creature* flame = me->SummonCreature(HELPER, Spawn[0], TEMPSUMMON_TIMED_DESPAWN, 17000)) ENSURE_AI(npc_wisp_invis::npc_wisp_invisAI, flame->AI())->SetType(2); burned = true; } @@ -784,7 +790,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_pulsing_pumpkinAI(creature); + return GetScarletMonasteryAI(creature); } struct npc_pulsing_pumpkinAI : public ScriptedAI @@ -820,7 +826,7 @@ public: void EnterCombat(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_SPROUTING) { @@ -900,7 +906,7 @@ class go_loosely_turned_soil : public GameObjectScript return; player->AreaExploredOrEventHappens(11405); - if (Creature* horseman = me->SummonCreature(HH_MOUNTED, FlightPoint[20].x, FlightPoint[20].y, FlightPoint[20].z, 0, TEMPSUMMON_MANUAL_DESPAWN, 0)) + if (Creature* horseman = me->SummonCreature(HH_MOUNTED, FlightPoint[20], TEMPSUMMON_MANUAL_DESPAWN, 0)) { ENSURE_AI(boss_headless_horseman::boss_headless_horsemanAI, horseman->AI())->PlayerGUID = player->GetGUID(); ENSURE_AI(boss_headless_horseman::boss_headless_horsemanAI, horseman->AI())->FlyMode(); diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_herod.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_herod.cpp index 7d3f0dd941c..509faae7957 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_herod.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_herod.cpp @@ -24,9 +24,9 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" +#include "scarlet_monastery.h" #include "ScriptedCreature.h" #include "ScriptedEscortAI.h" -#include "scarlet_monastery.h" enum Says { @@ -146,7 +146,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_scarlet_traineeAI(creature); + return GetScarletMonasteryAI(creature); } struct npc_scarlet_traineeAI : public npc_escortAI diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp index 12e28747256..92db652813a 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp @@ -24,8 +24,9 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "scarlet_monastery.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Spells { @@ -44,7 +45,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScarletMonasteryAI(creature); } struct boss_high_inquisitor_fairbanksAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_houndmaster_loksey.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_houndmaster_loksey.cpp index 3ec1664ee74..3a68e3a01e5 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_houndmaster_loksey.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_houndmaster_loksey.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "scarlet_monastery.h" +#include "ScriptedCreature.h" enum Yells { diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp index dd2443c12d7..eee97d1a134 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "scarlet_monastery.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Says { @@ -115,7 +117,7 @@ class boss_interrogator_vishas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScarletMonasteryAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp index cea8aa3b600..3f2a149771e 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp @@ -24,8 +24,11 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "scarlet_monastery.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Says @@ -65,7 +68,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScarletMonasteryAI(creature); } struct boss_scarlet_commander_mograineAI : public ScriptedAI @@ -160,7 +163,7 @@ public: } } - void SpellHit(Unit* /*who*/, const SpellInfo* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { //When hit with resurrection say text if (spell->Id == SPELL_SCARLETRESURRECTION) @@ -228,7 +231,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScarletMonasteryAI(creature); } struct boss_high_inquisitor_whitemaneAI : public ScriptedAI @@ -331,7 +334,7 @@ public: //If we are <75% hp cast healing spells at self or Mograine if (Heal_Timer <= diff) { - Creature* target = NULL; + Creature* target = nullptr; if (!HealthAbovePct(75)) target = me; diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp index cd07bedc628..bbce3417c02 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "scarlet_monastery.h" DoorData const doorData[] = @@ -43,26 +46,13 @@ class instance_scarlet_monastery : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_PUMPKIN_SHRINE: PumpkinShrineGUID = go->GetGUID(); break; - case GO_HIGH_INQUISITORS_DOOR: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_HIGH_INQUISITORS_DOOR: - AddDoor(go, false); - break; default: break; } diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h b/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h index 94db224f4ce..4653303cc21 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h @@ -18,6 +18,8 @@ #ifndef SCARLET_M_ #define SCARLET_M_ +#include "CreatureAIImpl.h" + #define SMScriptName "instance_scarlet_monastery" #define DataHeader "SM" @@ -60,7 +62,7 @@ enum SMGameObjectIds GO_PUMPKIN_SHRINE = 186267 }; -template +template inline AI* GetScarletMonasteryAI(T* obj) { return GetInstanceAI(obj, SMScriptName); diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp index 338aa2f62d0..dee7ea2a950 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp @@ -23,9 +23,15 @@ Category: Scholomance */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "scholomance.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" enum Says { @@ -59,14 +65,14 @@ class boss_darkmaster_gandling : public CreatureScript void Reset() override { _Reset(); - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_GANDLING))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_GANDLING))) gate->SetGoState(GO_STATE_ACTIVE); } void JustDied(Unit* /*killer*/) override { _JustDied(); - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_GANDLING))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_GANDLING))) gate->SetGoState(GO_STATE_ACTIVE); } @@ -78,7 +84,7 @@ class boss_darkmaster_gandling : public CreatureScript events.ScheduleEvent(EVENT_CURSE, 2000); events.ScheduleEvent(EVENT_SHADOW_PORTAL, 16000); - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_GANDLING))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_GANDLING))) gate->SetGoState(GO_STATE_READY); } @@ -131,7 +137,7 @@ class boss_darkmaster_gandling : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScholomanceAI(creature); } }; @@ -165,17 +171,10 @@ class spell_shadow_portal : public SpellScriptLoader { PrepareSpellScript(spell_shadow_portal_SpellScript); - public: - spell_shadow_portal_SpellScript() - { - _instance = nullptr; - } - - private: bool Load() override { _instance = GetCaster()->GetInstanceScript(); - return _instance != nullptr; + return InstanceHasScript(GetCaster(), ScholomanceScriptName); } void HandleCast(SpellEffIndex /*effIndex*/) @@ -232,7 +231,7 @@ class spell_shadow_portal : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_shadow_portal_SpellScript::HandleCast, EFFECT_0, SPELL_EFFECT_DUMMY); } - InstanceScript* _instance; + InstanceScript* _instance = nullptr; }; SpellScript* GetSpellScript() const override @@ -294,17 +293,10 @@ class spell_shadow_portal_rooms : public SpellScriptLoader { PrepareSpellScript(spell_shadow_portal_rooms_SpellScript); - public: - spell_shadow_portal_rooms_SpellScript() - { - _instance = nullptr; - } - - private: bool Load() override { _instance = GetCaster()->GetInstanceScript(); - return _instance != nullptr; + return InstanceHasScript(GetCaster(), ScholomanceScriptName); } void HandleSendEvent(SpellEffIndex effIndex) @@ -353,7 +345,7 @@ class spell_shadow_portal_rooms : public SpellScriptLoader break; } - if (gate_to_close && (caster->GetMap()->GetId() == 289)) + if (gate_to_close) { for (uint8 i = 0; i < 3; ++i) { @@ -374,7 +366,7 @@ class spell_shadow_portal_rooms : public SpellScriptLoader OnEffectHit += SpellEffectFn(spell_shadow_portal_rooms_SpellScript::HandleSendEvent, EFFECT_1, SPELL_EFFECT_SEND_EVENT); } - InstanceScript* _instance; + InstanceScript* _instance = nullptr; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp index e1b491e7453..239c042d1d4 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_death_knight_darkreaver.cpp @@ -24,6 +24,7 @@ SDCategory: Scholomance EndScriptData */ #include "ScriptMgr.h" +#include "scholomance.h" #include "ScriptedCreature.h" class boss_death_knight_darkreaver : public CreatureScript @@ -33,7 +34,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_death_knight_darkreaverAI(creature); + return GetScholomanceAI(creature); } struct boss_death_knight_darkreaverAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_doctor_theolen_krastinov.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_doctor_theolen_krastinov.cpp index 03a2bf0f293..9eec06cbb33 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_doctor_theolen_krastinov.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_doctor_theolen_krastinov.cpp @@ -23,8 +23,8 @@ Category: Scholomance */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "scholomance.h" +#include "ScriptedCreature.h" enum Say { @@ -102,7 +102,7 @@ class boss_doctor_theolen_krastinov : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_theolenkrastinovAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_illucia_barov.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_illucia_barov.cpp index cb569d2e238..8db6ade664d 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_illucia_barov.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_illucia_barov.cpp @@ -23,8 +23,8 @@ Category: Scholomance */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "scholomance.h" +#include "ScriptedCreature.h" enum Spells { @@ -103,7 +103,7 @@ class boss_illucia_barov : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_illuciabarovAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_instructor_malicia.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_instructor_malicia.cpp index e7a3bf99b43..1627fd52c9b 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_instructor_malicia.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_instructor_malicia.cpp @@ -23,8 +23,8 @@ SDCategory: Scholomance EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "scholomance.h" +#include "ScriptedCreature.h" enum Spells { @@ -148,7 +148,7 @@ class boss_instructor_malicia : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_instructormaliciaAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp index a55ecfe6a84..e4d7140e6f1 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "scholomance.h" #include "ScriptedCreature.h" enum Spells @@ -116,7 +117,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp index 4d7a8e599ab..33ad88e8d9e 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "scholomance.h" -#include "MoveSplineInit.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "scholomance.h" +#include "ScriptedCreature.h" enum Says { @@ -98,9 +102,9 @@ class boss_kirtonos_the_herald : public CreatureScript void JustDied(Unit* /*killer*/) override { - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_KIRTONOS))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_KIRTONOS))) gate->SetGoState(GO_STATE_ACTIVE); - if (GameObject* brazier = me->GetMap()->GetGameObject(instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) + if (GameObject* brazier = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) { brazier->ResetDoorOrButton(); brazier->SetGoState(GO_STATE_READY); @@ -110,9 +114,9 @@ class boss_kirtonos_the_herald : public CreatureScript void EnterEvadeMode(EvadeReason /*why*/) override { - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_KIRTONOS))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_KIRTONOS))) gate->SetGoState(GO_STATE_ACTIVE); - if (GameObject* brazier = me->GetMap()->GetGameObject(instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) + if (GameObject* brazier = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) { brazier->ResetDoorOrButton(); brazier->SetGoState(GO_STATE_READY); @@ -137,9 +141,7 @@ class boss_kirtonos_the_herald : public CreatureScript void MovementInform(uint32 type, uint32 id) override { if (type == WAYPOINT_MOTION_TYPE && id == POINT_KIRTONOS_LAND) - { events.ScheduleEvent(INTRO_2, 1500); - } } void UpdateAI(uint32 diff) override @@ -160,13 +162,13 @@ class boss_kirtonos_the_herald : public CreatureScript events.ScheduleEvent(INTRO_3, 1000); break; case INTRO_3: - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_KIRTONOS))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_KIRTONOS))) gate->SetGoState(GO_STATE_READY); me->SetFacingTo(0.01745329f); events.ScheduleEvent(INTRO_4, 3000); break; case INTRO_4: - if (GameObject* brazier = me->GetMap()->GetGameObject(instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) + if (GameObject* brazier = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) brazier->SetGoState(GO_STATE_READY); me->SetWalk(true); me->SetDisableGravity(false); @@ -256,7 +258,7 @@ class boss_kirtonos_the_herald : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScholomanceAI(creature); } }; @@ -295,7 +297,7 @@ class go_brazier_of_the_herald : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetScholomanceAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp index 121d6b51b42..8ff5fa9ccd3 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" +#include "scholomance.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "scholomance.h" enum Spells { @@ -130,7 +130,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_kormokAI(creature); + return GetScholomanceAI(creature); } }; @@ -154,10 +154,7 @@ class spell_kormok_summon_bone_mages : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint32 i = 0; i < 4; ++i) - if (!sSpellMgr->GetSpellInfo(SummonMageSpells[i])) - return false; - return true; + return ValidateSpellInfo(SummonMageSpells); } void HandleScript(SpellEffIndex effIndex) @@ -191,9 +188,7 @@ class spell_kormok_summon_bone_minions : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BONE_MINIONS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_BONE_MINIONS }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_lord_alexei_barov.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_lord_alexei_barov.cpp index 82feeaf5dd9..b5e64141aa8 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_lord_alexei_barov.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_lord_alexei_barov.cpp @@ -22,9 +22,9 @@ SDComment: aura applied/defined in database SDCategory: Scholomance EndScriptData */ +#include "scholomance.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "scholomance.h" enum Spells { @@ -98,7 +98,7 @@ class boss_lord_alexei_barov : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_lordalexeibarovAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_lorekeeper_polkelt.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_lorekeeper_polkelt.cpp index c162de33a3b..4ffb4591e09 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_lorekeeper_polkelt.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_lorekeeper_polkelt.cpp @@ -22,9 +22,9 @@ Comment: Category: Scholomance */ +#include "scholomance.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "scholomance.h" enum Spells { @@ -103,7 +103,7 @@ class boss_lorekeeper_polkelt : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_lorekeeperpolkeltAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_ras_frostwhisper.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_ras_frostwhisper.cpp index 77244dc7a93..f9994e6a3cf 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_ras_frostwhisper.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_ras_frostwhisper.cpp @@ -15,6 +15,7 @@ * with this program. If not, see . */ +#include "scholomance.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -118,7 +119,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_rasfrostAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_the_ravenian.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_the_ravenian.cpp index d2e54bf433c..75b9dc12ded 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_the_ravenian.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_the_ravenian.cpp @@ -22,9 +22,9 @@ Comment: Category: Scholomance */ +#include "scholomance.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "scholomance.h" enum Spells { @@ -103,7 +103,7 @@ class boss_the_ravenian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_theravenianAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_vectus.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_vectus.cpp index d24648b6d81..10beaee60ca 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_vectus.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_vectus.cpp @@ -15,6 +15,7 @@ * with this program. If not, see . */ +#include "scholomance.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" @@ -112,7 +113,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_vectusAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp b/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp index c6c3c6c4d10..984487f3d61 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "Player.h" #include "scholomance.h" @@ -25,7 +27,7 @@ Position const GandlingLoc = { 180.7712f, -5.428603f, 75.57024f, 1.291544f }; class instance_scholomance : public InstanceMapScript { public: - instance_scholomance() : InstanceMapScript("instance_scholomance", 289) { } + instance_scholomance() : InstanceMapScript(ScholomanceScriptName, 289) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { diff --git a/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h b/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h index abe6a7b415a..3b88f54775b 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h +++ b/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h @@ -18,6 +18,9 @@ #ifndef DEF_SCHOLOMANCE_H #define DEF_SCHOLOMANCE_H +#include "CreatureAIImpl.h" + +#define ScholomanceScriptName "instance_scholomance" #define DataHeader "SC" uint32 const EncounterCount = 8; @@ -53,4 +56,10 @@ enum SCGameobjectIds GO_BRAZIER_OF_THE_HERALD = 175564 }; +template +inline AI* GetScholomanceAI(T* obj) +{ + return GetInstanceAI(obj, ScholomanceScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp index 8e4eb61d322..e39bf1d83f3 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp @@ -16,15 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "InstanceScript.h" #include "LFGMgr.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" -#include "Group.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "shadowfang_keep.h" -#include "GridNotifiersImpl.h" +#include "SpellScript.h" enum ApothecarySpells { @@ -275,7 +277,7 @@ class boss_apothecary_hummel : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -325,7 +327,7 @@ class npc_apothecary_frye : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -388,7 +390,7 @@ class npc_apothecary_baxter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp index 9e84eb6f59e..9ec2a58f742 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp @@ -23,10 +23,13 @@ SDComment: SDCategory: Shadowfang Keep EndScriptData */ -#include "ScriptedCreature.h" #include "ScriptMgr.h" -#include "InstanceScript.h" #include "shadowfang_keep.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "ScriptedCreature.h" #include "TemporarySummon.h" #define MAX_ENCOUNTER 4 @@ -69,7 +72,7 @@ const Position SpawnLocation[] = class instance_shadowfang_keep : public InstanceMapScript { public: - instance_shadowfang_keep() : InstanceMapScript("instance_shadowfang_keep", 33) { } + instance_shadowfang_keep() : InstanceMapScript(SFKScriptName, 33) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -214,7 +217,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp index 077a5664b93..86ef68e8c4a 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp @@ -28,13 +28,13 @@ npc_shadowfang_prisoner EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ScriptedEscortAI.h" #include "shadowfang_keep.h" +#include "InstanceScript.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" /*###### ## npc_shadowfang_prisoner @@ -138,7 +138,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -149,7 +149,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } struct npc_arugal_voidwalkerAI : public ScriptedAI @@ -312,7 +312,7 @@ class boss_archmage_arugal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -333,7 +333,7 @@ class spell_shadowfang_keep_haunting_spirits : public SpellScriptLoader void HandleDummyTick(AuraEffect const* aurEff) { - GetTarget()->CastSpell((Unit*)NULL, aurEff->GetAmount(), true); + GetTarget()->CastSpell((Unit*)nullptr, aurEff->GetAmount(), true); } void HandleUpdatePeriodic(AuraEffect* aurEff) diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h index 7571f6f8fe3..3b2f6a7e105 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h @@ -19,6 +19,9 @@ #ifndef DEF_SHADOWFANG_H #define DEF_SHADOWFANG_H +#include "CreatureAIImpl.h" + +#define SFKScriptName "instance_shadowfang_keep" #define DataHeader "SK" enum SKDataTypes @@ -31,4 +34,10 @@ enum SKDataTypes DATA_APOTHECARY_HUMMEL = 6 }; +template +inline AI* GetShadowfangKeepAI(T* obj) +{ + return GetInstanceAI(obj, SFKScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp index ed8b2cfc853..2110b2b1d77 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -68,7 +69,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } struct boss_baron_rivendareAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp index f44a914121e..241f576260a 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -42,7 +43,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } struct boss_baroness_anastariAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_cannon_master_willey.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_cannon_master_willey.cpp index 23111e1d0fc..463c6de61bc 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_cannon_master_willey.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_cannon_master_willey.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "stratholme.h" //front, left #define ADD_1X 3553.851807f @@ -87,7 +88,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_cannon_master_willeyAI(creature); + return GetStratholmeAI(creature); } struct boss_cannon_master_willeyAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_dathrohan_balnazzar.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_dathrohan_balnazzar.cpp index 7fcb5e0ec0b..d1c9532ec85 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_dathrohan_balnazzar.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_dathrohan_balnazzar.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "stratholme.h" enum Spells { @@ -76,7 +77,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_dathrohan_balnazzarAI(creature); + return GetStratholmeAI(creature); } struct boss_dathrohan_balnazzarAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_magistrate_barthilas.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_magistrate_barthilas.cpp index 389aa1b497d..9c7c39718b8 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_magistrate_barthilas.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_magistrate_barthilas.cpp @@ -48,7 +48,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_magistrate_barthilasAI(creature); + return GetStratholmeAI(creature); } struct boss_magistrate_barthilasAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp index 768c414a01c..10c2b1327bb 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -117,7 +118,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp index c38ba7aad1d..ecf0bf7fe00 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -42,7 +43,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } struct boss_nerubenkanAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp index f1052bc16dc..8824367fe4b 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" #include "Player.h" @@ -58,7 +59,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } struct boss_silver_hand_bossesAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp index 23b2e55c928..373ca3a1bda 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp @@ -131,7 +131,7 @@ class boss_postmaster_malown : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp index 51725964ac5..cd7aa959c9e 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp @@ -24,8 +24,10 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" +#include "TemporarySummon.h" enum Spells { @@ -45,7 +47,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } struct boss_ramstein_the_gorgerAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_timmy_the_cruel.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_timmy_the_cruel.cpp index 6508c527cc0..473fc9b9048 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_timmy_the_cruel.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_timmy_the_cruel.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "stratholme.h" enum Says { @@ -43,7 +44,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_timmy_the_cruelAI(creature); + return GetStratholmeAI(creature); } struct boss_timmy_the_cruelAI : public ScriptedAI diff --git a/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp b/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp index e0edf1d189c..f55ed325148 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp @@ -24,10 +24,14 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "EventMap.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "stratholme.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "stratholme.h" enum Misc { @@ -43,7 +47,7 @@ enum InstanceEvents class instance_stratholme : public InstanceMapScript { public: - instance_stratholme() : InstanceMapScript("instance_stratholme", 329) { } + instance_stratholme() : InstanceMapScript(StratholmeScriptName, 329) { } struct instance_stratholme_InstanceMapScript : public InstanceScript { @@ -349,7 +353,7 @@ class instance_stratholme : public InstanceMapScript return saveStream.str(); } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp index 7ce650779de..02cb2e71667 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp @@ -31,12 +31,16 @@ npc_spectral_ghostly_citizen EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "stratholme.h" #include "Group.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "stratholme.h" /*###### ## go_gauntlet_gate (this is the _first_ of the gauntlet gates, two exist) @@ -84,7 +88,7 @@ class go_gauntlet_gate : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetStratholmeAI(go); } }; @@ -113,7 +117,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_restless_soulAI(creature); + return GetStratholmeAI(creature); } struct npc_restless_soulAI : public ScriptedAI @@ -141,7 +145,7 @@ public: void EnterCombat(Unit* /*who*/) override { } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (Tagged || spell->Id != SPELL_EGAN_BLASTER) return; @@ -206,7 +210,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_spectral_ghostly_citizenAI(creature); + return GetStratholmeAI(creature); } struct npc_spectral_ghostly_citizenAI : public ScriptedAI @@ -232,7 +236,7 @@ public: void EnterCombat(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (!Tagged && spell->Id == SPELL_EGAN_BLASTER) Tagged = true; diff --git a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h index dd98843e6b5..e30d6feecdc 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h +++ b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h @@ -19,6 +19,9 @@ #ifndef DEF_STRATHOLME_H #define DEF_STRATHOLME_H +#include "CreatureAIImpl.h" + +#define StratholmeScriptName "instance_stratholme" #define DataHeader "STR" enum STRDataTypes @@ -81,4 +84,10 @@ enum STRSpellIds SPELL_BARON_ULTIMATUM = 27861 }; +template +inline AI* GetStratholmeAI(T* obj) +{ + return GetInstanceAI(obj, StratholmeScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp index 396d3f0c004..74d00fbc3ee 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp @@ -24,7 +24,9 @@ SDCategory: Sunken Temple EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "sunken_temple.h" enum Gameobject @@ -59,7 +61,7 @@ static Position const statuePositions[nStatues] class instance_sunken_temple : public InstanceMapScript { public: - instance_sunken_temple() : InstanceMapScript("instance_sunken_temple", 109) { } + instance_sunken_temple() : InstanceMapScript(STScriptName, 109) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -176,14 +178,14 @@ public: void UseStatue(GameObject* go) { - go->SummonGameObject(GO_ATALAI_LIGHT1, *go, G3D::Quat(), 0); + go->SummonGameObject(GO_ATALAI_LIGHT1, *go, QuaternionData(), 0); go->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } void UseLastStatue(GameObject* go) { for (uint8 i = 0; i < nStatues; ++i) - go->SummonGameObject(GO_ATALAI_LIGHT2, statuePositions[i], G3D::Quat(), 0); + go->SummonGameObject(GO_ATALAI_LIGHT2, statuePositions[i], QuaternionData(), 0); go->SummonCreature(NPC_ATALALARION, atalalarianPos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200); } diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp index a39f636ee86..f896f7ba17a 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp @@ -28,10 +28,13 @@ at_malfurion_Stormrage_trigger EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "sunken_temple.h" +#include "InstanceScript.h" +#include "Map.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "sunken_temple.h" /*##### # at_malfurion_Stormrage_trigger @@ -49,7 +52,7 @@ class at_malfurion_stormrage : public AreaTriggerScript public: at_malfurion_stormrage() : AreaTriggerScript("at_malfurion_stormrage") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player->GetInstanceScript() && !player->FindNearestCreature(NPC_MALFURION_STORMRAGE, 15.0f) && player->GetQuestStatus(QUEST_THE_CHARGE_OF_DRAGONFLIGHTS) == QUEST_STATUS_REWARDED && player->GetQuestStatus(QUEST_ERANIKUS_TYRANT_OF_DREAMS) != QUEST_STATUS_REWARDED) @@ -82,7 +85,7 @@ class go_atalai_statue : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetSunkenTempleAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h index c6c2f087850..f2687c5de68 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h @@ -19,6 +19,9 @@ #ifndef DEF_SUNKEN_TEMPLE_H #define DEF_SUNKEN_TEMPLE_H +#include "CreatureAIImpl.h" + +#define STScriptName "instance_sunken_temple" #define DataHeader "ST" enum STEvents @@ -26,4 +29,10 @@ enum STEvents EVENT_STATE = 1 }; +template +inline AI* GetSunkenTempleAI(T* obj) +{ + return GetInstanceAI(obj, STScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp index 924d00169c8..66ef84c2273 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp @@ -23,6 +23,8 @@ SDComment: Find a way to start the intro, best code for the intro EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Log.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp index 195fc2bf0a9..51aad495c37 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" -#include "sunwell_plateau.h" #include "SpellInfo.h" +#include "sunwell_plateau.h" enum Quotes { @@ -160,7 +161,7 @@ public: me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { @@ -266,8 +267,8 @@ public: if (ShadowimageTimer <= diff) { - Unit* target = NULL; - Creature* temp = NULL; + Unit* target = nullptr; + Creature* temp = nullptr; for (uint8 i = 0; i<3; ++i) { target = SelectTarget(SELECT_TARGET_RANDOM, 0); @@ -436,7 +437,7 @@ public: me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { @@ -673,7 +674,7 @@ public: void EnterCombat(Unit* /*who*/) override { } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp index aa5720bef4e..045f6d956bb 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp @@ -22,12 +22,14 @@ SDComment: EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "sunwell_plateau.h" +#include "TemporarySummon.h" enum Yells { @@ -196,7 +198,7 @@ public: instance->SetBossState(DATA_FELMYST, DONE); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { // workaround for linked aura /*if (spell->Id == SPELL_VAPOR_FORCE) @@ -215,7 +217,7 @@ public: summon->CastSpell(summon, SPELL_FOG_CHARM, true); summon->CastSpell(summon, SPELL_FOG_CHARM2, true); } - me->DealDamage(caster, caster->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(caster, caster->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -360,7 +362,7 @@ public: } case 6: me->SetFacingTo(me->GetAngle(breathX, breathY)); - //DoTextEmote("takes a deep breath.", NULL); + //DoTextEmote("takes a deep breath.", nullptr); events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000); break; case 7: diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp index 83c8281a036..f6c02074774 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp @@ -24,10 +24,17 @@ SDCategory: Sunwell_Plateau EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "sunwell_plateau.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "sunwell_plateau.h" +#include "TemporarySummon.h" #include "WorldSession.h" enum Yells @@ -548,7 +555,7 @@ public: { #if MAX_PLAYERS_IN_SPECTRAL_REALM > 0 uint8 SpectralPlayers = 0; - Map::PlayerList const &PlayerList = go->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = go->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->GetSource() && i->GetSource()->GetPositionZ() < DEMON_REALM_Z + 5) @@ -685,7 +692,7 @@ public: void TeleportAllPlayersBack() { - Map::PlayerList const &playerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& playerList = me->GetMap()->GetPlayers(); Position const& homePos = me->GetHomePosition(); for (Map::PlayerList::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr) { diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp index 08bd7809f8e..4e841a82e14 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp @@ -25,11 +25,16 @@ EndScriptData */ /// @todo rewrite Armageddon #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "sunwell_plateau.h" -#include +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "sunwell_plateau.h" +#include "TemporarySummon.h" /*** Speech and sounds***/ enum Yells @@ -280,7 +285,7 @@ public: return ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_ORB_OF_THE_BLUE_DRAGONFLIGHT_4)); } - return NULL; + return nullptr; } void ResetOrbs() @@ -701,7 +706,7 @@ public: case TIMER_SPEECH: if (SpeechBegins) { - SpeechBegins=false; + SpeechBegins = false; switch (Phase) { case PHASE_NORMAL: @@ -744,7 +749,7 @@ public: case TIMER_LEGION_LIGHTNING: if (!me->IsNonMeleeSpellCast(false)) { - Unit* pRandomPlayer = NULL; + Unit* pRandomPlayer = nullptr; me->RemoveAurasDueToSpell(SPELL_SOUL_FLAY); for (uint8 z = 0; z < 6; ++z) @@ -839,7 +844,7 @@ public: TimerIsDeactivated[TIMER_ORBS_EMPOWER] = true; break; case TIMER_ARMAGEDDON: //Phase 4 - Unit* target = NULL; + Unit* target = nullptr; for (uint8 z = 0; z < 6; ++z) { target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); @@ -987,7 +992,7 @@ public: { if (Creature* pPortal = DoSpawnCreature(NPC_FELFIRE_PORTAL, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 20000)) { - ThreatContainer::StorageType const &threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) { Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp index fed97fc8488..f0bcb9dd3de 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "sunwell_plateau.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "sunwell_plateau.h" enum Spells { @@ -581,10 +583,7 @@ class spell_summon_blood_elves_script : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint8 i = 0; i < MAX_SUMMON_BLOOD_ELVES; ++i) - if (!sSpellMgr->GetSpellInfo(SummonBloodElvesSpells[i])) - return false; - return true; + return ValidateSpellInfo(SummonBloodElvesSpells); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -616,10 +615,7 @@ class spell_muru_darkness : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint8 i = 0; i < MAX_SUMMON_DARK_FIEND; ++i) - if (!sSpellMgr->GetSpellInfo(SummonDarkFiendSpells[i])) - return false; - return true; + return ValidateSpellInfo(SummonDarkFiendSpells); } void HandleAfterCast() diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp index 17325e9e00f..6b3c2b1bcaf 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp @@ -17,6 +17,8 @@ #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "Player.h" #include "sunwell_plateau.h" @@ -89,7 +91,7 @@ class instance_sunwell_plateau : public InstanceMapScript else TC_LOG_DEBUG("scripts", "Instance Sunwell Plateau: GetPlayerInMap, but PlayerList is empty!"); - return NULL; + return nullptr; } ObjectGuid GetGuidData(uint32 id) const override diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h b/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h index a25ed5b0ca2..cec43582958 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h @@ -18,6 +18,8 @@ #ifndef SUNWELL_PLATEAU_H #define SUNWELL_PLATEAU_H +#include "CreatureAIImpl.h" + #define SunwellPlateauScriptName "instance_sunwell_plateau" #define DataHeader "SWP" @@ -112,7 +114,7 @@ enum SWPGameObjectIds GO_MURUS_GATE_2 = 188118 }; -template +template AI* GetSunwellPlateauAI(T* obj) { return GetInstanceAI(obj, SunwellPlateauScriptName); diff --git a/src/server/scripts/EasternKingdoms/TheStockade/instance_the_stockade.cpp b/src/server/scripts/EasternKingdoms/TheStockade/instance_the_stockade.cpp index 822737dad87..c222f395a50 100644 --- a/src/server/scripts/EasternKingdoms/TheStockade/instance_the_stockade.cpp +++ b/src/server/scripts/EasternKingdoms/TheStockade/instance_the_stockade.cpp @@ -24,6 +24,7 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" class instance_the_stockade : public InstanceMapScript { diff --git a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp index af8ef8f4f39..c96d86aff57 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp @@ -27,10 +27,14 @@ On his death the vault door opens. EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "uldaman.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "uldaman.h" enum Says { @@ -125,10 +129,10 @@ class boss_archaedas : public CreatureScript me->SetControlled(false, UNIT_STATE_ROOT); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { // Being woken up from the altar, start the awaken sequence - if (spell == sSpellMgr->GetSpellInfo(SPELL_ARCHAEDAS_AWAKEN)) + if (spell->Id == SPELL_ARCHAEDAS_AWAKEN) { Talk(SAY_AGGRO); iAwakenTimer = 4000; @@ -212,7 +216,7 @@ class boss_archaedas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUldamanAI(creature); } }; @@ -276,10 +280,10 @@ class npc_archaedas_minions : public CreatureScript bAmIAwake = true; } - void SpellHit(Unit * /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit * /*caster*/, SpellInfo const* spell) override { // time to wake up, start animation - if (spell == sSpellMgr->GetSpellInfo(SPELL_ARCHAEDAS_AWAKEN)) + if (spell->Id == SPELL_ARCHAEDAS_AWAKEN) { iAwakenTimer = 5000; bWakingUp = true; @@ -318,7 +322,7 @@ class npc_archaedas_minions : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUldamanAI(creature); } }; @@ -381,7 +385,7 @@ class npc_stonekeepers : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUldamanAI(creature); } }; @@ -414,7 +418,7 @@ class go_altar_of_archaedas : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetUldamanAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/Uldaman/boss_ironaya.cpp b/src/server/scripts/EasternKingdoms/Uldaman/boss_ironaya.cpp index 98b94e09c70..5a17339b4de 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/boss_ironaya.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/boss_ironaya.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "uldaman.h" enum Ironaya { @@ -110,7 +111,7 @@ class boss_ironaya : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_ironayaAI(creature); + return GetUldamanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp index 360794facf6..a72acba44b3 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp @@ -24,8 +24,14 @@ SDCategory: Uldaman EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "uldaman.h" enum Spells @@ -51,7 +57,7 @@ const Position IronayaPoint = { -231.228f, 246.6135f, -49.01617f, 0.0f }; class instance_uldaman : public InstanceMapScript { public: - instance_uldaman() : InstanceMapScript("instance_uldaman", 70) { } + instance_uldaman() : InstanceMapScript(UldamanScriptName, 70) { } struct instance_uldaman_InstanceMapScript : public InstanceScript { @@ -416,7 +422,7 @@ class instance_uldaman : public InstanceMapScript return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp index 14fb5a06d43..9c84b399e43 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp @@ -30,10 +30,12 @@ at_map_chamber EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "uldaman.h" +#include "InstanceScript.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "uldaman.h" /*###### ## npc_jadespine_basilisk @@ -107,7 +109,7 @@ class npc_jadespine_basilisk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_jadespine_basiliskAI(creature); + return GetUldamanAI(creature); } }; @@ -135,7 +137,7 @@ class go_keystone_chamber : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetUldamanAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h index 0578da35895..d81793cf61c 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h +++ b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h @@ -19,6 +19,9 @@ #ifndef DEF_ULDAMAN_H #define DEF_ULDAMAN_H +#include "CreatureAIImpl.h" + +#define UldamanScriptName "instance_uldaman" #define DataHeader "UD" #define MAX_ENCOUNTER 3 @@ -42,4 +45,10 @@ enum UDGameObjectIds GO_KEYSTONE = 124371, }; +template +inline AI* GetUldamanAI(T* obj) +{ + return GetInstanceAI(obj, UldamanScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp index 1ab0ea8908c..f1b6c993a41 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp @@ -26,13 +26,14 @@ SQLUpdate: EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" -#include "zulaman.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "Weather.h" +#include "zulaman.h" enum Spells { @@ -170,7 +171,7 @@ class boss_akilzon : public CreatureScript if (Unit* target = (*i)) { if (Cloud && !Cloud->IsWithinDist(target, 6, false)) - Cloud->CastCustomSpell(target, SPELL_ZAP, &bp0, NULL, NULL, true, 0, 0, me->GetGUID()); + Cloud->CastCustomSpell(target, SPELL_ZAP, &bp0, nullptr, nullptr, true, 0, 0, me->GetGUID()); } } @@ -189,7 +190,7 @@ class boss_akilzon : public CreatureScript trigger->SetHealth(100000); trigger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Cloud) - Cloud->CastCustomSpell(trigger, /*43661*/SPELL_ZAP, &bp0, NULL, NULL, true, 0, 0, Cloud->GetGUID()); + Cloud->CastCustomSpell(trigger, /*43661*/SPELL_ZAP, &bp0, nullptr, nullptr, true, 0, 0, Cloud->GetGUID()); } } } @@ -203,7 +204,7 @@ class boss_akilzon : public CreatureScript me->InterruptNonMeleeSpells(false); CloudGUID.Clear(); if (Cloud) - Cloud->DealDamage(Cloud, Cloud->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + Cloud->DealDamage(Cloud, Cloud->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); SetWeather(WEATHER_STATE_FINE, 0.0f); isRaining = false; } diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp index 618190f750c..9443c9a9e6a 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp @@ -17,9 +17,11 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "zulaman.h" #include "SpellInfo.h" +#include "zulaman.h" enum Spells { @@ -134,7 +136,7 @@ class boss_halazzi : public CreatureScript damage = 0; } - void SpellHit(Unit*, const SpellInfo* spell) override + void SpellHit(Unit*, SpellInfo const* spell) override { if (spell->Id == SPELL_TRANSFORM_SPLIT2) EnterPhase(PHASE_HUMAN); diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp index 95600a06d36..ead3781d89b 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp @@ -24,9 +24,12 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "zulaman.h" enum Yells @@ -328,7 +331,7 @@ class boss_hexlord_malacrass : public CreatureScript { Unit* Temp = ObjectAccessor::GetUnit(*me, AddGUID[i]); if (Temp && Temp->IsAlive()) - Temp->DealDamage(Temp, Temp->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + Temp->DealDamage(Temp, Temp->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -471,7 +474,7 @@ class boss_hexlord_malacrass : public CreatureScript void UseAbility() { uint8 random = urand(0, 2); - Unit* target = NULL; + Unit* target = nullptr; switch (PlayerAbility[PlayerClass][random].target) { case ABILITY_TARGET_SELF: @@ -1015,15 +1018,13 @@ class spell_hexlord_unstable_affliction : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WL_UNSTABLE_AFFL_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WL_UNSTABLE_AFFL_DISPEL }); } void HandleDispel(DispelInfo* dispelInfo) { if (Unit* caster = GetCaster()) - caster->CastSpell(dispelInfo->GetDispeller(), SPELL_WL_UNSTABLE_AFFL_DISPEL, true, NULL, GetEffect(EFFECT_0)); + caster->CastSpell(dispelInfo->GetDispeller(), SPELL_WL_UNSTABLE_AFFL_DISPEL, true, nullptr, GetEffect(EFFECT_0)); } void Register() override diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp index 91978d052ad..90c0516da52 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp @@ -24,10 +24,14 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "zulaman.h" -#include "GridNotifiers.h" -#include "CellImpl.h" enum Yells { @@ -194,7 +198,7 @@ class boss_janalai : public CreatureScript void FireWall() { uint8 WallNum; - Creature* wall = NULL; + Creature* wall = nullptr; for (uint8 i = 0; i < 4; ++i) { if (i == 0 || i == 2) @@ -366,7 +370,7 @@ class boss_janalai : public CreatureScript if (!map->IsDungeon()) return; - Map::PlayerList const &PlayerList = map->GetPlayers(); + Map::PlayerList const& PlayerList = map->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* i_pl = i->GetSource()) if (i_pl->IsAlive()) @@ -441,7 +445,7 @@ class npc_janalai_firebomb : public CreatureScript void Reset() override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_FIRE_BOMB_THROW) DoCast(me, SPELL_FIRE_BOMB_DUMMY, true); @@ -667,7 +671,7 @@ class npc_janalai_egg : public CreatureScript void UpdateAI(uint32 /*diff*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_HATCH_EGG) DoCast(SPELL_SUMMON_HATCHLING); diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp index e2acc47d651..559390fece3 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp @@ -24,11 +24,11 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" #include "zulaman.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" enum Yells { diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp index 10d0772932c..1ebecc41b4b 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp @@ -23,9 +23,12 @@ SDComment: EndScriptData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "zulaman.h" #include "SpellInfo.h" +#include "TemporarySummon.h" +#include "zulaman.h" enum Says { @@ -580,7 +583,7 @@ class npc_zuljin_vortex : public CreatureScript void EnterCombat(Unit* /*target*/) override { } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_ZAP_INFORM) DoCast(caster, SPELL_ZAP_DAMAGE, true); diff --git a/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp b/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp index f0eb8ef7911..0c972756a72 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp @@ -24,10 +24,13 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "zulaman.h" +#include "Log.h" +#include "Map.h" #include "Player.h" #include "TemporarySummon.h" +#include "zulaman.h" enum Misc { diff --git a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp index affb1ab9406..9598940bbd4 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp @@ -28,12 +28,15 @@ npc_forest_frog EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "zulaman.h" -#include "Player.h" #include "SpellInfo.h" #include "SpellScript.h" +#include "zulaman.h" /*###### ## npc_forest_frog @@ -103,7 +106,7 @@ class npc_forest_frog : public CreatureScript me->UpdateEntry(cEntry); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_REMOVE_AMANI_CURSE && caster->GetTypeId() == TYPEID_PLAYER && me->GetEntry() == NPC_FOREST_FROG) { @@ -171,7 +174,7 @@ class npc_zulaman_hostage : public CreatureScript { if (HostageEntry[i] == entry) { - me->SummonGameObject(ChestEntry[i], Position(x - 2, y, z, 0.f), G3D::Quat(), 0); + me->SummonGameObject(ChestEntry[i], Position(x - 2, y, z, 0.f), QuaternionData(), 0); break; } } @@ -292,7 +295,7 @@ class npc_harrison_jones : public CreatureScript return false; } - void SpellHit(Unit*, const SpellInfo* spell) override + void SpellHit(Unit*, SpellInfo const* spell) override { if (spell->Id == SPELL_COSMETIC_SPEAR_THROW) { diff --git a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h index 99988310544..ae1323af6aa 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h +++ b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h @@ -19,6 +19,8 @@ #ifndef DEF_ZULAMAN_H #define DEF_ZULAMAN_H +#include "CreatureAIImpl.h" + #define ZulamanScriptName "instance_zulaman" #define DataHeader "ZA" @@ -65,10 +67,10 @@ enum ZAGameObjectIds GO_STRANGE_GONG = 187359 }; -template -inline AI* GetZulAmanAI(Creature* creature) +template +inline AI* GetZulAmanAI(T* obj) { - return GetInstanceAI(creature, ZulamanScriptName); + return GetInstanceAI(obj, ZulamanScriptName); } #endif diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_arlokk.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_arlokk.cpp index 40a1836d46a..8946edbe809 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_arlokk.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_arlokk.cpp @@ -25,8 +25,12 @@ TCCategory: Zul'Gurub EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" #include "zulgurub.h" @@ -240,7 +244,7 @@ class boss_arlokk : public CreatureScript me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 0, uint32(EQUIP_UNEQUIP)); me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, uint32(EQUIP_UNEQUIP)); /* - const CreatureTemplate* cinfo = me->GetCreatureTemplate(); + CreatureTemplate const* cinfo = me->GetCreatureTemplate(); me->SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, (cinfo->mindmg +((cinfo->mindmg/100) * 35))); me->SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, (cinfo->maxdmg +((cinfo->maxdmg/100) * 35))); me->UpdateDamagePhysical(BASE_ATTACK); @@ -288,7 +292,7 @@ class boss_arlokk : public CreatureScript me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 0, uint32(WEAPON_DAGGER)); me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, uint32(WEAPON_DAGGER)); /* - const CreatureTemplate* cinfo = me->GetCreatureTemplate(); + CreatureTemplate const* cinfo = me->GetCreatureTemplate(); me->SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, (cinfo->mindmg)); me->SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, (cinfo->maxdmg)); me->UpdateDamagePhysical(BASE_ATTACK); diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_gahzranka.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_gahzranka.cpp index a32e2fba7c0..f29babec4fe 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_gahzranka.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_gahzranka.cpp @@ -108,7 +108,7 @@ class boss_gahzranka : public CreatureScript // gahzranka CreatureAI* GetAI(Creature* creature) const override { - return new boss_gahzrankaAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_grilek.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_grilek.cpp index cb3859bf94e..4a6feab82eb 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_grilek.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_grilek.cpp @@ -109,7 +109,7 @@ class boss_grilek : public CreatureScript // grilek CreatureAI* GetAI(Creature* creature) const override { - return new boss_grilekAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_hakkar.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_hakkar.cpp index fb573604e74..16c8154af87 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_hakkar.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_hakkar.cpp @@ -23,6 +23,7 @@ Category: Zul'Gurub */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "zulgurub.h" @@ -173,7 +174,7 @@ class boss_hakkar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_hazzarah.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_hazzarah.cpp index ac223fff71f..6b0c75b9cc3 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_hazzarah.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_hazzarah.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "zulgurub.h" enum Spells @@ -114,7 +115,7 @@ class boss_hazzarah : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_hazzarahAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_jeklik.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_jeklik.cpp index ab62c42ab18..63d6388d497 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_jeklik.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_jeklik.cpp @@ -17,6 +17,7 @@ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "zulgurub.h" enum Says @@ -257,7 +258,7 @@ class npc_batrider : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_batriderAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_jindo.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_jindo.cpp index a849a680621..2c6ebefd1cb 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_jindo.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_jindo.cpp @@ -17,7 +17,10 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "zulgurub.h" enum Say @@ -164,7 +167,7 @@ class boss_jindo : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_jindoAI(creature); + return GetZulGurubAI(creature); } }; @@ -213,7 +216,7 @@ class npc_healing_ward : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulGurubAI(creature); } }; @@ -260,7 +263,7 @@ class npc_shade_of_jindo : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_shade_of_jindoAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp index e30fe8861f2..17027e2d056 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp @@ -24,10 +24,13 @@ SDCategory: Zul'Gurub EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "Spell.h" #include "SpellAuras.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "zulgurub.h" enum Says @@ -429,7 +432,7 @@ class npc_vilebranch_speaker : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_marli.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_marli.cpp index 03bc99d177a..9537aaec3e5 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_marli.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_marli.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "zulgurub.h" enum Says @@ -168,7 +169,7 @@ class boss_marli : public CreatureScript } case EVENT_CHARGE_PLAYER: { - Unit* target = NULL; + Unit* target = nullptr; int i = 0; while (i++ < 3) // max 3 tries to get a random target with power_mana { @@ -216,7 +217,7 @@ class boss_marli : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_marliAI(creature); + return GetZulGurubAI(creature); } }; @@ -265,7 +266,7 @@ class npc_spawn_of_marli : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_spawn_of_marliAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_renataki.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_renataki.cpp index 502630a8a89..351445c0c62 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_renataki.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_renataki.cpp @@ -165,7 +165,7 @@ class boss_renataki : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_renatakiAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_thekal.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_thekal.cpp index ac4d6d9e96f..7e6a9970629 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_thekal.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_thekal.cpp @@ -24,6 +24,8 @@ SDCategory: Zul'Gurub EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "zulgurub.h" @@ -164,7 +166,7 @@ class boss_thekal : public CreatureScript me->SetStandState(UNIT_STAND_STATE_STAND); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); /* - const CreatureTemplate* cinfo = me->GetCreatureTemplate(); + CreatureTemplate const* cinfo = me->GetCreatureTemplate(); me->SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, (cinfo->mindmg +((cinfo->mindmg/100) * 40))); me->SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, (cinfo->maxdmg +((cinfo->maxdmg/100) * 40))); me->UpdateDamagePhysical(BASE_ATTACK); @@ -257,7 +259,7 @@ class boss_thekal : public CreatureScript me->SetStandState(UNIT_STAND_STATE_SLEEP); me->AttackStop(); instance->SetBossState(DATA_THEKAL, SPECIAL); - WasDead=true; + WasDead = true; } if (me->HasUnitState(UNIT_STATE_CASTING)) @@ -269,7 +271,7 @@ class boss_thekal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulGurubAI(creature); } }; @@ -422,7 +424,7 @@ class npc_zealot_lorkhan : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulGurubAI(creature); } }; @@ -572,7 +574,7 @@ class npc_zealot_zath : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp index caa4587aaa1..e8b0b59d317 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp @@ -275,7 +275,7 @@ class boss_venoxis : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_venoxisAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_wushoolay.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_wushoolay.cpp index 750b6d2246a..44500347ca2 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_wushoolay.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_wushoolay.cpp @@ -101,7 +101,7 @@ class boss_wushoolay : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_wushoolayAI(creature); + return GetZulGurubAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp index b1b7869f4a9..b9ec02029f1 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp @@ -24,7 +24,10 @@ SDCategory: Zul'Gurub EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "zulgurub.h" DoorData const doorData[] = @@ -79,11 +82,10 @@ class instance_zulgurub : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_FORCEFIELD: - AddDoor(go, true); - break; case GO_GONG_OF_BETHEKK: _goGongOfBethekkGUID = go->GetGUID(); if (GetBossState(DATA_ARLOKK) == DONE) @@ -96,18 +98,6 @@ class instance_zulgurub : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_FORCEFIELD: - AddDoor(go, false); - break; - default: - break; - } - } - ObjectGuid GetGuidData(uint32 uiData) const override { switch (uiData) diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h b/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h index 4148b4d9e08..b2adf8cfe04 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h +++ b/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h @@ -18,12 +18,13 @@ #ifndef DEF_ZULGURUB_H #define DEF_ZULGURUB_H +#include "CreatureAIImpl.h" + +#define ZGScriptName "instance_zulgurub" #define DataHeader "ZG" uint32 const EncounterCount = 13; -#define ZGScriptName "instance_zulgurub" - enum ZGDataTypes { DATA_JEKLIK = 0, // Main boss @@ -67,8 +68,8 @@ enum ZGGameObjectIds GO_GONG_OF_BETHEKK = 180526 // Arlokk Event }; -template -AI* GetZulGurubAI(T* obj) +template +inline AI* GetZulGurubAI(T* obj) { return GetInstanceAI(obj, ZGScriptName); } diff --git a/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp b/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp index 2e4fd37554d..ae5435aa571 100644 --- a/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp @@ -48,9 +48,7 @@ class spell_razelikh_teleport_group : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_SINGLE) && !sSpellMgr->GetSpellInfo(SPELL_TELEPORT_SINGLE_IN_GROUP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_SINGLE, SPELL_TELEPORT_SINGLE_IN_GROUP }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -59,7 +57,7 @@ class spell_razelikh_teleport_group : public SpellScriptLoader { if (Group* group = player->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) if (member->IsWithinDistInMap(player, 20.0f) && !member->isDead()) member->CastSpell(member, SPELL_TELEPORT_SINGLE_IN_GROUP, true); diff --git a/src/server/scripts/EasternKingdoms/zone_duskwood.cpp b/src/server/scripts/EasternKingdoms/zone_duskwood.cpp index e521a3d1bb7..f350efd6396 100644 --- a/src/server/scripts/EasternKingdoms/zone_duskwood.cpp +++ b/src/server/scripts/EasternKingdoms/zone_duskwood.cpp @@ -26,6 +26,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "Player.h" +#include "TemporarySummon.h" enum TwilightCorrupter { @@ -146,7 +147,7 @@ class at_twilight_grove : public AreaTriggerScript public: at_twilight_grove() : AreaTriggerScript("at_twilight_grove") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player->GetQuestStatus(QUEST_NIGHTMARES_CORRUPTION) == QUEST_STATUS_INCOMPLETE) if (!player->FindNearestCreature(NPC_TWILIGHT_CORRUPTER, 500.0f, true)) diff --git a/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp b/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp index edf1d87c677..5a8197d8f5f 100644 --- a/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp @@ -28,10 +28,11 @@ npc_ranger_lilatha EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "WorldSession.h" /*###### diff --git a/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp b/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp index 5f7f56eee8e..af79fd66ea5 100644 --- a/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp @@ -29,9 +29,10 @@ npc_rinji EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedEscortAI.h" /*###### ## npc_oox09hl diff --git a/src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp b/src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp index 20b628e95d8..bc0f6ea959f 100644 --- a/src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp +++ b/src/server/scripts/EasternKingdoms/zone_silverpine_forest.cpp @@ -29,9 +29,11 @@ pyrewood_ambush EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CreatureAIImpl.h" #include "ScriptedEscortAI.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "TemporarySummon.h" /*###### ## npc_deathstalker_erland @@ -224,7 +226,7 @@ public: { if (Creature* summoned = me->SummonCreature(creatureId, PyrewoodSpawnPoints[position][0], PyrewoodSpawnPoints[position][1], PyrewoodSpawnPoints[position][2], PyrewoodSpawnPoints[position][3], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000)) { - Unit* target = NULL; + Unit* target = nullptr; if (PlayerGUID) if (Player* player = ObjectAccessor::GetPlayer(*me, PlayerGUID)) if (player->IsAlive() && RAND(0, 1)) diff --git a/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp b/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp index dab69c434e6..d883f282549 100644 --- a/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp +++ b/src/server/scripts/EasternKingdoms/zone_stormwind_city.cpp @@ -32,10 +32,12 @@ npc_lord_gregor_lescovar EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" /*###### ## npc_bartleby diff --git a/src/server/scripts/EasternKingdoms/zone_stranglethorn_vale.cpp b/src/server/scripts/EasternKingdoms/zone_stranglethorn_vale.cpp index 4fd9fa4d865..edcfc78d510 100644 --- a/src/server/scripts/EasternKingdoms/zone_stranglethorn_vale.cpp +++ b/src/server/scripts/EasternKingdoms/zone_stranglethorn_vale.cpp @@ -68,7 +68,7 @@ public: me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_NONE); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (bReset || spell->Id != 3607) return; diff --git a/src/server/scripts/EasternKingdoms/zone_swamp_of_sorrows.cpp b/src/server/scripts/EasternKingdoms/zone_swamp_of_sorrows.cpp index 5cd85585a9d..e0396397889 100644 --- a/src/server/scripts/EasternKingdoms/zone_swamp_of_sorrows.cpp +++ b/src/server/scripts/EasternKingdoms/zone_swamp_of_sorrows.cpp @@ -17,9 +17,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" /*###### ## npc_galen_goodward @@ -74,11 +75,11 @@ public: { switch (uiPointId) { - case 0: + case 0: { - GameObject* cage = NULL; + GameObject* cage = nullptr; if (galensCageGUID) - cage = me->GetMap()->GetGameObject(galensCageGUID); + cage = ObjectAccessor::GetGameObject(*me, galensCageGUID); else cage = GetClosestGameObjectWithEntry(me, GO_GALENS_CAGE, INTERACTION_DISTANCE); if (cage) @@ -88,9 +89,9 @@ public: } break; } - case 21: - Talk(EMOTE_DISAPPEAR); - break; + case 21: + Talk(EMOTE_DISAPPEAR); + break; } } @@ -99,7 +100,7 @@ public: switch (waypointId) { case 0: - if (GameObject* cage = me->GetMap()->GetGameObject(galensCageGUID)) + if (GameObject* cage = ObjectAccessor::GetGameObject(*me, galensCageGUID)) cage->ResetDoorOrButton(); break; case 20: diff --git a/src/server/scripts/EasternKingdoms/zone_tirisfal_glades.cpp b/src/server/scripts/EasternKingdoms/zone_tirisfal_glades.cpp index a8d6b67b718..19833db218c 100644 --- a/src/server/scripts/EasternKingdoms/zone_tirisfal_glades.cpp +++ b/src/server/scripts/EasternKingdoms/zone_tirisfal_glades.cpp @@ -30,9 +30,11 @@ go_mausoleum_trigger EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" /*###### ## npc_calvin_montague diff --git a/src/server/scripts/EasternKingdoms/zone_undercity.cpp b/src/server/scripts/EasternKingdoms/zone_undercity.cpp index 9524e341b1c..37fe5cec1f9 100644 --- a/src/server/scripts/EasternKingdoms/zone_undercity.cpp +++ b/src/server/scripts/EasternKingdoms/zone_undercity.cpp @@ -30,9 +30,11 @@ npc_parqual_fintallas EndContentData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" /*###### ## npc_lady_sylvanas_windrunner diff --git a/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp b/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp index 5839d40c15f..7ba95268562 100644 --- a/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp @@ -153,7 +153,7 @@ public: void DoDie() { //summoner dies here - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); //override any database `spawntimesecs` to prevent duplicated summons uint32 rTime = me->GetRespawnDelay(); if (rTime < 600) diff --git a/src/server/scripts/Events/childrens_week.cpp b/src/server/scripts/Events/childrens_week.cpp index cc38aed2964..f5f03bedcf1 100644 --- a/src/server/scripts/Events/childrens_week.cpp +++ b/src/server/scripts/Events/childrens_week.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "Player.h" enum Orphans { diff --git a/src/server/scripts/Events/fireworks_show.cpp b/src/server/scripts/Events/fireworks_show.cpp index b6b9cacf053..b725d64000f 100644 --- a/src/server/scripts/Events/fireworks_show.cpp +++ b/src/server/scripts/Events/fireworks_show.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "GameObjectAI.h" +#include "Containers.h" #include "CreatureAIImpl.h" +#include "EventMap.h" #include "GameEventMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "GameTime.h" +#include "Util.h" enum FireworksShowTypeObjects { @@ -75,7 +79,7 @@ enum FireworksZones STORMWIND = 1519 }; -static const std::vector BootyBayPos = +std::vector const BootyBayPos = { { -14358.03f, 515.058f, 34.2664f, 3.68265f }, { -14357.49f, 490.8445f, 39.47329f, 0.9773831f }, @@ -104,7 +108,7 @@ static const std::vector BootyBayPos = { -14378.1f, 473.5608f, 40.16786f, 0.9773831f } }; -static const std::vector StormwindPos = +std::vector const StormwindPos = { { -8823.592f, 470.316f, 179.2295f, 1.239183f }, { -8883.005f, 590.1927f, 163.1264f, 0.9773831f }, @@ -225,7 +229,7 @@ static const std::vector StormwindPos = { -8872.734375f, 573.338440f, 97.723770f, 1.831103f } }; -static const std::vector OrgrimmarPos = +std::vector const OrgrimmarPos = { { 1609.075f, -4383.707f, 90.23414f, 0.3665176f }, { 1469.648f, -4371.285f, 113.8313f, 6.073746f }, @@ -322,7 +326,7 @@ static const std::vector OrgrimmarPos = { 1493.26253f, -4402.19919f, 59.147816f, 2.2917f } }; -static const std::vector IronForgePos = +std::vector const IronForgePos = { { -5196.038f, -858.4618f, 525.0447f, 6.073746f }, { -5195.734f, -887.6441f, 534.168f, 3.68265f }, @@ -383,7 +387,7 @@ static const std::vector IronForgePos = { -5194.976f, -759.9896f, 517.6288f, 3.630291f } }; -static const std::vector SilvermoonPos = +std::vector const SilvermoonPos = { { 9466.583f, -7307.326f, 107.8366f, 0.1047193f }, { 9411.616f, -7322.223f, 79.95399f, 2.722713f }, @@ -453,7 +457,7 @@ static const std::vector SilvermoonPos = { 9411.504f, -7288.202f, 112.2664f, 2.844883f } }; -static const std::vector ExodarPos = +std::vector const ExodarPos = { { -3992.465f, -11843.86f, 186.4043f, 2.199115f }, { -3948.378f, -11854.06f, 135.6206f, 3.47321f }, @@ -515,7 +519,7 @@ static const std::vector ExodarPos = { -4036.461f, -11783.4f, 142.8152f, 4.729844f } }; -static const std::vector ThunderBluffPos = +std::vector const ThunderBluffPos = { { -1234.804f, -19.72239f, 206.5436f, 0.1396245f }, { -1244.442f, -35.88308f, 206.82f, 4.729844f }, @@ -577,7 +581,7 @@ static const std::vector ThunderBluffPos = { -1240.617f, -41.39486f, 205.0362f, 5.846854f } }; -static const std::vector UndercityPos = +std::vector const UndercityPos = { { 1850.231f, 257.0156f, 124.1743f, 4.729844f }, { 1863.302f, 193.9063f, 114.5829f, 0.9773831f }, @@ -637,7 +641,7 @@ static const std::vector UndercityPos = { 1850.288f, 267.309f, 125.0537f, 3.630291f } }; -static const std::vector DarnassusPos = +std::vector const DarnassusPos = { { 8578.888f, 975.2604f, 42.48742f, 5.846854f }, { 8574.236f, 944.2083f, 44.71943f, 4.76475f }, @@ -700,20 +704,20 @@ static const std::vector DarnassusPos = { 8554.825f, 813.0746f, 78.88226f, 6.0912f } }; -static const std::unordered_map const&> pos = +std::unordered_map const*> const PositionsByZoneMap = { - { STRANGLETHORN_VALE, BootyBayPos }, - { STORMWIND, StormwindPos }, - { ORGRIMMAR, OrgrimmarPos }, - { DUROTAR, OrgrimmarPos }, - { DUN_MOROGH, IronForgePos }, - { IRONFORGE, IronForgePos }, - { EVERSONG_WOODS, SilvermoonPos }, - { EXODAR, ExodarPos }, - { THUNDERBLUFF, ThunderBluffPos }, - { UNDERCITY, UndercityPos }, - { TIRISFAL_GLADES, UndercityPos }, - { TELDRASSIL, DarnassusPos } + { STRANGLETHORN_VALE, &BootyBayPos }, + { STORMWIND, &StormwindPos }, + { ORGRIMMAR, &OrgrimmarPos }, + { DUROTAR, &OrgrimmarPos }, + { DUN_MOROGH, &IronForgePos }, + { IRONFORGE, &IronForgePos }, + { EVERSONG_WOODS, &SilvermoonPos }, + { EXODAR, &ExodarPos }, + { THUNDERBLUFF, &ThunderBluffPos }, + { UNDERCITY, &UndercityPos }, + { TIRISFAL_GLADES, &UndercityPos }, + { TELDRASSIL, &DarnassusPos } }; class go_cheer_speaker : public GameObjectScript @@ -729,7 +733,7 @@ public: _big = true; } - uint32 CheerPicker() + static uint32 CheerPicker() { uint32 newid = RAND( SOUND_CHEER_1, @@ -740,7 +744,7 @@ public: return newid; } - uint32 FireworksPicker() + static uint32 FireworksPicker() { uint32 newid = RAND( FIREWORK_SHOW_TYPE_1_RED, @@ -770,7 +774,7 @@ public: return newid; } - uint32 FireworksBIGOnlyPicker() + static uint32 FireworksBIGOnlyPicker() { uint32 newid = RAND( FIREWORK_SHOW_TYPE_1_RED_BIG, @@ -841,45 +845,44 @@ public: { switch (eventId) { - case EVENT_CHEER: - { - me->PlayDistanceSound(CheerPicker()); - break; - } - case EVENT_FIRE: - { - auto it = pos.find(me->GetZoneId()); - if (it != pos.end()) + case EVENT_CHEER: { - Position const& rndpos = Trinity::Containers::SelectRandomContainerElement(it->second); - float rndrot = frand(-1.0000000f, 1.0000000f); - float rndrot2 = frand(-1.0000000f, 1.0000000f); - - if (_big) + me->PlayDistanceSound(CheerPicker()); + break; + } + case EVENT_FIRE: + { + if (std::vector const* positions = Trinity::Containers::MapGetValuePtr(PositionsByZoneMap, me->GetZoneId())) { - if (GameObject* firework = me->SummonGameObject(FireworksBIGOnlyPicker(), rndpos, G3D::Quat(0.f, 0.f, rndrot, rndrot2), 300)) + Position const& rndpos = Trinity::Containers::SelectRandomContainerElement(*positions); + float rndrot = frand(-1.0000000f, 1.0000000f); + float rndrot2 = frand(-1.0000000f, 1.0000000f); + + if (_big) { - firework->SetRespawnTime(0); - firework->Delete(); + if (GameObject* firework = me->SummonGameObject(FireworksBIGOnlyPicker(), rndpos, QuaternionData(0.f, 0.f, rndrot, rndrot2), 300)) + { + firework->SetRespawnTime(0); + firework->Delete(); + } } - } - else - { - if (GameObject* firework = me->SummonGameObject(FireworksPicker(), rndpos, G3D::Quat(0.f, 0.f, rndrot, rndrot2), 300)) + else { - firework->SetRespawnTime(0); - firework->Delete(); + if (GameObject* firework = me->SummonGameObject(FireworksPicker(), rndpos, QuaternionData(0.f, 0.f, rndrot, rndrot2), 300)) + { + firework->SetRespawnTime(0); + firework->Delete(); + } } } - } - if (_started == true) - _events.ScheduleEvent(EVENT_FIRE, Seconds(1), Seconds(2)); + if (_started == true) + _events.ScheduleEvent(EVENT_FIRE, Seconds(1), Seconds(2)); - break; - } - default: - break; + break; + } + default: + break; } } } diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp index b2d7f9cc166..8c57ce77ba0 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "blackfathom_deeps.h" -#include "ScriptedEscortAI.h" +#include "InstanceScript.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Map.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" enum Spells { @@ -53,7 +55,7 @@ class go_blackfathom_altar : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetBlackfathomDeepsAI(go); } }; @@ -79,7 +81,7 @@ class go_blackfathom_fire : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetBlackfathomDeepsAI(go); } }; @@ -90,7 +92,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } struct npc_blackfathom_deeps_eventAI : public ScriptedAI @@ -131,7 +133,7 @@ public: void AttackPlayer() { - Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlList = me->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; @@ -252,7 +254,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_morriduneAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h index 98daa49ebb5..b90a970da8b 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h @@ -19,6 +19,9 @@ #ifndef BFD_H_ #define BFD_H_ +#include "CreatureAIImpl.h" + +#define BFDScriptName "instance_blackfathom_deeps" #define DataHeader "BFD" uint32 const EncounterCount = 3; @@ -68,4 +71,10 @@ enum BFDGameObjectIds GO_ALTAR_OF_THE_DEEPS = 103016 }; +template +inline AI* GetBlackfathomDeepsAI(T* obj) +{ + return GetInstanceAI(obj, BFDScriptName); +} + #endif // BFD_H_ diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp index cee400603e1..19a671997e8 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp @@ -88,7 +88,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp index a287751e3cd..290ed9ee6c9 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp @@ -66,7 +66,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp index 68d898fb611..aee43175d9b 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp @@ -101,7 +101,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp index eca757c6177..16525357bb3 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp @@ -24,10 +24,14 @@ SDCategory: Blackfathom Deeps EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "blackfathom_deeps.h" +#include "Creature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "Random.h" -const Position LorgusPosition[4] = +Position const LorgusPosition[4] = { { -458.500610f, -38.343079f, -33.474445f, 0.0f }, { -469.423615f, -88.400513f, -39.265102f, 0.0f }, @@ -35,7 +39,7 @@ const Position LorgusPosition[4] = { -759.640564f, 16.658913f, -29.159529f, 0.0f } }; -const Position SpawnsLocation[] = +Position const SpawnsLocation[] = { {-775.431f, -153.853f, -25.871f, 3.207f}, {-775.404f, -174.132f, -25.871f, 3.185f}, @@ -47,7 +51,7 @@ const Position SpawnsLocation[] = class instance_blackfathom_deeps : public InstanceMapScript { public: - instance_blackfathom_deeps() : InstanceMapScript("instance_blackfathom_deeps", 48) { } + instance_blackfathom_deeps() : InstanceMapScript(BFDScriptName, 48) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp index 9965053bfc6..4e9fdbc0bc3 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "SpellScript.h" enum Spells { @@ -49,7 +50,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct boss_anetheronAI : public hyjal_trashAI @@ -102,7 +103,7 @@ public: { if (waypointId == 7) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -186,7 +187,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_towering_infernalAI : public ScriptedAI @@ -273,9 +274,7 @@ class spell_anetheron_vampiric_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VAMPIRIC_AURA_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_VAMPIRIC_AURA_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp index d36e7fda284..caed3f73324 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp @@ -24,10 +24,13 @@ SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" +#include "hyjal.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "Player.h" -#include "hyjal.h" enum Texts { @@ -99,7 +102,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_ancient_wispAI : public ScriptedAI @@ -140,7 +143,7 @@ public: { if (CheckTimer <= diff) { - if (Unit* Archimonde = ObjectAccessor::GetUnit(*me, ArchimondeGUID)) + if (Creature* Archimonde = ObjectAccessor::GetCreature(*me, ArchimondeGUID)) { if (Archimonde->HealthBelowPct(2) || !Archimonde->IsAlive()) DoCast(me, SPELL_DENOUEMENT_WISP); @@ -162,7 +165,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_doomfireAI(creature); + return GetHyjalAI(creature); } struct npc_doomfireAI : public ScriptedAI @@ -191,7 +194,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_doomfire_targettingAI(creature); + return GetHyjalAI(creature); } struct npc_doomfire_targettingAI : public ScriptedAI @@ -389,7 +392,7 @@ public: DoSpawnCreature(NPC_ANCIENT_WISP, float(rand32() % 40), float(rand32() % 40), 0, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); ++WispCount; if (WispCount >= 30) - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); events.ScheduleEvent(EVENT_SUMMON_WHISP, 1500); break; default: @@ -530,7 +533,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; @@ -546,9 +549,7 @@ class spell_archimonde_drain_world_tree_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRAIN_WORLD_TREE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRAIN_WORLD_TREE_TRIGGERED }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp index e8ba1f90d37..4eb9a71cff4 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" enum Spells { @@ -48,7 +49,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct boss_azgalorAI : public hyjal_trashAI @@ -105,7 +106,7 @@ public: { if (waypointId == 7 && instance) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -190,7 +191,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_lesser_doomguardAI : public hyjal_trashAI diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp index 51b32c2f20f..d5b43ab4d2d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" -#include "SpellScript.h" #include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -49,7 +50,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct boss_kazrogalAI : public hyjal_trashAI @@ -100,7 +101,7 @@ public: { if (waypointId == 7 && instance) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -206,9 +207,7 @@ class spell_mark_of_kazrogal : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_DAMAGE }); } void OnPeriodic(AuraEffect const* aurEff) @@ -217,7 +216,7 @@ class spell_mark_of_kazrogal : public SpellScriptLoader if (target->GetPower(POWER_MANA) == 0) { - target->CastSpell(target, SPELL_MARK_DAMAGE, true, NULL, aurEff); + target->CastSpell(target, SPELL_MARK_DAMAGE, true, nullptr, aurEff); // Remove aura SetDuration(0); } diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp index b6891597076..9d96aa20133 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" enum Spells { @@ -44,7 +45,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct boss_rage_winterchillAI : public hyjal_trashAI @@ -95,7 +96,7 @@ public: { if (waypointId == 7 && instance) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp index 83cb6d7d91c..7d33e4bb375 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp @@ -30,10 +30,11 @@ npc_tyrande_whisperwind EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "hyjalAI.h" +#include "InstanceScript.h" +#include "Log.h" #include "Player.h" +#include "ScriptedGossip.h" #define GOSSIP_ITEM_BEGIN_ALLY "My companions and I are with you, Lady Proudmoore." #define GOSSIP_ITEM_ANETHERON "We are ready for whatever Archimonde might send our way, Lady Proudmoore." @@ -122,7 +123,7 @@ class npc_jaina_proudmoore : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; @@ -202,7 +203,7 @@ class npc_thrall : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; @@ -250,7 +251,7 @@ class npc_tyrande_whisperwind : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h index caf7d690097..a90f7789690 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h @@ -19,6 +19,9 @@ #ifndef DEF_HYJAL_H #define DEF_HYJAL_H +#include "CreatureAIImpl.h" + +#define HyjalScriptName "instance_hyjal" #define DataHeader "HY" uint32 const EncounterCount = 5; @@ -93,4 +96,10 @@ enum HYGameobjectIds #define MINRAIDDAMAGE 700000 // minimal damage before trash can drop loot and reputation, resets if faction leader dies +template +inline AI* GetHyjalAI(T* obj) +{ + return GetInstanceAI(obj, HyjalScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp index db091296389..882689ee76d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp @@ -24,14 +24,15 @@ SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" -#include "hyjalAI.h" +#include "GridNotifiersImpl.h" #include "hyjal_trash.h" +#include "hyjalAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "TemporarySummon.h" enum Spawns { @@ -428,7 +429,7 @@ void hyjalAI::EnterEvadeMode(EvadeReason /*why*/) if (me->IsAlive()) me->GetMotionMaster()->MoveTargetedHome(); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); } void hyjalAI::EnterCombat(Unit* /*who*/) @@ -458,7 +459,7 @@ void hyjalAI::SummonCreature(uint32 entry, float Base[4][3]) { SpawnLoc[i] = Base[random][i]; } - Creature* creature = NULL; + Creature* creature = nullptr; switch (entry) { case 17906: //GARGOYLE @@ -650,7 +651,7 @@ void hyjalAI::SpawnVeins() return; for (uint8 i = 0; i < 7; ++i) { - GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], G3D::Quat(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); + GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], QuaternionData(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); if (gem) VeinGUID[i]=gem->GetGUID(); } @@ -662,7 +663,7 @@ void hyjalAI::SpawnVeins() return; for (uint8 i = 7; i < 14; ++i) { - GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], G3D::Quat(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); + GameObject* gem = me->SummonGameObject(GO_ANCIENT_VEIN, VeinPos[i][0], VeinPos[i][1], VeinPos[i][2], VeinPos[i][3], QuaternionData(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); if (gem) VeinGUID[i] = gem->GetGUID(); } @@ -674,7 +675,7 @@ void hyjalAI::DeSpawnVeins() { if (Faction == 1) { - Creature* unit=ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* unit = ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (!unit)return; hyjalAI* ai = CAST_AI(hyjalAI, unit->AI()); if (!ai)return; @@ -686,7 +687,7 @@ void hyjalAI::DeSpawnVeins() } else if (Faction) { - Creature* unit=ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_THRALL)); + Creature* unit = ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_THRALL)); if (!unit) return; hyjalAI* ai = CAST_AI(hyjalAI, unit->AI()); @@ -725,7 +726,7 @@ void hyjalAI::UpdateAI(uint32 diff) HideNearPos(me->GetPositionX(), me->GetPositionY()); HideNearPos(5037.76f, -1889.71f); for (uint8 i = 0; i < 92; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], G3D::Quat(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); + me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], QuaternionData(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); } else me->SetVisible(true); @@ -738,7 +739,7 @@ void hyjalAI::UpdateAI(uint32 diff) HideNearPos(5563, -2763.19f); HideNearPos(5542.2f, -2629.36f); for (uint8 i = 0; i < 65; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], G3D::Quat(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); + me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], QuaternionData(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); } else me->SetVisible(true); @@ -854,7 +855,7 @@ void hyjalAI::UpdateAI(uint32 diff) if (me->IsNonMeleeSpellCast(false)) me->InterruptNonMeleeSpells(false); - Unit* target = NULL; + Unit* target = nullptr; switch (Spells[i].TargetType) { @@ -1015,7 +1016,7 @@ void hyjalAI::DoOverrun(uint32 faction, const uint32 diff) { case 0://alliance for (uint8 i = 0; i < 92; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], G3D::Quat(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); + me->SummonGameObject(GO_ROARING_FLAME, AllianceFirePos[i][0], AllianceFirePos[i][1], AllianceFirePos[i][2], AllianceFirePos[i][3], QuaternionData(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); for (uint8 i = 0; i < 25; ++i)//summon 25 ghouls { @@ -1056,7 +1057,7 @@ void hyjalAI::DoOverrun(uint32 faction, const uint32 diff) break; case 1://horde for (uint8 i = 0; i < 65; ++i)//summon fires - me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], G3D::Quat(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); + me->SummonGameObject(GO_ROARING_FLAME, HordeFirePos[i][0], HordeFirePos[i][1], HordeFirePos[i][2], HordeFirePos[i][3], QuaternionData(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); for (uint8 i = 0; i < 26; ++i)//summon infernals { diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h index f6ce9011852..a61a568f61b 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h @@ -204,7 +204,6 @@ struct hyjalAI : public npc_escortAI private: uint32 SpellTimer[3]; - //std::list CreatureList; }; #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp index 5b93cafce32..b26d9081fc8 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "hyjal.h" #include "hyjal_trash.h" #include "hyjalAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "TemporarySummon.h" enum Spells { @@ -446,7 +449,7 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -458,8 +461,10 @@ public: if (Delay <= diff) { Delay=0; - }else{ - Delay-=diff; + } + else + { + Delay -= diff; return; } if (!meteor) @@ -482,7 +487,7 @@ public: CanMove = true; if (instance->GetData(DATA_ALLIANCE_RETREAT) && !instance->GetData(DATA_HORDE_RETREAT)) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else if (instance->GetData(DATA_ALLIANCE_RETREAT) && instance->GetData(DATA_HORDE_RETREAT)){ @@ -510,7 +515,7 @@ public: if (!imol) { DoCast(me, SPELL_IMMOLATION); - imol=true; + imol = true; } if (FlameBuffetTimer <= diff) { @@ -523,7 +528,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; @@ -534,7 +539,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_abominationAI : public hyjal_trashAI @@ -559,13 +564,13 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -628,7 +633,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_ghoulAI : public hyjal_trashAI @@ -657,13 +662,13 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -726,7 +731,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_necromancerAI : public hyjal_trashAI @@ -767,13 +772,13 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -850,7 +855,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_bansheeAI : public hyjal_trashAI @@ -880,13 +885,13 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -950,7 +955,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_crypt_fiendAI : public hyjal_trashAI @@ -976,13 +981,13 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -1036,7 +1041,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_fel_stalkerAI : public hyjal_trashAI @@ -1062,13 +1067,13 @@ public: { if (instance->GetData(DATA_ALLIANCE_RETREAT))//2.alliance boss down, attack thrall { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } else { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (target && target->IsAlive()) me->AddThreat(target, 0.0f); } @@ -1122,7 +1127,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_frost_wyrmAI : public hyjal_trashAI @@ -1154,7 +1159,7 @@ public: { if (waypointId == 2 && !IsOverrun) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) { me->AddThreat(target, 0.0f); @@ -1170,7 +1175,7 @@ public: float x, y, z; me->GetPosition(x, y, z); - z = me->GetMap()->GetHeight(me->GetPhaseMask(), x, y, z); + me->UpdateGroundPositionZ(x, y, z); me->GetMotionMaster()->MovePoint(0, x, y, z); me->UpdatePosition(x, y, z, 0); } @@ -1218,7 +1223,9 @@ public: { me->GetMotionMaster()->MoveChase(me->GetVictim()); MoveTimer = 2000; - } else MoveTimer-=diff; + } + else + MoveTimer -= diff; } if (FrostBreathTimer <= diff) @@ -1230,7 +1237,9 @@ public: me->GetMotionMaster()->Clear(); FrostBreathTimer = 4000; } - } else FrostBreathTimer -= diff; + } + else + FrostBreathTimer -= diff; } }; }; @@ -1242,7 +1251,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } struct npc_gargoyleAI : public hyjal_trashAI @@ -1275,7 +1284,7 @@ public: { if (waypointId == 2 && !IsOverrun) { - Unit* target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_THRALL)); + Creature* target = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (target && target->IsAlive()) { me->AddThreat(target, 0.0f); @@ -1288,7 +1297,7 @@ public: { float x, y, z; me->GetPosition(x, y, z); - z = me->GetMap()->GetHeight(me->GetPhaseMask(), x, y, z); + me->UpdateGroundPositionZ(x, y, z); me->GetMotionMaster()->MovePoint(0, x, y, z); me->UpdatePosition(x, y, z, 0); hyjal_trashAI::JustDied(killer); @@ -1351,12 +1360,14 @@ public: { float x, y, z; me->EnsureVictim()->GetPosition(x, y, z); - me->GetMotionMaster()->MovePoint(0, x, y, z+Zpos); + me->GetMotionMaster()->MovePoint(0, x, y, z + Zpos); Zpos -= 1.0f; if (Zpos <= 0) Zpos = 0; MoveTimer = 2000; - } else MoveTimer-=diff; + } + else + MoveTimer -= diff; } if (StrikeTimer <= diff) @@ -1367,8 +1378,12 @@ public: me->StopMoving(); me->GetMotionMaster()->Clear(); StrikeTimer = 2000 + rand32() % 1000; - } else StrikeTimer=0; - } else StrikeTimer -= diff; + } + else + StrikeTimer = 0; + } + else + StrikeTimer -= diff; } }; }; @@ -1380,7 +1395,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new alliance_riflemanAI(creature); + return GetHyjalAI(creature); } struct alliance_riflemanAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp index d3caf27c344..0a71552e804 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp @@ -24,9 +24,13 @@ SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "hyjal.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" /* Battle of Mount Hyjal encounters: 0 - Rage Winterchill event @@ -50,7 +54,7 @@ ObjectData const creatureData[] = class instance_hyjal : public InstanceMapScript { public: - instance_hyjal() : InstanceMapScript("instance_hyjal", 534) { } + instance_hyjal() : InstanceMapScript(HyjalScriptName, 534) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -276,7 +280,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp index 93fc93f348e..470d5f7f90c 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp @@ -24,8 +24,8 @@ SDCategory: Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "ScriptedCreature.h" enum Spells { @@ -114,7 +114,7 @@ class boss_epoch : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp index 1a7452732f9..1f42939c2f2 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "ScriptedCreature.h" enum Spells { @@ -55,7 +55,7 @@ class boss_infinite_corruptor : public CreatureScript if (Creature* guardian = me->FindNearestCreature(NPC_GUARDIAN_OF_TIME, 100.0f)) { - DoCast((Unit*)NULL, SPELL_CORRUPTION_OF_TIME_CHANNEL, false); + DoCast((Unit*)nullptr, SPELL_CORRUPTION_OF_TIME_CHANNEL, false); guardian->CastSpell(guardian, SPELL_CORRUPTION_OF_TIME_TARGET, false); } } @@ -104,7 +104,7 @@ class boss_infinite_corruptor : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp index 1c05b82d06b..2224ca4f439 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp @@ -24,9 +24,12 @@ SDCategory: Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" enum Spells { @@ -64,7 +67,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } struct boss_mal_ganisAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp index e4252ab7e7a..9ebba661c10 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp @@ -99,7 +99,7 @@ class boss_meathook : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp index cb512c02cf4..925b6367d93 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp @@ -120,7 +120,7 @@ class boss_salramm : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp index da1080c5d27..3b92e2926c6 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp @@ -16,13 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "culling_of_stratholme.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "TemporarySummon.h" enum Says { @@ -1224,7 +1228,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; @@ -1249,7 +1253,7 @@ class npc_crate_helper : public CreatureScript instance->SetData(DATA_CRATE_COUNT, instance->GetData(DATA_CRATE_COUNT) + 1); if (GameObject* crate = me->FindNearestGameObject(GO_SUSPICIOUS_CRATE, 5.0f)) { - crate->SummonGameObject(GO_PLAGUED_CRATE, *crate, G3D::Quat(), DAY); + crate->SummonGameObject(GO_PLAGUED_CRATE, *crate, QuaternionData(), DAY); crate->Delete(); } } @@ -1261,7 +1265,7 @@ class npc_crate_helper : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_crate_helperAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h index 0cd1a7a6459..926645eca85 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h @@ -18,8 +18,11 @@ #ifndef DEF_CULLING_OF_STRATHOLME_H #define DEF_CULLING_OF_STRATHOLME_H -#define DataHeader "CS" +#include "CreatureAIImpl.h" + #define CoSScriptName "instance_culling_of_stratholme" +#define DataHeader "CS" + uint32 const EncounterCount = 5; enum CSDataTypes @@ -100,4 +103,10 @@ enum CSInstanceEvents EVENT_INFINITE_TIMER = 1 }; +template +inline AI* GetCullingOfStratholmeAI(T* obj) +{ + return GetInstanceAI(obj, CoSScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp index 00b6edb7ee3..9881b57a840 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp @@ -16,12 +16,17 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "CreatureAI.h" #include "CreatureTextMgr.h" #include "culling_of_stratholme.h" +#include "EventMap.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" -#include "TemporarySummon.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /* Culling of Stratholme encounters: 0 - Meathook diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp index e23d81aab67..292e61ee3c8 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp @@ -24,6 +24,7 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "old_hillsbrad.h" @@ -54,7 +55,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOldHillsbradAI(creature); } struct boss_captain_skarlocAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp index 2625434b09a..06b876a3f92 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp @@ -24,8 +24,9 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "old_hillsbrad.h" +#include "ScriptedCreature.h" /*################### # boss_epoch_hunter # @@ -52,7 +53,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOldHillsbradAI(creature); } struct boss_epoch_hunterAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp index 34072f03975..2f4225f7a74 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp @@ -24,10 +24,12 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "old_hillsbrad.h" #include "ScriptedEscortAI.h" -#include "GameObjectAI.h" /*###### ## go_barrel_old_hillsbrad @@ -56,7 +58,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetOldHillsbradAI(go); } }; @@ -79,7 +81,7 @@ enum LieutenantDrake SPELL_FRIGHTENING_SHOUT = 33789 }; -G3D::Vector3 const DrakeWP[]= +Position const DrakeWP[]= { { 2125.84f, 88.2535f, 54.8830f }, { 2111.01f, 93.8022f, 52.6356f }, @@ -109,7 +111,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_lieutenant_drakeAI(creature); + return GetOldHillsbradAI(creature); } struct boss_lieutenant_drakeAI : public ScriptedAI @@ -163,7 +165,7 @@ public: /// @todo make this work if (CanPatrol && wpId == 0) { - me->GetMotionMaster()->MovePoint(wpId, DrakeWP[wpId].x, DrakeWP[wpId].y, DrakeWP[wpId].z); + me->GetMotionMaster()->MovePoint(wpId, DrakeWP[wpId]); ++wpId; } diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp index 5e4c9c0ed0e..145e13155b1 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp @@ -24,8 +24,10 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "old_hillsbrad.h" #include "Player.h" @@ -43,7 +45,7 @@ EndScriptData */ class instance_old_hillsbrad : public InstanceMapScript { public: - instance_old_hillsbrad() : InstanceMapScript("instance_old_hillsbrad", 560) { } + instance_old_hillsbrad() : InstanceMapScript(OHScriptName, 560) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -83,7 +85,7 @@ public: } TC_LOG_DEBUG("scripts", "Instance Old Hillsbrad: GetPlayerInMap, but PlayerList is empty!"); - return NULL; + return nullptr; } void UpdateQuestCredit() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp index 2a4d13d1634..29e94b2bd9f 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp @@ -30,11 +30,13 @@ npc_taretha EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "old_hillsbrad.h" +#include "Map.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" enum Erozion { @@ -100,7 +102,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOldHillsbradAI(creature); } }; @@ -349,7 +351,7 @@ public: case 106: { //trigger taretha to run down outside - if (Creature* Taretha = instance->instance->GetCreature(instance->GetGuidData(DATA_TARETHA))) + if (Creature* Taretha = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_TARETHA))) { if (Player* player = GetPlayerForEscort()) ENSURE_AI(npc_escortAI, (Taretha->AI()))->Start(false, true, player->GetGUID()); @@ -541,7 +543,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOldHillsbradAI(creature); } }; @@ -612,7 +614,7 @@ public: if (instance->GetGuidData(DATA_EPOCH).IsEmpty()) me->SummonCreature(ENTRY_EPOCH, 2639.13f, 698.55f, 65.43f, 4.59f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 120000); - if (Creature* thrall = (ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)))) + if (Creature* thrall = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL))) ENSURE_AI(npc_thrall_old_hillsbrad::npc_thrall_old_hillsbradAI, thrall->AI())->StartWP(); } } @@ -632,7 +634,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOldHillsbradAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h index 52eb8a6c4f7..109285640cb 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h @@ -19,6 +19,9 @@ #ifndef DEF_OLD_HILLSBRAD_H #define DEF_OLD_HILLSBRAD_H +#include "CreatureAIImpl.h" + +#define OHScriptName "instance_old_hillsbrad" #define DataHeader "OH" enum OHDataTypes @@ -41,4 +44,10 @@ enum OHWorldStateIds WORLD_STATE_OH = 2436 }; +template +inline AI* GetOldHillsbradAI(T* obj) +{ + return GetInstanceAI(obj, OHScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp index 17b51ddb22f..5763344ba81 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp @@ -24,6 +24,7 @@ Category: Caverns of Time, The Dark Portal */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "the_black_morass.h" @@ -79,7 +80,7 @@ public: if (me->IsWithinDistInMap(who, 20.0f)) { Talk(SAY_BANISH); - me->DealDamage(who, who->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(who, who->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -141,7 +142,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp index 55482fd37d6..5bf079c556e 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp @@ -24,6 +24,7 @@ Category: Caverns of Time, The Black Morass */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "the_black_morass.h" @@ -82,7 +83,7 @@ public: if (me->IsWithinDistInMap(who, 20.0f)) { Talk(SAY_BANISH); - me->DealDamage(who, who->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(who, who->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -147,7 +148,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp index 3ad05a79065..79dec3487fc 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp @@ -24,6 +24,7 @@ Category: Caverns of Time, The Black Morass */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "the_black_morass.h" @@ -85,7 +86,6 @@ public: } void MoveInLineOfSight(Unit* who) override - { //Despawn Time Keeper if (who->GetTypeId() == TYPEID_UNIT && who->GetEntry() == NPC_TIME_KEEPER) @@ -94,7 +94,7 @@ public: { Talk(SAY_BANISH); - me->DealDamage(who, who->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(who, who->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -145,7 +145,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp index 053b670c254..0705071dfb9 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp @@ -24,12 +24,14 @@ Category: Caverns of Time, The Black Morass */ #include "ScriptMgr.h" +#include "EventMap.h" #include "InstanceScript.h" -#include "the_black_morass.h" +#include "Log.h" +#include "Map.h" #include "Player.h" -#include "TemporarySummon.h" #include "SpellInfo.h" -#include "ScriptedCreature.h" +#include "TemporarySummon.h" +#include "the_black_morass.h" enum Misc { @@ -71,7 +73,7 @@ enum EventIds class instance_the_black_morass : public InstanceMapScript { public: - instance_the_black_morass() : InstanceMapScript("instance_the_black_morass", 269) { } + instance_the_black_morass() : InstanceMapScript(TBMScriptName, 269) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -180,7 +182,7 @@ public: { if (medivh->IsAlive()) { - medivh->DealDamage(medivh, medivh->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + medivh->DealDamage(medivh, medivh->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); m_auiEncounter[0] = FAIL; m_auiEncounter[1] = NOT_STARTED; } @@ -276,7 +278,7 @@ public: return summon; TC_LOG_DEBUG("scripts", "Instance The Black Morass: What just happened there? No boss, no loot, no fun..."); - return NULL; + return nullptr; } void DoSpawnPortal() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp index 2f76b20ea30..6aa008f89f5 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp @@ -17,11 +17,15 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "the_black_morass.h" -#include "Player.h" #include "SpellInfo.h" +#include "the_black_morass.h" enum MedivhBm { @@ -57,7 +61,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } struct npc_medivh_bmAI : public ScriptedAI @@ -139,7 +143,7 @@ public: void EnterCombat(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (SpellCorrupt_Timer) return; @@ -250,7 +254,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } struct npc_time_riftAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h index c5274e9c985..8798f8fffe6 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h @@ -19,6 +19,9 @@ #ifndef DEF_THEBLACKMORASS_H #define DEF_THEBLACKMORASS_H +#include "CreatureAIImpl.h" + +#define TBMScriptName "instance_the_black_morass" #define DataHeader "TBM" uint32 const EncounterCount = 2; @@ -65,4 +68,10 @@ enum TBMCreatureIds NPC_INFINITE_VANQUISHER = 18995 }; +template +inline AI* GetBlackMorassAI(T* obj) +{ + return GetInstanceAI(obj, TBMScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp b/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp index 22ee9fb6bea..8d3710c21f4 100644 --- a/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp +++ b/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp @@ -24,6 +24,7 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" // Bosses (East) // 0 - Pusillin @@ -67,7 +68,6 @@ public: { return new instance_dire_maul_InstanceMapScript(map); } - }; void AddSC_instance_dire_maul() diff --git a/src/server/scripts/Kalimdor/Maraudon/boss_celebras_the_cursed.cpp b/src/server/scripts/Kalimdor/Maraudon/boss_celebras_the_cursed.cpp index 491b05063f4..04fd6552e3e 100644 --- a/src/server/scripts/Kalimdor/Maraudon/boss_celebras_the_cursed.cpp +++ b/src/server/scripts/Kalimdor/Maraudon/boss_celebras_the_cursed.cpp @@ -24,6 +24,7 @@ SDCategory: Maraudon EndScriptData */ #include "ScriptMgr.h" +#include "maraudon.h" #include "ScriptedCreature.h" enum Spells @@ -40,7 +41,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new celebras_the_cursedAI(creature); + return GetMaraudonAI(creature); } struct celebras_the_cursedAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/Maraudon/boss_landslide.cpp b/src/server/scripts/Kalimdor/Maraudon/boss_landslide.cpp index 37f79658906..047f3ae9836 100644 --- a/src/server/scripts/Kalimdor/Maraudon/boss_landslide.cpp +++ b/src/server/scripts/Kalimdor/Maraudon/boss_landslide.cpp @@ -24,6 +24,7 @@ SDCategory: Maraudon EndScriptData */ #include "ScriptMgr.h" +#include "maraudon.h" #include "ScriptedCreature.h" enum Spells @@ -40,7 +41,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_landslideAI(creature); + return GetMaraudonAI(creature); } struct boss_landslideAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/Maraudon/boss_noxxion.cpp b/src/server/scripts/Kalimdor/Maraudon/boss_noxxion.cpp index 36514199010..fa351c51f87 100644 --- a/src/server/scripts/Kalimdor/Maraudon/boss_noxxion.cpp +++ b/src/server/scripts/Kalimdor/Maraudon/boss_noxxion.cpp @@ -24,6 +24,7 @@ SDCategory: Maraudon EndScriptData */ #include "ScriptMgr.h" +#include "maraudon.h" #include "ScriptedCreature.h" enum Spells @@ -39,7 +40,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_noxxionAI(creature); + return GetMaraudonAI(creature); } struct boss_noxxionAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/Maraudon/boss_princess_theradras.cpp b/src/server/scripts/Kalimdor/Maraudon/boss_princess_theradras.cpp index e5b98337883..c8116fe027b 100644 --- a/src/server/scripts/Kalimdor/Maraudon/boss_princess_theradras.cpp +++ b/src/server/scripts/Kalimdor/Maraudon/boss_princess_theradras.cpp @@ -24,7 +24,7 @@ SDCategory: Maraudon EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "maraudon.h" #include "ScriptedCreature.h" enum Spells @@ -42,7 +42,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_ptheradrasAI(creature); + return GetMaraudonAI(creature); } struct boss_ptheradrasAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp b/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp index b3e3552b4d5..35d5760605f 100644 --- a/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp +++ b/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp @@ -24,11 +24,13 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" +#include "maraudon.h" class instance_maraudon : public InstanceMapScript { public: - instance_maraudon() : InstanceMapScript("instance_maraudon", 349) { } + instance_maraudon() : InstanceMapScript(MaraudonScriptName, 349) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { diff --git a/src/server/scripts/Kalimdor/Maraudon/maraudon.h b/src/server/scripts/Kalimdor/Maraudon/maraudon.h new file mode 100644 index 00000000000..928cfb0cf78 --- /dev/null +++ b/src/server/scripts/Kalimdor/Maraudon/maraudon.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef maraudon_h__ +#define maraudon_h__ + +#include "CreatureAIImpl.h" + +#define MaraudonScriptName "instance_maraudon" + +template +inline AI* GetMaraudonAI(T* obj) +{ + return GetInstanceAI(obj, MaraudonScriptName); +} + +#endif // maraudon_h__ diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp b/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp index 52a86f5d2fa..8799facf2f6 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp +++ b/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp @@ -26,12 +26,14 @@ SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "onyxias_lair.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Yells { @@ -193,7 +195,7 @@ public: Talk(SAY_KILL); } - void SpellHit(Unit* /*pCaster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*pCaster*/, SpellInfo const* Spell) override { if (Spell->Id == SPELL_BREATH_EAST_TO_WEST || Spell->Id == SPELL_BREATH_WEST_TO_EAST || @@ -271,7 +273,7 @@ public: } } - void SpellHitTarget(Unit* target, const SpellInfo* Spell) override + void SpellHitTarget(Unit* target, SpellInfo const* Spell) override { //Workaround - Couldn't find a way to group this spells (All Eruption) if (((Spell->Id >= 17086 && Spell->Id <= 17095) || @@ -301,7 +303,7 @@ public: return &MoveData[i]; } - return NULL; + return nullptr; } void SetNextRandomPoint() @@ -353,7 +355,7 @@ public: { DoCastVictim(SPELL_BELLOWING_ROAR); // Eruption - GameObject* Floor = NULL; + GameObject* Floor = nullptr; Trinity::GameObjectInRangeCheck check(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 15); Trinity::GameObjectLastSearcher searcher(me, Floor, check); Cell::VisitGridObjects(me, searcher, 30.0f); @@ -492,7 +494,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOnyxiaAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp b/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp index afb7c801a01..ab0fb75cb16 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp +++ b/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp @@ -23,11 +23,10 @@ SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" -#include "Cell.h" +#include "AreaBoundary.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" #include "onyxias_lair.h" #include "TemporarySummon.h" @@ -39,7 +38,7 @@ BossBoundaryData const boundaries = class instance_onyxias_lair : public InstanceMapScript { public: - instance_onyxias_lair() : InstanceMapScript("instance_onyxias_lair", 249) { } + instance_onyxias_lair() : InstanceMapScript(OnyxiaScriptName, 249) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -112,7 +111,7 @@ public: //THIS GOB IS A TRAP - What shall i do? =( //Cast it spell? Copyed Heigan method floorEruption->SendCustomAnim(floorEruption->GetGoAnimProgress()); - floorEruption->CastSpell(NULL, Difficulty(instance->GetSpawnMode()) == RAID_DIFFICULTY_10MAN_NORMAL ? 17731 : 69294); //pFloorEruption->GetGOInfo()->trap.spellId + floorEruption->CastSpell(nullptr, Difficulty(instance->GetSpawnMode()) == RAID_DIFFICULTY_10MAN_NORMAL ? 17731 : 69294); //pFloorEruption->GetGOInfo()->trap.spellId //Get all immediatly nearby floors std::list nearFloorList; @@ -240,7 +239,7 @@ public: } } - bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* /*source*/, Unit const* /*target = NULL*/, uint32 /*miscValue1 = 0*/) override + bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* /*source*/, Unit const* /*target = nullptr*/, uint32 /*miscValue1 = 0*/) override { switch (criteriaId) { diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h b/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h index ba931c86ccd..1144b3835b6 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h +++ b/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h @@ -18,6 +18,9 @@ #ifndef DEF_ONYXIAS_LAIR_H #define DEF_ONYXIAS_LAIR_H +#include "CreatureAIImpl.h" + +#define OnyxiaScriptName "instance_onyxias_lair" #define DataHeader "OL" uint32 const EncounterCount = 1; @@ -69,4 +72,11 @@ enum OLAchievementData ACHIEV_CRITERIA_DEEP_BREATH_25_PLAYER = 12569, // Criteria for achievement 4407: She Deep Breaths More (25 player) Everybody evade Deep Breath ACHIEV_TIMED_START_EVENT = 6601, // Timed event for achievement 4402, 4005: More Dots! (10, 25 player) 5 min kill }; + +template +inline AI* GetOnyxiaAI(T* obj) +{ + return GetInstanceAI(obj, OnyxiaScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp b/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp index c49d6b296ec..ba00eb87728 100644 --- a/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp +++ b/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp @@ -24,6 +24,7 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" class instance_ragefire_chasm : public InstanceMapScript { diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/boss_amnennar_the_coldbringer.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/boss_amnennar_the_coldbringer.cpp index ffb75543d84..c4cb219ea82 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/boss_amnennar_the_coldbringer.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/boss_amnennar_the_coldbringer.cpp @@ -151,7 +151,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_amnennar_the_coldbringerAI(creature); + return GetRazorfenDownsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/boss_glutton.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/boss_glutton.cpp index 553375db4f8..b4fcf2a6298 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/boss_glutton.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/boss_glutton.cpp @@ -97,7 +97,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_gluttonAI(creature); + return GetRazorfenDownsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/boss_mordresh_fire_eye.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/boss_mordresh_fire_eye.cpp index 2f6e469f257..d7b9153ead7 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/boss_mordresh_fire_eye.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/boss_mordresh_fire_eye.cpp @@ -129,7 +129,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_mordresh_fire_eyeAI(creature); + return GetRazorfenDownsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/boss_tuten_kash.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/boss_tuten_kash.cpp index 2ad263d325b..b3c5a2c46a4 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/boss_tuten_kash.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/boss_tuten_kash.cpp @@ -100,7 +100,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_tuten_kashAI(creature); + return GetRazorfenDownsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp index 5fcc2e15a35..00b8099dbe2 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "ObjectMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "razorfen_downs.h" -#include "Player.h" #include "TemporarySummon.h" Position const PosSummonTutenkash[15] = diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp index a5329422683..f43f3cfc5db 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp @@ -28,15 +28,16 @@ npc_henry_stern EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CellImpl.h" #include "GameObjectAI.h" -#include "ScriptedGossip.h" -#include "razorfen_downs.h" -#include "Player.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" +#include "razorfen_downs.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" /*### ## npc_belnistrasz for Quest 3525 "Extinguishing the Idol" @@ -203,7 +204,7 @@ public: case EVENT_COMPLETE: { DoCast(me, SPELL_IDOM_ROOM_CAMERA_SHAKE); - me->SummonGameObject(GO_BELNISTRASZS_BRAZIER, 2577.196f, 947.0781f, 53.16757f, 2.356195f, G3D::Quat(0.f, 0.f, 0.9238796f, 0.3826832f), 3600); + me->SummonGameObject(GO_BELNISTRASZS_BRAZIER, 2577.196f, 947.0781f, 53.16757f, 2.356195f, QuaternionData(0.f, 0.f, 0.9238796f, 0.3826832f), 3600); std::list ClusterList; Trinity::AllWorldObjectsInRange objects(me, 50.0f); Trinity::WorldObjectListSearcher searcher(me, ClusterList, objects); @@ -254,7 +255,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetRazorfenDownsAI(creature); } }; @@ -292,7 +293,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetRazorfenDownsAI(creature); } }; @@ -362,7 +363,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetRazorfenDownsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h index fa78d8518c1..19c26869343 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h +++ b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h @@ -18,6 +18,8 @@ #ifndef DEF_RAZORFEN_DOWNS_H #define DEF_RAZORFEN_DOWNS_H +#include "CreatureAIImpl.h" + #define RFDScriptName "instance_razorfen_downs" #define DataHeader "RFD" @@ -61,8 +63,8 @@ enum RFDGameObjectIds GO_BELNISTRASZS_BRAZIER = 152097 }; -template -AI* GetRazorfenDownsAI(T* obj) +template +inline AI* GetRazorfenDownsAI(T* obj) { return GetInstanceAI(obj, RFDScriptName); } diff --git a/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp b/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp index c14383ffaa5..2348de6c45c 100644 --- a/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp +++ b/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp @@ -24,16 +24,19 @@ SDCategory: Razorfen Kraul EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "razorfen_kraul.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "razorfen_kraul.h" #define WARD_KEEPERS_NR 2 class instance_razorfen_kraul : public InstanceMapScript { public: - instance_razorfen_kraul() : InstanceMapScript("instance_razorfen_kraul", 47) { } + instance_razorfen_kraul() : InstanceMapScript(RFKScriptName, 47) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -60,7 +63,7 @@ public: return player; } TC_LOG_DEBUG("scripts", "Instance Razorfen Kraul: GetPlayerInMap, but PlayerList is empty!"); - return NULL; + return nullptr; } void OnGameObjectCreate(GameObject* go) override diff --git a/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.cpp b/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.cpp index 64feea50156..b2ee684d0f5 100644 --- a/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.cpp +++ b/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.cpp @@ -17,11 +17,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "razorfen_kraul.h" -#include "Player.h" #include "PetAI.h" +#include "Player.h" +#include "razorfen_kraul.h" +#include "ScriptedEscortAI.h" #include "SpellScript.h" enum Willix @@ -132,7 +131,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_willixAI(creature); + return GetRazorfenKraulAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.h b/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.h index 1de42a0bb3a..c4ec5207ccf 100644 --- a/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.h +++ b/src/server/scripts/Kalimdor/RazorfenKraul/razorfen_kraul.h @@ -19,7 +19,17 @@ #ifndef DEF_RAZORFEN_KRAUL_H #define DEF_RAZORFEN_KRAUL_H +#include "CreatureAIImpl.h" + +#define RFKScriptName "instance_razorfen_kraul" #define DataHeader "RFK" #define EVENT_WARD_KEEPER 1 + +template +inline AI* GetRazorfenKraulAI(T* obj) +{ + return GetInstanceAI(obj, RFKScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp index 23247e0ba06..59432c4051b 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" #include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" enum Spells { @@ -208,7 +211,7 @@ class boss_ayamiss : public CreatureScript break; case EVENT_SWARMER_ATTACK: for (GuidList::iterator i = _swarmers.begin(); i != _swarmers.end(); ++i) - if (Creature* swarmer = me->GetMap()->GetCreature(*i)) + if (Creature* swarmer = ObjectAccessor::GetCreature(*me, *i)) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) swarmer->AI()->AttackStart(target); @@ -241,7 +244,7 @@ class boss_ayamiss : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; @@ -295,7 +298,7 @@ class npc_hive_zara_larva : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp index 735463744d7..88097b1ec30 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp @@ -17,9 +17,11 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ruins_of_ahnqiraj.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "ruins_of_ahnqiraj.h" enum Emotes { @@ -77,7 +79,7 @@ class boss_buru : public CreatureScript BossAI::EnterEvadeMode(why); for (ObjectGuid eggGuid : Eggs) - if (Creature* egg = me->GetMap()->GetCreature(eggGuid)) + if (Creature* egg = ObjectAccessor::GetCreature(*me, eggGuid)) egg->Respawn(); Eggs.clear(); @@ -161,7 +163,7 @@ class boss_buru : public CreatureScript events.ScheduleEvent(EVENT_CREEPING_PLAGUE, 6000); break; case EVENT_RESPAWN_EGG: - if (Creature* egg = me->GetMap()->GetCreature(*Eggs.begin())) + if (Creature* egg = ObjectAccessor::GetCreature(*me, Eggs.front())) { egg->Respawn(); Eggs.pop_front(); @@ -189,7 +191,7 @@ class boss_buru : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_buruAI(creature); + return GetAQ20AI(creature); } }; @@ -208,7 +210,7 @@ class npc_buru_egg : public CreatureScript void EnterCombat(Unit* attacker) override { - if (Creature* buru = me->GetMap()->GetCreature(_instance->GetGuidData(DATA_BURU))) + if (Creature* buru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BURU))) if (!buru->IsInCombat()) buru->AI()->AttackStart(attacker); } @@ -216,7 +218,7 @@ class npc_buru_egg : public CreatureScript void JustSummoned(Creature* who) override { if (who->GetEntry() == NPC_HATCHLING) - if (Creature* buru = me->GetMap()->GetCreature(_instance->GetGuidData(DATA_BURU))) + if (Creature* buru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BURU))) if (Unit* target = buru->AI()->SelectTarget(SELECT_TARGET_RANDOM)) who->AI()->AttackStart(target); } @@ -227,7 +229,7 @@ class npc_buru_egg : public CreatureScript DoCastAOE(SPELL_EXPLODE_2, true); // Unknown purpose DoCast(me, SPELL_SUMMON_HATCHLING, true); - if (Creature* buru = me->GetMap()->GetCreature(_instance->GetGuidData(DATA_BURU))) + if (Creature* buru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BURU))) if (boss_buru::boss_buruAI* buruAI = dynamic_cast(buru->AI())) buruAI->ManageRespawn(me->GetGUID()); } @@ -237,7 +239,7 @@ class npc_buru_egg : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp index 1e8db0f104c..e0e0925e7ab 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp @@ -15,11 +15,12 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ruins_of_ahnqiraj.h" #include "CreatureTextMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" enum Spells { @@ -83,8 +84,8 @@ class boss_kurinnaxx : public CreatureScript void JustDied(Unit* /*killer*/) override { _JustDied(); - if (Creature* Ossirian = me->GetMap()->GetCreature(instance->GetGuidData(DATA_OSSIRIAN))) - sCreatureTextMgr->SendChat(Ossirian, SAY_KURINAXX_DEATH, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_ZONE); + if (Creature* Ossirian = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_OSSIRIAN))) + sCreatureTextMgr->SendChat(Ossirian, SAY_KURINAXX_DEATH, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_ZONE); } void UpdateAI(uint32 diff) override @@ -136,7 +137,7 @@ class boss_kurinnaxx : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp index 9f214eb5e12..f38f3058f7c 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_moam.cpp @@ -183,7 +183,7 @@ class boss_moam : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_moamAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp index 6d0001bac73..7d9d85f876e 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp @@ -16,13 +16,19 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "ruins_of_ahnqiraj.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Opcodes.h" #include "Player.h" +#include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "TemporarySummon.h" +#include "Weather.h" #include "WorldPacket.h" -#include "Opcodes.h" enum Texts { @@ -118,7 +124,8 @@ class boss_ossirian : public CreatureScript if (spell->Id == SpellWeakness[i]) { me->RemoveAurasDueToSpell(SPELL_SUPREME); - ((TempSummon*)caster)->UnSummon(); + if (Creature* creatureCaster = caster->ToCreature()) + creatureCaster->DespawnOrUnsummon(); SpawnNextCrystal(); } } @@ -127,7 +134,7 @@ class boss_ossirian : public CreatureScript void DoAction(int32 action) override { if (action == ACTION_TRIGGER_WEAKNESS) - if (Creature* Trigger = me->GetMap()->GetCreature(TriggerGUID)) + if (Creature* Trigger = ObjectAccessor::GetCreature(*me, TriggerGUID)) if (!Trigger->HasUnitState(UNIT_STATE_CASTING)) Trigger->CastSpell(Trigger, SpellWeakness[urand(0, 4)], false); } @@ -179,7 +186,7 @@ class boss_ossirian : public CreatureScript void Cleanup() { - if (GameObject* Crystal = me->GetMap()->GetGameObject(CrystalGUID)) + if (GameObject* Crystal = ObjectAccessor::GetGameObject(*me, CrystalGUID)) Crystal->Use(me); } @@ -188,10 +195,10 @@ class boss_ossirian : public CreatureScript if (CrystalIterator == NUM_CRYSTALS) CrystalIterator = 0; - if (Creature* Trigger = me->GetMap()->SummonCreature(NPC_OSSIRIAN_TRIGGER, CrystalCoordinates[CrystalIterator])) + if (Creature* Trigger = me->SummonCreature(NPC_OSSIRIAN_TRIGGER, CrystalCoordinates[CrystalIterator])) { TriggerGUID = Trigger->GetGUID(); - if (GameObject* Crystal = Trigger->SummonGameObject(GO_OSSIRIAN_CRYSTAL, CrystalCoordinates[CrystalIterator], G3D::Quat(), uint32(-1))) + if (GameObject* Crystal = Trigger->SummonGameObject(GO_OSSIRIAN_CRYSTAL, CrystalCoordinates[CrystalIterator], QuaternionData(), uint32(-1))) { CrystalGUID = Crystal->GetGUID(); ++CrystalIterator; @@ -270,7 +277,7 @@ class boss_ossirian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; @@ -298,7 +305,7 @@ class go_ossirian_crystal : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetAQ20AI(go); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_rajaxx.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_rajaxx.cpp index 5fd456c0295..397477b7129 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_rajaxx.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_rajaxx.cpp @@ -16,9 +16,9 @@ */ #include "ObjectMgr.h" -#include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" +#include "ScriptMgr.h" enum Yells { @@ -130,7 +130,7 @@ class boss_rajaxx : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_rajaxxAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp index 2c3e23f4dd4..8a24b8bdaf3 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "ruins_of_ahnqiraj.h" class instance_ruins_of_ahnqiraj : public InstanceMapScript { public: - instance_ruins_of_ahnqiraj() : InstanceMapScript("instance_ruins_of_ahnqiraj", 509) { } + instance_ruins_of_ahnqiraj() : InstanceMapScript(AQ20ScriptName, 509) { } struct instance_ruins_of_ahnqiraj_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h index 944c2768b9d..1c25c905328 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h @@ -18,6 +18,9 @@ #ifndef DEF_RUINS_OF_AHNQIRAJ_H #define DEF_RUINS_OF_AHNQIRAJ_H +#include "CreatureAIImpl.h" + +#define AQ20ScriptName "instance_ruins_of_ahnqiraj" #define DataHeader "AQR" enum AQRDataTypes @@ -57,4 +60,10 @@ enum AQRGameObjectIds GO_OSSIRIAN_CRYSTAL = 180619 }; +template +inline AI* GetAQ20AI(T* obj) +{ + return GetInstanceAI(obj, AQ20ScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp index 19af5cad56d..779e973f330 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp @@ -24,8 +24,11 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "temple_of_ahnqiraj.h" +#include "TemporarySummon.h" enum Spells { @@ -48,7 +51,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct boss_kriAI : public ScriptedAI @@ -147,7 +150,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct boss_vemAI : public ScriptedAI @@ -201,7 +204,7 @@ public: //Charge_Timer if (Charge_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) { @@ -242,7 +245,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct boss_yaujAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp index 9e03c3031aa..6f531894c98 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp @@ -24,9 +24,13 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "temple_of_ahnqiraj.h" -#include "Player.h" +#include "TemporarySummon.h" /* * This is a 2 phases events. Here follows an explanation of the main events and transition between phases and sub-phases. @@ -153,7 +157,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct eye_of_cthunAI : public ScriptedAI @@ -284,7 +288,7 @@ public: { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { - Creature* Spawned = NULL; + Creature* Spawned = nullptr; //Spawn claw tentacle on the random target Spawned = me->SummonCreature(NPC_CLAW_TENTACLE, *target, TEMPSUMMON_CORPSE_DESPAWN, 500); @@ -453,7 +457,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct cthunAI : public ScriptedAI @@ -545,7 +549,7 @@ public: Unit* SelectRandomNotStomach() { if (Stomach_Map.empty()) - return NULL; + return nullptr; std::unordered_map::const_iterator i = Stomach_Map.begin(); @@ -566,7 +570,7 @@ public: } if (temp.empty()) - return NULL; + return nullptr; j = temp.begin(); @@ -587,7 +591,7 @@ public: if (WisperTimer <= diff) { //Play random sound to the zone - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) me->PlayDirectSound(RANDOM_SOUND_WHISPER, itr->GetSource()); @@ -754,7 +758,7 @@ public: //Set target in stomach Stomach_Map[target->GetGUID()] = true; target->InterruptNonMeleeSpells(false); - target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, NULL, NULL, me->GetGUID()); + target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, nullptr, nullptr, me->GetGUID()); StomachEnterTarget = target->GetGUID(); StomachEnterVisTimer = 3800; } @@ -891,7 +895,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new eye_tentacleAI(creature); + return GetAQ40AI(creature); } struct eye_tentacleAI : public ScriptedAI @@ -969,7 +973,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new claw_tentacleAI(creature); + return GetAQ40AI(creature); } struct claw_tentacleAI : public ScriptedAI @@ -1083,7 +1087,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new giant_claw_tentacleAI(creature); + return GetAQ40AI(creature); } struct giant_claw_tentacleAI : public ScriptedAI @@ -1207,7 +1211,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new giant_eye_tentacleAI(creature); + return GetAQ40AI(creature); } struct giant_eye_tentacleAI : public ScriptedAI @@ -1273,7 +1277,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new flesh_tentacleAI(creature); + return GetAQ40AI(creature); } struct flesh_tentacleAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp index 011cf1509a5..e03bbe211c5 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp @@ -25,6 +25,8 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "temple_of_ahnqiraj.h" +#include "TemporarySummon.h" #define SOUND_SENTENCE_YOU 8588 #define SOUND_SERVE_TO 8589 @@ -48,7 +50,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_fankrissAI(creature); + return GetAQ40AI(creature); } struct boss_fankrissAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_huhuran.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_huhuran.cpp index 45a61cecd47..d0912023709 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_huhuran.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_huhuran.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "temple_of_ahnqiraj.h" enum Huhuran { @@ -46,7 +47,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_huhuranAI(creature); + return GetAQ40AI(creature); } struct boss_huhuranAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp index 2e8ee5f4259..3a154f40eed 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp @@ -43,7 +43,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_ouroAI(creature); + return GetAQ40AI(creature); } struct boss_ouroAI : public ScriptedAI @@ -122,7 +122,7 @@ public: //ChangeTarget_Timer if (Submerged && ChangeTarget_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_sartura.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_sartura.cpp index 006d6377b42..8d1e8ad302e 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_sartura.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_sartura.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "temple_of_ahnqiraj.h" enum Sartura { @@ -48,7 +49,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_sarturaAI(creature); + return GetAQ40AI(creature); } struct boss_sarturaAI : public ScriptedAI @@ -198,7 +199,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_sartura_royal_guardAI(creature); + return GetAQ40AI(creature); } struct npc_sartura_royal_guardAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp index 116f634893f..76833e06841 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp @@ -83,7 +83,7 @@ class boss_skeram : public CreatureScript { ScriptedAI::EnterEvadeMode(why); if (me->IsSummon()) - ((TempSummon*)me)->UnSummon(); + me->DespawnOrUnsummon(); } void JustSummoned(Creature* creature) override @@ -200,7 +200,7 @@ class boss_skeram : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_skeramAI(creature); + return GetAQ40AI(creature); } }; @@ -258,10 +258,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRUE_FULFILLMENT_2) - || !sSpellMgr->GetSpellInfo(SPELL_GENERIC_DISMOUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TRUE_FULFILLMENT_2, SPELL_GENERIC_DISMOUNT }); } void HandleEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp index e48e74897da..d98cf055d30 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp @@ -24,11 +24,15 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Item.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellInfo.h" #include "temple_of_ahnqiraj.h" #include "WorldPacket.h" -#include "Item.h" -#include "Spell.h" enum Spells { @@ -167,7 +171,7 @@ struct boss_twinemperorsAI : public ScriptedAI } } - void SpellHit(Unit* caster, const SpellInfo* entry) override + void SpellHit(Unit* caster, SpellInfo const* entry) override { if (caster == me) return; @@ -320,9 +324,9 @@ struct boss_twinemperorsAI : public ScriptedAI me->GetCreatureListWithEntryInGrid(lUnitList, 15317, 150.0f); if (lUnitList.empty()) - return NULL; + return nullptr; - Creature* nearb = NULL; + Creature* nearb = nullptr; for (std::list::const_iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) { @@ -382,9 +386,13 @@ struct boss_twinemperorsAI : public ScriptedAI if (!me->IsNonMeleeSpellCast(true)) { DoCast(me, SPELL_BERSERK); - EnrageTimer = 60*60000; - } else EnrageTimer = 0; - } else EnrageTimer-=diff; + EnrageTimer = 60 * 60000; + } + else + EnrageTimer = 0; + } + else + EnrageTimer -= diff; } }; @@ -395,7 +403,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct boss_veknilashAI : public boss_twinemperorsAI @@ -483,7 +491,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } struct boss_veklorAI : public boss_twinemperorsAI @@ -550,7 +558,7 @@ public: //Blizzard_Timer if (Blizzard_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45, true); if (target) DoCast(target, SPELL_BLIZZARD); diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp index 1d41e808bc9..189b706d153 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "temple_of_ahnqiraj.h" +#include "TemporarySummon.h" enum Spells { @@ -255,7 +259,7 @@ class boss_viscidus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_viscidusAI(creature); + return GetAQ40AI(creature); } }; @@ -272,7 +276,7 @@ class npc_glob_of_viscidus : public CreatureScript { InstanceScript* Instance = me->GetInstanceScript(); - if (Creature* Viscidus = me->GetMap()->GetCreature(Instance->GetGuidData(DATA_VISCIDUS))) + if (Creature* Viscidus = ObjectAccessor::GetCreature(*me, Instance->GetGuidData(DATA_VISCIDUS))) { if (BossAI* ViscidusAI = dynamic_cast(Viscidus->GetAI())) ViscidusAI->SummonedCreatureDespawn(me); @@ -304,7 +308,7 @@ class npc_glob_of_viscidus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp index 054844c9c2f..8596737bd14 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp @@ -24,13 +24,15 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "temple_of_ahnqiraj.h" class instance_temple_of_ahnqiraj : public InstanceMapScript { public: - instance_temple_of_ahnqiraj() : InstanceMapScript("instance_temple_of_ahnqiraj", 531) { } + instance_temple_of_ahnqiraj() : InstanceMapScript(AQ40ScriptName, 531) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -70,24 +72,24 @@ class instance_temple_of_ahnqiraj : public InstanceMapScript { switch (creature->GetEntry()) { - case NPC_SKERAM: - SkeramGUID = creature->GetGUID(); - break; - case NPC_VEM: - VemGUID = creature->GetGUID(); - break; - case NPC_KRI: - KriGUID = creature->GetGUID(); - break; - case NPC_VEKLOR: - VeklorGUID = creature->GetGUID(); - break; - case NPC_VEKNILASH: - VeknilashGUID = creature->GetGUID(); - break; - case NPC_VISCIDUS: - ViscidusGUID = creature->GetGUID(); - break; + case NPC_SKERAM: + SkeramGUID = creature->GetGUID(); + break; + case NPC_VEM: + VemGUID = creature->GetGUID(); + break; + case NPC_KRI: + KriGUID = creature->GetGUID(); + break; + case NPC_VEKLOR: + VeklorGUID = creature->GetGUID(); + break; + case NPC_VEKNILASH: + VeknilashGUID = creature->GetGUID(); + break; + case NPC_VISCIDUS: + ViscidusGUID = creature->GetGUID(); + break; } } @@ -101,26 +103,26 @@ class instance_temple_of_ahnqiraj : public InstanceMapScript { switch (type) { - case DATA_VEMISDEAD: - if (IsBossDied[0]) - return 1; - break; - - case DATA_VEKLORISDEAD: - if (IsBossDied[1]) - return 1; - break; - - case DATA_VEKNILASHISDEAD: - if (IsBossDied[2]) - return 1; - break; - - case DATA_BUG_TRIO_DEATH: - return BugTrioDeathCount; - - case DATA_CTHUN_PHASE: - return CthunPhase; + case DATA_VEMISDEAD: + if (IsBossDied[0]) + return 1; + break; + + case DATA_VEKLORISDEAD: + if (IsBossDied[1]) + return 1; + break; + + case DATA_VEKNILASHISDEAD: + if (IsBossDied[2]) + return 1; + break; + + case DATA_BUG_TRIO_DEATH: + return BugTrioDeathCount; + + case DATA_CTHUN_PHASE: + return CthunPhase; } return 0; } @@ -129,18 +131,18 @@ class instance_temple_of_ahnqiraj : public InstanceMapScript { switch (identifier) { - case DATA_SKERAM: - return SkeramGUID; - case DATA_VEM: - return VemGUID; - case DATA_KRI: - return KriGUID; - case DATA_VEKLOR: - return VeklorGUID; - case DATA_VEKNILASH: - return VeknilashGUID; - case DATA_VISCIDUS: - return ViscidusGUID; + case DATA_SKERAM: + return SkeramGUID; + case DATA_VEM: + return VemGUID; + case DATA_KRI: + return KriGUID; + case DATA_VEKLOR: + return VeklorGUID; + case DATA_VEKNILASH: + return VeknilashGUID; + case DATA_VISCIDUS: + return ViscidusGUID; } return ObjectGuid::Empty; } // end GetGuidData @@ -149,25 +151,25 @@ class instance_temple_of_ahnqiraj : public InstanceMapScript { switch (type) { - case DATA_VEM_DEATH: - IsBossDied[0] = true; - break; + case DATA_VEM_DEATH: + IsBossDied[0] = true; + break; - case DATA_BUG_TRIO_DEATH: - ++BugTrioDeathCount; - break; + case DATA_BUG_TRIO_DEATH: + ++BugTrioDeathCount; + break; - case DATA_VEKLOR_DEATH: - IsBossDied[1] = true; - break; + case DATA_VEKLOR_DEATH: + IsBossDied[1] = true; + break; - case DATA_VEKNILASH_DEATH: - IsBossDied[2] = true; - break; + case DATA_VEKNILASH_DEATH: + IsBossDied[2] = true; + break; - case DATA_CTHUN_PHASE: - CthunPhase = data; - break; + case DATA_CTHUN_PHASE: + CthunPhase = data; + break; } } }; diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp index a4457b7e82b..c7c41ef22c7 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp @@ -24,17 +24,9 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "WorldPacket.h" - -#include "Item.h" -#include "Player.h" -#include "Spell.h" - -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "temple_of_ahnqiraj.h" enum Spells { @@ -66,7 +58,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new aqsentinelAI(creature); + return GetAQ40AI(creature); } struct aqsentinelAI : public ScriptedAI diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h index 58e75af6276..1a1f366a946 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h @@ -19,6 +19,9 @@ #ifndef DEF_TEMPLE_OF_AHNQIRAJ_H #define DEF_TEMPLE_OF_AHNQIRAJ_H +#include "CreatureAIImpl.h" + +#define AQ40ScriptName "instance_temple_of_ahnqiraj" #define DataHeader "AQT" enum AQTDataTypes @@ -62,4 +65,10 @@ enum AQTCreatures NPC_VEKNILASH = 15275 }; +template +inline AI* GetAQ40AI(T* obj) +{ + return GetInstanceAI(obj, AQ40ScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp b/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp index 672bae016c1..3748e7ffc1c 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp +++ b/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp @@ -24,7 +24,10 @@ SDCategory: Wailing Caverns EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "wailing_caverns.h" #define MAX_ENCOUNTER 9 @@ -32,7 +35,7 @@ EndScriptData */ class instance_wailing_caverns : public InstanceMapScript { public: - instance_wailing_caverns() : InstanceMapScript("instance_wailing_caverns", 43) { } + instance_wailing_caverns() : InstanceMapScript(WCScriptName, 43) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -115,7 +118,7 @@ public: return saveStream.str(); } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp index 23516577f44..05385a0c6bf 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp +++ b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp @@ -27,11 +27,13 @@ EndScriptData */ EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "wailing_caverns.h" -#include "Player.h" /*###### ## npc_disciple_of_naralex @@ -205,7 +207,7 @@ public: ++eventProgress; eventTimer = 15000; //CAST_AI(npc_escort::npc_escortAI, me->AI())->SetCanDefend(false); - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) DoCast(naralex, SPELL_NARALEXS_AWAKENING, true); Talk(EMOTE_AWAKENING_RITUAL); } @@ -214,7 +216,7 @@ public: { ++eventProgress; eventTimer = 15000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(EMOTE_TROUBLED_SLEEP); me->SummonCreature(NPC_DEVIATE_MOCCASIN, 135.943f, 199.701f, -103.529f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); me->SummonCreature(NPC_DEVIATE_MOCCASIN, 151.08f, 221.13f, -103.609f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); @@ -225,7 +227,7 @@ public: { ++eventProgress; eventTimer = 30000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(EMOTE_WRITHE_IN_AGONY); me->SummonCreature(NPC_NIGHTMARE_ECTOPLASM, 133.413f, 207.188f, -102.469f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); me->SummonCreature(NPC_NIGHTMARE_ECTOPLASM, 142.857f, 218.645f, -102.905f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); @@ -239,7 +241,7 @@ public: if (eventProgress == 5) { ++eventProgress; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(EMOTE_HORRENDOUS_VISION); me->SummonCreature(NPC_MUTANUS_THE_DEVOURER, 150.872f, 262.905f, -103.503f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 300000); Talk(SAY_MUTANUS_THE_DEVOURER); @@ -250,7 +252,7 @@ public: { ++eventProgress; eventTimer = 3000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) { if (me->HasAura(SPELL_NARALEXS_AWAKENING)) me->RemoveAura(SPELL_NARALEXS_AWAKENING); @@ -264,7 +266,7 @@ public: { ++eventProgress; eventTimer = 6000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(SAY_THANK_YOU); } else @@ -272,7 +274,7 @@ public: { ++eventProgress; eventTimer = 8000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) { naralex->AI()->Talk(SAY_FAREWELL); naralex->AddAura(SPELL_FLIGHT_FORM, naralex); @@ -286,7 +288,7 @@ public: { ++eventProgress; eventTimer = 1500; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->GetMotionMaster()->MovePoint(25, naralex->GetPositionX(), naralex->GetPositionY(), naralex->GetPositionZ()); } else @@ -294,7 +296,7 @@ public: { ++eventProgress; eventTimer = 2500; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) { naralex->GetMotionMaster()->MovePoint(0, 117.095512f, 247.107971f, -96.167870f); naralex->GetMotionMaster()->MovePoint(1, 90.388809f, 276.135406f, -83.389801f); @@ -305,7 +307,7 @@ public: else if (eventProgress == 11) { - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->SetVisible(false); me->SetVisible(false); instance->SetData(TYPE_NARALEX_PART3, DONE); @@ -363,7 +365,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetWailingCavernsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h index 1b655815934..98d293c1416 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h +++ b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h @@ -19,6 +19,9 @@ #ifndef DEF_WAILING_CAVERNS_H #define DEF_WAILING_CAVERNS_H +#include "CreatureAIImpl.h" + +#define WCScriptName "instance_wailing_caverns" #define DataHeader "WC" enum WCDataTypes @@ -37,4 +40,10 @@ enum WCDataTypes DATA_NARALEX = 3679, }; +template +inline AI* GetWailingCavernsAI(T* obj) +{ + return GetInstanceAI(obj, WCScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp b/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp index 2a7af38c1ab..9e6da47dcf1 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp @@ -21,6 +21,7 @@ Category: Tanaris, ZulFarrak */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "zulfarrak.h" @@ -152,7 +153,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulFarrakAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp b/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp index cf8824395e3..0a4426e447e 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "zulfarrak.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" #include "TemporarySummon.h" +#include "zulfarrak.h" enum Misc { @@ -99,7 +102,7 @@ float Spawnsway[2][3] = class instance_zulfarrak : public InstanceMapScript { public: - instance_zulfarrak() : InstanceMapScript("instance_zulfarrak", 209) { } + instance_zulfarrak() : InstanceMapScript(ZFScriptName, 209) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -216,9 +219,9 @@ public: switch (type) { case EVENT_PYRAMID: - PyramidPhase=data; + PyramidPhase = data; break; - }; + } } virtual void Update(uint32 diff) override diff --git a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp index 6539decdd56..f27a910e4e7 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp @@ -29,11 +29,15 @@ npc_weegli_blastfuse EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "GameObjectAI.h" #include "zulfarrak.h" -#include "Player.h" /*###### ## npc_sergeant_bly @@ -99,7 +103,7 @@ public: { case 1: //weegli doesn't fight - he goes & blows up the door - if (Creature* pWeegli = instance->instance->GetCreature(instance->GetGuidData(ENTRY_WEEGLI))) + if (Creature* pWeegli = ObjectAccessor::GetCreature(*me, instance->GetGuidData(ENTRY_WEEGLI))) pWeegli->AI()->DoAction(0); Talk(SAY_1); Text_Timer = 5000; @@ -188,7 +192,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulFarrakAI(creature); } }; @@ -222,7 +226,7 @@ public: private: void initBlyCrewMember(uint32 entry, float x, float y, float z) { - if (Creature* crew = instance->instance->GetCreature(instance->GetGuidData(entry))) + if (Creature* crew = ObjectAccessor::GetCreature(*me, instance->GetGuidData(entry))) { crew->SetReactState(REACT_AGGRESSIVE); crew->SetWalk(true); @@ -235,7 +239,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetZulFarrakAI(go); } }; @@ -269,7 +273,7 @@ public: npc_weegli_blastfuseAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); - destroyingDoor=false; + destroyingDoor = false; Bomb_Timer = 10000; LandMine_Timer = 30000; } @@ -344,7 +348,7 @@ public: me->GetMotionMaster()->MovePoint(0, 1858.57f, 1146.35f, 14.745f); me->SetHomePosition(1858.57f, 1146.35f, 14.745f, 3.85f); // in case he gets interrupted Talk(SAY_WEEGLI_OK_I_GO); - destroyingDoor=true; + destroyingDoor = true; } } @@ -381,7 +385,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulFarrakAI(creature); } }; @@ -425,7 +429,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new go_shallow_graveAI(go); + return GetZulFarrakAI(go); } }; @@ -444,7 +448,7 @@ class at_zumrah : public AreaTriggerScript public: at_zumrah() : AreaTriggerScript("at_zumrah") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { Creature* pZumrah = player->FindNearestCreature(ZUMRAH_ID, 30.0f); diff --git a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h index e6f97b339aa..86916c2a580 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h +++ b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h @@ -19,6 +19,9 @@ #ifndef DEF_ZF_H #define DEF_ZF_H +#include "CreatureAIImpl.h" + +#define ZFScriptName "instance_zulfarrak" #define DataHeader "ZF" enum ZFEntries @@ -54,4 +57,10 @@ enum ZFPyramidPhases PYRAMID_KILLED_ALL_TROLLS, }; +template +inline AI* GetZulFarrakAI(T* obj) +{ + return GetInstanceAI(obj, ZFScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/boss_azuregos.cpp b/src/server/scripts/Kalimdor/boss_azuregos.cpp index 37542f08d99..a5ade380e31 100644 --- a/src/server/scripts/Kalimdor/boss_azuregos.cpp +++ b/src/server/scripts/Kalimdor/boss_azuregos.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" enum Say { @@ -188,11 +188,7 @@ class spell_mark_of_frost : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_FROST)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_AURA_OF_FROST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_FROST, SPELL_AURA_OF_FROST }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Kalimdor/zone_ashenvale.cpp b/src/server/scripts/Kalimdor/zone_ashenvale.cpp index 35fb7d4f418..f5680664e27 100644 --- a/src/server/scripts/Kalimdor/zone_ashenvale.cpp +++ b/src/server/scripts/Kalimdor/zone_ashenvale.cpp @@ -28,10 +28,12 @@ npc_ruul_snowhoof EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedEscortAI.h" +#include "SpellInfo.h" #include "SpellScript.h" /*#### diff --git a/src/server/scripts/Kalimdor/zone_azshara.cpp b/src/server/scripts/Kalimdor/zone_azshara.cpp index b6572c99f7d..0813b05705f 100644 --- a/src/server/scripts/Kalimdor/zone_azshara.cpp +++ b/src/server/scripts/Kalimdor/zone_azshara.cpp @@ -17,9 +17,11 @@ */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" #include "SpellInfo.h" /*###### @@ -65,7 +67,7 @@ public: void EnterCombat(Unit* /*who*/) override { } - void SpellHit(Unit* unit, const SpellInfo* spell) override + void SpellHit(Unit* unit, SpellInfo const* spell) override { if (spellhit) return; @@ -97,9 +99,9 @@ public: return; } // walk 5 seconds before summoning - if (spellhit && morphtimer<5000) + if (spellhit && morphtimer < 5000) { - morphtimer+=diff; + morphtimer += diff; if (morphtimer >= 5000) { DoCast(me, SPELL_POLYMORPH_BACKFIRE); // summon copies diff --git a/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp b/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp index 77295abb873..c4036fbe836 100644 --- a/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp +++ b/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp @@ -34,14 +34,15 @@ npc_death_ravager EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "ScriptedGossip.h" -#include "GameObjectAI.h" -#include "Cell.h" #include "CellImpl.h" +#include "GameObjectAI.h" #include "GridNotifiersImpl.h" -#include "GridNotifiers.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" /*###### ## npc_draenei_survivor @@ -112,7 +113,7 @@ public: } } - void SpellHit(Unit* Caster, const SpellInfo* Spell) override + void SpellHit(Unit* Caster, SpellInfo const* Spell) override { if (Spell->SpellFamilyFlags[2] & 0x080000000) { diff --git a/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp b/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp index 9dfd78f52e9..afecffd2ff1 100644 --- a/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp +++ b/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp @@ -27,14 +27,15 @@ EndScriptData */ npc_webbed_creature EndContentData */ -#include "Player.h" -#include "Group.h" -#include "GridNotifiersImpl.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "PassiveAI.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "Player.h" +#include "ScriptedEscortAI.h" /*###### ## npc_webbed_creature @@ -439,7 +440,7 @@ public: break; case EVENT_HEALING_SURGE: { - Unit* target = NULL; + Unit* target = nullptr; if (me->GetHealthPct() < 85) target = me; else if (Player* player = GetPlayerForEscort()) @@ -508,7 +509,7 @@ public: _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { - if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i], G3D::Quat(), 0)) + if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i], QuaternionData(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } me->HandleEmoteCommand(EMOTE_ONESHOT_NONE); // reset anim state @@ -604,7 +605,7 @@ public: _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { - if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i], G3D::Quat(), 0)) + if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i], QuaternionData(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } Talk(SAY_LEGOSO_15); @@ -749,7 +750,7 @@ public: SetEscortPaused(true); //Find Sironas and make it respawn if needed - Creature* sironas = NULL; + Creature* sironas = nullptr; Trinity::AllCreaturesOfEntryInRange check(me, NPC_SIRONAS, SIZE_OF_GRIDS); Trinity::CreatureSearcher searcher(me, sironas, check); Cell::VisitAllObjects(me, searcher, SIZE_OF_GRIDS); diff --git a/src/server/scripts/Kalimdor/zone_darkshore.cpp b/src/server/scripts/Kalimdor/zone_darkshore.cpp index 990c266e041..b2bdd76c137 100644 --- a/src/server/scripts/Kalimdor/zone_darkshore.cpp +++ b/src/server/scripts/Kalimdor/zone_darkshore.cpp @@ -104,7 +104,7 @@ public: } } - void SpellHit(Unit* /*pCaster*/, const SpellInfo* pSpell) override + void SpellHit(Unit* /*pCaster*/, SpellInfo const* pSpell) override { if (HasFollowState(STATE_FOLLOW_INPROGRESS | STATE_FOLLOW_PAUSED) && pSpell->Id == SPELL_AWAKEN) ClearSleeping(); diff --git a/src/server/scripts/Kalimdor/zone_desolace.cpp b/src/server/scripts/Kalimdor/zone_desolace.cpp index 0b0264439ff..9027b59f3e3 100644 --- a/src/server/scripts/Kalimdor/zone_desolace.cpp +++ b/src/server/scripts/Kalimdor/zone_desolace.cpp @@ -31,11 +31,12 @@ go_demon_portal EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" enum DyingKodo diff --git a/src/server/scripts/Kalimdor/zone_durotar.cpp b/src/server/scripts/Kalimdor/zone_durotar.cpp index 821c7d34641..d35c90fca0c 100644 --- a/src/server/scripts/Kalimdor/zone_durotar.cpp +++ b/src/server/scripts/Kalimdor/zone_durotar.cpp @@ -16,10 +16,15 @@ */ #include "ScriptMgr.h" +#include "CreatureAIImpl.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "Vehicle.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Texts { @@ -373,9 +378,7 @@ class spell_mount_check : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOUNTING_CHECK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MOUNTING_CHECK }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -421,11 +424,7 @@ class spell_voljin_war_drums : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOTIVATE_1)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MOTIVATE_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MOTIVATE_1, SPELL_MOTIVATE_2 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -478,12 +477,7 @@ class spell_voodoo : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BREW) || !sSpellMgr->GetSpellInfo(SPELL_GHOSTLY) || - !sSpellMgr->GetSpellInfo(SPELL_HEX1) || !sSpellMgr->GetSpellInfo(SPELL_HEX2) || - !sSpellMgr->GetSpellInfo(SPELL_HEX3) || !sSpellMgr->GetSpellInfo(SPELL_GROW) || - !sSpellMgr->GetSpellInfo(SPELL_LAUNCH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BREW, SPELL_GHOSTLY, SPELL_HEX1, SPELL_HEX2, SPELL_HEX3, SPELL_GROW, SPELL_LAUNCH }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp b/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp index 2c44c1b91aa..898eaa8521e 100644 --- a/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp +++ b/src/server/scripts/Kalimdor/zone_dustwallow_marsh.cpp @@ -30,11 +30,12 @@ npc_cassa_crimsonwing - handled by npc_taxi EndContentData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" #include "ScriptedGossip.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" #include "WorldSession.h" /*###### @@ -226,7 +227,6 @@ public: }; - enum SpellScripts { SPELL_OOZE_ZAP = 42489, @@ -246,9 +246,7 @@ class spell_ooze_zap : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_OOZE_ZAP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_OOZE_ZAP }); } SpellCastResult CheckRequirement() @@ -293,9 +291,7 @@ class spell_ooze_zap_channel_end : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_OOZE_ZAP_CHANNEL_END)) - return false; - return true; + return ValidateSpellInfo({ SPELL_OOZE_ZAP_CHANNEL_END }); } void HandleDummy(SpellEffIndex effIndex) @@ -329,9 +325,7 @@ class spell_energize_aoe : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ENERGIZED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ENERGIZED }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Kalimdor/zone_felwood.cpp b/src/server/scripts/Kalimdor/zone_felwood.cpp index 4ede963d5ad..70cbad8b295 100644 --- a/src/server/scripts/Kalimdor/zone_felwood.cpp +++ b/src/server/scripts/Kalimdor/zone_felwood.cpp @@ -28,9 +28,10 @@ at_ancient_leaf EndContentData */ #include "ScriptMgr.h" +#include "Map.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" /*###### ## at_ancient_leaf diff --git a/src/server/scripts/Kalimdor/zone_feralas.cpp b/src/server/scripts/Kalimdor/zone_feralas.cpp index b9c2a20abf1..16c30f6fadd 100644 --- a/src/server/scripts/Kalimdor/zone_feralas.cpp +++ b/src/server/scripts/Kalimdor/zone_feralas.cpp @@ -29,11 +29,12 @@ spell_gordunni_trap EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" #include "WorldSession.h" /*###### @@ -166,7 +167,7 @@ class spell_gordunni_trap : public SpellScriptLoader void HandleDummy() { Unit* caster = GetCaster(); - if (GameObject* chest = caster->SummonGameObject(urand(0, 1) ? GO_GORDUNNI_DIRT_MOUND_1 : GO_GORDUNNI_DIRT_MOUND_2, *caster, G3D::Quat(), 0)) + if (GameObject* chest = caster->SummonGameObject(urand(0, 1) ? GO_GORDUNNI_DIRT_MOUND_1 : GO_GORDUNNI_DIRT_MOUND_2, *caster, QuaternionData(), 0)) { chest->SetSpellId(GetSpellInfo()->Id); caster->RemoveGameObject(chest, false); diff --git a/src/server/scripts/Kalimdor/zone_moonglade.cpp b/src/server/scripts/Kalimdor/zone_moonglade.cpp index 1d220f9ad48..e8e6f5ff8d8 100644 --- a/src/server/scripts/Kalimdor/zone_moonglade.cpp +++ b/src/server/scripts/Kalimdor/zone_moonglade.cpp @@ -30,15 +30,15 @@ npc_giant_spotlight EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" -#include "Player.h" #include "SpellInfo.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" +#include "TemporarySummon.h" /*###### ## npc_clintar_spirit @@ -443,7 +443,7 @@ public: DoCast(SPELL_OMEN_SUMMON_SPOTLIGHT); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_ELUNE_CANDLE) { diff --git a/src/server/scripts/Kalimdor/zone_orgrimmar.cpp b/src/server/scripts/Kalimdor/zone_orgrimmar.cpp index e75f69287b7..2603173e992 100644 --- a/src/server/scripts/Kalimdor/zone_orgrimmar.cpp +++ b/src/server/scripts/Kalimdor/zone_orgrimmar.cpp @@ -29,13 +29,14 @@ npc_thrall_warchief EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "Player.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" /*###### ## npc_shenthul diff --git a/src/server/scripts/Kalimdor/zone_silithus.cpp b/src/server/scripts/Kalimdor/zone_silithus.cpp index 436e75ccffa..34d3cc7cded 100644 --- a/src/server/scripts/Kalimdor/zone_silithus.cpp +++ b/src/server/scripts/Kalimdor/zone_silithus.cpp @@ -36,11 +36,16 @@ TO DO: Dragons should use the HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF) after tr EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "CreatureAIImpl.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "Group.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" /*##### # Quest: A Pawn on the Eternal Board @@ -503,11 +508,11 @@ public: DoCast(player, SPELL_CALL_PRISMATIC_BARRIER, true); break; case 37: - me->SummonGameObject(GO_GATE_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); + me->SummonGameObject(GO_GATE_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), QuaternionData(), 0); break; case 38: DoCast(player, SPELL_CALL_GLYPHS_OF_WARDING, true); - me->SummonGameObject(GO_GLYPH_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); + me->SummonGameObject(GO_GLYPH_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), QuaternionData(), 0); break; case 39: Talk(ANACHRONOS_SAY_5, Fandral); @@ -516,7 +521,7 @@ public: Fandral->CastSpell(me, SPELL_CALL_ANCIENTS, true); break; case 41: - Fandral->SummonGameObject(GO_ROOTS_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); + Fandral->SummonGameObject(GO_ROOTS_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), QuaternionData(), 0); Fandral->AI()->Talk(FANDRAL_SAY_3); break; case 42: @@ -552,7 +557,7 @@ public: case 51: { uint32 entries[4] = { NPC_KALDOREI_INFANTRY, NPC_ANUBISATH_CONQUEROR, NPC_QIRAJI_WASP, NPC_QIRAJI_TANK }; - Unit* mob = NULL; + Unit* mob = nullptr; for (uint8 i = 0; i < 4; ++i) { mob = player->FindNearestCreature(entries[i], 50); @@ -616,7 +621,7 @@ public: { Talk(ARYGOS_YELL_1); AnachronosQuestTrigger->AI()->EnterEvadeMode(); - eventEnd=true; + eventEnd = true; } break; } @@ -739,7 +744,7 @@ public: } if (!hasTarget) { - Unit* target = NULL; + Unit* target = nullptr; if (me->GetEntry() == NPC_ANUBISATH_CONQUEROR || me->GetEntry() == NPC_QIRAJI_TANK || me->GetEntry() == NPC_QIRAJI_WASP) target = me->FindNearestCreature(NPC_KALDOREI_INFANTRY, 20, true); if (me->GetEntry() == NPC_KALDOREI_INFANTRY) @@ -867,7 +872,7 @@ public: if (Group* EventGroup = player->GetGroup()) { - Player* groupMember = NULL; + Player* groupMember = nullptr; uint8 GroupMemberCount = 0; uint8 DeadMemberCount = 0; diff --git a/src/server/scripts/Kalimdor/zone_tanaris.cpp b/src/server/scripts/Kalimdor/zone_tanaris.cpp index 197221bddcf..fcd531a10ce 100644 --- a/src/server/scripts/Kalimdor/zone_tanaris.cpp +++ b/src/server/scripts/Kalimdor/zone_tanaris.cpp @@ -31,11 +31,12 @@ npc_tooga EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedFollowerAI.h" -#include "Player.h" +#include "ScriptedGossip.h" #include "WorldSession.h" /*###### @@ -106,7 +107,7 @@ public: !player->HasItemCount(ITEM_SILVER_TOTEM, 1, true)) { ItemPosCountVec dest; - uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 11522, 1, NULL); + uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 11522, 1, nullptr); if (msg == EQUIP_ERR_OK) player->StoreNewItem(dest, ITEM_SILVER_TOTEM, true); } diff --git a/src/server/scripts/Kalimdor/zone_the_barrens.cpp b/src/server/scripts/Kalimdor/zone_the_barrens.cpp index ab63bdbc19e..1705f3e8dea 100644 --- a/src/server/scripts/Kalimdor/zone_the_barrens.cpp +++ b/src/server/scripts/Kalimdor/zone_the_barrens.cpp @@ -33,11 +33,13 @@ npc_wizzlecrank_shredder EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /*###### ## npc_beaten_corpse @@ -228,7 +230,7 @@ public: me->HandleEmoteCommand(EMOTE_ONESHOT_SALUTE); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_FLARE || spell->Id == SPELL_FOLLY) { @@ -370,7 +372,7 @@ public: { if (EventInProgress) { - Player* warrior = NULL; + Player* warrior = nullptr; if (PlayerGUID) warrior = ObjectAccessor::GetPlayer(*me, PlayerGUID); diff --git a/src/server/scripts/Kalimdor/zone_thousand_needles.cpp b/src/server/scripts/Kalimdor/zone_thousand_needles.cpp index d8d48f566bc..a1439f4cc00 100644 --- a/src/server/scripts/Kalimdor/zone_thousand_needles.cpp +++ b/src/server/scripts/Kalimdor/zone_thousand_needles.cpp @@ -32,11 +32,11 @@ go_panther_cage EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" /*##### # npc_kanati diff --git a/src/server/scripts/Kalimdor/zone_ungoro_crater.cpp b/src/server/scripts/Kalimdor/zone_ungoro_crater.cpp index f5b28a5f09a..4a1456a18c0 100644 --- a/src/server/scripts/Kalimdor/zone_ungoro_crater.cpp +++ b/src/server/scripts/Kalimdor/zone_ungoro_crater.cpp @@ -29,10 +29,10 @@ npc_ringo EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedFollowerAI.h" -#include "Player.h" #include "SpellInfo.h" enum AmeData @@ -227,7 +227,7 @@ public: } } - void SpellHit(Unit* /*pCaster*/, const SpellInfo* pSpell) override + void SpellHit(Unit* /*pCaster*/, SpellInfo const* pSpell) override { if (HasFollowState(STATE_FOLLOW_INPROGRESS | STATE_FOLLOW_PAUSED) && pSpell->Id == SPELL_REVIVE_RINGO) ClearFaint(); diff --git a/src/server/scripts/Kalimdor/zone_winterspring.cpp b/src/server/scripts/Kalimdor/zone_winterspring.cpp index 40e2dc6e6fd..9bc3711e830 100644 --- a/src/server/scripts/Kalimdor/zone_winterspring.cpp +++ b/src/server/scripts/Kalimdor/zone_winterspring.cpp @@ -30,11 +30,14 @@ go_elune_fire EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "WorldSession.h" /*###### @@ -168,7 +171,7 @@ public: // The array MUST be terminated by {0, 0, 0} DialogueHelper(DialogueEntry const* dialogueArray) : _dialogueArray(dialogueArray), - _currentEntry(NULL), + _currentEntry(nullptr), _actionTimer(0) { } // The array MUST be terminated by {0, 0, 0, 0, 0} @@ -212,7 +215,7 @@ protected: /// Will be called when a dialogue step was done virtual void JustDidDialogueStep(int32 /*entry*/) { } /// Will be called to get a speaker, MUST be implemented if not used in instances - virtual Creature* GetSpeakerByEntry(int32 /*entry*/) { return NULL; } + virtual Creature* GetSpeakerByEntry(int32 /*entry*/) { return nullptr; } private: void DoNextDialogueStep() @@ -422,7 +425,7 @@ public: (*itr)->Refresh(); } - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) me->SetFacingToObject(altar); break; } @@ -436,7 +439,7 @@ public: case 44: // Stop the escort and turn towards the altar SetEscortPaused(true); - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) me->SetFacingToObject(altar); break; } @@ -466,7 +469,7 @@ public: break; case SAY_PRIESTESS_ALTAR_9: // move near the escort npc - if (Creature* priestess = me->GetMap()->GetCreature(_firstPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _firstPriestessGUID)) priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[6].m_positionX, wingThicketLocations[6].m_positionY, wingThicketLocations[6].m_positionZ); break; case SAY_PRIESTESS_ALTAR_13: @@ -477,7 +480,7 @@ public: _guardEluneGUID = guard->GetGUID(); } // summon the Voice of Elune - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) { if (Creature* voice = me->SummonCreature(NPC_VOICE_ELUNE, altar->GetPositionX(), altar->GetPositionY(), altar->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) _voiceEluneGUID = voice->GetGUID(); @@ -485,7 +488,7 @@ public: break; case SAY_VOICE_ALTAR_15: // move near the escort npc and continue dialogue - if (Creature* priestess = me->GetMap()->GetCreature(_secondPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _secondPriestessGUID)) { priestess->AI()->Talk(SAY_PRIESTESS_ALTAR_14); priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[7].m_positionX, wingThicketLocations[7].m_positionY, wingThicketLocations[7].m_positionZ); @@ -493,7 +496,7 @@ public: break; case SAY_PRIESTESS_ALTAR_19: // make the voice of elune leave - if (Creature* guard = me->GetMap()->GetCreature(_guardEluneGUID)) + if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardEluneGUID)) { guard->GetMotionMaster()->MovePoint(0, wingThicketLocations[2].m_positionX, wingThicketLocations[2].m_positionY, wingThicketLocations[2].m_positionZ); guard->DespawnOrUnsummon(4000); @@ -501,7 +504,7 @@ public: break; case SAY_PRIESTESS_ALTAR_20: // make the first priestess leave - if (Creature* priestess = me->GetMap()->GetCreature(_firstPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _firstPriestessGUID)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[0].m_positionX, wingThicketLocations[0].m_positionY, wingThicketLocations[0].m_positionZ); priestess->DespawnOrUnsummon(4000); @@ -509,7 +512,7 @@ public: break; case SAY_PRIESTESS_ALTAR_21: // make the second priestess leave - if (Creature* priestess = me->GetMap()->GetCreature(_secondPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _secondPriestessGUID)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[1].m_positionX, wingThicketLocations[1].m_positionY, wingThicketLocations[1].m_positionZ); priestess->DespawnOrUnsummon(4000); @@ -525,7 +528,7 @@ public: break; case SAY_RANSHALLA_END_2: // Turn towards the altar and kneel - quest complete - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) { me->SetFacingToObject(altar); altar->ResetDoorOrButton(); @@ -548,13 +551,13 @@ public: case NPC_RANSHALLA: return me; case NPC_VOICE_ELUNE: - return me->GetMap()->GetCreature(_voiceEluneGUID); + return ObjectAccessor::GetCreature(*me, _voiceEluneGUID); case NPC_PRIESTESS_DATA_1: - return me->GetMap()->GetCreature(_firstPriestessGUID); + return ObjectAccessor::GetCreature(*me, _firstPriestessGUID); case NPC_PRIESTESS_DATA_2: - return me->GetMap()->GetCreature(_secondPriestessGUID); + return ObjectAccessor::GetCreature(*me, _secondPriestessGUID); default: - return NULL; + return nullptr; } } diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h index c1bf139c070..00bd46ce2d5 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h @@ -18,6 +18,8 @@ #ifndef AHNKAHET_H_ #define AHNKAHET_H_ +#include "CreatureAIImpl.h" + #define AhnKahetScriptName "instance_ahnkahet" #define DataHeader "AK" @@ -80,8 +82,8 @@ enum AKGameObjectIds GO_SPHERE_2 = 193094 }; -template -AI* GetAhnKahetAI(T* obj) +template +inline AI* GetAhnKahetAI(T* obj) { return GetInstanceAI(obj, AhnKahetScriptName); } diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp index f98a0b53030..f4881aaa9ed 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ahnkahet.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -88,22 +90,18 @@ class boss_amanitar : public CreatureScript for (uint8 i = 0; i < 30; ++i) { Position pos = me->GetRandomNearPosition(30.0f); - pos.m_positionZ = me->GetMap()->GetHeight(pos.GetPositionX(), pos.GetPositionY(), MAX_HEIGHT) + 2.0f; + me->UpdateGroundPositionZ(pos.GetPositionX(), pos.GetPositionY(), pos.m_positionZ); if (Creature* trigger = me->SummonCreature(NPC_TRIGGER, pos)) { Creature* temp1 = trigger->FindNearestCreature(NPC_HEALTHY_MUSHROOM, 4.0f, true); Creature* temp2 = trigger->FindNearestCreature(NPC_POISONOUS_MUSHROOM, 4.0f, true); - if (temp1 || temp2) - { - trigger->DisappearAndDie(); - } - else + if (!temp1 && !temp2) { u = 1 - u; - trigger->DisappearAndDie(); me->SummonCreature(u > 0 ? NPC_POISONOUS_MUSHROOM : NPC_HEALTHY_MUSHROOM, pos, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 60 * IN_MILLISECONDS); } + trigger->DespawnOrUnsummon(); } } } @@ -227,7 +225,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_amanitar_mushroomsAI(creature); + return GetAhnKahetAI(creature); } }; diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp index 242dd354a00..6eb1462da41 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp @@ -224,7 +224,7 @@ class npc_ahnkahar_nerubian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ahnkahar_nerubianAI(creature); + return GetAhnKahetAI(creature); } }; @@ -238,18 +238,9 @@ class spell_ahn_kahet_swarm : public SpellScriptLoader { PrepareSpellScript(spell_ahn_kahet_swarm_SpellScript); - public: - spell_ahn_kahet_swarm_SpellScript() - { - _targetCount = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SWARM_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SWARM_BUFF }); } void CountTargets(std::list& targets) @@ -279,7 +270,7 @@ class spell_ahn_kahet_swarm : public SpellScriptLoader OnEffectHit += SpellEffectFn(spell_ahn_kahet_swarm_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } - uint32 _targetCount; + uint32 _targetCount = 0; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp index 0d0389c79d7..f552fdfa080 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp @@ -20,10 +20,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ahnkahet.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "TemporarySummon.h" enum Spells { @@ -105,7 +109,7 @@ public: } } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_INSANITY) { @@ -124,7 +128,7 @@ public: // phase mask target->CastSpell(target, SPELL_INSANITY_TARGET+insanityHandled, true); // summon twisted party members for this target - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) { Player* player = i->GetSource(); @@ -145,7 +149,7 @@ public: void ResetPlayersPhaseMask() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) { Player* player = i->GetSource(); @@ -230,7 +234,7 @@ public: // Roll Insanity uint32 spell = GetSpellForPhaseMask(phase); uint32 spell2 = GetSpellForPhaseMask(nextPhase); - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -306,7 +310,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp index 8ee342db3a4..30ba1180663 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp @@ -21,9 +21,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ahnkahet.h" - +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Yells { @@ -326,7 +328,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; @@ -429,7 +431,7 @@ public: { case 1: { - Creature* boss = me->GetMap()->GetCreature(instance->GetGuidData(DATA_JEDOGA_SHADOWSEEKER)); + Creature* boss = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JEDOGA_SHADOWSEEKER)); if (boss) { ENSURE_AI(boss_jedoga_shadowseeker::boss_jedoga_shadowseekerAI, boss->AI())->bOpFerok = true; @@ -495,7 +497,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; @@ -578,7 +580,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp index 4124ff1a0a7..fcb37f56a87 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp @@ -16,11 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "ahnkahet.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "SpellScript.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "ahnkahet.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellScript.h" enum Spells { @@ -254,7 +260,7 @@ class boss_prince_taldaram : public CreatureScript if (_embraceTargetGUID) return ObjectAccessor::GetUnit(*me, _embraceTargetGUID); - return NULL; + return nullptr; } void RemovePrison() @@ -371,7 +377,7 @@ class npc_prince_taldaram_flame_sphere : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_prince_taldaram_flame_sphereAI(creature); + return GetAhnKahetAI(creature); } }; @@ -431,11 +437,7 @@ class spell_prince_taldaram_conjure_flame_sphere : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLAME_SPHERE_SUMMON_1) - || !sSpellMgr->GetSpellInfo(SPELL_FLAME_SPHERE_SUMMON_2) - || !sSpellMgr->GetSpellInfo(SPELL_FLAME_SPHERE_SUMMON_3)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLAME_SPHERE_SUMMON_1, SPELL_FLAME_SPHERE_SUMMON_2, SPELL_FLAME_SPHERE_SUMMON_3 }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp index be7b4cf4894..c629a5e66e7 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "ahnkahet.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h index bbd55c7944d..7e42df81f21 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h @@ -18,6 +18,9 @@ #ifndef AZJOL_NERUB_H_ #define AZJOL_NERUB_H_ +#include "CreatureAIImpl.h" + +#define AzjolNerubScriptName "instance_azjol_nerub" #define DataHeader "AN" uint32 const EncounterCount = 3; @@ -62,4 +65,10 @@ enum ANGameObjectIds GO_ANUBARAK_DOOR_3 = 192398 }; +template +inline AI* GetAzjolNerubAI(T* obj) +{ + return GetInstanceAI(obj, AzjolNerubScriptName); +} + #endif // AZJOL_NERUB_H_ diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp index 919f008c108..ebedf88f45a 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp @@ -16,10 +16,17 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "azjol_nerub.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "PassiveAI.h" -#include "azjol_nerub.h" +#include "TemporarySummon.h" enum Spells { @@ -405,7 +412,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -463,7 +470,7 @@ class npc_anubarak_anub_ar_darter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -530,7 +537,7 @@ class npc_anubarak_anub_ar_assassin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -565,7 +572,7 @@ class npc_anubarak_anub_ar_guardian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -600,7 +607,7 @@ class npc_anubarak_anub_ar_venomancer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -628,7 +635,7 @@ class npc_anubarak_impale_target : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -643,7 +650,7 @@ class spell_anubarak_pound : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_POUND_DAMAGE) != nullptr; + return ValidateSpellInfo({ SPELL_POUND_DAMAGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -676,7 +683,7 @@ class spell_anubarak_carrion_beetles : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return (sSpellMgr->GetSpellInfo(SPELL_CARRION_BEETLE) != nullptr); + return ValidateSpellInfo({ SPELL_CARRION_BEETLE }); } void HandlePeriodic(AuraEffect const* /*eff*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp index fc50bb3f0aa..faaa22cf9ac 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" +#include "azjol_nerub.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuras.h" #include "SpellAuraEffects.h" -#include "azjol_nerub.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Events { @@ -391,7 +395,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -569,7 +573,7 @@ class npc_anub_ar_crusher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -612,7 +616,7 @@ class npc_anub_ar_crusher_champion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -655,7 +659,7 @@ class npc_anub_ar_crusher_crypt_fiend : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -698,7 +702,7 @@ class npc_anub_ar_crusher_necromancer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -857,7 +861,7 @@ class npc_anub_ar_champion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -899,7 +903,7 @@ class npc_anub_ar_crypt_fiend : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -941,7 +945,7 @@ class npc_anub_ar_necromancer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -951,11 +955,10 @@ class spell_hadronox_periodic_summon_template_AuraScript : public AuraScript spell_hadronox_periodic_summon_template_AuraScript(uint32 topSpellId, uint32 bottomSpellId) : AuraScript(), _topSpellId(topSpellId), _bottomSpellId(bottomSpellId) { } PrepareAuraScript(spell_hadronox_periodic_summon_template_AuraScript); + private: bool Validate(SpellInfo const* /*spell*/) override { - return - (sSpellMgr->GetSpellInfo(_topSpellId) != nullptr) && - (sSpellMgr->GetSpellInfo(_bottomSpellId) != nullptr); + return ValidateSpellInfo({ _topSpellId, _bottomSpellId }); } void HandleApply(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) @@ -989,7 +992,6 @@ class spell_hadronox_periodic_summon_template_AuraScript : public AuraScript OnEffectPeriodic += AuraEffectPeriodicFn(spell_hadronox_periodic_summon_template_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } - private: uint32 _topSpellId; uint32 _bottomSpellId; }; @@ -1056,7 +1058,7 @@ class spell_hadronox_leeching_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_LEECH_POISON_HEAL) != nullptr; + return ValidateSpellInfo({ SPELL_LEECH_POISON_HEAL }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1094,11 +1096,7 @@ class spell_hadronox_web_doors : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return ( - sSpellMgr->GetSpellInfo(SPELL_SUMMON_CHAMPION_PERIODIC) && - sSpellMgr->GetSpellInfo(SPELL_SUMMON_CRYPT_FIEND_PERIODIC) && - sSpellMgr->GetSpellInfo(SPELL_SUMMON_NECROMANCER_PERIODIC) - ); + return ValidateSpellInfo({ SPELL_SUMMON_CHAMPION_PERIODIC, SPELL_SUMMON_CRYPT_FIEND_PERIODIC, SPELL_SUMMON_NECROMANCER_PERIODIC }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp index 27b4e7702b1..506ddd8cad2 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp @@ -19,13 +19,15 @@ * Comment: Find in the future best timers and the event is not implemented. */ -#include "Containers.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "azjol_nerub.h" +#include "Containers.h" +#include "InstanceScript.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" #include "SpellAuras.h" -#include "azjol_nerub.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Events { @@ -319,7 +321,7 @@ class boss_krik_thir : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -482,7 +484,7 @@ class npc_watcher_gashra : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -560,7 +562,7 @@ class npc_watcher_narjil : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -638,7 +640,7 @@ class npc_watcher_silthik : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -698,7 +700,7 @@ class npc_anub_ar_warrior : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -766,7 +768,7 @@ class npc_anub_ar_skirmisher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -827,7 +829,7 @@ class npc_anub_ar_shadowcaster : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -854,7 +856,7 @@ class npc_skittering_swarmer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -887,7 +889,7 @@ class npc_skittering_infector : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -910,7 +912,7 @@ class npc_gatewatcher_web_wrap : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -977,7 +979,7 @@ class spell_anub_ar_skirmisher_fixtate : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_FIXTATE_TRIGGERED) != nullptr; + return ValidateSpellInfo({ SPELL_FIXTATE_TRIGGERED }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1009,7 +1011,7 @@ class spell_gatewatcher_web_wrap : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_WEB_WRAP_WRAPPED) != nullptr; + return ValidateSpellInfo({ SPELL_WEB_WRAP_WRAPPED }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp index b45940e2e79..eb6692f0251 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp @@ -16,47 +16,51 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" #include "azjol_nerub.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { - { GO_KRIKTHIR_DOOR, DATA_KRIKTHIR, DOOR_TYPE_PASSAGE }, - { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK, DOOR_TYPE_ROOM }, - { GO_ANUBARAK_DOOR_2, DATA_ANUBARAK, DOOR_TYPE_ROOM }, - { GO_ANUBARAK_DOOR_3, DATA_ANUBARAK, DOOR_TYPE_ROOM }, - { 0, 0, DOOR_TYPE_ROOM } // END + { GO_KRIKTHIR_DOOR, DATA_KRIKTHIR, DOOR_TYPE_PASSAGE }, + { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK, DOOR_TYPE_ROOM }, + { GO_ANUBARAK_DOOR_2, DATA_ANUBARAK, DOOR_TYPE_ROOM }, + { GO_ANUBARAK_DOOR_3, DATA_ANUBARAK, DOOR_TYPE_ROOM }, + { 0, 0, DOOR_TYPE_ROOM } // END }; ObjectData const creatureData[] = { - { NPC_KRIKTHIR, DATA_KRIKTHIR }, - { NPC_HADRONOX, DATA_HADRONOX }, - { NPC_ANUBARAK, DATA_ANUBARAK }, - { NPC_WATCHER_NARJIL, DATA_WATCHER_GASHRA }, - { NPC_WATCHER_GASHRA, DATA_WATCHER_SILTHIK }, - { NPC_WATCHER_SILTHIK, DATA_WATCHER_NARJIL }, - { 0, 0 } // END + { NPC_KRIKTHIR, DATA_KRIKTHIR }, + { NPC_HADRONOX, DATA_HADRONOX }, + { NPC_ANUBARAK, DATA_ANUBARAK }, + { NPC_WATCHER_NARJIL, DATA_WATCHER_GASHRA }, + { NPC_WATCHER_GASHRA, DATA_WATCHER_SILTHIK }, + { NPC_WATCHER_SILTHIK, DATA_WATCHER_NARJIL }, + { 0, 0 } // END }; ObjectData const gameobjectData[] = { - { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK_WALL }, + { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK_WALL }, { GO_ANUBARAK_DOOR_3, DATA_ANUBARAK_WALL_2 }, - { 0, 0 } // END + { 0, 0 } // END }; BossBoundaryData const boundaries = { - { DATA_KRIKTHIR, new RectangleBoundary(400.0f, 580.0f, 623.5f, 810.0f) }, - { DATA_HADRONOX, new ZRangeBoundary(666.0f, 776.0f) }, + { DATA_KRIKTHIR, new RectangleBoundary(400.0f, 580.0f, 623.5f, 810.0f) }, + { DATA_HADRONOX, new ZRangeBoundary(666.0f, 776.0f) }, { DATA_ANUBARAK, new CircleBoundary(Position(550.6178f, 253.5917f), 26.0f) } }; class instance_azjol_nerub : public InstanceMapScript { public: - instance_azjol_nerub() : InstanceMapScript("instance_azjol_nerub", 601) { } + instance_azjol_nerub() : InstanceMapScript(AzjolNerubScriptName, 601) { } struct instance_azjol_nerub_InstanceScript : public InstanceScript { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp index 71487b5e048..11c48439da4 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "obsidian_sanctum.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Enums { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp index 4bdbee94db1..6cb362c6a7b 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "obsidian_sanctum.h" /* Obsidian Sanctum encounters: diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp index 45ca29fe6d1..22eb9cdb04a 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "obsidian_sanctum.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Enums { @@ -322,7 +324,7 @@ struct dummy_dragonAI : public ScriptedAI void JustDied(Unit* /*killer*/) override { if (!_canLoot) - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); uint32 spellId = 0; @@ -736,7 +738,7 @@ class npc_acolyte_of_vesperon : public CreatureScript vesperon->RemoveAurasDueToSpell(SPELL_TWILIGHT_TORMENT_VESP); } - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (PlayerList.isEmpty()) return; @@ -904,7 +906,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_flame_tsunamiAI(creature); + return GetObsidianSanctumAI(creature); } }; @@ -958,7 +960,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_twilight_fissureAI(creature); + return GetObsidianSanctumAI(creature); } }; @@ -1013,7 +1015,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_twilight_whelpAI(creature); + return GetObsidianSanctumAI(creature); } }; diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h index 92331e8c8bf..00547e204c6 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h @@ -18,6 +18,8 @@ #ifndef OBSIDIAN_SANCTUM_H_ #define OBSIDIAN_SANCTUM_H_ +#include "CreatureAIImpl.h" + #define OSScriptName "instance_obsidian_sanctum" #define DataHeader "OS" @@ -46,10 +48,10 @@ enum OSGameObjectIds GO_TWILIGHT_PORTAL = 193988 }; -template -AI* GetObsidianSanctumAI(Creature* creature) +template +inline AI* GetObsidianSanctumAI(T* obj) { - return GetInstanceAI(creature, OSScriptName); + return GetInstanceAI(obj, OSScriptName); } #endif // OBSIDIAN_SANCTUM_H_ diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp index 9bc4de0ae92..16955384cb8 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp @@ -15,11 +15,12 @@ * with this program. If not, see . */ -#include "ScriptedCreature.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" #include "ruby_sanctum.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Texts { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp index 6a3a185061b..d835549ad17 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ruby_sanctum.h" +#include "ScriptedCreature.h" enum Texts { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp index a85b07f95c3..1256e5745b3 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp @@ -16,15 +16,20 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Spell.h" -#include "Vehicle.h" -#include "MapManager.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "ScriptedCreature.h" -#include "ruby_sanctum.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ruby_sanctum.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Texts { @@ -759,7 +764,7 @@ class npc_halion_controller : public CreatureScript void DoCheckEvade() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->GetSource()) if (player->IsAlive() && CheckBoundary(player) && !player->IsGameMaster()) @@ -1438,11 +1443,10 @@ class spell_halion_combustion_consumption : public SpellScriptLoader public: spell_halion_combustion_consumption_AuraScript(uint32 spellID) : AuraScript(), _markSpell(spellID) { } - bool Validate(SpellInfo const* /*spell*/) override + private: + bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_markSpell)) - return false; - return true; + return ValidateSpellInfo({ _markSpell }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1494,9 +1498,7 @@ class spell_halion_combustion_consumption_periodic : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandleTick(AuraEffect const* aurEff) @@ -1538,11 +1540,10 @@ class spell_halion_marks : public SpellScriptLoader spell_halion_marks_AuraScript(uint32 summonSpell, uint32 removeSpell) : AuraScript(), _summonSpellId(summonSpell), _removeSpellId(removeSpell) { } + private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_summonSpellId)) - return false; - return true; + return ValidateSpellInfo({ _summonSpellId, _removeSpellId }); } /// We were purged. Force removed stacks to zero and trigger the appropriated remove handler. @@ -1623,7 +1624,7 @@ class spell_halion_damage_aoe_summon : public SpellScriptLoader class spell_halion_twilight_realm_handlers : public SpellScriptLoader { public: - spell_halion_twilight_realm_handlers(const char* scriptName, uint32 beforeHitSpell, bool isApplyHandler) : SpellScriptLoader(scriptName), + spell_halion_twilight_realm_handlers(char const* scriptName, uint32 beforeHitSpell, bool isApplyHandler) : SpellScriptLoader(scriptName), _beforeHitSpell(beforeHitSpell), _isApplyHandler(isApplyHandler) { } @@ -1636,11 +1637,10 @@ class spell_halion_twilight_realm_handlers : public SpellScriptLoader _isApply(isApplyHandler), _beforeHitSpellId(beforeHitSpell) { } + private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_beforeHitSpellId)) - return false; - return true; + return ValidateSpellInfo({ _beforeHitSpellId }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*handle*/) @@ -1697,11 +1697,7 @@ class spell_halion_clear_debuffs : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CLEAR_DEBUFFS)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_TWILIGHT_REALM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CLEAR_DEBUFFS, SPELL_TWILIGHT_REALM }); } void HandleScript(SpellEffIndex effIndex) @@ -1785,9 +1781,7 @@ class spell_halion_twilight_phasing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_TWILIGHT_PORTAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_TWILIGHT_PORTAL }); } void Phase() diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp index 96d64012489..e1f01fdfea4 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ruby_sanctum.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "ruby_sanctum.h" enum Texts { @@ -229,10 +231,7 @@ class spell_saviana_conflagration_init : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLAME_BEACON) - || !sSpellMgr->GetSpellInfo(SPELL_CONFLAGRATION_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLAME_BEACON, SPELL_CONFLAGRATION_2 }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp index c9d68808c12..db2fc0b407b 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp @@ -15,13 +15,17 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ruby_sanctum.h" #include "TemporarySummon.h" #include "WorldPacket.h" -#include "ruby_sanctum.h" + +Position const HalionControllerSpawnPos = { 3156.037f, 533.2656f, 72.97205f, 0.0f }; BossBoundaryData const boundaries = { @@ -68,7 +72,6 @@ ObjectData const gameObjectData[] = { 0, 0 } //END }; - class instance_ruby_sanctum : public InstanceMapScript { public: diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp index d298c35dd0a..e43b93e484d 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp @@ -16,11 +16,13 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ruby_sanctum.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellScript.h" -#include "ruby_sanctum.h" -#include "Player.h" enum Texts { @@ -183,9 +185,7 @@ class spell_ruby_sanctum_rallying_shout : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RALLY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RALLY }); } void CountTargets(std::list& targets) @@ -205,7 +205,6 @@ class spell_ruby_sanctum_rallying_shout : public SpellScriptLoader OnEffectHit += SpellEffectFn(spell_ruby_sanctum_rallying_shout_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } - private: uint32 _targetCount = 0; }; diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h index 6411037ad70..c8286cefda4 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h @@ -18,13 +18,13 @@ #ifndef RUBY_SANCTUM_H_ #define RUBY_SANCTUM_H_ +#include "CreatureAIImpl.h" + #define RSScriptName "instance_ruby_sanctum" #define DataHeader "RS" uint32 const EncounterCount = 4; -Position const HalionControllerSpawnPos = {3156.037f, 533.2656f, 72.97205f, 0.0f}; - enum RSDataTypes { // Encounter States/Boss GUIDs @@ -129,25 +129,10 @@ enum RSInstanceSpell SPELL_BERSERK = 26662 }; -template -CreatureAI* GetRubySanctumAI(Creature* creature) -{ - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(RSScriptName)) - return new AI(creature); - return nullptr; -} - -template -GameObjectAI* GetRubySanctumAI(GameObject* go) +template +inline AI* GetRubySanctumAI(T* obj) { - if (InstanceMap* instance = go->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(RSScriptName)) - return new AI(go); - - return nullptr; + return GetInstanceAI(obj, RSScriptName); } #endif // RUBY_SANCTUM_H_ diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp index 0b6c7738cc9..1061dc37aff 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp @@ -23,10 +23,13 @@ SDCategory: Trial of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedEscortAI.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "trial_of_the_champion.h" -#include "ScriptedEscortAI.h" /* enum Yells { @@ -253,7 +256,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -415,7 +418,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -492,7 +495,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_memoryAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -605,7 +608,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -650,10 +653,7 @@ class spell_paletress_summon_memory : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint8 i = 0; i < 25; ++i) - if (!sSpellMgr->GetSpellInfo(memorySpellId[i])) - return false; - return true; + return ValidateSpellInfo(memorySpellId); } void FilterTargets(std::list& targets) @@ -668,7 +668,7 @@ class spell_paletress_summon_memory : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { - GetHitUnit()->CastSpell(GetHitUnit(), memorySpellId[urand(0, 24)], true, NULL, NULL, GetCaster()->GetGUID()); + GetHitUnit()->CastSpell(GetHitUnit(), memorySpellId[urand(0, 24)], true, nullptr, nullptr, GetCaster()->GetGUID()); } void Register() override diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp index e5b749c5da0..be1c5b69bd8 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp @@ -23,7 +23,7 @@ SDCategory: Trial of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "ScriptedEscortAI.h" #include "trial_of_the_champion.h" @@ -296,7 +296,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -345,7 +345,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_risen_ghoulAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -374,7 +374,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_black_knight_skeletal_gryphonAI(creature); + return GetTrialOfTheChampionAI(creature); } }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp index 1bc8a45cbe2..5181b125fdf 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp @@ -24,11 +24,13 @@ SDCategory: Trial Of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" -#include "Vehicle.h" #include "trial_of_the_champion.h" -#include "Player.h" +#include "Vehicle.h" enum Spells { @@ -95,7 +97,7 @@ const Point MovementPoint[] = */ void AggroAllPlayers(Creature* temp) { - Map::PlayerList const &PlList = temp->GetMap()->GetPlayers(); + Map::PlayerList const& PlList = temp->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; @@ -303,7 +305,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -440,7 +442,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -583,7 +585,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -734,7 +736,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -894,7 +896,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -1019,7 +1021,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp index d05c2c303a4..5596c77bb71 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/instance_trial_of_the_champion.cpp @@ -22,17 +22,22 @@ SDCategory: Trial Of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "trial_of_the_champion.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" +#include "trial_of_the_champion.h" #define MAX_ENCOUNTER 4 class instance_trial_of_the_champion : public InstanceMapScript { public: - instance_trial_of_the_champion() : InstanceMapScript("instance_trial_of_the_champion", 650) { } + instance_trial_of_the_champion() : InstanceMapScript(ToCScriptName, 650) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -89,7 +94,7 @@ public: void OnCreatureCreate(Creature* creature) override { - Map::PlayerList const &players = instance->GetPlayers(); + Map::PlayerList const& players = instance->GetPlayers(); uint32 TeamInInstance = 0; if (!players.isEmpty()) @@ -180,7 +185,7 @@ public: { pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f); pAnnouncer->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_CHAMPIONS_LOOT_H : GO_CHAMPIONS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, G3D::Quat(), 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_CHAMPIONS_LOOT_H : GO_CHAMPIONS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, QuaternionData(), 90000); } } } @@ -203,7 +208,7 @@ public: { pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f); pAnnouncer->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_EADRIC_LOOT_H : GO_EADRIC_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, G3D::Quat(), 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_EADRIC_LOOT_H : GO_EADRIC_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, QuaternionData(), 90000); } break; case BOSS_ARGENT_CHALLENGE_P: @@ -212,7 +217,7 @@ public: { pAnnouncer->GetMotionMaster()->MovePoint(0, 748.309f, 619.487f, 411.171f); pAnnouncer->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); - pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_PALETRESS_LOOT_H : GO_PALETRESS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, G3D::Quat(), 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic()? GO_PALETRESS_LOOT_H : GO_PALETRESS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, QuaternionData(), 90000); } break; } @@ -287,7 +292,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp index f31010c9676..4dc43888726 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp @@ -27,11 +27,17 @@ npc_announcer_toc5 EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "trial_of_the_champion.h" #include "Vehicle.h" -#include "Player.h" enum Yells { @@ -362,8 +368,7 @@ public: void AggroAllPlayers(Creature* temp) { - Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); - + Map::PlayerList const& PlList = me->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; @@ -482,7 +487,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h index d4be2f90f6e..e4e67a6565d 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h @@ -19,6 +19,9 @@ #ifndef DEF_TOC_H #define DEF_TOC_H +#include "CreatureAIImpl.h" + +#define ToCScriptName "instance_trial_of_the_champion" #define DataHeader "TC" enum TCData @@ -127,4 +130,10 @@ enum TCVehicles VEHICLE_BLACK_KNIGHT = 35491 }; +template +inline AI* GetTrialOfTheChampionAI(T* obj) +{ + return GetInstanceAI(obj, ToCScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp index 96fe86446f2..60479c6be30 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp @@ -22,11 +22,15 @@ // Scarab - Kill credit isn't crediting? #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "trial_of_the_crusader.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "trial_of_the_crusader.h" enum Yells { @@ -428,7 +432,7 @@ class boss_anubarak_trial : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -506,7 +510,7 @@ class npc_swarm_scarab : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -600,7 +604,7 @@ class npc_nerubian_burrower : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -626,7 +630,8 @@ class npc_frost_sphere : public CreatureScript if (me->GetHealth() <= damage) { damage = 0; - float floorZ = me->GetMap()->GetHeight(me->GetPhaseMask(), me->GetPositionX(), me->GetPositionY(), me->GetPositionZ()); + float floorZ = me->GetPositionZ(); + me->UpdateGroundPositionZ(me->GetPositionX(), me->GetPositionY(), floorZ); if (fabs(me->GetPositionZ() - floorZ) < 0.1f) { // we are close to the ground @@ -671,7 +676,7 @@ class npc_frost_sphere : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_frost_sphereAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -824,7 +829,7 @@ class npc_anubarak_spike : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_anubarak_spikeAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -870,9 +875,7 @@ class spell_anubarak_leeching_swarm : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LEECHING_SWARM_DMG) || !sSpellMgr->GetSpellInfo(SPELL_LEECHING_SWARM_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LEECHING_SWARM_DMG, SPELL_LEECHING_SWARM_HEAL }); } void HandleEffectPeriodic(AuraEffect const* aurEff) diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp index 9ca1dee21f3..ef37afffc04 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp @@ -17,12 +17,17 @@ */ #include "ScriptMgr.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "trial_of_the_crusader.h" -#include "Player.h" -#include "GridNotifiers.h" enum Yells { @@ -339,6 +344,32 @@ enum Events EVENT_SPELL_LOCK = 2 }; +Position const FactionChampionLoc[] = +{ + { 514.231f, 105.569f, 418.234f, 0 }, // 0 - Horde Initial Pos 0 + { 508.334f, 115.377f, 418.234f, 0 }, // 1 - Horde Initial Pos 1 + { 506.454f, 126.291f, 418.234f, 0 }, // 2 - Horde Initial Pos 2 + { 506.243f, 106.596f, 421.592f, 0 }, // 3 - Horde Initial Pos 3 + { 499.885f, 117.717f, 421.557f, 0 }, // 4 - Horde Initial Pos 4 + + { 613.127f, 100.443f, 419.74f, 0 }, // 5 - Ally Initial Pos 0 + { 621.126f, 128.042f, 418.231f, 0 }, // 6 - Ally Initial Pos 1 + { 618.829f, 113.606f, 418.232f, 0 }, // 7 - Ally Initial Pos 2 + { 625.845f, 112.914f, 421.575f, 0 }, // 8 - Ally Initial Pos 3 + { 615.566f, 109.653f, 418.234f, 0 }, // 9 - Ally Initial Pos 4 + + { 535.469f, 113.012f, 394.66f, 0 }, // 10 - Horde Final Pos 0 + { 526.417f, 137.465f, 394.749f, 0 }, // 11 - Horde Final Pos 1 + { 528.108f, 111.057f, 395.289f, 0 }, // 12 - Horde Final Pos 2 + { 519.92f, 134.285f, 395.289f, 0 }, // 13 - Horde Final Pos 3 + { 533.648f, 119.148f, 394.646f, 0 }, // 14 - Horde Final Pos 4 + { 531.399f, 125.63f, 394.708f, 0 }, // 15 - Horde Final Pos 5 + { 528.958f, 131.47f, 394.73f, 0 }, // 16 - Horde Final Pos 6 + { 526.309f, 116.667f, 394.833f, 0 }, // 17 - Horde Final Pos 7 + { 524.238f, 122.411f, 394.819f, 0 }, // 18 - Horde Final Pos 8 + { 521.901f, 128.488f, 394.832f, 0 } // 19 - Horde Final Pos 9 +}; + class boss_toc_champion_controller : public CreatureScript { public: @@ -545,7 +576,7 @@ class boss_toc_champion_controller : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -631,7 +662,7 @@ struct boss_faction_championsAI : public BossAI { if (who->GetTypeId() == TYPEID_PLAYER) { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); uint32 TeamInInstance = 0; if (!players.isEmpty()) @@ -655,7 +686,7 @@ struct boss_faction_championsAI : public BossAI std::list lst = DoFindFriendlyMissingBuff(40.0f, spell); std::list::const_iterator itr = lst.begin(); if (lst.empty()) - return NULL; + return nullptr; advance(itr, rand32() % lst.size()); return (*itr); } @@ -670,7 +701,7 @@ struct boss_faction_championsAI : public BossAI if (target && target->getPowerType() == POWER_MANA) return target; } - return NULL; + return nullptr; } uint32 EnemiesInRange(float distance) @@ -835,7 +866,7 @@ class npc_toc_druid : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -928,7 +959,7 @@ class npc_toc_shaman : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1032,7 +1063,7 @@ class npc_toc_paladin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1117,7 +1148,7 @@ class npc_toc_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1215,7 +1246,7 @@ class npc_toc_shadow_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1306,7 +1337,7 @@ class npc_toc_warlock : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1400,7 +1431,7 @@ class npc_toc_mage : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1502,7 +1533,7 @@ class npc_toc_hunter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1594,7 +1625,7 @@ class npc_toc_boomkin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1698,7 +1729,7 @@ class npc_toc_warrior : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1794,7 +1825,7 @@ class npc_toc_dk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1899,7 +1930,7 @@ class npc_toc_rogue : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2033,7 +2064,7 @@ class npc_toc_enh_shaman : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2139,7 +2170,7 @@ class npc_toc_retro_paladin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2191,7 +2222,7 @@ class npc_toc_pet_warlock : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2239,7 +2270,7 @@ class npc_toc_pet_hunter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2254,15 +2285,13 @@ class spell_faction_champion_warl_unstable_affliction : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSTABLE_AFFLICTION_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSTABLE_AFFLICTION_DISPEL }); } void HandleDispel(DispelInfo* dispelInfo) { if (Unit* caster = GetCaster()) - caster->CastSpell(dispelInfo->GetDispeller(), SPELL_UNSTABLE_AFFLICTION_DISPEL, true, NULL, GetEffect(EFFECT_0)); + caster->CastSpell(dispelInfo->GetDispeller(), SPELL_UNSTABLE_AFFLICTION_DISPEL, true, nullptr, GetEffect(EFFECT_0)); } void Register() override @@ -2288,9 +2317,7 @@ class spell_faction_champion_death_grip : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_GRIP_PULL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEATH_GRIP_PULL }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2326,9 +2353,7 @@ class spell_toc_bloodlust : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(AURA_SATED)) - return false; - return true; + return ValidateSpellInfo({ AURA_SATED }); } void RemoveInvalidTargets(std::list& targets) @@ -2367,9 +2392,7 @@ class spell_toc_heroism : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(AURA_EXHAUSTION)) - return false; - return true; + return ValidateSpellInfo({ AURA_EXHAUSTION }); } void RemoveInvalidTargets(std::list& targets) diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp index 30a0138a689..7b6a20c1dd7 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "Player.h" #include "trial_of_the_crusader.h" enum Yells @@ -207,7 +210,7 @@ class boss_jaraxxus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -243,7 +246,7 @@ class npc_legion_flame : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -297,7 +300,7 @@ class npc_infernal_volcano : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_infernal_volcanoAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -350,7 +353,7 @@ class npc_fel_infernal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -401,7 +404,7 @@ class npc_nether_portal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_nether_portalAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -479,7 +482,7 @@ class npc_mistress_of_pain : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -591,9 +594,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FEL_STREAK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FEL_STREAK }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp index 258e392edde..81cd4ff8470 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp @@ -17,12 +17,17 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "trial_of_the_crusader.h" #include "Vehicle.h" -#include "Player.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" enum Yells { @@ -290,7 +295,7 @@ class boss_gormok : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -463,7 +468,7 @@ class npc_snobold_vassal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -499,7 +504,7 @@ class npc_firebomb : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -727,7 +732,7 @@ class boss_acidmaw : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -791,7 +796,7 @@ class boss_dreadscale : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -838,7 +843,7 @@ class npc_slime_pool : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -853,7 +858,7 @@ class spell_gormok_fire_bomb : public SpellScriptLoader void TriggerFireBomb(SpellEffIndex /*effIndex*/) { - if (const WorldLocation* pos = GetExplTargetDest()) + if (WorldLocation const* pos = GetExplTargetDest()) { if (Unit* caster = GetCaster()) caster->SummonCreature(NPC_FIRE_BOMB, pos->GetPositionX(), pos->GetPositionY(), pos->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30*IN_MILLISECONDS); @@ -1102,7 +1107,7 @@ class boss_icehowl : public CreatureScript } if (events.ExecuteEvent() == EVENT_TRAMPLE) { - Map::PlayerList const &lPlayers = me->GetMap()->GetPlayers(); + Map::PlayerList const& lPlayers = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) { if (Unit* player = itr->GetSource()) @@ -1155,7 +1160,7 @@ class boss_icehowl : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1170,9 +1175,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE_PLAYER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RIDE_PLAYER }); } bool Load() override @@ -1268,9 +1271,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE_PLAYER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RIDE_PLAYER }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -1302,9 +1303,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARALYSIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARALYSIS }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1340,7 +1339,7 @@ public: slowEff->ChangeAmount(newAmount); if (newAmount <= -100 && !GetTarget()->HasAura(SPELL_PARALYSIS)) - GetTarget()->CastSpell(GetTarget(), SPELL_PARALYSIS, true, NULL, slowEff, GetCasterGUID()); + GetTarget()->CastSpell(GetTarget(), SPELL_PARALYSIS, true, nullptr, slowEff, GetCasterGUID()); } } @@ -1362,7 +1361,7 @@ public: class spell_jormungars_snakes_spray : public SpellScriptLoader { public: - spell_jormungars_snakes_spray(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + spell_jormungars_snakes_spray(char const* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } class spell_jormungars_snakes_spray_SpellScript : public SpellScript { @@ -1371,11 +1370,10 @@ public: public: spell_jormungars_snakes_spray_SpellScript(uint32 spellId) : SpellScript(), _spellId(spellId) { } + private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1389,7 +1387,6 @@ public: OnEffectHitTarget += SpellEffectFn(spell_jormungars_snakes_spray_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); } - private: uint32 _spellId; }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp index 598caddd72f..ba4c19b316d 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp @@ -21,14 +21,16 @@ // - Hardcoded bullets spawner #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" +#include "SpellMgr.h" +#include "SpellScript.h" #include "trial_of_the_crusader.h" enum Texts @@ -451,7 +453,7 @@ class boss_fjola : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -484,7 +486,7 @@ class boss_eydis : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -526,7 +528,7 @@ class npc_essence_of_twin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_essence_of_twinAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -617,7 +619,7 @@ class npc_unleashed_dark : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_unleashed_darkAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -638,9 +640,9 @@ class npc_unleashed_light : public CreatureScript { DoCastAOE(SPELL_UNLEASHED_LIGHT_HELPER); me->GetMotionMaster()->MoveIdle(); - me->DespawnOrUnsummon(1*IN_MILLISECONDS); + me->DespawnOrUnsummon(1 * IN_MILLISECONDS); } - RangeCheckTimer = 0.5*IN_MILLISECONDS; + RangeCheckTimer = IN_MILLISECONDS / 2; } else RangeCheckTimer -= diff; @@ -649,7 +651,7 @@ class npc_unleashed_light : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_unleashed_lightAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -678,7 +680,7 @@ class npc_bullet_controller : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_bullet_controllerAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -691,16 +693,8 @@ class spell_powering_up : public SpellScriptLoader { PrepareSpellScript(spell_powering_up_SpellScript); - public: - spell_powering_up_SpellScript() - { - spellId = 0; - poweringUp = 0; - } - - private: - uint32 spellId; - uint32 poweringUp; + uint32 spellId = 0; + uint32 poweringUp = 0; bool Load() override { diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp index 4bf162838d0..506f076be33 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/instance_trial_of_the_crusader.cpp @@ -17,23 +17,29 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "trial_of_the_crusader.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" #include "TemporarySummon.h" +#include "trial_of_the_crusader.h" -BossBoundaryData const boundaries = { - { BOSS_BEASTS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, - { BOSS_JARAXXUS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, - { BOSS_CRUSADERS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, - { BOSS_VALKIRIES, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, - { BOSS_ANUBARAK, new EllipseBoundary(Position(746.0f, 135.0f), 100.0, 75.0) } +BossBoundaryData const boundaries = +{ + { BOSS_BEASTS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, + { BOSS_JARAXXUS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, + { BOSS_CRUSADERS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, + { BOSS_VALKIRIES, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, + { BOSS_ANUBARAK, new EllipseBoundary(Position(746.0f, 135.0f), 100.0, 75.0) } }; class instance_trial_of_the_crusader : public InstanceMapScript { public: - instance_trial_of_the_crusader() : InstanceMapScript("instance_trial_of_the_crusader", 649) { } + instance_trial_of_the_crusader() : InstanceMapScript(ToCrScriptName, 649) { } struct instance_trial_of_the_crusader_InstanceMapScript : public InstanceScript { @@ -314,7 +320,7 @@ class instance_trial_of_the_crusader : public InstanceMapScript if (tributeChest) if (Creature* tirion = instance->GetCreature(TirionGUID)) - if (GameObject* chest = tirion->SummonGameObject(tributeChest, 805.62f, 134.87f, 142.16f, 3.27f, G3D::Quat(), WEEK)) + if (GameObject* chest = tirion->SummonGameObject(tributeChest, 805.62f, 134.87f, 142.16f, 3.27f, QuaternionData(), WEEK)) chest->SetRespawnTime(chest->GetRespawnDelay()); break; } @@ -346,7 +352,7 @@ class instance_trial_of_the_crusader : public InstanceMapScript { --TrialCounter; // decrease attempt counter at wipe - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) if (Player* player = itr->GetSource()) player->SendUpdateWorldState(UPDATE_STATE_UI_COUNT, TrialCounter); @@ -640,7 +646,7 @@ class instance_trial_of_the_crusader : public InstanceMapScript return SaveDataBuffer; } - void Load(const char* strIn) override + void Load(char const* strIn) override { if (!strIn) { diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp index 084ce0b614d..c966f74cd89 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.cpp @@ -20,10 +20,16 @@ // - Need better implementation of Gossip and correct gossip text and option #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "trial_of_the_crusader.h" -#include "Player.h" enum Yells { @@ -81,6 +87,73 @@ enum Yells SAY_STAGE_4_07 = 1 }; +Position const ToCSpawnLoc[] = +{ + { 563.912f, 261.625f, 394.73f, 4.70437f }, // 0 Center + { 575.451f, 261.496f, 394.73f, 4.6541f }, // 1 Left + { 549.951f, 261.55f, 394.73f, 4.74835f } // 2 Right +}; + +Position const ToCCommonLoc[] = +{ + { 559.257996f, 90.266197f, 395.122986f, 0 }, // 0 Barrent + + { 563.672974f, 139.571f, 393.837006f, 0 }, // 1 Center + { 563.833008f, 187.244995f, 394.5f, 0 }, // 2 Backdoor + { 577.347839f, 195.338888f, 395.14f, 0 }, // 3 - Right + { 550.955933f, 195.338888f, 395.14f, 0 }, // 4 - Left + { 563.833008f, 195.244995f, 394.585561f, 0 }, // 5 - Center + { 573.5f, 180.5f, 395.14f, 0 }, // 6 Move 0 Right + { 553.5f, 180.5f, 395.14f, 0 }, // 7 Move 0 Left + { 573.0f, 170.0f, 395.14f, 0 }, // 8 Move 1 Right + { 555.5f, 170.0f, 395.14f, 0 }, // 9 Move 1 Left + { 563.8f, 216.1f, 395.1f, 0 }, // 10 Behind the door + + { 575.042358f, 195.260727f, 395.137146f, 0 }, // 5 + { 552.248901f, 195.331955f, 395.132658f, 0 }, // 6 + { 573.342285f, 195.515823f, 395.135956f, 0 }, // 7 + { 554.239929f, 195.825577f, 395.137909f, 0 }, // 8 + { 571.042358f, 195.260727f, 395.137146f, 0 }, // 9 + { 556.720581f, 195.015472f, 395.132658f, 0 }, // 10 + { 569.534119f, 195.214478f, 395.139526f, 0 }, // 11 + { 569.231201f, 195.941071f, 395.139526f, 0 }, // 12 + { 558.811610f, 195.985779f, 394.671661f, 0 }, // 13 + { 567.641724f, 195.351501f, 394.659943f, 0 }, // 14 + { 560.633972f, 195.391708f, 395.137543f, 0 }, // 15 + { 565.816956f, 195.477921f, 395.136810f, 0 } // 16 +}; + +Position const TwinValkyrsLoc[] = +{ + { 586.060242f, 117.514809f, 394.41f, 0 }, // 0 - Dark essence 1 + { 541.602112f, 161.879837f, 394.41f, 0 }, // 1 - Dark essence 2 + { 541.021118f, 117.262932f, 394.41f, 0 }, // 2 - Light essence 1 + { 586.200562f, 162.145523f, 394.41f, 0 } // 3 - Light essence 2 +}; + +Position const LichKingLoc[] = +{ + { 563.549f, 152.474f, 394.393f, 0 }, // 0 - Lich king start + { 563.547f, 141.613f, 393.908f, 0 } // 1 - Lich king end +}; + +Position const AnubarakLoc[] = +{ + { 783.9305f, 132.9722f, 142.6711f, 3.141593f }, // 0 - Anub'arak Spawn Location (sniffed) + { 695.240051f, 137.834824f, 142.200000f, 0 }, // 1 - Anub'arak move point location + { 694.886353f, 102.484665f, 142.119614f, 0 }, // 3 - Nerub Spawn + { 694.500671f, 185.363968f, 142.117905f, 0 }, // 5 - Nerub Spawn + { 731.987244f, 83.3824690f, 142.119614f, 0 }, // 2 - Nerub Spawn + { 740.184509f, 193.443390f, 142.117584f, 0 } // 4 - Nerub Spawn +}; + +Position const EndSpawnLoc[] = +{ + { 648.9167f, 131.0208f, 141.6161f, 0.f }, // 0 - Highlord Tirion Fordring + { 649.1614f, 142.0399f, 141.3057f, 0.f }, // 1 - Argent Mage + { 644.6250f, 149.2743f, 140.6015f, 5.f } // 2 - Portal to Dalaran +}; + struct _Messages { AnnouncerMessages msgnum; @@ -206,7 +279,7 @@ class npc_announcer_toc10 : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -335,7 +408,7 @@ class boss_lich_king_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -505,7 +578,7 @@ class npc_fizzlebang_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -751,7 +824,7 @@ class npc_tirion_toc : public CreatureScript case 6000: me->SummonCreature(NPC_TIRION_FORDRING, EndSpawnLoc[0]); me->SummonCreature(NPC_ARGENT_MAGE, EndSpawnLoc[1]); - me->SummonGameObject(GO_PORTAL_TO_DALARAN, EndSpawnLoc[2], G3D::Quat(), 0); + me->SummonGameObject(GO_PORTAL_TO_DALARAN, EndSpawnLoc[2], QuaternionData(), 0); _updateTimer = 20*IN_MILLISECONDS; _instance->SetData(TYPE_EVENT, 6005); break; @@ -792,7 +865,7 @@ class npc_tirion_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -875,7 +948,7 @@ class npc_garrosh_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -958,7 +1031,7 @@ class npc_varian_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h index 5178961d651..d744c7e1cd2 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/trial_of_the_crusader.h @@ -1,12 +1,31 @@ -/* Copyright (C) 2009 - 2010 by /dev/rsa for ScriptDev2 - * This program is free software licensed under GPL version 2 - * Please see the included DOCS/LICENSE.TXT for more information */ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2009-2010 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ #ifndef DEF_CRUSADER_H #define DEF_CRUSADER_H +#include "CreatureAIImpl.h" + +#define ToCrScriptName "instance_trial_of_the_crusader" #define DataHeader "TCR" +struct Position; + enum TCRDataTypes { BOSS_BEASTS = 0, @@ -44,106 +63,8 @@ enum TCRMiscData DESPAWN_TIME = 1200000 }; -const Position ToCSpawnLoc[]= -{ - {563.912f, 261.625f, 394.73f, 4.70437f}, // 0 Center - {575.451f, 261.496f, 394.73f, 4.6541f}, // 1 Left - {549.951f, 261.55f, 394.73f, 4.74835f} // 2 Right -}; - -const Position ToCCommonLoc[]= -{ - {559.257996f, 90.266197f, 395.122986f, 0}, // 0 Barrent - - {563.672974f, 139.571f, 393.837006f, 0}, // 1 Center - {563.833008f, 187.244995f, 394.5f, 0}, // 2 Backdoor - {577.347839f, 195.338888f, 395.14f, 0}, // 3 - Right - {550.955933f, 195.338888f, 395.14f, 0}, // 4 - Left - {563.833008f, 195.244995f, 394.585561f, 0}, // 5 - Center - {573.5f, 180.5f, 395.14f, 0}, // 6 Move 0 Right - {553.5f, 180.5f, 395.14f, 0}, // 7 Move 0 Left - {573.0f, 170.0f, 395.14f, 0}, // 8 Move 1 Right - {555.5f, 170.0f, 395.14f, 0}, // 9 Move 1 Left - {563.8f, 216.1f, 395.1f, 0}, // 10 Behind the door - - {575.042358f, 195.260727f, 395.137146f, 0}, // 5 - {552.248901f, 195.331955f, 395.132658f, 0}, // 6 - {573.342285f, 195.515823f, 395.135956f, 0}, // 7 - {554.239929f, 195.825577f, 395.137909f, 0}, // 8 - {571.042358f, 195.260727f, 395.137146f, 0}, // 9 - {556.720581f, 195.015472f, 395.132658f, 0}, // 10 - {569.534119f, 195.214478f, 395.139526f, 0}, // 11 - {569.231201f, 195.941071f, 395.139526f, 0}, // 12 - {558.811610f, 195.985779f, 394.671661f, 0}, // 13 - {567.641724f, 195.351501f, 394.659943f, 0}, // 14 - {560.633972f, 195.391708f, 395.137543f, 0}, // 15 - {565.816956f, 195.477921f, 395.136810f, 0} // 16 -}; - -const Position JaraxxusLoc[]= -{ - {508.104767f, 138.247345f, 395.128052f, 0}, // 0 - Fizzlebang start location - {548.610596f, 139.807800f, 394.321838f, 0}, // 1 - fizzlebang end - {581.854187f, 138.0f, 394.319f, 0}, // 2 - Portal Right - {550.558838f, 138.0f, 394.319f, 0} // 3 - Portal Left -}; - -const Position FactionChampionLoc[]= -{ - {514.231f, 105.569f, 418.234f, 0}, // 0 - Horde Initial Pos 0 - {508.334f, 115.377f, 418.234f, 0}, // 1 - Horde Initial Pos 1 - {506.454f, 126.291f, 418.234f, 0}, // 2 - Horde Initial Pos 2 - {506.243f, 106.596f, 421.592f, 0}, // 3 - Horde Initial Pos 3 - {499.885f, 117.717f, 421.557f, 0}, // 4 - Horde Initial Pos 4 - - {613.127f, 100.443f, 419.74f, 0}, // 5 - Ally Initial Pos 0 - {621.126f, 128.042f, 418.231f, 0}, // 6 - Ally Initial Pos 1 - {618.829f, 113.606f, 418.232f, 0}, // 7 - Ally Initial Pos 2 - {625.845f, 112.914f, 421.575f, 0}, // 8 - Ally Initial Pos 3 - {615.566f, 109.653f, 418.234f, 0}, // 9 - Ally Initial Pos 4 - - {535.469f, 113.012f, 394.66f, 0}, // 10 - Horde Final Pos 0 - {526.417f, 137.465f, 394.749f, 0}, // 11 - Horde Final Pos 1 - {528.108f, 111.057f, 395.289f, 0}, // 12 - Horde Final Pos 2 - {519.92f, 134.285f, 395.289f, 0}, // 13 - Horde Final Pos 3 - {533.648f, 119.148f, 394.646f, 0}, // 14 - Horde Final Pos 4 - {531.399f, 125.63f, 394.708f, 0}, // 15 - Horde Final Pos 5 - {528.958f, 131.47f, 394.73f, 0}, // 16 - Horde Final Pos 6 - {526.309f, 116.667f, 394.833f, 0}, // 17 - Horde Final Pos 7 - {524.238f, 122.411f, 394.819f, 0}, // 18 - Horde Final Pos 8 - {521.901f, 128.488f, 394.832f, 0} // 19 - Horde Final Pos 9 -}; - -const Position TwinValkyrsLoc[]= -{ - {586.060242f, 117.514809f, 394.41f, 0}, // 0 - Dark essence 1 - {541.602112f, 161.879837f, 394.41f, 0}, // 1 - Dark essence 2 - {541.021118f, 117.262932f, 394.41f, 0}, // 2 - Light essence 1 - {586.200562f, 162.145523f, 394.41f, 0} // 3 - Light essence 2 -}; - -const Position LichKingLoc[]= -{ - {563.549f, 152.474f, 394.393f, 0}, // 0 - Lich king start - {563.547f, 141.613f, 393.908f, 0} // 1 - Lich king end -}; - -const Position AnubarakLoc[]= -{ - {783.9305f, 132.9722f, 142.6711f, 3.141593f}, // 0 - Anub'arak Spawn Location (sniffed) - {695.240051f, 137.834824f, 142.200000f, 0}, // 1 - Anub'arak move point location - {694.886353f, 102.484665f, 142.119614f, 0}, // 3 - Nerub Spawn - {694.500671f, 185.363968f, 142.117905f, 0}, // 5 - Nerub Spawn - {731.987244f, 83.3824690f, 142.119614f, 0}, // 2 - Nerub Spawn - {740.184509f, 193.443390f, 142.117584f, 0} // 4 - Nerub Spawn -}; - -const Position EndSpawnLoc[]= -{ - {648.9167f, 131.0208f, 141.6161f, 0.f}, // 0 - Highlord Tirion Fordring - {649.1614f, 142.0399f, 141.3057f, 0.f}, // 1 - Argent Mage - {644.6250f, 149.2743f, 140.6015f, 5.f} // 2 - Portal to Dalaran -}; +extern Position const ToCCommonLoc[]; +extern Position const AnubarakLoc[]; enum TCRWorldStateIds { @@ -298,4 +219,10 @@ enum TCRAchievementData EVENT_START_TWINS_FIGHT = 21853 }; +template +inline AI* GetTrialOfTheCrusaderAI(T* obj) +{ + return GetInstanceAI(obj, ToCrScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp index 84734e48381..2a4f52e4ee1 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp @@ -20,8 +20,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "drak_tharon_keep.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp index 66c44c01019..2bcfd7a70d6 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "ScriptedCreature.h" #include "drak_tharon_keep.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" enum Yells { @@ -239,7 +243,7 @@ public: if (Creature* crystalChannelTarget = crystal->FindNearestCreature(NPC_CRYSTAL_CHANNEL_TARGET, 5.0f)) { if (active) - crystalChannelTarget->CastSpell((Unit*)NULL, SPELL_BEAM_CHANNEL); + crystalChannelTarget->CastSpell((Unit*)nullptr, SPELL_BEAM_CHANNEL); else if (crystalChannelTarget->HasUnitState(UNIT_STATE_CASTING)) crystalChannelTarget->CastStop(); } @@ -374,15 +378,13 @@ class spell_novos_summon_minions : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_COPY_OF_MINIONS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_COPY_OF_MINIONS }); } void HandleScript(SpellEffIndex /*effIndex*/) { for (uint8 i = 0; i < 2; ++i) - GetCaster()->CastSpell((Unit*)NULL, SPELL_SUMMON_COPY_OF_MINIONS, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SUMMON_COPY_OF_MINIONS, true); } void Register() override diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp index 00676a0a3c3..74746235628 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp @@ -219,9 +219,7 @@ class spell_tharon_ja_clear_gift_of_tharon_ja : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GIFT_OF_THARON_JA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GIFT_OF_THARON_JA }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp index 50bf88593c2..fd8b209e0cb 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" +#include "drak_tharon_keep.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "drak_tharon_keep.h" +#include "SpellScript.h" enum Spells { @@ -136,7 +139,7 @@ class boss_trollgore : public CreatureScript case EVENT_SPAWN: for (uint8 i = 0; i < 3; ++i) if (Creature* trigger = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_TROLLGORE_INVADER_SUMMONER_1 + i))) - trigger->CastSpell(trigger, RAND(SPELL_SUMMON_INVADER_A, SPELL_SUMMON_INVADER_B, SPELL_SUMMON_INVADER_C), true, NULL, NULL, me->GetGUID()); + trigger->CastSpell(trigger, RAND(SPELL_SUMMON_INVADER_A, SPELL_SUMMON_INVADER_B, SPELL_SUMMON_INVADER_C), true, nullptr, nullptr, me->GetGUID()); events.ScheduleEvent(EVENT_SPAWN, urand(30000, 40000)); break; @@ -234,9 +237,7 @@ class spell_trollgore_consume : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CONSUME_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CONSUME_BUFF }); } void HandleConsume(SpellEffIndex /*effIndex*/) @@ -269,16 +270,14 @@ class spell_trollgore_corpse_explode : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CORPSE_EXPLODE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CORPSE_EXPLODE_DAMAGE }); } void PeriodicTick(AuraEffect const* aurEff) { if (aurEff->GetTickNumber() == 2) if (Unit* caster = GetCaster()) - caster->CastSpell(GetTarget(), SPELL_CORPSE_EXPLODE_DAMAGE, true, NULL, aurEff); + caster->CastSpell(GetTarget(), SPELL_CORPSE_EXPLODE_DAMAGE, true, nullptr, aurEff); } void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -312,9 +311,7 @@ class spell_trollgore_invader_taunt : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleTaunt(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h b/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h index de016aed14e..02e29cc3763 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h +++ b/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h @@ -18,6 +18,8 @@ #ifndef DRAK_THARON_KEEP_H_ #define DRAK_THARON_KEEP_H_ +#include "CreatureAIImpl.h" + #define DrakTharonKeepScriptName "instance_drak_tharon_keep" #define DataHeader "DTK" @@ -84,10 +86,10 @@ enum DTKGameObjectIds GO_NOVOS_CRYSTAL_4 = 189302 }; -template -AI* GetDrakTharonKeepAI(Creature* creature) +template +inline AI* GetDrakTharonKeepAI(T* obj) { - return GetInstanceAI(creature, DrakTharonKeepScriptName); + return GetInstanceAI(obj, DrakTharonKeepScriptName); } #endif // DRAK_THARON_KEEP_H_ diff --git a/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp b/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp index 68ba3cb2591..dfd3f44ac6d 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "drak_tharon_keep.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ScriptedCreature.h" class instance_drak_tharon_keep : public InstanceMapScript { diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp index a7e679433c5..abab9f7ead7 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" +#include "forge_of_souls.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "forge_of_souls.h" +#include "SpellScript.h" enum Yells { @@ -212,7 +216,7 @@ class boss_bronjahm : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature, FoSScriptName); + return GetForgeOfSoulsAI(creature); } }; @@ -252,7 +256,7 @@ class npc_corrupted_soul_fragment : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature, FoSScriptName); + return GetForgeOfSoulsAI(creature); } }; diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp index 2b5224947ba..32b815f1f6d 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "forge_of_souls.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" -#include "SpellInfo.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "forge_of_souls.h" +#include "TemporarySummon.h" /* * @todo @@ -217,7 +221,7 @@ class boss_devourer_of_souls : public CreatureScript } } - void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) override + void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (spell->Id == H_SPELL_PHANTOM_BLAST) threeFaced = false; @@ -342,7 +346,7 @@ class boss_devourer_of_souls : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature, FoSScriptName); + return GetForgeOfSoulsAI(creature); } }; @@ -358,9 +362,7 @@ class spell_devourer_of_souls_mirrored_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIRRORED_SOUL_PROC_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIRRORED_SOUL_PROC_AURA }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -393,9 +395,7 @@ class spell_devourer_of_souls_mirrored_soul_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIRRORED_SOUL_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIRRORED_SOUL_DAMAGE }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -439,9 +439,7 @@ class spell_devourer_of_souls_mirrored_soul_target_selector : public SpellScript bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIRRORED_SOUL_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIRRORED_SOUL_BUFF }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp index 7a2c01ce17c..ae6be6f9ad2 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "forge_of_souls.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" enum Events { @@ -163,7 +163,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetForgeOfSoulsAI(creature); } }; @@ -272,7 +272,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetForgeOfSoulsAI(creature); } }; diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h index 897cd72ba50..08721c431cc 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h @@ -18,6 +18,8 @@ #ifndef FORGE_OF_SOULS_H_ #define FORGE_OF_SOULS_H_ +#include "CreatureAIImpl.h" + #define FoSScriptName "instance_forge_of_souls" #define DataHeader "FOS" @@ -55,4 +57,10 @@ enum FOSCreatures NPC_CRUCIBLE_OF_SOULS = 37094 }; +template +inline AI* GetForgeOfSoulsAI(T* obj) +{ + return GetInstanceAI(obj, FoSScriptName); +} + #endif // FORGE_OF_SOULS_H_ diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp index 2b6548bccc3..eac44c2d3f3 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp @@ -16,14 +16,16 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" +#include "Creature.h" #include "forge_of_souls.h" +#include "InstanceScript.h" +#include "Map.h" #include "Player.h" - BossBoundaryData const boundaries = { - { DATA_BRONJAHM, new CircleBoundary(Position(5297.3f, 2506.45f), 100.96) }, + { DATA_BRONJAHM, new CircleBoundary(Position(5297.3f, 2506.45f), 100.96) }, { DATA_DEVOURER_OF_SOULS, new ParallelogramBoundary(Position(5663.56f, 2570.53f), Position(5724.39f, 2520.45f), Position(5570.36f, 2461.42f)) } }; diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp index 3128014ad51..356e6c230b7 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "boss_horAI.h" #include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "SpellMgr.h" enum Texts { diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp new file mode 100644 index 00000000000..4aec3a9ed78 --- /dev/null +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "boss_horAI.h" +#include "halls_of_reflection.h" +#include "InstanceScript.h" + +boss_horAI::boss_horAI(Creature* creature, uint32 bossId) : BossAI(creature, bossId) +{ +} + +void boss_horAI::Reset() +{ + _Reset(); + me->SetVisible(false); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + me->SetReactState(REACT_PASSIVE); + if (instance->GetData(DATA_WAVE_COUNT) != NOT_STARTED) + instance->ProcessEvent(nullptr, EVENT_DO_WIPE); +} + +void boss_horAI::DoAction(int32 actionId) +{ + switch (actionId) + { + case ACTION_ENTER_COMBAT: // called by InstanceScript when boss shall enter in combat. + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + me->SetReactState(REACT_AGGRESSIVE); + DoZoneInCombat(me, 150.0f); + break; + default: + break; + } +} + +void boss_horAI::JustSummoned(Creature* summon) +{ + summons.Summon(summon); +} diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h new file mode 100644 index 00000000000..1d48ff6da1f --- /dev/null +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef boss_horAI_h__ +#define boss_horAI_h__ + +#include "ScriptedCreature.h" + +// Base class for FALRIC and MARWYN +struct boss_horAI : BossAI +{ + boss_horAI(Creature* creature, uint32 bossId); + void Reset() override; + void DoAction(int32 actionId) override; + void JustSummoned(Creature* summon) override; +}; + +#endif // boss_horAI_h__ diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp index b56301e8e65..00b9392eab8 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "boss_horAI.h" #include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Texts { diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp index af4e20ccb06..ab35de44aeb 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp @@ -16,13 +16,19 @@ */ #include "ScriptMgr.h" +#include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "Spell.h" +#include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "Transport.h" -#include "Player.h" -#include "MoveSplineInit.h" -#include "halls_of_reflection.h" enum Text { @@ -338,6 +344,12 @@ Position const IceWallTargetPosition[] = { 5318.289f, 1749.184f, 771.9423f, 0.8726646f } // 4th Icewall }; +void GameObjectDeleteDelayEvent::DeleteGameObject() +{ + if (GameObject* go = ObjectAccessor::GetGameObject(*_owner, _gameObjectGUID)) + go->Delete(); +} + class npc_jaina_or_sylvanas_intro_hor : public CreatureScript { public: @@ -1641,7 +1653,7 @@ class npc_phantom_hallucination : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_phantom_hallucinationAI(creature); + return GetHallsOfReflectionAI(creature); } }; @@ -1995,7 +2007,7 @@ class npc_spiritual_reflection : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_spiritual_reflectionAI(creature); + return GetHallsOfReflectionAI(creature); } }; @@ -2816,9 +2828,9 @@ class spell_hor_gunship_cannon_fire : public SpellScriptLoader if (!urand(0, 2)) { if (GetTarget()->GetEntry() == NPC_GUNSHIP_CANNON_HORDE) - GetTarget()->CastSpell((Unit*)NULL, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_HORDE, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_HORDE, true); else - GetTarget()->CastSpell((Unit*)NULL, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_ALLIANCE, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_ALLIANCE, true); } } diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h index 77f7d9d41a7..8d1fe6961c7 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h @@ -18,6 +18,10 @@ #ifndef HALLS_OF_REFLECTION_H_ #define HALLS_OF_REFLECTION_H_ +#include "CreatureAIImpl.h" +#include "EventProcessor.h" +#include "ObjectGuid.h" + #define HoRScriptName "instance_halls_of_reflection" #define DataHeader "HOR" @@ -192,51 +196,12 @@ enum HORInstanceYells SAY_CAPTAIN_FINAL = 1 }; -// Base class for FALRIC and MARWYN -struct boss_horAI : BossAI -{ - boss_horAI(Creature* creature, uint32 bossId) : BossAI(creature, bossId) { } - - void Reset() override - { - _Reset(); - me->SetVisible(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); - me->SetReactState(REACT_PASSIVE); - if (instance->GetData(DATA_WAVE_COUNT) != NOT_STARTED) - instance->ProcessEvent(NULL, EVENT_DO_WIPE); - } - - void DoAction(int32 actionId) override - { - switch (actionId) - { - case ACTION_ENTER_COMBAT: // called by InstanceScript when boss shall enter in combat. - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); - me->SetReactState(REACT_AGGRESSIVE); - DoZoneInCombat(me, 150.0f); - break; - default: - break; - } - } - - void JustSummoned(Creature* summon) override - { - summons.Summon(summon); - } -}; - class GameObjectDeleteDelayEvent : public BasicEvent { public: GameObjectDeleteDelayEvent(Unit* owner, ObjectGuid gameObjectGUID) : _owner(owner), _gameObjectGUID(gameObjectGUID) { } - void DeleteGameObject() - { - if (GameObject* go = ObjectAccessor::GetGameObject(*_owner, _gameObjectGUID)) - go->Delete(); - } + void DeleteGameObject(); bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { @@ -254,10 +219,10 @@ class GameObjectDeleteDelayEvent : public BasicEvent ObjectGuid _gameObjectGUID; }; -template -AI* GetHallsOfReflectionAI(Creature* creature) +template +inline AI* GetHallsOfReflectionAI(T* obj) { - return GetInstanceAI(creature, HoRScriptName); + return GetInstanceAI(obj, HoRScriptName); } #endif // HALLS_OF_REFLECTION_H_ diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp index 694ef000ed1..936a1117b88 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "halls_of_reflection.h" #include "InstanceScript.h" +#include "Map.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "Transport.h" #include "WorldPacket.h" -#include "halls_of_reflection.h" Position const JainaSpawnPos = { 5236.659f, 1929.894f, 707.7781f, 0.8726646f }; // Jaina Spawn Position Position const SylvanasSpawnPos = { 5236.667f, 1929.906f, 707.7781f, 0.8377581f }; // Sylvanas Spawn Position (sniffed) @@ -344,7 +346,7 @@ class instance_halls_of_reflection : public InstanceMapScript if (Creature* lichking = instance->GetCreature(TheLichKingEscapeGUID)) { - lichking->CastSpell((Unit*)NULL, SPELL_ACHIEV_CHECK, true); + lichking->CastSpell((Unit*)nullptr, SPELL_ACHIEV_CHECK, true); lichking->DespawnOrUnsummon(1); } break; @@ -438,7 +440,7 @@ class instance_halls_of_reflection : public InstanceMapScript break; case DATA_WAVE_COUNT: if (_waveCount && data == NOT_STARTED) - ProcessEvent(NULL, EVENT_DO_WIPE); + ProcessEvent(nullptr, EVENT_DO_WIPE); break; case DATA_FROSTSWORN_GENERAL: if (data == DONE) @@ -451,7 +453,7 @@ class instance_halls_of_reflection : public InstanceMapScript if (_quelDelarState == NOT_STARTED) { if (Creature* bunny = instance->GetCreature(FrostmourneAltarBunnyGUID)) - bunny->CastSpell((Unit*)NULL, SPELL_ESSENCE_OF_CAPTURED); + bunny->CastSpell((Unit*)nullptr, SPELL_ESSENCE_OF_CAPTURED); events.ScheduleEvent(EVENT_QUEL_DELAR_SUMMON_UTHER, 2000); } } @@ -516,7 +518,7 @@ class instance_halls_of_reflection : public InstanceMapScript switch (events.ExecuteEvent()) { case EVENT_NEXT_WAVE: - ProcessEvent(NULL, EVENT_ADD_WAVE); + ProcessEvent(nullptr, EVENT_ADD_WAVE); break; case EVENT_SPAWN_ESCAPE_EVENT: SpawnEscapeEvent(); diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp index fc1395437c1..5b806daf2b2 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "pit_of_saron.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuras.h" -#include "pit_of_saron.h" +#include "SpellScript.h" enum Yells { @@ -167,7 +171,7 @@ class boss_garfrost : public CreatureScript events.ScheduleEvent(EVENT_RESUME_ATTACK, 5000); } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_PERMAFROST_HELPER) { diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp index 270f4d0c700..05bf39cb5fb 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp @@ -16,12 +16,17 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "pit_of_saron.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "pit_of_saron.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "Player.h" enum Spells { @@ -374,7 +379,7 @@ class boss_krick : public CreatureScript if (Creature* temp = ObjectAccessor::GetCreature(*me, _instanceScript->GetGuidData(DATA_JAINA_SYLVANAS_1))) temp->DespawnOrUnsummon(); - Creature* jainaOrSylvanas = NULL; + Creature* jainaOrSylvanas = nullptr; if (_instanceScript->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) jainaOrSylvanas = me->SummonCreature(NPC_JAINA_PART1, outroPos[2], TEMPSUMMON_MANUAL_DESPAWN); else @@ -521,7 +526,7 @@ class spell_krick_explosive_barrage : public SpellScriptLoader if (Unit* caster = GetCaster()) if (caster->GetTypeId() == TYPEID_UNIT) { - Map::PlayerList const &players = caster->GetMap()->GetPlayers(); + Map::PlayerList const& players = caster->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (Player* player = itr->GetSource()) if (player->IsWithinDist(caster, 60.0f)) // don't know correct range diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp index 8ceceeff8e7..4e62380b983 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp @@ -16,13 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "pit_of_saron.h" -#include "Vehicle.h" #include "Player.h" #include "PlayerAI.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Yells { @@ -387,7 +391,7 @@ class boss_rimefang : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_rimefangAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -400,13 +404,13 @@ class player_overlord_brandAI : public PlayerAI { if (Creature* tyrannus = ObjectAccessor::GetCreature(*me, _tyrannusGUID)) if (Unit* victim = tyrannus->GetVictim()) - me->CastCustomSpell(SPELL_OVERLORD_BRAND_DAMAGE, SPELLVALUE_BASE_POINT0, damage, victim, true, NULL, NULL, tyrannus->GetGUID()); + me->CastCustomSpell(SPELL_OVERLORD_BRAND_DAMAGE, SPELLVALUE_BASE_POINT0, damage, victim, true, nullptr, nullptr, tyrannus->GetGUID()); } void HealDone(Unit* /*target*/, uint32& addHealth) override { if (Creature* tyrannus = ObjectAccessor::GetCreature(*me, _tyrannusGUID)) - me->CastCustomSpell(SPELL_OVERLORD_BRAND_HEAL, SPELLVALUE_BASE_POINT0, int32(addHealth * 5.5f), tyrannus, true, NULL, NULL, tyrannus->GetGUID()); + me->CastCustomSpell(SPELL_OVERLORD_BRAND_HEAL, SPELLVALUE_BASE_POINT0, int32(addHealth * 5.5f), tyrannus, true, nullptr, nullptr, tyrannus->GetGUID()); } void UpdateAI(uint32 /*diff*/) override { } @@ -424,14 +428,6 @@ class spell_tyrannus_overlord_brand : public SpellScriptLoader { PrepareAuraScript(spell_tyrannus_overlord_brand_AuraScript); - public: - spell_tyrannus_overlord_brand_AuraScript() - { - oldAI = nullptr; - oldAIState = false; - } - - private: bool Load() override { return GetCaster() && GetCaster()->GetEntry() == NPC_TYRANNUS; @@ -466,8 +462,8 @@ class spell_tyrannus_overlord_brand : public SpellScriptLoader AfterEffectRemove += AuraEffectRemoveFn(spell_tyrannus_overlord_brand_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } - PlayerAI* oldAI; - bool oldAIState; + PlayerAI* oldAI = nullptr; + bool oldAIState = false; }; AuraScript* GetAuraScript() const override @@ -520,9 +516,7 @@ class spell_tyrannus_rimefang_icy_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICY_BLAST_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICY_BLAST_AURA }); } void HandleTriggerMissile(SpellEffIndex effIndex) @@ -550,7 +544,7 @@ class at_tyrannus_event_starter : public AreaTriggerScript public: at_tyrannus_event_starter() : AreaTriggerScript("at_tyrannus_event_starter") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { InstanceScript* instance = player->GetInstanceScript(); if (player->IsGameMaster() || !instance) diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp index 652aed172fc..a5df7ecf2b5 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "pit_of_saron.h" #include "Player.h" @@ -164,28 +166,6 @@ class instance_pit_of_saron : public InstanceMapScript } } - void OnGameObjectCreate(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_ICE_WALL: - case GO_HALLS_OF_REFLECTION_PORTCULLIS: - AddDoor(go, true); - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_ICE_WALL: - case GO_HALLS_OF_REFLECTION_PORTCULLIS: - AddDoor(go, false); - break; - } - } - bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp index 0e11e7f9089..bd73ab93c6d 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "pit_of_saron.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "pit_of_saron.h" -#include "PassiveAI.h" #include "Vehicle.h" -#include "Player.h" enum Spells { @@ -40,6 +42,19 @@ enum Events EVENT_TACTICAL_BLINK = 2, }; +bool ScheduledIcicleSummons::Execute(uint64 /*time*/, uint32 /*diff*/) +{ + if (roll_chance_i(12)) + { + _trigger->CastSpell(_trigger, SPELL_ICICLE_SUMMON, true); + _trigger->m_Events.AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(20000, 35000))); + } + else + _trigger->m_Events.AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(1000, 20000))); + + return true; +} + class npc_ymirjar_flamebearer : public CreatureScript { public: @@ -101,7 +116,7 @@ class npc_ymirjar_flamebearer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ymirjar_flamebearerAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -155,7 +170,7 @@ class npc_iceborn_protodrake : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_iceborn_protodrakeAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -214,7 +229,7 @@ class npc_geist_ambusher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_geist_ambusherAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -303,12 +318,7 @@ class spell_pos_ice_shards : public SpellScriptLoader bool Load() override { // This script should execute only in Pit of Saron - if (InstanceMap* instance = GetCaster()->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(PoSScriptName)) - return true; - - return false; + return InstanceHasScript(GetCaster(), PoSScriptName); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h index 9f2a1abd3a6..b82f897bf98 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h @@ -18,6 +18,9 @@ #ifndef PIT_OF_SARON_H_ #define PIT_OF_SARON_H_ +#include "CreatureAIImpl.h" +#include "EventProcessor.h" + #define PoSScriptName "instance_pit_of_saron" #define DataHeader "POS" @@ -112,27 +115,16 @@ class ScheduledIcicleSummons : public BasicEvent public: ScheduledIcicleSummons(Creature* trigger) : _trigger(trigger) { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) override - { - if (roll_chance_i(12)) - { - _trigger->CastSpell(_trigger, SPELL_ICICLE_SUMMON, true); - _trigger->m_Events.AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(20000, 35000))); - } - else - _trigger->m_Events. AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(1000,20000))); - - return true; - } + bool Execute(uint64 /*time*/, uint32 /*diff*/) override; private: Creature* _trigger; }; -template -AI* GetPitOfSaronAI(Creature* creature) +template +inline AI* GetPitOfSaronAI(T* obj) { - return GetInstanceAI(creature, PoSScriptName); + return GetInstanceAI(obj, PoSScriptName); } #endif // PIT_OF_SARON_H_ diff --git a/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp b/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp index 7af34da74bb..465bb9bcf24 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp @@ -20,8 +20,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "gundrak.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Texts diff --git a/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp b/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp index 9d3dbd4e2dd..90f1d4af510 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" +#include "gundrak.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "gundrak.h" enum Spells { @@ -250,9 +252,7 @@ class spell_gal_darah_impaling_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_IMPALING_CHARGE_CONTROL_VEHICLE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_IMPALING_CHARGE_CONTROL_VEHICLE }); } bool Load() override diff --git a/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp b/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp index 22c023983b9..9eac3162096 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp @@ -225,9 +225,7 @@ class spell_moorabi_mojo_frenzy : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOJO_FRENZY_CAST_SPEED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MOJO_FRENZY_CAST_SPEED }); } void HandlePeriodic(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp b/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp index 62d215f9161..fb00acb39dc 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuras.h" #include "gundrak.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "TemporarySummon.h" enum Spells { @@ -209,7 +211,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_slad_ran_constrictorAI(creature); + return GetGundrakAI(creature); } struct npc_slad_ran_constrictorAI : public ScriptedAI @@ -264,7 +266,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_slad_ran_viperAI(creature); + return GetGundrakAI(creature); } struct npc_slad_ran_viperAI : public ScriptedAI diff --git a/src/server/scripts/Northrend/Gundrak/gundrak.h b/src/server/scripts/Northrend/Gundrak/gundrak.h index 44f160e36b7..e25b6e7461b 100644 --- a/src/server/scripts/Northrend/Gundrak/gundrak.h +++ b/src/server/scripts/Northrend/Gundrak/gundrak.h @@ -18,6 +18,8 @@ #ifndef GUNDRAK_H_ #define GUNDRAK_H_ +#include "CreatureAIImpl.h" + #define GundrakScriptName "instance_gundrak" #define DataHeader "GD" @@ -91,7 +93,7 @@ enum GDInstanceMisc TIMER_STATUE_ACTIVATION = 3500 }; -template +template inline AI* GetGundrakAI(T* obj) { return GetInstanceAI(obj, GundrakScriptName); diff --git a/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp b/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp index 3dd8503ce9d..c9e5848d2f5 100644 --- a/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp +++ b/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp @@ -16,20 +16,23 @@ */ #include "InstanceScript.h" -#include "Player.h" -#include "ScriptMgr.h" +#include "Creature.h" +#include "EventMap.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "gundrak.h" -#include "EventMap.h" +#include "Map.h" +#include "Player.h" +#include "ScriptMgr.h" DoorData const doorData[] = { { GO_GAL_DARAH_DOOR_1, DATA_GAL_DARAH, DOOR_TYPE_PASSAGE }, { GO_GAL_DARAH_DOOR_2, DATA_GAL_DARAH, DOOR_TYPE_PASSAGE }, - { GO_GAL_DARAH_DOOR_3, DATA_GAL_DARAH, DOOR_TYPE_ROOM }, + { GO_GAL_DARAH_DOOR_3, DATA_GAL_DARAH, DOOR_TYPE_ROOM }, { GO_ECK_THE_FEROCIOUS_DOOR, DATA_MOORABI, DOOR_TYPE_PASSAGE }, { GO_ECK_THE_FEROCIOUS_DOOR_BEHIND, DATA_ECK_THE_FEROCIOUS, DOOR_TYPE_PASSAGE }, - { 0, 0, DOOR_TYPE_ROOM } // END + { 0, 0, DOOR_TYPE_ROOM } // END }; ObjectData const creatureData[] = diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp index 5d74d128f6f..5b2248d5341 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp @@ -15,13 +15,20 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "icecrown_citadel.h" -#include "Player.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -1243,9 +1250,7 @@ class spell_taldaram_flame_ball_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BALL_OF_FLAMES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BALL_OF_FLAMES }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1355,10 +1360,7 @@ class spell_valanar_kinetic_bomb : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_KINETIC_BOMB_EXPLOSION) - || !sSpellMgr->GetSpellInfo(SPELL_KINETIC_BOMB_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_KINETIC_BOMB_EXPLOSION, SPELL_KINETIC_BOMB_VISUAL }); } void HandleDummyTick(AuraEffect const* /*aurEff*/) @@ -1462,9 +1464,7 @@ class spell_blood_council_shadow_prison : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_PRISON_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOW_PRISON_DAMAGE }); } void HandleDummyTick(AuraEffect const* aurEff) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp index e070829ea16..b908e1a9c35 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_queen_lana_thel.cpp @@ -15,13 +15,18 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "GridNotifiers.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "Spell.h" +#include "SpellMgr.h" +#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "icecrown_citadel.h" enum Texts { @@ -372,7 +377,7 @@ class boss_blood_queen_lana_thel : public CreatureScript } case EVENT_BLOOD_MIRROR: { - // victim can be NULL when this is processed in the same update tick as EVENT_AIR_PHASE + // victim can be nullptr when this is processed in the same update tick as EVENT_AIR_PHASE if (me->GetVictim()) { Player* newOfftank = SelectRandomTarget(true); @@ -477,13 +482,13 @@ class boss_blood_queen_lana_thel : public CreatureScript private: // offtank for this encounter is the player standing closest to main tank - Player* SelectRandomTarget(bool includeOfftank, std::list* targetList = NULL) + Player* SelectRandomTarget(bool includeOfftank, std::list* targetList = nullptr) { std::list const& threatlist = me->getThreatManager().getThreatList(); std::list tempTargets; if (threatlist.empty()) - return NULL; + return nullptr; for (std::list::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) if (Unit* refTarget = (*itr)->getTarget()) @@ -491,12 +496,12 @@ class boss_blood_queen_lana_thel : public CreatureScript tempTargets.push_back(refTarget->ToPlayer()); if (tempTargets.empty()) - return NULL; + return nullptr; if (targetList) { *targetList = tempTargets; - return NULL; + return nullptr; } if (includeOfftank) @@ -535,13 +540,7 @@ class spell_blood_queen_vampiric_bite : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_PLR)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_FRENZIED_BLOODTHIRST)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PRESENCE_OF_THE_DARKFALLEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_PLR, SPELL_FRENZIED_BLOODTHIRST, SPELL_PRESENCE_OF_THE_DARKFALLEN }); } SpellCastResult CheckTarget() @@ -671,9 +670,7 @@ class spell_blood_queen_bloodbolt : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TWILIGHT_BLOODBOLT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TWILIGHT_BLOODBOLT }); } bool Load() override @@ -722,9 +719,7 @@ class spell_blood_queen_essence_of_the_blood_queen : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_HEAL }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -809,9 +804,7 @@ class spell_blood_queen_pact_of_the_darkfallen_dmg : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PACT_OF_THE_DARKFALLEN_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PACT_OF_THE_DARKFALLEN_DAMAGE }); } // this is an additional effect to be executed diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp index 064e903ba62..172c54fd7e0 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp @@ -15,13 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellAuras.h" -#include "icecrown_citadel.h" -#include "Player.h" +#include "SpellScript.h" enum ScriptTexts { @@ -639,7 +642,7 @@ class npc_high_overlord_saurfang_icc : public CreatureScript { if (menuId == GOSSIP_MENU_HIGH_OVERLORD_SAURFANG) { - player->PlayerTalkClass->SendCloseGossip(); + CloseGossipMenuFor(player); DoAction(ACTION_START_EVENT); } return false; @@ -836,7 +839,7 @@ class npc_muradin_bronzebeard_icc : public CreatureScript { if (menuId == GOSSIP_MENU_MURADIN_BRONZEBEARD) { - player->PlayerTalkClass->SendCloseGossip(); + CloseGossipMenuFor(player); DoAction(ACTION_START_EVENT); } return false; @@ -1007,11 +1010,7 @@ class spell_deathbringer_blood_link : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_POWER)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_POWER, SPELL_BLOOD_POWER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1043,9 +1042,7 @@ class spell_deathbringer_blood_link_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_THE_FALLEN_CHAMPION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_THE_FALLEN_CHAMPION }); } void HandlePeriodicTick(AuraEffect const* /*aurEff*/) @@ -1128,9 +1125,7 @@ class spell_deathbringer_rune_of_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_DUMMY }); } void HandleScript(SpellEffIndex effIndex) @@ -1163,9 +1158,7 @@ class spell_deathbringer_blood_beast_blood_link : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_DUMMY }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1197,9 +1190,7 @@ class spell_deathbringer_blood_nova : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_DUMMY }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp index e92b66f358f..5b0ea090802 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp @@ -15,12 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuras.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum ScriptTexts { @@ -197,7 +201,7 @@ class boss_festergut : public CreatureScript // just cast and dont bother with target, conditions will handle it ++_inhaleCounter; if (_inhaleCounter < 3) - me->CastSpell(me, gaseousBlight[_inhaleCounter], true, NULL, NULL, me->GetGUID()); + me->CastSpell(me, gaseousBlight[_inhaleCounter], true, nullptr, nullptr, me->GetGUID()); } events.ScheduleEvent(EVENT_INHALE_BLIGHT, urand(33500, 35000)); @@ -410,9 +414,7 @@ class spell_festergut_gastric_bloat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GASTRIC_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GASTRIC_EXPLOSION }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -448,9 +450,7 @@ class spell_festergut_blighted_spores : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_INOCULATED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_INOCULATED }); } void ExtraEffect(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp index a30ea8e9cc5..aa0ce037619 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp @@ -15,22 +15,28 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "CellImpl.h" #include "CreatureTextMgr.h" -#include "GridNotifiersImpl.h" #include "GossipDef.h" +#include "GridNotifiersImpl.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "MoveSpline.h" #include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" -#include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellHistory.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "Transport.h" #include "TransportMgr.h" #include "Vehicle.h" -#include "icecrown_citadel.h" +#include enum Texts { @@ -383,7 +389,7 @@ public: void ResetSlots(uint32 team) { - _transport = NULL; + _transport = nullptr; for (uint32 i = 0; i < MAX_SLOTS; ++i) _controlledSlots[i].Clear(); @@ -398,7 +404,7 @@ public: return false; bool summoned = false; - time_t now = time(NULL); + time_t now = time(nullptr); for (int32 i = first; i <= last; ++i) { if (_respawnCooldowns[i] > now) @@ -411,7 +417,7 @@ public: continue; } - if (Creature* passenger = _transport->SummonPassenger(_slotInfo[i].Entry, SelectSpawnPoint(), TEMPSUMMON_CORPSE_TIMED_DESPAWN, NULL, 15000)) + if (Creature* passenger = _transport->SummonPassenger(_slotInfo[i].Entry, SelectSpawnPoint(), TEMPSUMMON_CORPSE_TIMED_DESPAWN, nullptr, 15000)) { _controlledSlots[i] = passenger->GetGUID(); _respawnCooldowns[i] = time_t(0); @@ -426,7 +432,7 @@ public: void ClearSlot(PassengerSlots slot) { _controlledSlots[slot].Clear(); - _respawnCooldowns[slot] = time(NULL) + _slotInfo[slot].Cooldown; + _respawnCooldowns[slot] = time(nullptr) + _slotInfo[slot].Cooldown; } bool SlotsNeedRefill(PassengerSlots first, PassengerSlots last) const @@ -541,7 +547,7 @@ uint32 const BattleExperienceEvent::ExperiencedTimes[5] = { 100000, 70000, 60000 struct gunship_npc_AI : public ScriptedAI { gunship_npc_AI(Creature* creature) : ScriptedAI(creature), - Instance(creature->GetInstanceScript()), Slot(NULL), Index(uint32(-1)) + Instance(creature->GetInstanceScript()), Slot(nullptr), Index(uint32(-1)) { BurningPitchId = Instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE ? SPELL_BURNING_PITCH_A : SPELL_BURNING_PITCH_H; me->setRegeneratingHealth(false); @@ -677,7 +683,7 @@ class npc_gunship : public CreatureScript { if (damage >= me->GetHealth()) { - JustDied(NULL); + JustDied(nullptr); damage = me->GetHealth() - 1; return; } @@ -833,7 +839,7 @@ class npc_gunship : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { if (!creature->GetTransport()) - return NULL; + return nullptr; return GetIcecrownCitadelAI(creature); } @@ -853,7 +859,7 @@ class npc_high_overlord_saurfang_igb : public CreatureScript _controller.SetTransport(creature->GetTransport()); me->setRegeneratingHealth(false); me->m_CombatDistance = 70.0f; - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _axethrowersYellCooldown = time_t(0); _rocketeersYellCooldown = time_t(0); } @@ -863,7 +869,7 @@ class npc_high_overlord_saurfang_igb : public CreatureScript ScriptedAI::InitializeAI(); _events.Reset(); - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _axethrowersYellCooldown = time_t(0); _rocketeersYellCooldown = time_t(0); } @@ -915,7 +921,7 @@ class npc_high_overlord_saurfang_igb : public CreatureScript } else if (action == ACTION_SPAWN_MAGE) { - time_t now = time(NULL); + time_t now = time(nullptr); if (_firstMageCooldown > now) _events.ScheduleEvent(EVENT_SUMMON_MAGE, (_firstMageCooldown - now) * IN_MILLISECONDS); else @@ -1034,10 +1040,10 @@ class npc_high_overlord_saurfang_igb : public CreatureScript _controller.SummonCreatures(SLOT_MARINE_1, Is25ManRaid() ? SLOT_MARINE_4 : SLOT_MARINE_2); _controller.SummonCreatures(SLOT_SERGEANT_1, Is25ManRaid() ? SLOT_SERGEANT_2 : SLOT_SERGEANT_1); if (Transport* orgrimsHammer = me->GetTransport()) - orgrimsHammer->SummonPassenger(NPC_TELEPORT_PORTAL, OrgrimsHammerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, NULL, 21000); + orgrimsHammer->SummonPassenger(NPC_TELEPORT_PORTAL, OrgrimsHammerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, nullptr, 21000); if (Transport* skybreaker = HashMapHolder::Find(_instance->GetGuidData(DATA_ICECROWN_GUNSHIP_BATTLE))) - skybreaker->SummonPassenger(NPC_TELEPORT_EXIT, SkybreakerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, NULL, 23000); + skybreaker->SummonPassenger(NPC_TELEPORT_EXIT, SkybreakerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, nullptr, 23000); _events.ScheduleEvent(EVENT_ADDS_BOARD_YELL, 6000); _events.ScheduleEvent(EVENT_ADDS, 60000); @@ -1049,10 +1055,10 @@ class npc_high_overlord_saurfang_igb : public CreatureScript case EVENT_CHECK_RIFLEMAN: if (_controller.SummonCreatures(SLOT_RIFLEMAN_1, Is25ManRaid() ? SLOT_RIFLEMAN_8 : SLOT_RIFLEMAN_4)) { - if (_axethrowersYellCooldown < time(NULL)) + if (_axethrowersYellCooldown < time(nullptr)) { Talk(SAY_SAURFANG_AXETHROWERS); - _axethrowersYellCooldown = time(NULL) + 5; + _axethrowersYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_RIFLEMAN, 1000); @@ -1060,10 +1066,10 @@ class npc_high_overlord_saurfang_igb : public CreatureScript case EVENT_CHECK_MORTAR: if (_controller.SummonCreatures(SLOT_MORTAR_1, Is25ManRaid() ? SLOT_MORTAR_4 : SLOT_MORTAR_2)) { - if (_rocketeersYellCooldown < time(NULL)) + if (_rocketeersYellCooldown < time(nullptr)) { Talk(SAY_SAURFANG_ROCKETEERS); - _rocketeersYellCooldown = time(NULL) + 5; + _rocketeersYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_MORTAR, 1000); @@ -1122,7 +1128,7 @@ class npc_muradin_bronzebeard_igb : public CreatureScript _controller.SetTransport(creature->GetTransport()); me->setRegeneratingHealth(false); me->m_CombatDistance = 70.0f; - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _riflemanYellCooldown = time_t(0); _mortarYellCooldown = time_t(0); } @@ -1132,7 +1138,7 @@ class npc_muradin_bronzebeard_igb : public CreatureScript ScriptedAI::InitializeAI(); _events.Reset(); - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _riflemanYellCooldown = time_t(0); _mortarYellCooldown = time_t(0); } @@ -1184,7 +1190,7 @@ class npc_muradin_bronzebeard_igb : public CreatureScript } else if (action == ACTION_SPAWN_MAGE) { - time_t now = time(NULL); + time_t now = time(nullptr); if (_firstMageCooldown > now) _events.ScheduleEvent(EVENT_SUMMON_MAGE, (_firstMageCooldown - now) * IN_MILLISECONDS); else @@ -1307,10 +1313,10 @@ class npc_muradin_bronzebeard_igb : public CreatureScript _controller.SummonCreatures(SLOT_MARINE_1, Is25ManRaid() ? SLOT_MARINE_4 : SLOT_MARINE_2); _controller.SummonCreatures(SLOT_SERGEANT_1, Is25ManRaid() ? SLOT_SERGEANT_2 : SLOT_SERGEANT_1); if (Transport* skybreaker = me->GetTransport()) - skybreaker->SummonPassenger(NPC_TELEPORT_PORTAL, SkybreakerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, NULL, 21000); + skybreaker->SummonPassenger(NPC_TELEPORT_PORTAL, SkybreakerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, nullptr, 21000); if (Transport* orgrimsHammer = HashMapHolder::Find(_instance->GetGuidData(DATA_ICECROWN_GUNSHIP_BATTLE))) - orgrimsHammer->SummonPassenger(NPC_TELEPORT_EXIT, OrgrimsHammerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, NULL, 23000); + orgrimsHammer->SummonPassenger(NPC_TELEPORT_EXIT, OrgrimsHammerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, nullptr, 23000); _events.ScheduleEvent(EVENT_ADDS_BOARD_YELL, 6000); _events.ScheduleEvent(EVENT_ADDS, 60000); @@ -1322,10 +1328,10 @@ class npc_muradin_bronzebeard_igb : public CreatureScript case EVENT_CHECK_RIFLEMAN: if (_controller.SummonCreatures(SLOT_RIFLEMAN_1, Is25ManRaid() ? SLOT_RIFLEMAN_8 : SLOT_RIFLEMAN_4)) { - if (_riflemanYellCooldown < time(NULL)) + if (_riflemanYellCooldown < time(nullptr)) { Talk(SAY_MURADIN_RIFLEMAN); - _riflemanYellCooldown = time(NULL) + 5; + _riflemanYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_RIFLEMAN, 1000); @@ -1333,10 +1339,10 @@ class npc_muradin_bronzebeard_igb : public CreatureScript case EVENT_CHECK_MORTAR: if (_controller.SummonCreatures(SLOT_MORTAR_1, Is25ManRaid() ? SLOT_MORTAR_4 : SLOT_MORTAR_2)) { - if (_mortarYellCooldown < time(NULL)) + if (_mortarYellCooldown < time(nullptr)) { Talk(SAY_MURADIN_MORTAR); - _mortarYellCooldown = time(NULL) + 5; + _mortarYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_MORTAR, 1000); @@ -1814,7 +1820,7 @@ class npc_gunship_cannon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_gunship_cannonAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1829,11 +1835,7 @@ class spell_igb_rocket_pack : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_PACK_DAMAGE) || - !sSpellMgr->GetSpellInfo(SPELL_ROCKET_BURST)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ROCKET_PACK_DAMAGE, SPELL_ROCKET_BURST }); } void HandlePeriodic(AuraEffect const* /*aurEff*/) @@ -1845,8 +1847,8 @@ class spell_igb_rocket_pack : public SpellScriptLoader void HandleRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { SpellInfo const* damageInfo = sSpellMgr->AssertSpellInfo(SPELL_ROCKET_PACK_DAMAGE); - GetTarget()->CastCustomSpell(SPELL_ROCKET_PACK_DAMAGE, SPELLVALUE_BASE_POINT0, 2 * (damageInfo->Effects[EFFECT_0].CalcValue() + aurEff->GetTickNumber() * aurEff->GetAmplitude()), NULL, TRIGGERED_FULL_MASK); - GetTarget()->CastSpell(NULL, SPELL_ROCKET_BURST, TRIGGERED_FULL_MASK); + GetTarget()->CastCustomSpell(SPELL_ROCKET_PACK_DAMAGE, SPELLVALUE_BASE_POINT0, 2 * (damageInfo->Effects[EFFECT_0].CalcValue() + aurEff->GetTickNumber() * aurEff->GetAmplitude()), nullptr, TRIGGERED_FULL_MASK); + GetTarget()->CastSpell(nullptr, SPELL_ROCKET_BURST, TRIGGERED_FULL_MASK); } void Register() override @@ -2101,7 +2103,7 @@ class spell_igb_overheat : public SpellScriptLoader WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, GetUnitOwner()->GetPackGUID().size() + 1); data << GetUnitOwner()->GetPackGUID(); data << uint8(value); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } } @@ -2251,7 +2253,7 @@ class spell_igb_burning_pitch : public SpellScriptLoader void HandleDummy(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); - GetCaster()->CastCustomSpell(uint32(GetEffectValue()), SPELLVALUE_BASE_POINT0, 8000, NULL, TRIGGERED_FULL_MASK); + GetCaster()->CastCustomSpell(uint32(GetEffectValue()), SPELLVALUE_BASE_POINT0, 8000, nullptr, TRIGGERED_FULL_MASK); GetHitUnit()->CastSpell(GetHitUnit(), SPELL_BURNING_PITCH, TRIGGERED_FULL_MASK); } @@ -2317,7 +2319,7 @@ class spell_igb_rocket_artillery_explosion : public SpellScriptLoader void DamageGunship(SpellEffIndex /*effIndex*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) - GetCaster()->CastCustomSpell(instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE ? SPELL_BURNING_PITCH_DAMAGE_A : SPELL_BURNING_PITCH_DAMAGE_H, SPELLVALUE_BASE_POINT0, 5000, NULL, TRIGGERED_FULL_MASK); + GetCaster()->CastCustomSpell(instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE ? SPELL_BURNING_PITCH_DAMAGE_A : SPELL_BURNING_PITCH_DAMAGE_H, SPELLVALUE_BASE_POINT0, 5000, nullptr, TRIGGERED_FULL_MASK); } void Register() override @@ -2402,7 +2404,7 @@ class spell_igb_check_for_players : public SpellScriptLoader void TriggerWipe() { if (!_playerCount) - GetCaster()->ToCreature()->AI()->JustDied(NULL); + GetCaster()->ToCreature()->AI()->JustDied(nullptr); } void TeleportPlayer(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp index 88f4f9e3399..602c191cfab 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp @@ -15,14 +15,18 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PoolMgr.h" #include "Group.h" #include "icecrown_citadel.h" -#include "SpellInfo.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "PoolMgr.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum ScriptTexts { @@ -453,7 +457,7 @@ class boss_lady_deathwhisper : public CreatureScript } } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_SUMMON_SPIRITS) _nextVengefulShadeTargetGUID.push_back(target->GetGUID()); @@ -540,7 +544,7 @@ class boss_lady_deathwhisper : public CreatureScript } // helper for summoning wave mobs - void Summon(uint32 entry, const Position& pos) + void Summon(uint32 entry, Position const& pos) { if (TempSummon* summon = me->SummonCreature(entry, pos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 10000)) summon->CastSpell(summon, SPELL_TELEPORT_VISUAL); @@ -1044,9 +1048,7 @@ class spell_deathwhisper_dominated_mind : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DOMINATE_MIND_SCALE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DOMINATE_MIND_SCALE }); } void HandleApply(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) @@ -1078,9 +1080,7 @@ class spell_deathwhisper_summon_spirits : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SHADE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SHADE }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp index 361516582c6..c13ce2ed638 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp @@ -15,13 +15,18 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuras.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "icecrown_citadel.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum ScriptTexts { @@ -618,11 +623,7 @@ class spell_marrowgar_bone_spike_graveyard : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint32 i = 0; i < 3; ++i) - if (!sSpellMgr->GetSpellInfo(BoneSpikeSummonId[i])) - return false; - - return true; + return ValidateSpellInfo(BoneSpikeSummonId); } bool Load() override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp index 95996143209..ca10713b47a 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp @@ -15,15 +15,22 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" +#include "DBCStores.h" +#include "GridNotifiers.h" #include "Group.h" -#include "Spell.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "GridNotifiers.h" enum Say { @@ -373,7 +380,7 @@ class boss_professor_putricide : public CreatureScript me->SetSpeedRate(MOVE_RUN, _baseSpeed); DoAction(ACTION_FESTERGUT_GAS); if (Creature* festergut = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_FESTERGUT))) - festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, NULL, NULL, festergut->GetGUID()); + festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, nullptr, nullptr, festergut->GetGUID()); break; case POINT_ROTFACE: instance->SetBossState(DATA_ROTFACE, IN_PROGRESS); // needed here for delayed gate close @@ -470,7 +477,7 @@ class boss_professor_putricide : public CreatureScript case ACTION_ROTFACE_OOZE: Talk(SAY_ROTFACE_OOZE_FLOOD); if (Creature* dummy = ObjectAccessor::GetCreature(*me, _oozeFloodDummyGUIDs[_oozeFloodStage])) - dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, NULL, NULL, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs) + dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, nullptr, nullptr, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs) if (++_oozeFloodStage == 4) _oozeFloodStage = 0; break; @@ -580,7 +587,7 @@ class boss_professor_putricide : public CreatureScript EnterEvadeMode(); break; case EVENT_FESTERGUT_GOO: - me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); events.ScheduleEvent(EVENT_FESTERGUT_GOO, (Is25ManRaid() ? 10000 : 30000) + urand(0, 5000), 0, PHASE_FESTERGUT); break; case EVENT_ROTFACE_DIES: @@ -881,20 +888,9 @@ class spell_putricide_ooze_channel : public SpellScriptLoader { PrepareSpellScript(spell_putricide_ooze_channel_SpellScript); - public: - spell_putricide_ooze_channel_SpellScript() - { - _target = nullptr; - } - - private: bool Validate(SpellInfo const* spell) override { - if (!spell->ExcludeTargetAuraSpell) - return false; - if (!sSpellMgr->GetSpellInfo(spell->ExcludeTargetAuraSpell)) - return false; - return true; + return ValidateSpellInfo({ spell->ExcludeTargetAuraSpell }); } // set up initial variables and check if caster is creature @@ -942,7 +938,7 @@ class spell_putricide_ooze_channel : public SpellScriptLoader AfterHit += SpellHitFn(spell_putricide_ooze_channel_SpellScript::StartAttack); } - WorldObject* _target; + WorldObject* _target = nullptr; }; SpellScript* GetSpellScript() const override @@ -1041,7 +1037,7 @@ class spell_putricide_unstable_experiment : public SpellScriptLoader uint32 stage = creature->AI()->GetData(DATA_EXPERIMENT_STAGE); creature->AI()->SetData(DATA_EXPERIMENT_STAGE, stage ^ true); - Creature* target = NULL; + Creature* target = nullptr; std::list creList; GetCreatureListWithEntryInGrid(creList, GetCaster(), NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 200.0f); // 2 of them are spawned at green place - weird trick blizz @@ -1112,10 +1108,7 @@ class spell_putricide_ooze_tank_protection : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell) || - !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell, spellInfo->Effects[EFFECT_1].TriggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1157,7 +1150,7 @@ class spell_putricide_choking_gas_bomb : public SpellScriptLoader continue; uint32 spellId = uint32(GetSpellInfo()->Effects[i].CalcValue()); - GetCaster()->CastSpell(GetCaster(), spellId, true, NULL, NULL, GetCaster()->GetGUID()); + GetCaster()->CastSpell(GetCaster(), spellId, true, nullptr, nullptr, GetCaster()->GetGUID()); } } @@ -1184,11 +1177,7 @@ class spell_putricide_unbound_plague : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE_SEARCHER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNBOUND_PLAGUE, SPELL_UNBOUND_PLAGUE_SEARCHER }); } void FilterTargets(std::list& targets) @@ -1332,7 +1321,7 @@ class spell_putricide_mutated_plague : public SpellScriptLoader damage *= int32(pow(multiplier, GetStackAmount())); damage = int32(damage * 1.5f); - GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, nullptr, aurEff, GetCasterGUID()); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1344,7 +1333,7 @@ class spell_putricide_mutated_plague : public SpellScriptLoader return; int32 heal = healSpellInfo->Effects[0].CalcValue() * GetStackAmount(); - GetTarget()->CastCustomSpell(healSpell, SPELLVALUE_BASE_POINT0, heal, GetTarget(), true, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(healSpell, SPELLVALUE_BASE_POINT0, heal, GetTarget(), true, nullptr, nullptr, GetCasterGUID()); } void Register() override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp index 21cb420cc5a..337bdc560b4 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp @@ -15,12 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" // KNOWN BUGS: // ~ No Slime Spray animation directly at target spot @@ -469,7 +473,7 @@ class spell_rotface_ooze_flood : public SpellScriptLoader return; triggers.sort(Trinity::ObjectDistanceOrderPred(GetHitUnit())); - GetHitUnit()->CastSpell(triggers.back(), uint32(GetEffectValue()), false, NULL, NULL, GetOriginalCaster() ? GetOriginalCaster()->GetGUID() : ObjectGuid::Empty); + GetHitUnit()->CastSpell(triggers.back(), uint32(GetEffectValue()), false, nullptr, nullptr, GetOriginalCaster() ? GetOriginalCaster()->GetGUID() : ObjectGuid::Empty); } void FilterTargets(std::list& targets) @@ -540,9 +544,7 @@ class spell_rotface_mutated_infection : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_2].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_2].CalcValue()) }); } void HandleEffectRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -676,7 +678,7 @@ class spell_rotface_large_ooze_buff_combine : public SpellScriptLoader if (Creature* cre = GetCaster()->ToCreature()) cre->AI()->DoAction(EVENT_STICKY_OOZE); - GetCaster()->CastSpell(GetCaster(), SPELL_UNSTABLE_OOZE_EXPLOSION, false, NULL, NULL, GetCaster()->GetGUID()); + GetCaster()->CastSpell(GetCaster(), SPELL_UNSTABLE_OOZE_EXPLOSION, false, nullptr, nullptr, GetCaster()->GetGUID()); if (InstanceScript* instance = GetCaster()->GetInstanceScript()) instance->SetData(DATA_OOZE_DANCE_ACHIEVEMENT, uint32(false)); } @@ -708,9 +710,7 @@ class spell_rotface_unstable_ooze_explosion_init : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER }); } void HandleCast(SpellEffIndex effIndex) @@ -759,7 +759,7 @@ class spell_rotface_unstable_ooze_explosion : public SpellScriptLoader // let Rotface handle the cast - caster dies before this executes if (InstanceScript* script = GetCaster()->GetInstanceScript()) if (Creature* rotface = script->instance->GetCreature(script->GetGuidData(DATA_ROTFACE))) - rotface->CastSpell(x, y, z, triggered_spell_id, true, NULL, NULL, GetCaster()->GetGUID()); + rotface->CastSpell(x, y, z, triggered_spell_id, true, nullptr, nullptr, GetCaster()->GetGUID()); } void Register() override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp index bed297de5c8..36574c9e812 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp @@ -15,12 +15,19 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -187,7 +194,7 @@ class FrostBombExplosion : public BasicEvent bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override { - _owner->CastSpell((Unit*)NULL, SPELL_FROST_BOMB, false, NULL, NULL, _sindragosaGUID); + _owner->CastSpell((Unit*)nullptr, SPELL_FROST_BOMB, false, nullptr, nullptr, _sindragosaGUID); _owner->RemoveAurasDueToSpell(SPELL_FROST_BOMB_VISUAL); return true; } @@ -363,7 +370,7 @@ class boss_sindragosa : public CreatureScript events.ScheduleEvent(EVENT_AIR_MOVEMENT, 1); break; case POINT_AIR_PHASE: - me->CastCustomSpell(SPELL_ICE_TOMB_TARGET, SPELLVALUE_MAX_TARGETS, RAID_MODE(2, 5, 2, 6), NULL, TRIGGERED_FULL_MASK); + me->CastCustomSpell(SPELL_ICE_TOMB_TARGET, SPELLVALUE_MAX_TARGETS, RAID_MODE(2, 5, 2, 6), nullptr, TRIGGERED_FULL_MASK); me->SetFacingTo(float(M_PI), true); events.ScheduleEvent(EVENT_AIR_MOVEMENT_FAR, 1); events.ScheduleEvent(EVENT_FROST_BOMB, 9000); @@ -1063,12 +1070,7 @@ class spell_sindragosa_s_fury : public SpellScriptLoader bool Load() override { // This script should execute only in Icecrown Citadel - if (InstanceMap* instance = GetCaster()->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(ICCScriptName)) - return true; - - return false; + return InstanceHasScript(GetCaster(), ICCScriptName); } void SelectDest() @@ -1237,15 +1239,13 @@ class spell_sindragosa_instability : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BACKLASH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BACKLASH }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE) - GetTarget()->CastCustomSpell(SPELL_BACKLASH, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_BACKLASH, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -1271,9 +1271,7 @@ class spell_sindragosa_frost_beacon : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_TOMB_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_TOMB_DAMAGE }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -1327,7 +1325,7 @@ class spell_sindragosa_ice_tomb : public SpellScriptLoader { summon->AI()->SetGUID(GetTarget()->GetGUID(), DATA_TRAPPED_PLAYER); GetTarget()->CastSpell(GetTarget(), SPELL_ICE_TOMB_UNTARGETABLE); - if (GameObject* go = summon->SummonGameObject(GO_ICE_BLOCK, pos, G3D::Quat(), 0)) + if (GameObject* go = summon->SummonGameObject(GO_ICE_BLOCK, pos, QuaternionData(), 0)) { go->SetSpellId(SPELL_ICE_TOMB_DAMAGE); summon->AddGameObject(go); @@ -1366,9 +1364,7 @@ class spell_sindragosa_icy_grip : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICY_GRIP_JUMP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICY_GRIP_JUMP }); } void HandleScript(SpellEffIndex effIndex) @@ -1440,9 +1436,7 @@ class spell_rimefang_icy_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICY_BLAST_AREA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICY_BLAST_AREA }); } void HandleTriggerMissile(SpellEffIndex effIndex) @@ -1492,9 +1486,7 @@ class spell_frostwarden_handler_order_whelp : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FOCUS_FIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FOCUS_FIRE }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp index e5736894b4c..b219ded2afd 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp @@ -15,19 +15,22 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Spell.h" -#include "Vehicle.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CreatureTextMgr.h" +#include "DBCStores.h" +#include "GridNotifiersImpl.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" +#include "Weather.h" enum Texts { @@ -469,7 +472,7 @@ class VileSpiritActivateEvent : public BasicEvent { _owner->SetReactState(REACT_AGGRESSIVE); _owner->CastSpell(_owner, SPELL_VILE_SPIRIT_MOVE_SEARCH, true); - _owner->CastSpell((Unit*)NULL, SPELL_VILE_SPIRIT_DAMAGE_SEARCH, true); + _owner->CastSpell((Unit*)nullptr, SPELL_VILE_SPIRIT_DAMAGE_SEARCH, true); return true; } @@ -487,7 +490,7 @@ class TriggerWickedSpirit : public BasicEvent bool Execute(uint64 /*time*/, uint32 /*diff*/) override { - _owner->CastCustomSpell(SPELL_TRIGGER_VILE_SPIRIT_HEROIC, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + _owner->CastCustomSpell(SPELL_TRIGGER_VILE_SPIRIT_HEROIC, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); if (--_counter) { @@ -623,8 +626,8 @@ class boss_the_lich_king : public CreatureScript me->GetMap()->SetZoneOverrideLight(AREA_ICECROWN_CITADEL, 0, 5000); break; case ACTION_BREAK_FROSTMOURNE: - me->CastSpell((Unit*)NULL, SPELL_SUMMON_BROKEN_FROSTMOURNE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); - me->CastSpell((Unit*)NULL, SPELL_SUMMON_BROKEN_FROSTMOURNE_2, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_BROKEN_FROSTMOURNE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_BROKEN_FROSTMOURNE_2, TRIGGERED_IGNORE_CAST_IN_PROGRESS); SetEquipmentSlots(false, EQUIP_BROKEN_FROSTMOURNE); events.ScheduleEvent(EVENT_OUTRO_TALK_6, 2500, 0, PHASE_OUTRO); break; @@ -706,7 +709,7 @@ class boss_the_lich_king : public CreatureScript summons.DespawnAll(); me->GetMap()->SetZoneMusic(AREA_ICECROWN_CITADEL, MUSIC_FURY_OF_FROSTMOURNE); me->InterruptNonMeleeSpells(true); - me->CastSpell((Unit*)NULL, SPELL_FURY_OF_FROSTMOURNE, TRIGGERED_NONE); + me->CastSpell((Unit*)nullptr, SPELL_FURY_OF_FROSTMOURNE, TRIGGERED_NONE); me->SetWalk(true); events.ScheduleEvent(EVENT_OUTRO_TALK_1, 2600, 0, PHASE_OUTRO); events.ScheduleEvent(EVENT_OUTRO_EMOTE_TALK, 6600, 0, PHASE_OUTRO); @@ -753,7 +756,7 @@ class boss_the_lich_king : public CreatureScript break; case NPC_FROSTMOURNE_TRIGGER: { - summon->CastSpell((Unit*)NULL, SPELL_BROKEN_FROSTMOURNE, true); + summon->CastSpell((Unit*)nullptr, SPELL_BROKEN_FROSTMOURNE, true); me->GetMap()->SetZoneOverrideLight(AREA_ICECROWN_CITADEL, LIGHT_SOULSTORM, 10000); me->GetMap()->SetZoneWeather(AREA_ICECROWN_CITADEL, WEATHER_STATE_BLACKSNOW, 0.5f); @@ -1064,7 +1067,7 @@ class boss_the_lich_king : public CreatureScript } break; case EVENT_FROSTMOURNE_HEROIC: - if (TempSummon* terenas = me->GetMap()->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE_H, TerenasSpawnHeroic, NULL, 50000)) + if (TempSummon* terenas = me->GetMap()->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE_H, TerenasSpawnHeroic, nullptr, 50000)) { terenas->AI()->DoAction(ACTION_FROSTMOURNE_INTRO); std::list triggers; @@ -1116,11 +1119,11 @@ class boss_the_lich_king : public CreatureScript Talk(SAY_LK_OUTRO_6); if (Creature* tirion = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HIGHLORD_TIRION_FORDRING))) tirion->SetFacingToObject(me); - me->CastSpell((Unit*)NULL, SPELL_SUMMON_BROKEN_FROSTMOURNE_3, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_BROKEN_FROSTMOURNE_3, TRIGGERED_IGNORE_CAST_IN_PROGRESS); SetEquipmentSlots(false, EQUIP_UNEQUIP); break; case EVENT_OUTRO_SOUL_BARRAGE: - me->CastSpell((Unit*)NULL, SPELL_SOUL_BARRAGE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SOUL_BARRAGE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); sCreatureTextMgr->SendSound(me, SOUND_PAIN, CHAT_MSG_MONSTER_YELL, 0, TEXT_RANGE_NORMAL, TEAM_OTHER, false); // set flight me->SetDisableGravity(true); @@ -1690,7 +1693,7 @@ class npc_strangulate_vehicle : public CreatureScript { if (Unit* summoner = summ->GetSummoner()) { - summoner->CastSpell((Unit*)NULL, SPELL_HARVEST_SOUL_VISUAL, true); + summoner->CastSpell((Unit*)nullptr, SPELL_HARVEST_SOUL_VISUAL, true); summoner->ExitVehicle(summoner); if (!IsHeroic()) summoner->CastSpell(summoner, SPELL_HARVEST_SOUL_TELEPORT, true); @@ -1772,7 +1775,7 @@ class npc_terenas_menethil : public CreatureScript } break; case ACTION_TELEPORT_BACK: - me->CastSpell((Unit*)NULL, SPELL_RESTORE_SOUL, TRIGGERED_NONE); + me->CastSpell((Unit*)nullptr, SPELL_RESTORE_SOUL, TRIGGERED_NONE); me->DespawnOrUnsummon(3000); break; default: @@ -1802,7 +1805,7 @@ class npc_terenas_menethil : public CreatureScript _events.ScheduleEvent(EVENT_TELEPORT_BACK, 1000); if (Creature* warden = me->FindNearestCreature(NPC_SPIRIT_WARDEN, 20.0f)) { - warden->CastSpell((Unit*)NULL, SPELL_DESTROY_SOUL, TRIGGERED_NONE); + warden->CastSpell((Unit*)nullptr, SPELL_DESTROY_SOUL, TRIGGERED_NONE); warden->DespawnOrUnsummon(2000); } @@ -1860,7 +1863,7 @@ class npc_terenas_menethil : public CreatureScript case EVENT_DESTROY_SOUL: me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Creature* warden = me->FindNearestCreature(NPC_SPIRIT_WARDEN, 20.0f)) - warden->CastSpell((Unit*)NULL, SPELL_DESTROY_SOUL, TRIGGERED_NONE); + warden->CastSpell((Unit*)nullptr, SPELL_DESTROY_SOUL, TRIGGERED_NONE); DoCast(SPELL_TERENAS_LOSES_INSIDE); _events.ScheduleEvent(EVENT_TELEPORT_BACK, 1000); break; @@ -2112,9 +2115,7 @@ class spell_the_lich_king_necrotic_plague : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NECROTIC_PLAGUE_JUMP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NECROTIC_PLAGUE_JUMP }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2132,7 +2133,7 @@ class spell_the_lich_king_necrotic_plague : public SpellScriptLoader CustomSpellValues values; //values.AddSpellMod(SPELLVALUE_AURA_STACK, 2); values.AddSpellMod(SPELLVALUE_MAX_TARGETS, 1); - GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, NULL, TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, nullptr, TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_PLAGUE_SIPHON, true); } @@ -2228,7 +2229,7 @@ class spell_the_lich_king_necrotic_plague_jump : public SpellScriptLoader CustomSpellValues values; values.AddSpellMod(SPELLVALUE_AURA_STACK, GetStackAmount()); - GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, NULL, TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, nullptr, TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_PLAGUE_SIPHON, true); } @@ -2247,7 +2248,7 @@ class spell_the_lich_king_necrotic_plague_jump : public SpellScriptLoader CustomSpellValues values; values.AddSpellMod(SPELLVALUE_AURA_STACK, GetStackAmount()); values.AddSpellMod(SPELLVALUE_BASE_POINT1, AURA_REMOVE_BY_ENEMY_SPELL); // add as marker (spell has no effect 1) - GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, NULL, TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, nullptr, TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_PLAGUE_SIPHON, true); @@ -2317,7 +2318,7 @@ class spell_the_lich_king_shadow_trap_periodic : public SpellScriptLoader if (targets.empty()) return; - GetCaster()->CastSpell((Unit*)NULL, SPELL_SHADOW_TRAP_KNOCKBACK, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SHADOW_TRAP_KNOCKBACK, true); } void Register() override @@ -2343,7 +2344,7 @@ class spell_the_lich_king_quake : public SpellScriptLoader bool Load() override { - return GetCaster()->GetInstanceScript() != NULL; + return GetCaster()->GetInstanceScript() != nullptr; } void FilterTargets(std::list& targets) @@ -2382,9 +2383,7 @@ class spell_the_lich_king_ice_burst_target_search : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_BURST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_BURST }); } void CheckTargetCount(std::list& unitList) @@ -2540,9 +2539,7 @@ class spell_the_lich_king_soul_reaper : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOUL_REAPER_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SOUL_REAPER_BUFF }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -2572,18 +2569,9 @@ class spell_the_lich_king_valkyr_target_search : public SpellScriptLoader { PrepareSpellScript(spell_the_lich_king_valkyr_target_search_SpellScript); - public: - spell_the_lich_king_valkyr_target_search_SpellScript() - { - _target = nullptr; - } - - private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHARGE }); } void SelectTarget(std::list& targets) @@ -2621,7 +2609,7 @@ class spell_the_lich_king_valkyr_target_search : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_the_lich_king_valkyr_target_search_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } - WorldObject* _target; + WorldObject* _target = nullptr; }; SpellScript* GetSpellScript() const override @@ -2667,9 +2655,7 @@ class spell_the_lich_king_life_siphon : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LIFE_SIPHON_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LIFE_SIPHON_HEAL }); } void TriggerHeal() @@ -2714,7 +2700,7 @@ class spell_the_lich_king_vile_spirits : public SpellScriptLoader void OnPeriodic(AuraEffect const* aurEff) { if (_is25Man || ((aurEff->GetTickNumber() - 1) % 5)) - GetTarget()->CastSpell((Unit*)NULL, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastSpell((Unit*)nullptr, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -2837,7 +2823,7 @@ class spell_the_lich_king_vile_spirit_damage_target_search : public SpellScriptL if (TempSummon* summon = GetCaster()->ToTempSummon()) if (Unit* summoner = summon->GetSummoner()) summoner->GetAI()->SetData(DATA_VILE, 1); - GetCaster()->CastSpell((Unit*)NULL, SPELL_SPIRIT_BURST, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SPIRIT_BURST, true); GetCaster()->ToCreature()->DespawnOrUnsummon(3000); GetCaster()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } @@ -2865,14 +2851,14 @@ class spell_the_lich_king_harvest_soul : public SpellScriptLoader bool Load() override { - return GetOwner()->GetInstanceScript() != NULL; + return GetOwner()->GetInstanceScript() != nullptr; } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { // m_originalCaster to allow stacking from different casters, meh if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_DEATH) - GetTarget()->CastSpell((Unit*)NULL, SPELL_HARVESTED_SOUL, true, NULL, NULL, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_HARVESTED_SOUL, true, nullptr, nullptr, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); } void Register() override @@ -2938,7 +2924,7 @@ class spell_the_lich_king_soul_rip : public SpellScriptLoader PreventDefaultAction(); // shouldn't be needed, this is channeled if (Unit* caster = GetCaster()) - caster->CastCustomSpell(SPELL_SOUL_RIP_DAMAGE, SPELLVALUE_BASE_POINT0, 5000 * aurEff->GetTickNumber(), GetTarget(), true, NULL, aurEff, GetCasterGUID()); + caster->CastCustomSpell(SPELL_SOUL_RIP_DAMAGE, SPELLVALUE_BASE_POINT0, 5000 * aurEff->GetTickNumber(), GetTarget(), true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -2972,7 +2958,7 @@ class spell_the_lich_king_restore_soul : public SpellScriptLoader bool Load() override { _instance = GetCaster()->GetInstanceScript(); - return _instance != NULL; + return _instance != nullptr; } void HandleScript(SpellEffIndex /*effIndex*/) @@ -3024,9 +3010,7 @@ class spell_the_lich_king_dark_hunger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DARK_HUNGER_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DARK_HUNGER_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3063,14 +3047,14 @@ class spell_the_lich_king_in_frostmourne_room : public SpellScriptLoader bool Load() override { - return GetOwner()->GetInstanceScript() != NULL; + return GetOwner()->GetInstanceScript() != nullptr; } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { // m_originalCaster to allow stacking from different casters, meh if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_DEATH) - GetTarget()->CastSpell((Unit*)NULL, SPELL_HARVESTED_SOUL, true, NULL, NULL, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_HARVESTED_SOUL, true, nullptr, nullptr, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); } void Register() override @@ -3097,7 +3081,7 @@ class spell_the_lich_king_summon_spirit_bomb : public SpellScriptLoader void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); - GetHitUnit()->CastSpell((Unit*)NULL, uint32(GetEffectValue()), true); + GetHitUnit()->CastSpell((Unit*)nullptr, uint32(GetEffectValue()), true); } void Register() override @@ -3155,7 +3139,7 @@ class spell_the_lich_king_jump : public SpellScriptLoader { PreventHitDefaultEffect(effIndex); GetHitUnit()->RemoveAurasDueToSpell(SPELL_RAISE_DEAD); - GetHitUnit()->CastSpell((Unit*)NULL, SPELL_JUMP_2, true); + GetHitUnit()->CastSpell((Unit*)nullptr, SPELL_JUMP_2, true); if (Creature* creature = GetHitCreature()) creature->AI()->DoAction(ACTION_BREAK_FROSTMOURNE); } diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp index 867fc1ae688..c558aa47d52 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp @@ -15,15 +15,17 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Texts { @@ -684,7 +686,7 @@ class npc_the_lich_king_controller : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1265,9 +1267,7 @@ class spell_dreamwalker_summon_suppresser : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SUPPRESSER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SUPPRESSER }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp index 6a56da6e902..789370d8762 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp @@ -15,18 +15,20 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "PassiveAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "SpellAuraEffects.h" -#include "SmartAI.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "ScriptedEscortAI.h" +#include "SmartAI.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "VehicleDefines.h" // Weekly quest support // * Deprogramming (DONE) @@ -731,7 +733,7 @@ class npc_alchemist_adrianna : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_alchemist_adriannaAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1119,7 +1121,7 @@ class npc_crok_scourgebane : public CreatureScript if (!_wipeCheckTimer) { _wipeCheckTimer = 1000; - Player* player = NULL; + Player* player = nullptr; Trinity::AnyPlayerInObjectRangeCheck check(me, 60.0f); Trinity::PlayerSearcher searcher(me, player, check); Cell::VisitWorldObjects(me, searcher, 60.0f); @@ -1433,7 +1435,7 @@ class npc_captain_arnath : public CreatureScript private: Creature* FindFriendlyCreature() const { - Creature* target = NULL; + Creature* target = nullptr; Trinity::MostHPMissingInRange u_check(me, 60.0f, 0); Trinity::CreatureLastSearcher searcher(me, target, u_check); Cell::VisitGridObjects(me, searcher, 60.0f); @@ -1674,7 +1676,7 @@ class npc_frostwing_vrykul : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_frostwing_vrykulAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1718,7 +1720,7 @@ class npc_impaling_spear : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_impaling_spearAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1768,7 +1770,7 @@ class npc_arthas_teleport_visual : public CreatureScript return GetIcecrownCitadelAI(creature); // Default to no script - return NULL; + return nullptr; } }; @@ -2107,6 +2109,49 @@ class spell_icc_soul_missile : public SpellScriptLoader } }; +class spell_trigger_spell_from_caster_SpellScript : public SpellScript +{ + PrepareSpellScript(spell_trigger_spell_from_caster_SpellScript); + + public: + spell_trigger_spell_from_caster_SpellScript(uint32 triggerId, TriggerCastFlags triggerFlags) + : SpellScript(), _triggerId(triggerId), _triggerFlags(triggerFlags) { } + + private: + bool Validate(SpellInfo const* /*spell*/) override + { + return ValidateSpellInfo({ _triggerId }); + } + + void HandleTrigger() + { + GetCaster()->CastSpell(GetHitUnit(), _triggerId, _triggerFlags); + } + + void Register() override + { + AfterHit += SpellHitFn(spell_trigger_spell_from_caster_SpellScript::HandleTrigger); + } + + uint32 _triggerId; + TriggerCastFlags _triggerFlags; +}; + +spell_trigger_spell_from_caster::spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId) + : SpellScriptLoader(scriptName), _triggerId(triggerId), _triggerFlags(TRIGGERED_FULL_MASK) +{ +} + +spell_trigger_spell_from_caster::spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId, TriggerCastFlags triggerFlags) + : SpellScriptLoader(scriptName), _triggerId(triggerId), _triggerFlags(triggerFlags) +{ +} + +SpellScript* spell_trigger_spell_from_caster::GetSpellScript() const +{ + return new spell_trigger_spell_from_caster_SpellScript(_triggerId, _triggerFlags); +} + class at_icc_saurfang_portal : public AreaTriggerScript { public: diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h index 8607714ff9c..e40ba687312 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h @@ -18,7 +18,11 @@ #ifndef ICECROWN_CITADEL_H_ #define ICECROWN_CITADEL_H_ -#include "SpellScript.h" +#include "CreatureAIImpl.h" +#include "ScriptMgr.h" + +struct Position; +enum TriggerCastFlags : uint32; #define ICCScriptName "instance_icecrown_citadel" #define DataHeader "IC" @@ -527,49 +531,16 @@ enum ICAreaIds class spell_trigger_spell_from_caster : public SpellScriptLoader { public: - spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId, TriggerCastFlags triggerFlags = TRIGGERED_FULL_MASK) - : SpellScriptLoader(scriptName), _triggerId(triggerId), _triggerFlags(triggerFlags) { } - - class spell_trigger_spell_from_caster_SpellScript : public SpellScript - { - PrepareSpellScript(spell_trigger_spell_from_caster_SpellScript); - - public: - spell_trigger_spell_from_caster_SpellScript(uint32 triggerId, TriggerCastFlags triggerFlags) - : SpellScript(), _triggerId(triggerId), _triggerFlags(triggerFlags) { } - - bool Validate(SpellInfo const* /*spell*/) override - { - if (!sSpellMgr->GetSpellInfo(_triggerId)) - return false; - return true; - } - - void HandleTrigger() - { - GetCaster()->CastSpell(GetHitUnit(), _triggerId, _triggerFlags); - } - - void Register() override - { - AfterHit += SpellHitFn(spell_trigger_spell_from_caster_SpellScript::HandleTrigger); - } - - uint32 _triggerId; - TriggerCastFlags _triggerFlags; - }; - - SpellScript* GetSpellScript() const override - { - return new spell_trigger_spell_from_caster_SpellScript(_triggerId, _triggerFlags); - } + spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId, TriggerCastFlags triggerFlags); + spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId); + SpellScript* GetSpellScript() const override; private: uint32 _triggerId; TriggerCastFlags _triggerFlags; }; -template +template inline AI* GetIcecrownCitadelAI(T* obj) { return GetInstanceAI(obj, ICCScriptName); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp index 571de70bc0a..d9158249649 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp @@ -15,13 +15,15 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "icecrown_citadel.h" #include "InstanceScript.h" #include "Player.h" #include "ScriptedGossip.h" -#include "ScriptMgr.h" #include "Spell.h" -#include "icecrown_citadel.h" +#include "SpellMgr.h" static std::vector const TeleportSpells = { diff --git a/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp index 4f14a49cf49..37baf7afe8d 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp @@ -15,17 +15,19 @@ * with this program. If not, see . */ -#include "AccountMgr.h" +#include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "CreatureAI.h" +#include "icecrown_citadel.h" #include "InstanceScript.h" +#include "Map.h" #include "ObjectMgr.h" #include "Player.h" #include "PoolMgr.h" -#include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "Transport.h" #include "TransportMgr.h" #include "WorldPacket.h" -#include "icecrown_citadel.h" enum EventIds { @@ -184,7 +186,7 @@ class instance_icecrown_citadel : public InstanceMapScript { if (!TeamInInstance) { - Map::PlayerList const &players = instance->GetPlayers(); + Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) if (Player* player = players.begin()->GetSource()) TeamInInstance = player->GetTeam(); @@ -1301,12 +1303,12 @@ class instance_icecrown_citadel : public InstanceMapScript teleporter->SetGoState(GO_STATE_ACTIVE); std::list stalkers; - GetCreatureListWithEntryInGrid(stalkers, teleporter, NPC_INVISIBLE_STALKER, 100.0f); + teleporter->GetCreatureListWithEntryInGrid(stalkers, NPC_INVISIBLE_STALKER, 100.0f); if (stalkers.empty()) return; stalkers.sort(Trinity::ObjectDistanceOrderPred(teleporter)); - stalkers.front()->CastSpell((Unit*)NULL, SPELL_ARTHAS_TELEPORTER_CEREMONY, false); + stalkers.front()->CastSpell((Unit*)nullptr, SPELL_ARTHAS_TELEPORTER_CEREMONY, false); stalkers.pop_front(); for (std::list::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr) (*itr)->AI()->Reset(); @@ -1443,11 +1445,11 @@ class instance_icecrown_citadel : public InstanceMapScript } break; case EVENT_TELEPORT_TO_FROSTMOURNE: // Harvest Soul (normal mode) - if (Creature* terenas = instance->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE, TerenasSpawn, NULL, 63000)) + if (Creature* terenas = instance->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE, TerenasSpawn, nullptr, 63000)) { terenas->AI()->DoAction(ACTION_FROSTMOURNE_INTRO); std::list triggers; - GetCreatureListWithEntryInGrid(triggers, terenas, NPC_WORLD_TRIGGER_INFINITE_AOI, 100.0f); + terenas->GetCreatureListWithEntryInGrid(triggers, NPC_WORLD_TRIGGER_INFINITE_AOI, 100.0f); if (!triggers.empty()) { triggers.sort(Trinity::ObjectDistanceOrderPred(terenas, false)); @@ -1455,7 +1457,7 @@ class instance_icecrown_citadel : public InstanceMapScript visual->CastSpell(visual, SPELL_FROSTMOURNE_TELEPORT_VISUAL, true); } - if (Creature* warden = instance->SummonCreature(NPC_SPIRIT_WARDEN, SpiritWardenSpawn, NULL, 63000)) + if (Creature* warden = instance->SummonCreature(NPC_SPIRIT_WARDEN, SpiritWardenSpawn, nullptr, 63000)) { terenas->AI()->AttackStart(warden); warden->AddThreat(terenas, 300000.0f); diff --git a/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp b/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp index 005abab81a4..7918fae1f77 100644 --- a/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp +++ b/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp @@ -16,13 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PassiveAI.h" #include "BattlegroundIC.h" +#include "GameObject.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "Player.h" -#include "Vehicle.h" -#include "SpellScript.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellScript.h" +#include "Vehicle.h" // TO-DO: This should be done with SmartAI, but yet it does not correctly support vehicles's AIs. // Even adding ReactState Passive we still have issues using SmartAI. @@ -115,8 +119,8 @@ class npc_ioc_gunship_captain : public CreatureScript DoCast(me, SPELL_TELEPORT_VISUAL_ONLY); break; case EVENT_DESPAWN: - if (me->GetMap()->ToBattlegroundMap()) - if (Battleground* bgIoC = me->GetMap()->ToBattlegroundMap()->GetBG()) + if (BattlegroundMap* iocMap = me->GetMap()->ToBattlegroundMap()) + if (Battleground* bgIoC = iocMap->GetBG()) bgIoC->DelCreature(BG_IC_NPC_GUNSHIP_CAPTAIN_1); break; default: @@ -278,9 +282,7 @@ class spell_ioc_seaforium_blast_credit : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_A_BOMB_INABLE_CREDIT) || !sSpellMgr->GetSpellInfo(SPELL_A_BOMB_INATION_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_A_BOMB_INABLE_CREDIT, SPELL_A_BOMB_INATION_CREDIT }); } void HandleAchievementCredit(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp b/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp index 371b250358b..5454ff7c848 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "naxxramas.h" +#include "Player.h" +#include "ScriptedCreature.h" enum AnubSays { @@ -79,7 +81,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct boss_anubrekhanAI : public BossAI diff --git a/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp b/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp index 2814a504b17..da3d95a5173 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "naxxramas.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellAuras.h" -#include "SpellInfo.h" enum Yells { @@ -190,7 +191,7 @@ class boss_faerlina : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_faerlinaAI(creature); + return GetNaxxramasAI(creature); } }; @@ -244,7 +245,7 @@ class npc_faerlina_add : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp b/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp index c38f388d01b..597471597dd 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp @@ -15,13 +15,18 @@ * with this program. If not, see . */ -#include "Player.h" -#include "GameTime.h" #include "ScriptMgr.h" +#include "GameTime.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "naxxramas.h" +#include "SpellScript.h" enum Horseman { @@ -210,7 +215,7 @@ struct boss_four_horsemen_baseAI : public BossAI return; } instance->SetBossState(BOSS_HORSEMEN, IN_PROGRESS); - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); if (players.isEmpty()) // sanity check ResetEncounter(); @@ -378,7 +383,7 @@ struct boss_four_horsemen_baseAI : public BossAI private: const Horseman _which; - const Position* _initialPath; + Position const* _initialPath; bool _myMovementFinished; uint8 _nextMovement; uint32 _timeDied; @@ -455,7 +460,7 @@ class boss_four_horsemen_baron : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -537,7 +542,7 @@ class boss_four_horsemen_thane : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -607,7 +612,7 @@ class boss_four_horsemen_lady : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -689,7 +694,7 @@ class boss_four_horsemen_sir : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp index 1d2dd84f119..42fbac5ff86 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellScript.h" -#include enum Texts { @@ -94,7 +96,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct boss_gluthAI : public BossAI @@ -192,7 +194,7 @@ public: Creature* zombie = nullptr; for (SummonList::const_iterator itr = summons.begin(); !zombie && itr != summons.end(); ++itr) { - zombie=ObjectAccessor::GetCreature(*me, *itr); + zombie = ObjectAccessor::GetCreature(*me, *itr); if (!zombie || !zombie->IsAlive() || !zombie->IsWithinDistInMap(me, 10.0)) zombie = nullptr; } @@ -326,7 +328,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - return (sSpellMgr->GetSpellInfo(SPELL_DECIMATE_DMG) != nullptr); + return ValidateSpellInfo({ SPELL_DECIMATE_DMG }); } void Register() override @@ -473,7 +475,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp index 9fcb35b269b..c09de96f7b6 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "GridNotifiers.h" -#include "CombatAI.h" #include "AreaBoundary.h" +#include "CombatAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" /* Constants */ enum Yells @@ -558,7 +562,7 @@ class boss_gothik : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -665,7 +669,7 @@ class npc_gothik_minion_livingtrainee : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -694,7 +698,7 @@ class npc_gothik_minion_livingknight : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -724,7 +728,7 @@ class npc_gothik_minion_livingrider : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -753,7 +757,7 @@ class npc_gothik_minion_spectraltrainee : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -782,7 +786,7 @@ class npc_gothik_minion_spectralknight : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -847,7 +851,7 @@ class npc_gothik_minion_spectralrider : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -876,7 +880,7 @@ class npc_gothik_minion_spectralhorse : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -887,7 +891,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct npc_gothik_triggerAI : public ScriptedAI diff --git a/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp b/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp index 914db8461d4..626a7c023af 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp @@ -107,7 +107,7 @@ class boss_grobbulus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_grobbulusAI(creature); + return GetNaxxramasAI(creature); } }; @@ -135,7 +135,7 @@ class npc_grobbulus_poison_cloud : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_grobbulus_poison_cloudAI(creature); + return GetNaxxramasAI(creature); } }; @@ -151,10 +151,7 @@ class spell_grobbulus_mutating_injection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MUTATING_EXPLOSION) - || !sSpellMgr->GetSpellInfo(SPELL_POISON_CLOUD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MUTATING_EXPLOSION, SPELL_POISON_CLOUD }); } void HandleRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -166,7 +163,7 @@ class spell_grobbulus_mutating_injection : public SpellScriptLoader if (Unit* caster = GetCaster()) { caster->CastSpell(GetTarget(), SPELL_MUTATING_EXPLOSION, true); - GetTarget()->CastSpell(GetTarget(), SPELL_POISON_CLOUD, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastSpell(GetTarget(), SPELL_POISON_CLOUD, true, nullptr, aurEff, GetCasterGUID()); } } @@ -194,9 +191,7 @@ class spell_grobbulus_poison_cloud : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void PeriodicTick(AuraEffect const* aurEff) @@ -205,7 +200,7 @@ class spell_grobbulus_poison_cloud : public SpellScriptLoader uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; int32 mod = int32(((float(aurEff->GetTickNumber()) / aurEff->GetTotalTicks()) * 0.9f + 0.1f) * 10000 * 2 / 3); - GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)NULL, TRIGGERED_FULL_MASK, NULL, aurEff); + GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)nullptr, TRIGGERED_FULL_MASK, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp b/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp index de24bff691a..add15715165 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" #include "naxxramas.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" enum Spells { @@ -77,7 +81,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct boss_heiganAI : public BossAI @@ -131,8 +135,8 @@ public: _eruptTiles[section].clear(); for (uint8 i = 0; i < numEruptions[section]; ++i) { - std::pair::const_iterator, std::unordered_multimap::const_iterator> tileIt = mapGOs.equal_range(spawnId++); - for (std::unordered_multimap::const_iterator it = tileIt.first; it != tileIt.second; ++it) + auto tileIt = mapGOs.equal_range(spawnId++); + for (auto it = tileIt.first; it != tileIt.second; ++it) _eruptTiles[section].push_back(it->second->GetGUID()); } } @@ -230,13 +234,13 @@ class spell_heigan_eruption : public SpellScriptLoader void HandleScript(SpellEffIndex /*eff*/) { Unit* caster = GetCaster(); - if (!caster || !GetHitPlayer()) + if (!caster || !GetHitUnit()) return; - if (GetHitDamage() >= int32(GetHitPlayer()->GetHealth())) + if (GetHitDamage() >= int32(GetHitUnit()->GetHealth())) if (InstanceScript* instance = caster->GetInstanceScript()) if (Creature* Heigan = ObjectAccessor::GetCreature(*caster, instance->GetGuidData(DATA_HEIGAN))) - Heigan->AI()->KilledUnit(GetHitPlayer()); + Heigan->AI()->KilledUnit(GetHitUnit()); } void Register() override diff --git a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp index 42c7af5735c..93b91bec9f3 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp @@ -16,11 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "PlayerAI.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -568,7 +574,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -699,7 +705,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -725,7 +731,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -768,7 +774,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -862,7 +868,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -909,9 +915,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MANA_DETONATION_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MANA_DETONATION_DAMAGE }); } void HandleScript(AuraEffect const* aurEff) @@ -922,7 +926,7 @@ public: if (int32 mana = int32(target->GetMaxPower(POWER_MANA) / 10)) { mana = target->ModifyPower(POWER_MANA, -mana); - target->CastCustomSpell(SPELL_MANA_DETONATION_DAMAGE, SPELLVALUE_BASE_POINT0, -mana * 10, target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_MANA_DETONATION_DAMAGE, SPELLVALUE_BASE_POINT0, -mana * 10, target, true, nullptr, aurEff); } } @@ -943,7 +947,7 @@ class at_kelthuzad_center : public AreaTriggerScript public: at_kelthuzad_center() : AreaTriggerScript("at_kelthuzad_center") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { InstanceScript* instance = player->GetInstanceScript(); if (!instance || instance->GetBossState(BOSS_KELTHUZAD) != NOT_STARTED) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp b/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp index 0506d85faa3..57f3e06a90a 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "naxxramas.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "naxxramas.h" enum Spells { @@ -146,7 +147,7 @@ class boss_loatheb : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_loathebAI(creature); + return GetNaxxramasAI(creature); } }; @@ -172,9 +173,7 @@ class spell_loatheb_deathbloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATHBLOOM_FINAL_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEATHBLOOM_FINAL_DAMAGE }); } void AfterRemove(AuraEffect const* eff, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp b/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp index d513a4e1583..1627cba08b9 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "naxxramas.h" enum Spells { @@ -83,7 +87,7 @@ struct WebTargetSelector : public std::unary_function } private: - const Unit* _maexxna; + Unit const* _maexxna; }; class boss_maexxna : public CreatureScript @@ -93,7 +97,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_maexxnaAI(creature); + return GetNaxxramasAI(creature); } struct boss_maexxnaAI : public BossAI @@ -194,7 +198,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_webwrapAI(creature); + return GetNaxxramasAI(creature); } struct npc_webwrapAI : public NullCreatureAI @@ -217,7 +221,7 @@ public: if (Unit* victim = ObjectAccessor::GetUnit(*me, victimGUID)) { visibleTimer = (me->GetDistance2d(victim)/WEB_WRAP_MOVE_SPEED + 0.5f) * IN_MILLISECONDS; - victim->CastSpell(victim, SPELL_WEB_WRAP, true, NULL, NULL, me->GetGUID()); + victim->CastSpell(victim, SPELL_WEB_WRAP, true, nullptr, nullptr, me->GetGUID()); } } diff --git a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp index daf9aba31bc..9394ececc08 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ScriptedCreature.h" enum Phases { @@ -334,7 +335,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp b/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp index 6c5ba318354..92dcdf95da4 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "naxxramas.h" +#include "ScriptedCreature.h" enum Spells { @@ -61,7 +62,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct boss_patchwerkAI : public BossAI @@ -119,8 +120,8 @@ public: // Hateful Strike targets the highest non-MT threat in melee range on 10man // and the higher HP target out of the two highest non-MT threats in melee range on 25man float MostThreat = 0.0f; - Unit* secondThreatTarget = NULL; - Unit* thirdThreatTarget = NULL; + Unit* secondThreatTarget = nullptr; + Unit* thirdThreatTarget = nullptr; std::list::const_iterator i = me->getThreatManager().getThreatList().begin(); for (; i != me->getThreatManager().getThreatList().end(); ++i) @@ -148,7 +149,7 @@ public: } } - Unit* pHatefulTarget = NULL; + Unit* pHatefulTarget = nullptr; if (!thirdThreatTarget) pHatefulTarget = secondThreatTarget; else if (secondThreatTarget) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp b/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp index 51eb68b6eed..4679fb17358 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" -#include "naxxramas.h" enum Yells { @@ -60,7 +63,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_razuviousAI(creature); + return GetNaxxramasAI(creature); } struct boss_razuviousAI : public BossAI @@ -240,7 +243,7 @@ class npc_dk_understudy : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp index 29e0d9f1555..205a098d077 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp @@ -16,12 +16,17 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" -#include "naxxramas.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Yells { @@ -376,7 +381,7 @@ class boss_sapphiron : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_sapphironAI(creature); + return GetNaxxramasAI(creature); } }; @@ -412,7 +417,7 @@ class go_sapphiron_birth : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetNaxxramasAI(go); } }; @@ -486,7 +491,7 @@ class spell_sapphiron_icebolt : public SpellScriptLoader return; float x, y, z; GetTarget()->GetPosition(x, y, z); - if (GameObject* block = GetTarget()->SummonGameObject(GO_ICEBLOCK, x, y, z, 0.f, G3D::Quat(), 25)) + if (GameObject* block = GetTarget()->SummonGameObject(GO_ICEBLOCK, x, y, z, 0.f, QuaternionData(), 25)) _block = block->GetGUID(); } @@ -517,7 +522,7 @@ class spell_sapphiron_summon_blizzard : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return !!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BLIZZARD); + return ValidateSpellInfo({ SPELL_SUMMON_BLIZZARD }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp b/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp index 48459ffd3a6..a74dd052695 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" -#include "ObjectGuid.h" -#include "naxxramas.h" - enum Phases { @@ -164,7 +167,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct boss_thaddiusAI : public BossAI @@ -480,7 +483,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct npc_stalaggAI : public ScriptedAI @@ -748,7 +751,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct npc_feugenAI : public ScriptedAI @@ -1019,7 +1022,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } struct npc_teslaAI : public ScriptedAI @@ -1044,15 +1047,16 @@ class spell_thaddius_polarity_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return ( - sSpellMgr->GetSpellInfo(SPELL_POLARITY_SHIFT) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_AMP) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_AMP) - ); + return ValidateSpellInfo( + { + SPELL_POLARITY_SHIFT, + SPELL_POSITIVE_CHARGE_APPLY, + SPELL_POSITIVE_CHARGE_TICK, + SPELL_POSITIVE_CHARGE_AMP, + SPELL_NEGATIVE_CHARGE_APPLY, + SPELL_NEGATIVE_CHARGE_TICK, + SPELL_NEGATIVE_CHARGE_AMP + }); } void HandleTargets(std::list& targetList) @@ -1143,15 +1147,16 @@ class spell_thaddius_polarity_shift : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return ( - sSpellMgr->GetSpellInfo(SPELL_POLARITY_SHIFT) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_AMP) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_AMP) - ); + return ValidateSpellInfo( + { + SPELL_POLARITY_SHIFT, + SPELL_POSITIVE_CHARGE_APPLY, + SPELL_POSITIVE_CHARGE_TICK, + SPELL_POSITIVE_CHARGE_AMP, + SPELL_NEGATIVE_CHARGE_APPLY, + SPELL_NEGATIVE_CHARGE_TICK, + SPELL_NEGATIVE_CHARGE_AMP + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1195,7 +1200,7 @@ class spell_thaddius_magnetic_pull : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_MAGNETIC_PULL) ? true : false; + return ValidateSpellInfo({ SPELL_MAGNETIC_PULL }); } void HandleCast() // only feugen ever casts this according to wowhead data diff --git a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp index a76284d803b..f8638a33fa0 100644 --- a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp +++ b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp @@ -16,9 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "AreaBoundary.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "TemporarySummon.h" BossBoundaryData const boundaries = { @@ -104,7 +109,7 @@ ObjectData const objectData[] = class instance_naxxramas : public InstanceMapScript { public: - instance_naxxramas() : InstanceMapScript("instance_naxxramas", 533) { } + instance_naxxramas() : InstanceMapScript(NaxxramasScriptName, 533) { } struct instance_naxxramas_InstanceMapScript : public InstanceScript { @@ -490,7 +495,7 @@ class instance_naxxramas : public InstanceMapScript std::list spawns; instance->SummonCreatureGroup(nextFroggerWave, &spawns); if (!spawns.empty()) - (*spawns.begin())->GetMotionMaster()->MovePath(10 * NPC_FROGGER + nextFroggerWave, false); + spawns.front()->GetMotionMaster()->MovePath(10 * NPC_FROGGER + nextFroggerWave, false); events.Repeat(Seconds(1) + Milliseconds(666)); nextFroggerWave = (nextFroggerWave+1) % 3; break; @@ -546,7 +551,7 @@ class instance_naxxramas : public InstanceMapScript return true; } - bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target = NULL*/, uint32 /*miscvalue1 = 0*/) override + bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target = nullptr*/, uint32 /*miscvalue1 = 0*/) override { switch (criteria_id) { diff --git a/src/server/scripts/Northrend/Naxxramas/naxxramas.h b/src/server/scripts/Northrend/Naxxramas/naxxramas.h index e847179ddeb..2813e338245 100644 --- a/src/server/scripts/Northrend/Naxxramas/naxxramas.h +++ b/src/server/scripts/Northrend/Naxxramas/naxxramas.h @@ -18,6 +18,9 @@ #ifndef DEF_NAXXRAMAS_H #define DEF_NAXXRAMAS_H +#include "CreatureAIImpl.h" + +#define NaxxramasScriptName "instance_naxxramas" #define DataHeader "NAX" uint32 const EncounterCount = 15; @@ -215,17 +218,11 @@ enum NAXInstanceTexts SAY_DIALOGUE_SAPPHIRON_LICH_KING2 = 2 }; -/* -template -CreatureAI* GetNaxxramasAI(Creature* creature) -{ - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(NaxxramasScriptName)) - return new AI(creature); - return NULL; +template +inline AI* GetNaxxramasAI(T* obj) +{ + return GetInstanceAI(obj, NaxxramasScriptName); } -*/ #endif diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp b/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp index 7994c5b640d..dcf26afa14b 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp @@ -20,16 +20,22 @@ SDName: Boss Malygos Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "CombatAI.h" +#include "CreatureTextMgr.h" #include "eye_of_eternity.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "CombatAI.h" -#include "GameObjectAI.h" -#include "CreatureTextMgr.h" -#include "MoveSplineInit.h" enum Events { @@ -998,7 +1004,7 @@ public: _JustDied(); Talk(SAY_DEATH); if (Creature* alexstraszaGiftBoxBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_GIFT_BOX_BUNNY_GUID))) - alexstraszaGiftBoxBunny->SummonGameObject(RAID_MODE(GO_HEART_OF_MAGIC_10, GO_HEART_OF_MAGIC_25), HeartOfMagicSpawnPos, G3D::Quat(), 0); + alexstraszaGiftBoxBunny->SummonGameObject(RAID_MODE(GO_HEART_OF_MAGIC_10, GO_HEART_OF_MAGIC_25), HeartOfMagicSpawnPos, QuaternionData(), 0); me->SummonCreature(NPC_ALEXSTRASZA, AlexstraszaSpawnPos, TEMPSUMMON_MANUAL_DESPAWN); me->DespawnOrUnsummon(5*IN_MILLISECONDS); @@ -1027,7 +1033,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1077,7 +1083,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1138,7 +1144,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1249,7 +1255,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1312,7 +1318,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1388,7 +1394,7 @@ class npc_nexus_lord : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1455,7 +1461,7 @@ class npc_scion_of_eternity : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1509,7 +1515,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1574,7 +1580,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_wyrmrest_skytalonAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1600,7 +1606,7 @@ class npc_static_field : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_static_fieldAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1620,10 +1626,7 @@ class spell_malygos_portal_beam : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PORTAL_OPENED)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_PORTAL_OPENED }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1723,10 +1726,7 @@ class spell_malygos_arcane_storm : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ARCANE_STORM_EXTRA_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ARCANE_STORM_EXTRA_VISUAL }); } void FilterTargets(std::list& targets) @@ -1820,10 +1820,7 @@ class spell_malygos_vortex_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VORTEX_1) || !sSpellMgr->GetSpellInfo(SPELL_VORTEX_6)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_VORTEX_1, SPELL_VORTEX_6 }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1842,7 +1839,7 @@ class spell_malygos_vortex_visual : public SpellScriptLoader if (InstanceScript* instance = caster->GetInstanceScript()) { // Teleport spell - I'm not sure but might be it must be cast by each vehicle when it's passenger leaves it. - if (Creature* trigger = caster->GetMap()->GetCreature(instance->GetGuidData(DATA_TRIGGER))) + if (Creature* trigger = ObjectAccessor::GetCreature(*caster, instance->GetGuidData(DATA_TRIGGER))) trigger->CastSpell(targetPlayer, SPELL_VORTEX_6, true); } } @@ -1978,7 +1975,7 @@ class spell_scion_of_eternity_arcane_barrage : public SpellScriptLoader bool Load() override { - return GetCaster()->GetTypeId() == TYPEID_UNIT && GetCaster()->GetInstanceScript() != NULL; + return GetCaster()->GetTypeId() == TYPEID_UNIT && GetCaster()->GetInstanceScript() != nullptr; } void FilterMeleeHoverDiskPassangers(std::list& targets) @@ -2063,10 +2060,7 @@ class spell_malygos_destroy_platform_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DESTROY_PLATFORM_BOOM_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_DESTROY_PLATFORM_BOOM_VISUAL }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2105,10 +2099,7 @@ class spell_alexstrasza_bunny_destroy_platform_boom_visual : public SpellScriptL bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DESTROY_PLATFORM_EVENT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_DESTROY_PLATFORM_EVENT }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2153,7 +2144,7 @@ class spell_alexstrasza_bunny_destroy_platform_event : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { - GetCaster()->CastSpell((Unit*)NULL, SPELL_SUMMON_RED_DRAGON_BUDDY_F_CAST); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SUMMON_RED_DRAGON_BUDDY_F_CAST); } void Register() override @@ -2251,10 +2242,7 @@ class spell_malygos_surge_of_power_warning_selector_25 : public SpellScriptLoade bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SURGE_OF_POWER_PHASE_3_25)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_SURGE_OF_POWER_PHASE_3_25 }); } void SendThreeTargets(std::list& targets) @@ -2285,7 +2273,7 @@ class spell_malygos_surge_of_power_warning_selector_25 : public SpellScriptLoade void ExecuteMainSpell() { - GetCaster()->ToCreature()->CastSpell((Unit*)NULL, SPELL_SURGE_OF_POWER_PHASE_3_25); + GetCaster()->ToCreature()->CastSpell((Unit*)nullptr, SPELL_SURGE_OF_POWER_PHASE_3_25); } void Register() override @@ -2368,10 +2356,7 @@ class spell_alexstrasza_gift_beam : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ALEXSTRASZAS_GIFT_BEAM_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ALEXSTRASZAS_GIFT_BEAM_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2425,9 +2410,9 @@ class spell_alexstrasza_gift_beam_visual : public SpellScriptLoader if (Creature* target = GetTarget()->ToCreature()) { if (target->GetMap()->GetDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL) - _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_10, *target, G3D::Quat(), 0); + _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_10, *target, QuaternionData(), 0); else if (target->GetMap()->GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) - _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_25, *target, G3D::Quat(), 0); + _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_25, *target, QuaternionData(), 0); } } diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h b/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h index 52a32da8c60..0de2d1a9e2a 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h @@ -18,6 +18,9 @@ #ifndef DEF_EYE_OF_ETERNITY_H #define DEF_EYE_OF_ETERNITY_H +#include "CreatureAIImpl.h" + +#define EoEScriptName "instance_eye_of_eternity" #define DataHeader "EOE" enum EOEInstanceData @@ -84,4 +87,10 @@ enum EOEInstanceSpells SPELL_SUMMOM_RED_DRAGON_BUDDY = 56070 }; +template +inline AI* GetEyeOfEternityAI(T* obj) +{ + return GetInstanceAI(obj, EoEScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp b/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp index d5ef16f7ad5..ef10057f180 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" +#include "Creature.h" +#include "CreatureAI.h" #include "eye_of_eternity.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" #include "Player.h" BossBoundaryData const boundaries = @@ -29,7 +33,7 @@ BossBoundaryData const boundaries = class instance_eye_of_eternity : public InstanceMapScript { public: - instance_eye_of_eternity() : InstanceMapScript("instance_eye_of_eternity", 616) { } + instance_eye_of_eternity() : InstanceMapScript(EoEScriptName, 616) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -86,7 +90,7 @@ public: void SpawnGameObject(uint32 entry, Position const& pos) { GameObject* go = new GameObject(); - if (!go->Create(instance->GenerateLowGuid(), entry, instance, PHASEMASK_NORMAL, pos, G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(instance->GenerateLowGuid(), entry, instance, PHASEMASK_NORMAL, pos, QuaternionData(), 255, GO_STATE_READY)) { delete go; return; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp index e8c5da8d76e..11322c30d1d 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp @@ -17,8 +17,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "nexus.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -189,7 +192,7 @@ class boss_anomalus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; @@ -263,7 +266,7 @@ class npc_chaotic_rift : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp index 3d19f54d84a..cb17a64563a 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" +#include "InstanceScript.h" #include "nexus.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -216,7 +219,7 @@ class boss_keristrasza : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; @@ -248,7 +251,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetNexusAI(go); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp index a3d6f1a107a..09944d921bc 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp @@ -16,11 +16,14 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "GameEventMgr.h" #include "GameTime.h" -#include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "nexus.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -71,7 +74,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } struct boss_magus_telestraAI : public ScriptedAI diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp index 935d309eb02..630806bdcec 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "nexus.h" +#include "ScriptedCreature.h" enum Spells { @@ -100,7 +100,7 @@ class boss_nexus_commanders : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp index 950ba5d91f7..95651b032b6 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp @@ -17,8 +17,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "nexus.h" +#include "ScriptedCreature.h" #include "SpellScript.h" enum Spells @@ -170,7 +171,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; @@ -258,7 +259,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_crystal_spike_triggerAI(creature); + return GetNexusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp b/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp index dcb1886e818..cb07de16ab7 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "Player.h" +#include "Map.h" #include "nexus.h" +#include "Player.h" class instance_nexus : public InstanceMapScript { diff --git a/src/server/scripts/Northrend/Nexus/Nexus/nexus.h b/src/server/scripts/Northrend/Nexus/Nexus/nexus.h index c4b07c78c3b..3045c922f4b 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/nexus.h +++ b/src/server/scripts/Northrend/Nexus/Nexus/nexus.h @@ -18,6 +18,8 @@ #ifndef DEF_NEXUS_H #define DEF_NEXUS_H +#include "CreatureAIImpl.h" + #define NexusScriptName "instance_nexus" #define DataHeader "NEX" @@ -63,4 +65,10 @@ enum NEXGameObjectIds GO_TELESTRAS_CONTAINMET_SPHERE = 188526 }; +template +inline AI* GetNexusAI(T* obj) +{ + return GetInstanceAI(obj, NexusScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp index 90eeafb407b..c81f378b8b4 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "oculus.h" +#include "ScriptedCreature.h" enum Spells { @@ -201,7 +203,7 @@ class npc_unstable_sphere : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_unstable_sphereAI(creature); + return GetOculusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp index c5a1a95b2f8..06a99cd6c3e 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "oculus.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "oculus.h" // Types of drake mounts: Ruby (Tank), Amber (DPS), Emerald (Healer) // Two Repeating phases @@ -258,7 +258,7 @@ class boss_eregos : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_eregosAI(creature); + return GetOculusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp index b07c0f22169..459b9cb188d 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp @@ -23,8 +23,9 @@ SDCategory: Instance Script EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "MotionMaster.h" #include "oculus.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Spells diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp index 7865ffaec8d..460288d99f0 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "oculus.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "oculus.h" enum Says { @@ -233,7 +236,7 @@ class npc_azure_ring_captain : public CreatureScript { switch (action) { - case ACTION_CALL_DRAGON_EVENT: + case ACTION_CALL_DRAGON_EVENT: if (Creature* varos = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_VAROS))) { if (Unit* victim = varos->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0)) @@ -255,7 +258,7 @@ class npc_azure_ring_captain : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOculusAI(creature); } }; @@ -271,7 +274,7 @@ class spell_varos_centrifuge_shield : public SpellScriptLoader bool Load() override { Unit* caster = GetCaster(); - return (caster && caster->ToCreature()); + return caster && caster->GetTypeId() == TYPEID_UNIT; } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp b/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp index 4d152ba5fa4..41189cf818b 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp @@ -16,10 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "WorldPacket.h" +#include "Map.h" +#include "MotionMaster.h" #include "oculus.h" +#include "TemporarySummon.h" +#include "WorldPacket.h" DoorData const doorData[] = { @@ -111,11 +116,10 @@ class instance_oculus : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_DRAGON_CAGE_DOOR: - AddDoor(go, true); - break; case GO_EREGOS_CACHE_N: case GO_EREGOS_CACHE_H: EregosCacheGUID = go->GetGUID(); @@ -125,18 +129,6 @@ class instance_oculus : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_DRAGON_CAGE_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - void OnUnitDeath(Unit* unit) override { Creature* creature = unit->ToCreature(); diff --git a/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp b/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp index 4aa0cf0d76e..96b354e9ba2 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" +#include "CombatAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "oculus.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "SpellScript.h" +#include "Spell.h" #include "SpellAuraEffects.h" -#include "SpellInfo.h" -#include "CombatAI.h" -#include "Player.h" +#include "SpellScript.h" #include "Vehicle.h" -#include "oculus.h" enum GossipNPCs { @@ -263,7 +266,7 @@ class npc_ruby_emerald_amber_drake : public CreatureScript Initialize(); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (Unit* creator = ObjectAccessor::GetUnit(*me, me->GetCreatorGUID())) if (spell->Id == SPELL_GPS) @@ -478,9 +481,7 @@ class spell_oculus_evasive_maneuvers : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RUBY_EVASIVE_CHARGES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RUBY_EVASIVE_CHARGES }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -515,9 +516,7 @@ class spell_oculus_shock_lance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AMBER_SHOCK_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AMBER_SHOCK_CHARGE }); } void CalcDamage() @@ -557,9 +556,7 @@ class spell_oculus_stop_time : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AMBER_SHOCK_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AMBER_SHOCK_CHARGE }); } void Apply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -597,9 +594,7 @@ class spell_oculus_temporal_rift : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AMBER_SHOCK_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AMBER_SHOCK_CHARGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Northrend/Nexus/Oculus/oculus.h b/src/server/scripts/Northrend/Nexus/Oculus/oculus.h index 712c7f3963d..4967d3e56e4 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/oculus.h +++ b/src/server/scripts/Northrend/Nexus/Oculus/oculus.h @@ -18,6 +18,8 @@ #ifndef OCULUS_H_ #define OCULUS_H_ +#include "CreatureAIImpl.h" + #define OculusScriptName "instance_oculus" #define DataHeader "OC" @@ -105,10 +107,10 @@ enum OCMisc POINT_MOVE_OUT = 1 }; -template -AI* GetOculusAI(Creature* creature) +template +inline AI* GetOculusAI(T* obj) { - return GetInstanceAI(creature, OculusScriptName); + return GetInstanceAI(obj, OculusScriptName); } #endif // OCULUS_H_ diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp index 65991267f63..05c6038f714 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp @@ -24,8 +24,10 @@ SDCategory: Halls of Lightning EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Yells { @@ -99,7 +101,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } struct boss_bjarngrimAI : public ScriptedAI @@ -392,7 +394,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } struct npc_stormforged_lieutenantAI : public ScriptedAI diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp index aadab9f1d29..a61b5f91489 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp @@ -21,8 +21,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Spells @@ -69,7 +72,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } struct boss_ionarAI : public ScriptedAI @@ -144,7 +147,7 @@ public: Talk(SAY_SLAY); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_DISPERSE) { @@ -376,7 +379,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } }; diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp index 3cd470d1a37..a749b783fc2 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp @@ -24,9 +24,11 @@ SDCategory: Halls of Lightning EndScriptData */ #include "ScriptMgr.h" +#include "halls_of_lightning.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "halls_of_lightning.h" enum Texts { @@ -205,7 +207,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } }; diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp index c0c2998f874..604fdeb6123 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp @@ -24,10 +24,12 @@ SDCategory: Halls of Lightning EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_lightning.h" -#include "Player.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellMgr.h" enum Texts { @@ -200,7 +202,7 @@ public: summoned->GetMotionMaster()->MoveFollow(target, 0.0f, 0.0f); // Why healing when just summoned? - summoned->CastSpell(summoned, SPELL_HEAT, false, NULL, NULL, me->GetGUID()); + summoned->CastSpell(summoned, SPELL_HEAT, false, nullptr, nullptr, me->GetGUID()); } } @@ -365,9 +367,8 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } - }; /*###### @@ -381,7 +382,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_molten_golemAI(creature); + return GetHallsOfLightningAI(creature); } struct npc_molten_golemAI : public ScriptedAI @@ -437,7 +438,7 @@ public: } } - void SpellHit(Unit* /*pCaster*/, const SpellInfo* pSpell) override + void SpellHit(Unit* /*pCaster*/, SpellInfo const* pSpell) override { // This is the dummy effect of the spells if (pSpell->Id == sSpellMgr->GetSpellIdForDifficulty(SPELL_SHATTER, me)) diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h index 2cbbd8556b6..742b36c539f 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h @@ -18,6 +18,8 @@ #ifndef HALLS_OF_LIGHTNING_H_ #define HALLS_OF_LIGHTNING_H_ +#include "CreatureAIImpl.h" + #define HoLScriptName "instance_halls_of_lightning" #define DataHeader "HOL" @@ -49,10 +51,10 @@ enum HOLGameObjectIds GO_LOKEN_THRONE = 192654 }; -template -AI* GetHallsOfLightningAI(Creature* creature) +template +inline AI* GetHallsOfLightningAI(T* obj) { - return GetInstanceAI(creature, HoLScriptName); + return GetInstanceAI(obj, HoLScriptName); } #endif // HALLS_OF_LIGHTNING_H_ diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp index 0782a552bc4..0508db5fddb 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" +#include "GameObject.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { { GO_VOLKHAN_DOOR, DATA_VOLKHAN, DOOR_TYPE_PASSAGE }, { GO_IONAR_DOOR, DATA_IONAR, DOOR_TYPE_PASSAGE }, { GO_LOKEN_DOOR, DATA_LOKEN, DOOR_TYPE_PASSAGE }, - { 0, 0, DOOR_TYPE_ROOM } // END + { 0, 0, DOOR_TYPE_ROOM } // END }; class instance_halls_of_lightning : public InstanceMapScript @@ -64,13 +67,10 @@ class instance_halls_of_lightning : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_VOLKHAN_DOOR: - case GO_IONAR_DOOR: - case GO_LOKEN_DOOR: - AddDoor(go, true); - break; case GO_LOKEN_THRONE: LokenGlobeGUID = go->GetGUID(); break; @@ -79,20 +79,6 @@ class instance_halls_of_lightning : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_VOLKHAN_DOOR: - case GO_IONAR_DOOR: - case GO_LOKEN_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp index 4674984d8c3..338b273808f 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "halls_of_stone.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "halls_of_stone.h" enum Spells { @@ -155,7 +156,7 @@ class spell_krystallus_shatter : public SpellScriptLoader if (Unit* target = GetHitUnit()) { target->RemoveAurasDueToSpell(SPELL_STONED); - target->CastSpell((Unit*)NULL, SPELL_SHATTER_EFFECT, true); + target->CastSpell((Unit*)nullptr, SPELL_SHATTER_EFFECT, true); } } diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp index 692875c496c..6463c0c1aef 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Yells { diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp index 47fc35d6207..9f6ccce5a87 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp index 9937f4d6fc7..2e926b17710 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp @@ -16,11 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" enum Texts { @@ -553,7 +555,7 @@ public: me->SetStandState(UNIT_STAND_STATE_STAND); instance->HandleGameObject(instance->GetGuidData(DATA_GO_SKY_FLOOR), true); if (Creature* temp = ObjectAccessor::GetCreature(*me, uiControllerGUID)) - temp->DealDamage(temp, temp->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + temp->DealDamage(temp, temp->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); bIsBattle = true; SetEscortPaused(false); JumpToNextStep(6500); diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h index 69042bf18f4..358ab05f024 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h @@ -18,6 +18,8 @@ #ifndef HALLS_OF_STONE_H_ #define HALLS_OF_STONE_H_ +#include "CreatureAIImpl.h" + #define HoSScriptName "instance_halls_of_stone" #define DataHeader "HOS" @@ -67,10 +69,10 @@ enum HOSGameObjectIds GO_TRIBUNAL_SKY_FLOOR = 191527 }; -template -AI* GetHallsOfStoneAI(Creature* creature) +template +inline AI* GetHallsOfStoneAI(T* obj) { - return GetInstanceAI(creature, HoSScriptName); + return GetInstanceAI(obj, HoSScriptName); } #endif // HALLS_OF_STONE_H_ diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp index 7609a8518c8..8f8897cee95 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp @@ -15,10 +15,13 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "Player.h" #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "Map.h" +#include "Player.h" DoorData const doorData[] = { @@ -72,6 +75,8 @@ class instance_halls_of_stone : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_ABEDNEUM: @@ -95,21 +100,6 @@ class instance_halls_of_stone : public InstanceMapScript case GO_TRIBUNAL_SKY_FLOOR: TribunalSkyFloorGUID = go->GetGUID(); break; - case GO_SJONNIR_DOOR: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_SJONNIR_DOOR: - AddDoor(go, false); - break; default: break; } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp index 891263bbfcd..aacf9332a75 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_algalon_the_observer.cpp @@ -15,16 +15,23 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "PassiveAI.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "MapManager.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "MoveSplineInit.h" -#include "ulduar.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "ulduar.h" enum Texts { @@ -247,7 +254,7 @@ class ActivateLivingConstellation : public BasicEvent if (!_instance || _instance->GetBossState(BOSS_ALGALON) != IN_PROGRESS) return true; // delete event - _owner->CastSpell((Unit*)NULL, SPELL_TRIGGER_3_ADDS, TRIGGERED_FULL_MASK); + _owner->CastSpell((Unit*)nullptr, SPELL_TRIGGER_3_ADDS, TRIGGERED_FULL_MASK); _owner->m_Events.AddEvent(this, execTime + urand(45000, 50000)); return false; } @@ -266,7 +273,7 @@ class CosmicSmashDamageEvent : public BasicEvent bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { - _caster->CastSpell((Unit*)NULL, SPELL_COSMIC_SMASH_TRIGGERED, TRIGGERED_FULL_MASK); + _caster->CastSpell((Unit*)nullptr, SPELL_COSMIC_SMASH_TRIGGERED, TRIGGERED_FULL_MASK); return true; } @@ -283,7 +290,7 @@ class SummonUnleashedDarkMatter : public BasicEvent bool Execute(uint64 execTime, uint32 /*diff*/) override { - _caster->CastSpell((Unit*)NULL, SPELL_SUMMON_UNLEASHED_DARK_MATTER, TRIGGERED_FULL_MASK); + _caster->CastSpell((Unit*)nullptr, SPELL_SUMMON_UNLEASHED_DARK_MATTER, TRIGGERED_FULL_MASK); _caster->m_Events.AddEvent(this, execTime + 30000); return false; } @@ -465,9 +472,9 @@ class boss_algalon_the_observer : public CreatureScript break; case NPC_BLACK_HOLE: summon->SetReactState(REACT_PASSIVE); - summon->CastSpell((Unit*)NULL, SPELL_BLACK_HOLE_TRIGGER, TRIGGERED_FULL_MASK); + summon->CastSpell((Unit*)nullptr, SPELL_BLACK_HOLE_TRIGGER, TRIGGERED_FULL_MASK); summon->CastSpell(summon, SPELL_CONSTELLATION_PHASE_TRIGGER, TRIGGERED_FULL_MASK); - summon->CastSpell((Unit*)NULL, SPELL_BLACK_HOLE_EXPLOSION); + summon->CastSpell((Unit*)nullptr, SPELL_BLACK_HOLE_EXPLOSION); summon->CastSpell(summon, SPELL_SUMMON_VOID_ZONE_VISUAL, TRIGGERED_FULL_MASK); break; case NPC_ALGALON_VOID_ZONE_VISUAL_STALKER: @@ -777,7 +784,7 @@ class npc_living_constellation : public CreatureScript me->DespawnOrUnsummon(1); if (InstanceScript* instance = me->GetInstanceScript()) instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EVENT_ID_SUPERMASSIVE_START); - caster->CastSpell((Unit*)NULL, SPELL_BLACK_HOLE_CREDIT, TRIGGERED_FULL_MASK); + caster->CastSpell((Unit*)nullptr, SPELL_BLACK_HOLE_CREDIT, TRIGGERED_FULL_MASK); caster->ToCreature()->DespawnOrUnsummon(1); } @@ -1186,7 +1193,7 @@ class spell_algalon_collapse : public SpellScriptLoader void HandlePeriodic(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); - GetTarget()->DealDamage(GetTarget(), GetTarget()->CountPctFromMaxHealth(1), NULL, NODAMAGE); + GetTarget()->DealDamage(GetTarget(), GetTarget()->CountPctFromMaxHealth(1), nullptr, NODAMAGE); } void Register() override diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp index fe6565664fa..0a22fafb95e 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp @@ -23,9 +23,14 @@ SDCategory: Ulduar - Ulduar EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "ulduar.h" enum AssemblySpells @@ -206,7 +211,7 @@ class boss_steelbreaker : public CreatureScript } else { - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); Talk(SAY_STEELBREAKER_DEATH); //DoCastAOE(SPELL_SUPERCHARGE, true); @@ -354,7 +359,7 @@ class boss_runemaster_molgeim : public CreatureScript } else { - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); Talk(SAY_MOLGEIM_DEATH); //DoCastAOE(SPELL_SUPERCHARGE, true); @@ -530,7 +535,7 @@ class boss_stormcaller_brundir : public CreatureScript } else { - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); Talk(SAY_BRUNDIR_DEATH); //DoCastAOE(SPELL_SUPERCHARGE, true); @@ -725,15 +730,13 @@ class spell_assembly_rune_of_summoning : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RUNE_OF_SUMMONING_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RUNE_OF_SUMMONING_SUMMON }); } void HandlePeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_RUNE_OF_SUMMONING_SUMMON, true, NULL, aurEff, GetTarget()->IsSummon() ? GetTarget()->ToTempSummon()->GetSummonerGUID() : ObjectGuid::Empty); + GetTarget()->CastSpell(GetTarget(), SPELL_RUNE_OF_SUMMONING_SUMMON, true, nullptr, aurEff, GetTarget()->IsSummon() ? GetTarget()->ToTempSummon()->GetSummonerGUID() : ObjectGuid::Empty); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp index 8fd85e1c130..b9983785a18 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "ulduar.h" diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp index d89a9d08fe5..dac2a8707d9 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp @@ -23,23 +23,21 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "GameObjectAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CombatAI.h" +#include "GameObjectAI.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" -#include "ObjectMgr.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "Spell.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "Vehicle.h" -#include "VehicleDefines.h" #include "ulduar.h" -#include "Spell.h" +#include "Vehicle.h" enum Spells { @@ -1007,7 +1005,7 @@ public: npc_escortAI::UpdateAI(diff); if (!HasEscortState(STATE_ESCORT_ESCORTING)) - Start(false, true, ObjectGuid::Empty, NULL, false, true); + Start(false, true, ObjectGuid::Empty, nullptr, false, true); else { if (infernoTimer <= diff) @@ -1755,11 +1753,11 @@ class spell_vehicle_throw_passenger : public SpellScriptLoader { // use 99 because it is 3d search std::list targetList; - Trinity::WorldObjectSpellAreaTargetCheck check(99, GetExplTargetDest(), GetCaster(), GetCaster(), GetSpellInfo(), TARGET_CHECK_DEFAULT, NULL); + Trinity::WorldObjectSpellAreaTargetCheck check(99, GetExplTargetDest(), GetCaster(), GetCaster(), GetSpellInfo(), TARGET_CHECK_DEFAULT, nullptr); Trinity::WorldObjectListSearcher searcher(GetCaster(), targetList, check); Cell::VisitAllObjects(GetCaster(), searcher, 99.0f); float minDist = 99 * 99; - Unit* target = NULL; + Unit* target = nullptr; for (std::list::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp index 61482ac9f83..b8846cace28 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "TemporarySummon.h" #include "ulduar.h" enum FreyaYells @@ -609,7 +611,7 @@ class boss_freya : public CreatureScript /* 25N */ {62955, 62956, 62957, 62958} }; - me->CastSpell((Unit*)NULL, summonSpell[me->GetMap()->GetDifficulty()][elderCount], true); + me->CastSpell((Unit*)nullptr, summonSpell[me->GetMap()->GetDifficulty()][elderCount], true); Talk(SAY_DEATH); @@ -839,7 +841,7 @@ class boss_elder_stonebark : public CreatureScript if (me->HasAura(SPELL_PETRIFIED_BARK)) { int32 reflect = damage; - who->CastCustomSpell(who, SPELL_PETRIFIED_BARK_DMG, &reflect, NULL, NULL, true); + who->CastCustomSpell(who, SPELL_PETRIFIED_BARK_DMG, &reflect, nullptr, nullptr, true); damage = 0; } } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp index 00370d87516..cba47d66951 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp @@ -16,11 +16,14 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "ulduar.h" -#include "Player.h" enum VezaxYells { @@ -275,7 +278,7 @@ class boss_general_vezax : public CreatureScript /* Player Range Check Purpose: If there are playersMin people within rangeMin, rangeMax: return a random players in that range. - If not, return NULL and allow other target selection + If not, return nullptr and allow other target selection */ Unit* CheckPlayersInRange(uint8 playersMin, float rangeMin, float rangeMax) { @@ -294,11 +297,11 @@ class boss_general_vezax : public CreatureScript } if (PlayerList.empty()) - return NULL; + return nullptr; size_t size = PlayerList.size(); if (size < playersMin) - return NULL; + return nullptr; return Trinity::Containers::SelectRandomContainerElement(PlayerList); } @@ -371,7 +374,7 @@ class boss_saronite_animus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUlduarAI(creature); } }; @@ -441,7 +444,7 @@ class npc_saronite_vapors : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUlduarAI(creature); } }; @@ -456,9 +459,7 @@ class spell_general_vezax_mark_of_the_faceless : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_THE_FACELESS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_THE_FACELESS_DAMAGE }); } void HandleEffectPeriodic(AuraEffect const* aurEff) @@ -519,9 +520,7 @@ class spell_general_vezax_saronite_vapors : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SARONITE_VAPORS_ENERGIZE) || !sSpellMgr->GetSpellInfo(SPELL_SARONITE_VAPORS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SARONITE_VAPORS_ENERGIZE, SPELL_SARONITE_VAPORS_DAMAGE }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -530,8 +529,8 @@ class spell_general_vezax_saronite_vapors : public SpellScriptLoader { int32 mana = int32(aurEff->GetAmount() * std::pow(2.0f, GetStackAmount())); // mana restore - bp * 2^stackamount int32 damage = mana * 2; - caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_ENERGIZE, &mana, NULL, NULL, true); - caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_DAMAGE, &damage, NULL, NULL, true); + caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_ENERGIZE, &mana, nullptr, nullptr, true); + caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_DAMAGE, &damage, nullptr, nullptr, true); } } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp index 59b9cc5bcb1..a7a90595ffe 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp @@ -16,13 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "ulduar.h" /* @todo Achievements @@ -959,7 +960,7 @@ class npc_toasty_fire : public CreatureScript DoCast(me, SPELL_SINGED, true); } - void SpellHit(Unit* /*who*/, const SpellInfo* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { if (spell->Id == SPELL_BLOCK_OF_ICE || spell->Id == SPELL_ICE_SHARD || spell->Id == SPELL_ICE_SHARD_HIT) { @@ -1048,7 +1049,7 @@ public: return; int32 damage = int32(200 * std::pow(2.0f, GetStackAmount())); - caster->CastCustomSpell(caster, SPELL_BITING_COLD_DAMAGE, &damage, NULL, NULL, true); + caster->CastCustomSpell(caster, SPELL_BITING_COLD_DAMAGE, &damage, nullptr, nullptr, true); if (caster->isMoving()) caster->RemoveAuraFromStack(SPELL_BITING_COLD_TRIGGERED); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp index 7aa60e8af68..1fb7dda696a 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp @@ -15,11 +15,13 @@ * with this program. If not, see . */ -#include "GameTime.h" #include "ScriptMgr.h" +#include "GameTime.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "ulduar.h" #include "Vehicle.h" @@ -252,7 +254,7 @@ class boss_ignis : public CreatureScript if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { slagPotTarget->ExitVehicle(); - slagPotTarget = NULL; + slagPotTarget = nullptr; _slagPotGUID.Clear(); events.CancelEvent(EVENT_END_POT); } @@ -454,10 +456,7 @@ class spell_ignis_slag_pot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SLAG_POT_DAMAGE) - || !sSpellMgr->GetSpellInfo(SPELL_SLAG_IMBUED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SLAG_POT_DAMAGE, SPELL_SLAG_IMBUED }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp index 33e97e8baf6..57ace8ec195 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "ulduar.h" #include "Vehicle.h" -#include "Player.h" /* ScriptData SDName: boss_kologarn @@ -340,7 +344,7 @@ class spell_ulduar_rubble_summon : public SpellScriptLoader ObjectGuid originalCaster = caster->GetInstanceScript() ? caster->GetInstanceScript()->GetGuidData(BOSS_KOLOGARN) : ObjectGuid::Empty; uint32 spellId = GetEffectValue(); for (uint8 i = 0; i < 5; ++i) - caster->CastSpell(caster, spellId, true, NULL, NULL, originalCaster); + caster->CastSpell(caster, spellId, true, nullptr, nullptr, originalCaster); } void Register() override diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp index 7929ab54eb6..9ed4f098ed6 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp @@ -15,15 +15,17 @@ * with this program. If not, see . */ -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "GameObjectAI.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "ulduar.h" #include "Vehicle.h" @@ -493,7 +495,7 @@ class boss_mimiron : public CreatureScript { case EVENT_SUMMON_FLAMES: if (Creature* worldtrigger = instance->GetCreature(DATA_MIMIRON_WORLD_TRIGGER)) - worldtrigger->CastCustomSpell(SPELL_SCRIPT_EFFECT_SUMMON_FLAMES_INITIAL, SPELLVALUE_MAX_TARGETS, 3, NULL, true, NULL, NULL, me->GetGUID()); + worldtrigger->CastCustomSpell(SPELL_SCRIPT_EFFECT_SUMMON_FLAMES_INITIAL, SPELLVALUE_MAX_TARGETS, 3, nullptr, true, nullptr, nullptr, me->GetGUID()); events.RescheduleEvent(EVENT_SUMMON_FLAMES, 28000); break; case EVENT_INTRO_1: @@ -645,10 +647,10 @@ class boss_mimiron : public CreatureScript { if (Creature* computer = instance->GetCreature(DATA_COMPUTER)) computer->AI()->DoAction(DO_DEACTIVATE_COMPUTER); - me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION_FIREFIGHTER, GO_CACHE_OF_INNOVATION_FIREFIGHTER_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, G3D::Quat(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); + me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION_FIREFIGHTER, GO_CACHE_OF_INNOVATION_FIREFIGHTER_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, QuaternionData(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); } else - me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION, GO_CACHE_OF_INNOVATION_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, G3D::Quat(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); + me->SummonGameObject(RAID_MODE(GO_CACHE_OF_INNOVATION, GO_CACHE_OF_INNOVATION_HERO), 2744.040f, 2569.352f, 364.3135f, 3.124123f, QuaternionData(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); events.ScheduleEvent(EVENT_OUTTRO_3, 11000); break; case EVENT_OUTTRO_3: @@ -1229,15 +1231,15 @@ class boss_aerial_command_unit : public CreatureScript switch (eventId) { case EVENT_SUMMON_FIRE_BOTS: - me->CastCustomSpell(SPELL_SUMMON_FIRE_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 3, NULL, true); + me->CastCustomSpell(SPELL_SUMMON_FIRE_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 3, nullptr, true); events.RescheduleEvent(EVENT_SUMMON_FIRE_BOTS, 45000, 0, PHASE_AERIAL_COMMAND_UNIT); break; case EVENT_SUMMON_JUNK_BOT: - me->CastCustomSpell(SPELL_SUMMON_JUNK_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + me->CastCustomSpell(SPELL_SUMMON_JUNK_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); events.RescheduleEvent(EVENT_SUMMON_JUNK_BOT, urand(11000, 12000), 0, PHASE_AERIAL_COMMAND_UNIT); break; case EVENT_SUMMON_ASSAULT_BOT: - me->CastCustomSpell(SPELL_SUMMON_ASSAULT_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + me->CastCustomSpell(SPELL_SUMMON_ASSAULT_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); events.RescheduleEvent(EVENT_SUMMON_ASSAULT_BOT, 30000, 0, PHASE_AERIAL_COMMAND_UNIT); break; case EVENT_SUMMON_BOMB_BOT: @@ -1787,9 +1789,7 @@ class spell_mimiron_fire_search : public SpellScriptLoader private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WATER_SPRAY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WATER_SPRAY }); } void FilterTargets(std::list& targets) @@ -1878,9 +1878,7 @@ class spell_mimiron_magnetic_core : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGNETIC_CORE_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGNETIC_CORE_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1933,9 +1931,7 @@ class spell_mimiron_napalm_shell : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NAPALM_SHELL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NAPALM_SHELL }); } void FilterTargets(std::list& targets) @@ -2011,9 +2007,7 @@ class spell_mimiron_plasma_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PLASMA_BLAST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PLASMA_BLAST }); } bool Load() override @@ -2087,9 +2081,7 @@ class spell_mimiron_proximity_mines : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PROXIMITY_MINE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_PROXIMITY_MINE }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2122,9 +2114,7 @@ class spell_mimiron_proximity_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PROXIMITY_MINE_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PROXIMITY_MINE_EXPLOSION }); } void FilterTargets(std::list& targets) @@ -2137,7 +2127,7 @@ class spell_mimiron_proximity_trigger : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { - GetCaster()->CastSpell((Unit*)NULL, SPELL_PROXIMITY_MINE_EXPLOSION, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_PROXIMITY_MINE_EXPLOSION, true); } void Register() override @@ -2165,9 +2155,7 @@ class spell_mimiron_rapid_burst : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RAPID_BURST_LEFT) || !sSpellMgr->GetSpellInfo(SPELL_RAPID_BURST_RIGHT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RAPID_BURST_LEFT, SPELL_RAPID_BURST_RIGHT }); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2179,7 +2167,7 @@ class spell_mimiron_rapid_burst : public SpellScriptLoader void HandleDummyTick(AuraEffect const* aurEff) { if (GetCaster()) - GetCaster()->CastSpell(GetTarget(), aurEff->GetTickNumber() % 2 == 0 ? SPELL_RAPID_BURST_RIGHT : SPELL_RAPID_BURST_LEFT, true, NULL, aurEff); + GetCaster()->CastSpell(GetTarget(), aurEff->GetTickNumber() % 2 == 0 ? SPELL_RAPID_BURST_RIGHT : SPELL_RAPID_BURST_LEFT, true, nullptr, aurEff); } void Register() override @@ -2207,9 +2195,7 @@ class spell_mimiron_rocket_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SCRIPT_EFFECT_ROCKET_STRIKE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SCRIPT_EFFECT_ROCKET_STRIKE }); } void FilterTargets(std::list& targets) @@ -2227,7 +2213,7 @@ class spell_mimiron_rocket_strike : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { - GetHitUnit()->CastSpell((Unit*)NULL, SPELL_SCRIPT_EFFECT_ROCKET_STRIKE, true, NULL, NULL, GetCaster()->GetGUID()); + GetHitUnit()->CastSpell((Unit*)nullptr, SPELL_SCRIPT_EFFECT_ROCKET_STRIKE, true, nullptr, nullptr, GetCaster()->GetGUID()); } void Register() override @@ -2255,9 +2241,7 @@ class spell_mimiron_rocket_strike_damage : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NOT_SO_FRIENDLY_FIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NOT_SO_FRIENDLY_FIRE }); } void HandleAfterCast() @@ -2276,7 +2260,7 @@ class spell_mimiron_rocket_strike_damage : public SpellScriptLoader void HandleFriendlyFire(SpellEffIndex /*effIndex*/) { - GetHitUnit()->CastSpell((Unit*)NULL, SPELL_NOT_SO_FRIENDLY_FIRE, true); + GetHitUnit()->CastSpell((Unit*)nullptr, SPELL_NOT_SO_FRIENDLY_FIRE, true); } void Register() override @@ -2305,9 +2289,7 @@ class spell_mimiron_rocket_strike_target_select : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ROCKET_STRIKE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ROCKET_STRIKE }); } void FilterTargets(std::list& targets) @@ -2329,7 +2311,7 @@ class spell_mimiron_rocket_strike_target_select : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) - GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_ROCKET_STRIKE, true, NULL, NULL, instance->GetGuidData(DATA_VX_001)); + GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_ROCKET_STRIKE, true, nullptr, nullptr, instance->GetGuidData(DATA_VX_001)); GetCaster()->SetDisplayId(11686); } @@ -2415,9 +2397,7 @@ class spell_mimiron_summon_assault_bot : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ASSAULT_BOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ASSAULT_BOT }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2425,7 +2405,7 @@ class spell_mimiron_summon_assault_bot : public SpellScriptLoader if (Unit* caster = GetCaster()) if (InstanceScript* instance = caster->GetInstanceScript()) if (instance->GetBossState(BOSS_MIMIRON) == IN_PROGRESS) - caster->CastSpell(caster, SPELL_SUMMON_ASSAULT_BOT, false, NULL, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); + caster->CastSpell(caster, SPELL_SUMMON_ASSAULT_BOT, false, nullptr, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); } void Register() override @@ -2452,9 +2432,7 @@ class spell_mimiron_summon_assault_bot_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ASSAULT_BOT_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ASSAULT_BOT_DUMMY }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2486,10 +2464,7 @@ class spell_mimiron_summon_fire_bot : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FIRE_BOT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FIRE_BOT }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2497,7 +2472,7 @@ class spell_mimiron_summon_fire_bot : public SpellScriptLoader if (Unit* caster = GetCaster()) if (InstanceScript* instance = caster->GetInstanceScript()) if (instance->GetBossState(BOSS_MIMIRON) == IN_PROGRESS) - caster->CastSpell(caster, SPELL_SUMMON_FIRE_BOT, false, NULL, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); + caster->CastSpell(caster, SPELL_SUMMON_FIRE_BOT, false, nullptr, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); } void Register() override @@ -2524,9 +2499,7 @@ class spell_mimiron_summon_fire_bot_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FIRE_BOT_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FIRE_BOT_DUMMY }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2595,9 +2568,7 @@ class spell_mimiron_summon_flames_spread : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FLAMES_SPREAD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FLAMES_SPREAD }); } void HandleTick(AuraEffect const* /*aurEff*/) @@ -2632,9 +2603,7 @@ class spell_mimiron_summon_frost_bomb_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FROST_BOMB)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FROST_BOMB }); } void FilterTargets(std::list& targets) @@ -2683,9 +2652,7 @@ class spell_mimiron_summon_junk_bot : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_JUNK_BOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_JUNK_BOT }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2693,7 +2660,7 @@ class spell_mimiron_summon_junk_bot : public SpellScriptLoader if (Unit* caster = GetCaster()) if (InstanceScript* instance = caster->GetInstanceScript()) if (instance->GetBossState(BOSS_MIMIRON) == IN_PROGRESS) - caster->CastSpell(caster, SPELL_SUMMON_JUNK_BOT, false, NULL, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); + caster->CastSpell(caster, SPELL_SUMMON_JUNK_BOT, false, nullptr, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); } void Register() override @@ -2720,9 +2687,7 @@ class spell_mimiron_summon_junk_bot_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_JUNK_BOT_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_JUNK_BOT_DUMMY }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp index 1ab33be99ba..d571bd541df 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp @@ -18,13 +18,19 @@ /// @todo Harpoon chain from 62505 should not get removed when other chain is applied #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "GameObjectAI.h" +#include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "ulduar.h" -#include "SpellInfo.h" -#include "Player.h" enum Says { @@ -250,7 +256,7 @@ class boss_razorscale_controller : public CreatureScript break; case ACTION_PLACE_BROKEN_HARPOON: for (uint8 n = 0; n < RAID_MODE(2, 4); n++) - me->SummonGameObject(GO_RAZOR_BROKEN_HARPOON, PosHarpoon[n].GetPositionX(), PosHarpoon[n].GetPositionY(), PosHarpoon[n].GetPositionZ(), 2.286f, G3D::Quat(), 180); + me->SummonGameObject(GO_RAZOR_BROKEN_HARPOON, PosHarpoon[n].GetPositionX(), PosHarpoon[n].GetPositionY(), PosHarpoon[n].GetPositionZ(), 2.286f, QuaternionData(), 180); break; } } @@ -265,7 +271,7 @@ class boss_razorscale_controller : public CreatureScript { case EVENT_BUILD_HARPOON_1: Talk(EMOTE_HARPOON); - if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_1, PosHarpoon[0].GetPositionX(), PosHarpoon[0].GetPositionY(), PosHarpoon[0].GetPositionZ(), 4.790f, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_1, PosHarpoon[0].GetPositionX(), PosHarpoon[0].GetPositionY(), PosHarpoon[0].GetPositionZ(), 4.790f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) //only nearest broken harpoon brokenHarpoon->RemoveFromWorld(); @@ -275,7 +281,7 @@ class boss_razorscale_controller : public CreatureScript return; case EVENT_BUILD_HARPOON_2: Talk(EMOTE_HARPOON); - if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_2, PosHarpoon[1].GetPositionX(), PosHarpoon[1].GetPositionY(), PosHarpoon[1].GetPositionZ(), 4.659f, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_2, PosHarpoon[1].GetPositionX(), PosHarpoon[1].GetPositionY(), PosHarpoon[1].GetPositionZ(), 4.659f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) brokenHarpoon->RemoveFromWorld(); @@ -284,7 +290,7 @@ class boss_razorscale_controller : public CreatureScript return; case EVENT_BUILD_HARPOON_3: Talk(EMOTE_HARPOON); - if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_3, PosHarpoon[2].GetPositionX(), PosHarpoon[2].GetPositionY(), PosHarpoon[2].GetPositionZ(), 5.382f, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_3, PosHarpoon[2].GetPositionX(), PosHarpoon[2].GetPositionY(), PosHarpoon[2].GetPositionZ(), 5.382f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) brokenHarpoon->RemoveFromWorld(); @@ -294,7 +300,7 @@ class boss_razorscale_controller : public CreatureScript return; case EVENT_BUILD_HARPOON_4: Talk(EMOTE_HARPOON); - if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_4, PosHarpoon[3].GetPositionX(), PosHarpoon[3].GetPositionY(), PosHarpoon[3].GetPositionZ(), 4.266f, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_4, PosHarpoon[3].GetPositionX(), PosHarpoon[3].GetPositionY(), PosHarpoon[3].GetPositionZ(), 4.266f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) brokenHarpoon->RemoveFromWorld(); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp index 0dc4e553ad7..cfa977166ad 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp @@ -15,16 +15,22 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" #include "TypeContainerVisitor.h" -#include "CellImpl.h" -#include "GridNotifiersImpl.h" #include "ulduar.h" +#include enum Spells { @@ -317,8 +323,7 @@ enum DisplayIds THORIM_WEAPON_DISPLAY_ID = 45900 }; -uint32 const LightningOrbPathSize = 8; -G3D::Vector3 const LightningOrbPath[LightningOrbPathSize] = +Position const LightningOrbPath[] = { { 2134.889893f, -298.632996f, 438.247467f }, { 2134.570068f, -440.317993f, 438.247467f }, @@ -329,6 +334,7 @@ G3D::Vector3 const LightningOrbPath[LightningOrbPathSize] = { 2202.208008f, -262.939270f, 412.168976f }, { 2182.310059f, -263.233093f, 414.739410f } }; +std::size_t const LightningOrbPathSize = std::extent::value; // used for trash jump calculation Position const ArenaCenter = { 2134.77f, -262.307f }; @@ -352,7 +358,7 @@ class HeightPositionCheck bool operator()(Position const* pos) const { - return pos->GetPositionZ() > THORIM_BALCONY_Z_CHECK == _ret; + return (pos->GetPositionZ() > THORIM_BALCONY_Z_CHECK) == _ret; } private: @@ -647,7 +653,12 @@ class boss_thorim : public CreatureScript summon->GetMotionMaster()->MovePoint(EVENT_CHARGE_PREPATH, LightningOrbPath[LightningOrbPathSize - 1], false); - Movement::PointsArray path(LightningOrbPath, LightningOrbPath + LightningOrbPathSize); + Movement::PointsArray path; + path.reserve(LightningOrbPathSize); + std::transform(std::begin(LightningOrbPath), std::end(LightningOrbPath), std::back_inserter(path), [](Position const& pos) + { + return G3D::Vector3(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); + }); Movement::MoveSplineInit init(summon); init.MovebyPath(path); @@ -1749,9 +1760,7 @@ class spell_thorim_charge_orb : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LIGHTNING_PILLAR_1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LIGHTNING_PILLAR_1 }); } void FilterTargets(std::list& targets) @@ -1797,9 +1806,7 @@ class spell_thorim_lightning_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LIGHTNING_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LIGHTNING_CHARGE }); } void HandleFocus() @@ -1880,10 +1887,7 @@ class spell_thorim_stormhammer : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_STORMHAMMER_BOOMERANG) - || !sSpellMgr->GetSpellInfo(SPELL_DEAFENING_THUNDER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_STORMHAMMER_BOOMERANG, SPELL_DEAFENING_THUNDER }); } void FilterTargets(std::list& targets) @@ -1941,10 +1945,7 @@ class spell_thorim_stormhammer_sif : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_STORMHAMMER_BOOMERANG) - || !sSpellMgr->GetSpellInfo(SPELL_SIF_TRANSFORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_STORMHAMMER_BOOMERANG, SPELL_SIF_TRANSFORM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2014,9 +2015,7 @@ class spell_thorim_runic_smash : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RUNIC_SMASH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RUNIC_SMASH }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp index 863740fa70f..2fce8d7a5be 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp @@ -22,15 +22,18 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Opcodes.h" +#include "PassiveAI.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "ulduar.h" #include "Vehicle.h" -#include "Player.h" #include "WorldPacket.h" -#include "Opcodes.h" -#include "PassiveAI.h" enum Spells { @@ -736,7 +739,7 @@ class npc_life_spark : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_life_sparkAI(creature); + return GetUlduarAI(creature); } struct npc_life_sparkAI : public ScriptedAI @@ -807,7 +810,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_xt_void_zoneAI(creature); + return GetUlduarAI(creature); } }; @@ -823,9 +826,7 @@ class spell_xt002_searing_light_spawn_life_spark : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_LIFE_SPARK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_LIFE_SPARK }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -859,9 +860,7 @@ class spell_xt002_gravity_bomb_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_VOID_ZONE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_VOID_ZONE }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -943,19 +942,7 @@ class spell_xt002_heart_overload_periodic : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ENERGY_ORB)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_RECHARGE_BOOMBOT)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_RECHARGE_PUMMELER)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_RECHARGE_SCRAPBOT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ENERGY_ORB, SPELL_RECHARGE_BOOMBOT, SPELL_RECHARGE_PUMMELER, SPELL_RECHARGE_SCRAPBOT }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1074,9 +1061,7 @@ class spell_xt002_321_boombot_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ACHIEVEMENT_CREDIT_NERF_SCRAPBOTS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ACHIEVEMENT_CREDIT_NERF_SCRAPBOTS }); } bool CheckProc(ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp index a47362b1082..66970ee996f 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp @@ -16,12 +16,20 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CreatureTextMgr.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" -#include "SpellScript.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" #include "SpellAuraEffects.h" -#include "MoveSplineInit.h" -#include "CreatureTextMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "ulduar.h" enum Yells @@ -550,7 +558,7 @@ class boss_voice_of_yogg_saron : public CreatureScript if (Creature* yogg = instance->GetCreature(BOSS_YOGG_SARON)) { yogg->AI()->Talk(EMOTE_YOGG_SARON_EXTINGUISH_ALL_LIFE, me); - yogg->CastSpell((Unit*)NULL, SPELL_EXTINGUISH_ALL_LIFE, true); + yogg->CastSpell((Unit*)nullptr, SPELL_EXTINGUISH_ALL_LIFE, true); } events.ScheduleEvent(EVENT_EXTINGUISH_ALL_LIFE, 10000); // cast it again after a short while, players can survive break; @@ -1093,7 +1101,7 @@ class boss_brain_of_yogg_saron : public CreatureScript uint8 illusion = _instance->GetData(DATA_ILLUSION); if (++_tentaclesKilled >= (illusion == ICECROWN_ILLUSION ? 9 : 8)) { - sCreatureTextMgr->SendChat(me, EMOTE_BRAIN_ILLUSION_SHATTERED, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_AREA); + sCreatureTextMgr->SendChat(me, EMOTE_BRAIN_ILLUSION_SHATTERED, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_AREA); _summons.DespawnAll(); DoCastAOE(SPELL_SHATTERED_ILLUSION, true); _instance->HandleGameObject(_instance->GetGuidData(GO_BRAIN_ROOM_DOOR_1 + illusion), true); @@ -2061,9 +2069,7 @@ class spell_yogg_saron_malady_of_the_mind : public SpellScriptLoader // 63830 bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MALADY_OF_THE_MIND_JUMP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MALADY_OF_THE_MIND_JUMP }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2133,11 +2139,7 @@ class spell_yogg_saron_brain_link : public SpellScriptLoader // 63802 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BRAIN_LINK_DAMAGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_BRAIN_LINK_NO_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BRAIN_LINK_DAMAGE, SPELL_BRAIN_LINK_NO_DAMAGE }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2231,9 +2233,7 @@ class spell_yogg_saron_boil_ominously : public SpellScriptLoader // 63030 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_GUARDIAN_1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_GUARDIAN_1 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2332,15 +2332,13 @@ class spell_yogg_saron_empowering_shadows_missile : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_EMPOWERING_SHADOWS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_EMPOWERING_SHADOWS }); } void HandleScript(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) - target->CastSpell((Unit*)NULL, SPELL_EMPOWERING_SHADOWS, true); + target->CastSpell((Unit*)nullptr, SPELL_EMPOWERING_SHADOWS, true); } void Register() override @@ -2367,9 +2365,7 @@ class spell_yogg_saron_constrictor_tentacle : public SpellScriptLoader // 64 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR_TENTACLE_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CONSTRICTOR_TENTACLE_SUMMON }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2400,9 +2396,7 @@ class spell_yogg_saron_lunge : public SpellScriptLoader // 64131 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SQUEEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SQUEEZE }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2495,11 +2489,7 @@ class spell_yogg_saron_empowered : public SpellScriptLoader // 64161 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_EMPOWERED_BUFF)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WEAKENED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_EMPOWERED_BUFF, SPELL_WEAKENED }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2600,11 +2590,7 @@ class spell_yogg_saron_death_ray_warning_visual : public SpellScriptLoader / bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_RAY_PERIODIC)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_RAY_DAMAGE_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEATH_RAY_PERIODIC, SPELL_DEATH_RAY_DAMAGE_VISUAL }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2612,7 +2598,7 @@ class spell_yogg_saron_death_ray_warning_visual : public SpellScriptLoader / if (Unit* caster = GetCaster()) { caster->CastSpell(caster, SPELL_DEATH_RAY_PERIODIC, true); - caster->CastSpell((Unit*)NULL, SPELL_DEATH_RAY_DAMAGE_VISUAL, true); + caster->CastSpell((Unit*)nullptr, SPELL_DEATH_RAY_DAMAGE_VISUAL, true); // TODO: set better movement caster->GetMotionMaster()->MoveConfused(); } @@ -2641,9 +2627,7 @@ class spell_yogg_saron_cancel_illusion_room_aura : public SpellScriptLoader / bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_BACK_TO_MAIN_ROOM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_BACK_TO_MAIN_ROOM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2704,11 +2688,7 @@ class spell_yogg_saron_revealed_tentacle : public SpellScriptLoader // 64012 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TENTACLE_VOID_ZONE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_GRIM_REPRISAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TENTACLE_VOID_ZONE, SPELL_GRIM_REPRISAL }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2744,9 +2724,7 @@ class spell_yogg_saron_grim_reprisal : public SpellScriptLoader // 63305 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GRIM_REPRISAL_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GRIM_REPRISAL_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2783,11 +2761,7 @@ class spell_yogg_saron_induce_madness : public SpellScriptLoader // 64059 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_BACK_TO_MAIN_ROOM)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHATTERED_ILLUSION_REMOVE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_BACK_TO_MAIN_ROOM, SPELL_SHATTERED_ILLUSION_REMOVE }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2802,7 +2776,7 @@ class spell_yogg_saron_induce_madness : public SpellScriptLoader // 64059 void ClearShatteredIllusion() { - GetCaster()->CastSpell((Unit*)NULL, SPELL_SHATTERED_ILLUSION_REMOVE); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SHATTERED_ILLUSION_REMOVE); if (InstanceScript* instance = GetCaster()->GetInstanceScript()) if (Creature* voice = instance->GetCreature(DATA_VOICE_OF_YOGG_SARON)) @@ -2850,11 +2824,7 @@ class spell_yogg_saron_sanity : public SpellScriptLoader // 63050 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LOW_SANITY_SCREEN_EFFECT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_INSANE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LOW_SANITY_SCREEN_EFFECT, SPELL_INSANE }); } void DummyTick(AuraEffect const* /*aurEff*/) @@ -2909,9 +2879,7 @@ class spell_yogg_saron_insane : public SpellScriptLoader // 63120 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_INSANE_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_INSANE_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -3151,9 +3119,7 @@ class spell_yogg_saron_hodirs_protective_gaze : public SpellScriptLoader // bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLASH_FREEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLASH_FREEZE }); } bool CanApply(Unit* target) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp index d662578b9d5..e023be23cd4 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp @@ -15,14 +15,20 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "Vehicle.h" +#include "Item.h" +#include "Map.h" #include "Player.h" -#include "ScriptedCreature.h" -#include "ScriptMgr.h" +#include "Spell.h" #include "SpellScript.h" -#include "WorldPacket.h" +#include "TemporarySummon.h" #include "ulduar.h" +#include "Vehicle.h" +#include "WorldPacket.h" static BossBoundaryData const boundaries = { @@ -885,7 +891,7 @@ class instance_ulduar : public InstanceMapScript return 0; } - bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const*, Unit const* /* = NULL */, uint32 /* = 0 */) override + bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const*, Unit const* /* = nullptr */, uint32 /* = 0 */) override { switch (criteriaId) { diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h b/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h index 15964534640..4548eac4b97 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h @@ -18,6 +18,8 @@ #ifndef DEF_ULDUAR_H #define DEF_ULDUAR_H +#include "CreatureAIImpl.h" + #define UlduarScriptName "instance_ulduar" #define DataHeader "UU" @@ -490,8 +492,8 @@ enum YoggSaronIllusions STORMWIND_ILLUSION = 2, }; -template -AI* GetUlduarAI(T* obj) +template +inline AI* GetUlduarAI(T* obj) { return GetInstanceAI(obj, UlduarScriptName); } diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp index 7eb24fb5dd4..6300fa0e9c1 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp @@ -23,9 +23,12 @@ SDCategory: Utgarde Keep EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "Spell.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "utgarde_keep.h" enum Yells @@ -406,7 +409,7 @@ class npc_ingvar_throw_dummy : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ingvar_throw_dummyAI(creature); + return GetUtgardeKeepAI(creature); } }; @@ -449,9 +452,7 @@ class spell_ingvar_woe_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WOE_STRIKE_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WOE_STRIKE_EFFECT }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -466,7 +467,7 @@ class spell_ingvar_woe_strike : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetActor(), SPELL_WOE_STRIKE_EFFECT, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetActor(), SPELL_WOE_STRIKE_EFFECT, true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp index 6c798de3db6..b10a6a97e04 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp @@ -23,9 +23,12 @@ SDCategory: Utgarde Keep EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "utgarde_keep.h" enum KelsethEncounter diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp index 27da9c2e8bf..3834f5d7f15 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp @@ -23,6 +23,8 @@ SDCategory: Utgarde Keep EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "utgarde_keep.h" diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp index ed8f349edd6..90269688eca 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "utgarde_keep.h" DoorData const doorData[] = @@ -85,6 +88,8 @@ class instance_utgarde_keep : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_BELLOW_1: @@ -123,23 +128,6 @@ class instance_utgarde_keep : public InstanceMapScript Forges[2].AnvilGUID = go->GetGUID(); HandleGameObject(ObjectGuid::Empty, Forges[2].Event != NOT_STARTED, go); break; - case GO_GIANT_PORTCULLIS_1: - case GO_GIANT_PORTCULLIS_2: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_GIANT_PORTCULLIS_1: - case GO_GIANT_PORTCULLIS_2: - AddDoor(go, false); - break; default: break; } diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp index be70f79f2dc..2fa0fc38932 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" -#include "utgarde_keep.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "utgarde_keep.h" uint32 ForgeSearch[3] = { @@ -130,9 +133,7 @@ class spell_ticking_time_bomb : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TICKING_TIME_BOMB_EXPLODE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TICKING_TIME_BOMB_EXPLODE }); } void HandleOnEffectRemove(AuraEffect const* /* aurEff */, AuraEffectHandleModes /* mode */) @@ -169,9 +170,7 @@ class spell_fixate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIXATE_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIXATE_TRIGGER }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -208,9 +207,7 @@ class spell_uk_second_wind : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SECOND_WIND_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SECOND_WIND_TRIGGER }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -342,7 +339,7 @@ class npc_enslaved_proto_drake : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_enslaved_proto_drakeAI(creature); + return GetUtgardeKeepAI(creature); } }; diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h index 81a357e4cff..ac8304f9fd5 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h @@ -18,6 +18,8 @@ #ifndef UTGARDE_KEEP_H_ #define UTGARDE_KEEP_H_ +#include "CreatureAIImpl.h" + #define UKScriptName "instance_utgarde_keep" #define DataHeader "UK" @@ -85,10 +87,10 @@ struct ForgeInfo uint32 Event; }; -template -AI* GetUtgardeKeepAI(Creature* creature) +template +inline AI* GetUtgardeKeepAI(T* obj) { - return GetInstanceAI(creature, UKScriptName); + return GetInstanceAI(obj, UKScriptName); } #endif // UTGARDE_KEEP_H_ diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp index f4eec389275..60426fe448f 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "utgarde_pinnacle.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" +#include "utgarde_pinnacle.h" enum Spells { @@ -620,9 +624,7 @@ class spell_palehoof_crazed_effect : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CRAZED_TAUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CRAZED_TAUNT }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -654,9 +656,7 @@ class spell_palehoof_awaken_subboss : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ORB_CHANNEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ORB_CHANNEL }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp index 1e2da34120e..4ba41149c45 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp @@ -16,13 +16,16 @@ */ #include "ScriptMgr.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "utgarde_pinnacle.h" -#include "GridNotifiers.h" -#include "Player.h" -#include "MoveSplineInit.h" enum Spells { @@ -322,7 +325,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -436,7 +439,7 @@ public: } } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_LAUNCH_HARPOON) if (Creature* skadi = _instance->GetCreature(DATA_SKADI_THE_RUTHLESS)) @@ -455,7 +458,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -551,7 +554,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -582,7 +585,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -619,7 +622,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -634,9 +637,7 @@ class spell_freezing_cloud_area_right : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FREEZING_CLOUD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FREEZING_CLOUD }); } void FilterTargets(std::list& targets) @@ -673,9 +674,7 @@ class spell_freezing_cloud_area_left : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FREEZING_CLOUD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FREEZING_CLOUD }); } void FilterTargets(std::list& targets) @@ -821,9 +820,7 @@ class spell_skadi_poisoned_spear : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POISONED_SPEAR_PERIODIC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_POISONED_SPEAR_PERIODIC }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp index 7eff09338fc..a9337ffcb15 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp @@ -16,9 +16,14 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "utgarde_pinnacle.h" enum Spells diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp index a55ddfa6bdd..83b25986222 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "utgarde_pinnacle.h" #include "SpellInfo.h" -#include "SpellScript.h" +#include "TemporarySummon.h" +#include "utgarde_pinnacle.h" enum Spells { diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp index 2afe31455ce..c5e6ea0f80b 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "utgarde_pinnacle.h" BossBoundaryData const boundaries = diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h index f4d217c74f3..30fbc460190 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h @@ -18,6 +18,8 @@ #ifndef UTGARDE_PINNACLE_H_ #define UTGARDE_PINNACLE_H_ +#include "CreatureAIImpl.h" + #define UPScriptName "instance_utgarde_pinnacle" #define DataHeader "UP" @@ -95,8 +97,8 @@ enum UPGameObjectIds GO_KING_YMIRON_DOOR = 192174 }; -template -AI* GetUtgardePinnacleAI(T* obj) +template +inline AI* GetUtgardePinnacleAI(T* obj) { return GetInstanceAI(obj, UPScriptName); } diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp index 71ee6285074..03ee2289818 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp @@ -138,7 +138,7 @@ class boss_archavon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_archavonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -212,7 +212,7 @@ class npc_archavon_warder : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_archavon_warderAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -228,12 +228,13 @@ class spell_archavon_rock_shards : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_VISUAL_L) - || !sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_VISUAL_R) - || !sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_DAMAGE_L) - || !sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_DAMAGE_R)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROCK_SHARDS_VISUAL_L, + SPELL_ROCK_SHARDS_VISUAL_R, + SPELL_ROCK_SHARDS_DAMAGE_L, + SPELL_ROCK_SHARDS_DAMAGE_R + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -242,12 +243,12 @@ class spell_archavon_rock_shards : public SpellScriptLoader for (uint8 i = 0; i < 3; ++i) { - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_VISUAL_L, true); - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_VISUAL_R, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_VISUAL_L, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_VISUAL_R, true); } - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_DAMAGE_L, true); - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_DAMAGE_R, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_DAMAGE_L, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_DAMAGE_R, true); } void Register() override diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp index 20a86e2c8f7..aa7bd9db9ab 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "vault_of_archavon.h" @@ -92,7 +94,7 @@ class boss_emalon : public CreatureScript { BossAI::JustSummoned(summoned); - // AttackStart has NULL-check for victim + // AttackStart has nullptr-check for victim if (summoned->AI()) summoned->AI()->AttackStart(me->GetVictim()); } @@ -171,7 +173,7 @@ class boss_emalon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_emalonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -277,7 +279,7 @@ class npc_tempest_minion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVaultOfArchavonAI(creature); } }; diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp index 6141c2167d4..93faab4b854 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp @@ -17,7 +17,6 @@ #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "SpellScript.h" #include "vault_of_archavon.h" @@ -117,7 +116,7 @@ class boss_koralon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_koralonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -181,7 +180,7 @@ class npc_flame_warder : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_flame_warderAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -196,15 +195,13 @@ class spell_koralon_meteor_fists : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_METEOR_FISTS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_METEOR_FISTS_DAMAGE }); } void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, nullptr, aurEff); } void Register() override @@ -273,15 +270,13 @@ class spell_flame_warder_meteor_fists : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FW_METEOR_FISTS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FW_METEOR_FISTS_DAMAGE }); } void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp index 5747d20160d..0f785817e9b 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "vault_of_archavon.h" @@ -117,7 +119,7 @@ class boss_toravon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_toravonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -172,7 +174,7 @@ class npc_frost_warder : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_frost_warderAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -233,7 +235,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_frozen_orbAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -287,7 +289,7 @@ class npc_frozen_orb_stalker : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVaultOfArchavonAI(creature); } }; diff --git a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp index a3bac4f39dd..f399449932f 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "vault_of_archavon.h" /* Vault of Archavon encounters: @@ -29,7 +31,7 @@ class instance_vault_of_archavon : public InstanceMapScript { public: - instance_vault_of_archavon() : InstanceMapScript("instance_vault_of_archavon", 624) { } + instance_vault_of_archavon() : InstanceMapScript(VoAScriptName, 624) { } struct instance_vault_of_archavon_InstanceMapScript : public InstanceScript { @@ -84,13 +86,13 @@ class instance_vault_of_archavon : public InstanceMapScript switch (type) { case DATA_ARCHAVON: - ArchavonDeath = time(NULL); + ArchavonDeath = time(nullptr); break; case DATA_EMALON: - EmalonDeath = time(NULL); + EmalonDeath = time(nullptr); break; case DATA_KORALON: - KoralonDeath = time(NULL); + KoralonDeath = time(nullptr); break; default: return true; diff --git a/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h b/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h index 3af77979c68..d4f252d3715 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h +++ b/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h @@ -18,6 +18,9 @@ #ifndef DEF_ARCHAVON_H #define DEF_ARCHAVON_H +#include "CreatureAIImpl.h" + +#define VoAScriptName "instance_vault_of_archavon" #define DataHeader "VA" uint32 const EncounterCount = 4; @@ -49,4 +52,10 @@ enum VAAchievementSpells SPELL_EARTH_WIND_FIRE_ACHIEVEMENT_CHECK = 68308, }; +template +inline AI* GetVaultOfArchavonAI(T* obj) +{ + return GetInstanceAI(obj, VoAScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp b/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp index ebcc48f5ed8..bb7239d2cc5 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "SpellScript.h" #include "ScriptedCreature.h" #include "violet_hold.h" @@ -154,9 +155,7 @@ class spell_cyanigosa_arcane_vacuum : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PLAYER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_PLAYER }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp b/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp index 1bc7223f08e..1346363a920 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp @@ -16,6 +16,9 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "violet_hold.h" diff --git a/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp b/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp index 3ce72ebd74f..12efea5646a 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" -#include "SpellAuraEffects.h" +#include "SpellAuras.h" #include "SpellScript.h" #include "violet_hold.h" @@ -351,9 +353,7 @@ class spell_ichoron_merge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHRINK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHRINK }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -426,14 +426,15 @@ class spell_ichoron_splatter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_1) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_2) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_3) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_4) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_5) - || !sSpellMgr->GetSpellInfo(SPELL_SHRINK)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WATER_GLOBULE_SUMMON_1, + SPELL_WATER_GLOBULE_SUMMON_2, + SPELL_WATER_GLOBULE_SUMMON_3, + SPELL_WATER_GLOBULE_SUMMON_4, + SPELL_WATER_GLOBULE_SUMMON_5, + SPELL_SHRINK + }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp b/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp index 1a25a0b69fe..4434b49a20c 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "violet_hold.h" diff --git a/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp b/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp index cc1e96f78b2..8f8f875b530 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "violet_hold.h" enum Spells diff --git a/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp b/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp index 367ab44b466..b55f9bfb91d 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" #include "violet_hold.h" /* @@ -261,9 +263,7 @@ class spell_xevozz_summon_players : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGIC_PULL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGIC_PULL }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp b/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp index f26ca430538..7fe9068d684 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "violet_hold.h" diff --git a/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp b/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp index a956c11c11b..cf5d256f3a6 100644 --- a/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp +++ b/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "WorldPacket.h" -#include "violet_hold.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" +#include "violet_hold.h" +#include "WorldPacket.h" /* * TODO: @@ -65,7 +69,7 @@ Position const PortalIntroPositions[PortalIntroPositionsSize] = // sniff uint32 const EncouterPortalsCount = PortalPositionsSize + PortalElitePositionsSize; uint32 const MoraggPathSize = 3; -G3D::Vector3 const MoraggPath[MoraggPathSize] = // sniff +Position const MoraggPath[MoraggPathSize] = // sniff { { 1893.895f, 728.1261f, 47.75016f }, { 1892.997f, 738.4987f, 47.66684f }, @@ -73,7 +77,7 @@ G3D::Vector3 const MoraggPath[MoraggPathSize] = // sniff }; uint32 const ErekemPathSize = 3; -G3D::Vector3 const ErekemPath[ErekemPathSize] = // sniff +Position const ErekemPath[ErekemPathSize] = // sniff { { 1871.456f, 871.0361f, 43.41524f }, { 1874.948f, 859.5452f, 43.33349f }, @@ -81,7 +85,7 @@ G3D::Vector3 const ErekemPath[ErekemPathSize] = // sniff }; uint32 const ErekemGuardLeftPathSize = 3; -G3D::Vector3 const ErekemGuardLeftPath[ErekemGuardLeftPathSize] = // sniff +Position const ErekemGuardLeftPath[ErekemGuardLeftPathSize] = // sniff { { 1853.752f, 862.4528f, 43.41614f }, { 1866.931f, 854.577f, 43.3335f }, @@ -89,7 +93,7 @@ G3D::Vector3 const ErekemGuardLeftPath[ErekemGuardLeftPathSize] = // sniff }; uint32 const ErekemGuardRightPathSize = 3; -G3D::Vector3 const ErekemGuardRightPath[ErekemGuardRightPathSize] = // sniff +Position const ErekemGuardRightPath[ErekemGuardRightPathSize] = // sniff { { 1892.418f, 872.2831f, 43.41563f }, { 1885.639f, 859.0245f, 43.3335f }, @@ -97,7 +101,7 @@ G3D::Vector3 const ErekemGuardRightPath[ErekemGuardRightPathSize] = // sniff }; uint32 const IchoronPathSize = 5; -G3D::Vector3 const IchoronPath[IchoronPathSize] = // sniff +Position const IchoronPath[IchoronPathSize] = // sniff { { 1942.041f, 749.5228f, 30.95229f }, { 1930.571f, 762.9065f, 31.98814f }, @@ -107,7 +111,7 @@ G3D::Vector3 const IchoronPath[IchoronPathSize] = // sniff }; uint32 const LavanthorPathSize = 3; -G3D::Vector3 const LavanthorPath[LavanthorPathSize] = // sniff +Position const LavanthorPath[LavanthorPathSize] = // sniff { { 1844.557f, 748.7083f, 38.74205f }, { 1854.618f, 761.5295f, 38.65631f }, @@ -115,7 +119,7 @@ G3D::Vector3 const LavanthorPath[LavanthorPathSize] = // sniff }; uint32 const XevozzPathSize = 3; -G3D::Vector3 const XevozzPath[XevozzPathSize] = // sniff +Position const XevozzPath[XevozzPathSize] = // sniff { { 1908.417f, 845.8502f, 38.71947f }, { 1905.557f, 841.3157f, 38.65529f }, @@ -123,7 +127,7 @@ G3D::Vector3 const XevozzPath[XevozzPathSize] = // sniff }; uint32 const ZuramatPathSize = 3; -G3D::Vector3 const ZuramatPath[ZuramatPathSize] = // sniff +Position const ZuramatPath[ZuramatPathSize] = // sniff { { 1934.151f, 860.9463f, 47.29499f }, { 1927.085f, 852.1342f, 47.19214f }, @@ -330,11 +334,11 @@ class instance_violet_hold : public InstanceMapScript { case DATA_1ST_BOSS: if (state == DONE) - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_EREKEM, nullptr); + UpdateEncounterStateForKilledCreature(NPC_EREKEM, nullptr); break; case DATA_2ND_BOSS: if (state == DONE) - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_MORAGG, nullptr); + UpdateEncounterStateForKilledCreature(NPC_MORAGG, nullptr); break; case DATA_CYANIGOSA: if (state == DONE) diff --git a/src/server/scripts/Northrend/VioletHold/violet_hold.cpp b/src/server/scripts/Northrend/VioletHold/violet_hold.cpp index 4aa2a1aabb5..7f8d987ef31 100644 --- a/src/server/scripts/Northrend/VioletHold/violet_hold.cpp +++ b/src/server/scripts/Northrend/VioletHold/violet_hold.cpp @@ -15,14 +15,18 @@ * with this program. If not, see . */ -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "ScriptedGossip.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "violet_hold.h" /* @@ -156,7 +160,7 @@ enum Sinclari SAY_SINCLARI_PORTAL_KEEPER = 2 }; -G3D::Vector3 const FirstPortalWPs[6] = +Position const FirstPortalWPs[] = { {1877.670288f, 842.280273f, 43.333591f}, {1877.338867f, 834.615356f, 38.762287f}, @@ -167,7 +171,7 @@ G3D::Vector3 const FirstPortalWPs[6] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const SecondPortalFirstWPs[9] = +Position const SecondPortalFirstWPs[] = { {1902.561401f, 853.334656f, 47.106117f}, {1895.486084f, 855.376404f, 44.334591f}, @@ -181,7 +185,7 @@ G3D::Vector3 const SecondPortalFirstWPs[9] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const SecondPortalSecondWPs[8] = +Position const SecondPortalSecondWPs[] = { {1929.392212f, 837.614990f, 47.136166f}, {1928.290649f, 824.750427f, 45.474411f}, @@ -194,7 +198,7 @@ G3D::Vector3 const SecondPortalSecondWPs[8] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const ThirdPortalWPs[8] = +Position const ThirdPortalWPs[] = { {1934.049438f, 815.778503f, 52.408699f}, {1928.290649f, 824.750427f, 45.474411f}, @@ -207,7 +211,7 @@ G3D::Vector3 const ThirdPortalWPs[8] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const FourthPortalWPs[9] = +Position const FourthPortalWPs[] = { {1921.658447f, 761.657043f, 50.866741f}, {1910.559814f, 755.780457f, 47.701447f}, @@ -221,7 +225,7 @@ G3D::Vector3 const FourthPortalWPs[9] = //{1827.100342f, 801.605957f, 44.363358f} }; -G3D::Vector3 const FifthPortalWPs[6] = +Position const FifthPortalWPs[] = { {1887.398804f, 763.633240f, 47.666851f}, {1879.020386f, 775.396973f, 38.705990f}, @@ -232,7 +236,7 @@ G3D::Vector3 const FifthPortalWPs[6] = //{1827.100342f, 801.605957f, 44.363358f} }; -G3D::Vector3 const SixthPoralWPs[4] = +Position const SixthPortalWPs[] = { {1888.861084f, 805.074768f, 38.375790f}, {1869.793823f, 804.135804f, 38.647018f}, @@ -241,13 +245,12 @@ G3D::Vector3 const SixthPoralWPs[4] = //{1826.889648f, 803.929993f, 44.363239f} }; -G3D::Vector3 const DefaultPortalWPs[1] = +Position const DefaultPortalWPs[] = { { 1843.567017f, 804.288208f, 44.139091f } }; -uint32 const SaboteurMoraggPathSize = 5; -G3D::Vector3 const SaboteurMoraggPath[SaboteurMoraggPathSize] = // sniff +Position const SaboteurMoraggPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1885.71f, 799.8929f, 38.37241f }, @@ -256,8 +259,7 @@ G3D::Vector3 const SaboteurMoraggPath[SaboteurMoraggPathSize] = // sniff { 1894.603f, 739.9231f, 47.66684f }, }; -uint32 const SaboteurErekemPathSize = 5; -G3D::Vector3 const SaboteurErekemPath[SaboteurErekemPathSize] = // sniff +Position const SaboteurErekemPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1881.047f, 829.6866f, 38.64856f }, @@ -266,24 +268,21 @@ G3D::Vector3 const SaboteurErekemPath[SaboteurErekemPathSize] = // sniff { 1873.747f, 864.1373f, 43.33349f } }; -uint32 const SaboteurIchoronPathSize = 3; -G3D::Vector3 const SaboteurIchoronPath[SaboteurIchoronPathSize] = // sniff +Position const SaboteurIchoronPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1888.672f, 801.2348f, 38.42305f }, { 1901.987f, 793.3254f, 38.65126f } }; -uint32 const SaboteurLavanthorPathSize = 3; -G3D::Vector3 const SaboteurLavanthorPath[SaboteurLavanthorPathSize] = // sniff +Position const SaboteurLavanthorPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1867.925f, 778.8035f, 38.64702f }, { 1853.304f, 759.0161f, 38.65761f } }; -uint32 const SaboteurXevozzPathSize = 4; -G3D::Vector3 const SaboteurXevozzPath[SaboteurXevozzPathSize] = // sniff +Position const SaboteurXevozzPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1889.096f, 810.0487f, 38.43871f }, @@ -291,8 +290,7 @@ G3D::Vector3 const SaboteurXevozzPath[SaboteurXevozzPathSize] = // sniff { 1906.666f, 842.3111f, 38.63351f } }; -uint32 const SaboteurZuramatPathSize = 7; -G3D::Vector3 const SaboteurZuramatPath[SaboteurZuramatPathSize] = // sniff +Position const SaboteurZuramatPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1889.69f, 807.0032f, 38.39914f }, @@ -543,41 +541,35 @@ class npc_azure_saboteur : public CreatureScript _bossId = _instance->GetData(DATA_2ND_BOSS); } - void StartMovement() + template + void StartSmoothPath(Position const (&path)[N]) { - uint32 pathSize = 0; - G3D::Vector3 const* path = nullptr; + me->GetMotionMaster()->MoveSmoothPath(POINT_INTRO, &path[0], N, false); + } + void StartMovement() + { switch (_bossId) { case DATA_MORAGG: - pathSize = SaboteurMoraggPathSize; - path = SaboteurMoraggPath; + StartSmoothPath(SaboteurMoraggPath); break; case DATA_EREKEM: - pathSize = SaboteurErekemPathSize; - path = SaboteurErekemPath; + StartSmoothPath(SaboteurErekemPath); break; case DATA_ICHORON: - pathSize = SaboteurIchoronPathSize; - path = SaboteurIchoronPath; + StartSmoothPath(SaboteurIchoronPath); break; case DATA_LAVANTHOR: - pathSize = SaboteurLavanthorPathSize; - path = SaboteurLavanthorPath; + StartSmoothPath(SaboteurLavanthorPath); break; case DATA_XEVOZZ: - pathSize = SaboteurXevozzPathSize; - path = SaboteurXevozzPath; + StartSmoothPath(SaboteurXevozzPath); break; case DATA_ZURAMAT: - pathSize = SaboteurZuramatPathSize; - path = SaboteurZuramatPath; + StartSmoothPath(SaboteurZuramatPath); break; } - - if (path) - me->GetMotionMaster()->MoveSmoothPath(POINT_INTRO, path, pathSize, false); } void Reset() override @@ -849,58 +841,57 @@ struct violet_hold_trashAI : public npc_escortAI _scheduler.CancelAll(); } + template + Position const* GetPathAndInitLastWaypointFrom(Position const (&path)[N]) + { + _lastWaypointId = N - 1; + return &path[0]; + } + void SetData(uint32 type, uint32 data) override { if (type == DATA_PORTAL_LOCATION) { - G3D::Vector3 const* path = nullptr; + Position const* path = nullptr; switch (data) { case 0: - _lastWaypointId = 5; - path = FirstPortalWPs; + path = GetPathAndInitLastWaypointFrom(FirstPortalWPs); break; case 7: switch (urand(0, 1)) { case 0: - _lastWaypointId = 8; - path = SecondPortalFirstWPs; + path = GetPathAndInitLastWaypointFrom(SecondPortalFirstWPs); break; case 1: - _lastWaypointId = 7; - path = SecondPortalSecondWPs; + path = GetPathAndInitLastWaypointFrom(SecondPortalSecondWPs); break; } break; case 2: - _lastWaypointId = 7; - path = ThirdPortalWPs; + path = GetPathAndInitLastWaypointFrom(ThirdPortalWPs); break; case 6: - _lastWaypointId = 8; - path = FourthPortalWPs; + path = GetPathAndInitLastWaypointFrom(FourthPortalWPs); break; case 1: - _lastWaypointId = 5; - path = FifthPortalWPs; + path = GetPathAndInitLastWaypointFrom(FifthPortalWPs); break; case 5: - _lastWaypointId = 3; - path = SixthPoralWPs; + path = GetPathAndInitLastWaypointFrom(SixthPortalWPs); break; default: - _lastWaypointId = 0; - path = DefaultPortalWPs; + path = GetPathAndInitLastWaypointFrom(DefaultPortalWPs); break; } if (path) { for (uint32 i = 0; i <= _lastWaypointId; i++) - AddWaypoint(i, path[i].x + irand(-1, 1), path[i].y + irand(-1, 1), path[i].z, 0); - me->SetHomePosition(path[_lastWaypointId].x, path[_lastWaypointId].y, path[_lastWaypointId].z, float(M_PI)); + AddWaypoint(i, path[i].GetPositionX() + irand(-1, 1), path[i].GetPositionY() + irand(-1, 1), path[i].GetPositionZ(), 0); + me->SetHomePosition(path[_lastWaypointId].GetPositionX(), path[_lastWaypointId].GetPositionY(), path[_lastWaypointId].GetPositionZ(), float(M_PI)); } Start(true, true); @@ -1299,7 +1290,7 @@ class npc_violet_hold_defense_system : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_violet_hold_defense_systemAI(creature); + return GetVioletHoldAI(creature); } }; @@ -1404,9 +1395,7 @@ class spell_violet_hold_teleport_player : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_PLAYER_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_PLAYER_EFFECT }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/VioletHold/violet_hold.h b/src/server/scripts/Northrend/VioletHold/violet_hold.h index 4238634d8c1..e6095bd5c01 100644 --- a/src/server/scripts/Northrend/VioletHold/violet_hold.h +++ b/src/server/scripts/Northrend/VioletHold/violet_hold.h @@ -18,6 +18,8 @@ #ifndef VIOLET_HOLD_H_ #define VIOLET_HOLD_H_ +#include "CreatureAIImpl.h" + #define VioletHoldScriptName "instance_violet_hold" #define DataHeader "VH" @@ -151,7 +153,7 @@ enum VHInstanceMisc POINT_INTRO = 1 }; -template +template inline AI* GetVioletHoldAI(T* obj) { return GetInstanceAI(obj, VioletHoldScriptName); diff --git a/src/server/scripts/Northrend/zone_borean_tundra.cpp b/src/server/scripts/Northrend/zone_borean_tundra.cpp index d67df0875aa..2e62c09bc17 100644 --- a/src/server/scripts/Northrend/zone_borean_tundra.cpp +++ b/src/server/scripts/Northrend/zone_borean_tundra.cpp @@ -34,15 +34,19 @@ npc_lurgglbr EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedFollowerAI.h" -#include "Player.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" #include "SpellInfo.h" -#include "WorldSession.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" +#include "WorldSession.h" /*###### ## npc_sinkhole_kill_credit @@ -87,7 +91,7 @@ public: Initialize(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (phase || spell->Id != SPELL_SET_CART) return; @@ -463,7 +467,7 @@ public: void JustDied(Unit* /*killer*/) override { - if (GameObject* go_caribou = me->GetMap()->GetGameObject(go_caribouGUID)) + if (GameObject* go_caribou = ObjectAccessor::GetGameObject(*me, go_caribouGUID)) go_caribou->SetLootState(GO_JUST_DEACTIVATED); if (TempSummon* summon = me->ToTempSummon()) @@ -472,7 +476,7 @@ public: if (Player* player = temp->ToPlayer()) player->KilledMonsterCredit(me->GetEntry()); - if (GameObject* go_caribou = me->GetMap()->GetGameObject(go_caribouGUID)) + if (GameObject* go_caribou = ObjectAccessor::GetGameObject(*me, go_caribouGUID)) go_caribou->SetGoState(GO_STATE_READY); } @@ -516,7 +520,7 @@ public: break; case 7: { - GameObject* go_caribou = NULL; + GameObject* go_caribou = nullptr; for (uint8 i = 0; i < CaribouTrapsNum; ++i) { go_caribou = me->FindNearestGameObject(CaribouTraps[i], 5.0f); @@ -1457,7 +1461,7 @@ public: AttackStart(who); } - void SpellHit(Unit* pCaster, const SpellInfo* pSpell) override + void SpellHit(Unit* pCaster, SpellInfo const* pSpell) override { if (pSpell->Id == SPELL_ARCANE_CHAINS && pCaster->GetTypeId() == TYPEID_PLAYER && !HealthAbovePct(50) && !bEnslaved) { @@ -1567,7 +1571,7 @@ public: { } - void SpellHit(Unit* unit, const SpellInfo* spell) override + void SpellHit(Unit* unit, SpellInfo const* spell) override { if (spell->Id == SPELL_NEURAL_NEEDLE && unit->GetTypeId() == TYPEID_PLAYER) if (Player* player = unit->ToPlayer()) @@ -1645,7 +1649,7 @@ public: void JustDied(Unit* /*killer*/) override { - if (Player* player=GetPlayerForEscort()) + if (Player* player = GetPlayerForEscort()) player->FailQuest(QUEST_ESCAPING_THE_MIST); } @@ -1860,7 +1864,7 @@ public: { Initialize(); - GameObject* pTrap = NULL; + GameObject* pTrap = nullptr; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = me->FindNearestGameObject(MammothTraps[i], 11.0f); @@ -1899,7 +1903,7 @@ public: me->DisappearAndDie(); - GameObject* pTrap = NULL; + GameObject* pTrap = nullptr; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = me->FindNearestGameObject(MammothTraps[i], 11.0f); @@ -2160,9 +2164,9 @@ enum HiddenCultist SAY_HIDDEN_CULTIST_4 = 3 }; -const char* GOSSIP_ITEM_TOM_HEGGER = "What do you know about the Cult of the Damned?"; -const char* GOSSIP_ITEM_GUARD_MITCHELLS = "How long have you worked for the Cult of the Damned?"; -const char* GOSSIP_ITEM_SALTY_JOHN_THORPE = "I have a reason to believe you're involved in the cultist activity"; +char const* GOSSIP_ITEM_TOM_HEGGER = "What do you know about the Cult of the Damned?"; +char const* GOSSIP_ITEM_GUARD_MITCHELLS = "How long have you worked for the Cult of the Damned?"; +char const* GOSSIP_ITEM_SALTY_JOHN_THORPE = "I have a reason to believe you're involved in the cultist activity"; class npc_hidden_cultist : public CreatureScript { @@ -2290,7 +2294,7 @@ public: bool GossipHello(Player* player) override { uint32 uiGossipText = 0; - const char* charGossipItem; + char const* charGossipItem; switch (me->GetEntry()) { @@ -2365,7 +2369,7 @@ public: { if (GetTarget()->isDead()) if (Unit* caster = GetCaster()) - caster->CastSpell(NULL, SPELL_WINDSOUL_CREDT); + caster->CastSpell(nullptr, SPELL_WINDSOUL_CREDT); } void Register() override diff --git a/src/server/scripts/Northrend/zone_crystalsong_forest.cpp b/src/server/scripts/Northrend/zone_crystalsong_forest.cpp index 4dadebb1cda..b58ac0ac144 100644 --- a/src/server/scripts/Northrend/zone_crystalsong_forest.cpp +++ b/src/server/scripts/Northrend/zone_crystalsong_forest.cpp @@ -24,8 +24,8 @@ SDCategory: CrystalsongForest Script Data End */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "Player.h" /******************************************************* * npc_warmage_violetstand @@ -97,7 +97,6 @@ public: if (Creature* pOrb = ObjectAccessor::GetCreature(*me, targetGUID)) DoCast(pOrb, SPELL_TRANSITUS_SHIELD_BEAM); - } }; diff --git a/src/server/scripts/Northrend/zone_dalaran.cpp b/src/server/scripts/Northrend/zone_dalaran.cpp index 0e51de2382a..a8920ff3a07 100644 --- a/src/server/scripts/Northrend/zone_dalaran.cpp +++ b/src/server/scripts/Northrend/zone_dalaran.cpp @@ -24,9 +24,13 @@ SDCategory: Dalaran Script Data End */ #include "ScriptMgr.h" +#include "DatabaseEnv.h" +#include "Mail.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" #include "WorldSession.h" /******************************************************* @@ -165,17 +169,16 @@ class npc_minigob_manabonk : public CreatureScript Player* SelectTargetInDalaran() { - std::list PlayerInDalaranList; - PlayerInDalaranList.clear(); + std::vector PlayerInDalaranList; - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (Player* player = itr->GetSource()->ToPlayer()) if (player->GetZoneId() == ZONE_DALARAN && !player->IsFlying() && !player->IsMounted() && !player->IsGameMaster()) PlayerInDalaranList.push_back(player); if (PlayerInDalaranList.empty()) - return NULL; + return nullptr; return Trinity::Containers::SelectRandomContainerElement(PlayerInDalaranList); } diff --git a/src/server/scripts/Northrend/zone_dragonblight.cpp b/src/server/scripts/Northrend/zone_dragonblight.cpp index 0d718c6b365..e8b70b98010 100644 --- a/src/server/scripts/Northrend/zone_dragonblight.cpp +++ b/src/server/scripts/Northrend/zone_dragonblight.cpp @@ -28,14 +28,16 @@ npc_alexstrasza_wr_gate EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CombatAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "ScriptedEscortAI.h" #include "ScriptedGossip.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ScriptedEscortAI.h" #include "Vehicle.h" -#include "CombatAI.h" -#include "Player.h" /*##### # npc_commander_eligor_dawnbringer @@ -640,7 +642,7 @@ class npc_torturer_lecraft : public CreatureScript Talk (SAY_AGGRO, player); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id != SPELL_HIGH_EXECUTORS_BRANDING_IRON) return; @@ -715,7 +717,7 @@ class at_nearby_messenger_torvus : public AreaTriggerScript public: at_nearby_messenger_torvus() : AreaTriggerScript("at_nearby_messenger_torvus") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player->IsAlive()) if (Quest const* quest = sObjectMgr->GetQuestTemplate(QUEST_MESSAGE_FROM_THE_WEST)) diff --git a/src/server/scripts/Northrend/zone_grizzly_hills.cpp b/src/server/scripts/Northrend/zone_grizzly_hills.cpp index fb724e0dc93..78be007420d 100644 --- a/src/server/scripts/Northrend/zone_grizzly_hills.cpp +++ b/src/server/scripts/Northrend/zone_grizzly_hills.cpp @@ -17,12 +17,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "CombatAI.h" +#include "CreatureTextMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "CreatureTextMgr.h" -#include "CombatAI.h" +#include "TemporarySummon.h" /*###### ## Quest 12027: Mr. Floppy's Perilous Adventure @@ -300,7 +303,7 @@ public: _gender = Data; } - void SpellHit(Unit* Caster, const SpellInfo* Spell) override + void SpellHit(Unit* Caster, SpellInfo const* Spell) override { if (Spell->Id == SPELL_OUTHOUSE_GROANS) { @@ -495,7 +498,7 @@ public: me->DespawnOrUnsummon(_despawnTimer); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_RENEW_SKIRMISHER && caster->GetTypeId() == TYPEID_PLAYER && caster->ToPlayer()->GetQuestStatus(QUEST_OVERWHELMED) == QUEST_STATUS_INCOMPLETE) @@ -953,9 +956,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARHEAD_Z_CHECK) || !sSpellMgr->GetSpellInfo(SPELL_WARHEAD_SEEKING_LUMBERSHIP) || !sSpellMgr->GetSpellInfo(SPELL_WARHEAD_FUSE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARHEAD_Z_CHECK, SPELL_WARHEAD_SEEKING_LUMBERSHIP, SPELL_WARHEAD_FUSE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -997,9 +998,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARACHUTE) || !sSpellMgr->GetSpellInfo(SPELL_TORPEDO_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARACHUTE, SPELL_TORPEDO_EXPLOSION }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/zone_howling_fjord.cpp b/src/server/scripts/Northrend/zone_howling_fjord.cpp index 595008c38a7..aeb2fa3e59a 100644 --- a/src/server/scripts/Northrend/zone_howling_fjord.cpp +++ b/src/server/scripts/Northrend/zone_howling_fjord.cpp @@ -28,12 +28,14 @@ npc_apothecary_hanes EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" /*###### ## npc_apothecary_hanes @@ -560,9 +562,7 @@ class spell_mindless_abomination_explosion_fx_master : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RANDOM_CIRCUMFERENCE_POINT_POISON) || !sSpellMgr->GetSpellInfo(SPELL_COSMETIC_BLOOD_EXPLOSION_GREEN_LARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RANDOM_CIRCUMFERENCE_POINT_POISON, SPELL_COSMETIC_BLOOD_EXPLOSION_GREEN_LARGE }); } void HandleScript(SpellEffIndex /*eff*/) diff --git a/src/server/scripts/Northrend/zone_icecrown.cpp b/src/server/scripts/Northrend/zone_icecrown.cpp index 849a3d5568b..b7f60c8e9d2 100644 --- a/src/server/scripts/Northrend/zone_icecrown.cpp +++ b/src/server/scripts/Northrend/zone_icecrown.cpp @@ -17,12 +17,14 @@ */ #include "ScriptMgr.h" +#include "CombatAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellAuras.h" -#include "Player.h" #include "TemporarySummon.h" -#include "CombatAI.h" /*###### ## npc_argent_valiant diff --git a/src/server/scripts/Northrend/zone_sholazar_basin.cpp b/src/server/scripts/Northrend/zone_sholazar_basin.cpp index 4022c293aae..118aae0da83 100644 --- a/src/server/scripts/Northrend/zone_sholazar_basin.cpp +++ b/src/server/scripts/Northrend/zone_sholazar_basin.cpp @@ -29,14 +29,18 @@ npc_haiphoon (Quest: "Song of Wind and Water") EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "CombatAI.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" #include "ScriptedEscortAI.h" -#include "SpellScript.h" +#include "ScriptedGossip.h" #include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "CombatAI.h" -#include "Player.h" /*###### ## npc_vekjik @@ -275,7 +279,7 @@ public: case 1: Talk(SAY_WP_3); me->CastSpell(5918.33f, 5372.91f, -98.770f, SPELL_EXPLODE_CRYSTAL, true); - me->SummonGameObject(184743, 5918.33f, 5372.91f, -98.770f, 0, G3D::Quat(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds + me->SummonGameObject(184743, 5918.33f, 5372.91f, -98.770f, 0, QuaternionData(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds me->HandleEmoteCommand(EMOTE_ONESHOT_LAUGH); break; case 2: @@ -286,7 +290,7 @@ public: break; case 8: me->CastSpell(5887.37f, 5379.39f, -91.289f, SPELL_EXPLODE_CRYSTAL, true); - me->SummonGameObject(184743, 5887.37f, 5379.39f, -91.289f, 0, G3D::Quat(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds + me->SummonGameObject(184743, 5887.37f, 5379.39f, -91.289f, 0, QuaternionData(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds me->HandleEmoteCommand(EMOTE_ONESHOT_LAUGH); break; case 9: diff --git a/src/server/scripts/Northrend/zone_storm_peaks.cpp b/src/server/scripts/Northrend/zone_storm_peaks.cpp index 806aff4f3b3..5bc39c7e47d 100644 --- a/src/server/scripts/Northrend/zone_storm_peaks.cpp +++ b/src/server/scripts/Northrend/zone_storm_peaks.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "CombatAI.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" #include "SpellHistory.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "CombatAI.h" -#include "Player.h" #include "WorldSession.h" ///////////////////// @@ -222,7 +225,7 @@ public: me->DespawnOrUnsummon(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id != SPELL_ICE_LANCE) return; @@ -528,7 +531,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) voice->AI()->Talk(SAY_VOICE_1, player); } - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_1, 7860.273f, -1383.622f, 1538.302f, -1.658062f, G3D::Quat(0.f, 0.f, -0.737277f, 0.6755905f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_1, 7860.273f, -1383.622f, 1538.302f, -1.658062f, QuaternionData(0.f, 0.f, -0.737277f, 0.6755905f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_5, 6000); break; @@ -536,7 +539,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_2, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_2, 7875.67f, -1387.266f, 1538.323f, -2.373644f, G3D::Quat(0.f, 0.f, -0.9271832f, 0.3746083f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_2, 7875.67f, -1387.266f, 1538.323f, -2.373644f, QuaternionData(0.f, 0.f, -0.9271832f, 0.3746083f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_6, 6000); break; @@ -544,7 +547,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_3, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_3, 7879.212f, -1401.175f, 1538.279f, 2.967041f, G3D::Quat(0.f, 0.f, 0.9961939f, 0.08716504f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_3, 7879.212f, -1401.175f, 1538.279f, 2.967041f, QuaternionData(0.f, 0.f, 0.9961939f, 0.08716504f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_7, 6000); break; @@ -552,7 +555,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_4, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_4, 7868.944f, -1411.18f, 1538.213f, 2.111848f, G3D::Quat(0.f, 0.f, 0.8703556f, 0.4924237f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_4, 7868.944f, -1411.18f, 1538.213f, 2.111848f, QuaternionData(0.f, 0.f, 0.8703556f, 0.4924237f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_8, 6000); break; @@ -560,7 +563,7 @@ public: if (Player* player = ObjectAccessor::GetPlayer(*me, playerGUID)) if (Creature* voice = ObjectAccessor::GetCreature(*me, voiceGUID)) voice->AI()->Talk(SAY_VOICE_5, player); - if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_5, 7855.11f, -1406.839f, 1538.42f, 1.151916f, G3D::Quat(0.f, 0.f, 0.5446386f, 0.8386708f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_5, 7855.11f, -1406.839f, 1538.42f, 1.151916f, QuaternionData(0.f, 0.f, 0.5446386f, 0.8386708f), 0)) objectGUID[objectCounter] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_9, 6000); break; @@ -968,9 +971,7 @@ class spell_jokkum_scriptcast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_JOKKUM_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_JOKKUM_SUMMON }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1001,9 +1002,7 @@ class spell_veranus_summon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_VERANUS_AND_THORIM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_VERANUS_AND_THORIM }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1038,22 +1037,15 @@ class spell_close_rift : public SpellScriptLoader { PrepareAuraScript(spell_close_rift_AuraScript); - public: - spell_close_rift_AuraScript() - { - _counter = 0; - } - - private: bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_DESPAWN_RIFT) != nullptr; + return ValidateSpellInfo({ SPELL_DESPAWN_RIFT }); } void HandlePeriodic(AuraEffect const* /* aurEff */) { if (++_counter == 5) - GetTarget()->CastSpell((Unit*)NULL, SPELL_DESPAWN_RIFT, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_DESPAWN_RIFT, true); } void Register() override @@ -1062,7 +1054,7 @@ class spell_close_rift : public SpellScriptLoader } private: - uint8 _counter; + uint8 _counter = 0; }; @@ -1084,9 +1076,7 @@ class spell_eject_passenger_wild_wyrm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIGHT_WYRM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIGHT_WYRM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1246,9 +1236,7 @@ class spell_low_health_trigger : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1352,9 +1340,7 @@ class spell_fatal_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FATAL_STRIKE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FATAL_STRIKE_DAMAGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1431,9 +1417,7 @@ class spell_player_mount_wyrm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIGHT_WYRM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIGHT_WYRM }); } void HandleDummy(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/zone_wintergrasp.cpp b/src/server/scripts/Northrend/zone_wintergrasp.cpp index 5f8148dcfa9..64ac0441f93 100644 --- a/src/server/scripts/Northrend/zone_wintergrasp.cpp +++ b/src/server/scripts/Northrend/zone_wintergrasp.cpp @@ -1,31 +1,35 @@ -/* Copyright (C) 2008 - 2009 Trinity - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. +/* + * Copyright (C) 2008-2017 TrinityCore * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . */ +#include "ScriptMgr.h" +#include "Battlefield.h" #include "BattlefieldMgr.h" #include "BattlefieldWG.h" -#include "Battlefield.h" -#include "ScriptSystem.h" -#include "WorldSession.h" -#include "ObjectMgr.h" -#include "Vehicle.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "ObjectMgr.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "ScriptSystem.h" #include "SpellScript.h" -#include "Player.h" +#include "Vehicle.h" +#include "WorldSession.h" #define GOSSIP_HELLO_DEMO1 "Build catapult." #define GOSSIP_HELLO_DEMO2 "Build demolisher." @@ -304,7 +308,7 @@ class npc_wg_queue : public CreatureScript else { uint32 timer = wintergrasp->GetTimer() / 1000; - player->SendUpdateWorldState(4354, time(NULL) + timer); + player->SendUpdateWorldState(4354, time(nullptr) + timer); if (timer < 15 * MINUTE) { AddGossipItemFor(player, GOSSIP_ICON_CHAT, player->GetSession()->GetTrinityString(WG_NPCQUEUE_TEXTOPTION_JOIN), GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); @@ -431,12 +435,13 @@ class spell_wintergrasp_force_building : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BUILD_CATAPULT_FORCE) - || !sSpellMgr->GetSpellInfo(SPELL_BUILD_DEMOLISHER_FORCE) - || !sSpellMgr->GetSpellInfo(SPELL_BUILD_SIEGE_VEHICLE_FORCE_HORDE) - || !sSpellMgr->GetSpellInfo(SPELL_BUILD_SIEGE_VEHICLE_FORCE_ALLIANCE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_BUILD_CATAPULT_FORCE, + SPELL_BUILD_DEMOLISHER_FORCE, + SPELL_BUILD_SIEGE_VEHICLE_FORCE_HORDE, + SPELL_BUILD_SIEGE_VEHICLE_FORCE_ALLIANCE + }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/Northrend/zone_zuldrak.cpp b/src/server/scripts/Northrend/zone_zuldrak.cpp index a4eac22f16c..607e6845157 100644 --- a/src/server/scripts/Northrend/zone_zuldrak.cpp +++ b/src/server/scripts/Northrend/zone_zuldrak.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "Vehicle.h" /*#### @@ -86,7 +89,7 @@ public: me->setDeathState(DEAD); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_UNLOCK_SHACKLE) { @@ -142,7 +145,7 @@ public: void MoveInLineOfSight(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_FREE_RAGECLAW) { @@ -646,9 +649,12 @@ class spell_random_ingredient_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RANDOM_INGREDIENT_EASY) || !sSpellMgr->GetSpellInfo(SPELL_RANDOM_INGREDIENT_MEDIUM) || !sSpellMgr->GetSpellInfo(SPELL_RANDOM_INGREDIENT_HARD)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_RANDOM_INGREDIENT_EASY, + SPELL_RANDOM_INGREDIENT_MEDIUM, + SPELL_RANDOM_INGREDIENT_HARD + }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -693,15 +699,30 @@ class spell_random_ingredient : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FETCH_KNOTROOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PICKLED_EAGLE_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPECKLED_GUANO) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_WITHERED_BATWING) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SEASONED_SLIDER_CIDER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_MUDDY_MIRE_MAGGOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPIKY_SPIDER_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_HAIRY_HERRING_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_ICECROWN_BOTTLED_WATER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_WASPS_WINGS) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PRISMATIC_MOJO) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_RAPTOR_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_AMBERSEED) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CHILLED_SERPENT_MUCUS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRYSTALLIZED_HOGSNOT) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_TROLLBANE) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_FROZEN_SPIDER_ICHOR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FETCH_KNOTROOT, SPELL_HAVE_KNOTROOT, + SPELL_FETCH_PICKLED_EAGLE_EGG, SPELL_HAVE_PICKLED_EAGLE_EGG, + SPELL_FETCH_SPECKLED_GUANO, SPELL_HAVE_SPECKLED_GUANO, + SPELL_FETCH_WITHERED_BATWING, SPELL_HAVE_WITHERED_BATWING, + SPELL_FETCH_SEASONED_SLIDER_CIDER, SPELL_HAVE_SEASONED_SLIDER_CIDER, + SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH, SPELL_HAVE_PULVERIZED_GARGOYLE_TEETH, + SPELL_FETCH_MUDDY_MIRE_MAGGOT, SPELL_HAVE_MUDDY_MIRE_MAGGOT, + SPELL_FETCH_SPIKY_SPIDER_EGG, SPELL_HAVE_SPIKY_SPIDER_EGG, + SPELL_FETCH_HAIRY_HERRING_HEAD, SPELL_HAVE_HAIRY_HERRING_HEAD, + SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION, SPELL_HAVE_PUTRID_PIRATE_PERSPIRATION, + SPELL_FETCH_ICECROWN_BOTTLED_WATER, SPELL_HAVE_ICECROWN_BOTTLED_WATER, + SPELL_FETCH_WASPS_WINGS, SPELL_HAVE_WASPS_WINGS, + SPELL_FETCH_PRISMATIC_MOJO, SPELL_HAVE_PRISMATIC_MOJO, + SPELL_FETCH_RAPTOR_CLAW, SPELL_HAVE_RAPTOR_CLAW, + SPELL_FETCH_AMBERSEED, SPELL_HAVE_AMBERSEED, + SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW, SPELL_HAVE_SHRUNKEN_DRAGONS_CLAW, + SPELL_FETCH_CHILLED_SERPENT_MUCUS, SPELL_HAVE_CHILLED_SERPENT_MUCUS, + SPELL_FETCH_CRYSTALLIZED_HOGSNOT, SPELL_HAVE_CRYSTALLIZED_HOGSNOT, + SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS, SPELL_HAVE_CRUSHED_BASILISK_CRYSTALS, + SPELL_FETCH_TROLLBANE, SPELL_HAVE_TROLLBANE, + SPELL_FETCH_FROZEN_SPIDER_ICHOR, SPELL_HAVE_FROZEN_SPIDER_ICHOR, + }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -725,7 +746,7 @@ class spell_random_ingredient : public SpellScriptLoader if (Creature* finklestein = GetClosestCreatureWithEntry(player, NPC_FINKLESTEIN, 25.0f)) { - finklestein->CastSpell(player, FetchIngredients[ingredient][0], true, NULL); + finklestein->CastSpell(player, FetchIngredients[ingredient][0], true, nullptr); finklestein->AI()->Talk(FetchIngredients[ingredient][3], player); } } @@ -757,22 +778,30 @@ class spell_pot_check : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FETCH_KNOTROOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PICKLED_EAGLE_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPECKLED_GUANO) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_WITHERED_BATWING) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SEASONED_SLIDER_CIDER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_MUDDY_MIRE_MAGGOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPIKY_SPIDER_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_HAIRY_HERRING_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_ICECROWN_BOTTLED_WATER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_WASPS_WINGS) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PRISMATIC_MOJO) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_RAPTOR_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_AMBERSEED) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CHILLED_SERPENT_MUCUS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRYSTALLIZED_HOGSNOT) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_TROLLBANE) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_FROZEN_SPIDER_ICHOR) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_KNOTROOT) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_PICKLED_EAGLE_EGG) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_SPECKLED_GUANO) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_WITHERED_BATWING) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_SEASONED_SLIDER_CIDER) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_PULVERIZED_GARGOYLE_TEETH) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_MUDDY_MIRE_MAGGOT) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_SPIKY_SPIDER_EGG) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_HAIRY_HERRING_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_PUTRID_PIRATE_PERSPIRATION) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_ICECROWN_BOTTLED_WATER) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_WASPS_WINGS) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_PRISMATIC_MOJO) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_RAPTOR_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_AMBERSEED) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_SHRUNKEN_DRAGONS_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_CHILLED_SERPENT_MUCUS) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_CRYSTALLIZED_HOGSNOT) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_CRUSHED_BASILISK_CRYSTALS) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_TROLLBANE) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_FROZEN_SPIDER_ICHOR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FETCH_KNOTROOT, SPELL_HAVE_KNOTROOT, + SPELL_FETCH_PICKLED_EAGLE_EGG, SPELL_HAVE_PICKLED_EAGLE_EGG, + SPELL_FETCH_SPECKLED_GUANO, SPELL_HAVE_SPECKLED_GUANO, + SPELL_FETCH_WITHERED_BATWING, SPELL_HAVE_WITHERED_BATWING, + SPELL_FETCH_SEASONED_SLIDER_CIDER, SPELL_HAVE_SEASONED_SLIDER_CIDER, + SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH, SPELL_HAVE_PULVERIZED_GARGOYLE_TEETH, + SPELL_FETCH_MUDDY_MIRE_MAGGOT, SPELL_HAVE_MUDDY_MIRE_MAGGOT, + SPELL_FETCH_SPIKY_SPIDER_EGG, SPELL_HAVE_SPIKY_SPIDER_EGG, + SPELL_FETCH_HAIRY_HERRING_HEAD, SPELL_HAVE_HAIRY_HERRING_HEAD, + SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION, SPELL_HAVE_PUTRID_PIRATE_PERSPIRATION, + SPELL_FETCH_ICECROWN_BOTTLED_WATER, SPELL_HAVE_ICECROWN_BOTTLED_WATER, + SPELL_FETCH_WASPS_WINGS, SPELL_HAVE_WASPS_WINGS, + SPELL_FETCH_PRISMATIC_MOJO, SPELL_HAVE_PRISMATIC_MOJO, + SPELL_FETCH_RAPTOR_CLAW, SPELL_HAVE_RAPTOR_CLAW, + SPELL_FETCH_AMBERSEED, SPELL_HAVE_AMBERSEED, + SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW, SPELL_HAVE_SHRUNKEN_DRAGONS_CLAW, + SPELL_FETCH_CHILLED_SERPENT_MUCUS, SPELL_HAVE_CHILLED_SERPENT_MUCUS, + SPELL_FETCH_CRYSTALLIZED_HOGSNOT, SPELL_HAVE_CRYSTALLIZED_HOGSNOT, + SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS, SPELL_HAVE_CRUSHED_BASILISK_CRYSTALS, + SPELL_FETCH_TROLLBANE, SPELL_HAVE_TROLLBANE, + SPELL_FETCH_FROZEN_SPIDER_ICHOR, SPELL_HAVE_FROZEN_SPIDER_ICHOR, + }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -900,7 +929,7 @@ public: Reset(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id != GYMERS_GRAB) return; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp index c73327f652c..01598548041 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp @@ -31,9 +31,9 @@ uint32 const EP_AllianceBuffs[4] = { 11413, 11414, 11415, 1386 }; uint32 const EP_HordeBuffs[4] = { 30880, 30683, 30682, 29520 }; -uint32 const EP_GraveYardZone = 139; +uint32 const EP_GraveyardZone = 139; -uint32 const EP_GraveYardId = 927; +uint32 const EP_GraveyardId = 927; uint8 const EPBuffZonesNum = 3; @@ -116,14 +116,14 @@ void OPvPCapturePointEP_EWT::ChangeState() artkit = 2; SummonSupportUnitAtNorthpassTower(ALLIANCE); ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_EWT, ALLIANCE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_EASTWALL_TOWER_TAKEN_ALLIANCE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_EASTWALL_TOWER_TAKEN_ALLIANCE); break; case OBJECTIVESTATE_HORDE: m_TowerState = EP_TS_H; artkit = 1; SummonSupportUnitAtNorthpassTower(HORDE); ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_EWT, HORDE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_EASTWALL_TOWER_TAKEN_HORDE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_EASTWALL_TOWER_TAKEN_HORDE); break; case OBJECTIVESTATE_NEUTRAL: m_TowerState = EP_TS_N; @@ -214,14 +214,14 @@ void OPvPCapturePointEP_NPT::ChangeState() artkit = 2; SummonGO(ALLIANCE); ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_NPT, ALLIANCE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_NORTHPASS_TOWER_TAKEN_ALLIANCE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_NORTHPASS_TOWER_TAKEN_ALLIANCE); break; case OBJECTIVESTATE_HORDE: m_TowerState = EP_TS_H; artkit = 1; SummonGO(HORDE); ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_NPT, HORDE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_NORTHPASS_TOWER_TAKEN_HORDE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_NORTHPASS_TOWER_TAKEN_HORDE); break; case OBJECTIVESTATE_NEUTRAL: m_TowerState = EP_TS_N; @@ -317,16 +317,16 @@ void OPvPCapturePointEP_CGT::ChangeState() case OBJECTIVESTATE_ALLIANCE: m_TowerState = EP_TS_A; artkit = 2; - LinkGraveYard(ALLIANCE); + LinkGraveyard(ALLIANCE); ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_CGT, ALLIANCE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_CROWN_GUARD_TOWER_TAKEN_ALLIANCE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_CROWN_GUARD_TOWER_TAKEN_ALLIANCE); break; case OBJECTIVESTATE_HORDE: m_TowerState = EP_TS_H; artkit = 1; - LinkGraveYard(HORDE); + LinkGraveyard(HORDE); ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_CGT, HORDE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_CROWN_GUARD_TOWER_TAKEN_HORDE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_CROWN_GUARD_TOWER_TAKEN_HORDE); break; case OBJECTIVESTATE_NEUTRAL: m_TowerState = EP_TS_N; @@ -375,13 +375,13 @@ void OPvPCapturePointEP_CGT::UpdateTowerState() m_PvP->SendUpdateWorldState(EP_CGT_N, (m_TowerState & EP_TS_N) != 0); } -void OPvPCapturePointEP_CGT::LinkGraveYard(uint32 team) +void OPvPCapturePointEP_CGT::LinkGraveyard(uint32 team) { if (m_GraveyardSide != team) { m_GraveyardSide = team; - sObjectMgr->RemoveGraveYardLink(EP_GraveYardId, EP_GraveYardZone, team, false); - sObjectMgr->AddGraveYardLink(EP_GraveYardId, EP_GraveYardZone, team, false); + sObjectMgr->RemoveGraveyardLink(EP_GraveyardId, EP_GraveyardZone, team, false); + sObjectMgr->AddGraveyardLink(EP_GraveyardId, EP_GraveyardZone, team, false); } } @@ -408,14 +408,14 @@ void OPvPCapturePointEP_PWT::ChangeState() SummonFlightMaster(ALLIANCE); artkit = 2; ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_PWT, ALLIANCE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_PLAGUEWOOD_TOWER_TAKEN_ALLIANCE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_PLAGUEWOOD_TOWER_TAKEN_ALLIANCE); break; case OBJECTIVESTATE_HORDE: m_TowerState = EP_TS_H; SummonFlightMaster(HORDE); artkit = 1; ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_PWT, HORDE); - m_PvP->SendDefenseMessage(EP_GraveYardZone, TEXT_PLAGUEWOOD_TOWER_TAKEN_HORDE); + m_PvP->SendDefenseMessage(EP_GraveyardZone, TEXT_PLAGUEWOOD_TOWER_TAKEN_HORDE); break; case OBJECTIVESTATE_NEUTRAL: m_TowerState = EP_TS_N; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h b/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h index e5c92129c47..5d9dbf97296 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h @@ -175,7 +175,7 @@ class OPvPCapturePointEP_CGT : public OPvPCapturePoint void FillInitialWorldStates(WorldPacket & data); protected: - void LinkGraveYard(uint32 team); + void LinkGraveyard(uint32 team); void UpdateTowerState(); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp index 99fa669d731..72fb3efc961 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp @@ -15,16 +15,14 @@ * with this program. If not, see . */ -#include "MapManager.h" #include "ScriptMgr.h" +#include "GameObject.h" +#include "Map.h" #include "OutdoorPvPHP.h" -#include "OutdoorPvP.h" #include "OutdoorPvPMgr.h" #include "Player.h" -#include "ObjectMgr.h" #include "WorldPacket.h" - uint32 const OutdoorPvPHPBuffZonesNum = 6; // HP, citadel, ramparts, blood furnace, shattered halls, mag's lair uint32 const OutdoorPvPHPBuffZones[OutdoorPvPHPBuffZonesNum] = { 3483, 3563, 3562, 3713, 3714, 3836 }; @@ -254,7 +252,7 @@ void OPvPCapturePointHP::ChangeState() break; } - Map* map = sMapMgr->FindMap(530, 0); + Map* map = m_PvP->GetMap(); auto bounds = map->GetGameObjectBySpawnIdStore().equal_range(m_capturePointSpawnId); for (auto itr = bounds.first; itr != bounds.second; ++itr) itr->second->SetGoArtKit(artkit); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp index 2b3eb49c13f..12070e4130a 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp @@ -15,12 +15,14 @@ * with this program. If not, see . */ -#include "MapManager.h" #include "ScriptMgr.h" -#include "OutdoorPvPNA.h" -#include "Player.h" +#include "Creature.h" +#include "GameObject.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" +#include "OutdoorPvPNA.h" +#include "Map.h" +#include "Player.h" #include "WorldPacket.h" // kill credit for pks @@ -132,7 +134,7 @@ creature_type const AllianceControlNPCs[NA_CONTROL_NPC_NUM] = OutdoorPvPNA::OutdoorPvPNA() { m_TypeId = OUTDOOR_PVP_NA; - m_obj = NULL; + m_obj = nullptr; } void OutdoorPvPNA::HandleKillImpl(Player* player, Unit* killed) @@ -154,30 +156,30 @@ uint32 OPvPCapturePointNA::GetAliveGuardsCount() { switch (itr->first) { - case NA_NPC_GUARD_01: - case NA_NPC_GUARD_02: - case NA_NPC_GUARD_03: - case NA_NPC_GUARD_04: - case NA_NPC_GUARD_05: - case NA_NPC_GUARD_06: - case NA_NPC_GUARD_07: - case NA_NPC_GUARD_08: - case NA_NPC_GUARD_09: - case NA_NPC_GUARD_10: - case NA_NPC_GUARD_11: - case NA_NPC_GUARD_12: - case NA_NPC_GUARD_13: - case NA_NPC_GUARD_14: - case NA_NPC_GUARD_15: - { - auto bounds = m_PvP->GetMap()->GetCreatureBySpawnIdStore().equal_range(itr->second); - for (auto itr2 = bounds.first; itr2 != bounds.second; ++itr2) - if (itr2->second->IsAlive()) - ++cnt; - break; - } - default: - break; + case NA_NPC_GUARD_01: + case NA_NPC_GUARD_02: + case NA_NPC_GUARD_03: + case NA_NPC_GUARD_04: + case NA_NPC_GUARD_05: + case NA_NPC_GUARD_06: + case NA_NPC_GUARD_07: + case NA_NPC_GUARD_08: + case NA_NPC_GUARD_09: + case NA_NPC_GUARD_10: + case NA_NPC_GUARD_11: + case NA_NPC_GUARD_12: + case NA_NPC_GUARD_13: + case NA_NPC_GUARD_14: + case NA_NPC_GUARD_15: + { + auto bounds = m_PvP->GetMap()->GetCreatureBySpawnIdStore().equal_range(itr->second); + for (auto itr2 = bounds.first; itr2 != bounds.second; ++itr2) + if (itr2->second->IsAlive()) + ++cnt; + break; + } + default: + break; } } return cnt; @@ -241,11 +243,11 @@ void OPvPCapturePointNA::DeSpawnGOs() void OPvPCapturePointNA::FactionTakeOver(uint32 team) { if (m_ControllingFaction) - sObjectMgr->RemoveGraveYardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); + sObjectMgr->RemoveGraveyardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); m_ControllingFaction = team; if (m_ControllingFaction) - sObjectMgr->AddGraveYardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); + sObjectMgr->AddGraveyardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); DeSpawnGOs(); DeSpawnNPCs(); SpawnGOsForTeam(team); @@ -487,11 +489,11 @@ int32 OPvPCapturePointNA::HandleOpenGo(Player* player, GameObject* go) int32 retval = OPvPCapturePoint::HandleOpenGo(player, go); if (retval >= 0) { - const go_type * gos = NULL; + go_type const* gos = nullptr; if (m_ControllingFaction == ALLIANCE) - gos=AllianceControlGOs; + gos = AllianceControlGOs; else if (m_ControllingFaction == HORDE) - gos=HordeControlGOs; + gos = HordeControlGOs; else return -1; @@ -502,101 +504,101 @@ int32 OPvPCapturePointNA::HandleOpenGo(Player* player, GameObject* go) switch (retval) { - case NA_DESTROYED_ROOST_S: - del = NA_DESTROYED_ROOST_S; - add = NA_ROOST_S; - add2 = NA_BOMB_WAGON_S; - if (m_ControllingFaction == HORDE) - m_WyvernStateSouth = WYVERN_ALLIANCE; - else - m_WyvernStateSouth = WYVERN_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_S); - break; - case NA_DESTROYED_ROOST_N: - del = NA_DESTROYED_ROOST_N; - add = NA_ROOST_N; - add2 = NA_BOMB_WAGON_N; - if (m_ControllingFaction == HORDE) - m_WyvernStateNorth = WYVERN_ALLIANCE; - else - m_WyvernStateNorth = WYVERN_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_N); - break; - case NA_DESTROYED_ROOST_W: - del = NA_DESTROYED_ROOST_W; - add = NA_ROOST_W; - add2 = NA_BOMB_WAGON_W; - if (m_ControllingFaction == HORDE) - m_WyvernStateWest = WYVERN_ALLIANCE; - else - m_WyvernStateWest = WYVERN_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_W); - break; - case NA_DESTROYED_ROOST_E: - del = NA_DESTROYED_ROOST_E; - add = NA_ROOST_E; - add2 = NA_BOMB_WAGON_E; - if (m_ControllingFaction == HORDE) - m_WyvernStateEast = WYVERN_ALLIANCE; - else - m_WyvernStateEast = WYVERN_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_E); - break; - case NA_BOMB_WAGON_S: - del = NA_BOMB_WAGON_S; - del2 = NA_ROOST_S; - add = NA_DESTROYED_ROOST_S; - if (m_ControllingFaction == HORDE) - m_WyvernStateSouth = WYVERN_NEU_ALLIANCE; - else - m_WyvernStateSouth = WYVERN_NEU_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_S); - break; - case NA_BOMB_WAGON_N: - del = NA_BOMB_WAGON_N; - del2 = NA_ROOST_N; - add = NA_DESTROYED_ROOST_N; - if (m_ControllingFaction == HORDE) - m_WyvernStateNorth = WYVERN_NEU_ALLIANCE; - else - m_WyvernStateNorth = WYVERN_NEU_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_N); - break; - case NA_BOMB_WAGON_W: - del = NA_BOMB_WAGON_W; - del2 = NA_ROOST_W; - add = NA_DESTROYED_ROOST_W; - if (m_ControllingFaction == HORDE) - m_WyvernStateWest = WYVERN_NEU_ALLIANCE; - else - m_WyvernStateWest = WYVERN_NEU_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_W); - break; - case NA_BOMB_WAGON_E: - del = NA_BOMB_WAGON_E; - del2 = NA_ROOST_E; - add = NA_DESTROYED_ROOST_E; - if (m_ControllingFaction == HORDE) - m_WyvernStateEast = WYVERN_NEU_ALLIANCE; - else - m_WyvernStateEast = WYVERN_NEU_HORDE; - UpdateWyvernRoostWorldState(NA_ROOST_E); - break; - default: - return -1; - break; + case NA_DESTROYED_ROOST_S: + del = NA_DESTROYED_ROOST_S; + add = NA_ROOST_S; + add2 = NA_BOMB_WAGON_S; + if (m_ControllingFaction == HORDE) + m_WyvernStateSouth = WYVERN_ALLIANCE; + else + m_WyvernStateSouth = WYVERN_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_S); + break; + case NA_DESTROYED_ROOST_N: + del = NA_DESTROYED_ROOST_N; + add = NA_ROOST_N; + add2 = NA_BOMB_WAGON_N; + if (m_ControllingFaction == HORDE) + m_WyvernStateNorth = WYVERN_ALLIANCE; + else + m_WyvernStateNorth = WYVERN_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_N); + break; + case NA_DESTROYED_ROOST_W: + del = NA_DESTROYED_ROOST_W; + add = NA_ROOST_W; + add2 = NA_BOMB_WAGON_W; + if (m_ControllingFaction == HORDE) + m_WyvernStateWest = WYVERN_ALLIANCE; + else + m_WyvernStateWest = WYVERN_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_W); + break; + case NA_DESTROYED_ROOST_E: + del = NA_DESTROYED_ROOST_E; + add = NA_ROOST_E; + add2 = NA_BOMB_WAGON_E; + if (m_ControllingFaction == HORDE) + m_WyvernStateEast = WYVERN_ALLIANCE; + else + m_WyvernStateEast = WYVERN_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_E); + break; + case NA_BOMB_WAGON_S: + del = NA_BOMB_WAGON_S; + del2 = NA_ROOST_S; + add = NA_DESTROYED_ROOST_S; + if (m_ControllingFaction == HORDE) + m_WyvernStateSouth = WYVERN_NEU_ALLIANCE; + else + m_WyvernStateSouth = WYVERN_NEU_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_S); + break; + case NA_BOMB_WAGON_N: + del = NA_BOMB_WAGON_N; + del2 = NA_ROOST_N; + add = NA_DESTROYED_ROOST_N; + if (m_ControllingFaction == HORDE) + m_WyvernStateNorth = WYVERN_NEU_ALLIANCE; + else + m_WyvernStateNorth = WYVERN_NEU_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_N); + break; + case NA_BOMB_WAGON_W: + del = NA_BOMB_WAGON_W; + del2 = NA_ROOST_W; + add = NA_DESTROYED_ROOST_W; + if (m_ControllingFaction == HORDE) + m_WyvernStateWest = WYVERN_NEU_ALLIANCE; + else + m_WyvernStateWest = WYVERN_NEU_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_W); + break; + case NA_BOMB_WAGON_E: + del = NA_BOMB_WAGON_E; + del2 = NA_ROOST_E; + add = NA_DESTROYED_ROOST_E; + if (m_ControllingFaction == HORDE) + m_WyvernStateEast = WYVERN_NEU_ALLIANCE; + else + m_WyvernStateEast = WYVERN_NEU_HORDE; + UpdateWyvernRoostWorldState(NA_ROOST_E); + break; + default: + return -1; + break; } - if (del>-1) + if (del > -1) DelObject(del); - if (del2>-1) + if (del2 > -1) DelObject(del2); - if (add>-1) + if (add > -1) AddObject(add, gos[add].entry, gos[add].map, gos[add].pos, gos[add].rot); - if (add2>-1) + if (add2 > -1) AddObject(add2, gos[add2].entry, gos[add2].map, gos[add2].pos, gos[add2].rot); return retval; @@ -677,7 +679,7 @@ void OPvPCapturePointNA::ChangeState() break; } - auto bounds = sMapMgr->FindMap(530, 0)->GetGameObjectBySpawnIdStore().equal_range(m_capturePointSpawnId); + auto bounds = m_PvP->GetMap()->GetGameObjectBySpawnIdStore().equal_range(m_capturePointSpawnId); for (auto itr = bounds.first; itr != bounds.second; ++itr) itr->second->SetGoArtKit(artkit); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp index 89fb30a5b6a..cea1d482d51 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp @@ -16,16 +16,17 @@ */ #include "ScriptMgr.h" -#include "OutdoorPvPSI.h" -#include "WorldPacket.h" -#include "Player.h" +#include "DBCStores.h" #include "GameObject.h" -#include "MapManager.h" +#include "Language.h" +#include "Map.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" +#include "OutdoorPvPSI.h" +#include "Player.h" #include "ReputationMgr.h" -#include "Language.h" #include "World.h" +#include "WorldPacket.h" uint32 const SI_MAX_RESOURCES = 200; @@ -120,7 +121,7 @@ bool OutdoorPvPSI::HandleAreaTrigger(Player* player, uint32 trigger) // reward player player->CastSpell(player, SI_TRACES_OF_SILITHYST, true); // add 19 honor - player->RewardHonor(NULL, 1, 19); + player->RewardHonor(nullptr, 1, 19); // add 20 cenarion circle repu player->GetReputationMgr().ModifyReputation(sFactionStore.LookupEntry(609), 20); // complete quest @@ -146,7 +147,7 @@ bool OutdoorPvPSI::HandleAreaTrigger(Player* player, uint32 trigger) // reward player player->CastSpell(player, SI_TRACES_OF_SILITHYST, true); // add 19 honor - player->RewardHonor(NULL, 1, 19); + player->RewardHonor(nullptr, 1, 19); // add 20 cenarion circle repu player->GetReputationMgr().ModifyReputation(sFactionStore.LookupEntry(609), 20); // complete quest @@ -176,7 +177,7 @@ bool OutdoorPvPSI::HandleDropFlag(Player* player, uint32 spellId) GameObject* go = new GameObject; Map* map = player->GetMap(); - if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, QuaternionData(), 255, GO_STATE_READY)) { delete go; return true; @@ -205,7 +206,7 @@ bool OutdoorPvPSI::HandleDropFlag(Player* player, uint32 spellId) GameObject* go = new GameObject; Map* map = player->GetMap(); - if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, QuaternionData(), 255, GO_STATE_READY)) { delete go; return true; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp index 6f87e29034f..efd3f7836d1 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp @@ -15,14 +15,14 @@ * with this program. If not, see . */ -#include "MapManager.h" #include "ScriptMgr.h" -#include "OutdoorPvPTF.h" +#include "GameObject.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "OutdoorPvPMgr.h" -#include "OutdoorPvP.h" -#include "WorldPacket.h" +#include "OutdoorPvPTF.h" #include "Player.h" -#include "ObjectMgr.h" +#include "WorldPacket.h" uint8 const OutdoorPvPTFBuffZonesNum = 5; uint32 const OutdoorPvPTFBuffZones[OutdoorPvPTFBuffZonesNum] = @@ -341,46 +341,46 @@ void OPvPCapturePointTF::ChangeState() switch (m_State) { - case OBJECTIVESTATE_ALLIANCE: - { - m_TowerState = TF_TOWERSTATE_A; - artkit = 2; - uint32 alliance_towers = ((OutdoorPvPTF*)m_PvP)->GetAllianceTowersControlled(); - if (alliance_towers < TF_TOWER_NUM) - ((OutdoorPvPTF*)m_PvP)->SetAllianceTowersControlled(++alliance_towers); - - m_PvP->SendDefenseMessage(OutdoorPvPTFBuffZones[0], TEXT_SPIRIT_TOWER_TAKEN_ALLIANCE); - - for (GuidSet::iterator itr = m_activePlayers[0].begin(); itr != m_activePlayers[0].end(); ++itr) - if (Player* player = ObjectAccessor::FindPlayer(*itr)) - player->AreaExploredOrEventHappens(TF_ALLY_QUEST); - break; - } - case OBJECTIVESTATE_HORDE: - { - m_TowerState = TF_TOWERSTATE_H; - artkit = 1; - uint32 horde_towers = ((OutdoorPvPTF*)m_PvP)->GetHordeTowersControlled(); - if (horde_towers < TF_TOWER_NUM) - ((OutdoorPvPTF*)m_PvP)->SetHordeTowersControlled(++horde_towers); - - m_PvP->SendDefenseMessage(OutdoorPvPTFBuffZones[0], TEXT_SPIRIT_TOWER_TAKEN_HORDE); - - for (GuidSet::iterator itr = m_activePlayers[1].begin(); itr != m_activePlayers[1].end(); ++itr) - if (Player* player = ObjectAccessor::FindPlayer(*itr)) - player->AreaExploredOrEventHappens(TF_HORDE_QUEST); - break; - } - case OBJECTIVESTATE_NEUTRAL: - case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE: - case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE: - case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE: - case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE: - m_TowerState = TF_TOWERSTATE_N; - break; + case OBJECTIVESTATE_ALLIANCE: + { + m_TowerState = TF_TOWERSTATE_A; + artkit = 2; + uint32 alliance_towers = ((OutdoorPvPTF*)m_PvP)->GetAllianceTowersControlled(); + if (alliance_towers < TF_TOWER_NUM) + ((OutdoorPvPTF*)m_PvP)->SetAllianceTowersControlled(++alliance_towers); + + m_PvP->SendDefenseMessage(OutdoorPvPTFBuffZones[0], TEXT_SPIRIT_TOWER_TAKEN_ALLIANCE); + + for (GuidSet::iterator itr = m_activePlayers[0].begin(); itr != m_activePlayers[0].end(); ++itr) + if (Player* player = ObjectAccessor::FindPlayer(*itr)) + player->AreaExploredOrEventHappens(TF_ALLY_QUEST); + break; + } + case OBJECTIVESTATE_HORDE: + { + m_TowerState = TF_TOWERSTATE_H; + artkit = 1; + uint32 horde_towers = ((OutdoorPvPTF*)m_PvP)->GetHordeTowersControlled(); + if (horde_towers < TF_TOWER_NUM) + ((OutdoorPvPTF*)m_PvP)->SetHordeTowersControlled(++horde_towers); + + m_PvP->SendDefenseMessage(OutdoorPvPTFBuffZones[0], TEXT_SPIRIT_TOWER_TAKEN_HORDE); + + for (GuidSet::iterator itr = m_activePlayers[1].begin(); itr != m_activePlayers[1].end(); ++itr) + if (Player* player = ObjectAccessor::FindPlayer(*itr)) + player->AreaExploredOrEventHappens(TF_HORDE_QUEST); + break; + } + case OBJECTIVESTATE_NEUTRAL: + case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE: + case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE: + case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE: + case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE: + m_TowerState = TF_TOWERSTATE_N; + break; } - auto bounds = sMapMgr->FindMap(530, 0)->GetGameObjectBySpawnIdStore().equal_range(m_capturePointSpawnId); + auto bounds = m_PvP->GetMap()->GetGameObjectBySpawnIdStore().equal_range(m_capturePointSpawnId); for (auto itr = bounds.first; itr != bounds.second; ++itr) itr->second->SetGoArtKit(artkit); diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp index 738c6ab685f..64b7aa88321 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp @@ -164,11 +164,11 @@ bool OutdoorPvPZM::Update(uint32 diff) if (changed) { if (m_AllianceTowersControlled == ZM_NUM_BEACONS) - m_GraveYard->SetBeaconState(ALLIANCE); + m_Graveyard->SetBeaconState(ALLIANCE); else if (m_HordeTowersControlled == ZM_NUM_BEACONS) - m_GraveYard->SetBeaconState(HORDE); + m_Graveyard->SetBeaconState(HORDE); else - m_GraveYard->SetBeaconState(0); + m_Graveyard->SetBeaconState(0); } return changed; } @@ -177,12 +177,12 @@ void OutdoorPvPZM::HandlePlayerEnterZone(Player* player, uint32 zone) { if (player->GetTeam() == ALLIANCE) { - if (m_GraveYard->GetGraveYardState() & ZM_GRAVEYARD_A) + if (m_Graveyard->GetGraveyardState() & ZM_GRAVEYARD_A) player->CastSpell(player, ZM_CAPTURE_BUFF, true); } else { - if (m_GraveYard->GetGraveYardState() & ZM_GRAVEYARD_H) + if (m_Graveyard->GetGraveyardState() & ZM_GRAVEYARD_H) player->CastSpell(player, ZM_CAPTURE_BUFF, true); } OutdoorPvP::HandlePlayerEnterZone(player, zone); @@ -201,7 +201,7 @@ void OutdoorPvPZM::HandlePlayerLeaveZone(Player* player, uint32 zone) OutdoorPvPZM::OutdoorPvPZM() { m_TypeId = OUTDOOR_PVP_ZM; - m_GraveYard = NULL; + m_Graveyard = nullptr; m_AllianceTowersControlled = 0; m_HordeTowersControlled = 0; } @@ -219,8 +219,8 @@ bool OutdoorPvPZM::SetupOutdoorPvP() AddCapturePoint(new OPvPCapturePointZM_Beacon(this, ZM_BEACON_WEST)); AddCapturePoint(new OPvPCapturePointZM_Beacon(this, ZM_BEACON_EAST)); - m_GraveYard = new OPvPCapturePointZM_GraveYard(this); - AddCapturePoint(m_GraveYard); // though the update function isn't used, the handleusego is! + m_Graveyard = new OPvPCapturePointZM_Graveyard(this); + AddCapturePoint(m_Graveyard); // though the update function isn't used, the handleusego is! return true; } @@ -236,36 +236,36 @@ void OutdoorPvPZM::HandleKillImpl(Player* player, Unit* killed) player->CastSpell(player, ZM_HordePlayerKillReward, true); } -bool OPvPCapturePointZM_GraveYard::Update(uint32 /*diff*/) +bool OPvPCapturePointZM_Graveyard::Update(uint32 /*diff*/) { bool retval = m_State != m_OldState; m_State = m_OldState; return retval; } -int32 OPvPCapturePointZM_GraveYard::HandleOpenGo(Player* player, GameObject* go) +int32 OPvPCapturePointZM_Graveyard::HandleOpenGo(Player* player, GameObject* go) { int32 retval = OPvPCapturePoint::HandleOpenGo(player, go); if (retval >= 0) { - if (player->HasAura(ZM_BATTLE_STANDARD_A) && m_GraveYardState != ZM_GRAVEYARD_A) + if (player->HasAura(ZM_BATTLE_STANDARD_A) && m_GraveyardState != ZM_GRAVEYARD_A) { - m_GraveYardState = ZM_GRAVEYARD_A; + m_GraveyardState = ZM_GRAVEYARD_A; DelObject(0); // only one gotype is used in the whole outdoor pvp, no need to call it a constant AddObject(0, ZM_Banner_A.entry, ZM_Banner_A.map, ZM_Banner_A.pos, ZM_Banner_A.rot); - sObjectMgr->RemoveGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE); // rem gy - sObjectMgr->AddGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE, false); // add gy + sObjectMgr->RemoveGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE); // rem gy + sObjectMgr->AddGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE, false); // add gy m_PvP->TeamApplyBuff(TEAM_ALLIANCE, ZM_CAPTURE_BUFF); player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_A); m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, TEXT_TWIN_SPIRE_RUINS_TAKEN_ALLIANCE); } - else if (player->HasAura(ZM_BATTLE_STANDARD_H) && m_GraveYardState != ZM_GRAVEYARD_H) + else if (player->HasAura(ZM_BATTLE_STANDARD_H) && m_GraveyardState != ZM_GRAVEYARD_H) { - m_GraveYardState = ZM_GRAVEYARD_H; + m_GraveyardState = ZM_GRAVEYARD_H; DelObject(0); // only one gotype is used in the whole outdoor pvp, no need to call it a constant AddObject(0, ZM_Banner_H.entry, ZM_Banner_H.map, ZM_Banner_H.pos, ZM_Banner_H.rot); - sObjectMgr->RemoveGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE); // rem gy - sObjectMgr->AddGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE, false); // add gy + sObjectMgr->RemoveGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE); // rem gy + sObjectMgr->AddGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE, false); // add gy m_PvP->TeamApplyBuff(TEAM_HORDE, ZM_CAPTURE_BUFF); player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_H); m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, TEXT_TWIN_SPIRE_RUINS_TAKEN_HORDE); @@ -275,11 +275,11 @@ int32 OPvPCapturePointZM_GraveYard::HandleOpenGo(Player* player, GameObject* go) return retval; } -OPvPCapturePointZM_GraveYard::OPvPCapturePointZM_GraveYard(OutdoorPvP* pvp) +OPvPCapturePointZM_Graveyard::OPvPCapturePointZM_Graveyard(OutdoorPvP* pvp) : OPvPCapturePoint(pvp) { m_BothControllingFaction = 0; - m_GraveYardState = ZM_GRAVEYARD_N; + m_GraveyardState = ZM_GRAVEYARD_N; m_FlagCarrierGUID.Clear(); // add field scouts here AddCreature(ZM_ALLIANCE_FIELD_SCOUT, ZM_AllianceFieldScout.entry, ZM_AllianceFieldScout.map, ZM_AllianceFieldScout.pos); @@ -288,11 +288,11 @@ OPvPCapturePointZM_GraveYard::OPvPCapturePointZM_GraveYard(OutdoorPvP* pvp) AddObject(0, ZM_Banner_N.entry, ZM_Banner_N.map, ZM_Banner_N.pos, ZM_Banner_N.rot); } -void OPvPCapturePointZM_GraveYard::UpdateTowerState() +void OPvPCapturePointZM_Graveyard::UpdateTowerState() { - m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_N, uint32((m_GraveYardState & ZM_GRAVEYARD_N) != 0)); - m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_H, uint32((m_GraveYardState & ZM_GRAVEYARD_H) != 0)); - m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_A, uint32((m_GraveYardState & ZM_GRAVEYARD_A) != 0)); + m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_N, uint32((m_GraveyardState & ZM_GRAVEYARD_N) != 0)); + m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_H, uint32((m_GraveyardState & ZM_GRAVEYARD_H) != 0)); + m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_A, uint32((m_GraveyardState & ZM_GRAVEYARD_A) != 0)); m_PvP->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_READY, uint32(m_BothControllingFaction == ALLIANCE)); m_PvP->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_NOT_READY, uint32(m_BothControllingFaction != ALLIANCE)); @@ -300,11 +300,11 @@ void OPvPCapturePointZM_GraveYard::UpdateTowerState() m_PvP->SendUpdateWorldState(ZM_MAP_HORDE_FLAG_NOT_READY, uint32(m_BothControllingFaction != HORDE)); } -void OPvPCapturePointZM_GraveYard::FillInitialWorldStates(WorldPacket &data) +void OPvPCapturePointZM_Graveyard::FillInitialWorldStates(WorldPacket &data) { - data << ZM_MAP_GRAVEYARD_N << uint32((m_GraveYardState & ZM_GRAVEYARD_N) != 0); - data << ZM_MAP_GRAVEYARD_H << uint32((m_GraveYardState & ZM_GRAVEYARD_H) != 0); - data << ZM_MAP_GRAVEYARD_A << uint32((m_GraveYardState & ZM_GRAVEYARD_A) != 0); + data << ZM_MAP_GRAVEYARD_N << uint32((m_GraveyardState & ZM_GRAVEYARD_N) != 0); + data << ZM_MAP_GRAVEYARD_H << uint32((m_GraveyardState & ZM_GRAVEYARD_H) != 0); + data << ZM_MAP_GRAVEYARD_A << uint32((m_GraveyardState & ZM_GRAVEYARD_A) != 0); data << ZM_MAP_ALLIANCE_FLAG_READY << uint32(m_BothControllingFaction == ALLIANCE); data << ZM_MAP_ALLIANCE_FLAG_NOT_READY << uint32(m_BothControllingFaction != ALLIANCE); @@ -312,7 +312,7 @@ void OPvPCapturePointZM_GraveYard::FillInitialWorldStates(WorldPacket &data) data << ZM_MAP_HORDE_FLAG_NOT_READY << uint32(m_BothControllingFaction != HORDE); } -void OPvPCapturePointZM_GraveYard::SetBeaconState(uint32 controlling_faction) +void OPvPCapturePointZM_Graveyard::SetBeaconState(uint32 controlling_faction) { // nothing to do here if (m_BothControllingFaction == controlling_faction) @@ -323,20 +323,20 @@ void OPvPCapturePointZM_GraveYard::SetBeaconState(uint32 controlling_faction) { case ALLIANCE: // if ally already controls the gy and taken back both beacons, return, nothing to do for us - if (m_GraveYardState & ZM_GRAVEYARD_A) + if (m_GraveyardState & ZM_GRAVEYARD_A) return; // ally doesn't control the gy, but controls the side beacons -> add gossip option, add neutral banner break; case HORDE: // if horde already controls the gy and taken back both beacons, return, nothing to do for us - if (m_GraveYardState & ZM_GRAVEYARD_H) + if (m_GraveyardState & ZM_GRAVEYARD_H) return; // horde doesn't control the gy, but controls the side beacons -> add gossip option, add neutral banner break; default: // if the graveyard is not neutral, then leave it that way // if the graveyard is neutral, then we have to dispel the buff from the flag carrier - if (m_GraveYardState & ZM_GRAVEYARD_N) + if (m_GraveyardState & ZM_GRAVEYARD_N) { // gy was neutral, thus neutral banner was spawned, it is possible that someone was taking the flag to the gy if (m_FlagCarrierGUID) @@ -357,21 +357,21 @@ void OPvPCapturePointZM_GraveYard::SetBeaconState(uint32 controlling_faction) UpdateTowerState(); } -bool OPvPCapturePointZM_GraveYard::CanTalkTo(Player* player, Creature* c, GossipMenuItems const& /*gso*/) +bool OPvPCapturePointZM_Graveyard::CanTalkTo(Player* player, Creature* c, GossipMenuItems const& /*gso*/) { std::map::iterator itr = m_CreatureTypes.find(c->GetSpawnId()); if (itr != m_CreatureTypes.end()) { - if (itr->second == ZM_ALLIANCE_FIELD_SCOUT && player->GetTeam() == ALLIANCE && m_BothControllingFaction == ALLIANCE && !m_FlagCarrierGUID && m_GraveYardState != ZM_GRAVEYARD_A) + if (itr->second == ZM_ALLIANCE_FIELD_SCOUT && player->GetTeam() == ALLIANCE && m_BothControllingFaction == ALLIANCE && !m_FlagCarrierGUID && m_GraveyardState != ZM_GRAVEYARD_A) return true; - else if (itr->second == ZM_HORDE_FIELD_SCOUT && player->GetTeam() == HORDE && m_BothControllingFaction == HORDE && !m_FlagCarrierGUID && m_GraveYardState != ZM_GRAVEYARD_H) + else if (itr->second == ZM_HORDE_FIELD_SCOUT && player->GetTeam() == HORDE && m_BothControllingFaction == HORDE && !m_FlagCarrierGUID && m_GraveyardState != ZM_GRAVEYARD_H) return true; } return false; } -bool OPvPCapturePointZM_GraveYard::HandleGossipOption(Player* player, Creature* creature, uint32 /*gossipid*/) +bool OPvPCapturePointZM_Graveyard::HandleGossipOption(Player* player, Creature* creature, uint32 /*gossipid*/) { std::map::iterator itr = m_CreatureTypes.find(creature->GetSpawnId()); @@ -397,7 +397,7 @@ bool OPvPCapturePointZM_GraveYard::HandleGossipOption(Player* player, Creature* return false; } -bool OPvPCapturePointZM_GraveYard::HandleDropFlag(Player* /*player*/, uint32 spellId) +bool OPvPCapturePointZM_Graveyard::HandleDropFlag(Player* /*player*/, uint32 spellId) { switch (spellId) { @@ -411,9 +411,9 @@ bool OPvPCapturePointZM_GraveYard::HandleDropFlag(Player* /*player*/, uint32 spe return false; } -uint32 OPvPCapturePointZM_GraveYard::GetGraveYardState() const +uint32 OPvPCapturePointZM_Graveyard::GetGraveyardState() const { - return m_GraveYardState; + return m_GraveyardState; } uint32 OutdoorPvPZM::GetAllianceTowersControlled() const diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h index 77301b96328..e042c47a64c 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h @@ -114,17 +114,17 @@ class OPvPCapturePointZM_Beacon : public OPvPCapturePoint uint32 m_TowerState; }; -enum ZM_GraveYardState +enum ZM_GraveyardState { ZM_GRAVEYARD_N = 1, ZM_GRAVEYARD_A = 2, ZM_GRAVEYARD_H = 4 }; -class OPvPCapturePointZM_GraveYard : public OPvPCapturePoint +class OPvPCapturePointZM_Graveyard : public OPvPCapturePoint { public: - OPvPCapturePointZM_GraveYard(OutdoorPvP* pvp); + OPvPCapturePointZM_Graveyard(OutdoorPvP* pvp); bool Update(uint32 diff) override; @@ -144,10 +144,10 @@ class OPvPCapturePointZM_GraveYard : public OPvPCapturePoint bool CanTalkTo(Player* player, Creature* creature, GossipMenuItems const& gso) override; - uint32 GetGraveYardState() const; + uint32 GetGraveyardState() const; private: - uint32 m_GraveYardState; + uint32 m_GraveyardState; protected: uint32 m_BothControllingFaction; @@ -180,7 +180,7 @@ class OutdoorPvPZM : public OutdoorPvP void SetHordeTowersControlled(uint32 count); private: - OPvPCapturePointZM_GraveYard * m_GraveYard; + OPvPCapturePointZM_Graveyard * m_Graveyard; uint32 m_AllianceTowersControlled; uint32 m_HordeTowersControlled; diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h index 18354890ba9..5bc6d049f5a 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h @@ -18,6 +18,8 @@ #ifndef AUCHENAI_CRYPTS_H_ #define AUCHENAI_CRYPTS_H_ +#include "CreatureAIImpl.h" + #define ACScriptName "instance_auchenai_crypts" #define DataHeader "AC" @@ -30,10 +32,10 @@ enum ACDataTypes DATA_EXARCH_MALADAAR = 1 }; -template -AI* GetAuchenaiCryptsAI(Creature* creature) +template +inline AI* GetAuchenaiCryptsAI(T* obj) { - return GetInstanceAI(creature, ACScriptName); + return GetInstanceAI(obj, ACScriptName); } #endif // AUCHENAI_CRYPTS_H_ diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp index 386d65c31ce..a6ef54233bb 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp @@ -30,6 +30,8 @@ npc_avatar_of_martyred EndContentData */ #include "ScriptMgr.h" +#include "auchenai_crypts.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" enum Spells @@ -56,7 +58,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_stolen_soulAI(creature); + return GetAuchenaiCryptsAI(creature); } struct npc_stolen_soulAI : public ScriptedAI @@ -163,7 +165,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_exarch_maladaarAI(creature); + return GetAuchenaiCryptsAI(creature); } struct boss_exarch_maladaarAI : public ScriptedAI @@ -319,7 +321,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_avatar_of_martyredAI(creature); + return GetAuchenaiCryptsAI(creature); } struct npc_avatar_of_martyredAI : public ScriptedAI diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp index 1037fcebcf8..b59cf598454 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp @@ -24,8 +24,11 @@ Category: Auchindoun, Auchenai Crypts EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "auchenai_crypts.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" enum Spells { @@ -55,7 +58,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_shirrak_the_dead_watcherAI(creature); + return GetAuchenaiCryptsAI(creature); } struct boss_shirrak_the_dead_watcherAI : public ScriptedAI @@ -109,7 +112,7 @@ public: if (Inhibitmagic_Timer <= diff) { float dist; - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* i_pl = i->GetSource()) if (i_pl->IsAlive() && (dist = i_pl->GetDistance(me)) < 45) @@ -172,7 +175,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_focus_fireAI(creature); + return GetAuchenaiCryptsAI(creature); } struct npc_focus_fireAI : public ScriptedAI diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp index 9655b20b551..4f88489923c 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "auchenai_crypts.h" +#include "InstanceScript.h" +#include "Map.h" class instance_auchenai_crypts : public InstanceMapScript { diff --git a/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp b/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp index 7917d40b8f7..6623feead32 100644 --- a/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp +++ b/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp @@ -23,8 +23,9 @@ SDCategory: Auchindoun, Mana Tombs EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mana_tombs.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Yells { @@ -259,7 +260,7 @@ class npc_ethereal_beacon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ethereal_beaconAI(creature); + return GetManaTombsAI(creature); } }; @@ -324,7 +325,7 @@ class npc_ethereal_apprentice : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ethereal_apprenticeAI(creature); + return GetManaTombsAI(creature); } }; @@ -380,7 +381,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_yorAI(creature); + return GetManaTombsAI(creature); } }; diff --git a/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp b/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp index 7f388b198ae..8ab7c798194 100644 --- a/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp +++ b/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp @@ -18,6 +18,7 @@ #include "ScriptMgr.h" #include "InstanceScript.h" #include "mana_tombs.h" +#include "Map.h" class instance_mana_tombs : public InstanceMapScript { diff --git a/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h b/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h index 707eb89ef9b..0a48696cfbf 100644 --- a/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h +++ b/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h @@ -18,6 +18,8 @@ #ifndef MANA_TOMBS_H_ #define MANA_TOMBS_H_ +#include "CreatureAIImpl.h" + #define MTScriptName "instance_mana_tombs" #define DataHeader "MT" @@ -32,10 +34,10 @@ enum MTDataTypes DATA_YOR = 3 }; -template -AI* GetManaTombsAI(Creature* creature) +template +inline AI* GetManaTombsAI(T* obj) { - return GetInstanceAI(creature, MTScriptName); + return GetInstanceAI(obj, MTScriptName); } #endif // MANA_TOMBS_H_ diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp index f0bc7a3b537..91a4efc3c62 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp @@ -257,7 +257,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_fireAI(creature); + return GetSethekkHallsAI(creature); } }; @@ -316,7 +316,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_arcaneAI(creature); + return GetSethekkHallsAI(creature); } }; @@ -375,7 +375,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_frostAI(creature); + return GetSethekkHallsAI(creature); } }; @@ -434,7 +434,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_shadowAI(creature); + return GetSethekkHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp index 369bce2457e..c97fa51a502 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp @@ -173,9 +173,7 @@ class spell_talon_king_ikiss_blink : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLINK_TELEPORT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLINK_TELEPORT }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp b/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp index 31f874dcb61..40882ea933b 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp @@ -16,13 +16,16 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "sethekk_halls.h" DoorData const doorData[] = { { GO_IKISS_DOOR, DATA_TALON_KING_IKISS, DOOR_TYPE_PASSAGE }, - { 0, 0, DOOR_TYPE_ROOM } // END + { 0, 0, DOOR_TYPE_ROOM } // END }; ObjectData const gameObjectData[] = diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h b/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h index 3471b23daa2..39f8aa9511c 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h @@ -18,6 +18,8 @@ #ifndef SETHEKK_HALLS_H_ #define SETHEKK_HALLS_H_ +#include "CreatureAIImpl.h" + #define SHScriptName "instance_sethekk_halls" #define DataHeader "SH" @@ -46,10 +48,10 @@ enum SHGameObjectIds GO_TALON_KING_COFFER = 187372 }; -template -AI* GetSethekkHallsAI(Creature* creature) +template +inline AI* GetSethekkHallsAI(T* obj) { - return GetInstanceAI(creature, SHScriptName); + return GetInstanceAI(obj, SHScriptName); } #endif // SETHEKK_HALLS_H_ diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp index 976f95cfd90..c12dd178729 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp @@ -24,7 +24,7 @@ SDCategory: Auchindoun, Shadow Labyrinth EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "ScriptedEscortAI.h" #include "shadow_labyrinth.h" @@ -115,7 +115,7 @@ class boss_ambassador_hellmaw : public CreatureScript me->RemoveAurasDueToSpell(SPELL_BANISH); Talk(SAY_INTRO); - Start(true, false, ObjectGuid::Empty, NULL, false, true); + Start(true, false, ObjectGuid::Empty, nullptr, false, true); } void EnterCombat(Unit* /*who*/) override diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp index fa3978840c9..f0a47bd8604 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp @@ -24,6 +24,7 @@ Category: Auchindoun, Shadow Labyrinth */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shadow_labyrinth.h" diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp index 2c9eba30a12..35276572243 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp @@ -23,9 +23,14 @@ Category: Auchindoun, Shadow Labyrinth */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "shadow_labyrinth.h" -#include "Player.h" +#include "TemporarySummon.h" enum GrandmasterVorpil { @@ -182,7 +187,7 @@ class boss_grandmaster_vorpil : public CreatureScript break; case EVENT_DRAW_SHADOWS: { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* i_pl = i->GetSource()) if (i_pl->IsAlive() && !i_pl->HasAura(SPELL_BANISH)) diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp index ac9ef77cd82..896deca41f7 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp @@ -24,9 +24,10 @@ SDCategory: Auchindoun, Shadow Labyrinth EndScriptData */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "shadow_labyrinth.h" +#include "SpellScript.h" enum Murmur { @@ -188,14 +189,12 @@ class spell_murmur_sonic_boom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SONIC_BOOM_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SONIC_BOOM_EFFECT }); } void HandleEffect(SpellEffIndex /*effIndex*/) { - GetCaster()->CastSpell((Unit*)NULL, SPELL_SONIC_BOOM_EFFECT, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SONIC_BOOM_EFFECT, true); } void Register() override diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp index 0e75d609195..c5ddb8e6b50 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "ScriptedCreature.h" +#include "Map.h" #include "shadow_labyrinth.h" DoorData const doorData[] = diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp index 8b830ccad65..cbfd8b2c197 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp @@ -36,9 +36,7 @@ class spell_mark_of_malice : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_MALICE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_MALICE_TRIGGERED }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h index 48334af4ab9..0c7e7b5afca 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h @@ -18,6 +18,8 @@ #ifndef SHADOW_LABYRINTH_H_ #define SHADOW_LABYRINTH_H_ +#include "CreatureAIImpl.h" + #define SLScriptName "instance_shadow_labyrinth" #define DataHeader "SL" @@ -54,10 +56,10 @@ enum SLMisc ACTION_AMBASSADOR_HELLMAW_BANISH = 2, }; -template -AI* GetShadowLabyrinthAI(Creature* creature) +template +inline AI* GetShadowLabyrinthAI(T* obj) { - return GetInstanceAI(creature, SLScriptName); + return GetInstanceAI(obj, SLScriptName); } #endif // SHADOW_LABYRINTH_H_ diff --git a/src/server/scripts/Outland/BlackTemple/black_temple.cpp b/src/server/scripts/Outland/BlackTemple/black_temple.cpp index 042cff87618..08b00caa519 100644 --- a/src/server/scripts/Outland/BlackTemple/black_temple.cpp +++ b/src/server/scripts/Outland/BlackTemple/black_temple.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" -#include "SpellScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -137,11 +138,11 @@ public: { for (ObjectGuid guid : _bloodmageList) if (Creature* bloodmage = ObjectAccessor::GetCreature(*me, guid)) - bloodmage->CastSpell((Unit*)NULL, SPELL_SUMMON_CHANNEL); + bloodmage->CastSpell((Unit*)nullptr, SPELL_SUMMON_CHANNEL); for (ObjectGuid guid : _deathshaperList) if (Creature* deathshaper = ObjectAccessor::GetCreature(*me, guid)) - deathshaper->CastSpell((Unit*)NULL, SPELL_SUMMON_CHANNEL); + deathshaper->CastSpell((Unit*)nullptr, SPELL_SUMMON_CHANNEL); _events.ScheduleEvent(EVENT_SET_CHANNELERS, 12000); @@ -298,9 +299,7 @@ class spell_illidari_nightlord_shadow_inferno : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_INFERNO_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOW_INFERNO_DAMAGE }); } void OnPeriodic(AuraEffect const* aurEffect) diff --git a/src/server/scripts/Outland/BlackTemple/black_temple.h b/src/server/scripts/Outland/BlackTemple/black_temple.h index b1c4b31ca63..bdade01ab33 100644 --- a/src/server/scripts/Outland/BlackTemple/black_temple.h +++ b/src/server/scripts/Outland/BlackTemple/black_temple.h @@ -18,6 +18,8 @@ #ifndef BLACK_TEMPLE_H_ #define BLACK_TEMPLE_H_ +#include "CreatureAIImpl.h" + #define BTScriptName "instance_black_temple" #define DataHeader "BT" @@ -138,8 +140,8 @@ enum BlackTempleMisc ACTION_OPEN_DOOR = 4 }; -template -AI* GetBlackTempleAI(T* obj) +template +inline AI* GetBlackTempleAI(T* obj) { return GetInstanceAI(obj, BTScriptName); } diff --git a/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp b/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp index 7d851ec8bf7..085ea796f05 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp @@ -16,12 +16,12 @@ */ #include "ScriptMgr.h" +#include "black_temple.h" +#include "GridNotifiers.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "PassiveAI.h" -#include "GridNotifiers.h" - -#include "black_temple.h" enum Says { @@ -381,9 +381,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FEL_RAGE_TARGET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FEL_RAGE_TARGET }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp b/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp index 84ce4d42354..a7bfbf317c3 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp @@ -16,15 +16,20 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "PassiveAI.h" #include "black_temple.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "GridNotifiersImpl.h" +#include "TemporarySummon.h" enum IllidanSay { @@ -676,7 +681,7 @@ public: void EnterEvadeModeIfNeeded() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->GetSource()) if (player->IsAlive() && !player->IsGameMaster() && CheckBoundary(player)) @@ -1889,9 +1894,7 @@ class spell_illidan_akama_door_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ARCANE_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ARCANE_EXPLOSION }); } void OnRemoveDummy(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1928,9 +1931,7 @@ class spell_illidan_draw_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRAW_SOUL_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRAW_SOUL_HEAL }); } void HandleScriptEffect(SpellEffIndex effIndex) @@ -1964,9 +1965,7 @@ class spell_illidan_parasitic_shadowfiend : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PARASITIC_SHADOWFIENDS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_PARASITIC_SHADOWFIENDS }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2028,9 +2027,7 @@ class spell_illidan_tear_of_azzinoth_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNCAGED_WRATH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNCAGED_WRATH }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -2071,9 +2068,7 @@ class spell_illidan_flame_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLAZE_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLAZE_SUMMON }); } void HandleBlaze(SpellEffIndex /*effIndex*/) @@ -2135,9 +2130,7 @@ class spell_illidan_agonizing_flames : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AGONIZING_FLAMES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AGONIZING_FLAMES }); } void FilterTargets(std::list& targets) @@ -2180,9 +2173,7 @@ class spell_illidan_demon_transform1 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEMON_TRANSFORM_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEMON_TRANSFORM_2 }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -2216,10 +2207,7 @@ class spell_illidan_demon_transform2 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEMON_FORM) - || !sSpellMgr->GetSpellInfo(SPELL_DEMON_TRANSFORM_3)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEMON_FORM, SPELL_DEMON_TRANSFORM_3 }); } void OnPeriodic(AuraEffect const* aurEff) @@ -2267,9 +2255,7 @@ class spell_illidan_flame_burst : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLAME_BURST_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLAME_BURST_EFFECT }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -2301,9 +2287,7 @@ class spell_illidan_find_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARALYZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARALYZE }); } void FilterTargets(std::list& targets) @@ -2420,9 +2404,7 @@ class spell_illidan_caged : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CAGED_DEBUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CAGED_DEBUFF }); } void OnPeriodic(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp b/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp index e19b0189147..245f7960628 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp @@ -16,15 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "black_temple.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -631,9 +630,7 @@ class spell_illidari_council_empyreal_balance : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BALANCE_OF_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BALANCE_OF_POWER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -698,9 +695,7 @@ class spell_illidari_council_balance_of_power : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHARED_RULE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHARED_RULE }); } void Absorb(AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& /*absorbAmount*/) @@ -734,9 +729,7 @@ class spell_illidari_council_deadly_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEADLY_POISON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEADLY_POISON }); } void OnTrigger(AuraEffect const* aurEff) @@ -771,9 +764,7 @@ class spell_illidari_council_deadly_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ENVENOM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ENVENOM }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -806,12 +797,10 @@ class spell_illidari_council_reflective_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_REFLECTIVE_SHIELD_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_REFLECTIVE_SHIELD_DAMAGE }); } - void OnAbsorb(AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & absorbAmount) + void OnAbsorb(AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount) { Unit* target = GetTarget(); if (dmgInfo.GetAttacker() == target) @@ -845,11 +834,12 @@ class spell_illidari_council_judgement : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_JUDGEMENT_OF_BLOOD) - || !sSpellMgr->GetSpellInfo(SPELL_JUDGEMENT_OF_COMMAND) - || !sSpellMgr->GetSpellInfo(SPELL_JUDGEMENT_PRIMER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_JUDGEMENT_OF_BLOOD, + SPELL_JUDGEMENT_OF_COMMAND, + SPELL_JUDGEMENT_PRIMER + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -893,10 +883,11 @@ class spell_illidari_council_seal : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SEAL_OF_COMMAND) - || !sSpellMgr->GetSpellInfo(SPELL_SEAL_OF_BLOOD)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SEAL_OF_COMMAND, + SPELL_SEAL_OF_BLOOD + }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp index d1993aae981..38fa695c5db 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp @@ -218,10 +218,11 @@ class spell_mother_shahraz_fatal_attraction : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SABER_LASH_IMMUNITY) - || !sSpellMgr->GetSpellInfo(SPELL_FATAL_ATTRACTION)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SABER_LASH_IMMUNITY, + SPELL_FATAL_ATTRACTION + }); } void FilterTargets(std::list& targets) @@ -265,9 +266,7 @@ class spell_mother_shahraz_fatal_attraction_link : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FATAL_ATTRACTION_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FATAL_ATTRACTION_DAMAGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -299,9 +298,7 @@ class spell_mother_shahraz_saber_lash : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_1].TriggerSpell }); } void OnTrigger(AuraEffect const* aurEff) @@ -340,9 +337,7 @@ class spell_mother_shahraz_generic_periodic : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void OnTrigger(AuraEffect const* aurEff) @@ -378,10 +373,7 @@ class spell_mother_shahraz_random_periodic : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId : RandomBeam) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo(RandomBeam); } void OnPeriodic(AuraEffect const* /*aurEffect*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp b/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp index d5f52b2fc7c..ae3d961ca68 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedCreature.h" #include "Spell.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "Player.h" +#include "SpellScript.h" enum Says { @@ -727,9 +729,7 @@ class spell_reliquary_of_souls_aura_of_desire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AURA_OF_DESIRE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AURA_OF_DESIRE_DAMAGE }); } void OnProcSpell(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -809,9 +809,7 @@ class spell_reliquary_of_souls_spite : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SPITE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SPITE_DAMAGE }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp b/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp index c2131a46696..231fa47fbda 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp @@ -15,15 +15,19 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "black_temple.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "GridNotifiers.h" -#include "black_temple.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Says { @@ -286,7 +290,7 @@ public: void EnterEvadeModeIfNeeded() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->GetSource()) if (player->IsAlive() && !player->IsGameMaster() && CheckBoundary(player)) @@ -1200,9 +1204,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADE_SOUL_CHANNEL_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADE_SOUL_CHANNEL_2 }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp b/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp index 67dfa42b543..e2ec4990ccd 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PassiveAI.h" #include "black_temple.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "ScriptedCreature.h" enum Texts { diff --git a/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp b/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp index 0e5d5d26f73..4061eed85ec 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" -#include "SpellScript.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -388,15 +391,16 @@ class spell_teron_gorefiend_shadow_of_death : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SPIRIT) - || !sSpellMgr->GetSpellInfo(SPELL_POSSESS_SPIRIT_IMMUNE) - || !sSpellMgr->GetSpellInfo(SPELL_SPIRITUAL_VENGEANCE) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_1) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_2) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_3) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_4)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SUMMON_SPIRIT, + SPELL_POSSESS_SPIRIT_IMMUNE, + SPELL_SPIRITUAL_VENGEANCE, + SPELL_SUMMON_SKELETRON_1, + SPELL_SUMMON_SKELETRON_2, + SPELL_SUMMON_SKELETRON_3, + SPELL_SUMMON_SKELETRON_4 + }); } void Absorb(AuraEffect* /*aurEff*/, DamageInfo& /*dmgInfo*/, uint32& /*absorbAmount*/) @@ -472,11 +476,12 @@ class spell_teron_gorefiend_shadow_of_death_remove : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_OF_DEATH) - || !sSpellMgr->GetSpellInfo(SPELL_POSSESS_SPIRIT_IMMUNE) - || !sSpellMgr->GetSpellInfo(SPELL_SPIRITUAL_VENGEANCE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHADOW_OF_DEATH, + SPELL_POSSESS_SPIRIT_IMMUNE, + SPELL_SPIRITUAL_VENGEANCE + }); } void RemoveAuras() diff --git a/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp b/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp index faaa2887e34..b49ad6e3f20 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GameObjectAI.h" #include "black_temple.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "GridNotifiers.h" enum Texts { @@ -88,7 +90,7 @@ public: Talk(SAY_DEATH); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_HURL_SPINE && me->HasAura(SPELL_TIDAL_SHIELD)) { @@ -140,7 +142,7 @@ public: DoCast(target, SPELL_IMPALING_SPINE, true); SpineTargetGUID = target->GetGUID(); //must let target summon, otherwise you cannot click the spine - target->SummonGameObject(GO_NAJENTUS_SPINE, *target, G3D::Quat(), 30); + target->SummonGameObject(GO_NAJENTUS_SPINE, *target, QuaternionData(), 30); Talk(SAY_NEEDLE); } events.Repeat(Seconds(20), Seconds(25)); @@ -211,9 +213,7 @@ class spell_najentus_needle_spine : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NEEDLE_SPINE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NEEDLE_SPINE }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp index a12d920736d..f679428e44e 100644 --- a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp +++ b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp @@ -16,8 +16,13 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" #include "black_temple.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp index a468f9714ad..0554505ae74 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp @@ -24,9 +24,12 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "serpent_shrine.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedEscortAI.h" +#include "serpent_shrine.h" +#include "TemporarySummon.h" enum FathomlordKarathress { @@ -104,7 +107,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomlord_karathressAI : public ScriptedAI @@ -303,7 +306,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomguard_sharkkisAI : public ScriptedAI @@ -341,7 +344,7 @@ public: Creature* Pet = ObjectAccessor::GetCreature(*me, SummonedPet); if (Pet && Pet->IsAlive()) - Pet->DealDamage(Pet, Pet->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + Pet->DealDamage(Pet, Pet->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); SummonedPet.Clear(); @@ -447,7 +450,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomguard_tidalvessAI : public ScriptedAI @@ -569,7 +572,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomguard_caribdisAI : public ScriptedAI @@ -674,9 +677,9 @@ public: if (Heal_Timer <= diff) { // It can be cast on any of the mobs - Unit* unit = NULL; + Unit* unit = nullptr; - while (unit == NULL || !unit->IsAlive()) + while (unit == nullptr || !unit->IsAlive()) unit = selectAdvisorUnit(); if (unit && unit->IsAlive()) @@ -691,7 +694,7 @@ public: Unit* selectAdvisorUnit() { - Unit* unit = NULL; + Unit* unit = nullptr; switch (rand32() % 4) { case 0: diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp index a7b00d4ef70..c9727c196ef 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp @@ -24,8 +24,11 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" +#include "TemporarySummon.h" enum HydrossTheUnstable { @@ -86,7 +89,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_hydross_the_unstableAI : public ScriptedAI @@ -217,7 +220,7 @@ public: if (!beam) { SummonBeams(); - beam=true; + beam = true; } //Return since we have no target if (!UpdateVictim()) diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp index 6e2a0f3c192..e8259aa34dd 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp @@ -24,10 +24,16 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" #include "Spell.h" -#include "Player.h" +#include "TemporarySummon.h" #include "WorldSession.h" enum LadyVashj @@ -140,7 +146,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_lady_vashjAI : public ScriptedAI @@ -257,7 +263,7 @@ public: void EnterCombat(Unit* who) override { // remove old tainted cores to prevent cheating in phase 2 - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) if (Player* player = itr->GetSource()) player->DestroyItemCount(31088, 1, true); @@ -327,7 +333,7 @@ public: } else { - AggroTimer-=diff; + AggroTimer -= diff; return; } } @@ -555,7 +561,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_enchanted_elementalAI : public ScriptedAI @@ -650,7 +656,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_tainted_elementalAI : public ScriptedAI @@ -724,7 +730,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_toxic_sporebatAI : public ScriptedAI @@ -826,7 +832,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_shield_generator_channelAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp index 3342b423f14..ced4aeb9fd3 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_leotheras_the_blind.cpp @@ -24,9 +24,14 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" -#include "Player.h" +#include "TemporarySummon.h" enum LeotherasTheBlind { @@ -76,7 +81,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_inner_demonAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_inner_demonAI : public ScriptedAI @@ -153,7 +158,7 @@ public: AttackStart(owner); } else if (owner && owner->isDead()) { - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); return; } } @@ -186,7 +191,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_leotheras_the_blindAI : public ScriptedAI @@ -327,7 +332,7 @@ public: if (instance->GetGuidData(DATA_LEOTHERAS_EVENT_STARTER)) { - Unit* victim = NULL; + Unit* victim = nullptr; victim = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_LEOTHERAS_EVENT_STARTER)); if (victim) me->getThreatManager().addThreat(victim, 1); @@ -514,7 +519,7 @@ public: { //DoCastVictim(SPELL_CHAOS_BLAST, true); int damage = 100; - me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, NULL, NULL, false, NULL, NULL, me->GetGUID()); + me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, nullptr, nullptr, false, nullptr, nullptr, me->GetGUID()); } ChaosBlast_Timer = 3000; } else ChaosBlast_Timer -= diff; @@ -580,7 +585,7 @@ public: //at this point he divides himself in two parts CastConsumingMadness(); DespawnDemon(); - Creature* Copy = NULL; + Creature* Copy = nullptr; Copy = DoSpawnCreature(DEMON_FORM, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 6000); if (Copy) { @@ -608,7 +613,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_leotheras_the_blind_demonformAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_leotheras_the_blind_demonformAI : public ScriptedAI @@ -672,7 +677,7 @@ public: { //DoCastVictim(SPELL_CHAOS_BLAST, true); int damage = 100; - me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, NULL, NULL, false, NULL, NULL, me->GetGUID()); + me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, nullptr, nullptr, false, nullptr, nullptr, me->GetGUID()); ChaosBlast_Timer = 3000; } } else ChaosBlast_Timer -= diff; @@ -689,7 +694,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_greyheart_spellbinderAI : public ScriptedAI @@ -758,7 +763,7 @@ public: if (!me->IsInCombat() && instance->GetGuidData(DATA_LEOTHERAS_EVENT_STARTER)) { - Unit* victim = NULL; + Unit* victim = nullptr; victim = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_LEOTHERAS_EVENT_STARTER)); if (victim) AttackStart(victim); @@ -778,7 +783,7 @@ public: if (Mindblast_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target)DoCast(target, SPELL_MINDBLAST); @@ -788,7 +793,7 @@ public: if (Earthshock_Timer <= diff) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) { if (Player* i_pl = itr->GetSource()) diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp index 7337763c298..e93ea5e7ec9 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp @@ -24,11 +24,16 @@ SDCategory: The Lurker Below EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedCreature.h" #include "serpent_shrine.h" #include "Spell.h" -#include "Player.h" +#include "TemporarySummon.h" enum Spells { @@ -84,7 +89,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_the_lurker_belowAI : public ScriptedAI @@ -170,7 +175,6 @@ public: } void MoveInLineOfSight(Unit* who) override - { if (!CanStartEvent) // boss is invisible, don't attack return; @@ -239,7 +243,9 @@ public: DoCast(me, SPELL_SUBMERGE); PhaseTimer = 60000; // 60secs submerged Submerged = true; - } else PhaseTimer-=diff; + } + else + PhaseTimer -= diff; if (SpoutTimer <= diff) { @@ -250,19 +256,23 @@ public: WhirlTimer = 20000; // whirl directly after spout RotTimer = 20000; return; - } else SpoutTimer -= diff; + } + else + SpoutTimer -= diff; // Whirl directly after a Spout and at random times if (WhirlTimer <= diff) { WhirlTimer = 18000; DoCast(me, SPELL_WHIRL); - } else WhirlTimer -= diff; + } + else + WhirlTimer -= diff; if (CheckTimer <= diff)//check if there are players in melee range { InRange = false; - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -272,11 +282,13 @@ public: } } CheckTimer = 2000; - } else CheckTimer -= diff; + } + else + CheckTimer -= diff; if (RotTimer) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->GetSource() && i->GetSource()->IsAlive() && me->HasInArc(diff/20000.f*float(M_PI)*2.f, i->GetSource()) && me->IsWithinDist(i->GetSource(), SPOUT_DIST) && !i->GetSource()->IsInWater()) @@ -292,7 +304,9 @@ public: if (RotTimer <= diff) { RotTimer = 0; - } else RotTimer -= diff; + } + else + RotTimer -= diff; return; } @@ -304,7 +318,9 @@ public: if (target) DoCast(target, SPELL_GEYSER, true); GeyserTimer = rand32() % 5000 + 15000; - } else GeyserTimer -= diff; + } + else + GeyserTimer -= diff; if (!InRange) // if on players in melee range cast Waterbolt { @@ -316,7 +332,9 @@ public: if (target) DoCast(target, SPELL_WATERBOLT, true); WaterboltTimer = 3000; - } else WaterboltTimer -= diff; + } + else + WaterboltTimer -= diff; } if (!UpdateVictim()) @@ -339,7 +357,9 @@ public: SpoutTimer = 3000; // directly cast Spout after emerging! PhaseTimer = 120000; return; - } else PhaseTimer-=diff; + } + else + PhaseTimer -= diff; if (me->getThreatManager().getThreatList().empty()) // check if should evade { @@ -371,7 +391,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_coilfang_ambusherAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_coilfang_ambusherAI : public ScriptedAI @@ -421,7 +441,7 @@ public: { int bp0 = 1100; if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) - me->CastCustomSpell(target, SPELL_SHOOT, &bp0, NULL, NULL, true); + me->CastCustomSpell(target, SPELL_SHOOT, &bp0, nullptr, nullptr, true); ShootBowTimer = 4000 + rand32() % 5000; MultiShotTimer += 1500; // add global cooldown } else ShootBowTimer -= diff; @@ -460,7 +480,7 @@ class go_strange_pool : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetSerpentshrineCavernAI(go); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp index 8640213703e..02ccdb7f075 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp @@ -24,8 +24,11 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" +#include "TemporarySummon.h" enum Yells { @@ -91,7 +94,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_morogrim_tidewalkerAI : public ScriptedAI @@ -296,7 +299,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_water_globuleAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_water_globuleAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp index 0844e1a3e0f..4b694ab5861 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp @@ -24,11 +24,14 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "InstanceScript.h" -#include "serpent_shrine.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "serpent_shrine.h" #include "TemporarySummon.h" -#include "GameObjectAI.h" #define MAX_ENCOUNTER 6 @@ -81,14 +84,14 @@ class go_bridge_console : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetSerpentshrineCavernAI(go); } }; class instance_serpent_shrine : public InstanceMapScript { public: - instance_serpent_shrine() : InstanceMapScript("instance_serpent_shrine", 548) { } + instance_serpent_shrine() : InstanceMapScript(SSCScriptName, 548) { } struct instance_serpentshrine_cavern_InstanceMapScript : public InstanceScript { @@ -130,7 +133,7 @@ class instance_serpent_shrine : public InstanceMapScript else Water = WATERSTATE_FRENZY; - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (PlayerList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -141,12 +144,11 @@ class instance_serpent_shrine : public InstanceMapScript { if (Water == WATERSTATE_SCALDING) { - if (!player->HasAura(SPELL_SCALDINGWATER)) - { player->CastSpell(player, SPELL_SCALDINGWATER, true); - } - } else if (Water == WATERSTATE_FRENZY) + + } + else if (Water == WATERSTATE_FRENZY) { //spawn frenzy if (DoSpawnFrenzy) @@ -390,7 +392,7 @@ class instance_serpent_shrine : public InstanceMapScript return stream.str(); } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h index 0fe6a947e05..0878bb7352d 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h @@ -19,6 +19,9 @@ #ifndef DEF_SERPENT_SHRINE_H #define DEF_SERPENT_SHRINE_H +#include "CreatureAIImpl.h" + +#define SSCScriptName "instance_serpent_shrine" #define DataHeader "SS" enum SSWaterEventState @@ -57,4 +60,10 @@ enum SSDataTypes DATA_TRASH = 25, }; +template +inline AI* GetSerpentshrineCavernAI(T* obj) +{ + return GetInstanceAI(obj, SSCScriptName); +} + #endif diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp index f7e9dff38bf..90d3800b965 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp @@ -114,7 +114,7 @@ class boss_hydromancer_thespia : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } }; @@ -175,7 +175,7 @@ class npc_coilfang_waterelemental : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_coilfang_waterelementalAI(creature); + return GetSteamVaultAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp index bd13ab09a67..f0bbe51c31d 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp @@ -23,6 +23,8 @@ SDCategory: Coilfang Resevoir, The Steamvault EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "steam_vault.h" @@ -57,7 +59,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct boss_mekgineer_steamriggerAI : public ScriptedAI @@ -200,7 +202,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct npc_steamrigger_mechanicAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp index e0aaf89e25d..cc57cc53ffa 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp @@ -23,9 +23,10 @@ SDCategory: Coilfang Resevoir, The Steamvault EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" -#include "steam_vault.h" #include "SpellInfo.h" +#include "steam_vault.h" enum NagaDistiller { @@ -50,7 +51,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct npc_naga_distillerAI : public ScriptedAI @@ -103,7 +104,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct boss_warlord_kalithreshAI : public ScriptedAI @@ -148,7 +149,7 @@ public: Talk(SAY_SLAY); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { //hack :( if (spell->Id == SPELL_WARLORDS_RAGE_PROC) diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp index e1ee926e85d..be3afe3f2a8 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp @@ -16,8 +16,12 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "steam_vault.h" class go_main_chambers_access_panel : public GameObjectScript diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h index ceed2eaaa14..8d0a6136cef 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h @@ -18,6 +18,8 @@ #ifndef DEF_STEAM_VAULT_H #define DEF_STEAM_VAULT_H +#include "CreatureAIImpl.h" + #define SteamVaultScriptName "instance_steam_vault" #define DataHeader "SV" @@ -49,8 +51,8 @@ enum SVGameObjectIds GO_ACCESS_PANEL_MEK = 184126 }; -template -AI* GetSteamVaultAI(T* obj) +template +inline AI* GetSteamVaultAI(T* obj) { return GetInstanceAI(obj, SteamVaultScriptName); } diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp index f50506784a9..4bbbb8f6a29 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp @@ -15,14 +15,22 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "CreatureTextMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "Group.h" +#include "InstanceScript.h" #include "LFGMgr.h" -#include "ScriptedGossip.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "GameObjectAI.h" -#include "ScriptMgr.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "the_slave_pens.h" enum Spells @@ -280,7 +288,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -358,7 +366,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -396,7 +404,7 @@ public: _summons.DespawnAll(); ResetFlameCallers(); - me->SummonGameObject(GO_ICE_STONE, -69.90455f, -162.2449f, -2.366563f, 2.426008f, G3D::Quat(0.0f, 0.0f, 0.9366722f, 0.3502074f), 0); + me->SummonGameObject(GO_ICE_STONE, -69.90455f, -162.2449f, -2.366563f, 2.426008f, QuaternionData(0.0f, 0.0f, 0.9366722f, 0.3502074f), 0); } void DoAction(int32 action) override @@ -510,7 +518,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -638,7 +646,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -672,7 +680,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetSlavePensAI(go); } }; @@ -688,9 +696,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SYNCH_HEALTH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SYNCH_HEALTH }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -724,9 +730,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_WHISP_FLIGHT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMONING_RHYME_BONFIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCE_WHISP_FLIGHT, SPELL_SUMMONING_RHYME_BONFIRE }); } void PeriodicTick(AuraEffect const* aurEff) @@ -742,14 +746,14 @@ public: switch (aurEff->GetTickNumber()) { case 1: - sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_1, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_1, nullptr, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); player->CastSpell(player, SPELL_SUMMONING_RHYME_BONFIRE, true); break; case 2: - sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_2, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_2, nullptr, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); break; case 3: - sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_3, NULL, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_3, nullptr, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); Remove(); break; } @@ -779,9 +783,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_GO) || !sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_KNOCKBACK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ICE_SPEAR_GO, SPELL_ICE_SPEAR_KNOCKBACK }); } void PeriodicTick(AuraEffect const* aurEff) @@ -832,9 +834,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_TARGET_PICKER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_SPEAR_TARGET_PICKER }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -867,9 +867,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_BUNNY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ICE_SPEAR_BUNNY }); } void FilterTargets(std::list& targets) @@ -912,9 +910,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SLIPPERY_FLOOR_SLIP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SLIPPERY_FLOOR_SLIP }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -951,9 +947,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_COLD_SLAP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_COLD_SLAP }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -1013,9 +1007,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_BOMBARDMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_BOMBARDMENT }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp index 7a9fa30b631..0c93b0b1631 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp @@ -134,7 +134,7 @@ class boss_mennu_the_betrayer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_mennu_the_betrayerAI(creature); + return GetSlavePensAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp index 36400166f09..6d46ef4ac07 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp @@ -117,7 +117,7 @@ class boss_quagmirran : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_quagmirranAI(creature); + return GetSlavePensAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp index cab61b0f7e9..71e51df4c1c 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp @@ -128,7 +128,7 @@ class boss_rokmar_the_crackler : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_rokmar_the_cracklerAI(creature); + return GetSlavePensAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp index 77b438a11c2..22650515c90 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/instance_the_slave_pens.cpp @@ -23,7 +23,9 @@ gets instead the deserter debuff. */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "the_slave_pens.h" class instance_the_slave_pens : public InstanceMapScript diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h index 9b22d61f4e7..3127941e392 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h @@ -18,6 +18,8 @@ #ifndef SLAVE_PENS_H #define SLAVE_PENS_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 3; #define SPScriptName "instance_the_slave_pens" @@ -66,4 +68,10 @@ enum SPGameObjectIds GO_ICE_STONE = 187882 }; +template +inline AI* GetSlavePensAI(T* obj) +{ + return GetInstanceAI(obj, SPScriptName); +} + #endif // SLAVE_PENS_H diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp index ca8c64194ab..3ca97269d19 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "the_underbog.h" enum Spells { @@ -43,7 +44,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_hungarfenAI(creature); + return GetTheUnderbogAI(creature); } struct boss_hungarfenAI : public ScriptedAI @@ -117,7 +118,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_underbog_mushroomAI(creature); + return GetTheUnderbogAI(creature); } struct npc_underbog_mushroomAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp index a21d4238625..9794b7d331a 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp @@ -24,7 +24,9 @@ SDCategory: Coilfang Resevoir, Underbog EndScriptData */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "the_underbog.h" enum Spells { @@ -49,7 +51,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_the_black_stalkerAI(creature); + return GetTheUnderbogAI(creature); } struct boss_the_black_stalkerAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp index 7da087cc0b1..6168f57e3f2 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp @@ -24,11 +24,13 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" +#include "the_underbog.h" class instance_the_underbog : public InstanceMapScript { public: - instance_the_underbog() : InstanceMapScript("instance_the_underbog", 546) { } + instance_the_underbog() : InstanceMapScript(TheUndebogScriptName, 546) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h new file mode 100644 index 00000000000..7de1686dfb7 --- /dev/null +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef the_underbog_h__ +#define the_underbog_h__ + +#include "CreatureAIImpl.h" + +#define TheUndebogScriptName "instance_the_underbog" + +template +inline AI* GetTheUnderbogAI(T* obj) +{ + return GetInstanceAI(obj, TheUndebogScriptName); +} + +#endif // the_underbog_h__ diff --git a/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp b/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp index 1406c118ad1..4d65803a7cd 100644 --- a/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp +++ b/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp @@ -24,9 +24,11 @@ SDCategory: Gruul's Lair EndScriptData */ #include "ScriptMgr.h" +#include "gruuls_lair.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "gruuls_lair.h" enum Yells { @@ -121,7 +123,7 @@ class boss_gruul : public CreatureScript Talk(SAY_DEATH); } - void SpellHitTarget(Unit* target, const SpellInfo* pSpell) override + void SpellHitTarget(Unit* target, SpellInfo const* pSpell) override { //This to emulate effect1 (77) of SPELL_GROUND_SLAM, knock back to any direction //It's initially wrong, since this will cause fall damage, which is by comments, not intended. @@ -132,11 +134,11 @@ class boss_gruul : public CreatureScript switch (urand(0, 1)) { case 0: - target->CastSpell(target, SPELL_MAGNETIC_PULL, true, NULL, NULL, me->GetGUID()); + target->CastSpell(target, SPELL_MAGNETIC_PULL, true, nullptr, nullptr, me->GetGUID()); break; case 1: - target->CastSpell(target, SPELL_KNOCK_BACK, true, NULL, NULL, me->GetGUID()); + target->CastSpell(target, SPELL_KNOCK_BACK, true, nullptr, nullptr, me->GetGUID()); break; } } @@ -234,7 +236,7 @@ class boss_gruul : public CreatureScript if (m_uiCaveIn_StaticTimer >= 4000) m_uiCaveIn_StaticTimer -= 2000; - m_uiCaveIn_Timer = m_uiCaveIn_StaticTimer; + m_uiCaveIn_Timer = m_uiCaveIn_StaticTimer; } else m_uiCaveIn_Timer -= diff; @@ -275,11 +277,7 @@ class spell_gruul_shatter : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_STONED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHATTER_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_STONED, SPELL_SHATTER_EFFECT }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -287,7 +285,7 @@ class spell_gruul_shatter : public SpellScriptLoader if (Unit* target = GetHitUnit()) { target->RemoveAurasDueToSpell(SPELL_STONED); - target->CastSpell((Unit*)NULL, SPELL_SHATTER_EFFECT, true); + target->CastSpell((Unit*)nullptr, SPELL_SHATTER_EFFECT, true); } } diff --git a/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp b/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp index 2d3cd909ff6..b3aafe004a6 100644 --- a/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp +++ b/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp @@ -24,8 +24,11 @@ SDCategory: Gruul's Lair EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "gruuls_lair.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum HighKingMaulgar { @@ -178,7 +181,7 @@ public: //Charging_Timer if (Charging_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) { @@ -290,7 +293,7 @@ public: //DeathCoil Timer /need correct timer if (DeathCoil_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) DoCast(target, SPELL_DEATH_COIL); @@ -555,7 +558,7 @@ public: //BlastWave_Timer if (BlastWave_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; std::list t_list = me->getThreatManager().getThreatList(); std::vector target_list; for (std::list::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) @@ -564,7 +567,7 @@ public: //15 yard radius minimum if (target && target->IsWithinDist(me, 15, false)) target_list.push_back(target); - target = NULL; + target = nullptr; } if (!target_list.empty()) target = *(target_list.begin() + rand32() % target_list.size()); diff --git a/src/server/scripts/Outland/GruulsLair/gruuls_lair.h b/src/server/scripts/Outland/GruulsLair/gruuls_lair.h index dd9017d780d..4497d88ca05 100644 --- a/src/server/scripts/Outland/GruulsLair/gruuls_lair.h +++ b/src/server/scripts/Outland/GruulsLair/gruuls_lair.h @@ -18,6 +18,8 @@ #ifndef GRUULS_LAIR_H_ #define GRUULS_LAIR_H_ +#include "CreatureAIImpl.h" + #define GLScriptName "instance_gruuls_lair" #define DataHeader "GL" @@ -45,10 +47,10 @@ enum GLGameObjectIds GO_GRUUL_DOOR = 184662 }; -template -AI* GetGruulsLairAI(Creature* creature) +template +inline AI* GetGruulsLairAI(T* obj) { - return GetInstanceAI(creature, GLScriptName); + return GetInstanceAI(obj, GLScriptName); } #endif // GRUULS_LAIR_H_ diff --git a/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp b/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp index 2145ebee721..55cda953d94 100644 --- a/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp +++ b/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" #include "gruuls_lair.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { @@ -52,58 +54,12 @@ class instance_gruuls_lair : public InstanceMapScript void OnCreatureCreate(Creature* creature) override { - switch (creature->GetEntry()) - { - case NPC_MAULGAR: - MaulgarGUID = creature->GetGUID(); - // no break; - case NPC_KROSH_FIREHAND: - case NPC_OLM_THE_SUMMONER: - case NPC_KIGGLER_THE_CRAZED: - case NPC_BLINDEYE_THE_SEER: - AddMinion(creature, true); - break; - default: - break; - } - } + InstanceScript::OnCreatureCreate(creature); - void OnCreatureRemove(Creature* creature) override - { switch (creature->GetEntry()) { case NPC_MAULGAR: - case NPC_KROSH_FIREHAND: - case NPC_OLM_THE_SUMMONER: - case NPC_KIGGLER_THE_CRAZED: - case NPC_BLINDEYE_THE_SEER: - AddMinion(creature, false); - break; - default: - break; - } - } - - void OnGameObjectCreate(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_MAULGAR_DOOR: - case GO_GRUUL_DOOR: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_MAULGAR_DOOR: - case GO_GRUUL_DOOR: - AddDoor(go, false); + MaulgarGUID = creature->GetGUID(); break; default: break; diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h index 942f6fa9e6a..cf8ce2e5024 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h @@ -18,6 +18,8 @@ #ifndef BLOOD_FURNACE_H_ #define BLOOD_FURNACE_H_ +#include "CreatureAIImpl.h" + #define BFScriptName "instance_blood_furnace" #define DataHeader "BF" @@ -80,8 +82,8 @@ enum BFActionIds ACTION_PREPARE_BROGGOK = 3 }; -template -AI* GetBloodFurnaceAI(T* obj) +template +inline AI* GetBloodFurnaceAI(T* obj) { return GetInstanceAI(obj, BFScriptName); } diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp index ddf51c0821d..69f7a05a634 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp @@ -16,11 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "blood_furnace.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "SpellScript.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" -#include "blood_furnace.h" +#include "SpellScript.h" enum Yells { @@ -166,9 +169,7 @@ class spell_broggok_poison_cloud : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void PeriodicTick(AuraEffect const* aurEff) @@ -177,7 +178,7 @@ class spell_broggok_poison_cloud : public SpellScriptLoader uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; int32 mod = int32(((float(aurEff->GetTickNumber()) / aurEff->GetTotalTicks()) * 0.9f + 0.1f) * 10000 * 2 / 3); - GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)NULL, TRIGGERED_FULL_MASK, NULL, aurEff); + GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)nullptr, TRIGGERED_FULL_MASK, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp index f3764c68434..a91669761d1 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp @@ -17,9 +17,11 @@ */ #include "ScriptMgr.h" +#include "blood_furnace.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "blood_furnace.h" +#include "TemporarySummon.h" enum Kelidan { diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp index 09cd247d89a..e662282b2be 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "blood_furnace.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ScriptedCreature.h" DoorData const doorData[] = { @@ -79,17 +81,12 @@ class instance_blood_furnace : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_PRISON_DOOR_04: PrisonDoor4GUID = go->GetGUID(); - // no break - case GO_PRISON_DOOR_01: - case GO_PRISON_DOOR_02: - case GO_PRISON_DOOR_03: - case GO_PRISON_DOOR_05: - case GO_SUMMON_DOOR: - AddDoor(go, true); break; case GO_BROGGOK_LEVER: BroggokLeverGUID = go->GetGUID(); @@ -123,23 +120,6 @@ class instance_blood_furnace : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_PRISON_DOOR_01: - case GO_PRISON_DOOR_02: - case GO_PRISON_DOOR_03: - case GO_PRISON_DOOR_04: - case GO_PRISON_DOOR_05: - case GO_SUMMON_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - ObjectGuid GetGuidData(uint32 type) const override { switch (type) diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp index feb8b29ca98..a8914c31b96 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp @@ -24,9 +24,10 @@ SDCategory: Hellfire Citadel, Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" #include "hellfire_ramparts.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Says { @@ -157,7 +158,7 @@ class boss_omor_the_unscarred : public CreatureScript else if (OrbitalStrike_Timer <= diff) { - Unit* temp = NULL; + Unit* temp = nullptr; if (me->IsWithinMeleeRange(me->GetVictim())) temp = me->GetVictim(); else temp = SelectTarget(SELECT_TARGET_RANDOM, 0); @@ -230,7 +231,7 @@ class boss_omor_the_unscarred : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHellfireRampartsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp index 7a4651f3f00..ecfecf2073e 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp @@ -24,9 +24,12 @@ Category: Hellfire Citadel, Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" +#include "hellfire_ramparts.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" -#include "hellfire_ramparts.h" +#include "TemporarySummon.h" enum Says { @@ -108,7 +111,7 @@ class boss_nazan : public CreatureScript } } - void SpellHitTarget(Unit* target, const SpellInfo* entry) override + void SpellHitTarget(Unit* target, SpellInfo const* entry) override { if (target && entry->Id == uint32(SPELL_FIREBALL)) me->SummonCreature(NPC_LIQUID_FIRE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 30000); @@ -196,7 +199,7 @@ class boss_nazan : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_nazanAI(creature); + return GetHellfireRampartsAI(creature); } }; @@ -282,7 +285,7 @@ class boss_vazruden : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_vazrudenAI(creature); + return GetHellfireRampartsAI(creature); } }; @@ -454,7 +457,7 @@ class boss_vazruden_the_herald : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_vazruden_the_heraldAI(creature); + return GetHellfireRampartsAI(creature); } }; @@ -511,7 +514,7 @@ class npc_hellfire_sentry : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_hellfire_sentryAI(creature); + return GetHellfireRampartsAI(creature); } }; void AddSC_boss_vazruden_the_herald() diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp index 0115d3fdd88..dd2e7700d1c 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp @@ -24,8 +24,8 @@ SDCategory: Hellfire Citadel, Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "hellfire_ramparts.h" +#include "ScriptedCreature.h" enum Says { @@ -175,7 +175,7 @@ class boss_watchkeeper_gargolmar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_watchkeeper_gargolmarAI(creature); + return GetHellfireRampartsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h index 620f4018f6d..3137398e766 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h @@ -19,6 +19,9 @@ #ifndef DEF_RAMPARTS_H #define DEF_RAMPARTS_H +#include "CreatureAIImpl.h" + +#define HRScriptName "instance_ramparts" #define DataHeader "HR" uint32 const EncounterCount = 4; @@ -46,4 +49,10 @@ enum HRGameobjectIds GO_FEL_IRON_CHEST_HEROIC = 185169 }; +template +inline AI* GetHellfireRampartsAI(T* obj) +{ + return GetInstanceAI(obj, HRScriptName); +} + #endif diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp index 8d6ac51f81a..2de3c155eef 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp @@ -24,13 +24,15 @@ SDCategory: Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "GameObject.h" #include "hellfire_ramparts.h" +#include "InstanceScript.h" +#include "Map.h" class instance_ramparts : public InstanceMapScript { public: - instance_ramparts() : InstanceMapScript("instance_ramparts", 543) { } + instance_ramparts() : InstanceMapScript(HRScriptName, 543) { } struct instance_ramparts_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp index c4917afd598..bd676f73680 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp @@ -16,14 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" #include "magtheridons_lair.h" +#include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "PassiveAI.h" -#include "GameObjectAI.h" enum Yells { @@ -304,7 +306,7 @@ class boss_magtheridon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagtheridonsLairAI(creature); } }; @@ -422,7 +424,7 @@ class npc_hellfire_channeler : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagtheridonsLairAI(creature); } }; @@ -455,7 +457,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_magtheridon_roomAI(creature); + return GetMagtheridonsLairAI(creature); } }; @@ -483,7 +485,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new go_manticron_cubeAI(go); + return GetMagtheridonsLairAI(go); } }; @@ -499,9 +501,7 @@ class spell_magtheridon_blaze_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLAZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLAZE }); } void HandleAura() @@ -534,9 +534,7 @@ class spell_magtheridon_shadow_grasp : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIND_EXHAUSTION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIND_EXHAUSTION }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -570,10 +568,11 @@ class spell_magtheridon_shadow_grasp_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_CAGE) - || !sSpellMgr->GetSpellInfo(SPELL_SHADOW_GRASP_VISUAL)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHADOW_CAGE, + SPELL_SHADOW_GRASP_VISUAL + }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp index 6ad969c4ab7..087343a83f4 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "AreaBoundary.h" +#include "GameObject.h" #include "InstanceScript.h" #include "magtheridons_lair.h" +#include "Map.h" +#include "ScriptedCreature.h" BossBoundaryData const boundaries = { @@ -64,7 +67,7 @@ static MLDataTypes const collapseObjectDatas[] = class instance_magtheridons_lair : public InstanceMapScript { public: - instance_magtheridons_lair() : InstanceMapScript("instance_magtheridons_lair", 544) { } + instance_magtheridons_lair() : InstanceMapScript(MLScriptName, 544) { } struct instance_magtheridons_lair_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h index 7ed1ab9ebaa..2b330222d6d 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h @@ -18,6 +18,9 @@ #ifndef DEF_MAGTHERIDONS_LAIR_H #define DEF_MAGTHERIDONS_LAIR_H +#include "CreatureAIImpl.h" + +#define MLScriptName "instance_magtheridons_lair" #define DataHeader "ML" uint32 const EncounterCount = 1; @@ -71,4 +74,10 @@ enum MLGameObjectIds GO_MAGTHERIDON_COLUMN_5 = 184637 }; +template +inline AI* GetMagtheridonsLairAI(T* obj) +{ + return GetInstanceAI(obj, MLScriptName); +} + #endif diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp index 2bf0b1870fb..b6dcb21af5c 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp @@ -30,6 +30,8 @@ npc_lesser_shadow_fissure EndContentData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shattered_halls.h" @@ -299,7 +301,7 @@ class boss_grand_warlock_nethekurse : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; @@ -367,7 +369,7 @@ class npc_fel_orc_convert : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; @@ -392,7 +394,7 @@ class npc_lesser_shadow_fissure : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_lesser_shadow_fissureAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp index 68ac53eb708..967e01a5cef 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp @@ -29,6 +29,8 @@ boss_warbringer_omrogg EndContentData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shattered_halls.h" @@ -393,7 +395,7 @@ class boss_warbringer_omrogg : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; @@ -443,7 +445,7 @@ class npc_omrogg_heads : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp index 08b442e033b..4d51aa67447 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warchief_kargath_bladefist.cpp @@ -28,6 +28,9 @@ boss_warchief_kargath_bladefist EndContentData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shattered_halls.h" @@ -331,7 +334,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp index 156100f1316..f4fa4ab4cde 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp @@ -24,13 +24,15 @@ SDCategory: Hellfire Citadel, Shattered Halls EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "InstanceScript.h" +#include "Map.h" #include "Player.h" -#include "SpellAuras.h" +#include "ScriptedCreature.h" #include "shattered_halls.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" DoorData const doorData[] = { @@ -42,7 +44,7 @@ DoorData const doorData[] = class instance_shattered_halls : public InstanceMapScript { public: - instance_shattered_halls() : InstanceMapScript("instance_shattered_halls", 540) { } + instance_shattered_halls() : InstanceMapScript(SHScriptName, 540) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -92,35 +94,11 @@ class instance_shattered_halls : public InstanceMapScript ex->SetDuration(executionTimer); } - void OnGameObjectCreate(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_GRAND_WARLOCK_CHAMBER_DOOR_1: - case GO_GRAND_WARLOCK_CHAMBER_DOOR_2: - AddDoor(go, true); - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_GRAND_WARLOCK_CHAMBER_DOOR_1: - case GO_GRAND_WARLOCK_CHAMBER_DOOR_2: - AddDoor(go, false); - default: - break; - } - } - void OnCreatureCreate(Creature* creature) override { if (!_team) { - Map::PlayerList const &players = instance->GetPlayers(); + Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) if (Player* player = players.begin()->GetSource()) _team = player->GetTeam(); diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp index 3dad650b782..45fc8df0d1a 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp @@ -16,13 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "SpellAuras.h" +#include "ScriptedCreature.h" #include "shattered_halls.h" +#include "SpellScript.h" +#include "TemporarySummon.h" class at_nethekurse_exit : public AreaTriggerScript { @@ -109,7 +110,7 @@ class boss_shattered_executioner : public CreatureScript if (instance->GetData(DATA_PRISONERS_EXECUTED) > 0) return; - Map::PlayerList const &players = instance->instance->GetPlayers(); + Map::PlayerList const& players = instance->instance->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { Player* pl = itr->GetSource(); @@ -128,7 +129,7 @@ class boss_shattered_executioner : public CreatureScript if (data == 1) { - Map::PlayerList const &players = instance->instance->GetPlayers(); + Map::PlayerList const& players = instance->instance->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { Player* pl = itr->GetSource(); @@ -173,7 +174,7 @@ class boss_shattered_executioner : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h index d62746e098f..50483e6f518 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h @@ -19,6 +19,9 @@ #ifndef DEF_SHATTERED_H #define DEF_SHATTERED_H +#include "CreatureAIImpl.h" + +#define SHScriptName "instance_shattered_halls" #define DataHeader "SH" uint32 const EncounterCount = 4; @@ -88,27 +91,32 @@ enum SHActions ACTION_EXECUTIONER_TAUNT = 1 }; -const Position Executioner = { 152.8524f, -83.63912f, 2.021005f, 0.06981317f }; +Position const Executioner = { 152.8524f, -83.63912f, 2.021005f, 0.06981317f }; struct FactionSpawnerHelper { - FactionSpawnerHelper(uint32 allianceEntry, uint32 hordeEntry, const Position& pos) : _allianceNPC(allianceEntry), _hordeNPC(hordeEntry), _spawnPos(pos) { } + FactionSpawnerHelper(uint32 allianceEntry, uint32 hordeEntry, Position const& pos) : _allianceNPC(allianceEntry), _hordeNPC(hordeEntry), _spawnPos(pos) { } inline uint32 operator()(uint32 teamID) const { return teamID == ALLIANCE ? _allianceNPC : _hordeNPC; } inline Position const& GetPos() const { return _spawnPos; } private: - const uint32 _allianceNPC; - const uint32 _hordeNPC; - const Position _spawnPos; + uint32 const _allianceNPC; + uint32 const _hordeNPC; + Position const _spawnPos; }; -const FactionSpawnerHelper executionerVictims[VictimCount] = +FactionSpawnerHelper const executionerVictims[VictimCount] = { { NPC_CAPTAIN_ALINA, NPC_CAPTAIN_BONESHATTER, { 138.8807f, -84.22707f, 1.992269f, 0.06981317f } }, { NPC_ALLIANCE_VICTIM_1, NPC_HORDE_VICTIM_1, { 151.2411f, -91.02930f, 2.019741f, 1.57079600f } }, { NPC_ALLIANCE_VICTIM_2, NPC_HORDE_VICTIM_2, { 151.0459f, -77.51981f, 2.021008f, 4.74729500f } } }; +template +inline AI* GetShatteredHallsAI(T* obj) +{ + return GetInstanceAI(obj, SHScriptName); +} #endif diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp index 07d833bb234..4e891c9ba7a 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp @@ -24,9 +24,13 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "the_eye.h" #include "SpellInfo.h" +#include "TemporarySummon.h" +#include "the_eye.h" enum Spells { @@ -185,13 +189,13 @@ class boss_alar : public CreatureScript } } - void SpellHit(Unit*, const SpellInfo* spell) override + void SpellHit(Unit*, SpellInfo const* spell) override { if (spell->Id == SPELL_DIVE_BOMB_VISUAL) { me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, true); me->SetDisplayId(11686); - //me->SendUpdateObjectToAllExcept(NULL); + //me->SendUpdateObjectToAllExcept(nullptr); } } @@ -432,7 +436,7 @@ class boss_alar : public CreatureScript } else { - Unit* target = NULL; + Unit* target = nullptr; target = me->SelectNearestTargetInAttackDistance(5); if (target) AttackStart(target); @@ -448,7 +452,7 @@ class boss_alar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -520,7 +524,7 @@ class npc_ember_of_alar : public CreatureScript if (toDie) { - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); //me->SetVisibility(VISIBILITY_OFF); } @@ -531,7 +535,7 @@ class npc_ember_of_alar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -553,7 +557,7 @@ class npc_flame_patch_alar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_flame_patch_alarAI(creature); + return GetTheEyeAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp index 3ba299d2ea0..813910f5bc5 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp @@ -24,10 +24,13 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" - +#include "TemporarySummon.h" #include "the_eye.h" enum Yells @@ -289,7 +292,7 @@ class boss_high_astromancer_solarian : public CreatureScript //After these 50 seconds she portals to the middle of the room and disappears, leaving 3 light portals behind. me->GetMotionMaster()->Clear(); me->UpdatePosition(CENTER_X, CENTER_Y, CENTER_Z, CENTER_O); - for (uint8 i=0; i <= 2; ++i) + for (uint8 i = 0; i <= 2; ++i) { if (!i) { @@ -306,15 +309,15 @@ class boss_high_astromancer_solarian : public CreatureScript } if ((std::abs(Portals[2][0] - Portals[1][0]) < 7) && (std::abs(Portals[2][1] - Portals[1][1]) < 7)) { - int i=1; + int i = 1; if (std::abs(CENTER_X + 26.0f - Portals[2][0]) < 7) i = -1; - Portals[2][0] = Portals[2][0]+7*i; + Portals[2][0] = Portals[2][0] + 7 * i; Portals[2][1] = Portal_Y(Portals[2][0], LARGE_PORTAL_RADIUS); } - for (int i=0; i <= 2; ++i) + for (int i = 0; i <= 2; ++i) { - if (Creature* Summoned = me->SummonCreature(NPC_ASTROMANCER_SOLARIAN_SPOTLIGHT, Portals[i][0], Portals[i][1], Portals[i][2], CENTER_O, TEMPSUMMON_TIMED_DESPAWN, Phase2_Timer+Phase3_Timer+AppearDelay_Timer+1700)) + if (Creature* Summoned = me->SummonCreature(NPC_ASTROMANCER_SOLARIAN_SPOTLIGHT, Portals[i][0], Portals[i][1], Portals[i][2], CENTER_O, TEMPSUMMON_TIMED_DESPAWN, Phase2_Timer + Phase3_Timer + AppearDelay_Timer + 1700)) { Summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Summoned->CastSpell(Summoned, SPELL_SPOTLIGHT, false); @@ -323,7 +326,7 @@ class boss_high_astromancer_solarian : public CreatureScript AppearDelay = true; } else - Phase1_Timer-=diff; + Phase1_Timer -= diff; } else if (Phase == 2) { @@ -410,7 +413,7 @@ class boss_high_astromancer_solarian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -455,7 +458,7 @@ class npc_solarium_priest : public CreatureScript if (healTimer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; switch (urand(0, 1)) { case 0: @@ -497,7 +500,7 @@ class npc_solarium_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -512,9 +515,7 @@ class spell_astromancer_wrath_of_the_astromancer : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WRATH_OF_THE_ASTROMANCER_DOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WRATH_OF_THE_ASTROMANCER_DOT }); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp index 09e360a3b87..78ba67004bc 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp @@ -24,8 +24,13 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "Spell.h" +#include "SpellInfo.h" #include "SpellScript.h" #include "the_eye.h" @@ -864,7 +869,7 @@ class boss_kaelthas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -969,7 +974,7 @@ class boss_thaladred_the_darkener : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1033,7 +1038,7 @@ class boss_lord_sanguinar : public CreatureScript }; CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1119,7 +1124,7 @@ class boss_grand_astromancer_capernian : public CreatureScript //Conflagration_Timer if (Conflagration_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target && me->IsWithinDistInMap(target, 30)) @@ -1136,8 +1141,8 @@ class boss_grand_astromancer_capernian : public CreatureScript if (ArcaneExplosion_Timer <= diff) { bool InMeleeRange = false; - Unit* target = NULL; - ThreatContainer::StorageType const &threatlist = me->getThreatManager().getThreatList(); + Unit* target = nullptr; + ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator i = threatlist.begin(); i!= threatlist.end(); ++i) { Unit* unit = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid()); @@ -1164,7 +1169,7 @@ class boss_grand_astromancer_capernian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1243,7 +1248,7 @@ class boss_master_engineer_telonicus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1313,7 +1318,7 @@ class npc_kael_flamestrike : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_kael_flamestrikeAI(creature); + return GetTheEyeAI(creature); } }; @@ -1372,7 +1377,7 @@ class npc_phoenix_tk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_phoenix_tkAI(creature); + return GetTheEyeAI(creature); } }; @@ -1438,7 +1443,7 @@ class npc_phoenix_egg_tk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_phoenix_egg_tkAI(creature); + return GetTheEyeAI(creature); } }; @@ -1460,11 +1465,7 @@ class spell_kael_gravity_lapse : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint8 i = 0; i < 25; ++i) - if (!sSpellMgr->GetSpellInfo(GravityLapseSpells[i])) - return false; - - return true; + return ValidateSpellInfo(GravityLapseSpells); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp index c111756aa5c..962228a215a 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "the_eye.h" @@ -110,7 +111,7 @@ class boss_void_reaver : public CreatureScript break; case EVENT_ARCANE_ORB: { - Unit* target = NULL; + Unit* target = nullptr; std::list t_list = me->getThreatManager().getThreatList(); std::vector target_list; for (std::list::const_iterator itr = t_list.begin(); itr != t_list.end(); ++itr) @@ -121,7 +122,7 @@ class boss_void_reaver : public CreatureScript // exclude pets & totems, 18 yard radius minimum if (target->GetTypeId() == TYPEID_PLAYER && target->IsAlive() && !target->IsWithinDist(me, 18, false)) target_list.push_back(target); - target = NULL; + target = nullptr; } if (!target_list.empty()) @@ -130,7 +131,7 @@ class boss_void_reaver : public CreatureScript target = me->GetVictim(); if (target) - me->CastSpell(target, SPELL_ARCANE_ORB, false, NULL, NULL); + me->CastSpell(target, SPELL_ARCANE_ORB, false, nullptr, nullptr); events.ScheduleEvent(EVENT_ARCANE_ORB, 3000); break; @@ -167,7 +168,7 @@ class boss_void_reaver : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp b/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp index 0d279c928f0..71471909f6b 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp @@ -24,7 +24,9 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "the_eye.h" /* The Eye encounters: @@ -52,7 +54,7 @@ ObjectData const gameObjectData[] = class instance_the_eye : public InstanceMapScript { public: - instance_the_eye() : InstanceMapScript("instance_the_eye", 550) { } + instance_the_eye() : InstanceMapScript(TheEyeScriptName, 550) { } struct instance_the_eye_InstanceMapScript : public InstanceScript { @@ -106,13 +108,13 @@ class instance_the_eye : public InstanceMapScript { switch (identifier) { - case DATA_THALADREDTHEDARKENER: return ThaladredTheDarkener; - case DATA_LORDSANGUINAR: return LordSanguinar; - case DATA_GRANDASTROMANCERCAPERNIAN: return GrandAstromancerCapernian; - case DATA_MASTERENGINEERTELONICUS: return MasterEngineerTelonicus; - case DATA_KAELTHAS: return Kaelthas; - case DATA_HIGH_ASTROMANCER_SOLARIAN: return Astromancer; - case DATA_ALAR: return Alar; + case DATA_THALADREDTHEDARKENER: return ThaladredTheDarkener; + case DATA_LORDSANGUINAR: return LordSanguinar; + case DATA_GRANDASTROMANCERCAPERNIAN: return GrandAstromancerCapernian; + case DATA_MASTERENGINEERTELONICUS: return MasterEngineerTelonicus; + case DATA_KAELTHAS: return Kaelthas; + case DATA_HIGH_ASTROMANCER_SOLARIAN: return Astromancer; + case DATA_ALAR: return Alar; } return ObjectGuid::Empty; } diff --git a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp index feabaf8e701..1cbb522552c 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp @@ -110,7 +110,7 @@ class npc_crystalcore_devastator : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_crystalcore_devastatorAI(creature); + return GetTheEyeAI(creature); } }; void AddSC_the_eye() diff --git a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h index 1111e2409f5..1ac735f750c 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h +++ b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h @@ -19,6 +19,9 @@ #ifndef DEF_THE_EYE_H #define DEF_THE_EYE_H +#include "CreatureAIImpl.h" + +#define TheEyeScriptName "instance_the_eye" #define DataHeader "TE" uint32 const EncounterCount = 4; @@ -63,4 +66,10 @@ enum TEGameObjectIds GO_ARCANE_DOOR_RIGHT = 184325 }; +template +inline AI* GetTheEyeAI(T* obj) +{ + return GetInstanceAI(obj, TheEyeScriptName); +} + #endif diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp index b10b6276337..6376a0e8175 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp @@ -23,8 +23,8 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mechanar.h" +#include "ScriptedCreature.h" enum Say { @@ -120,7 +120,7 @@ class boss_gatewatcher_gyrokill : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_gatewatcher_gyrokillAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp index 1733d94bc78..0b060d35771 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp @@ -24,8 +24,8 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mechanar.h" +#include "ScriptedCreature.h" enum Says { @@ -127,7 +127,7 @@ class boss_gatewatcher_iron_hand : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_gatewatcher_iron_handAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp index 19036555787..4d804355423 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "mechanar.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Spells { @@ -155,7 +156,7 @@ class boss_mechano_lord_capacitus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_mechano_lord_capacitusAI(creature); + return GetMechanarAI(creature); } }; @@ -170,15 +171,13 @@ class spell_capacitus_polarity_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_STACK)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_STACK)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_POSITIVE_CHARGE, + SPELL_POSITIVE_CHARGE_STACK, + SPELL_NEGATIVE_CHARGE, + SPELL_NEGATIVE_CHARGE_STACK + }); } void HandleTargets(std::list& targetList) @@ -238,9 +237,7 @@ class spell_capacitus_polarity_shift : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POSITIVE_POLARITY) || !sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_POLARITY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_POSITIVE_POLARITY, SPELL_NEGATIVE_POLARITY }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -248,7 +245,7 @@ class spell_capacitus_polarity_shift : public SpellScriptLoader Unit* target = GetHitUnit(); Unit* caster = GetCaster(); - target->CastSpell(target, roll_chance_i(50) ? SPELL_POSITIVE_POLARITY : SPELL_NEGATIVE_POLARITY, true, NULL, NULL, caster->GetGUID()); + target->CastSpell(target, roll_chance_i(50) ? SPELL_POSITIVE_POLARITY : SPELL_NEGATIVE_POLARITY, true, nullptr, nullptr, caster->GetGUID()); } void Register() override diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp index 483cf3284c3..15f70ada7a7 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp @@ -24,8 +24,10 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "mechanar.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Says { @@ -141,7 +143,7 @@ class boss_nethermancer_sepethrea : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_nethermancer_sepethreaAI(creature); + return GetMechanarAI(creature); } }; @@ -229,7 +231,7 @@ class npc_ragin_flames : public CreatureScript }; CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp index 9ddca823d9e..25bbfe0392a 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp @@ -24,8 +24,9 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mechanar.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Says { @@ -163,7 +164,7 @@ class boss_pathaleon_the_calculator : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_pathaleon_the_calculatorAI(creature); + return GetMechanarAI(creature); } }; @@ -243,7 +244,7 @@ class npc_nether_wraith : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_nether_wraithAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp index 47587cf528e..5b5c2beb7dd 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp @@ -18,20 +18,21 @@ #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" #include "mechanar.h" static DoorData const doorData[] = { { GO_DOOR_MOARG_1, DATA_GATEWATCHER_IRON_HAND, DOOR_TYPE_PASSAGE }, { GO_DOOR_MOARG_2, DATA_GATEWATCHER_GYROKILL, DOOR_TYPE_PASSAGE }, - { GO_DOOR_NETHERMANCER, DATA_NETHERMANCER_SEPRETHREA, DOOR_TYPE_ROOM }, - { 0, 0, DOOR_TYPE_ROOM } + { GO_DOOR_NETHERMANCER, DATA_NETHERMANCER_SEPRETHREA, DOOR_TYPE_ROOM }, + { 0, 0, DOOR_TYPE_ROOM } }; class instance_mechanar : public InstanceMapScript { public: - instance_mechanar(): InstanceMapScript("instance_mechanar", 554) { } + instance_mechanar(): InstanceMapScript(MechanarScriptName, 554) { } struct instance_mechanar_InstanceMapScript : public InstanceScript { @@ -42,34 +43,6 @@ class instance_mechanar : public InstanceMapScript LoadDoorData(doorData); } - void OnGameObjectCreate(GameObject* gameObject) override - { - switch (gameObject->GetEntry()) - { - case GO_DOOR_MOARG_1: - case GO_DOOR_MOARG_2: - case GO_DOOR_NETHERMANCER: - AddDoor(gameObject, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* gameObject) override - { - switch (gameObject->GetEntry()) - { - case GO_DOOR_MOARG_1: - case GO_DOOR_MOARG_2: - case GO_DOOR_NETHERMANCER: - AddDoor(gameObject, false); - break; - default: - break; - } - } - bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h b/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h index 35494c745f8..b4edfd9c74e 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h @@ -18,6 +18,9 @@ #ifndef DEF_MECHANAR_H #define DEF_MECHANAR_H +#include "CreatureAIImpl.h" + +#define MechanarScriptName "instance_mechanar" #define DataHeader "MR" uint32 const EncounterCount = 5; @@ -38,4 +41,10 @@ enum MRGameobjectIds GO_DOOR_NETHERMANCER = 184449 }; +template +inline AI* GetMechanarAI(T* obj) +{ + return GetInstanceAI(obj, MechanarScriptName); +} + #endif diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp index 6c469601efc..d571c155dbe 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp @@ -30,8 +30,10 @@ npc_zerekethvoidzone EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" /*##### # npc_millhouse_manastorm @@ -549,7 +551,7 @@ class npc_zerekethvoidzone : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_zerekethvoidzoneAI(creature); + return GetArcatrazAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h index 038dfb16067..2ccf1684860 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h @@ -18,6 +18,8 @@ #ifndef ARCATRAZ_H #define ARCATRAZ_H +#include "CreatureAIImpl.h" + #define ArcatrazScriptName "instance_arcatraz" #define DataHeader "AZ" @@ -62,10 +64,10 @@ enum AZGameObjectIds GO_WARDENS_SHIELD = 184802 // shield 'protecting' mellichar }; -template -AI* GetArcatrazAI(Creature* creature) +template +inline AI* GetArcatrazAI(T* obj) { - return GetInstanceAI(creature, ArcatrazScriptName); + return GetInstanceAI(obj, ArcatrazScriptName); } #endif // ARCATRAZ_H diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp index 52481ac629d..e2235a34c3c 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Say { diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp index 763d0c206cc..564bb6b2d9c 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp @@ -29,8 +29,10 @@ boss_harbinger_skyriss_illusion EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Says { @@ -293,7 +295,7 @@ class boss_harbinger_skyriss_illusion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_harbinger_skyriss_illusionAI(creature); + return GetArcatrazAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp index 4f12a669a6a..561dbaa8c5a 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp @@ -23,8 +23,11 @@ SDCategory: Tempest Keep, The Arcatraz EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Say { diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp index 54693d3776a..bb21b999d5d 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp @@ -118,7 +118,7 @@ class boss_zereketh_the_unbound : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_zereketh_the_unboundAI(creature); + return GetArcatrazAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp index b79274d3b5d..ba5b7b7e0a5 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "arcatraz.h" +#include "Creature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { @@ -64,12 +67,10 @@ class instance_arcatraz : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: - case GO_CONTAINMENT_CORE_SECURITY_FIELD_BETA: - AddDoor(go, true); - break; case GO_STASIS_POD_ALPHA: StasisPodGUIDs[0] = go->GetGUID(); break; @@ -93,19 +94,6 @@ class instance_arcatraz : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: - case GO_CONTAINMENT_CORE_SECURITY_FIELD_BETA: - AddDoor(go, false); - break; - default: - break; - } - } - void SetData(uint32 type, uint32 data) override { switch (type) diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp index ad83bd90e61..48c2d0dadad 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "Map.h" #include "ScriptedCreature.h" -#include "the_botanica.h" #include "SpellScript.h" +#include "the_botanica.h" enum Says { @@ -142,7 +143,7 @@ class boss_commander_sarannis : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_commander_sarannisAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp index 91de750ad81..204a52609b0 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp @@ -24,6 +24,8 @@ SDCategory: Tempest Keep, The Botanica EndScriptData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "the_botanica.h" @@ -210,7 +212,7 @@ class boss_high_botanist_freywinn : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_high_botanist_freywinnAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp index e8283eeb8cb..31241a050dd 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp @@ -223,7 +223,7 @@ class boss_laj : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_lajAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp index 6480b8a2b58..67a27523d99 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp @@ -152,7 +152,7 @@ class boss_thorngrin_the_tender : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_thorngrin_the_tenderAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp index 6980ca054e9..291be813dc1 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp @@ -24,7 +24,10 @@ SDCategory: Tempest Keep, The Botanica EndScriptData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "the_botanica.h" enum Says @@ -94,7 +97,6 @@ class npc_warp_splinter_treant : public CreatureScript void MoveInLineOfSight(Unit* /*who*/) override { } - void UpdateAI(uint32 diff) override { if (!UpdateVictim() || !me->GetVictim()) @@ -107,7 +109,7 @@ class npc_warp_splinter_treant : public CreatureScript { int32 CurrentHP_Treant = (int32)me->GetHealth(); Warp->CastCustomSpell(Warp, SPELL_HEAL_FATHER, &CurrentHP_Treant, 0, 0, true, 0, 0, me->GetGUID()); - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); return; } me->GetMotionMaster()->MoveFollow(Warp, 0, 0); @@ -125,7 +127,7 @@ class npc_warp_splinter_treant : public CreatureScript }; CreatureAI* GetAI(Creature* creature) const override { - return new npc_warp_splinter_treantAI(creature); + return GetBotanicaAI(creature); } }; @@ -239,7 +241,7 @@ class boss_warp_splinter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_warp_splinterAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp b/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp index 3d878bae81e..6e092b743f3 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "the_botanica.h" class instance_the_botanica : public InstanceMapScript { public: - instance_the_botanica() : InstanceMapScript("instance_the_botanica", 553) { } + instance_the_botanica() : InstanceMapScript(BotanicaScriptName, 553) { } struct instance_the_botanica_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h b/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h index fc773d0b133..55a4be28e33 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h +++ b/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h @@ -19,6 +19,9 @@ #ifndef DEF_THE_BOTANICA_H #define DEF_THE_BOTANICA_H +#include "CreatureAIImpl.h" + +#define BotanicaScriptName "instance_the_botanica" #define DataHeader "BC" uint32 const EncounterCount = 5; @@ -41,4 +44,10 @@ enum BCCreatureIds NPC_WARP_SPLINTER = 17977 }; +template +inline AI* GetBotanicaAI(T* obj) +{ + return GetInstanceAI(obj, BotanicaScriptName); +} + #endif diff --git a/src/server/scripts/Outland/boss_doomlord_kazzak.cpp b/src/server/scripts/Outland/boss_doomlord_kazzak.cpp index 4d8ca8ff2be..93ea132a545 100644 --- a/src/server/scripts/Outland/boss_doomlord_kazzak.cpp +++ b/src/server/scripts/Outland/boss_doomlord_kazzak.cpp @@ -187,9 +187,7 @@ class spell_mark_of_kazzak : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_KAZZAK_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_KAZZAK_DAMAGE }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) @@ -204,7 +202,7 @@ class spell_mark_of_kazzak : public SpellScriptLoader if (target->GetPower(POWER_MANA) == 0) { - target->CastSpell(target, SPELL_MARK_OF_KAZZAK_DAMAGE, true, NULL, aurEff); + target->CastSpell(target, SPELL_MARK_OF_KAZZAK_DAMAGE, true, nullptr, aurEff); // Remove aura SetDuration(0); } @@ -234,9 +232,7 @@ class spell_twisted_reflection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TWISTED_REFLECTION_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TWISTED_REFLECTION_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Outland/zone_blades_edge_mountains.cpp b/src/server/scripts/Outland/zone_blades_edge_mountains.cpp index e3e39d0c27e..1bad0a75231 100644 --- a/src/server/scripts/Outland/zone_blades_edge_mountains.cpp +++ b/src/server/scripts/Outland/zone_blades_edge_mountains.cpp @@ -30,17 +30,19 @@ go_legion_obelisk EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CellImpl.h" +#include "CreatureAIImpl.h" #include "GameObjectAI.h" -#include "ScriptedGossip.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" /*###### ## npc_nether_drake @@ -125,7 +127,7 @@ public: me->DespawnOrUnsummon(1); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_T_PHASE_MODULATOR && caster->GetTypeId() == TYPEID_PLAYER) { @@ -842,7 +844,7 @@ class npc_simon_bunny : public CreatureScript } } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { // Cast SPELL_BAD_PRESS_DAMAGE with scaled basepoints when the visual hits the target. // Need Fix: When SPELL_BAD_PRESS_TRIGGER hits target it triggers spell SPELL_BAD_PRESS_DAMAGE by itself @@ -850,7 +852,7 @@ class npc_simon_bunny : public CreatureScript if (spell->Id == SPELL_BAD_PRESS_TRIGGER) { int32 bp = (int32)((float)(fails)*0.33f*target->GetMaxHealth()); - target->CastCustomSpell(target, SPELL_BAD_PRESS_DAMAGE, &bp, NULL, NULL, true); + target->CastCustomSpell(target, SPELL_BAD_PRESS_DAMAGE, &bp, nullptr, nullptr, true); } } @@ -987,7 +989,7 @@ public: { // Spell 37392 does not exist in dbc, manually spawning me->SummonCreature(NPC_OSCILLATING_FREQUENCY_SCANNER_TOP_BUNNY, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ() + 0.5f, me->GetOrientation(), TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 50000); - me->SummonGameObject(GO_OSCILLATING_FREQUENCY_SCANNER, *me, G3D::Quat(), 50); + me->SummonGameObject(GO_OSCILLATING_FREQUENCY_SCANNER, *me, QuaternionData(), 50); me->DespawnOrUnsummon(50000); } diff --git a/src/server/scripts/Outland/zone_hellfire_peninsula.cpp b/src/server/scripts/Outland/zone_hellfire_peninsula.cpp index e5bf6b87386..7c80a20aba9 100644 --- a/src/server/scripts/Outland/zone_hellfire_peninsula.cpp +++ b/src/server/scripts/Outland/zone_hellfire_peninsula.cpp @@ -31,10 +31,12 @@ npc_fel_guard_hound EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "WorldSession.h" /*###### diff --git a/src/server/scripts/Outland/zone_nagrand.cpp b/src/server/scripts/Outland/zone_nagrand.cpp index 6908e705a8e..ce71c80e5f0 100644 --- a/src/server/scripts/Outland/zone_nagrand.cpp +++ b/src/server/scripts/Outland/zone_nagrand.cpp @@ -27,13 +27,16 @@ EndScriptData */ npc_maghar_captive npc_creditmarker_visit_with_ancestors EndContentData */ + #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /*###### ## npc_maghar_captive @@ -141,7 +144,7 @@ public: } - void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) override + void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (spell->Id == SPELL_CHAIN_LIGHTNING) { @@ -514,7 +517,7 @@ public: summoned->AI()->AttackStart(me); } - void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) override + void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (spell->Id == SPELL_KUR_CHAIN_LIGHTNING) { diff --git a/src/server/scripts/Outland/zone_netherstorm.cpp b/src/server/scripts/Outland/zone_netherstorm.cpp index 6bb351169a3..8f8fc39a2b3 100644 --- a/src/server/scripts/Outland/zone_netherstorm.cpp +++ b/src/server/scripts/Outland/zone_netherstorm.cpp @@ -31,11 +31,13 @@ go_captain_tyralius_prison EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" /*###### ## npc_commander_dawnforge @@ -316,7 +318,7 @@ class at_commander_dawnforge : public AreaTriggerScript public: at_commander_dawnforge() : AreaTriggerScript("at_commander_dawnforge") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { //if player lost aura or not have at all, we should not try start event. if (!player->HasAura(SPELL_SUNFURY_DISGUISE)) @@ -407,7 +409,7 @@ public: PlayerGUID = who->GetGUID(); } - //void SpellHit(Unit* /*caster*/, const SpellInfo* /*spell*/) override + //void SpellHit(Unit* /*caster*/, SpellInfo const* /*spell*/) override //{ // DoCast(me, SPELL_DE_MATERIALIZE); //} @@ -612,7 +614,7 @@ public: // take the GO -> animation me->HandleEmoteCommand(EMOTE_STATE_LOOT); SetEscortPaused(true); - bTake=true; + bTake = true; } break; case 36: //return and quest_complete @@ -639,7 +641,7 @@ public: if (GameObject* go = GetClosestGameObjectWithEntry(me, GO_DRAENEI_MACHINE, INTERACTION_DISTANCE)) { SetEscortPaused(false); - bTake=false; + bTake = false; uiTakeTimer = 3000; go->Delete(); } diff --git a/src/server/scripts/Outland/zone_shadowmoon_valley.cpp b/src/server/scripts/Outland/zone_shadowmoon_valley.cpp index 9ab9b9b4eb3..9e89c34fe72 100644 --- a/src/server/scripts/Outland/zone_shadowmoon_valley.cpp +++ b/src/server/scripts/Outland/zone_shadowmoon_valley.cpp @@ -37,14 +37,17 @@ npc_enraged_spirit EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "Group.h" -#include "SpellScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "WorldSession.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" /*##### # npc_invis_infernal_caster @@ -75,7 +78,8 @@ public: void Reset() override { - ground = me->GetMap()->GetHeight(me->GetPositionX(), me->GetPositionY(), me->GetPositionZMinusOffset()); + ground = me->GetPositionZ(); + me->UpdateGroundPositionZ(me->GetPositionX(), me->GetPositionY(), ground); SummonInfernal(); events.ScheduleEvent(EVENT_CAST_SUMMON_INFERNAL, urand(1000, 3000)); } @@ -159,7 +163,7 @@ public: caster->AI()->SetData(TYPE_INFERNAL, DATA_DIED); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_SUMMON_INFERNAL) { @@ -378,7 +382,7 @@ public: me->SetDisableGravity(false); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (!caster) return; @@ -507,7 +511,7 @@ public: Initialize(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (!caster) return; @@ -550,7 +554,7 @@ public: player->KilledMonsterCredit(23209); } PoisonTimer = 0; - me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(me, me->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } else PoisonTimer -= diff; } if (!UpdateVictim()) @@ -1463,8 +1467,8 @@ public: } // Spawn Soul on Kill ALWAYS! - Creature* Summoned = NULL; - Unit* totemOspirits = NULL; + Creature* Summoned = nullptr; + Unit* totemOspirits = nullptr; if (entry != 0) Summoned = DoSpawnCreature(entry, 0, 0, 1, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 5000); @@ -1559,7 +1563,7 @@ public: } } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_WHISTLE) { diff --git a/src/server/scripts/Outland/zone_terokkar_forest.cpp b/src/server/scripts/Outland/zone_terokkar_forest.cpp index e1ef8991aa8..1ccb7950fa0 100644 --- a/src/server/scripts/Outland/zone_terokkar_forest.cpp +++ b/src/server/scripts/Outland/zone_terokkar_forest.cpp @@ -33,12 +33,12 @@ npc_slim EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "GameObjectAI.h" #include "Group.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "WorldSession.h" /*###### @@ -110,7 +110,7 @@ public: { if (Group* group = player->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupie = itr->GetSource(); if (groupie && groupie->IsInMap(player) && diff --git a/src/server/scripts/Outland/zone_zangarmarsh.cpp b/src/server/scripts/Outland/zone_zangarmarsh.cpp index 52263d56879..fabf7290129 100644 --- a/src/server/scripts/Outland/zone_zangarmarsh.cpp +++ b/src/server/scripts/Outland/zone_zangarmarsh.cpp @@ -287,13 +287,13 @@ public: { ItemPosCountVec dest; uint32 itemId = 24573; - InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, 1, NULL); + InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, 1, nullptr); if (msg == EQUIP_ERR_OK) { player->StoreNewItem(dest, itemId, true); } else - player->SendEquipError(msg, NULL, NULL, itemId); + player->SendEquipError(msg, nullptr, nullptr, itemId); } SendGossipMenuFor(player, 9231, me->GetGUID()); break; diff --git a/src/server/scripts/Pet/pet_dk.cpp b/src/server/scripts/Pet/pet_dk.cpp index a17b9fd8b59..43bf59857b8 100644 --- a/src/server/scripts/Pet/pet_dk.cpp +++ b/src/server/scripts/Pet/pet_dk.cpp @@ -21,12 +21,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "CombatAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum DeathKnightSpells { diff --git a/src/server/scripts/Pet/pet_generic.cpp b/src/server/scripts/Pet/pet_generic.cpp index 3f08f8273ac..f45afa95901 100644 --- a/src/server/scripts/Pet/pet_generic.cpp +++ b/src/server/scripts/Pet/pet_generic.cpp @@ -28,9 +28,13 @@ EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "DBCStructure.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" enum BabyBlizzardBearMisc { diff --git a/src/server/scripts/Pet/pet_hunter.cpp b/src/server/scripts/Pet/pet_hunter.cpp index d7acbed9ab5..b68511ea7f5 100644 --- a/src/server/scripts/Pet/pet_hunter.cpp +++ b/src/server/scripts/Pet/pet_hunter.cpp @@ -21,9 +21,11 @@ */ #include "ScriptMgr.h" +#include "CreatureAIImpl.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" +#include "TemporarySummon.h" enum HunterSpells { @@ -168,10 +170,11 @@ class spell_pet_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PET_SWOOP) || - !sSpellMgr->GetSpellInfo(SPELL_PET_CHARGE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PET_SWOOP, + SPELL_PET_CHARGE + }); } void HandleDummy(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -214,9 +217,7 @@ class spell_pet_guard_dog : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PET_GUARD_DOG_HAPPINESS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PET_GUARD_DOG_HAPPINESS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -266,9 +267,7 @@ class spell_pet_silverback : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PET_GUARD_DOG_HAPPINESS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PET_GUARD_DOG_HAPPINESS }); } bool CheckProc(ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Pet/pet_mage.cpp b/src/server/scripts/Pet/pet_mage.cpp index fa2e65f7104..b782f550c3b 100644 --- a/src/server/scripts/Pet/pet_mage.cpp +++ b/src/server/scripts/Pet/pet_mage.cpp @@ -21,14 +21,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CellImpl.h" #include "CombatAI.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" #include "Pet.h" #include "PetAI.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "ScriptedCreature.h" enum MageSpells { diff --git a/src/server/scripts/ScriptPCH.cpp b/src/server/scripts/ScriptPCH.cpp index 41fecf3c60d..25425276d24 100644 --- a/src/server/scripts/ScriptPCH.cpp +++ b/src/server/scripts/ScriptPCH.cpp @@ -1,6 +1,19 @@ -/* Copyright (C) 2006 - 2009 ScriptDev2 -* This program is free software licensed under GPL version 2 -* Please see the included DOCS/LICENSE.TXT for more information */ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ #include "ScriptPCH.h" - diff --git a/src/server/scripts/ScriptPCH.h b/src/server/scripts/ScriptPCH.h index 1cd25309055..6754b485875 100644 --- a/src/server/scripts/ScriptPCH.h +++ b/src/server/scripts/ScriptPCH.h @@ -1,9 +1,20 @@ -/* Copyright (C) 2006 - 2009 ScriptDev2 -* This program is free software licensed under GPL version 2 -* Please see the included DOCS/LICENSE.TXT for more information */ - -#ifndef SC_PRECOMPILED_H -#define SC_PRECOMPILED_H +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ #include "ScriptMgr.h" #include "Cell.h" @@ -24,10 +35,3 @@ #include "ObjectMgr.h" #include "SpellScript.h" #include "SpellAuraEffects.h" - -#ifdef _WIN32 -#include -#endif - -#endif - diff --git a/src/server/scripts/Spells/spell_dk.cpp b/src/server/scripts/Spells/spell_dk.cpp index a55dbd765a0..bd2e36bc30f 100644 --- a/src/server/scripts/Spells/spell_dk.cpp +++ b/src/server/scripts/Spells/spell_dk.cpp @@ -21,12 +21,20 @@ * Scriptnames of files in this file should be prefixed with "spell_dk_". */ +#include "ScriptMgr.h" +#include "Containers.h" +#include "DBCStores.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" #include "PlayerAI.h" -#include "ScriptMgr.h" -#include "SpellScript.h" +#include "Spell.h" #include "SpellAuraEffects.h" -#include "Containers.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum DeathKnightSpells { @@ -117,14 +125,15 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_HOLY) || - !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_FIRE) || - !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_FROST) || - !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_NATURE) || - !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_SHADOW) || - !sSpellMgr->GetSpellInfo(SPELL_DK_ACCLIMATION_ARCANE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_ACCLIMATION_HOLY, + SPELL_DK_ACCLIMATION_FIRE, + SPELL_DK_ACCLIMATION_NATURE, + SPELL_DK_ACCLIMATION_FROST, + SPELL_DK_ACCLIMATION_SHADOW, + SPELL_DK_ACCLIMATION_ARCANE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -206,9 +215,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_ADVANTAGE_T10_4P_MELEE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_ADVANTAGE_T10_4P_MELEE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -317,9 +324,7 @@ class spell_dk_anti_magic_shell_self : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_RUNIC_POWER_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_RUNIC_POWER_ENERGIZE }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/) @@ -337,7 +342,7 @@ class spell_dk_anti_magic_shell_self : public SpellScriptLoader // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power. // This, if I'm not mistaken, shows that we get back ~20% of the absorbed damage as runic power. int32 bp = CalculatePct(absorbAmount, 20); - GetTarget()->CastCustomSpell(SPELL_DK_RUNIC_POWER_ENERGIZE, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DK_RUNIC_POWER_ENERGIZE, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, nullptr, aurEff); } void Register() override @@ -381,9 +386,7 @@ class spell_dk_anti_magic_zone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_ANTI_MAGIC_SHELL_TALENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_ANTI_MAGIC_SHELL_TALENT }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/) @@ -463,9 +466,7 @@ class spell_dk_blood_boil : public SpellScriptLoader private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_BOIL_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_BLOOD_BOIL_TRIGGERED }); } bool Load() override @@ -506,18 +507,9 @@ class spell_dk_blood_gorged : public SpellScriptLoader { PrepareAuraScript(spell_dk_blood_gorged_AuraScript); - public: - spell_dk_blood_gorged_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_GORGED_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_BLOOD_GORGED_HEAL }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -544,7 +536,7 @@ class spell_dk_blood_gorged : public SpellScriptLoader } private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -592,9 +584,7 @@ class spell_dk_butchery : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BUTCHERY_RUNIC_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_BUTCHERY_RUNIC_POWER }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -649,27 +639,21 @@ class spell_dk_corpse_explosion : public SpellScriptLoader { PrepareSpellScript(spell_dk_corpse_explosion_SpellScript); - public: - spell_dk_corpse_explosion_SpellScript() - { - _target = nullptr; - } - - private: bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_CORPSE_EXPLOSION_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_GHOUL_EXPLODE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_CORPSE_EXPLOSION_VISUAL) - || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].CalcValue())) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_CORPSE_EXPLOSION_TRIGGERED, + SPELL_DK_GHOUL_EXPLODE, + SPELL_DK_CORPSE_EXPLOSION_VISUAL, + static_cast(spellInfo->Effects[EFFECT_1].CalcValue()) + }); } void CheckTarget(WorldObject*& target) { if (CorpseExplosionCheck(GetCaster()->GetGUID(), true)(target)) - target = NULL; + target = nullptr; _target = target; } @@ -698,7 +682,7 @@ class spell_dk_corpse_explosion : public SpellScriptLoader if (effIndex == EFFECT_0) GetCaster()->CastCustomSpell(GetSpellInfo()->Effects[EFFECT_1].CalcValue(), SPELLVALUE_BASE_POINT0, GetEffectValue(), target, true); else if (effIndex == EFFECT_1) - GetCaster()->CastCustomSpell(GetEffectValue(), SPELLVALUE_BASE_POINT0, GetSpell()->CalculateDamage(EFFECT_0, NULL), target, true); + GetCaster()->CastCustomSpell(GetEffectValue(), SPELLVALUE_BASE_POINT0, GetSpell()->CalculateDamage(EFFECT_0, nullptr), target, true); } void HandleCorpseExplosion(SpellEffIndex effIndex) @@ -729,8 +713,7 @@ class spell_dk_corpse_explosion : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_dk_corpse_explosion_SpellScript::HandleCorpseExplosion, EFFECT_1, SPELL_EFFECT_DUMMY); } - private: - WorldObject* _target; + WorldObject* _target = nullptr; }; SpellScript* GetSpellScript() const override @@ -814,7 +797,7 @@ class spell_dk_death_and_decay : public SpellScriptLoader void HandleDummyTick(AuraEffect const* aurEff) { if (Unit* caster = GetCaster()) - caster->CastCustomSpell(SPELL_DK_DEATH_AND_DECAY_DAMAGE, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff); + caster->CastCustomSpell(SPELL_DK_DEATH_AND_DECAY_DAMAGE, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff); } void Register() override @@ -841,9 +824,7 @@ class spell_dk_death_coil : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_COIL_DAMAGE) || !sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_COIL_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_DEATH_COIL_DAMAGE, SPELL_DK_DEATH_COIL_HEAL }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -855,13 +836,13 @@ class spell_dk_death_coil : public SpellScriptLoader if (caster->IsFriendlyTo(target)) { int32 bp = int32(damage * 1.5f); - caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_HEAL, &bp, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_HEAL, &bp, nullptr, nullptr, true); } else { if (AuraEffect const* auraEffect = caster->GetAuraEffect(SPELL_DK_ITEM_SIGIL_VENGEFUL_HEART, EFFECT_1)) damage += auraEffect->GetBaseAmount(); - caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_DAMAGE, &damage, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_DAMAGE, &damage, nullptr, nullptr, true); } } } @@ -998,7 +979,7 @@ class spell_dk_death_pact : public SpellScriptLoader void FilterTargets(std::list& targetList) { - Unit* target = NULL; + Unit* target = nullptr; for (std::list::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) @@ -1117,9 +1098,7 @@ class spell_dk_death_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_STRIKE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_DEATH_STRIKE_HEAL }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1132,7 +1111,7 @@ class spell_dk_death_strike : public SpellScriptLoader // Improved Death Strike if (AuraEffect const* aurEff = caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, DK_ICON_ID_IMPROVED_DEATH_STRIKE, 0)) AddPct(bp, caster->CalculateSpellDamage(caster, aurEff->GetSpellInfo(), 2)); - caster->CastCustomSpell(caster, SPELL_DK_DEATH_STRIKE_HEAL, &bp, NULL, NULL, false); + caster->CastCustomSpell(caster, SPELL_DK_DEATH_STRIKE_HEAL, &bp, nullptr, nullptr, false); } } @@ -1161,10 +1140,8 @@ class spell_dk_ghoul_explode : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_CORPSE_EXPLOSION_TRIGGERED) - || spellInfo->Effects[EFFECT_2].CalcValue() <= 0) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_CORPSE_EXPLOSION_TRIGGERED }) && + spellInfo->Effects[EFFECT_2].CalcValue() > 0; } void HandleDamage(SpellEffIndex /*effIndex*/) @@ -1209,9 +1186,7 @@ class spell_dk_glyph_of_death_grip : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_GRIP_INITIAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_DEATH_GRIP_INITIAL }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -1244,9 +1219,7 @@ class spell_dk_glyph_of_scourge_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_GLYPH_OF_SCOURGE_STRIKE_SCRIPT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_GLYPH_OF_SCOURGE_STRIKE_SCRIPT }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1359,19 +1332,20 @@ class spell_dk_improved_blood_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED + }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if ((target->HasAura(SPELL_DK_FROST_PRESENCE) || target->HasAura(SPELL_DK_UNHOLY_PRESENCE)) && !target->HasAura(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT1, aurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT1, aurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1406,9 +1380,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_BLOOD_PRESENCE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_IMPROVED_BLOOD_PRESENCE_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1452,19 +1424,20 @@ class spell_dk_improved_frost_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_FROST_PRESENCE_TRIGGERED + }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if ((target->HasAura(SPELL_DK_BLOOD_PRESENCE) || target->HasAura(SPELL_DK_UNHOLY_PRESENCE)) && !target->HasAura(SPELL_DK_FROST_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_FROST_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_FROST_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1499,13 +1472,14 @@ class spell_dk_improved_unholy_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, + SPELL_DK_UNHOLY_PRESENCE_TRIGGERED + }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1515,11 +1489,11 @@ class spell_dk_improved_unholy_presence : public SpellScriptLoader { // Not listed as any effect, only base points set in dbc int32 basePoints = GetSpellInfo()->Effects[EFFECT_1].CalcValue(); - target->CastCustomSpell(target, SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, &basePoints, &basePoints, &basePoints, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, &basePoints, &basePoints, &basePoints, true, nullptr, aurEff); } if ((target->HasAura(SPELL_DK_BLOOD_PRESENCE) || target->HasAura(SPELL_DK_FROST_PRESENCE)) && !target->HasAura(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1557,9 +1531,7 @@ class spell_dk_pvp_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_RUNIC_RETURN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_RUNIC_RETURN }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1602,9 +1574,7 @@ class spell_dk_mark_of_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_MARK_OF_BLOOD_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_MARK_OF_BLOOD_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1637,9 +1607,7 @@ class spell_dk_necrosis : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_NECROSIS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_NECROSIS_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1678,11 +1646,12 @@ class spell_dk_pestilence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_GLYPH_OF_DISEASE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PLAGUE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_FEVER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_GLYPH_OF_DISEASE, + SPELL_DK_BLOOD_PLAGUE, + SPELL_DK_FROST_FEVER + }); } void OnHit(SpellEffIndex /*effIndex*/) @@ -1765,19 +1734,19 @@ class spell_dk_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_BLOOD_PRESENCE_R1) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_FROST_PRESENCE_R1) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_R1) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED)) - return false; - - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_IMPROVED_BLOOD_PRESENCE_R1, + SPELL_DK_IMPROVED_FROST_PRESENCE_R1, + SPELL_DK_IMPROVED_UNHOLY_PRESENCE_R1, + SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED, + SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, + SPELL_DK_FROST_PRESENCE_TRIGGERED, + SPELL_DK_UNHOLY_PRESENCE_TRIGGERED + }); } void HandleImprovedBloodPresence(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1788,7 +1757,7 @@ class spell_dk_presence : public SpellScriptLoader target->CastSpell(target, SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED, true); else if (AuraEffect const* impAurEff = target->GetAuraEffectOfRankedSpell(SPELL_DK_IMPROVED_BLOOD_PRESENCE_R1, EFFECT_0)) if (!target->HasAura(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT1, impAurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_IMPROVED_BLOOD_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT1, impAurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleImprovedFrostPresence(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1799,7 +1768,7 @@ class spell_dk_presence : public SpellScriptLoader target->CastSpell(target, SPELL_DK_FROST_PRESENCE_TRIGGERED, true); else if (AuraEffect const* impAurEff = target->GetAuraEffectOfRankedSpell(SPELL_DK_IMPROVED_FROST_PRESENCE_R1, EFFECT_0)) if (!target->HasAura(SPELL_DK_FROST_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_FROST_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, impAurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_FROST_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, impAurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleImprovedUnholyPresence(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1815,10 +1784,10 @@ class spell_dk_presence : public SpellScriptLoader { // Not listed as any effect, only base points set int32 bp = impAurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue(); - target->CastCustomSpell(target, SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, &bp, &bp, &bp, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, &bp, &bp, &bp, true, nullptr, aurEff); } else if (!target->HasAura(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, impAurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, impAurEff->GetAmount(), target, true, nullptr, aurEff); } } @@ -1879,22 +1848,15 @@ class spell_dk_raise_dead : public SpellScriptLoader { PrepareSpellScript(spell_dk_raise_dead_SpellScript); - public: - spell_dk_raise_dead_SpellScript() - { - _result = SPELL_CAST_OK; - _corpse = false; - } - - private: bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].CalcValue()) - || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_2].CalcValue()) - || !sSpellMgr->GetSpellInfo(SPELL_DK_RAISE_DEAD_USE_REAGENT) - || !sSpellMgr->GetSpellInfo(SPELL_DK_MASTER_OF_GHOULS)) - return false; - return true; + return ValidateSpellInfo( + { + static_cast(spellInfo->Effects[EFFECT_1].CalcValue()), + static_cast(spellInfo->Effects[EFFECT_2].CalcValue()), + SPELL_DK_RAISE_DEAD_USE_REAGENT, + SPELL_DK_MASTER_OF_GHOULS + }); } bool Load() override @@ -1957,7 +1919,7 @@ class spell_dk_raise_dead : public SpellScriptLoader { // Don't add caster to target map, if we found a corpse to raise dead if (_corpse) - target = NULL; + target = nullptr; } void ConsumeReagents() @@ -1984,7 +1946,7 @@ class spell_dk_raise_dead : public SpellScriptLoader SpellCastTargets targets; targets.SetDst(*GetHitUnit()); - GetCaster()->CastSpell(targets, spellInfo, NULL, TRIGGERED_FULL_MASK); + GetCaster()->CastSpell(targets, spellInfo, nullptr, TRIGGERED_FULL_MASK); } void OverrideCooldown() @@ -2007,9 +1969,8 @@ class spell_dk_raise_dead : public SpellScriptLoader AfterCast += SpellCastFn(spell_dk_raise_dead_SpellScript::OverrideCooldown); } - private: - SpellCastResult _result; - bool _corpse; + SpellCastResult _result = SPELL_CAST_OK; + bool _corpse = false; }; SpellScript* GetSpellScript() const override @@ -2094,15 +2055,13 @@ class spell_dk_scent_of_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_SCENT_OF_BLOOD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_SCENT_OF_BLOOD }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_DK_SCENT_OF_BLOOD, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_DK_SCENT_OF_BLOOD, true, nullptr, aurEff); ModStackAmount(-1); } @@ -2170,9 +2129,7 @@ class spell_dk_scourge_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_SCOURGE_STRIKE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_SCOURGE_STRIKE_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2197,7 +2154,7 @@ class spell_dk_scourge_strike : public SpellScriptLoader if (AuraEffect* aurEff = caster->GetAuraEffectOfRankedSpell(SPELL_DK_BLACK_ICE_R1, EFFECT_0)) AddPct(bp, aurEff->GetAmount()); - caster->CastCustomSpell(unitTarget, SPELL_DK_SCOURGE_STRIKE_TRIGGERED, &bp, NULL, NULL, true); + caster->CastCustomSpell(unitTarget, SPELL_DK_SCOURGE_STRIKE_TRIGGERED, &bp, nullptr, nullptr, true); } } @@ -2277,9 +2234,7 @@ class spell_dk_sudden_doom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_COIL_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_DEATH_COIL_R1 }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2329,14 +2284,15 @@ class spell_dk_threat_of_thassarian : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_OBLITERATE_OFF_HAND_R1) || - !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_STRIKE_OFF_HAND_R1) || - !sSpellMgr->GetSpellInfo(SPELL_DK_PLAGUE_STRIKE_OFF_HAND_R1) || - !sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_STRIKE_OFF_HAND_R1) || - !sSpellMgr->GetSpellInfo(SPELL_DK_RUNE_STRIKE_OFF_HAND_R1) || - !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_STRIKE_OFF_HAND_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_OBLITERATE_OFF_HAND_R1, + SPELL_DK_FROST_STRIKE_OFF_HAND_R1, + SPELL_DK_PLAGUE_STRIKE_OFF_HAND_R1, + SPELL_DK_DEATH_STRIKE_OFF_HAND_R1, + SPELL_DK_RUNE_STRIKE_OFF_HAND_R1, + SPELL_DK_BLOOD_STRIKE_OFF_HAND_R1 + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2406,10 +2362,11 @@ class spell_dk_unholy_blight : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_BLIGHT_DAMAGE) || - !sSpellMgr->GetSpellInfo(SPELL_DK_GLYPH_OF_UNHOLY_BLIGHT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_UNHOLY_BLIGHT_DAMAGE, + SPELL_DK_GLYPH_OF_UNHOLY_BLIGHT + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2486,9 +2443,7 @@ class spell_dk_vendetta : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_VENDETTA_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_VENDETTA_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2523,9 +2478,7 @@ class spell_dk_wandering_plague : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_WANDERING_PLAGUE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_WANDERING_PLAGUE_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2566,13 +2519,6 @@ class spell_dk_will_of_the_necropolis : public SpellScriptLoader { PrepareAuraScript(spell_dk_will_of_the_necropolis_AuraScript); - public: - spell_dk_will_of_the_necropolis_AuraScript() - { - absorbPct = 0; - } - - private: bool Validate(SpellInfo const* spellInfo) override { SpellInfo const* firstRankSpellInfo = sSpellMgr->GetSpellInfo(SPELL_DK_WILL_OF_THE_NECROPOLIS_AURA_R1); @@ -2590,7 +2536,7 @@ class spell_dk_will_of_the_necropolis : public SpellScriptLoader return true; } - uint32 absorbPct; + uint32 absorbPct = 0; bool Load() override { @@ -2707,9 +2653,7 @@ public: bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_0].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_0].CalcValue()) }); } bool Load() override @@ -2778,11 +2722,12 @@ class player_ghoulAI : public PlayerAI }; // 46619 - Raise Ally -#define DkRaiseAllyScriptName "spell_dk_raise_ally" class spell_dk_raise_ally : public SpellScriptLoader { public: - spell_dk_raise_ally() : SpellScriptLoader(DkRaiseAllyScriptName) { } + static char constexpr const ScriptName[] = "spell_dk_raise_ally"; + + spell_dk_raise_ally() : SpellScriptLoader(ScriptName) { } class spell_dk_raise_ally_SpellScript : public SpellScript { @@ -2825,7 +2770,7 @@ public: Default SUMMON_CATEGORY_PUPPET behaviour sets possesor as originalCaster, in this case we need caster as possesor and originalCaster as owner */ - //summon->RemoveCharmedBy(NULL); + //summon->RemoveCharmedBy(nullptr); summon->SetCharmedBy(caster, CHARM_TYPE_POSSESS); @@ -2849,7 +2794,7 @@ public: void SetGhoul(SpellEffIndex /*effIndex*/) { if (Aura* aura = GetHitAura()) - if (spell_dk_raise_ally_AuraScript* script = dynamic_cast(aura->GetScriptByName(DkRaiseAllyScriptName))) + if (spell_dk_raise_ally_AuraScript* script = aura->GetScript(ScriptName)) script->SetGhoulGuid(_ghoulGuid); } @@ -2874,12 +2819,6 @@ public: PrepareAuraScript(spell_dk_raise_ally_AuraScript); public: - spell_dk_raise_ally_AuraScript() - { - oldAI = nullptr; - oldAIState = false; - } - void SetGhoulGuid(ObjectGuid guid) { ghoulGuid = guid; @@ -2929,8 +2868,8 @@ public: } ObjectGuid ghoulGuid; - PlayerAI* oldAI; - bool oldAIState; + PlayerAI* oldAI = nullptr; + bool oldAIState = false; }; AuraScript* GetAuraScript() const override @@ -2938,6 +2877,7 @@ public: return new spell_dk_raise_ally_AuraScript(); } }; +char constexpr const spell_dk_raise_ally::ScriptName[]; // 47480 - Thrash class spell_dk_ghoul_thrash : public SpellScriptLoader @@ -2951,9 +2891,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GHOUL_FRENZY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GHOUL_FRENZY }); } void CalcDamage() diff --git a/src/server/scripts/Spells/spell_druid.cpp b/src/server/scripts/Spells/spell_druid.cpp index 11a47b025d8..d57bd1e3008 100644 --- a/src/server/scripts/Spells/spell_druid.cpp +++ b/src/server/scripts/Spells/spell_druid.cpp @@ -21,12 +21,14 @@ * Scriptnames of files in this file should be prefixed with "spell_dru_". */ -#include "Player.h" -#include "GameTime.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "Containers.h" +#include "GameTime.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum DruidSpells { @@ -101,9 +103,7 @@ class spell_dru_barkskin : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_BARKSKIN_01)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_BARKSKIN_01 }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -136,10 +136,11 @@ class spell_dru_bear_form_passive : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_ENRAGE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ITEM_T10_FERAL_4P_BONUS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_ENRAGE, + SPELL_DRUID_ITEM_T10_FERAL_4P_BONUS + }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) @@ -215,11 +216,11 @@ class spell_dru_eclipse : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_ECLIPSE_LUNAR_PROC)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_ECLIPSE_SOLAR_PROC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_ECLIPSE_LUNAR_PROC, + SPELL_DRUID_ECLIPSE_SOLAR_PROC + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -301,12 +302,13 @@ class spell_dru_enrage : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_KING_OF_THE_JUNGLE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ENRAGE_MOD_DAMAGE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ENRAGED_DEFENSE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ITEM_T10_FERAL_4P_BONUS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_KING_OF_THE_JUNGLE, + SPELL_DRUID_ENRAGE_MOD_DAMAGE, + SPELL_DRUID_ENRAGED_DEFENSE, + SPELL_DRUID_ITEM_T10_FERAL_4P_BONUS + }); } void RecalculateBaseArmor() @@ -370,13 +372,14 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_BEAR) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_CAT) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_MOONKIN) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_NONE) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_FORMS_TRINKET_TREE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_FORMS_TRINKET_BEAR, + SPELL_DRUID_FORMS_TRINKET_CAT, + SPELL_DRUID_FORMS_TRINKET_MOONKIN, + SPELL_DRUID_FORMS_TRINKET_NONE, + SPELL_DRUID_FORMS_TRINKET_TREE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -486,9 +489,7 @@ class spell_dru_glyph_of_barkskin : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_BARKSKIN_01)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_BARKSKIN_01 }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -521,9 +522,7 @@ class spell_dru_glyph_of_innervate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_INNERVATE_REGEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_GLYPH_OF_INNERVATE_REGEN }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -562,9 +561,7 @@ class spell_dru_glyph_of_rake : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_RAKE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_GLYPH_OF_RAKE_TRIGGERED }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -603,9 +600,7 @@ class spell_dru_glyph_of_rejuvenation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_REJUVENATION_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_GLYPH_OF_REJUVENATION_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -649,10 +644,11 @@ class spell_dru_glyph_of_shred : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_RIP) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_RIP_DURATION_LACERATE_DMG)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_GLYPH_OF_RIP, + SPELL_DRUID_RIP_DURATION_LACERATE_DMG + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -708,9 +704,7 @@ class spell_dru_glyph_of_starfire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_INCREASED_MOONFIRE_DURATION) || !sSpellMgr->GetSpellInfo(SPELL_DRUID_NATURES_SPLENDOR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_INCREASED_MOONFIRE_DURATION, SPELL_DRUID_NATURES_SPLENDOR }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -762,9 +756,7 @@ class spell_dru_glyph_of_starfire_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_STARFIRE_SCRIPT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_GLYPH_OF_STARFIRE_SCRIPT }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -892,11 +884,12 @@ class spell_dru_leader_of_the_pack : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_IMP_LEADER_OF_THE_PACK_R1) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_IMP_LEADER_OF_THE_PACK_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_IMP_LEADER_OF_THE_PACK_MANA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_IMP_LEADER_OF_THE_PACK_R1, + SPELL_DRUID_IMP_LEADER_OF_THE_PACK_HEAL, + SPELL_DRUID_IMP_LEADER_OF_THE_PACK_MANA + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -951,11 +944,11 @@ class spell_dru_lifebloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIFEBLOOM_FINAL_HEAL)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIFEBLOOM_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, + SPELL_DRUID_LIFEBLOOM_ENERGIZE + }); } void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -972,15 +965,15 @@ class spell_dru_lifebloom : public SpellScriptLoader healAmount = caster->SpellHealingBonusDone(GetTarget(), GetSpellInfo(), healAmount, HEAL, stack); healAmount = GetTarget()->SpellHealingBonusTaken(caster, GetSpellInfo(), healAmount, HEAL, stack); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); // restore mana int32 returnMana = CalculatePct(caster->GetCreateMana(), GetSpellInfo()->ManaCostPercentage) * stack / 2; - caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); return; } - GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); } void HandleDispel(DispelInfo* dispelInfo) @@ -995,15 +988,15 @@ class spell_dru_lifebloom : public SpellScriptLoader { healAmount = caster->SpellHealingBonusDone(target, GetSpellInfo(), healAmount, HEAL, dispelInfo->GetRemovedCharges()); healAmount = target->SpellHealingBonusTaken(caster, GetSpellInfo(), healAmount, HEAL, dispelInfo->GetRemovedCharges()); - target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, NULL, GetCasterGUID()); + target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, nullptr, GetCasterGUID()); // restore mana int32 returnMana = CalculatePct(caster->GetCreateMana(), GetSpellInfo()->ManaCostPercentage) * dispelInfo->GetRemovedCharges() / 2; - caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, NULL, NULL, true, NULL, NULL, GetCasterGUID()); + caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, nullptr, nullptr, true, nullptr, nullptr, GetCasterGUID()); return; } - target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, NULL, GetCasterGUID()); + target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, nullptr, GetCasterGUID()); } } } @@ -1033,9 +1026,7 @@ class spell_dru_living_seed : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIVING_SEED_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_LIVING_SEED_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1074,15 +1065,13 @@ class spell_dru_living_seed_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIVING_SEED_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_LIVING_SEED_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastCustomSpell(SPELL_DRUID_LIVING_SEED_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DRUID_LIVING_SEED_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff); } void Register() override @@ -1160,10 +1149,11 @@ class spell_dru_omen_of_clarity : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_BALANCE_T10_BONUS) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_BALANCE_T10_BONUS_PROC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_BALANCE_T10_BONUS, + SPELL_DRUID_BALANCE_T10_BONUS_PROC + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -1304,12 +1294,13 @@ class spell_dru_revitalize : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_REVITALIZE_ENERGIZE_MANA) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_REVITALIZE_ENERGIZE_RAGE) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_REVITALIZE_ENERGIZE_ENERGY) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_REVITALIZE_ENERGIZE_RP)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_REVITALIZE_ENERGIZE_MANA, + SPELL_DRUID_REVITALIZE_ENERGIZE_RAGE, + SPELL_DRUID_REVITALIZE_ENERGIZE_ENERGY, + SPELL_DRUID_REVITALIZE_ENERGIZE_RP + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1414,9 +1405,7 @@ class spell_dru_savage_defense : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1470,15 +1459,13 @@ class spell_dru_savage_roar : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_SAVAGE_ROAR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_SAVAGE_ROAR }); } void AfterApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); - target->CastSpell(target, SPELL_DRUID_SAVAGE_ROAR, true, NULL, aurEff, GetCasterGUID()); + target->CastSpell(target, SPELL_DRUID_SAVAGE_ROAR, true, nullptr, aurEff, GetCasterGUID()); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1608,9 +1595,7 @@ class spell_dru_survival_instincts : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_SURVIVAL_INSTINCTS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_SURVIVAL_INSTINCTS }); } void AfterApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1746,11 +1731,12 @@ class spell_dru_t3_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_T3_PROC_ENERGIZE_MANA) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_T3_PROC_ENERGIZE_RAGE) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_T3_PROC_ENERGIZE_ENERGY)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_T3_PROC_ENERGIZE_MANA, + SPELL_DRUID_T3_PROC_ENERGIZE_RAGE, + SPELL_DRUID_T3_PROC_ENERGIZE_ENERGY + }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -1809,9 +1795,7 @@ class spell_dru_t3_6p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_BLESSING_OF_THE_CLAW)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_BLESSING_OF_THE_CLAW }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1844,9 +1828,7 @@ class spell_dru_t3_8p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_EXHILARATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_EXHILARATE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1886,9 +1868,7 @@ class spell_dru_t4_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_INFUSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_INFUSION }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1921,11 +1901,11 @@ class spell_dru_item_t6_trinket : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_BLESSING_OF_REMULOS) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_BLESSING_OF_ELUNE) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_BLESSING_OF_CENARIUS)) - return false; - return true; + return ValidateSpellInfo({ + SPELL_DRUID_BLESSING_OF_REMULOS, + SPELL_DRUID_BLESSING_OF_ELUNE, + SPELL_DRUID_BLESSING_OF_CENARIUS + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1987,10 +1967,11 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_T9_FERAL_RELIC_BEAR) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_T9_FERAL_RELIC_CAT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_T9_FERAL_RELIC_BEAR, + SPELL_DRUID_T9_FERAL_RELIC_CAT + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2058,9 +2039,7 @@ class spell_dru_t10_balance_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LANGUISH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_LANGUISH }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2162,9 +2141,7 @@ class spell_dru_t10_restoration_4p_bonus_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_REJUVENATION_T10_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_REJUVENATION_T10_PROC }); } bool CheckProc(ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_generic.cpp b/src/server/scripts/Spells/spell_generic.cpp index 3e9184acc94..cbec8270e18 100644 --- a/src/server/scripts/Spells/spell_generic.cpp +++ b/src/server/scripts/Spells/spell_generic.cpp @@ -23,21 +23,23 @@ */ #include "ScriptMgr.h" -#include "GameTime.h" #include "Battleground.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" +#include "DBCStores.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceScript.h" +#include "Item.h" #include "LFGMgr.h" +#include "Log.h" #include "Pet.h" #include "ReputationMgr.h" #include "SkillDiscovery.h" +#include "SpellAuraEffects.h" #include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "Vehicle.h" class spell_gen_absorb0_hitlimit1 : public SpellScriptLoader @@ -49,14 +51,7 @@ class spell_gen_absorb0_hitlimit1 : public SpellScriptLoader { PrepareAuraScript(spell_gen_absorb0_hitlimit1_AuraScript); - public: - spell_gen_absorb0_hitlimit1_AuraScript() - { - limit = 0; - } - - private: - uint32 limit; + uint32 limit = 0; bool Load() override { @@ -103,13 +98,14 @@ class spell_gen_adaptive_warding : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_FIRE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_NATURE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_FROST) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_SHADOW) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_ARCANE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_GEN_ADAPTIVE_WARDING_FIRE, + SPELL_GEN_ADAPTIVE_WARDING_NATURE, + SPELL_GEN_ADAPTIVE_WARDING_FROST, + SPELL_GEN_ADAPTIVE_WARDING_SHADOW, + SPELL_GEN_ADAPTIVE_WARDING_ARCANE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -219,9 +215,7 @@ class spell_gen_animal_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SPAWN_BLOOD_POOL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SPAWN_BLOOD_POOL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -301,9 +295,7 @@ class spell_gen_aura_service_uniform : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SERVICE_UNIFORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SERVICE_UNIFORM }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -398,9 +390,7 @@ class spell_gen_bandage : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RECENTLY_BANDAGED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RECENTLY_BANDAGED }); } SpellCastResult CheckCast() @@ -450,9 +440,7 @@ class spell_gen_blood_reserve : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_BLOOD_RESERVE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GEN_BLOOD_RESERVE_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -563,10 +551,8 @@ class spell_gen_bonked : public SpellScriptLoader target->RemoveAurasDueToSpell(SPELL_BONKED); if (Aura const* auraOnGuard = target->GetAura(SPELL_ON_GUARD)) - { if (Item* item = target->GetItemByGuid(auraOnGuard->GetCastItemGUID())) target->DestroyItemCount(item->GetEntry(), 1, true); - } } } @@ -618,7 +604,7 @@ enum BreakShieldSpells class spell_gen_break_shield: public SpellScriptLoader { public: - spell_gen_break_shield(const char* name) : SpellScriptLoader(name) { } + spell_gen_break_shield(char const* name) : SpellScriptLoader(name) { } class spell_gen_break_shield_SpellScript : public SpellScript { @@ -731,9 +717,7 @@ class spell_gen_burning_depths_necrolyte_image : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_2].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_2].CalcValue()) }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -776,16 +760,14 @@ class spell_gen_cannibalize : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CANNIBALIZE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CANNIBALIZE_TRIGGERED }); } SpellCastResult CheckIfCorpseNear() { Unit* caster = GetCaster(); float max_range = GetSpellInfo()->GetMaxRange(false); - WorldObject* result = NULL; + WorldObject* result = nullptr; // search for nearby enemy corpse in range Trinity::AnyDeadUnitSpellTargetInRangeCheck check(caster, max_range, GetSpellInfo(), TARGET_CHECK_ENEMY); Trinity::WorldObjectSearcher searcher(caster, result, check); @@ -831,16 +813,14 @@ class spell_gen_chaos_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHAOS_BLAST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHAOS_BLAST }); } void HandleDummy(SpellEffIndex /* effIndex */) { int32 basepoints0 = 100; Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) - caster->CastCustomSpell(target, SPELL_CHAOS_BLAST, &basepoints0, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_CHAOS_BLAST, &basepoints0, nullptr, nullptr, true); } void Register() override @@ -931,23 +911,17 @@ class spell_gen_clone_weapon_aura : public SpellScriptLoader { PrepareAuraScript(spell_gen_clone_weapon_auraScript); - public: - spell_gen_clone_weapon_auraScript() - { - prevItem = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_2_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_3_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_2_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_RANGED_AURA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_COPY_WEAPON_AURA, + SPELL_COPY_WEAPON_2_AURA, + SPELL_COPY_WEAPON_3_AURA, + SPELL_COPY_OFFHAND_AURA, + SPELL_COPY_OFFHAND_2_AURA, + SPELL_COPY_RANGED_AURA + }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1035,8 +1009,7 @@ class spell_gen_clone_weapon_aura : public SpellScriptLoader OnEffectRemove += AuraEffectRemoveFn(spell_gen_clone_weapon_auraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } - private: - uint32 prevItem; + uint32 prevItem = 0; }; AuraScript* GetAuraScript() const override @@ -1101,10 +1074,11 @@ class spell_gen_create_lance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_LANCE_ALLIANCE) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_LANCE_HORDE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CREATE_LANCE_ALLIANCE, + SPELL_CREATE_LANCE_HORDE + }); } void HandleScript(SpellEffIndex effIndex) @@ -1185,7 +1159,7 @@ enum DalaranDisguiseSpells class spell_gen_dalaran_disguise : public SpellScriptLoader { public: - spell_gen_dalaran_disguise(const char* name) : SpellScriptLoader(name) { } + spell_gen_dalaran_disguise(char const* name) : SpellScriptLoader(name) { } class spell_gen_dalaran_disguise_SpellScript : public SpellScript { @@ -1196,17 +1170,22 @@ class spell_gen_dalaran_disguise : public SpellScriptLoader switch (spellInfo->Id) { case SPELL_SUNREAVER_DISGUISE_TRIGGER: - if (!sSpellMgr->GetSpellInfo(SPELL_SUNREAVER_DISGUISE_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_SUNREAVER_DISGUISE_MALE)) - return false; - break; + return ValidateSpellInfo( + { + SPELL_SUNREAVER_DISGUISE_FEMALE, + SPELL_SUNREAVER_DISGUISE_MALE + }); case SPELL_SILVER_COVENANT_DISGUISE_TRIGGER: - if (!sSpellMgr->GetSpellInfo(SPELL_SILVER_COVENANT_DISGUISE_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_SILVER_COVENANT_DISGUISE_MALE)) - return false; + return ValidateSpellInfo( + { + SPELL_SILVER_COVENANT_DISGUISE_FEMALE, + SPELL_SILVER_COVENANT_DISGUISE_MALE + }); + default: break; } - return true; + + return false; } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1265,9 +1244,7 @@ class spell_gen_damage_reduction_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DAMAGE_REDUCTION_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DAMAGE_REDUCTION_AURA }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1320,13 +1297,12 @@ class spell_gen_defend : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VISUAL_SHIELD_1)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_VISUAL_SHIELD_2)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_VISUAL_SHIELD_3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_VISUAL_SHIELD_1, + SPELL_VISUAL_SHIELD_2, + SPELL_VISUAL_SHIELD_3 + }); } void RefreshVisualShields(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1338,7 +1314,7 @@ class spell_gen_defend : public SpellScriptLoader for (uint8 i = 0; i < GetSpellInfo()->StackAmount; ++i) target->RemoveAurasDueToSpell(SPELL_VISUAL_SHIELD_1 + i); - target->CastSpell(target, SPELL_VISUAL_SHIELD_1 + GetAura()->GetStackAmount() - 1, true, NULL, aurEff); + target->CastSpell(target, SPELL_VISUAL_SHIELD_1 + GetAura()->GetStackAmount() - 1, true, nullptr, aurEff); } else GetTarget()->RemoveAurasDueToSpell(GetId()); @@ -1442,9 +1418,7 @@ class spell_gen_divine_storm_cd_reset : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DIVINE_STORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DIVINE_STORM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1512,13 +1486,6 @@ class spell_gen_dungeon_credit : public SpellScriptLoader { PrepareSpellScript(spell_gen_dungeon_credit_SpellScript); - public: - spell_gen_dungeon_credit_SpellScript() - { - _handled = false; - } - - private: bool Load() override { return GetCaster()->GetTypeId() == TYPEID_UNIT; @@ -1533,7 +1500,7 @@ class spell_gen_dungeon_credit : public SpellScriptLoader _handled = true; Unit* caster = GetCaster(); if (InstanceScript* instance = caster->GetInstanceScript()) - instance->UpdateEncounterState(ENCOUNTER_CREDIT_CAST_SPELL, GetSpellInfo()->Id, caster); + instance->UpdateEncounterStateForSpellCast(GetSpellInfo()->Id, caster); } void Register() override @@ -1541,8 +1508,7 @@ class spell_gen_dungeon_credit : public SpellScriptLoader AfterHit += SpellHitFn(spell_gen_dungeon_credit_SpellScript::CreditEncounter); } - private: - bool _handled; + bool _handled = false; }; SpellScript* GetSpellScript() const override @@ -1575,13 +1541,14 @@ class spell_gen_elune_candle : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_CHEST) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_HAND_R) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_HAND_L) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_NORMAL)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ELUNE_CANDLE_OMEN_HEAD, + SPELL_ELUNE_CANDLE_OMEN_CHEST, + SPELL_ELUNE_CANDLE_OMEN_HAND_R, + SPELL_ELUNE_CANDLE_OMEN_HAND_L, + SPELL_ELUNE_CANDLE_NORMAL + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1609,7 +1576,7 @@ class spell_gen_elune_candle : public SpellScriptLoader else spellId = SPELL_ELUNE_CANDLE_NORMAL; - GetCaster()->CastSpell(GetHitUnit(), spellId, true, NULL); + GetCaster()->CastSpell(GetHitUnit(), spellId, true, nullptr); } void Register() override @@ -1642,11 +1609,12 @@ class spell_gen_gadgetzan_transporter_backfire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_MALFUNCTION_POLYMORPH) || - !sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_EVIL_TWIN) || - !sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_MALFUNCTION_MISS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TRANSPORTER_MALFUNCTION_POLYMORPH, + SPELL_TRANSPORTER_EVIL_TWIN, + SPELL_TRANSPORTER_MALFUNCTION_MISS + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -1743,10 +1711,11 @@ class spell_gen_gnomish_transporter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_SUCCESS) || - !sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_FAILURE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TRANSPORTER_SUCCESS, + SPELL_TRANSPORTER_FAILURE + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -1805,7 +1774,7 @@ enum GenericLifebloom class spell_gen_lifebloom : public SpellScriptLoader { public: - spell_gen_lifebloom(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + spell_gen_lifebloom(char const* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } class spell_gen_lifebloom_AuraScript : public AuraScript { @@ -1814,11 +1783,10 @@ class spell_gen_lifebloom : public SpellScriptLoader public: spell_gen_lifebloom_AuraScript(uint32 spellId) : AuraScript(), _spellId(spellId) { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1828,7 +1796,7 @@ class spell_gen_lifebloom : public SpellScriptLoader return; // final heal - GetTarget()->CastSpell(GetTarget(), _spellId, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastSpell(GetTarget(), _spellId, true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -1836,7 +1804,6 @@ class spell_gen_lifebloom : public SpellScriptLoader AfterEffectRemove += AuraEffectRemoveFn(spell_gen_lifebloom_AuraScript::AfterRemove, EFFECT_0, SPELL_AURA_PERIODIC_HEAL, AURA_EFFECT_HANDLE_REAL); } - private: uint32 _spellId; }; @@ -1961,7 +1928,7 @@ enum Mounts class spell_gen_mount : public SpellScriptLoader { public: - spell_gen_mount(const char* name, uint32 mount0 = 0, uint32 mount60 = 0, uint32 mount100 = 0, uint32 mount150 = 0, uint32 mount280 = 0, uint32 mount310 = 0) : SpellScriptLoader(name), + spell_gen_mount(char const* name, uint32 mount0 = 0, uint32 mount60 = 0, uint32 mount100 = 0, uint32 mount150 = 0, uint32 mount280 = 0, uint32 mount310 = 0) : SpellScriptLoader(name), _mount0(mount0), _mount60(mount60), _mount100(mount100), _mount150(mount150), _mount280(mount280), _mount310(mount310) { } class spell_gen_mount_SpellScript : public SpellScript @@ -1972,21 +1939,24 @@ class spell_gen_mount : public SpellScriptLoader spell_gen_mount_SpellScript(uint32 mount0, uint32 mount60, uint32 mount100, uint32 mount150, uint32 mount280, uint32 mount310) : SpellScript(), _mount0(mount0), _mount60(mount60), _mount100(mount100), _mount150(mount150), _mount280(mount280), _mount310(mount310) { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (_mount0 && !sSpellMgr->GetSpellInfo(_mount0)) - return false; - if (_mount60 && !sSpellMgr->GetSpellInfo(_mount60)) - return false; - if (_mount100 && !sSpellMgr->GetSpellInfo(_mount100)) - return false; - if (_mount150 && !sSpellMgr->GetSpellInfo(_mount150)) - return false; - if (_mount280 && !sSpellMgr->GetSpellInfo(_mount280)) - return false; - if (_mount310 && !sSpellMgr->GetSpellInfo(_mount310)) - return false; - return true; + bool result = true; + if (_mount0) + result &= ValidateSpellInfo({ _mount0 }); + if (_mount60) + result &= ValidateSpellInfo({ _mount60 }); + if (_mount100) + result &= ValidateSpellInfo({ _mount100 }); + if (_mount150) + result &= ValidateSpellInfo({ _mount150 }); + if (_mount280) + result &= ValidateSpellInfo({ _mount280 }); + if (_mount310) + result &= ValidateSpellInfo({ _mount310 }); + + return result; } void HandleMount(SpellEffIndex effIndex) @@ -2047,7 +2017,6 @@ class spell_gen_mount : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_gen_mount_SpellScript::HandleMount, EFFECT_2, SPELL_EFFECT_SCRIPT_EFFECT); } - private: uint32 _mount0; uint32 _mount60; uint32 _mount100; @@ -2249,9 +2218,7 @@ class spell_gen_moss_covered_feet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FALL_DOWN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FALL_DOWN }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2272,7 +2239,7 @@ class spell_gen_moss_covered_feet : public SpellScriptLoader } }; -enum Netherbloom +enum Netherbloom : uint32 { SPELL_NETHERBLOOM_POLLEN_1 = 28703 }; @@ -2290,8 +2257,9 @@ class spell_gen_netherbloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { for (uint8 i = 0; i < 5; ++i) - if (!sSpellMgr->GetSpellInfo(SPELL_NETHERBLOOM_POLLEN_1 + i)) + if (!ValidateSpellInfo({ SPELL_NETHERBLOOM_POLLEN_1 + i })) return false; + return true; } @@ -2347,9 +2315,7 @@ class spell_gen_nightmare_vine : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NIGHTMARE_POLLEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NIGHTMARE_POLLEN }); } void HandleScript(SpellEffIndex effIndex) @@ -2398,14 +2364,15 @@ class spell_gen_obsidian_armor : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_HOLY) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_FIRE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_NATURE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_FROST) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_SHADOW) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_ARCANE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_GEN_OBSIDIAN_ARMOR_HOLY, + SPELL_GEN_OBSIDIAN_ARMOR_FIRE, + SPELL_GEN_OBSIDIAN_ARMOR_NATURE, + SPELL_GEN_OBSIDIAN_ARMOR_FROST, + SPELL_GEN_OBSIDIAN_ARMOR_SHADOW, + SPELL_GEN_OBSIDIAN_ARMOR_ARCANE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2448,7 +2415,7 @@ class spell_gen_obsidian_armor : public SpellScriptLoader default: return; } - GetTarget()->CastSpell(GetTarget(), spellId, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), spellId, true, nullptr, aurEff); } void Register() override @@ -2526,11 +2493,12 @@ class spell_gen_orc_disguise : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ORC_DISGUISE_TRIGGER) || - !sSpellMgr->GetSpellInfo(SPELL_ORC_DISGUISE_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_ORC_DISGUISE_FEMALE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ORC_DISGUISE_TRIGGER, + SPELL_ORC_DISGUISE_MALE, + SPELL_ORC_DISGUISE_FEMALE + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2575,9 +2543,7 @@ class spell_gen_paralytic_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARALYSIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARALYSIS }); } void HandleStun(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2603,7 +2569,7 @@ class spell_gen_paralytic_poison : public SpellScriptLoader class spell_gen_proc_below_pct_damaged : public SpellScriptLoader { public: - spell_gen_proc_below_pct_damaged(const char* name) : SpellScriptLoader(name) { } + spell_gen_proc_below_pct_damaged(char const* name) : SpellScriptLoader(name) { } class spell_gen_proc_below_pct_damaged_AuraScript : public AuraScript { @@ -2679,10 +2645,11 @@ class spell_gen_parachute : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARACHUTE) || - !sSpellMgr->GetSpellInfo(SPELL_PARACHUTE_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PARACHUTE, + SPELL_PARACHUTE_BUFF + }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -2965,9 +2932,7 @@ class spell_gen_seaforium_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PLANT_CHARGES_CREDIT_ACHIEVEMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PLANT_CHARGES_CREDIT_ACHIEVEMENT }); } bool Load() override @@ -2978,7 +2943,7 @@ class spell_gen_seaforium_blast : public SpellScriptLoader void AchievementCredit(SpellEffIndex /*effIndex*/) { - // but in effect handling OriginalCaster can become NULL + // but in effect handling OriginalCaster can become nullptr if (Unit* originalCaster = GetOriginalCaster()) if (GameObject* go = GetHitGObj()) if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) @@ -3053,7 +3018,7 @@ class spell_gen_spirit_healer_res : public SpellScriptLoader { WorldPacket data(SMSG_SPIRIT_HEALER_CONFIRM, 8); data << uint64(target->GetGUID()); - originalCaster->GetSession()->SendPacket(&data); + originalCaster->SendDirectMessage(&data); } } @@ -3078,7 +3043,7 @@ enum SummonElemental class spell_gen_summon_elemental : public SpellScriptLoader { public: - spell_gen_summon_elemental(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + spell_gen_summon_elemental(char const* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } class spell_gen_summon_elemental_AuraScript : public AuraScript { @@ -3087,11 +3052,10 @@ class spell_gen_summon_elemental : public SpellScriptLoader public: spell_gen_summon_elemental_AuraScript(uint32 spellId) : AuraScript(), _spellId(spellId) { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } void AfterApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -3106,7 +3070,7 @@ class spell_gen_summon_elemental : public SpellScriptLoader if (GetCaster()) if (Unit* owner = GetCaster()->GetOwner()) if (owner->GetTypeId() == TYPEID_PLAYER) /// @todo this check is maybe wrong - owner->ToPlayer()->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + owner->ToPlayer()->RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); } void Register() override @@ -3115,7 +3079,6 @@ class spell_gen_summon_elemental : public SpellScriptLoader AfterEffectRemove += AuraEffectRemoveFn(spell_gen_summon_elemental_AuraScript::AfterRemove, EFFECT_1, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } - private: uint32 _spellId; }; @@ -3144,9 +3107,7 @@ class spell_gen_summon_tournament_mount : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LANCE_EQUIPPED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LANCE_EQUIPPED }); } SpellCastResult CheckIfLanceEquiped() @@ -3220,10 +3181,11 @@ class spell_gen_tournament_duel : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ON_TOURNAMENT_MOUNT) || - !sSpellMgr->GetSpellInfo(SPELL_MOUNTED_DUEL)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ON_TOURNAMENT_MOUNT, + SPELL_MOUNTED_DUEL + }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -3307,9 +3269,7 @@ class spell_pvp_trinket_wotf_shared_cd : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Triggered)) - return false; - return true; + return ValidateSpellInfo({ Triggered }); } void HandleScript() @@ -3371,7 +3331,7 @@ class spell_gen_turkey_marker : public SpellScriptLoader // on stack 15 cast the achievement crediting spell if (GetStackAmount() >= 15) - target->CastSpell(target, SPELL_TURKEY_VENGEANCE, true, NULL, aurEff, GetCasterGUID()); + target->CastSpell(target, SPELL_TURKEY_VENGEANCE, true, nullptr, aurEff, GetCasterGUID()); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -3463,9 +3423,7 @@ class spell_gen_vampiric_touch : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VAMPIRIC_TOUCH_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_VAMPIRIC_TOUCH_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3630,15 +3588,13 @@ class spell_gen_whisper_gulch_yogg_saron_whisper : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_YOGG_SARON_WHISPER_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_YOGG_SARON_WHISPER_DUMMY }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); - GetTarget()->CastSpell((Unit*)NULL, SPELL_YOGG_SARON_WHISPER_DUMMY, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_YOGG_SARON_WHISPER_DUMMY, true); } void Register() override @@ -3733,9 +3689,7 @@ class spell_gen_gm_freeze : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GM_FREEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GM_FREEZE }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -3918,18 +3872,9 @@ public: { PrepareAuraScript(spell_gen_mixology_bonus_AuraScript); - public: - spell_gen_mixology_bonus_AuraScript() - { - bonus = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIXOLOGY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIXOLOGY }); } bool Load() override @@ -4115,7 +4060,7 @@ public: } } - int32 bonus; + int32 bonus = 0; void Register() override { diff --git a/src/server/scripts/Spells/spell_holiday.cpp b/src/server/scripts/Spells/spell_holiday.cpp index 588bccb9596..eac0ff10c23 100644 --- a/src/server/scripts/Spells/spell_holiday.cpp +++ b/src/server/scripts/Spells/spell_holiday.cpp @@ -21,15 +21,15 @@ * Scriptnames in this file should be prefixed with "spell_#holidayname_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CellImpl.h" +#include "CreatureAIImpl.h" +#include "GridNotifiersImpl.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" #include "Vehicle.h" +#include "World.h" // 45102 Romantic Picnic enum SpellsPicnic @@ -135,10 +135,7 @@ class spell_hallow_end_candy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId : spells) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo(spells); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -181,10 +178,11 @@ class spell_hallow_end_candy_pirate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE) - || !sSpellMgr->GetSpellInfo(SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE, + SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE + }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -238,11 +236,19 @@ class spell_hallow_end_trick : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_MALE) || !sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_MALE) - || !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_MALE) || !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_FEMALE) - || !sSpellMgr->GetSpellInfo(SPELL_SKELETON_COSTUME) || !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_MALE) || !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_TRICK_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PIRATE_COSTUME_MALE, + SPELL_PIRATE_COSTUME_FEMALE, + SPELL_NINJA_COSTUME_MALE, + SPELL_NINJA_COSTUME_FEMALE, + SPELL_LEPER_GNOME_COSTUME_MALE, + SPELL_LEPER_GNOME_COSTUME_FEMALE, + SPELL_SKELETON_COSTUME, + SPELL_GHOST_COSTUME_MALE, + SPELL_GHOST_COSTUME_FEMALE, + SPELL_TRICK_BUFF + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -311,9 +317,7 @@ class spell_hallow_end_trick_or_treat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRICK) || !sSpellMgr->GetSpellInfo(SPELL_TREAT) || !sSpellMgr->GetSpellInfo(SPELL_TRICKED_OR_TREATED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TRICK, SPELL_TREAT, SPELL_TRICKED_OR_TREATED }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -349,13 +353,12 @@ class spell_hallow_end_tricky_treat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRICKY_TREAT_SPEED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_TRICKY_TREAT_TRIGGER)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_UPSET_TUMMY)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TRICKY_TREAT_SPEED, + SPELL_TRICKY_TREAT_TRIGGER, + SPELL_UPSET_TUMMY + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -402,16 +405,17 @@ public: bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_FEMALE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PIRATE_COSTUME_MALE, + SPELL_PIRATE_COSTUME_FEMALE, + SPELL_NINJA_COSTUME_MALE, + SPELL_NINJA_COSTUME_FEMALE, + SPELL_LEPER_GNOME_COSTUME_MALE, + SPELL_LEPER_GNOME_COSTUME_FEMALE, + SPELL_GHOST_COSTUME_MALE, + SPELL_GHOST_COSTUME_FEMALE + }); } void HandleScriptEffect() @@ -472,7 +476,7 @@ class spell_pilgrims_bounty_buff_food : public SpellScriptLoader private: uint32 const _triggeredSpellId; public: - spell_pilgrims_bounty_buff_food(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_pilgrims_bounty_buff_food(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_pilgrims_bounty_buff_food_AuraScript : public AuraScript { @@ -565,7 +569,7 @@ class spell_pilgrims_bounty_feast_on : public SpellScriptLoader if (Player* player = target->ToPlayer()) { player->CastSpell(player, SPELL_ON_PLATE_EAT_VISUAL, true); - caster->CastSpell(player, _spellId, true, NULL, NULL, player->GetGUID()); + caster->CastSpell(player, _spellId, true, nullptr, nullptr, player->GetGUID()); } if (Aura* aura = caster->GetAura(GetEffectValue())) @@ -609,9 +613,7 @@ class spell_pilgrims_bounty_turkey_tracker : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_KILL_COUNTER_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_KILL_COUNTER_VISUAL_MAX)) - return false; - return true; + return ValidateSpellInfo({ SPELL_KILL_COUNTER_VISUAL, SPELL_KILL_COUNTER_VISUAL_MAX }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -673,22 +675,21 @@ class spell_pilgrims_bounty_well_fed : public SpellScriptLoader uint32 _triggeredSpellId; public: - spell_pilgrims_bounty_well_fed(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_pilgrims_bounty_well_fed(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_pilgrims_bounty_well_fed_SpellScript : public SpellScript { PrepareSpellScript(spell_pilgrims_bounty_well_fed_SpellScript); - private: + uint32 _triggeredSpellId; public: spell_pilgrims_bounty_well_fed_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { } + private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) - return false; - return true; + return ValidateSpellInfo({ _triggeredSpellId }); } void HandleScript(SpellEffIndex effIndex) @@ -780,13 +781,13 @@ class spell_pilgrims_bounty_on_plate : public SpellScriptLoader uint32 _triggeredSpellId4; public: - spell_pilgrims_bounty_on_plate(const char* name, uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScriptLoader(name), + spell_pilgrims_bounty_on_plate(char const* name, uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScriptLoader(name), _triggeredSpellId1(triggeredSpellId1), _triggeredSpellId2(triggeredSpellId2), _triggeredSpellId3(triggeredSpellId3), _triggeredSpellId4(triggeredSpellId4) { } class spell_pilgrims_bounty_on_plate_SpellScript : public SpellScript { PrepareSpellScript(spell_pilgrims_bounty_on_plate_SpellScript); - private: + uint32 _triggeredSpellId1; uint32 _triggeredSpellId2; uint32 _triggeredSpellId3; @@ -796,14 +797,16 @@ class spell_pilgrims_bounty_on_plate : public SpellScriptLoader spell_pilgrims_bounty_on_plate_SpellScript(uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScript(), _triggeredSpellId1(triggeredSpellId1), _triggeredSpellId2(triggeredSpellId2), _triggeredSpellId3(triggeredSpellId3), _triggeredSpellId4(triggeredSpellId4) { } + private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId1) - || !sSpellMgr->GetSpellInfo(_triggeredSpellId2) - || !sSpellMgr->GetSpellInfo(_triggeredSpellId3) - || !sSpellMgr->GetSpellInfo(_triggeredSpellId4)) - return false; - return true; + return ValidateSpellInfo( + { + _triggeredSpellId1, + _triggeredSpellId2, + _triggeredSpellId3, + _triggeredSpellId4 + }); } Vehicle* GetTable(Unit* target) @@ -898,23 +901,21 @@ class spell_pilgrims_bounty_a_serving_of : public SpellScriptLoader private: uint32 _triggeredSpellId; public: - spell_pilgrims_bounty_a_serving_of(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_pilgrims_bounty_a_serving_of(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_pilgrims_bounty_a_serving_of_AuraScript : public AuraScript { PrepareAuraScript(spell_pilgrims_bounty_a_serving_of_AuraScript); - private: uint32 _triggeredSpellId; public: spell_pilgrims_bounty_a_serving_of_AuraScript(uint32 triggeredSpellId) : AuraScript(), _triggeredSpellId(triggeredSpellId) { } + private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) - return false; - return true; + return ValidateSpellInfo({ _triggeredSpellId }); } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -976,11 +977,12 @@ class spell_winter_veil_mistletoe : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_MISTLETOE) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_HOLLY) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_SNOWFLAKES)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CREATE_MISTLETOE, + SPELL_CREATE_HOLLY, + SPELL_CREATE_SNOWFLAKES + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1013,6 +1015,14 @@ enum PX238WinterWondervolt SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4 = 26274 }; +uint32 const WonderboltTransformSpells[] = +{ + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_1, + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_2, + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_3, + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4 +}; + class spell_winter_veil_px_238_winter_wondervolt : public SpellScriptLoader { public: @@ -1024,33 +1034,20 @@ class spell_winter_veil_px_238_winter_wondervolt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_1) || - !sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_2) || - !sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_3) || - !sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4)) - return false; - return true; + return ValidateSpellInfo(WonderboltTransformSpells); } void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); - uint32 const spells[4] = - { - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_1, - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_2, - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_3, - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4 - }; - if (Unit* target = GetHitUnit()) { - for (uint8 i = 0; i < 4; ++i) - if (target->HasAura(spells[i])) + for (uint32 spell : WonderboltTransformSpells) + if (target->HasAura(spell)) return; - target->CastSpell(target, spells[urand(0, 3)], true); + target->CastSpell(target, Trinity::Containers::SelectRandomContainerElement(WonderboltTransformSpells), true); } } @@ -1321,7 +1318,7 @@ class spell_brewfest_relay_race_intro_force_player_to_throw : public SpellScript PreventHitDefaultEffect(effIndex); // All this spells trigger a spell that requires reagents; if the // triggered spell is cast as "triggered", reagents are not consumed - GetHitUnit()->CastSpell((Unit*)NULL, GetSpellInfo()->Effects[effIndex].TriggerSpell, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)); + GetHitUnit()->CastSpell((Unit*)nullptr, GetSpellInfo()->Effects[effIndex].TriggerSpell, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)); } void Register() override @@ -1507,9 +1504,7 @@ class spell_midsummer_braziers_hit : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TORCH_TOSSING_TRAINING) || !sSpellMgr->GetSpellInfo(SPELL_TORCH_TOSSING_PRACTICE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TORCH_TOSSING_TRAINING, SPELL_TORCH_TOSSING_PRACTICE }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1560,11 +1555,12 @@ class spell_gen_ribbon_pole_dancer_check : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HAS_FULL_MIDSUMMER_SET) - || !sSpellMgr->GetSpellInfo(SPELL_RIBBON_DANCE) - || !sSpellMgr->GetSpellInfo(SPELL_BURNING_HOT_POLE_DANCE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HAS_FULL_MIDSUMMER_SET, + SPELL_RIBBON_DANCE, + SPELL_BURNING_HOT_POLE_DANCE + }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Spells/spell_hunter.cpp b/src/server/scripts/Spells/spell_hunter.cpp index 79ca0a1eb6c..2b9bfac79e9 100644 --- a/src/server/scripts/Spells/spell_hunter.cpp +++ b/src/server/scripts/Spells/spell_hunter.cpp @@ -21,15 +21,14 @@ * Scriptnames of files in this file should be prefixed with "spell_hun_". */ -#include "Pet.h" #include "ScriptMgr.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "Pet.h" +#include "SpellAuraEffects.h" #include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" enum HunterSpells { @@ -87,9 +86,7 @@ class spell_hun_aspect_of_the_beast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_ASPECT_OF_THE_BEAST_PET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_ASPECT_OF_THE_BEAST_PET }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -131,12 +128,13 @@ class spell_hun_ascpect_of_the_viper : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_ASPECT_OF_THE_VIPER_ENERGIZE) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_GLYPH_OF_ASPECT_OF_THE_VIPER) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_VIPER_ATTACK_SPEED) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_VICIOUS_VIPER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HUNTER_ASPECT_OF_THE_VIPER_ENERGIZE, + SPELL_HUNTER_GLYPH_OF_ASPECT_OF_THE_VIPER, + SPELL_HUNTER_VIPER_ATTACK_SPEED, + SPELL_HUNTER_VICIOUS_VIPER + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -149,14 +147,14 @@ class spell_hun_ascpect_of_the_viper : public SpellScriptLoader if (AuraEffect const* glyph = GetTarget()->GetAuraEffect(SPELL_HUNTER_GLYPH_OF_ASPECT_OF_THE_VIPER, EFFECT_0)) AddPct(mana, glyph->GetAmount()); - GetTarget()->CastCustomSpell(SPELL_HUNTER_ASPECT_OF_THE_VIPER_ENERGIZE, SPELLVALUE_BASE_POINT0, mana, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_HUNTER_ASPECT_OF_THE_VIPER_ENERGIZE, SPELLVALUE_BASE_POINT0, mana, GetTarget(), true, nullptr, aurEff); } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { // Hunter T7 4P Bonus if (GetTarget()->HasAura(SPELL_HUNTER_VIPER_ATTACK_SPEED)) - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_VICIOUS_VIPER, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_VICIOUS_VIPER, true, nullptr, aurEff); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -192,9 +190,7 @@ class spell_hun_chimera_shot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_SERPENT) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_VIPER) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_SCORPID)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_CHIMERA_SHOT_SERPENT, SPELL_HUNTER_CHIMERA_SHOT_VIPER, SPELL_HUNTER_CHIMERA_SHOT_SCORPID }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -225,7 +221,8 @@ class spell_hun_chimera_shot : public SpellScriptLoader // first, calculate damage of basic tick (C&P from AuraEffect::HandlePeriodicDamageAurasTick) basePoint = (aurEff->GetAmount() + aurEff->GetBonusAmount()) * aurEff->GetDonePct(); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(aurEff->GetId(), basePoint); + modOwner->ApplySpellMod(aurEff->GetId(), SPELLMOD_DOT, basePoint); + basePoint = unitTarget->SpellDamageBonusTaken(caster, aurEff->GetSpellInfo(), basePoint, DOT, aura->GetStackAmount()); // then, multiply to get damage potential @@ -287,9 +284,7 @@ class spell_hun_cobra_strikes : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -382,9 +377,7 @@ class spell_hun_glyph_of_arcane_shot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_GLYPH_OF_ARCANE_SHOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_GLYPH_OF_ARCANE_SHOT }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -444,9 +437,7 @@ class spell_hun_glyph_of_mend_pet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_GLYPH_OF_MEND_PET_HAPPINESS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_GLYPH_OF_MEND_PET_HAPPINESS }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -479,9 +470,7 @@ class spell_hun_hunting_party : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_REPLENISHMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_REPLENISHMENT }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -514,9 +503,7 @@ class spell_hun_improved_mend_pet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_IMPROVED_MEND_PET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_IMPROVED_MEND_PET }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -527,7 +514,7 @@ class spell_hun_improved_mend_pet : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_IMPROVED_MEND_PET, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_IMPROVED_MEND_PET, true, nullptr, aurEff); } void Register() override @@ -555,9 +542,7 @@ class spell_hun_invigoration : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_INVIGORATION_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_INVIGORATION_TRIGGERED }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -592,9 +577,7 @@ class spell_hun_kill_command_pet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_KILL_COMMAND_HUNTER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_KILL_COMMAND_HUNTER }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -632,16 +615,14 @@ class spell_hun_last_stand_pet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_LAST_STAND_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PET_LAST_STAND_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); int32 healthModSpellBasePoints0 = int32(caster->CountPctFromMaxHealth(30)); - caster->CastCustomSpell(caster, SPELL_HUNTER_PET_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, NULL, NULL, true, NULL); + caster->CastCustomSpell(caster, SPELL_HUNTER_PET_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, nullptr, nullptr, true, nullptr); } void Register() override @@ -668,10 +649,11 @@ class spell_hun_lock_and_load : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_LOCK_AND_LOAD_TRIGGER) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_LOCK_AND_LOAD_MARKER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HUNTER_LOCK_AND_LOAD_TRIGGER, + SPELL_HUNTER_LOCK_AND_LOAD_MARKER + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -740,9 +722,12 @@ class spell_hun_masters_call : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_MASTERS_CALL_TRIGGERED) || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue()) || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].CalcValue())) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HUNTER_MASTERS_CALL_TRIGGERED, + static_cast(spellInfo->Effects[EFFECT_0].CalcValue()), + static_cast(spellInfo->Effects[EFFECT_1].CalcValue()) + }); } bool Load() override @@ -820,9 +805,7 @@ class spell_hun_misdirection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_MISDIRECTION_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_MISDIRECTION_PROC }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -839,7 +822,7 @@ class spell_hun_misdirection : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_MISDIRECTION_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_MISDIRECTION_PROC, true, nullptr, aurEff); } void Register() override @@ -902,16 +885,14 @@ class spell_hun_pet_carrion_feeder : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED }); } SpellCastResult CheckIfCorpseNear() { Unit* caster = GetCaster(); float max_range = GetSpellInfo()->GetMaxRange(false); - WorldObject* result = NULL; + WorldObject* result = nullptr; // search for nearby enemy corpse in range Trinity::AnyDeadUnitSpellTargetInRangeCheck check(caster, max_range, GetSpellInfo(), TARGET_CHECK_ENEMY); Trinity::WorldObjectSearcher searcher(caster, result, check); @@ -961,9 +942,7 @@ class spell_hun_pet_heart_of_the_phoenix : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1003,9 +982,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PIERCING_SHOTS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PIERCING_SHOTS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1060,9 +1037,7 @@ class spell_hun_rapid_recuperation : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandlePeriodic(AuraEffect const* aurEff) @@ -1099,10 +1074,11 @@ class spell_hun_rapid_recuperation_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_RAPID_RECUPERATION_MANA_R1) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_RAPID_RECUPERATION_MANA_R2)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HUNTER_RAPID_RECUPERATION_MANA_R1, + SPELL_HUNTER_RAPID_RECUPERATION_MANA_R2 + }); } void HandleRapidFireProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -1202,9 +1178,7 @@ class spell_hun_roar_of_sacrifice : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROAR_OF_SACRIFICE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROAR_OF_SACRIFICE_TRIGGERED }); } bool CheckProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1288,9 +1262,7 @@ class spell_hun_sniper_training : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_SNIPER_TRAINING_R1) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_SNIPER_TRAINING_R1, SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1 }); } void HandlePeriodic(AuraEffect const* aurEff) @@ -1431,9 +1403,7 @@ class spell_hun_thrill_of_the_hunt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_THRILL_OF_THE_HUNT_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_THRILL_OF_THE_HUNT_MANA }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1489,9 +1459,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_T9_4P_GREATNESS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_T9_4P_GREATNESS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1534,10 +1502,11 @@ class spell_hun_viper_attack_speed : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_ASPECT_OF_THE_VIPER) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_VICIOUS_VIPER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HUNTER_ASPECT_OF_THE_VIPER, + SPELL_HUNTER_VICIOUS_VIPER + }); } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Spells/spell_item.cpp b/src/server/scripts/Spells/spell_item.cpp index 01f3efb0e33..0de0c0c00b9 100644 --- a/src/server/scripts/Spells/spell_item.cpp +++ b/src/server/scripts/Spells/spell_item.cpp @@ -21,15 +21,20 @@ * Scriptnames of files in this file should be prefixed with "spell_item_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellHistory.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "SkillDiscovery.h" #include "Battleground.h" +#include "Containers.h" +#include "Creature.h" +#include "CreatureAIImpl.h" #include "DBCStores.h" +#include "Map.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "SkillDiscovery.h" +#include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" // Generic script for handling item dummy effects which trigger another spell. class spell_item_trigger_spell : public SpellScriptLoader @@ -38,22 +43,21 @@ class spell_item_trigger_spell : public SpellScriptLoader uint32 _triggeredSpellId; public: - spell_item_trigger_spell(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_item_trigger_spell(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_item_trigger_spell_SpellScript : public SpellScript { PrepareSpellScript(spell_item_trigger_spell_SpellScript); - private: + uint32 _triggeredSpellId; public: spell_item_trigger_spell_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) - return false; - return true; + return ValidateSpellInfo({ _triggeredSpellId }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -92,15 +96,13 @@ class spell_item_aegis_of_preservation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AEGIS_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AEGIS_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_AEGIS_HEAL, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_AEGIS_HEAL, true, nullptr, aurEff); } void Register() override @@ -142,10 +144,11 @@ class spell_item_alchemists_stone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ALCHEMISTS_STONE_EXTRA_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_ALCHEMISTS_STONE_EXTRA_MANA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ALCHEMISTS_STONE_EXTRA_HEAL, + SPELL_ALCHEMISTS_STONE_EXTRA_MANA + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -213,11 +216,12 @@ class spell_item_anger_capacitor : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOTE_OF_ANGER) || - !sSpellMgr->GetSpellInfo(SPELL_MANIFEST_ANGER_MAIN_HAND) || - !sSpellMgr->GetSpellInfo(SPELL_MANIFEST_ANGER_OFF_HAND)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MOTE_OF_ANGER, + SPELL_MANIFEST_ANGER_MAIN_HAND, + SPELL_MANIFEST_ANGER_OFF_HAND + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -234,7 +238,7 @@ class spell_item_anger_capacitor : public SpellScriptLoader caster->RemoveAurasDueToSpell(SPELL_MOTE_OF_ANGER); uint32 spellId = SPELL_MANIFEST_ANGER_MAIN_HAND; if (Player* player = caster->ToPlayer()) - if (player->GetWeaponForAttack(OFF_ATTACK, true) && urand(0, 1)) + if (player->GetWeaponForAttack(OFF_ATTACK, true) && roll_chance_i(50)) spellId = SPELL_MANIFEST_ANGER_OFF_HAND; caster->CastSpell(target, spellId, true, nullptr, aurEff); @@ -312,18 +316,18 @@ class spell_item_aura_of_madness : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOCIOPATH) || - !sSpellMgr->GetSpellInfo(SPELL_DELUSIONAL) || - !sSpellMgr->GetSpellInfo(SPELL_KLEPTOMANIA) || - !sSpellMgr->GetSpellInfo(SPELL_MEGALOMANIA) || - !sSpellMgr->GetSpellInfo(SPELL_PARANOIA) || - !sSpellMgr->GetSpellInfo(SPELL_MANIC) || - !sSpellMgr->GetSpellInfo(SPELL_NARCISSISM) || - !sSpellMgr->GetSpellInfo(SPELL_MARTYR_COMPLEX) || - !sSpellMgr->GetSpellInfo(SPELL_DEMENTIA) || - !sObjectMgr->GetBroadcastText(SAY_MADNESS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SOCIOPATH, + SPELL_DELUSIONAL, + SPELL_KLEPTOMANIA, + SPELL_MEGALOMANIA, + SPELL_PARANOIA, + SPELL_MANIC, + SPELL_NARCISSISM, + SPELL_MARTYR_COMPLEX, + SPELL_DEMENTIA + }) && sObjectMgr->GetBroadcastText(SAY_MADNESS); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -389,10 +393,11 @@ class spell_item_dementia : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEMENTIA_POS) || - !sSpellMgr->GetSpellInfo(SPELL_DEMENTIA_NEG)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DEMENTIA_POS, + SPELL_DEMENTIA_NEG + }); } void HandlePeriodicDummy(AuraEffect const* aurEff) @@ -430,9 +435,7 @@ class spell_item_blessing_of_ancient_kings : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PROTECTION_OF_ANCIENT_KINGS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PROTECTION_OF_ANCIENT_KINGS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -519,9 +522,7 @@ class spell_item_deadly_precision_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEADLY_PRECISION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEADLY_PRECISION }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -575,13 +576,14 @@ class spell_item_deathbringers_will : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Strength) || - !sSpellMgr->GetSpellInfo(Agility) || - !sSpellMgr->GetSpellInfo(AttackPower) || - !sSpellMgr->GetSpellInfo(Critical) || - !sSpellMgr->GetSpellInfo(Haste)) - return false; - return true; + return ValidateSpellInfo( + { + Strength, + Agility, + AttackPower, + Critical, + Haste + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -706,11 +708,10 @@ class spell_item_defibrillate : public SpellScriptLoader public: spell_item_defibrillate_SpellScript(uint8 chance, uint32 failSpell) : SpellScript(), _chance(chance), _failSpell(failSpell) { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (_failSpell && !sSpellMgr->GetSpellInfo(_failSpell)) - return false; - return true; + return !_failSpell || ValidateSpellInfo({ _failSpell }); } void HandleScript(SpellEffIndex effIndex) @@ -728,7 +729,6 @@ class spell_item_defibrillate : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_item_defibrillate_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_RESURRECT); } - private: uint8 _chance; uint32 _failSpell; }; @@ -760,15 +760,13 @@ class spell_item_desperate_defense : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DESPERATE_RAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DESPERATE_RAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_DESPERATE_RAGE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_DESPERATE_RAGE, true, nullptr, aurEff); } void Register() override @@ -810,17 +808,14 @@ class spell_item_deviate_fish : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId = SPELL_SLEEPY; spellId <= SPELL_HEALTHY_SPIRIT; ++spellId) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SLEEPY, SPELL_INVIGORATE, SPELL_SHRINK, SPELL_PARTY_TIME, SPELL_HEALTHY_SPIRIT }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = urand(SPELL_SLEEPY, SPELL_HEALTHY_SPIRIT); - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -852,9 +847,7 @@ class spell_item_discerning_eye_beast_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DISCERNING_EYE_BEAST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DISCERNING_EYE_BEAST }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -926,9 +919,7 @@ class spell_item_fate_rune_of_unsurpassed_vigor : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSURPASSED_VIGOR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSURPASSED_VIGOR }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -969,9 +960,7 @@ class spell_item_flask_of_the_north : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_SP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_STR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLASK_OF_THE_NORTH_SP, SPELL_FLASK_OF_THE_NORTH_AP, SPELL_FLASK_OF_THE_NORTH_STR }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1004,7 +993,7 @@ class spell_item_flask_of_the_north : public SpellScriptLoader break; } - caster->CastSpell(caster, possibleSpells[urand(0, (possibleSpells.size() - 1))], true, NULL); + caster->CastSpell(caster, possibleSpells[urand(0, (possibleSpells.size() - 1))], true, nullptr); } void Register() override @@ -1037,9 +1026,7 @@ class spell_item_frozen_shadoweave : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMEND)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOWMEND }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1085,9 +1072,7 @@ class spell_item_gnomish_death_ray : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_SELF) || !sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_TARGET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GNOMISH_DEATH_RAY_SELF, SPELL_GNOMISH_DEATH_RAY_TARGET }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1132,9 +1117,7 @@ class spell_item_harm_prevention_belt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCEFIELD_COLLAPSE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCEFIELD_COLLAPSE }); } void HandleProc(ProcEventInfo& /*eventInfo*/) @@ -1172,9 +1155,7 @@ class spell_item_healing_touch_refund : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HEALING_TOUCH_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HEALING_TOUCH_MANA }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1226,12 +1207,13 @@ class spell_item_heartpierce : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Energy) || - !sSpellMgr->GetSpellInfo(Mana) || - !sSpellMgr->GetSpellInfo(Rage) || - !sSpellMgr->GetSpellInfo(RunicPower)) - return false; - return true; + return ValidateSpellInfo( + { + Energy, + Mana, + Rage, + RunicPower + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1334,9 +1316,14 @@ class spell_item_make_a_wish : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_BLESSING) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_MIGHTY_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FURIOUS_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_TINY_MAGICAL_CRAWDAD) || !sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_GIFT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MR_PINCHYS_BLESSING, + SPELL_SUMMON_MIGHTY_MR_PINCHY, + SPELL_SUMMON_FURIOUS_MR_PINCHY, + SPELL_TINY_MAGICAL_CRAWDAD, + SPELL_MR_PINCHYS_GIFT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1350,7 +1337,7 @@ class spell_item_make_a_wish : public SpellScriptLoader case 3: spellId = SPELL_SUMMON_FURIOUS_MR_PINCHY; break; case 4: spellId = SPELL_TINY_MAGICAL_CRAWDAD; break; } - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -1384,9 +1371,7 @@ class spell_item_mark_of_conquest : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_CONQUEST_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_CONQUEST_ENERGIZE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1485,9 +1470,7 @@ class spell_item_necrotic_touch : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ITEM_NECROTIC_TOUCH_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ITEM_NECROTIC_TOUCH_PROC }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1539,9 +1522,12 @@ class spell_item_net_o_matic : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_NET_O_MATIC_TRIGGERED1, + SPELL_NET_O_MATIC_TRIGGERED2, + SPELL_NET_O_MATIC_TRIGGERED3 + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1596,9 +1582,12 @@ class spell_item_noggenfogger_elixir : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1, + SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2, + SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3 + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1673,9 +1662,7 @@ class spell_item_persistent_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PERSISTENT_SHIELD_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PERSISTENT_SHIELD_TRIGGERED }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1729,9 +1716,7 @@ class spell_item_pet_healing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HEALTH_LINK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HEALTH_LINK }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1813,10 +1798,13 @@ class spell_item_savory_deviate_delight : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId = SPELL_FLIP_OUT_MALE; spellId <= SPELL_YAAARRRR_FEMALE; ++spellId) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FLIP_OUT_MALE, + SPELL_FLIP_OUT_FEMALE, + SPELL_YAAARRRR_MALE, + SPELL_YAAARRRR_FEMALE + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1830,7 +1818,7 @@ class spell_item_savory_deviate_delight : public SpellScriptLoader // Yaaarrrr - pirate case 2: spellId = (caster->getGender() == GENDER_MALE ? SPELL_YAAARRRR_MALE : SPELL_YAAARRRR_FEMALE); break; } - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -2013,13 +2001,12 @@ class spell_item_shadowmourne : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, + SPELL_SHADOWMOURNE_SOUL_FRAGMENT, + SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2032,14 +2019,14 @@ class spell_item_shadowmourne : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_SHADOWMOURNE_SOUL_FRAGMENT, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_SHADOWMOURNE_SOUL_FRAGMENT, true, nullptr, aurEff); // this can't be handled in AuraScript of SoulFragments because we need to know victim if (Aura* soulFragments = GetTarget()->GetAura(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) { if (soulFragments->GetStackAmount() >= 10) { - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, true, nullptr, aurEff); soulFragments->Remove(); } } @@ -2070,9 +2057,12 @@ class spell_item_shadowmourne_soul_fragment : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_LOW) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_HIGH) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHADOWMOURNE_VISUAL_LOW, + SPELL_SHADOWMOURNE_VISUAL_HIGH, + SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF + }); } void OnStackChange(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2139,9 +2129,15 @@ class spell_item_six_demon_bag : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FROSTBOLT) || !sSpellMgr->GetSpellInfo(SPELL_POLYMORPH) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FELHOUND_MINION) || !sSpellMgr->GetSpellInfo(SPELL_FIREBALL) || !sSpellMgr->GetSpellInfo(SPELL_CHAIN_LIGHTNING) || !sSpellMgr->GetSpellInfo(SPELL_ENVELOPING_WINDS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FROSTBOLT, + SPELL_POLYMORPH, + SPELL_SUMMON_FELHOUND_MINION, + SPELL_FIREBALL, + SPELL_CHAIN_LIGHTNING, + SPELL_ENVELOPING_WINDS + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2204,9 +2200,7 @@ class spell_item_swift_hand_justice_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SWIFT_HAND_OF_JUSTICE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SWIFT_HAND_OF_JUSTICE_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2248,9 +2242,7 @@ class spell_item_totem_of_flowing_water : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LESSER_HEALING_WAVE_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LESSER_HEALING_WAVE_MANA }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2325,9 +2317,12 @@ class spell_item_underbelly_elixir : public SpellScriptLoader } bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_UNDERBELLY_ELIXIR_TRIGGERED1, + SPELL_UNDERBELLY_ELIXIR_TRIGGERED2, + SPELL_UNDERBELLY_ELIXIR_TRIGGERED3 + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2339,7 +2334,7 @@ class spell_item_underbelly_elixir : public SpellScriptLoader case 1: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED1; break; case 2: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED2; break; } - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -2423,9 +2418,12 @@ class spell_item_red_rider_air_rifle : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_HOLD_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT_SELF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_AIR_RIFLE_HOLD_VISUAL, + SPELL_AIR_RIFLE_SHOOT, + SPELL_AIR_RIFLE_SHOOT_SELF + }); } void HandleScript(SpellEffIndex effIndex) @@ -2654,9 +2652,12 @@ class spell_item_vanquished_clutches : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CRUSHER) || !sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR) || !sSpellMgr->GetSpellInfo(SPELL_CORRUPTOR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CRUSHER, + SPELL_CONSTRICTOR, + SPELL_CORRUPTOR + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2840,15 +2841,17 @@ class spell_item_purify_helboar_meat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PURIFIED_HELBOAR_MEAT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_TOXIC_HELBOAR_MEAT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SUMMON_PURIFIED_HELBOAR_MEAT, + SPELL_SUMMON_TOXIC_HELBOAR_MEAT + }); } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); - caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, NULL); + caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, nullptr); } void Register() override @@ -2889,7 +2892,7 @@ class spell_item_crystal_prison_dummy_dnd : public SpellScriptLoader if (Creature* target = GetHitCreature()) if (target->isDead() && !target->IsPet()) { - GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, *target, G3D::Quat(), uint32(target->GetRespawnTime()-time(NULL))); + GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, *target, QuaternionData(), uint32(target->GetRespawnTime()-time(nullptr))); target->DespawnOrUnsummon(); } } @@ -2926,11 +2929,14 @@ class spell_item_reindeer_transformation : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_310) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_280) - || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_60) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_100) - || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_60)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FLYING_REINDEER_310, + SPELL_FLYING_REINDEER_280, + SPELL_FLYING_REINDEER_60, + SPELL_REINDEER_100, + SPELL_REINDEER_60 + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -2991,9 +2997,7 @@ class spell_item_nigh_invulnerability : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NIGH_INVULNERABILITY) || !sSpellMgr->GetSpellInfo(SPELL_COMPLETE_VULNERABILITY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NIGH_INVULNERABILITY, SPELL_COMPLETE_VULNERABILITY }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3037,9 +3041,7 @@ class spell_item_poultryizer : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_BACKFIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_POULTRYIZER_SUCCESS, SPELL_POULTRYIZER_BACKFIRE }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3081,9 +3083,7 @@ class spell_item_socrethars_stone : public SpellScriptLoader } bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_TO_SEAT) || !sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_FROM_SEAT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SOCRETHAR_TO_SEAT, SPELL_SOCRETHAR_FROM_SEAT }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3132,9 +3132,9 @@ class spell_item_demon_broiled_surprise : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_DEMON_BROILED_SURPRISE) || !sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) || !sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CREATE_DEMON_BROILED_SURPRISE }) && + sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) && + sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW); } bool Load() override @@ -3189,9 +3189,7 @@ class spell_item_complete_raptor_capture : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RAPTOR_CAPTURE_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RAPTOR_CAPTURE_CREDIT }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3202,7 +3200,7 @@ class spell_item_complete_raptor_capture : public SpellScriptLoader GetHitCreature()->DespawnOrUnsummon(); //cast spell Raptor Capture Credit - caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, NULL); + caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, nullptr); } } @@ -3283,9 +3281,13 @@ class spell_item_brewfest_mount_transformation : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_60) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_60)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MOUNT_RAM_100, + SPELL_MOUNT_RAM_60, + SPELL_MOUNT_KODO_100, + SPELL_MOUNT_KODO_60 + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3353,9 +3355,7 @@ class spell_item_nitro_boots : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_BACKFIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NITRO_BOOTS_SUCCESS, SPELL_NITRO_BOOTS_BACKFIRE }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3399,9 +3399,7 @@ class spell_item_teach_language : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LEARN_GNOMISH_BINARY) || !sSpellMgr->GetSpellInfo(SPELL_LEARN_GOBLIN_BINARY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LEARN_GNOMISH_BINARY, SPELL_LEARN_GOBLIN_BINARY }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3445,9 +3443,7 @@ class spell_item_rocket_boots : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_BOOTS_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROCKET_BOOTS_PROC }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3457,7 +3453,7 @@ class spell_item_rocket_boots : public SpellScriptLoader bg->EventPlayerDroppedFlag(caster); caster->GetSpellHistory()->ResetCooldown(SPELL_ROCKET_BOOTS_PROC); - caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, NULL); + caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, nullptr); } SpellCastResult CheckCast() @@ -3497,9 +3493,7 @@ class spell_item_pygmy_oil : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_PYGMY_AURA) || !sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_SMALLER_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PYGMY_OIL_PYGMY_AURA, SPELL_PYGMY_OIL_SMALLER_AURA }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3583,9 +3577,9 @@ class spell_item_chicken_cover : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHICKEN_NET) || !sSpellMgr->GetSpellInfo(SPELL_CAPTURE_CHICKEN_ESCAPE) || !sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) || !sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHICKEN_NET, SPELL_CAPTURE_CHICKEN_ESCAPE }) && + sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) && + sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3744,10 +3738,11 @@ class spell_item_shard_of_the_scale : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(HealProc) || - !sSpellMgr->GetSpellInfo(DamageProc)) - return false; - return true; + return ValidateSpellInfo( + { + HealProc, + DamageProc + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3794,12 +3789,13 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_DRUID) || - !sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_PALADIN) || - !sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_PRIEST) || - !sSpellMgr->GetSpellInfo(SPELL_SOUL_PRESERVER_SHAMAN)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SOUL_PRESERVER_DRUID, + SPELL_SOUL_PRESERVER_PALADIN, + SPELL_SOUL_PRESERVER_PRIEST, + SPELL_SOUL_PRESERVER_SHAMAN + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3881,12 +3877,9 @@ class spell_item_sunwell_neck : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sFactionStore.LookupEntry(FACTION_ALDOR) || - !sFactionStore.LookupEntry(FACTION_SCRYERS) || - !sSpellMgr->GetSpellInfo(Aldors) || - !sSpellMgr->GetSpellInfo(Scryers)) - return false; - return true; + return ValidateSpellInfo({ Aldors, Scryers }) && + sFactionStore.LookupEntry(FACTION_ALDOR) && + sFactionStore.LookupEntry(FACTION_SCRYERS); } bool CheckProc(ProcEventInfo& eventInfo) @@ -3981,12 +3974,13 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_NORMAL_STRENGTH) || - !sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_NORMAL_AGILITY) || - !sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_HEROIC_STRENGTH) || - !sSpellMgr->GetSpellInfo(SPELL_DEATH_CHOICE_HEROIC_AGILITY)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DEATH_CHOICE_NORMAL_STRENGTH, + SPELL_DEATH_CHOICE_NORMAL_AGILITY, + SPELL_DEATH_CHOICE_HEROIC_STRENGTH, + SPELL_DEATH_CHOICE_HEROIC_AGILITY + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4065,11 +4059,10 @@ public: { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_stackSpell) || !sSpellMgr->GetSpellInfo(_triggerSpell)) - return false; - return true; + return ValidateSpellInfo({ _stackSpell, _triggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4097,7 +4090,6 @@ public: OnEffectProc += AuraEffectProcFn(spell_item_trinket_stack_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); } - private: uint32 _stackSpell; uint32 _triggerSpell; }; @@ -4115,7 +4107,7 @@ private: // 57345 - Darkmoon Card: Greatness enum DarkmoonCardSpells { - SPELL_DARKMOON_CARD_STRENGHT = 60229, + SPELL_DARKMOON_CARD_STRENGTH = 60229, SPELL_DARKMOON_CARD_AGILITY = 60233, SPELL_DARKMOON_CARD_INTELLECT = 60234, SPELL_DARKMOON_CARD_SPIRIT = 60235, @@ -4132,12 +4124,13 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_STRENGHT) || - !sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_AGILITY) || - !sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_INTELLECT) || - !sSpellMgr->GetSpellInfo(SPELL_DARKMOON_CARD_SPIRIT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DARKMOON_CARD_STRENGTH, + SPELL_DARKMOON_CARD_AGILITY, + SPELL_DARKMOON_CARD_INTELLECT, + SPELL_DARKMOON_CARD_SPIRIT + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4151,11 +4144,11 @@ public: float spi = caster->GetStat(STAT_SPIRIT); float stat = 0.0f; - uint32 spellTrigger = SPELL_DARKMOON_CARD_STRENGHT; + uint32 spellTrigger = SPELL_DARKMOON_CARD_STRENGTH; if (str > stat) { - spellTrigger = SPELL_DARKMOON_CARD_STRENGHT; + spellTrigger = SPELL_DARKMOON_CARD_STRENGTH; stat = str; } @@ -4209,9 +4202,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHARM_WITCH_DOCTOR_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHARM_WITCH_DOCTOR_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4258,10 +4249,11 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MANA_DRAIN_ENERGIZE) - || !sSpellMgr->GetSpellInfo(SPELL_MANA_DRAIN_LEECH)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MANA_DRAIN_ENERGIZE, + SPELL_MANA_DRAIN_LEECH + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4309,11 +4301,8 @@ class spell_item_taunt_flag_targeting : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TAUNT_FLAG)) - return false; - if (!sObjectMgr->GetBroadcastText(EMOTE_PLANTS_FLAG)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TAUNT_FLAG }) && + sObjectMgr->GetBroadcastText(EMOTE_PLANTS_FLAG); } void FilterTargets(std::list& targets) @@ -4381,9 +4370,7 @@ class spell_item_mind_control_cap : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_MIND_CONTROL_CAP) || !sSpellMgr->GetSpellInfo(SPELL_DULLARD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GNOMISH_MIND_CONTROL_CAP, SPELL_DULLARD }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -4436,9 +4423,7 @@ class spell_item_universal_remote : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CONTROL_MACHINE) || !sSpellMgr->GetSpellInfo(SPELL_MOBILITY_MALFUNCTION) || !sSpellMgr->GetSpellInfo(SPELL_TARGET_LOCK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CONTROL_MACHINE, SPELL_MOBILITY_MALFUNCTION, SPELL_TARGET_LOCK }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -4492,9 +4477,7 @@ class spell_item_zandalarian_charm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } bool CheckProc(ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_mage.cpp b/src/server/scripts/Spells/spell_mage.cpp index 72b4a323710..c40e164a130 100644 --- a/src/server/scripts/Spells/spell_mage.cpp +++ b/src/server/scripts/Spells/spell_mage.cpp @@ -21,11 +21,14 @@ * Scriptnames of files in this file should be prefixed with "spell_mage_". */ -#include "Player.h" #include "ScriptMgr.h" +#include "Creature.h" +#include "Player.h" +#include "Random.h" +#include "SpellAuraEffects.h" #include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" enum MageSpells { @@ -79,11 +82,11 @@ class spell_mage_incanters_absorbtion_base_AuraScript : public AuraScript public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_INCANTERS_ABSORBTION_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, + SPELL_MAGE_INCANTERS_ABSORBTION_R1 + }); } void Trigger(AuraEffect* aurEff, DamageInfo& /*dmgInfo*/, uint32& absorbAmount) @@ -93,7 +96,7 @@ class spell_mage_incanters_absorbtion_base_AuraScript : public AuraScript if (AuraEffect* talentAurEff = target->GetAuraEffectOfRankedSpell(SPELL_MAGE_INCANTERS_ABSORBTION_R1, EFFECT_0)) { int32 bp = CalculatePct(absorbAmount, talentAurEff->GetAmount()); - target->CastCustomSpell(target, SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, &bp, NULL, NULL, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, &bp, nullptr, nullptr, true, nullptr, aurEff); } } }; @@ -110,10 +113,11 @@ class spell_mage_arcane_potency : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_POTENCY_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_POTENCY_RANK_2)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_ARCANE_POTENCY_RANK_1, + SPELL_MAGE_ARCANE_POTENCY_RANK_2 + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -161,9 +165,7 @@ class spell_mage_blast_wave : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_GLYPH_OF_BLAST_WAVE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_GLYPH_OF_BLAST_WAVE }); } void HandleKnockBack(SpellEffIndex effIndex) @@ -196,9 +198,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_BLAZING_SPEED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_BLAZING_SPEED }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -264,9 +264,7 @@ class spell_mage_burnout : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_BURNOUT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_BURNOUT }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -350,9 +348,7 @@ class spell_mage_combustion : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_COMBUSTION_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_COMBUSTION_PROC }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -391,9 +387,7 @@ class spell_mage_imp_blizzard : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_CHILLED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_CHILLED }); } void HandleChill(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -428,9 +422,7 @@ class spell_mage_imp_mana_gems : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_MANA_SURGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_MANA_SURGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -463,9 +455,7 @@ class spell_mage_empowered_fire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_EMPOWERED_FIRE_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_EMPOWERED_FIRE_PROC }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -511,9 +501,7 @@ class spell_mage_fingers_of_frost : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FINGERS_OF_FROST_AURASTATE_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FINGERS_OF_FROST_AURASTATE_AURA }); } void HandleDummy(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -553,11 +541,11 @@ class spell_mage_fire_frost_ward : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FROST_WARDING_TRIGGERED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FROST_WARDING_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_FROST_WARDING_TRIGGERED, + SPELL_MAGE_FROST_WARDING_R1 + }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& canBeRecalculated) @@ -586,7 +574,7 @@ class spell_mage_fire_frost_ward : public SpellScriptLoader { int32 bp = dmgInfo.GetDamage(); dmgInfo.AbsorbDamage(bp); - target->CastCustomSpell(target, SPELL_MAGE_FROST_WARDING_TRIGGERED, &bp, NULL, NULL, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_MAGE_FROST_WARDING_TRIGGERED, &bp, nullptr, nullptr, true, nullptr, aurEff); absorbAmount = 0; PreventDefaultAction(); } @@ -617,18 +605,9 @@ class spell_mage_focus_magic : public SpellScriptLoader { PrepareAuraScript(spell_mage_focus_magic_AuraScript); - public: - spell_mage_focus_magic_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FOCUS_MAGIC_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FOCUS_MAGIC_PROC }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -640,7 +619,7 @@ class spell_mage_focus_magic : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(_procTarget, SPELL_MAGE_FOCUS_MAGIC_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_MAGE_FOCUS_MAGIC_PROC, true, nullptr, aurEff); } void Register() override @@ -649,8 +628,7 @@ class spell_mage_focus_magic : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_mage_focus_magic_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_MOD_SPELL_CRIT_CHANCE); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -673,11 +651,12 @@ class spell_mage_gen_extra_effects : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_T10_2P_BONUS) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_T10_2P_BONUS_EFFECT) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_T8_4P_BONUS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_T10_2P_BONUS, + SPELL_MAGE_T10_2P_BONUS_EFFECT, + SPELL_MAGE_T8_4P_BONUS + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -825,9 +804,7 @@ class spell_mage_hot_streak : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_HOT_STREAK_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_HOT_STREAK_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -880,9 +857,7 @@ class spell_mage_ice_barrier : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_SHATTERED_BARRIER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_SHATTERED_BARRIER }); } void CalculateAmount(AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated) @@ -942,9 +917,7 @@ class spell_mage_ignite : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_IGNITE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_IGNITE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -989,9 +962,7 @@ class spell_mage_living_bomb : public SpellScriptLoader bool Validate(SpellInfo const* spell) override { - if (!sSpellMgr->GetSpellInfo(uint32(spell->Effects[EFFECT_1].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ static_cast(spell->Effects[EFFECT_1].CalcValue()) }); } void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1001,7 +972,7 @@ class spell_mage_living_bomb : public SpellScriptLoader return; if (Unit* caster = GetCaster()) - caster->CastSpell(GetTarget(), uint32(aurEff->GetAmount()), true, NULL, aurEff); + caster->CastSpell(GetTarget(), uint32(aurEff->GetAmount()), true, nullptr, aurEff); } void Register() override @@ -1028,9 +999,7 @@ class spell_mage_magic_absorption : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_MAGIC_ABSORPTION_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_MAGIC_ABSORPTION_MANA }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1065,10 +1034,8 @@ class spell_mage_mana_shield : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!spell_mage_incanters_absorbtion_base_AuraScript::Validate(spellInfo) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_SURGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_ARCANE_SURGE }) && + spell_mage_incanters_absorbtion_base_AuraScript::Validate(spellInfo); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& canBeRecalculated) @@ -1119,9 +1086,7 @@ class spell_mage_master_of_elements : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_MASTER_OF_ELEMENTS_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_MASTER_OF_ELEMENTS_ENERGIZE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1209,22 +1174,18 @@ class spell_mage_polymorph_cast_visual : public SpellScriptLoader { PrepareSpellScript(spell_mage_polymorph_cast_visual_SpellScript); - static const uint32 PolymorhForms[6]; + static const uint32 PolymorphForms[6]; bool Validate(SpellInfo const* /*spellInfo*/) override { - // check if spell ids exist in dbc - for (uint32 i = 0; i < 6; ++i) - if (!sSpellMgr->GetSpellInfo(PolymorhForms[i])) - return false; - return true; + return ValidateSpellInfo(PolymorphForms); } void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* target = GetCaster()->FindNearestCreature(NPC_AUROSALIA, 30.0f)) if (target->GetTypeId() == TYPEID_UNIT) - target->CastSpell(target, PolymorhForms[urand(0, 5)], true); + target->CastSpell(target, PolymorphForms[urand(0, 5)], true); } void Register() override @@ -1239,7 +1200,7 @@ class spell_mage_polymorph_cast_visual : public SpellScriptLoader } }; -const uint32 spell_mage_polymorph_cast_visual::spell_mage_polymorph_cast_visual_SpellScript::PolymorhForms[6] = +const uint32 spell_mage_polymorph_cast_visual::spell_mage_polymorph_cast_visual_SpellScript::PolymorphForms[6] = { SPELL_MAGE_SQUIRREL_FORM, SPELL_MAGE_GIRAFFE_FORM, @@ -1261,9 +1222,12 @@ class spell_mage_summon_water_elemental : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_GLYPH_OF_ETERNAL_WATER) || !sSpellMgr->GetSpellInfo(SPELL_MAGE_SUMMON_WATER_ELEMENTAL_TEMPORARY) || !sSpellMgr->GetSpellInfo(SPELL_MAGE_SUMMON_WATER_ELEMENTAL_PERMANENT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_GLYPH_OF_ETERNAL_WATER, + SPELL_MAGE_SUMMON_WATER_ELEMENTAL_TEMPORARY, + SPELL_MAGE_SUMMON_WATER_ELEMENTAL_PERMANENT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Spells/spell_paladin.cpp b/src/server/scripts/Spells/spell_paladin.cpp index b259db332a9..08ea6472a8d 100644 --- a/src/server/scripts/Spells/spell_paladin.cpp +++ b/src/server/scripts/Spells/spell_paladin.cpp @@ -21,13 +21,15 @@ * Scriptnames of files in this file should be prefixed with "spell_pal_". */ -#include "Player.h" -#include "GameTime.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "GameTime.h" +#include "Group.h" +#include "Player.h" +#include "Random.h" #include "SpellAuraEffects.h" #include "SpellHistory.h" -#include "Group.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum PaladinSpells { @@ -146,15 +148,8 @@ class spell_pal_ardent_defender : public SpellScriptLoader { PrepareAuraScript(spell_pal_ardent_defender_AuraScript); - public: - spell_pal_ardent_defender_AuraScript() - { - absorbPct = 0; - healPct = 0; - } - - private: - uint32 absorbPct, healPct; + uint32 _absorbPct = 0; + uint32 _healPct = 0; enum Spell { @@ -163,15 +158,13 @@ class spell_pal_ardent_defender : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(PAL_SPELL_ARDENT_DEFENDER_HEAL)) - return false; - return true; + return ValidateSpellInfo({ PAL_SPELL_ARDENT_DEFENDER_HEAL }); } bool Load() override { - healPct = GetSpellInfo()->Effects[EFFECT_1].CalcValue(); - absorbPct = GetSpellInfo()->Effects[EFFECT_0].CalcValue(); + _absorbPct = GetSpellInfo()->Effects[EFFECT_0].CalcValue(); + _healPct = GetSpellInfo()->Effects[EFFECT_1].CalcValue(); return GetUnitOwner()->GetTypeId() == TYPEID_PLAYER; } @@ -181,7 +174,7 @@ class spell_pal_ardent_defender : public SpellScriptLoader amount = -1; } - void Absorb(AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & absorbAmount) + void Absorb(AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& absorbAmount) { Unit* victim = GetTarget(); int32 remainingHealth = victim->GetHealth() - dmgInfo.GetDamage(); @@ -192,15 +185,13 @@ class spell_pal_ardent_defender : public SpellScriptLoader // Cast healing spell, completely avoid damage absorbAmount = dmgInfo.GetDamage(); - uint32 defenseSkillValue = victim->GetDefenseSkillValue(); + float defenseSkillValue = victim->GetDefenseSkillValue(); // Max heal when defense skill denies critical hits from raid bosses // Formula: max defense at level + 140 (raiting from gear) - uint32 reqDefForMaxHeal = victim->getLevel() * 5 + 140; - float pctFromDefense = (defenseSkillValue >= reqDefForMaxHeal) - ? 1.0f - : float(defenseSkillValue) / float(reqDefForMaxHeal); + float reqDefForMaxHeal = victim->GetMaxSkillValueForLevel() + 140.0f; + float defenseFactor = std::min(1.0f, defenseSkillValue / reqDefForMaxHeal); - int32 healAmount = int32(victim->CountPctFromMaxHealth(uint32(healPct * pctFromDefense))); + int32 healAmount = int32(victim->CountPctFromMaxHealth(static_cast(lroundf(_healPct * defenseFactor)))); victim->CastCustomSpell(PAL_SPELL_ARDENT_DEFENDER_HEAL, SPELLVALUE_BASE_POINT0, healAmount, victim, true, nullptr, aurEff); victim->GetSpellHistory()->AddCooldown(PAL_SPELL_ARDENT_DEFENDER_HEAL, 0, std::chrono::minutes(2)); } @@ -210,7 +201,7 @@ class spell_pal_ardent_defender : public SpellScriptLoader uint32 damageToReduce = (victim->GetHealth() < allowedHealth) ? dmgInfo.GetDamage() : allowedHealth - remainingHealth; - absorbAmount = CalculatePct(damageToReduce, absorbPct); + absorbAmount = CalculatePct(damageToReduce, _absorbPct); } } @@ -239,9 +230,7 @@ class spell_pal_aura_mastery : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_AURA_MASTERY_IMMUNE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_AURA_MASTERY_IMMUNE }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -279,9 +268,7 @@ class spell_pal_aura_mastery_immune : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_CONCENTRACTION_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_CONCENTRACTION_AURA }); } bool CheckAreaTarget(Unit* target) @@ -313,10 +300,11 @@ class spell_pal_avenging_wrath : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SANCTIFIED_WRATH) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_SANCTIFIED_WRATH_TALENT_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_SANCTIFIED_WRATH, + SPELL_PALADIN_SANCTIFIED_WRATH_TALENT_R1 + }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -325,7 +313,7 @@ class spell_pal_avenging_wrath : public SpellScriptLoader if (AuraEffect const* aurEff = target->GetAuraEffectOfRankedSpell(SPELL_PALADIN_SANCTIFIED_WRATH_TALENT_R1, EFFECT_2)) { int32 basepoints = aurEff->GetAmount(); - target->CastCustomSpell(target, SPELL_PALADIN_SANCTIFIED_WRATH, &basepoints, &basepoints, NULL, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_PALADIN_SANCTIFIED_WRATH, &basepoints, &basepoints, nullptr, true, nullptr, aurEff); } } @@ -359,9 +347,13 @@ class spell_pal_blessing_of_faith : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_DRUID) || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PALADIN) || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PRIEST) || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_SHAMAN)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_DRUID, + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PALADIN, + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PRIEST, + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_SHAMAN + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -416,11 +408,11 @@ class spell_pal_blessing_of_sanctuary : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_SANCTUARY_BUFF)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_SANCTUARY_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_BLESSING_OF_SANCTUARY_BUFF, + SPELL_PALADIN_BLESSING_OF_SANCTUARY_ENERGIZE + }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -444,7 +436,7 @@ class spell_pal_blessing_of_sanctuary : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_PALADIN_BLESSING_OF_SANCTUARY_ENERGIZE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_PALADIN_BLESSING_OF_SANCTUARY_ENERGIZE, true, nullptr, aurEff); } void Register() override @@ -558,32 +550,23 @@ class spell_pal_divine_storm : public SpellScriptLoader { PrepareSpellScript(spell_pal_divine_storm_SpellScript); - public: - spell_pal_divine_storm_SpellScript() - { - healPct = 0; - } - - private: - uint32 healPct; + uint32 _healPct = 0; bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_DIVINE_STORM_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_DIVINE_STORM_DUMMY }); } bool Load() override { - healPct = GetSpellInfo()->Effects[EFFECT_1].CalcValue(GetCaster()); + _healPct = GetSpellInfo()->Effects[EFFECT_1].CalcValue(GetCaster()); return true; } void TriggerHeal() { Unit* caster = GetCaster(); - caster->CastCustomSpell(SPELL_PALADIN_DIVINE_STORM_DUMMY, SPELLVALUE_BASE_POINT0, (GetHitDamage() * healPct) / 100, caster, true); + caster->CastCustomSpell(SPELL_PALADIN_DIVINE_STORM_DUMMY, SPELLVALUE_BASE_POINT0, (GetHitDamage() * _healPct) / 100, caster, true); } void Register() override @@ -608,18 +591,10 @@ class spell_pal_divine_storm_dummy : public SpellScriptLoader { PrepareSpellScript(spell_pal_divine_storm_dummy_SpellScript); - public: - spell_pal_divine_storm_dummy_SpellScript() - { - _targetCount = 0; - } - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_DIVINE_STORM_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_DIVINE_STORM_HEAL }); } void CountTargets(std::list& targetList) @@ -633,10 +608,10 @@ class spell_pal_divine_storm_dummy : public SpellScriptLoader return; int32 heal = GetEffectValue() / _targetCount; - GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_PALADIN_DIVINE_STORM_HEAL, &heal, NULL, NULL, true); + GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_PALADIN_DIVINE_STORM_HEAL, &heal, nullptr, nullptr, true); } - private: - uint32 _targetCount; + + uint32 _targetCount = 0; void Register() override { @@ -699,9 +674,7 @@ class spell_pal_eye_for_an_eye : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_EYE_FOR_AN_EYE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_EYE_FOR_AN_EYE_DAMAGE }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -740,9 +713,7 @@ class spell_pal_glyph_of_divinity : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_GLYPH_OF_DIVINITY_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_GLYPH_OF_DIVINITY_PROC }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -817,9 +788,7 @@ class spell_pal_glyph_of_holy_light_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_GLYPH_OF_HOLY_LIGHT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_GLYPH_OF_HOLY_LIGHT_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -860,9 +829,7 @@ class spell_pal_guarded_by_the_light : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_DIVINE_PLEA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_DIVINE_PLEA }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -980,9 +947,7 @@ class spell_pal_heart_of_the_crusader : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_HEART_OF_THE_CRUSADER_EFF_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_HEART_OF_THE_CRUSADER_EFF_R1 }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1089,11 +1054,12 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_SHOCK_R1_HEALING) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_ILLUMINATION_ENERGIZE) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_SHOCK_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_HOLY_SHOCK_R1_HEALING, + SPELL_PALADIN_ILLUMINATION_ENERGIZE, + SPELL_PALADIN_HOLY_SHOCK_R1 + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1153,11 +1119,12 @@ class spell_pal_improved_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_SANCTIFIED_RETRIBUTION_R1) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_SWIFT_RETRIBUTION_R1)) - return false; - return true; + return ValidateSpellInfo( + { + _spellId, + SPELL_PALADIN_SANCTIFIED_RETRIBUTION_R1, + SPELL_PALADIN_SWIFT_RETRIBUTION_R1 + }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1251,9 +1218,7 @@ class spell_pal_improved_lay_of_hands : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1286,11 +1251,12 @@ class spell_pal_infusion_of_light : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SACRED_SHIELD) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_T9_HOLY_4P_BONUS) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_FLASH_OF_LIGHT_PROC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_SACRED_SHIELD, + SPELL_PALADIN_T9_HOLY_4P_BONUS, + SPELL_PALADIN_FLASH_OF_LIGHT_PROC + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1353,15 +1319,13 @@ class spell_pal_item_healing_discount : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_ITEM_HEALING_TRANCE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_ITEM_HEALING_TRANCE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_PALADIN_ITEM_HEALING_TRANCE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_PALADIN_ITEM_HEALING_TRANCE, true, nullptr, aurEff); } void Register() override @@ -1388,10 +1352,11 @@ class spell_pal_item_t6_trinket : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_ENDURING_LIGHT) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_ENDURING_JUDGEMENT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_ENDURING_LIGHT, + SPELL_PALADIN_ENDURING_JUDGEMENT + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1450,12 +1415,14 @@ class spell_pal_judgement : public SpellScriptLoader public: spell_pal_judgement_SpellScript(uint32 spellId) : SpellScript(), _spellId(spellId) { } + private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_JUDGEMENT_DAMAGE) - || !sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_JUDGEMENT_DAMAGE, + _spellId + }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -1485,7 +1452,6 @@ class spell_pal_judgement : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_pal_judgement_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } - private: uint32 const _spellId; }; @@ -1512,7 +1478,7 @@ class spell_pal_judgement_of_command : public SpellScriptLoader { if (Unit* unitTarget = GetHitUnit()) if (SpellInfo const* spell_proto = sSpellMgr->GetSpellInfo(GetEffectValue())) - GetCaster()->CastSpell(unitTarget, spell_proto, true, NULL); + GetCaster()->CastSpell(unitTarget, spell_proto, true, nullptr); } void Register() override @@ -1539,9 +1505,7 @@ class spell_pal_judgement_of_light_heal : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_JUDGEMENT_OF_LIGHT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_JUDGEMENT_OF_LIGHT_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1578,9 +1542,7 @@ class spell_pal_judgement_of_wisdom_mana : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_JUDGEMENT_OF_WISDOM_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_JUDGEMENT_OF_WISDOM_MANA }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1624,9 +1586,7 @@ class spell_pal_judgements_of_the_just : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_JUDGEMENTS_OF_THE_JUST_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_JUDGEMENTS_OF_THE_JUST_PROC }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1659,10 +1619,11 @@ class spell_pal_judgements_of_the_wise : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_REPLENISHMENT) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_JUDGEMENTS_OF_THE_WISE_MANA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_REPLENISHMENT, + SPELL_PALADIN_JUDGEMENTS_OF_THE_WISE_MANA + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1698,13 +1659,12 @@ class spell_pal_lay_on_hands : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_FORBEARANCE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_AVENGING_WRATH_MARKER)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_IMMUNE_SHIELD_MARKER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_FORBEARANCE, + SPELL_PALADIN_AVENGING_WRATH_MARKER, + SPELL_PALADIN_IMMUNE_SHIELD_MARKER + }); } SpellCastResult CheckCast() @@ -1754,13 +1714,14 @@ class spell_pal_light_s_beacon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_BEACON_OF_LIGHT) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_1) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_2) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_3) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_LIGHT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_BEACON_OF_LIGHT, + SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_1, + SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_2, + SPELL_PALADIN_BEACON_OF_LIGHT_HEAL_3, + SPELL_PALADIN_HOLY_LIGHT + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1820,9 +1781,7 @@ class spell_pal_righteous_defense : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_RIGHTEOUS_DEFENSE_TAUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_RIGHTEOUS_DEFENSE_TAUNT }); } SpellCastResult CheckCast() @@ -1884,9 +1843,7 @@ class spell_pal_righteous_vengeance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_RIGHTEOUS_VENGEANCE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_RIGHTEOUS_VENGEANCE_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1977,10 +1934,11 @@ class spell_pal_sacred_shield_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SACRED_SHIELD_TRIGGER) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_T8_HOLY_4P_BONUS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_SACRED_SHIELD_TRIGGER, + SPELL_PALADIN_T8_HOLY_4P_BONUS + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2030,9 +1988,7 @@ class spell_pal_seal_of_righteousness : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2048,7 +2004,7 @@ class spell_pal_seal_of_righteousness : public SpellScriptLoader int32 holy = GetTarget()->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_HOLY); holy += eventInfo.GetProcTarget()->SpellBaseDamageBonusTaken(SPELL_SCHOOL_MASK_HOLY); int32 bp = int32((ap * 0.022f + 0.044f * holy) * GetTarget()->GetAttackTime(BASE_ATTACK) / 1000); - GetTarget()->CastCustomSpell(SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS, SPELLVALUE_BASE_POINT0, bp, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS, SPELLVALUE_BASE_POINT0, bp, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -2079,10 +2035,11 @@ class spell_pal_seal_of_vengeance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(DoTSpell) || - !sSpellMgr->GetSpellInfo(DamageSpell)) - return false; - return true; + return ValidateSpellInfo( + { + DoTSpell, + DamageSpell + }); } /* @@ -2205,9 +2162,7 @@ class spell_pal_spiritual_attunement : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SPIRITUAL_ATTUNEMENT_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_SPIRITUAL_ATTUNEMENT_MANA }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2253,9 +2208,7 @@ class spell_pal_sheath_of_light : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SHEATH_OF_LIGHT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_SHEATH_OF_LIGHT_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2302,12 +2255,13 @@ class spell_pal_t3_6p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_POWER_ARMOR) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_POWER_ATTACK_POWER) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_POWER_SPELL_POWER) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_POWER_MP5)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_HOLY_POWER_ARMOR, + SPELL_PALADIN_HOLY_POWER_ATTACK_POWER, + SPELL_PALADIN_HOLY_POWER_SPELL_POWER, + SPELL_PALADIN_HOLY_POWER_MP5 + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2368,9 +2322,7 @@ class spell_pal_t8_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_MENDING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_HOLY_MENDING }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_pet.cpp b/src/server/scripts/Spells/spell_pet.cpp index abe40cc2c7d..1386a212322 100644 --- a/src/server/scripts/Spells/spell_pet.cpp +++ b/src/server/scripts/Spells/spell_pet.cpp @@ -22,11 +22,13 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" +#include "ObjectMgr.h" +#include "Pet.h" +#include "Player.h" #include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" #include "Unit.h" -#include "Player.h" -#include "Pet.h" enum HunterPetCalculate { @@ -1497,13 +1499,6 @@ public: { PrepareAuraScript(spell_dk_pet_scaling_01_AuraScript); - public: - spell_dk_pet_scaling_01_AuraScript() - { - _tempHealth = 0; - } - - private: bool Load() override { if (!GetCaster() || !GetCaster()->GetOwner() || GetCaster()->GetOwner()->GetTypeId() != TYPEID_PLAYER) @@ -1563,7 +1558,7 @@ public: float mod = 0.7f; // Ravenous Dead - AuraEffect const* aurEff = NULL; + AuraEffect const* aurEff = nullptr; // Check just if owner has Ravenous Dead since it's effect is not an aura aurEff = owner->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DEATHKNIGHT, 3010, 0); if (aurEff) @@ -1587,8 +1582,7 @@ public: DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_dk_pet_scaling_01_AuraScript::CalculateStrengthAmount, EFFECT_1, SPELL_AURA_MOD_STAT); } - private: - uint32 _tempHealth; + uint32 _tempHealth = 0; }; AuraScript* GetAuraScript() const override diff --git a/src/server/scripts/Spells/spell_priest.cpp b/src/server/scripts/Spells/spell_priest.cpp index cd8aa4138a0..4ba231b021c 100644 --- a/src/server/scripts/Spells/spell_priest.cpp +++ b/src/server/scripts/Spells/spell_priest.cpp @@ -21,11 +21,12 @@ * Scriptnames of files in this file should be prefixed with "spell_pri_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum PriestSpells { @@ -115,9 +116,7 @@ class spell_pri_aq_3p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_ORACULAR_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_ORACULAR_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -159,9 +158,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_BLESSED_RECOVERY_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_BLESSED_RECOVERY_R1 }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -205,10 +202,11 @@ class spell_pri_body_and_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_BODY_AND_SOUL_POISON_TRIGGER) || - !sSpellMgr->GetSpellInfo(SPELL_PRIEST_ABOLISH_DISEASE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_BODY_AND_SOUL_POISON_TRIGGER, + SPELL_PRIEST_ABOLISH_DISEASE + }); } void HandleProcTriggerSpell(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -264,9 +262,7 @@ class spell_pri_circle_of_healing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_CIRCLE_OF_HEALING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GLYPH_OF_CIRCLE_OF_HEALING }); } void FilterTargets(std::list& targets) @@ -306,9 +302,7 @@ class spell_pri_divine_aegis : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_DIVINE_AEGIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_DIVINE_AEGIS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -395,9 +389,7 @@ class spell_pri_glyph_of_dispel_magic : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_DISPEL_MAGIC_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GLYPH_OF_DISPEL_MAGIC_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -439,9 +431,7 @@ class spell_pri_glyph_of_prayer_of_healing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -479,20 +469,11 @@ class spell_pri_guardian_spirit : public SpellScriptLoader { PrepareAuraScript(spell_pri_guardian_spirit_AuraScript); - public: - spell_pri_guardian_spirit_AuraScript() - { - healPct = 0; - } - - private: - uint32 healPct; + uint32 healPct = 0; bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL }); } bool Load() override @@ -516,7 +497,7 @@ class spell_pri_guardian_spirit : public SpellScriptLoader int32 healAmount = int32(target->CountPctFromMaxHealth(healPct)); // remove the aura now, we don't want 40% healing bonus Remove(AURA_REMOVE_BY_ENEMY_SPELL); - target->CastCustomSpell(target, SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL, &healAmount, NULL, NULL, true); + target->CastCustomSpell(target, SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL, &healAmount, nullptr, nullptr, true); absorbAmount = dmgInfo.GetDamage(); } @@ -610,10 +591,11 @@ class spell_pri_improved_spirit_tap : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_SHADOW_WORD_DEATH_R1) || - !sSpellMgr->GetSpellInfo(SPELL_PRIEST_MIND_BLAST_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_SHADOW_WORD_DEATH_R1, + SPELL_PRIEST_MIND_BLAST_R1 + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -654,10 +636,11 @@ class spell_pri_item_t6_trinket : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_DIVINE_BLESSING) || - !sSpellMgr->GetSpellInfo(SPELL_PRIEST_DIVINE_WRATH)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_DIVINE_BLESSING, + SPELL_PRIEST_DIVINE_WRATH + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -780,18 +763,9 @@ class spell_pri_mana_leech : public SpellScriptLoader { PrepareAuraScript(spell_pri_mana_leech_AuraScript); - public: - spell_pri_mana_leech_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_MANA_LEECH_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_MANA_LEECH_PROC }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -803,7 +777,7 @@ class spell_pri_mana_leech : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(_procTarget, SPELL_PRIEST_MANA_LEECH_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_PRIEST_MANA_LEECH_PROC, true, nullptr, aurEff); } void Register() override @@ -812,8 +786,7 @@ class spell_pri_mana_leech : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_pri_mana_leech_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -1003,11 +976,11 @@ class spell_pri_power_word_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_REFLECTIVE_SHIELD_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED, + SPELL_PRIEST_REFLECTIVE_SHIELD_R1 + }); } void CalculateAmount(AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated) @@ -1049,7 +1022,7 @@ class spell_pri_power_word_shield : public SpellScriptLoader if (AuraEffect* talentAurEff = target->GetAuraEffectOfRankedSpell(SPELL_PRIEST_REFLECTIVE_SHIELD_R1, EFFECT_0)) { int32 bp = CalculatePct(absorbAmount, talentAurEff->GetAmount()); - target->CastCustomSpell(dmgInfo.GetAttacker(), SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED, &bp, NULL, NULL, true, NULL, aurEff); + target->CastCustomSpell(dmgInfo.GetAttacker(), SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED, &bp, nullptr, nullptr, true, nullptr, aurEff); } } @@ -1127,7 +1100,8 @@ class spell_pri_renew : public SpellScriptLoader { int32 heal = (aurEff->GetAmount() + aurEff->GetBonusAmount()) * aurEff->GetDonePct(); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), heal); + modOwner->ApplySpellMod(GetId(), SPELLMOD_DOT, heal); + heal = GetTarget()->SpellHealingBonusTaken(caster, GetSpellInfo(), heal, DOT); heal *= GetSpellInfo()->GetMaxTicks(); @@ -1161,9 +1135,7 @@ class spell_pri_shadowfiend_death : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_SHADOWFIEND_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GLYPH_OF_SHADOWFIEND_MANA }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1244,9 +1216,7 @@ class spell_pri_vampiric_embrace : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_VAMPIRIC_EMBRACE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_VAMPIRIC_EMBRACE_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1286,10 +1256,11 @@ class spell_pri_vampiric_touch : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_VAMPIRIC_TOUCH_DISPEL) || - !sSpellMgr->GetSpellInfo(SPELL_REPLENISHMENT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_VAMPIRIC_TOUCH_DISPEL, + SPELL_REPLENISHMENT + }); } bool CheckDummy(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -1346,9 +1317,7 @@ class spell_pri_t3_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_ARMOR_OF_FAITH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_ARMOR_OF_FAITH }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1381,9 +1350,7 @@ class spell_pri_t5_heal_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_ITEM_EFFICIENCY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_ITEM_EFFICIENCY }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1428,9 +1395,7 @@ class spell_pri_t10_heal_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_BLESSED_HEALING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_BLESSED_HEALING }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_quest.cpp b/src/server/scripts/Spells/spell_quest.cpp index 4b3074888cb..72e29df22f8 100644 --- a/src/server/scripts/Spells/spell_quest.cpp +++ b/src/server/scripts/Spells/spell_quest.cpp @@ -21,15 +21,15 @@ * Scriptnames of files in this file should be prefixed with "spell_q#questID_". */ +#include "ScriptMgr.h" #include "CellImpl.h" +#include "CreatureAIImpl.h" #include "CreatureTextMgr.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Player.h" -#include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "Vehicle.h" class spell_generic_quest_update_entry_SpellScript : public SpellScript @@ -104,9 +104,7 @@ class spell_q2203_thaumaturgy_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_THAUMATURGY_CHANNEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_THAUMATURGY_CHANNEL }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -152,16 +150,14 @@ class spell_q5206_test_fetid_skull : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_RESONATING_SKULL) || !sSpellMgr->GetSpellInfo(SPELL_CREATE_BONE_DUST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CREATE_RESONATING_SKULL, SPELL_CREATE_BONE_DUST }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = roll_chance_i(50) ? SPELL_CREATE_RESONATING_SKULL : SPELL_CREATE_BONE_DUST; - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -316,9 +312,7 @@ class spell_q11396_11399_scourging_crystal_controller : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3) || !sSpellMgr->GetSpellInfo(SPELL_SCOURGING_CRYSTAL_CONTROLLER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3, SPELL_SCOURGING_CRYSTAL_CONTROLLER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -354,9 +348,7 @@ class spell_q11396_11399_scourging_crystal_controller_dummy : public SpellScript bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -417,9 +409,7 @@ class spell_q11587_arcane_prisoner_rescue : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ARCANE_PRISONER_MALE) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_ARCANE_PRISONER_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_ARCANE_PRISONER_KILL_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ARCANE_PRISONER_MALE, SPELL_SUMMON_ARCANE_PRISONER_FEMALE, SPELL_ARCANE_PRISONER_KILL_CREDIT }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -480,9 +470,15 @@ class spell_q11730_ultrasonic_screwdriver : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SCAVENGEBOT_004A8) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SENTRYBOT_57K) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_DEFENDOTANK_66D) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SCAVENGEBOT_005B6) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_55D_COLLECTATRON) || !sSpellMgr->GetSpellInfo(SPELL_ROBOT_KILL_CREDIT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SUMMON_SCAVENGEBOT_004A8, + SPELL_SUMMON_SENTRYBOT_57K, + SPELL_SUMMON_DEFENDOTANK_66D, + SPELL_SUMMON_SCAVENGEBOT_005B6, + SPELL_SUMMON_55D_COLLECTATRON, + SPELL_ROBOT_KILL_CREDIT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -592,9 +588,13 @@ class spell_q12634_despawn_fruit_tosser : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BANANAS_FALL_TO_GROUND) || !sSpellMgr->GetSpellInfo(SPELL_ORANGE_FALLS_TO_GROUND) || !sSpellMgr->GetSpellInfo(SPELL_PAPAYA_FALLS_TO_GROUND) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_ADVENTUROUS_DWARF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_BANANAS_FALL_TO_GROUND, + SPELL_ORANGE_FALLS_TO_GROUND, + SPELL_PAPAYA_FALLS_TO_GROUND, + SPELL_SUMMON_ADVENTUROUS_DWARF + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -608,7 +608,7 @@ class spell_q12634_despawn_fruit_tosser : public SpellScriptLoader // sometimes, if you're lucky, you get a dwarf if (roll_chance_i(5)) spellId = SPELL_SUMMON_ADVENTUROUS_DWARF; - GetCaster()->CastSpell(GetCaster(), spellId, true, NULL); + GetCaster()->CastSpell(GetCaster(), spellId, true, nullptr); } void Register() override @@ -642,7 +642,7 @@ class spell_q12683_take_sputum_sample : public SpellScriptLoader if (caster->HasAuraEffect(reqAuraId, 0)) { uint32 spellId = GetSpellInfo()->Effects[EFFECT_0].CalcValue(); - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } } @@ -744,9 +744,7 @@ class spell_q12937_relief_for_the_fallen : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRIGGER_AID_OF_THE_EARTHEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TRIGGER_AID_OF_THE_EARTHEN }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -754,7 +752,7 @@ class spell_q12937_relief_for_the_fallen : public SpellScriptLoader Player* caster = GetCaster()->ToPlayer(); if (Creature* target = GetHitCreature()) { - caster->CastSpell(caster, SPELL_TRIGGER_AID_OF_THE_EARTHEN, true, NULL); + caster->CastSpell(caster, SPELL_TRIGGER_AID_OF_THE_EARTHEN, true, nullptr); caster->KilledMonsterCredit(NPC_FALLEN_EARTHEN_DEFENDER); target->DespawnOrUnsummon(); } @@ -790,9 +788,7 @@ class spell_q10041_q10040_who_are_they : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MALE_DISGUISE) || !sSpellMgr->GetSpellInfo(SPELL_FEMALE_DISGUISE) || !sSpellMgr->GetSpellInfo(SPELL_GENERIC_DISGUISE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MALE_DISGUISE, SPELL_FEMALE_DISGUISE, SPELL_GENERIC_DISGUISE }); } void HandleScript(SpellEffIndex effIndex) @@ -1051,9 +1047,7 @@ class spell_q14112_14145_chum_the_water: public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SUMMON_ANGRY_KVALDIR) || !sSpellMgr->GetSpellInfo(SUMMON_NORTH_SEA_MAKO) || !sSpellMgr->GetSpellInfo(SUMMON_NORTH_SEA_THRESHER) || !sSpellMgr->GetSpellInfo(SUMMON_NORTH_SEA_BLUE_SHARK)) - return false; - return true; + return ValidateSpellInfo({ SUMMON_ANGRY_KVALDIR, SUMMON_NORTH_SEA_MAKO, SUMMON_NORTH_SEA_THRESHER, SUMMON_NORTH_SEA_BLUE_SHARK }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -1662,16 +1656,14 @@ class spell_q12527_zuldrak_rat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_GORGED_LURKING_BASILISK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_GORGED_LURKING_BASILISK }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) { if (GetHitAura() && GetHitAura()->GetStackAmount() >= GetSpellInfo()->StackAmount) { - GetHitUnit()->CastSpell((Unit*) NULL, SPELL_SUMMON_GORGED_LURKING_BASILISK, true); + GetHitUnit()->CastSpell((Unit*) nullptr, SPELL_SUMMON_GORGED_LURKING_BASILISK, true); if (Creature* basilisk = GetHitUnit()->ToCreature()) basilisk->DespawnOrUnsummon(); } @@ -1734,9 +1726,7 @@ class spell_q12730_quenching_mist : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLICKERING_FLAMES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLICKERING_FLAMES }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -1777,10 +1767,7 @@ class spell_q13291_q13292_q13239_q13261_frostbrood_skytalon_grab_decoy : public bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_RIDE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1864,9 +1851,8 @@ class spell_q12847_summon_soul_moveto_bunny : public SpellScriptLoader enum BearFlankMaster { - SPELL_BEAR_FLANK_MASTER = 56565, SPELL_CREATE_BEAR_FLANK = 56566, - SPELL_BEAR_FLANK_FAIL = 56569 + SPELL_BEAR_FLANK_FAIL = 56569 }; class spell_q13011_bear_flank_master : public SpellScriptLoader @@ -1880,10 +1866,11 @@ class spell_q13011_bear_flank_master : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BEAR_FLANK_MASTER) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_BEAR_FLANK)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CREATE_BEAR_FLANK, + SPELL_BEAR_FLANK_FAIL + }); } bool Load() override @@ -1929,9 +1916,7 @@ class spell_q13086_cannons_target : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleEffectDummy(SpellEffIndex /*effIndex*/) @@ -1980,14 +1965,15 @@ class spell_q12690_burst_at_the_seams : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_DMG) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_DMG_2) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_BONE) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_MEAT) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_BMEAT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_BURST_AT_THE_SEAMS, + SPELL_BURST_AT_THE_SEAMS_DMG, + SPELL_BURST_AT_THE_SEAMS_DMG_2, + SPELL_BURST_AT_THE_SEAMS_BONE, + SPELL_BURST_AT_THE_SEAMS_MEAT, + SPELL_BURST_AT_THE_SEAMS_BMEAT + }); } bool Load() override @@ -2056,9 +2042,7 @@ class spell_q12308_escape_from_silverbrook : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_WORGEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_WORGEN }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2134,12 +2118,13 @@ class spell_q12641_death_comes_from_on_high : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORGE_CREDIT) || - !sSpellMgr->GetSpellInfo(SPELL_TOWN_HALL_CREDIT) || - !sSpellMgr->GetSpellInfo(SPELL_SCARLET_HOLD_CREDIT) || - !sSpellMgr->GetSpellInfo(SPELL_CHAPEL_CREDIT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FORGE_CREDIT, + SPELL_TOWN_HALL_CREDIT, + SPELL_SCARLET_HOLD_CREDIT, + SPELL_CHAPEL_CREDIT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2164,7 +2149,7 @@ class spell_q12641_death_comes_from_on_high : public SpellScriptLoader return; } - GetCaster()->CastSpell((Unit*)NULL, spellId, true); + GetCaster()->CastSpell((Unit*)nullptr, spellId, true); } void Register() override @@ -2230,7 +2215,7 @@ class spell_q12619_emblazon_runeblade : public SpellScriptLoader { PreventDefaultAction(); if (Unit* caster = GetCaster()) - caster->CastSpell(caster, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, NULL, aurEff); + caster->CastSpell(caster, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, nullptr, aurEff); } void Register() override @@ -2289,9 +2274,7 @@ class spell_q12919_gymers_grab : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE_GYMER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RIDE_GYMER }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2368,9 +2351,7 @@ class spell_q13400_illidan_kill_master : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ILLIDAN_KILL_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ILLIDAN_KILL_CREDIT }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2410,9 +2391,7 @@ class spell_q14100_q14111_make_player_destroy_totems : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TOTEM_OF_THE_EARTHEN_RING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TOTEM_OF_THE_EARTHEN_RING }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -2451,11 +2430,7 @@ class spell_q10929_fumping : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SAND_GNOME)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BONE_SLICER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SAND_GNOME, SPELL_SUMMON_BONE_SLICER }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Spells/spell_rogue.cpp b/src/server/scripts/Spells/spell_rogue.cpp index 4d9f32de2db..750b5073a7c 100644 --- a/src/server/scripts/Spells/spell_rogue.cpp +++ b/src/server/scripts/Spells/spell_rogue.cpp @@ -21,12 +21,17 @@ * Scriptnames of files in this file should be prefixed with "spell_rog_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "Containers.h" +#include "DBCStores.h" +#include "Item.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "SpellAuraEffects.h" #include "SpellHistory.h" -#include "Containers.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum RogueSpells { @@ -60,18 +65,9 @@ class spell_rog_blade_flurry : public SpellScriptLoader { PrepareAuraScript(spell_rog_blade_flurry_AuraScript); - public: - spell_rog_blade_flurry_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_BLADE_FLURRY_EXTRA_ATTACK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_BLADE_FLURRY_EXTRA_ATTACK }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -96,8 +92,7 @@ class spell_rog_blade_flurry : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_rog_blade_flurry_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_MOD_MELEE_HASTE); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -116,20 +111,11 @@ class spell_rog_cheat_death : public SpellScriptLoader { PrepareAuraScript(spell_rog_cheat_death_AuraScript); - public: - spell_rog_cheat_death_AuraScript() - { - absorbChance = 0; - } - - private: - uint32 absorbChance; + uint32 absorbChance = 0; bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_CHEAT_DEATH_COOLDOWN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_CHEAT_DEATH_COOLDOWN }); } bool Load() override @@ -227,9 +213,7 @@ class spell_rog_deadly_brew : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_CRIPPLING_POISON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_CRIPPLING_POISON }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -260,13 +244,6 @@ class spell_rog_deadly_poison : public SpellScriptLoader { PrepareSpellScript(spell_rog_deadly_poison_SpellScript); - public: - spell_rog_deadly_poison_SpellScript() - { - _stackAmount = 0; - } - - private: bool Load() override { // at this point CastItem must already be initialized @@ -341,7 +318,7 @@ class spell_rog_deadly_poison : public SpellScriptLoader AfterHit += SpellHitFn(spell_rog_deadly_poison_SpellScript::HandleAfterHit); } - uint8 _stackAmount; + uint8 _stackAmount = 0; }; SpellScript* GetSpellScript() const override @@ -351,11 +328,12 @@ class spell_rog_deadly_poison : public SpellScriptLoader }; // 51690 - Killing Spree -#define KillingSpreeScriptName "spell_rog_killing_spree" class spell_rog_killing_spree : public SpellScriptLoader { public: - spell_rog_killing_spree() : SpellScriptLoader(KillingSpreeScriptName) { } + static char constexpr const ScriptName[] = "spell_rog_killing_spree"; + + spell_rog_killing_spree() : SpellScriptLoader(ScriptName) { } class spell_rog_killing_spree_SpellScript : public SpellScript { @@ -370,10 +348,8 @@ class spell_rog_killing_spree : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { if (Aura* aura = GetCaster()->GetAura(SPELL_ROGUE_KILLING_SPREE)) - { - if (spell_rog_killing_spree_AuraScript* script = dynamic_cast(aura->GetScriptByName(KillingSpreeScriptName))) + if (spell_rog_killing_spree_AuraScript* script = aura->GetScript(ScriptName)) script->AddTarget(GetHitUnit()); - } } void Register() override @@ -394,11 +370,12 @@ class spell_rog_killing_spree : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_KILLING_SPREE_TELEPORT) - || !sSpellMgr->GetSpellInfo(SPELL_ROGUE_KILLING_SPREE_WEAPON_DMG) - || !sSpellMgr->GetSpellInfo(SPELL_ROGUE_KILLING_SPREE_DMG_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROGUE_KILLING_SPREE_TELEPORT, + SPELL_ROGUE_KILLING_SPREE_WEAPON_DMG, + SPELL_ROGUE_KILLING_SPREE_DMG_BUFF + }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -449,6 +426,7 @@ class spell_rog_killing_spree : public SpellScriptLoader return new spell_rog_killing_spree_AuraScript(); } }; +char constexpr const spell_rog_killing_spree::ScriptName[]; // -31130 - Nerves of Steel class spell_rog_nerves_of_steel : public SpellScriptLoader @@ -518,9 +496,7 @@ class spell_rog_preparation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_GLYPH_OF_PREPARATION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_GLYPH_OF_PREPARATION }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -566,9 +542,7 @@ class spell_rog_prey_on_the_weak : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_PREY_ON_THE_WEAK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_PREY_ON_THE_WEAK }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -611,9 +585,7 @@ class spell_rog_quick_recovery : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_QUICK_RECOVERY_ENERGY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_QUICK_RECOVERY_ENERGY }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -641,11 +613,12 @@ class spell_rog_quick_recovery : public SpellScriptLoader }; // -1943 - Rupture -static char const* const RuptureScriptName = "spell_rog_rupture"; class spell_rog_rupture : public SpellScriptLoader { public: - spell_rog_rupture() : SpellScriptLoader(RuptureScriptName) { } + static char constexpr const ScriptName[] = "spell_rog_rupture"; + + spell_rog_rupture() : SpellScriptLoader(ScriptName) { } class spell_rog_rupture_AuraScript : public AuraScript { @@ -703,6 +676,7 @@ class spell_rog_rupture : public SpellScriptLoader return new spell_rog_rupture_AuraScript(); } }; +char constexpr const spell_rog_rupture::ScriptName[]; // 56800 - Glyph of Backstab (dummy) class spell_rog_glyph_of_backstab : public SpellScriptLoader @@ -716,9 +690,7 @@ class spell_rog_glyph_of_backstab : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_GLYPH_OF_BACKSTAB_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_GLYPH_OF_BACKSTAB_TRIGGER }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -759,7 +731,7 @@ class spell_rog_glyph_of_backstab_triggered : public SpellScriptLoader // search our Rupture aura on target if (AuraEffect* aurEff = GetHitUnit()->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x00100000, 0, 0, caster->GetGUID())) { - RuptureAuraScript* ruptureAuraScript = dynamic_cast(aurEff->GetBase()->GetScriptByName(RuptureScriptName)); + RuptureAuraScript* ruptureAuraScript = aurEff->GetBase()->GetScript(spell_rog_rupture::ScriptName); if (!ruptureAuraScript) return; @@ -843,9 +815,7 @@ class spell_rog_shiv : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_SHIV_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_SHIV_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -877,20 +847,13 @@ class spell_rog_tricks_of_the_trade : public SpellScriptLoader { PrepareAuraScript(spell_rog_tricks_of_the_trade_AuraScript); - public: - spell_rog_tricks_of_the_trade_AuraScript() - { - _redirectTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_TRICKS_OF_THE_TRADE_DMG_BOOST)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_TRICKS_OF_THE_TRADE_PROC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROGUE_TRICKS_OF_THE_TRADE_DMG_BOOST, + SPELL_ROGUE_TRICKS_OF_THE_TRADE_PROC + }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -922,8 +885,7 @@ class spell_rog_tricks_of_the_trade : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_rog_tricks_of_the_trade_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_DUMMY); } - private: - Unit* _redirectTarget; + Unit* _redirectTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -971,10 +933,11 @@ public: bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_HONOR_AMONG_THIEVES_2) || - !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROGUE_HONOR_AMONG_THIEVES_2, + spellInfo->Effects[EFFECT_0].TriggerSpell + }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -1023,10 +986,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_HONOR_AMONG_THIEVES_PROC)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ROGUE_HONOR_AMONG_THIEVES_PROC }); } void FilterTargets(std::list& targets) @@ -1089,9 +1049,7 @@ class spell_rog_turn_the_tables : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) diff --git a/src/server/scripts/Spells/spell_shaman.cpp b/src/server/scripts/Spells/spell_shaman.cpp index 0b93927ecd0..5b89beaee2c 100644 --- a/src/server/scripts/Spells/spell_shaman.cpp +++ b/src/server/scripts/Spells/spell_shaman.cpp @@ -21,13 +21,17 @@ * Scriptnames of files in this file should be prefixed with "spell_sha_". */ -#include "Player.h" #include "ScriptMgr.h" #include "GridNotifiers.h" -#include "Unit.h" +#include "Item.h" +#include "ObjectAccessor.h" +#include "Map.h" +#include "Player.h" +#include "SpellAuraEffects.h" #include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "Unit.h" enum ShamanSpells { @@ -106,9 +110,7 @@ class spell_sha_ancestral_awakening : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ANCESTRAL_AWAKENING_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ANCESTRAL_AWAKENING_DUMMY }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -146,9 +148,7 @@ class spell_sha_ancestral_awakening_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ANCESTRAL_AWAKENING_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ANCESTRAL_AWAKENING_PROC }); } void FilterTargets(std::list& targets) @@ -167,7 +167,7 @@ class spell_sha_ancestral_awakening_proc : public SpellScriptLoader { int32 damage = GetEffectValue(); if (GetHitUnit()) - GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_SHAMAN_ANCESTRAL_AWAKENING_PROC, &damage, NULL, NULL, true); + GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_SHAMAN_ANCESTRAL_AWAKENING_PROC, &damage, nullptr, nullptr, true); } void Register() override @@ -277,9 +277,7 @@ class spell_sha_bloodlust : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_SATED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_SATED }); } void RemoveInvalidTargets(std::list& targets) @@ -371,16 +369,14 @@ class spell_sha_cleansing_totem_pulse : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_CLEANSING_TOTEM_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_CLEANSING_TOTEM_EFFECT }); } void HandleDummy(SpellEffIndex /*effIndex*/) { int32 bp = 1; if (GetCaster() && GetHitUnit() && GetOriginalCaster()) - GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_SHAMAN_CLEANSING_TOTEM_EFFECT, NULL, &bp, NULL, true, NULL, NULL, GetOriginalCaster()->GetGUID()); + GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_SHAMAN_CLEANSING_TOTEM_EFFECT, nullptr, &bp, nullptr, true, nullptr, nullptr, GetOriginalCaster()->GetGUID()); } void Register() override @@ -407,9 +403,7 @@ class spell_sha_earth_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_EARTH_SHIELD_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_EARTH_SHIELD_HEAL }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) @@ -451,9 +445,7 @@ class spell_sha_earthbind_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_EARTHBIND_TOTEM) || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_EARTHEN_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TOTEM_EARTHBIND_TOTEM, SPELL_SHAMAN_TOTEM_EARTHEN_POWER }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -463,7 +455,7 @@ class spell_sha_earthbind_totem : public SpellScriptLoader if (Player* owner = GetCaster()->GetCharmerOrOwnerPlayerOrPlayerItself()) if (AuraEffect* aur = owner->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 2289, 0)) if (roll_chance_i(aur->GetBaseAmount())) - GetTarget()->CastSpell((Unit*)NULL, SPELL_SHAMAN_TOTEM_EARTHEN_POWER, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_SHAMAN_TOTEM_EARTHEN_POWER, true); } void Apply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -550,9 +542,7 @@ class spell_sha_earthliving_weapon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_BLESSING_OF_THE_ETERNALS_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_BLESSING_OF_THE_ETERNALS_R1 }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -648,11 +638,7 @@ class spell_sha_flame_shock : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_FLOWS_R1)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LAVA_FLOWS_R1, SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1 }); } void HandleDispel(DispelInfo* /*dispelInfo*/) @@ -694,9 +680,7 @@ class spell_sha_flametongue_weapon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_FLAMETONGUE_ATTACK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_FLAMETONGUE_ATTACK }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -778,9 +762,7 @@ class spell_sha_frozen_power : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_FREEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_FREEZE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -864,9 +846,7 @@ class spell_sha_glyph_of_healing_wave : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_GLYPH_OF_HEALING_WAVE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_GLYPH_OF_HEALING_WAVE_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -908,9 +888,7 @@ class spell_sha_glyph_of_totem_of_wrath : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_OF_WRATH_SPELL_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TOTEM_OF_WRATH_SPELL_POWER }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -969,9 +947,7 @@ class spell_sha_healing_stream_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_GLYPH_OF_HEALING_STREAM_TOTEM) || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_HEALING_STREAM_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_GLYPH_OF_HEALING_STREAM_TOTEM, SPELL_SHAMAN_TOTEM_HEALING_STREAM_HEAL }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1027,9 +1003,7 @@ class spell_sha_heroism : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_EXHAUSTION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_EXHAUSTION }); } void RemoveInvalidTargets(std::list& targets) @@ -1129,10 +1103,11 @@ class spell_sha_lightning_overload : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LIGHTNING_BOLT_OVERLOAD_R1) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_CHAIN_LIGHTNING_OVERLOAD_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_LIGHTNING_BOLT_OVERLOAD_R1, + SPELL_SHAMAN_CHAIN_LIGHTNING_OVERLOAD_R1 + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1188,9 +1163,7 @@ class spell_sha_item_lightning_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1223,9 +1196,7 @@ class spell_sha_item_lightning_shield_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -1258,9 +1229,7 @@ class spell_sha_item_mana_surge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_MANA_SURGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ITEM_MANA_SURGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1300,10 +1269,11 @@ class spell_sha_item_t6_trinket : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ENERGY_SURGE) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_POWER_SURGE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_ENERGY_SURGE, + SPELL_SHAMAN_POWER_SURGE + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1365,9 +1335,7 @@ class spell_sha_item_t10_elemental_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ELEMENTAL_MASTERY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ELEMENTAL_MASTERY }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -1446,9 +1414,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LIGHTNING_SHIELD_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LIGHTNING_SHIELD_R1 }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1491,10 +1457,11 @@ class spell_sha_maelstrom_weapon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_MAELSTROM_POWER) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_T10_ENHANCEMENT_4P_BONUS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_MAELSTROM_POWER, + SPELL_SHAMAN_T10_ENHANCEMENT_4P_BONUS + }); } void HandleBonus(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1534,9 +1501,7 @@ class spell_sha_mana_spring_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_MANA_SPRING_TOTEM_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_MANA_SPRING_TOTEM_ENERGIZE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1573,9 +1538,7 @@ class spell_sha_mana_tide_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_GLYPH_OF_MANA_TIDE) || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_MANA_TIDE_TOTEM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_GLYPH_OF_MANA_TIDE, SPELL_SHAMAN_MANA_TIDE_TOTEM }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1623,9 +1586,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_NATURE_GUARDIAN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_NATURE_GUARDIAN }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1676,9 +1637,7 @@ class spell_sha_sentry_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_BIND_SIGHT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_BIND_SIGHT }); } void AfterApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1721,9 +1680,7 @@ class spell_sha_shamanistic_rage : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_SHAMANISTIC_RAGE_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_SHAMANISTIC_RAGE_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -1759,9 +1716,7 @@ class spell_sha_spirit_hunt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_SPIRIT_HUNT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_SPIRIT_HUNT_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1805,9 +1760,7 @@ class spell_sha_static_shock : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LIGHTNING_SHIELD_DAMAGE_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LIGHTNING_SHIELD_DAMAGE_R1 }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1850,9 +1803,7 @@ class spell_sha_tidal_force_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TIDAL_FORCE_CRIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TIDAL_FORCE_CRIT }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -1914,9 +1865,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEMIC_MASTERY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TOTEMIC_MASTERY }); } void HandleDummy(AuraEffect const* aurEff) @@ -1954,12 +1903,13 @@ class spell_sha_t3_6p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEMIC_POWER_ARMOR) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEMIC_POWER_ATTACK_POWER) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEMIC_POWER_SPELL_POWER) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEMIC_POWER_MP5)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_TOTEMIC_POWER_ARMOR, + SPELL_SHAMAN_TOTEMIC_POWER_ATTACK_POWER, + SPELL_SHAMAN_TOTEMIC_POWER_SPELL_POWER, + SPELL_SHAMAN_TOTEMIC_POWER_MP5 + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2020,9 +1970,7 @@ class spell_sha_t8_elemental_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ELECTRIFIED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ELECTRIFIED }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2069,9 +2017,7 @@ class spell_sha_t9_elemental_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_BURST_BONUS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LAVA_BURST_BONUS_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2163,9 +2109,7 @@ class spell_sha_t10_restoration_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_CHAINED_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_CHAINED_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2212,11 +2156,12 @@ class spell_sha_windfury_weapon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_WINDFURY_WEAPON_R1) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_WINDFURY_ATTACK_MH) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_WINDFURY_ATTACK_OH)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_WINDFURY_WEAPON_R1, + SPELL_SHAMAN_WINDFURY_ATTACK_MH, + SPELL_SHAMAN_WINDFURY_ATTACK_OH + }); } bool CheckProc(ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_warlock.cpp b/src/server/scripts/Spells/spell_warlock.cpp index 1f8954d0da7..1b602210889 100644 --- a/src/server/scripts/Spells/spell_warlock.cpp +++ b/src/server/scripts/Spells/spell_warlock.cpp @@ -21,10 +21,16 @@ * Scriptnames of files in this file should be prefixed with "spell_warl_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "Creature.h" +#include "GameObject.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Random.h" #include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum WarlockSpells { @@ -152,9 +158,7 @@ class spell_warl_create_healthstone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMPROVED_HEALTHSTONE_R1) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMPROVED_HEALTHSTONE_R2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_IMPROVED_HEALTHSTONE_R1, SPELL_WARLOCK_IMPROVED_HEALTHSTONE_R2 }); } SpellCastResult CheckCast() @@ -163,7 +167,7 @@ class spell_warl_create_healthstone : public SpellScriptLoader { uint8 spellRank = GetSpellInfo()->GetRank(); ItemPosCountVec dest; - InventoryResult msg = caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, iTypes[spellRank - 1][0], 1, NULL); + InventoryResult msg = caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, iTypes[spellRank - 1][0], 1, nullptr); if (msg != EQUIP_ERR_OK) return SPELL_FAILED_TOO_MANY_OF_ITEM; } @@ -233,9 +237,7 @@ class spell_warl_curse_of_doom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_CURSE_OF_DOOM_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_CURSE_OF_DOOM_EFFECT }); } bool Load() override @@ -253,7 +255,7 @@ class spell_warl_curse_of_doom : public SpellScriptLoader return; if (GetCaster()->ToPlayer()->isHonorOrXPTarget(GetTarget())) - GetCaster()->CastSpell(GetTarget(), SPELL_WARLOCK_CURSE_OF_DOOM_EFFECT, true, NULL, aurEff); + GetCaster()->CastSpell(GetTarget(), SPELL_WARLOCK_CURSE_OF_DOOM_EFFECT, true, nullptr, aurEff); } void Register() override @@ -396,9 +398,14 @@ class spell_warl_demonic_empowerment : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_SUCCUBUS) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELGUARD) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELHUNTER) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_IMP)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_SUCCUBUS, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELGUARD, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELHUNTER, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_IMP + }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -418,7 +425,7 @@ class spell_warl_demonic_empowerment : public SpellScriptLoader { SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER); int32 hp = int32(targetCreature->CountPctFromMaxHealth(GetCaster()->CalculateSpellDamage(targetCreature, spellInfo, 0))); - targetCreature->CastCustomSpell(targetCreature, SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER, &hp, NULL, NULL, true); + targetCreature->CastCustomSpell(targetCreature, SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER, &hp, nullptr, nullptr, true); //unitTarget->CastSpell(unitTarget, 54441, true); break; } @@ -462,10 +469,11 @@ class spell_warl_drain_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMPROVED_DRAIN_SOUL_R1) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMPROVED_DRAIN_SOUL_PROC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_IMPROVED_DRAIN_SOUL_R1, + SPELL_WARLOCK_IMPROVED_DRAIN_SOUL_PROC + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -543,9 +551,7 @@ class spell_warl_fel_synergy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_FEL_SYNERGY_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_FEL_SYNERGY_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -591,9 +597,7 @@ class spell_warl_glyph_of_corruption_nightfall : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SHADOW_TRANCE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_SHADOW_TRANCE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -627,9 +631,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_LIFE_TAP_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_GLYPH_OF_LIFE_TAP_TRIGGERED }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -663,15 +665,13 @@ class spell_warl_glyph_of_shadowflame : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME, true, nullptr, aurEff); } void Register() override @@ -715,9 +715,7 @@ class spell_warl_haunt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_HAUNT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_HAUNT_HEAL }); } void HandleRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -725,7 +723,7 @@ class spell_warl_haunt : public SpellScriptLoader if (Unit* caster = GetCaster()) { int32 amount = aurEff->GetAmount(); - GetTarget()->CastCustomSpell(caster, SPELL_WARLOCK_HAUNT_HEAL, &amount, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(caster, SPELL_WARLOCK_HAUNT_HEAL, &amount, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); } } @@ -806,9 +804,7 @@ class spell_warl_life_tap : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_LIFE_TAP_ENERGIZE) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_LIFE_TAP_ENERGIZE, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -826,7 +822,7 @@ class spell_warl_life_tap : public SpellScriptLoader if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, WARLOCK_ICON_ID_IMPROVED_LIFE_TAP, 0)) AddPct(mana, aurEff->GetAmount()); - caster->CastCustomSpell(target, SPELL_WARLOCK_LIFE_TAP_ENERGIZE, &mana, NULL, NULL, false); + caster->CastCustomSpell(target, SPELL_WARLOCK_LIFE_TAP_ENERGIZE, &mana, nullptr, nullptr, false); // Mana Feed int32 manaFeedVal = 0; @@ -836,7 +832,7 @@ class spell_warl_life_tap : public SpellScriptLoader if (manaFeedVal > 0) { ApplyPct(manaFeedVal, mana); - caster->CastCustomSpell(caster, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2, &manaFeedVal, NULL, NULL, true, NULL); + caster->CastCustomSpell(caster, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2, &manaFeedVal, nullptr, nullptr, true, nullptr); } } } @@ -873,14 +869,15 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_HOLY) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_FIRE) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_FROST) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_ARCANE) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_SHADOW) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_PROTECTION_NATURE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_NETHER_PROTECTION_HOLY, + SPELL_WARLOCK_NETHER_PROTECTION_FIRE, + SPELL_WARLOCK_NETHER_PROTECTION_NATURE, + SPELL_WARLOCK_NETHER_PROTECTION_FROST, + SPELL_WARLOCK_NETHER_PROTECTION_SHADOW, + SPELL_WARLOCK_NETHER_PROTECTION_ARCANE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -962,9 +959,7 @@ class spell_warl_demonic_pact : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_PACT_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_DEMONIC_PACT_PROC }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1039,9 +1034,7 @@ class spell_warl_seduction : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_SUCCUBUS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_GLYPH_OF_SUCCUBUS }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1108,9 +1101,7 @@ class spell_warl_seed_of_corruption_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SEED_OF_CORRUPTION_DAMAGE_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_SEED_OF_CORRUPTION_DAMAGE_R1 }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1168,9 +1159,7 @@ class spell_warl_seed_of_corruption_generic : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SEED_OF_CORRUPTION_GENERIC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_SEED_OF_CORRUPTION_GENERIC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1257,11 +1246,11 @@ class spell_warl_siphon_life : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SIPHON_LIFE_HEAL)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_SIPHON_LIFE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_SIPHON_LIFE_HEAL, + SPELL_WARLOCK_GLYPH_OF_SIPHON_LIFE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1310,15 +1299,16 @@ class spell_warl_soul_leech : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_LEECH_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMP_SOUL_LEECH_R1) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_LEECH_PET_MANA_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_LEECH_PET_MANA_2) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_LEECH_CASTER_MANA_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_LEECH_CASTER_MANA_2) || - !sSpellMgr->GetSpellInfo(SPELL_REPLENISHMENT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_SOUL_LEECH_HEAL, + SPELL_WARLOCK_IMP_SOUL_LEECH_R1, + SPELL_WARLOCK_SOUL_LEECH_PET_MANA_1, + SPELL_WARLOCK_SOUL_LEECH_PET_MANA_2, + SPELL_WARLOCK_SOUL_LEECH_CASTER_MANA_1, + SPELL_WARLOCK_SOUL_LEECH_CASTER_MANA_2, + SPELL_REPLENISHMENT + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1375,9 +1365,7 @@ class spell_warl_soulshatter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOULSHATTER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_SOULSHATTER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1417,9 +1405,7 @@ class spell_warl_t4_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Trigger)) - return false; - return true; + return ValidateSpellInfo({ Trigger }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1453,9 +1439,7 @@ class spell_warl_unstable_affliction : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL }); } void HandleDispel(DispelInfo* dispelInfo) @@ -1465,7 +1449,7 @@ class spell_warl_unstable_affliction : public SpellScriptLoader { int32 damage = aurEff->GetAmount() * 9; // backfire damage and silence - caster->CastCustomSpell(dispelInfo->GetDispeller(), SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL, &damage, NULL, NULL, true, NULL, aurEff); + caster->CastCustomSpell(dispelInfo->GetDispeller(), SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL, &damage, nullptr, nullptr, true, nullptr, aurEff); } } diff --git a/src/server/scripts/Spells/spell_warrior.cpp b/src/server/scripts/Spells/spell_warrior.cpp index 7ee2833e30f..70a4946b424 100644 --- a/src/server/scripts/Spells/spell_warrior.cpp +++ b/src/server/scripts/Spells/spell_warrior.cpp @@ -21,11 +21,13 @@ * Scriptnames of files in this file should be prefixed with "spell_warr_". */ -#include "Player.h" #include "ScriptMgr.h" +#include "Player.h" +#include "Random.h" +#include "SpellAuraEffects.h" #include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" enum WarriorSpells { @@ -109,7 +111,7 @@ class spell_warr_bloodthirst : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { int32 damage = GetEffectValue(); - GetCaster()->CastCustomSpell(GetCaster(), SPELL_WARRIOR_BLOODTHIRST, &damage, NULL, NULL, true, NULL); + GetCaster()->CastCustomSpell(GetCaster(), SPELL_WARRIOR_BLOODTHIRST, &damage, nullptr, nullptr, true, nullptr); } void Register() override @@ -165,16 +167,14 @@ class spell_warr_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_TALENT) || !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_BUFF) || !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_TALENT, SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_BUFF, SPELL_WARRIOR_CHARGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) { int32 chargeBasePoints0 = GetEffectValue(); Unit* caster = GetCaster(); - caster->CastCustomSpell(caster, SPELL_WARRIOR_CHARGE, &chargeBasePoints0, NULL, NULL, true); + caster->CastCustomSpell(caster, SPELL_WARRIOR_CHARGE, &chargeBasePoints0, nullptr, nullptr, true); // Juggernaut crit bonus if (caster->HasAura(SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_TALENT)) @@ -232,9 +232,7 @@ class spell_warr_damage_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DAMAGE_SHIELD_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_DAMAGE_SHIELD_DAMAGE }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -243,7 +241,7 @@ class spell_warr_damage_shield : public SpellScriptLoader // % of amount blocked int32 damage = CalculatePct(int32(GetTarget()->GetShieldBlockValue()), aurEff->GetAmount()); - GetTarget()->CastCustomSpell(SPELL_WARRIOR_DAMAGE_SHIELD_DAMAGE, SPELLVALUE_BASE_POINT0, damage, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_WARRIOR_DAMAGE_SHIELD_DAMAGE, SPELLVALUE_BASE_POINT0, damage, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -270,12 +268,13 @@ class spell_warr_deep_wounds : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_RANK_2) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_RANK_3) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_DEEP_WOUNDS_RANK_1, + SPELL_WARRIOR_DEEP_WOUNDS_RANK_2, + SPELL_WARRIOR_DEEP_WOUNDS_RANK_3, + SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -319,9 +318,7 @@ class spell_warr_deep_wounds_aura : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -373,9 +370,7 @@ class spell_warr_execute : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_EXECUTE) || !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_GLYPH_OF_EXECUTION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_EXECUTE, SPELL_WARRIOR_GLYPH_OF_EXECUTION }); } void HandleEffect(SpellEffIndex effIndex) @@ -401,7 +396,7 @@ class spell_warr_execute : public SpellScriptLoader int32 bp = GetEffectValue() + int32(rageUsed * spellInfo->Effects[effIndex].DamageMultiplier + caster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.2f); - caster->CastCustomSpell(target, SPELL_WARRIOR_EXECUTE, &bp, NULL, NULL, true, NULL, NULL, GetOriginalCaster()->GetGUID()); + caster->CastCustomSpell(target, SPELL_WARRIOR_EXECUTE, &bp, nullptr, nullptr, true, nullptr, nullptr, GetOriginalCaster()->GetGUID()); } } @@ -430,12 +425,13 @@ class spell_warr_extra_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_T10_MELEE_4P_BONUS) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_EXTRA_CHARGE) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SLAM_GCD_REDUCED) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_EXECUTE_GCD_REDUCED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_T10_MELEE_4P_BONUS, + SPELL_WARRIOR_EXTRA_CHARGE, + SPELL_WARRIOR_SLAM_GCD_REDUCED, + SPELL_WARRIOR_EXECUTE_GCD_REDUCED + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -481,9 +477,7 @@ class spell_warr_glyph_of_blocking : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_GLYPH_OF_BLOCKING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_GLYPH_OF_BLOCKING }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -553,9 +547,7 @@ class spell_warr_improved_spell_reflection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_IMPROVED_SPELL_REFLECTION_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_IMPROVED_SPELL_REFLECTION_TRIGGER }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -617,9 +609,7 @@ class spell_warr_item_t10_prot_4p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_STOICISM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_STOICISM }); } void HandleProc(ProcEventInfo& eventInfo) @@ -655,16 +645,14 @@ class spell_warr_last_stand : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_LAST_STAND_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_LAST_STAND_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); int32 healthModSpellBasePoints0 = int32(caster->CountPctFromMaxHealth(GetEffectValue())); - caster->CastCustomSpell(caster, SPELL_WARRIOR_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, NULL, NULL, true, NULL); + caster->CastCustomSpell(caster, SPELL_WARRIOR_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, nullptr, nullptr, true, nullptr); } void Register() override @@ -775,9 +763,7 @@ class spell_warr_retaliation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_RETALIATION_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_RETALIATION_DAMAGE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -789,7 +775,7 @@ class spell_warr_retaliation : public SpellScriptLoader void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARRIOR_RETALIATION_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARRIOR_RETALIATION_DAMAGE, true, nullptr, aurEff); } void Register() override @@ -817,10 +803,11 @@ class spell_warr_second_wind : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SECOND_WIND_TRIGGER_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SECOND_WIND_TRIGGER_2)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_SECOND_WIND_TRIGGER_1, + SPELL_WARRIOR_SECOND_WIND_TRIGGER_2 + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -898,9 +885,7 @@ class spell_warr_slam : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SLAM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_SLAM }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -931,18 +916,9 @@ class spell_warr_sweeping_strikes : public SpellScriptLoader { PrepareAuraScript(spell_warr_sweeping_strikes_AuraScript); - public: - spell_warr_sweeping_strikes_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_1) || !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_1, SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_2 }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -976,8 +952,7 @@ class spell_warr_sweeping_strikes : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_warr_sweeping_strikes_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -1063,24 +1038,15 @@ class spell_warr_vigilance : public SpellScriptLoader { PrepareAuraScript(spell_warr_vigilance_AuraScript); - public: - spell_warr_vigilance_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_GLYPH_OF_VIGILANCE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_VIGILANCE_PROC)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_VIGILANCE_REDIRECT_THREAT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_DAMAGE_REDUCTION_AURA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_GLYPH_OF_VIGILANCE, + SPELL_WARRIOR_VIGILANCE_PROC, + SPELL_WARRIOR_VIGILANCE_REDIRECT_THREAT, + SPELL_GEN_DAMAGE_REDUCTION_AURA + }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1126,7 +1092,7 @@ class spell_warr_vigilance : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(_procTarget, SPELL_WARRIOR_VIGILANCE_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_WARRIOR_VIGILANCE_PROC, true, nullptr, aurEff); } void Register() override @@ -1138,8 +1104,7 @@ class spell_warr_vigilance : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_warr_vigilance_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override diff --git a/src/server/scripts/World/action_ip_logger.cpp b/src/server/scripts/World/action_ip_logger.cpp index 3c515b38dfe..9dc3fba9896 100644 --- a/src/server/scripts/World/action_ip_logger.cpp +++ b/src/server/scripts/World/action_ip_logger.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" -#include "Channel.h" -#include "Guild.h" -#include "Group.h" +#include "DatabaseEnv.h" +#include "Player.h" +#include "WorldSession.h" enum IPLoggingTypes { diff --git a/src/server/scripts/World/areatrigger_scripts.cpp b/src/server/scripts/World/areatrigger_scripts.cpp index a3fb056ba8f..a7d730f185a 100644 --- a/src/server/scripts/World/areatrigger_scripts.cpp +++ b/src/server/scripts/World/areatrigger_scripts.cpp @@ -35,10 +35,15 @@ at_brewfest at_area_52_entrance EndContentData */ -#include "GameTime.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "DBCStructure.h" +#include "GameObject.h" +#include "GameTime.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" /*###### ## at_coilfang_waterfall diff --git a/src/server/scripts/World/boss_emerald_dragons.cpp b/src/server/scripts/World/boss_emerald_dragons.cpp index c674a32f43f..65bd57c2a16 100644 --- a/src/server/scripts/World/boss_emerald_dragons.cpp +++ b/src/server/scripts/World/boss_emerald_dragons.cpp @@ -17,12 +17,13 @@ */ #include "ObjectMgr.h" -#include "ScriptMgr.h" +#include "MotionMaster.h" +#include "PassiveAI.h" #include "ScriptedCreature.h" -#include "SpellScript.h" +#include "ScriptMgr.h" #include "Spell.h" #include "SpellAuraEffects.h" -#include "PassiveAI.h" +#include "SpellScript.h" // // Emerald Dragon NPCs and IDs (kept here for reference) @@ -397,7 +398,7 @@ class boss_lethon : public CreatureScript switch (eventId) { case EVENT_SHADOW_BOLT_WHIRL: - me->CastSpell((Unit*)NULL, SPELL_SHADOW_BOLT_WHIRL, false); + me->CastSpell((Unit*)nullptr, SPELL_SHADOW_BOLT_WHIRL, false); events.ScheduleEvent(EVENT_SHADOW_BOLT_WHIRL, urand(15000, 30000)); break; default: @@ -437,7 +438,7 @@ class npc_spirit_shade : public CreatureScript { if (moveType == FOLLOW_MOTION_TYPE && data == _summonerGuid.GetCounter()) { - me->CastSpell((Unit*)NULL, SPELL_DARK_OFFERING, false); + me->CastSpell((Unit*)nullptr, SPELL_DARK_OFFERING, false); me->DespawnOrUnsummon(1000); } } @@ -770,11 +771,11 @@ class spell_mark_of_nature : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_NATURE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_AURA_OF_NATURE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MARK_OF_NATURE, + SPELL_AURA_OF_NATURE + }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/World/chat_log.cpp b/src/server/scripts/World/chat_log.cpp index 9b3465174a4..90e7d4863ca 100644 --- a/src/server/scripts/World/chat_log.cpp +++ b/src/server/scripts/World/chat_log.cpp @@ -17,8 +17,10 @@ #include "ScriptMgr.h" #include "Channel.h" -#include "Guild.h" #include "Group.h" +#include "Guild.h" +#include "Log.h" +#include "Player.h" class ChatLogScript : public PlayerScript { diff --git a/src/server/scripts/World/duel_reset.cpp b/src/server/scripts/World/duel_reset.cpp index 3d8692780b6..8a794091e60 100644 --- a/src/server/scripts/World/duel_reset.cpp +++ b/src/server/scripts/World/duel_reset.cpp @@ -15,11 +15,14 @@ * with this program. If not, see . */ -#include "GameTime.h" #include "ScriptMgr.h" -#include "Player.h" +#include "GameTime.h" #include "Pet.h" +#include "Player.h" +#include "SpellHistory.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "World.h" class DuelResetScript : public PlayerScript { diff --git a/src/server/scripts/World/go_scripts.cpp b/src/server/scripts/World/go_scripts.cpp index c6a61a1d508..d9aa9358ee7 100644 --- a/src/server/scripts/World/go_scripts.cpp +++ b/src/server/scripts/World/go_scripts.cpp @@ -46,14 +46,22 @@ go_bells EndContentData */ #include "ScriptMgr.h" +#include "DBCStructure.h" +#include "GameEventMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GameTime.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "GameObjectAI.h" #include "Spell.h" -#include "Player.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" #include "WorldSession.h" -#include "GameEventMgr.h" -#include "GameTime.h" /*###### ## go_cat_figurine @@ -1765,7 +1773,7 @@ public: break; std::vector playersNearby; - me->GetPlayerListInGrid(playersNearby, me->GetMap()->GetVisibilityRange()); + me->GetPlayerListInGrid(playersNearby, me->GetVisibilityRange()); for (Player* player : playersNearby) { if (player->GetTeamId() == TEAM_HORDE) diff --git a/src/server/scripts/World/guards.cpp b/src/server/scripts/World/guards.cpp index a5d3ce8d500..638e53c45c5 100644 --- a/src/server/scripts/World/guards.cpp +++ b/src/server/scripts/World/guards.cpp @@ -30,8 +30,9 @@ guard_shattrath_scryer EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "GuardAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" #include "SpellInfo.h" @@ -120,7 +121,7 @@ public: if (me->IsWithinMeleeRange(me->GetVictim())) { bool healing = false; - SpellInfo const* info = NULL; + SpellInfo const* info = nullptr; //Select a healing spell if less than 30% hp if (me->HealthBelowPct(30)) @@ -156,7 +157,7 @@ public: if (!me->IsNonMeleeSpellCast(false)) { bool healing = false; - SpellInfo const* info = NULL; + SpellInfo const* info = nullptr; //Select a healing spell if less than 30% hp ONLY 33% of the time if (me->HealthBelowPct(30) && 33 > urand(0, 99)) diff --git a/src/server/scripts/World/item_scripts.cpp b/src/server/scripts/World/item_scripts.cpp index 64caa7ec4d1..8253aa23414 100644 --- a/src/server/scripts/World/item_scripts.cpp +++ b/src/server/scripts/World/item_scripts.cpp @@ -31,9 +31,13 @@ item_only_for_flight Items which should only useable while flying EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "Item.h" +#include "Player.h" #include "ScriptedCreature.h" #include "Spell.h" -#include "Player.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" /*##### # item_only_for_flight @@ -76,7 +80,7 @@ public: return false; // error - player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); + player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, nullptr); return true; } }; @@ -119,7 +123,7 @@ public: targets.GetUnitTarget()->GetEntry() == 20748 && !targets.GetUnitTarget()->HasAura(32578)) return false; - player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); + player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, nullptr); return true; } }; @@ -139,7 +143,7 @@ public: return false; else { - player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); + player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, nullptr); return true; } } @@ -159,7 +163,7 @@ public: ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 39883, 1); // Cracked Egg if (msg == EQUIP_ERR_OK) - player->StoreNewItem(dest, 39883, true, Item::GenerateItemRandomPropertyId(39883)); + player->StoreNewItem(dest, 39883, true, GenerateItemRandomPropertyId(39883)); return true; } @@ -179,7 +183,7 @@ public: ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 44718, 1); // Ripe Disgusting Jar if (msg == EQUIP_ERR_OK) - player->StoreNewItem(dest, 44718, true, Item::GenerateItemRandomPropertyId(44718)); + player->StoreNewItem(dest, 44718, true, GenerateItemRandomPropertyId(44718)); return true; } @@ -225,7 +229,7 @@ public: bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const & /*targets*/) override { - GameObject* go = NULL; + GameObject* go = nullptr; for (uint8 i = 0; i < CaribouTrapsNum; ++i) { go = player->FindNearestGameObject(CaribouTraps[i], 5.0f); @@ -241,7 +245,7 @@ public: float x, y, z; go->GetClosePoint(x, y, z, go->GetCombatReach() / 3, 7.0f); - go->SummonGameObject(GO_HIGH_QUALITY_FUR, *go, G3D::Quat(), 1); + go->SummonGameObject(GO_HIGH_QUALITY_FUR, *go, QuaternionData(), 1); if (TempSummon* summon = player->SummonCreature(NPC_NESINGWARY_TRAPPER, x, y, z, go->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 1000)) { summon->SetVisible(false); @@ -268,16 +272,16 @@ class item_petrov_cluster_bombs : public ItemScript public: item_petrov_cluster_bombs() : ItemScript("item_petrov_cluster_bombs") { } - bool OnUse(Player* player, Item* item, const SpellCastTargets & /*targets*/) override + bool OnUse(Player* player, Item* item, SpellCastTargets const& /*targets*/) override { if (player->GetZoneId() != ZONE_ID_HOWLING) return false; if (!player->GetTransport() || player->GetAreaId() != AREA_ID_SHATTERED_STRAITS) { - player->SendEquipError(EQUIP_ERR_NONE, item, NULL); + player->SendEquipError(EQUIP_ERR_NONE, item, nullptr); - if (const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(SPELL_PETROV_BOMB)) + if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(SPELL_PETROV_BOMB)) Spell::SendCastResult(player, spellInfo, 1, SPELL_FAILED_NOT_HERE); return true; @@ -334,7 +338,7 @@ class item_dehta_trap_smasher : public ItemScript public: item_dehta_trap_smasher() : ItemScript("item_dehta_trap_smasher") { } - bool OnUse(Player* player, Item* /*item*/, const SpellCastTargets & /*targets*/) override + bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const& /*targets*/) override { if (player->GetQuestStatus(QUEST_CANNOT_HELP_THEMSELVES) != QUEST_STATUS_INCOMPLETE) return false; @@ -343,7 +347,7 @@ public: if (!pMammoth) return false; - GameObject* pTrap = NULL; + GameObject* pTrap = nullptr; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = player->FindNearestGameObject(MammothTraps[i], 11.0f); @@ -370,7 +374,7 @@ class item_trident_of_nazjan : public ItemScript public: item_trident_of_nazjan() : ItemScript("item_Trident_of_Nazjan") { } - bool OnUse(Player* player, Item* item, const SpellCastTargets & /*targets*/) override + bool OnUse(Player* player, Item* item, SpellCastTargets const& /*targets*/) override { if (player->GetQuestStatus(QUEST_THE_EMISSARY) == QUEST_STATUS_INCOMPLETE) { @@ -379,9 +383,9 @@ public: pLeviroth->AI()->AttackStart(player); return false; } else - player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); + player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, nullptr); } else - player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); + player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, nullptr); return true; } }; @@ -404,10 +408,10 @@ public: if (player->FindNearestCreature(NPC_VANIRAS_SENTRY_TOTEM, 10.0f)) return false; else - player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); + player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, nullptr); } else - player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, NULL); + player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, item, nullptr); return true; } }; diff --git a/src/server/scripts/World/mob_generic_creature.cpp b/src/server/scripts/World/mob_generic_creature.cpp index a7370fde1b5..0c71177ccac 100644 --- a/src/server/scripts/World/mob_generic_creature.cpp +++ b/src/server/scripts/World/mob_generic_creature.cpp @@ -17,8 +17,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" #include "PassiveAI.h" +#include "SpellMgr.h" class trigger_periodic : public CreatureScript { @@ -29,13 +30,13 @@ public: { trigger_periodicAI(Creature* creature) : NullCreatureAI(creature) { - spell = me->m_spells[0] ? sSpellMgr->GetSpellInfo(me->m_spells[0]) : NULL; + spell = me->m_spells[0] ? sSpellMgr->GetSpellInfo(me->m_spells[0]) : nullptr; interval = me->GetAttackTime(BASE_ATTACK); timer = interval; } uint32 timer, interval; - const SpellInfo* spell; + SpellInfo const* spell; void UpdateAI(uint32 diff) override { diff --git a/src/server/scripts/World/npc_innkeeper.cpp b/src/server/scripts/World/npc_innkeeper.cpp index d5cba9a7225..7db733c7f78 100644 --- a/src/server/scripts/World/npc_innkeeper.cpp +++ b/src/server/scripts/World/npc_innkeeper.cpp @@ -57,7 +57,7 @@ public: { if (IsHolidayActive(HOLIDAY_HALLOWS_END) && !player->HasAura(SPELL_TRICK_OR_TREATED)) { - const char* localizedEntry; + char const* localizedEntry; switch (player->GetSession()->GetSessionDbcLocale()) { case LOCALE_frFR: localizedEntry = LOCALE_TRICK_OR_TREAT_2; break; @@ -76,7 +76,7 @@ public: if (me->IsInnkeeper()) { - const char* localizedEntry; + char const* localizedEntry; switch (player->GetSession()->GetSessionDbcLocale()) { case LOCALE_deDE: localizedEntry = LOCALE_INNKEEPER_3; break; diff --git a/src/server/scripts/World/npc_professions.cpp b/src/server/scripts/World/npc_professions.cpp index bfc8f19add0..9f1df957784 100644 --- a/src/server/scripts/World/npc_professions.cpp +++ b/src/server/scripts/World/npc_professions.cpp @@ -24,11 +24,14 @@ SDCategory: NPCs/GOBs EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "GameObjectAI.h" +#include "Item.h" +#include "Log.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "SpellMgr.h" #include "WorldSession.h" /* @@ -288,7 +291,7 @@ bool EquippedOk(Player* player, uint32 spellId) if (!reqSpell) continue; - Item* item = NULL; + Item* item = nullptr; for (uint8 j = EQUIPMENT_SLOT_START; j < EQUIPMENT_SLOT_END; ++j) { item = player->GetItemByPos(INVENTORY_SLOT_BAG_0, j); @@ -433,7 +436,7 @@ void ProcessUnlearnAction(Player* player, Creature* creature, uint32 spellId, ui player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, 0, 0); } else - player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, NULL, NULL); + player->SendEquipError(EQUIP_ERR_CANT_DO_RIGHT_NOW, nullptr, nullptr); CloseGossipMenuFor(player); } diff --git a/src/server/scripts/World/npcs_special.cpp b/src/server/scripts/World/npcs_special.cpp index 7a8b8e77e9a..8fc60e6ace7 100644 --- a/src/server/scripts/World/npcs_special.cpp +++ b/src/server/scripts/World/npcs_special.cpp @@ -17,26 +17,27 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "ObjectMgr.h" -#include "ScriptMgr.h" -#include "World.h" -#include "PassiveAI.h" +#include "CellImpl.h" +#include "CombatAI.h" +#include "CreatureTextMgr.h" #include "GameEventMgr.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" -#include "SpellHistory.h" -#include "SpellAuras.h" +#include "Log.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "PassiveAI.h" #include "Pet.h" -#include "CreatureTextMgr.h" -#include "CombatAI.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "ScriptMgr.h" #include "SmartAI.h" +#include "SpellAuras.h" +#include "SpellHistory.h" +#include "SpellMgr.h" #include "Vehicle.h" -#include "MoveSplineInit.h" +#include "World.h" /*######## # npc_air_force_bots @@ -104,13 +105,13 @@ public: { npc_air_force_botsAI(Creature* creature) : ScriptedAI(creature) { - SpawnAssoc = NULL; + SpawnAssoc = nullptr; SpawnedGUID.Clear(); // find the correct spawnhandling - static uint32 entryCount = sizeof(spawnAssociations) / sizeof(SpawnAssociation); + static uint8 constexpr const EntryCount = uint8(std::extent::value); - for (uint8 i = 0; i < entryCount; ++i) + for (uint8 i = 0; i < EntryCount; ++i) { if (spawnAssociations[i].thisCreatureEntry == creature->GetEntry()) { @@ -128,7 +129,7 @@ public: if (!spawnedTemplate) { TC_LOG_ERROR("sql.sql", "TCSR: Creature template entry %u does not exist in DB, which is required by npc_air_force_bots", SpawnAssoc->spawnedCreatureEntry); - SpawnAssoc = NULL; + SpawnAssoc = nullptr; return; } } @@ -148,7 +149,7 @@ public: else { TC_LOG_ERROR("sql.sql", "TCSR: npc_air_force_bots: wasn't able to spawn Creature %u", SpawnAssoc->spawnedCreatureEntry); - SpawnAssoc = NULL; + SpawnAssoc = nullptr; } return summoned; @@ -161,7 +162,7 @@ public: if (creature && creature->IsAlive()) return creature; - return NULL; + return nullptr; } void MoveInLineOfSight(Unit* who) override @@ -177,7 +178,7 @@ public: if (!playerTarget) return; - Creature* lastSpawnedGuard = SpawnedGUID.IsEmpty() ? NULL : GetSummonedGuard(); + Creature* lastSpawnedGuard = SpawnedGUID.IsEmpty() ? nullptr : GetSummonedGuard(); // prevent calling Unit::GetUnit at next MoveInLineOfSight call - speedup if (!lastSpawnedGuard) @@ -846,7 +847,7 @@ public: void Initialize() { DoctorGUID.Clear(); - Coord = NULL; + Coord = nullptr; } ObjectGuid DoctorGUID; @@ -1810,7 +1811,7 @@ public: void DamageTaken(Unit* doneBy, uint32& damage) override { me->AddThreat(doneBy, float(damage)); // just to create threat reference - _damageTimes[doneBy->GetGUID()] = time(NULL); + _damageTimes[doneBy->GetGUID()] = time(nullptr); damage = 0; } @@ -1830,7 +1831,7 @@ public: { case EVENT_TD_CHECK_COMBAT: { - time_t now = time(NULL); + time_t now = time(nullptr); for (std::unordered_map::iterator itr = _damageTimes.begin(); itr != _damageTimes.end();) { // If unit has not dealt damage to training dummy for 5 seconds, remove him from combat @@ -2180,7 +2181,7 @@ public: GameObject* FindNearestLauncher() { - GameObject* launcher = NULL; + GameObject* launcher = nullptr; if (isCluster()) { @@ -2295,7 +2296,7 @@ public: break; } - const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (spellInfo && spellInfo->Effects[0].Effect == SPELL_EFFECT_SUMMON_OBJECT_WILD) return spellInfo->Effects[0].MiscValue; @@ -2340,7 +2341,7 @@ public: float displacement = 0.7f; for (uint8 i = 0; i < 4; i++) - me->SummonGameObject(GetFireworkGameObjectId(), me->GetPositionX() + (i % 2 == 0 ? displacement : -displacement), me->GetPositionY() + (i > 1 ? displacement : -displacement), me->GetPositionZ() + 4.0f, me->GetOrientation(), G3D::Quat(), 1); + me->SummonGameObject(GetFireworkGameObjectId(), me->GetPositionX() + (i % 2 == 0 ? displacement : -displacement), me->GetPositionY() + (i > 1 ? displacement : -displacement), me->GetPositionZ() + 4.0f, me->GetOrientation(), QuaternionData(), 1); } else //me->CastSpell(me, GetFireworkSpell(me->GetEntry()), true); diff --git a/src/server/shared/DataStores/DBCDatabaseLoader.cpp b/src/server/shared/DataStores/DBCDatabaseLoader.cpp new file mode 100644 index 00000000000..3ef3e8f64c0 --- /dev/null +++ b/src/server/shared/DataStores/DBCDatabaseLoader.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "DBCDatabaseLoader.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "Errors.h" +#include "Log.h" +#include + +DBCDatabaseLoader::DBCDatabaseLoader(std::string const& storageName, std::string const& dbFormatString, std::string const& primaryKey, char const* dbcFormatString) + : _formatString(dbFormatString), _indexName(primaryKey), _sqlTableName(storageName), _dbcFormat(dbcFormatString), _sqlIndexPos(0), _recordSize(0) +{ + // Convert dbc file name to sql table name + std::transform(_sqlTableName.begin(), _sqlTableName.end(), _sqlTableName.begin(), ::tolower); + for (char& c : _sqlTableName) + if (c == '.') + c = '_'; + + // Get sql index position + int32 indexPos = -1; + _recordSize = DBCFileLoader::GetFormatRecordSize(_dbcFormat, &indexPos); + ASSERT(indexPos >= 0); + ASSERT(_recordSize); + + uint32 uindexPos = uint32(indexPos); + for (uint32 x = 0; x < _formatString.size(); ++x) + { + // Count only fields present in sql + if (_formatString[x] == FT_SQL_PRESENT) + { + if (x == uindexPos) + break; + ++_sqlIndexPos; + } + } +} + +static char const* nullStr = ""; + +char* DBCDatabaseLoader::Load(uint32& records, char**& indexTable) +{ + std::ostringstream queryBuilder; + queryBuilder << "SELECT * FROM " << _sqlTableName + << " ORDER BY " << _indexName << " DESC;"; + + // no error if empty set + QueryResult result = WorldDatabase.Query(queryBuilder.str().c_str()); + if (!result) + return nullptr; + + // Check if sql index pos is valid + if (int32(result->GetFieldCount() - 1) < _sqlIndexPos) + { + ASSERT(false, "Invalid index pos for dbc:'%s'", _sqlTableName.c_str()); + return nullptr; + } + + // Resize index table + // database query *MUST* contain ORDER BY `index_field` DESC clause + uint32 indexTableSize = std::max(records, (*result)[_sqlIndexPos].GetUInt32() + 1); + if (indexTableSize > records) + { + char** tmpIdxTable = new char*[indexTableSize]; + memset(tmpIdxTable, 0, indexTableSize * sizeof(char*)); + memcpy(tmpIdxTable, indexTable, records * sizeof(char*)); + delete[] indexTable; + indexTable = tmpIdxTable; + } + + std::unique_ptr dataTable = Trinity::make_unique(result->GetRowCount() * _recordSize); + std::unique_ptr newIndexes = Trinity::make_unique(result->GetRowCount()); + uint32 newRecords = 0; + + // Insert sql data into the data array + do + { + Field* fields = result->Fetch(); + uint32 offset = 0; + + uint32 indexValue = fields[_sqlIndexPos].GetUInt32(); + + char* dataValue = indexTable[indexValue]; + if (!dataValue) + { + newIndexes[newRecords] = indexValue; + dataValue = &dataTable[newRecords++ * _recordSize]; + } + else + { + // Attempt to overwrite existing data + ASSERT(false, "Index %d already exists in dbc:'%s'", indexValue, _sqlTableName.c_str()); + return nullptr; + } + + uint32 columnNumber = 0; + uint32 sqlColumnNumber = 0; + + for (; columnNumber < _formatString.size(); ++columnNumber) + { + if (_formatString[columnNumber] == FT_SQL_ABSENT) + { + switch (_dbcFormat[columnNumber]) + { + case FT_FLOAT: + *reinterpret_cast(&dataValue[offset]) = 0.0f; + offset += 4; + break; + case FT_IND: + case FT_INT: + *reinterpret_cast(&dataValue[offset]) = uint32(0); + offset += 4; + break; + case FT_BYTE: + *reinterpret_cast(&dataValue[offset]) = uint8(0); + offset += 1; + break; + case FT_STRING: + *reinterpret_cast(&dataValue[offset]) = const_cast(nullStr); + offset += sizeof(char*); + break; + } + } + else if (_formatString[columnNumber] == FT_SQL_PRESENT) + { + bool validSqlColumn = true; + switch (_dbcFormat[columnNumber]) + { + case FT_FLOAT: + *reinterpret_cast(&dataValue[offset]) = fields[sqlColumnNumber].GetFloat(); + offset += 4; + break; + case FT_IND: + case FT_INT: + *reinterpret_cast(&dataValue[offset]) = fields[sqlColumnNumber].GetUInt32(); + offset += 4; + break; + case FT_BYTE: + *reinterpret_cast(&dataValue[offset]) = fields[sqlColumnNumber].GetUInt8(); + offset += 1; + break; + case FT_STRING: + ASSERT(false, "Unsupported data type in table '%s' at char %d", _sqlTableName.c_str(), columnNumber); + return nullptr; + case FT_SORT: + break; + default: + validSqlColumn = false; + break; + } + if (validSqlColumn && (columnNumber != (_formatString.size() - 1))) + sqlColumnNumber++; + } + else + { + ASSERT(false, "Incorrect sql format string '%s' at char %d", _sqlTableName.c_str(), columnNumber); + break; + } + } + + if (sqlColumnNumber != (result->GetFieldCount() - 1)) + { + ASSERT(false, "SQL and DBC format strings are not matching for table: '%s'", _sqlTableName.c_str()); + return nullptr; + } + + ASSERT(offset == _recordSize); + } while (result->NextRow()); + + ASSERT(newRecords == result->GetRowCount()); + + // insert new records to index table + for (uint32 i = 0; i < newRecords; ++i) + indexTable[newIndexes[i]] = &dataTable[i * _recordSize]; + + records = indexTableSize; + + return dataTable.release(); +} diff --git a/src/server/shared/DataStores/DBCDatabaseLoader.h b/src/server/shared/DataStores/DBCDatabaseLoader.h new file mode 100644 index 00000000000..153a0eb4dcb --- /dev/null +++ b/src/server/shared/DataStores/DBCDatabaseLoader.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef DBCDatabaseLoader_h__ +#define DBCDatabaseLoader_h__ + +#include "DBCFileLoader.h" +#include +#include + +struct TC_SHARED_API DBCDatabaseLoader +{ + DBCDatabaseLoader(std::string const& storageName, std::string const& dbFormatString, std::string const& primaryKey, char const* dbcFormatString); + + char* Load(uint32& records, char**& indexTable); + +private: + std::string const& _formatString; + std::string const& _indexName; + std::string _sqlTableName; + char const* _dbcFormat; + int32 _sqlIndexPos; + uint32 _recordSize; + + DBCDatabaseLoader(DBCDatabaseLoader const& right) = delete; + DBCDatabaseLoader& operator=(DBCDatabaseLoader const& right) = delete; +}; + +#endif // DBCDatabaseLoader_h__ diff --git a/src/server/shared/DataStores/DBCFileLoader.cpp b/src/server/shared/DataStores/DBCFileLoader.cpp deleted file mode 100644 index 8c92260e62d..00000000000 --- a/src/server/shared/DataStores/DBCFileLoader.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/* - * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2009 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 the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#include -#include -#include - -#include "DBCFileLoader.h" -#include "Errors.h" - -DBCFileLoader::DBCFileLoader() : recordSize(0), recordCount(0), fieldCount(0), stringSize(0), fieldsOffset(NULL), data(NULL), stringTable(NULL) { } - -bool DBCFileLoader::Load(const char* filename, const char* fmt) -{ - uint32 header; - if (data) - { - delete [] data; - data = NULL; - } - - FILE* f = fopen(filename, "rb"); - if (!f) - return false; - - if (fread(&header, 4, 1, f) != 1) // Number of records - { - fclose(f); - return false; - } - - - EndianConvert(header); - - if (header != 0x43424457) //'WDBC' - { - fclose(f); - return false; - } - - if (fread(&recordCount, 4, 1, f) != 1) // Number of records - { - fclose(f); - return false; - } - - EndianConvert(recordCount); - - if (fread(&fieldCount, 4, 1, f) != 1) // Number of fields - { - fclose(f); - return false; - } - - EndianConvert(fieldCount); - - if (fread(&recordSize, 4, 1, f) != 1) // Size of a record - { - fclose(f); - return false; - } - - EndianConvert(recordSize); - - if (fread(&stringSize, 4, 1, f) != 1) // String size - { - fclose(f); - return false; - } - - EndianConvert(stringSize); - - fieldsOffset = new uint32[fieldCount]; - fieldsOffset[0] = 0; - for (uint32 i = 1; i < fieldCount; ++i) - { - fieldsOffset[i] = fieldsOffset[i - 1]; - if (fmt[i - 1] == 'b' || fmt[i - 1] == 'X') // byte fields - fieldsOffset[i] += sizeof(uint8); - else // 4 byte fields (int32/float/strings) - fieldsOffset[i] += sizeof(uint32); - } - - data = new unsigned char[recordSize * recordCount + stringSize]; - stringTable = data + recordSize*recordCount; - - if (fread(data, recordSize * recordCount + stringSize, 1, f) != 1) - { - fclose(f); - return false; - } - - fclose(f); - - return true; -} - -DBCFileLoader::~DBCFileLoader() -{ - delete[] data; - - delete[] fieldsOffset; -} - -DBCFileLoader::Record DBCFileLoader::getRecord(size_t id) -{ - assert(data); - return Record(*this, data + id * recordSize); -} - -uint32 DBCFileLoader::GetFormatRecordSize(const char* format, int32* index_pos) -{ - uint32 recordsize = 0; - int32 i = -1; - for (uint32 x = 0; format[x]; ++x) - { - switch (format[x]) - { - case FT_FLOAT: - recordsize += sizeof(float); - break; - case FT_INT: - recordsize += sizeof(uint32); - break; - case FT_STRING: - recordsize += sizeof(char*); - break; - case FT_SORT: - i = x; - break; - case FT_IND: - i = x; - recordsize += sizeof(uint32); - break; - case FT_BYTE: - recordsize += sizeof(uint8); - break; - case FT_NA: - case FT_NA_BYTE: - break; - case FT_LOGIC: - ASSERT(false && "Attempted to load DBC files that do not have field types that match what is in the core. Check DBCfmt.h or your DBC files."); - break; - default: - ASSERT(false && "Unknown field format character in DBCfmt.h"); - break; - } - } - - if (index_pos) - *index_pos = i; - - return recordsize; -} - -char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char**& indexTable, uint32 sqlRecordCount, uint32 sqlHighestIndex, char*& sqlDataTable) -{ - /* - format STRING, NA, FLOAT, NA, INT <=> - struct{ - char* field0, - float field1, - int field2 - }entry; - - this func will generate entry[rows] data; - */ - - typedef char* ptr; - if (strlen(format) != fieldCount) - return NULL; - - //get struct size and index pos - int32 i; - uint32 recordsize = GetFormatRecordSize(format, &i); - - if (i >= 0) - { - uint32 maxi = 0; - //find max index - for (uint32 y = 0; y < recordCount; ++y) - { - uint32 ind = getRecord(y).getUInt(i); - if (ind > maxi) - maxi = ind; - } - - // If higher index avalible from sql - use it instead of dbcs - if (sqlHighestIndex > maxi) - maxi = sqlHighestIndex; - - ++maxi; - records = maxi; - indexTable = new ptr[maxi]; - memset(indexTable, 0, maxi * sizeof(ptr)); - } - else - { - records = recordCount + sqlRecordCount; - indexTable = new ptr[recordCount + sqlRecordCount]; - } - - char* dataTable = new char[(recordCount + sqlRecordCount) * recordsize]; - - uint32 offset = 0; - - for (uint32 y = 0; y < recordCount; ++y) - { - if (i >= 0) - indexTable[getRecord(y).getUInt(i)] = &dataTable[offset]; - else - indexTable[y] = &dataTable[offset]; - - for (uint32 x=0; x < fieldCount; ++x) - { - switch (format[x]) - { - case FT_FLOAT: - *((float*)(&dataTable[offset])) = getRecord(y).getFloat(x); - offset += sizeof(float); - break; - case FT_IND: - case FT_INT: - *((uint32*)(&dataTable[offset])) = getRecord(y).getUInt(x); - offset += sizeof(uint32); - break; - case FT_BYTE: - *((uint8*)(&dataTable[offset])) = getRecord(y).getUInt8(x); - offset += sizeof(uint8); - break; - case FT_STRING: - *((char**)(&dataTable[offset])) = NULL; // will replace non-empty or "" strings in AutoProduceStrings - offset += sizeof(char*); - break; - case FT_LOGIC: - ASSERT(false && "Attempted to load DBC files that do not have field types that match what is in the core. Check DBCfmt.h or your DBC files."); - break; - case FT_NA: - case FT_NA_BYTE: - case FT_SORT: - break; - default: - ASSERT(false && "Unknown field format character in DBCfmt.h"); - break; - } - } - } - - sqlDataTable = dataTable + offset; - - return dataTable; -} - -char* DBCFileLoader::AutoProduceStrings(const char* format, char* dataTable) -{ - if (strlen(format) != fieldCount) - return NULL; - - char* stringPool = new char[stringSize]; - memcpy(stringPool, stringTable, stringSize); - - uint32 offset = 0; - - for (uint32 y = 0; y < recordCount; ++y) - { - for (uint32 x = 0; x < fieldCount; ++x) - { - switch (format[x]) - { - case FT_FLOAT: - offset += sizeof(float); - break; - case FT_IND: - case FT_INT: - offset += sizeof(uint32); - break; - case FT_BYTE: - offset += sizeof(uint8); - break; - case FT_STRING: - { - // fill only not filled entries - char** slot = (char**)(&dataTable[offset]); - if (!*slot || !**slot) - { - const char * st = getRecord(y).getString(x); - *slot=stringPool+(st-(const char*)stringTable); - } - offset += sizeof(char*); - break; - } - case FT_LOGIC: - ASSERT(false && "Attempted to load DBC files that does not have field types that match what is in the core. Check DBCfmt.h or your DBC files."); - break; - case FT_NA: - case FT_NA_BYTE: - case FT_SORT: - break; - default: - ASSERT(false && "Unknown field format character in DBCfmt.h"); - break; - } - } - } - - return stringPool; -} diff --git a/src/server/shared/DataStores/DBCFileLoader.h b/src/server/shared/DataStores/DBCFileLoader.h deleted file mode 100644 index 1c005a9e670..00000000000 --- a/src/server/shared/DataStores/DBCFileLoader.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2009 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 the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef DBC_FILE_LOADER_H -#define DBC_FILE_LOADER_H -#include "Define.h" -#include "Utilities/ByteConverter.h" -#include - -enum DbcFieldFormat -{ - FT_NA='x', //not used or unknown, 4 byte size - FT_NA_BYTE='X', //not used or unknown, byte - FT_STRING='s', //char* - FT_FLOAT='f', //float - FT_INT='i', //uint32 - FT_BYTE='b', //uint8 - FT_SORT='d', //sorted by this field, field is not included - FT_IND='n', //the same, but parsed to data - FT_LOGIC='l', //Logical (boolean) - FT_SQL_PRESENT='p', //Used in sql format to mark column present in sql dbc - FT_SQL_ABSENT='a' //Used in sql format to mark column absent in sql dbc -}; - -class TC_SHARED_API DBCFileLoader -{ - public: - DBCFileLoader(); - ~DBCFileLoader(); - - bool Load(const char *filename, const char *fmt); - - class Record - { - public: - float getFloat(size_t field) const - { - assert(field < file.fieldCount); - float val = *reinterpret_cast(offset+file.GetOffset(field)); - EndianConvert(val); - return val; - } - uint32 getUInt(size_t field) const - { - assert(field < file.fieldCount); - uint32 val = *reinterpret_cast(offset+file.GetOffset(field)); - EndianConvert(val); - return val; - } - uint8 getUInt8(size_t field) const - { - assert(field < file.fieldCount); - return *reinterpret_cast(offset+file.GetOffset(field)); - } - - const char *getString(size_t field) const - { - assert(field < file.fieldCount); - size_t stringOffset = getUInt(field); - assert(stringOffset < file.stringSize); - return reinterpret_cast(file.stringTable + stringOffset); - } - - private: - Record(DBCFileLoader &file_, unsigned char *offset_): offset(offset_), file(file_) { } - unsigned char *offset; - DBCFileLoader &file; - - friend class DBCFileLoader; - - }; - - // Get record by id - Record getRecord(size_t id); - /// Get begin iterator over records - - uint32 GetNumRows() const { return recordCount; } - uint32 GetRowSize() const { return recordSize; } - uint32 GetCols() const { return fieldCount; } - uint32 GetOffset(size_t id) const { return (fieldsOffset != NULL && id < fieldCount) ? fieldsOffset[id] : 0; } - bool IsLoaded() const { return data != NULL; } - char* AutoProduceData(const char* fmt, uint32& count, char**& indexTable, uint32 sqlRecordCount, uint32 sqlHighestIndex, char *& sqlDataTable); - char* AutoProduceStrings(const char* fmt, char* dataTable); - static uint32 GetFormatRecordSize(const char * format, int32 * index_pos = NULL); - private: - - uint32 recordSize; - uint32 recordCount; - uint32 fieldCount; - uint32 stringSize; - uint32 *fieldsOffset; - unsigned char *data; - unsigned char *stringTable; - - DBCFileLoader(DBCFileLoader const& right) = delete; - DBCFileLoader& operator=(DBCFileLoader const& right) = delete; -}; -#endif diff --git a/src/server/shared/DataStores/DBCStorageIterator.h b/src/server/shared/DataStores/DBCStorageIterator.h new file mode 100644 index 00000000000..be1e58db967 --- /dev/null +++ b/src/server/shared/DataStores/DBCStorageIterator.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef DBCStorageIterator_h__ +#define DBCStorageIterator_h__ + +#include "Define.h" +#include + +template +class DBCStorageIterator : public std::iterator +{ + public: + DBCStorageIterator() : _index(nullptr), _pos(0), _end(0) { } + DBCStorageIterator(T** index, uint32 size, uint32 pos = 0) : _index(index), _pos(pos), _end(size) + { + if (_pos < _end) + { + while (_pos < _end && !_index[_pos]) + ++_pos; + } + } + + T const* operator->() { return _index[_pos]; } + T const* operator*() { return _index[_pos]; } + + bool operator==(DBCStorageIterator const& right) const { /*ASSERT(_index == right._index, "Iterator belongs to a different container")*/ return _pos == right._pos; } + bool operator!=(DBCStorageIterator const& right) const { return !(*this == right); } + + DBCStorageIterator& operator++() + { + if (_pos < _end) + { + do + ++_pos; + while (_pos < _end && !_index[_pos]); + } + + return *this; + } + + DBCStorageIterator operator++(int) + { + DBCStorageIterator tmp = *this; + ++*this; + return tmp; + } + + private: + T** _index; + uint32 _pos; + uint32 _end; +}; + +#endif // DBCStorageIterator_h__ diff --git a/src/server/shared/DataStores/DBCStore.cpp b/src/server/shared/DataStores/DBCStore.cpp new file mode 100644 index 00000000000..30cae057f90 --- /dev/null +++ b/src/server/shared/DataStores/DBCStore.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "DBCStore.h" +#include "DBCDatabaseLoader.h" + +DBCStorageBase::DBCStorageBase(char const* fmt) : _fieldCount(0), _fileFormat(fmt), _dataTable(nullptr), _indexTableSize(0) +{ +} + +DBCStorageBase::~DBCStorageBase() +{ + delete[] _dataTable; + delete[] _dataTableEx; + for (char* strings : _stringPool) + delete[] strings; +} + +bool DBCStorageBase::Load(std::string const& path, char**& indexTable) +{ + indexTable = nullptr; + + DBCFileLoader dbc; + // Check if load was sucessful, only then continue + if (!dbc.Load(path.c_str(), _fileFormat)) + return false; + + _fieldCount = dbc.GetCols(); + + // load raw non-string data + _dataTable = dbc.AutoProduceData(_fileFormat, _indexTableSize, indexTable); + + // load strings from dbc data + if (char* stringBlock = dbc.AutoProduceStrings(_fileFormat, _dataTable)) + _stringPool.push_back(stringBlock); + + // error in dbc file at loading if NULL + return indexTable != nullptr; +} + +bool DBCStorageBase::LoadStringsFrom(std::string const& path, char** indexTable) +{ + // DBC must be already loaded using Load + if (!indexTable) + return false; + + DBCFileLoader dbc; + // Check if load was successful, only then continue + if (!dbc.Load(path.c_str(), _fileFormat)) + return false; + + // load strings from another locale dbc data + if (char* stringBlock = dbc.AutoProduceStrings(_fileFormat, _dataTable)) + _stringPool.push_back(stringBlock); + + return true; +} + +void DBCStorageBase::LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey, char**& indexTable) +{ + _dataTableEx = DBCDatabaseLoader(path, dbFormat, primaryKey, _fileFormat).Load(_indexTableSize, indexTable); +} diff --git a/src/server/shared/DataStores/DBCStore.h b/src/server/shared/DataStores/DBCStore.h index b11bb0b74d4..e04f434cf89 100644 --- a/src/server/shared/DataStores/DBCStore.h +++ b/src/server/shared/DataStores/DBCStore.h @@ -19,289 +19,83 @@ #ifndef DBCSTORE_H #define DBCSTORE_H -#include "DBCFileLoader.h" -#include "Logging/Log.h" -#include "Field.h" -#include "DatabaseWorkerPool.h" -#include "Implementation/WorldDatabase.h" -#include "DatabaseEnv.h" +#include "Common.h" +#include "DBCStorageIterator.h" +#include -struct SqlDbc + /// Interface class for common access +class TC_SHARED_API DBCStorageBase { - std::string const* formatString; - std::string const* indexName; - std::string sqlTableName; - int32 indexPos; - int32 sqlIndexPos; - SqlDbc(std::string const* _filename, std::string const* _format, std::string const* _idname, char const* fmt) - : formatString(_format), indexName (_idname), sqlIndexPos(0) - { - // Convert dbc file name to sql table name - sqlTableName = *_filename; - for (uint32 i = 0; i< sqlTableName.size(); ++i) - { - if (isalpha(sqlTableName[i])) - sqlTableName[i] = char(tolower(sqlTableName[i])); - else if (sqlTableName[i] == '.') - sqlTableName[i] = '_'; - } - - // Get sql index position - DBCFileLoader::GetFormatRecordSize(fmt, &indexPos); - if (indexPos >= 0) - { - uint32 uindexPos = uint32(indexPos); - for (uint32 x = 0; x < formatString->size(); ++x) - { - // Count only fields present in sql - if ((*formatString)[x] == FT_SQL_PRESENT) - { - if (x == uindexPos) - break; - ++sqlIndexPos; - } - } - } - } - -private: - SqlDbc(SqlDbc const& right) = delete; - SqlDbc& operator=(SqlDbc const& right) = delete; + public: + DBCStorageBase(char const* fmt); + virtual ~DBCStorageBase(); + + char const* GetFormat() const { return _fileFormat; } + uint32 GetFieldCount() const { return _fieldCount; } + + virtual bool Load(std::string const& path) = 0; + virtual bool LoadStringsFrom(std::string const& path) = 0; + virtual void LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey) = 0; + + protected: + bool Load(std::string const& path, char**& indexTable); + bool LoadStringsFrom(std::string const& path, char** indexTable); + void LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey, char**& indexTable); + + uint32 _fieldCount; + char const* _fileFormat; + char* _dataTable; + char* _dataTableEx; + std::vector _stringPool; + uint32 _indexTableSize; }; -template -class DBCStorage +template +class DBCStorage : public DBCStorageBase { - typedef std::list StringPoolList; public: - explicit DBCStorage(char const* f) - : fmt(f), nCount(0), fieldCount(0), dataTable(NULL) - { - indexTable.asT = NULL; - } + typedef DBCStorageIterator iterator; - ~DBCStorage() { Clear(); } - - T const* LookupEntry(uint32 id) const + explicit DBCStorage(char const* fmt) : DBCStorageBase(fmt) { - return (id >= nCount) ? NULL : indexTable.asT[id]; + _indexTable.AsT = nullptr; } - T const* AssertEntry(uint32 id) const + ~DBCStorage() { - T const* entry = LookupEntry(id); - ASSERT(entry); - return entry; + delete[] reinterpret_cast(_indexTable.AsT); } - uint32 GetNumRows() const { return nCount; } - char const* GetFormat() const { return fmt; } - uint32 GetFieldCount() const { return fieldCount; } - - bool Load(char const* fn, SqlDbc* sql) - { - DBCFileLoader dbc; - // Check if load was sucessful, only then continue - if (!dbc.Load(fn, fmt)) - return false; - - uint32 sqlRecordCount = 0; - uint32 sqlHighestIndex = 0; - Field* fields = NULL; - QueryResult result = QueryResult(NULL); - // Load data from sql - if (sql) - { - std::string query = "SELECT * FROM " + sql->sqlTableName; - if (sql->indexPos >= 0) - query +=" ORDER BY " + *sql->indexName + " DESC"; - query += ';'; - - - result = WorldDatabase.Query(query.c_str()); - if (result) - { - sqlRecordCount = uint32(result->GetRowCount()); - if (sql->indexPos >= 0) - { - fields = result->Fetch(); - sqlHighestIndex = fields[sql->sqlIndexPos].GetUInt32(); - } - - // Check if sql index pos is valid - if (int32(result->GetFieldCount() - 1) < sql->sqlIndexPos) - { - TC_LOG_ERROR("server.loading", "Invalid index pos for dbc:'%s'", sql->sqlTableName.c_str()); - return false; - } - } - } - - char* sqlDataTable = NULL; - fieldCount = dbc.GetCols(); - - dataTable = reinterpret_cast(dbc.AutoProduceData(fmt, nCount, indexTable.asChar, - sqlRecordCount, sqlHighestIndex, sqlDataTable)); + T const* LookupEntry(uint32 id) const { return (id >= _indexTableSize) ? nullptr : _indexTable.AsT[id]; } + T const* AssertEntry(uint32 id) const { return ASSERT_NOTNULL(LookupEntry(id)); } - stringPoolList.push_back(dbc.AutoProduceStrings(fmt, reinterpret_cast(dataTable))); + uint32 GetNumRows() const { return _indexTableSize; } - // Insert sql data into arrays - if (result) - { - if (indexTable.asT) - { - uint32 offset = 0; - uint32 rowIndex = dbc.GetNumRows(); - do - { - if (!fields) - fields = result->Fetch(); - - if (sql->indexPos >= 0) - { - uint32 id = fields[sql->sqlIndexPos].GetUInt32(); - if (indexTable.asT[id]) - { - TC_LOG_ERROR("server.loading", "Index %d already exists in dbc:'%s'", id, sql->sqlTableName.c_str()); - return false; - } - - indexTable.asT[id] = reinterpret_cast(&sqlDataTable[offset]); - } - else - indexTable.asT[rowIndex]= reinterpret_cast(&sqlDataTable[offset]); - - uint32 columnNumber = 0; - uint32 sqlColumnNumber = 0; - - for (; columnNumber < sql->formatString->size(); ++columnNumber) - { - if ((*sql->formatString)[columnNumber] == FT_SQL_ABSENT) - { - switch (fmt[columnNumber]) - { - case FT_FLOAT: - *reinterpret_cast(&sqlDataTable[offset]) = 0.0f; - offset += 4; - break; - case FT_IND: - case FT_INT: - *reinterpret_cast(&sqlDataTable[offset]) = uint32(0); - offset += 4; - break; - case FT_BYTE: - *reinterpret_cast(&sqlDataTable[offset]) = uint8(0); - offset += 1; - break; - case FT_STRING: - // Beginning of the pool - empty string - *reinterpret_cast(&sqlDataTable[offset]) = stringPoolList.back(); - offset += sizeof(char*); - break; - } - } - else if ((*sql->formatString)[columnNumber] == FT_SQL_PRESENT) - { - bool validSqlColumn = true; - switch (fmt[columnNumber]) - { - case FT_FLOAT: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetFloat(); - offset += 4; - break; - case FT_IND: - case FT_INT: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetUInt32(); - offset += 4; - break; - case FT_BYTE: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetUInt8(); - offset += 1; - break; - case FT_STRING: - TC_LOG_ERROR("server.loading", "Unsupported data type in table '%s' at char %d", sql->sqlTableName.c_str(), columnNumber); - return false; - case FT_SORT: - break; - default: - validSqlColumn = false; - break; - } - if (validSqlColumn && (columnNumber != (sql->formatString->size()-1))) - sqlColumnNumber++; - } - else - { - TC_LOG_ERROR("server.loading", "Incorrect sql format string '%s' at char %d", sql->sqlTableName.c_str(), columnNumber); - return false; - } - } - - if (sqlColumnNumber != (result->GetFieldCount() - 1)) - { - TC_LOG_ERROR("server.loading", "SQL and DBC format strings are not matching for table: '%s'", sql->sqlTableName.c_str()); - return false; - } - - fields = NULL; - ++rowIndex; - } while (result->NextRow()); - } - } - - // error in dbc file at loading if NULL - return indexTable.asT != NULL; + bool Load(std::string const& path) override + { + return DBCStorageBase::Load(path, _indexTable.AsChar); } - bool LoadStringsFrom(char const* fn) + bool LoadStringsFrom(std::string const& path) override { - // DBC must be already loaded using Load - if (!indexTable.asT) - return false; - - DBCFileLoader dbc; - // Check if load was successful, only then continue - if (!dbc.Load(fn, fmt)) - return false; - - stringPoolList.push_back(dbc.AutoProduceStrings(fmt, reinterpret_cast(dataTable))); - - return true; + return DBCStorageBase::LoadStringsFrom(path, _indexTable.AsChar); } - void Clear() + void LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey) override { - if (!indexTable.asT) - return; - - delete[] reinterpret_cast(indexTable.asT); - indexTable.asT = NULL; - delete[] reinterpret_cast(dataTable); - dataTable = NULL; - - while (!stringPoolList.empty()) - { - delete[] stringPoolList.front(); - stringPoolList.pop_front(); - } - - nCount = 0; + DBCStorageBase::LoadFromDB(path, dbFormat, primaryKey, _indexTable.AsChar); } - private: - char const* fmt; - uint32 nCount; - uint32 fieldCount; + iterator begin() { return iterator(_indexTable.AsT, _indexTableSize); } + iterator end() { return iterator(_indexTable.AsT, _indexTableSize, _indexTableSize); } + private: union { - T** asT; - char** asChar; + T** AsT; + char** AsChar; } - indexTable; - - T* dataTable; - StringPoolList stringPoolList; + _indexTable; DBCStorage(DBCStorage const& right) = delete; DBCStorage& operator=(DBCStorage const& right) = delete; diff --git a/src/server/shared/Dynamic/FactoryHolder.h b/src/server/shared/Dynamic/FactoryHolder.h index 9c9e2ada5e0..9e67fe11467 100644 --- a/src/server/shared/Dynamic/FactoryHolder.h +++ b/src/server/shared/Dynamic/FactoryHolder.h @@ -20,8 +20,8 @@ #define TRINITY_FACTORY_HOLDER #include "Define.h" -#include "Dynamic/TypeList.h" #include "ObjectRegistry.h" +#include "TypeList.h" /** FactoryHolder holds a factory object of a specific type */ diff --git a/src/server/shared/Dynamic/LinkedList.h b/src/server/shared/Dynamic/LinkedList.h index 0d64c337cbe..74f4ca553f4 100644 --- a/src/server/shared/Dynamic/LinkedList.h +++ b/src/server/shared/Dynamic/LinkedList.h @@ -165,13 +165,13 @@ class LinkedListHead { // construct with node pointer _Pnode } - Iterator& operator=(Iterator const &_Right) + Iterator& operator=(Iterator const& _Right) { _Ptr = _Right._Ptr; return *this; } - Iterator& operator=(const_pointer const &_Right) + Iterator& operator=(const_pointer const& _Right) { _Ptr = pointer(_Right); return *this; @@ -213,22 +213,22 @@ class LinkedListHead return (_Tmp); } - bool operator==(Iterator const &_Right) const + bool operator==(Iterator const& _Right) const { // test for iterator equality return (_Ptr == _Right._Ptr); } - bool operator!=(Iterator const &_Right) const + bool operator!=(Iterator const& _Right) const { // test for iterator inequality return (!(*this == _Right)); } - bool operator==(pointer const &_Right) const + bool operator==(pointer const& _Right) const { // test for pointer equality return (_Ptr != _Right); } - bool operator!=(pointer const &_Right) const + bool operator!=(pointer const& _Right) const { // test for pointer equality return (!(*this == _Right)); } diff --git a/src/server/shared/Dynamic/LinkedReference/Reference.h b/src/server/shared/Dynamic/LinkedReference/Reference.h index c0c4ec21a80..4002de2d584 100644 --- a/src/server/shared/Dynamic/LinkedReference/Reference.h +++ b/src/server/shared/Dynamic/LinkedReference/Reference.h @@ -40,7 +40,7 @@ template class Reference : public LinkedListElement // Tell our refFrom (source) object, that the link is cut (Target destroyed) virtual void sourceObjectDestroyLink() = 0; public: - Reference() { iRefTo = NULL; iRefFrom = NULL; } + Reference() { iRefTo = nullptr; iRefFrom = nullptr; } virtual ~Reference() { } // Create new link @@ -49,7 +49,7 @@ template class Reference : public LinkedListElement ASSERT(fromObj); // fromObj MUST not be NULL if (isValid()) unlink(); - if (toObj != NULL) + if (toObj != nullptr) { iRefTo = toObj; iRefFrom = fromObj; @@ -63,8 +63,8 @@ template class Reference : public LinkedListElement { targetObjectDestroyLink(); delink(); - iRefTo = NULL; - iRefFrom = NULL; + iRefTo = nullptr; + iRefFrom = nullptr; } // Link is invalid due to destruction of referenced target object. Call comes from the refTo object @@ -73,12 +73,12 @@ template class Reference : public LinkedListElement { sourceObjectDestroyLink(); delink(); - iRefTo = NULL; + iRefTo = nullptr; } bool isValid() const // Only check the iRefTo { - return iRefTo != NULL; + return iRefTo != nullptr; } Reference * next() { return((Reference *) LinkedListElement::next()); } diff --git a/src/server/shared/Dynamic/ObjectRegistry.h b/src/server/shared/Dynamic/ObjectRegistry.h index 5f614819b13..8ed72c476e8 100644 --- a/src/server/shared/Dynamic/ObjectRegistry.h +++ b/src/server/shared/Dynamic/ObjectRegistry.h @@ -82,6 +82,8 @@ class ObjectRegistry final // non instanceable, only static ObjectRegistry() { } ~ObjectRegistry() { } + ObjectRegistry(ObjectRegistry const&) = delete; + ObjectRegistry& operator=(ObjectRegistry const&) = delete; }; #endif diff --git a/src/server/shared/Dynamic/TypeContainer.h b/src/server/shared/Dynamic/TypeContainer.h deleted file mode 100644 index 7e825136755..00000000000 --- a/src/server/shared/Dynamic/TypeContainer.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2009 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 the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef TRINITY_TYPECONTAINER_H -#define TRINITY_TYPECONTAINER_H - -/* - * Here, you'll find a series of containers that allow you to hold multiple - * types of object at the same time. - */ - -#include -#include -#include -#include "Define.h" -#include "Dynamic/TypeList.h" -#include "GridRefManager.h" - -/* - * @class ContainerMapList is a mulit-type container for map elements - * By itself its meaningless but collaborate along with TypeContainers, - * it become the most powerfully container in the whole system. - */ -template -struct ContainerMapList -{ - //std::map _element; - GridRefManager _element; -}; - -template<> -struct ContainerMapList /* nothing is in type null */ -{ -}; - -template -struct ContainerMapList > -{ - ContainerMapList _elements; - ContainerMapList _TailElements; -}; - -template -struct ContainerUnorderedMap -{ - std::unordered_map _element; -}; - -template -struct ContainerUnorderedMap -{ -}; - -template -struct ContainerUnorderedMap, KEY_TYPE> -{ - ContainerUnorderedMap _elements; - ContainerUnorderedMap _TailElements; -}; - -#include "TypeContainerFunctions.h" - -/* - * @class TypeMapContainer contains a fixed number of types and is - * determined at compile time. This is probably the most complicated - * class and do its simplest thing, that is, holds objects - * of different types. - */ - -template -class TypeMapContainer -{ - public: - template size_t Count() const { return Trinity::Count(i_elements, (SPECIFIC_TYPE*)NULL); } - - /// inserts a specific object into the container - template - bool insert(SPECIFIC_TYPE *obj) - { - SPECIFIC_TYPE* t = Trinity::Insert(i_elements, obj); - return (t != NULL); - } - - /// Removes the object from the container, and returns the removed object - //template - //bool remove(SPECIFIC_TYPE* obj) - //{ - // SPECIFIC_TYPE* t = Trinity::Remove(i_elements, obj); - // return (t != NULL); - //} - - ContainerMapList & GetElements(void) { return i_elements; } - const ContainerMapList & GetElements(void) const { return i_elements;} - - private: - ContainerMapList i_elements; -}; - -template -class TypeUnorderedMapContainer -{ -public: - template - bool Insert(KEY_TYPE const& handle, SPECIFIC_TYPE* obj) - { - return Trinity::Insert(_elements, handle, obj); - } - - template - bool Remove(KEY_TYPE const& handle) - { - return Trinity::Remove(_elements, handle, (SPECIFIC_TYPE*)NULL); - } - - template - SPECIFIC_TYPE* Find(KEY_TYPE const& handle) - { - return Trinity::Find(_elements, handle, (SPECIFIC_TYPE*)NULL); - } - - ContainerUnorderedMap& GetElements() { return _elements; } - ContainerUnorderedMap const& GetElements() const { return _elements; } - -private: - ContainerUnorderedMap _elements; -}; - -#endif diff --git a/src/server/shared/Dynamic/TypeContainerFunctions.h b/src/server/shared/Dynamic/TypeContainerFunctions.h deleted file mode 100644 index 97d20922a05..00000000000 --- a/src/server/shared/Dynamic/TypeContainerFunctions.h +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2009 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 the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef TYPECONTAINER_FUNCTIONS_H -#define TYPECONTAINER_FUNCTIONS_H - -/* - * Here you'll find a list of helper functions to make - * the TypeContainer usefull. Without it, its hard - * to access or mutate the container. - */ - -#include "Define.h" -#include "Dynamic/TypeList.h" -#include -#include - -namespace Trinity -{ - // Helpers - // Insert helpers - template - bool Insert(ContainerUnorderedMap& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* obj) - { - auto i = elements._element.find(handle); - if (i == elements._element.end()) - { - elements._element[handle] = obj; - return true; - } - else - { - ASSERT(i->second == obj, "Object with certain key already in but objects are different!"); - return false; - } - } - - template - bool Insert(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) - { - return false; - } - - template - bool Insert(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) - { - return false; - } - - template - bool Insert(ContainerUnorderedMap, KEY_TYPE>& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* obj) - { - bool ret = Insert(elements._elements, handle, obj); - return ret ? ret : Insert(elements._TailElements, handle, obj); - } - - // Find helpers - template - SPECIFIC_TYPE* Find(ContainerUnorderedMap const& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) - { - auto i = elements._element.find(handle); - if (i == elements._element.end()) - return nullptr; - else - return i->second; - } - - template - SPECIFIC_TYPE* Find(ContainerUnorderedMap const& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) - { - return nullptr; - } - - template - SPECIFIC_TYPE* Find(ContainerUnorderedMap const& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) - { - return nullptr; - } - - template - SPECIFIC_TYPE* Find(ContainerUnorderedMap, KEY_TYPE> const& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) - { - SPECIFIC_TYPE* ret = Find(elements._elements, handle, (SPECIFIC_TYPE*)nullptr); - return ret ? ret : Find(elements._TailElements, handle, (SPECIFIC_TYPE*)nullptr); - } - - // Erase helpers - template - bool Remove(ContainerUnorderedMap& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) - { - elements._element.erase(handle); - return true; - } - - template - bool Remove(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) - { - return false; - } - - template - bool Remove(ContainerUnorderedMap& /*elements*/, KEY_TYPE const& /*handle*/, SPECIFIC_TYPE* /*obj*/) - { - return false; - } - - template - bool Remove(ContainerUnorderedMap, KEY_TYPE>& elements, KEY_TYPE const& handle, SPECIFIC_TYPE* /*obj*/) - { - bool ret = Remove(elements._elements, handle, (SPECIFIC_TYPE*)nullptr); - return ret ? ret : Remove(elements._TailElements, handle, (SPECIFIC_TYPE*)nullptr); - } - - /* ContainerMapList Helpers */ - // count functions - template - size_t Count(ContainerMapList const& elements, SPECIFIC_TYPE* /*fake*/) - { - return elements._element.getSize(); - } - - template - size_t Count(ContainerMapList const& /*elements*/, SPECIFIC_TYPE* /*fake*/) - { - return 0; - } - - template - size_t Count(ContainerMapList const& /*elements*/, SPECIFIC_TYPE* /*fake*/) - { - return 0; - } - - template - size_t Count(ContainerMapList> const& elements, SPECIFIC_TYPE* fake) - { - return Count(elements._elements, fake); - } - - template - size_t Count(ContainerMapList> const& elements, SPECIFIC_TYPE* fake) - { - return Count(elements._TailElements, fake); - } - - // non-const insert functions - template - SPECIFIC_TYPE* Insert(ContainerMapList& elements, SPECIFIC_TYPE* obj) - { - //elements._element[hdl] = obj; - obj->AddToGrid(elements._element); - return obj; - } - - template - SPECIFIC_TYPE* Insert(ContainerMapList& /*elements*/, SPECIFIC_TYPE* /*obj*/) - { - return nullptr; - } - - // this is a missed - template - SPECIFIC_TYPE* Insert(ContainerMapList& /*elements*/, SPECIFIC_TYPE* /*obj*/) - { - return nullptr; // a missed - } - - // Recursion - template - SPECIFIC_TYPE* Insert(ContainerMapList>& elements, SPECIFIC_TYPE* obj) - { - SPECIFIC_TYPE* t = Insert(elements._elements, obj); - return (t != nullptr ? t : Insert(elements._TailElements, obj)); - } - - //// non-const remove method - //template SPECIFIC_TYPE* Remove(ContainerMapList & /*elements*/, SPECIFIC_TYPE *obj) - //{ - // obj->GetGridRef().unlink(); - // return obj; - //} - - //template SPECIFIC_TYPE* Remove(ContainerMapList &/*elements*/, SPECIFIC_TYPE * /*obj*/) - //{ - // return nullptr; - //} - - //// this is a missed - //template SPECIFIC_TYPE* Remove(ContainerMapList &/*elements*/, SPECIFIC_TYPE * /*obj*/) - //{ - // return nullptr; // a missed - //} - - //template SPECIFIC_TYPE* Remove(ContainerMapList > &elements, SPECIFIC_TYPE *obj) - //{ - // // The head element is bad - // SPECIFIC_TYPE* t = Remove(elements._elements, obj); - // return (t != nullptr ? t : Remove(elements._TailElements, obj)); - //} -} -#endif - diff --git a/src/server/shared/Dynamic/TypeContainerVisitor.h b/src/server/shared/Dynamic/TypeContainerVisitor.h deleted file mode 100644 index f15cfe66758..00000000000 --- a/src/server/shared/Dynamic/TypeContainerVisitor.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2008-2017 TrinityCore - * Copyright (C) 2005-2009 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 the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef TRINITY_TYPECONTAINERVISITOR_H -#define TRINITY_TYPECONTAINERVISITOR_H - -/* - * @class TypeContainerVisitor is implemented as a visitor pattern. It is - * a visitor to the TypeContainerList or TypeContainerMapList. The visitor has - * to overload its types as a visit method is called. - */ - -#include "Define.h" -#include "Dynamic/TypeContainer.h" - -// forward declaration -template class TypeContainerVisitor; - -// visitor helper -template void VisitorHelper(VISITOR &v, TYPE_CONTAINER &c) -{ - v.Visit(c); -} - -// terminate condition container map list -template void VisitorHelper(VISITOR &/*v*/, ContainerMapList &/*c*/) { } - -template void VisitorHelper(VISITOR &v, ContainerMapList &c) -{ - v.Visit(c._element); -} - -// recursion container map list -template void VisitorHelper(VISITOR &v, ContainerMapList > &c) -{ - VisitorHelper(v, c._elements); - VisitorHelper(v, c._TailElements); -} - -// for TypeMapContainer -template void VisitorHelper(VISITOR &v, TypeMapContainer &c) -{ - VisitorHelper(v, c.GetElements()); -} - -// TypeUnorderedMapContainer -template -void VisitorHelper(VISITOR& /*v*/, ContainerUnorderedMap& /*c*/) { } - -template -void VisitorHelper(VISITOR& v, ContainerUnorderedMap& c) -{ - v.Visit(c._element); -} - -template -void VisitorHelper(VISITOR& v, ContainerUnorderedMap, KEY_TYPE>& c) -{ - VisitorHelper(v, c._elements); - VisitorHelper(v, c._TailElements); -} - -template -void VisitorHelper(VISITOR& v, TypeUnorderedMapContainer& c) -{ - VisitorHelper(v, c.GetElements()); -} - -template -class TypeContainerVisitor -{ - public: - TypeContainerVisitor(VISITOR &v) : i_visitor(v) { } - - void Visit(TYPE_CONTAINER &c) - { - VisitorHelper(i_visitor, c); - } - - void Visit(const TYPE_CONTAINER &c) const - { - VisitorHelper(i_visitor, c); - } - - private: - VISITOR &i_visitor; -}; -#endif - diff --git a/src/server/shared/Memory.h b/src/server/shared/Memory.h index 7aeb4dc3f0a..e41e4baf025 100644 --- a/src/server/shared/Memory.h +++ b/src/server/shared/Memory.h @@ -1,4 +1,19 @@ - +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ #ifndef _MEMORY_H #define _MEMORY_H diff --git a/src/server/shared/Networking/AsyncAcceptor.h b/src/server/shared/Networking/AsyncAcceptor.h index 7c827ec4454..dc6c5332c23 100644 --- a/src/server/shared/Networking/AsyncAcceptor.h +++ b/src/server/shared/Networking/AsyncAcceptor.h @@ -19,7 +19,8 @@ #define __ASYNCACCEPT_H_ #include "Log.h" -#include +#include +#include #include #include diff --git a/src/server/shared/Packets/ByteBuffer.cpp b/src/server/shared/Packets/ByteBuffer.cpp index f9860f273ed..a4ab6e1daf7 100644 --- a/src/server/shared/Packets/ByteBuffer.cpp +++ b/src/server/shared/Packets/ByteBuffer.cpp @@ -17,11 +17,13 @@ */ #include "ByteBuffer.h" +#include "Errors.h" #include "MessageBuffer.h" #include "Common.h" #include "Log.h" - +#include "Util.h" #include +#include ByteBuffer::ByteBuffer(MessageBuffer&& buffer) : _rpos(0), _wpos(0), _storage(buffer.Move()) { @@ -51,6 +53,78 @@ ByteBufferSourceException::ByteBufferSourceException(size_t pos, size_t size, message().assign(ss.str()); } +ByteBuffer& ByteBuffer::operator>>(float& value) +{ + value = read(); + if (!std::isfinite(value)) + throw ByteBufferException(); + return *this; +} + +ByteBuffer& ByteBuffer::operator>>(double& value) +{ + value = read(); + if (!std::isfinite(value)) + throw ByteBufferException(); + return *this; +} + +uint32 ByteBuffer::ReadPackedTime() +{ + uint32 packedDate = read(); + tm lt = tm(); + + lt.tm_min = packedDate & 0x3F; + lt.tm_hour = (packedDate >> 6) & 0x1F; + //lt.tm_wday = (packedDate >> 11) & 7; + lt.tm_mday = ((packedDate >> 14) & 0x3F) + 1; + lt.tm_mon = (packedDate >> 20) & 0xF; + lt.tm_year = ((packedDate >> 24) & 0x1F) + 100; + + return uint32(mktime(<)); +} + +void ByteBuffer::append(uint8 const* src, size_t cnt) +{ + ASSERT(src, "Attempted to put a NULL-pointer in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", _wpos, size()); + ASSERT(cnt, "Attempted to put a zero-sized value in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", _wpos, size()); + ASSERT(size() < 10000000); + + size_t const newSize = _wpos + cnt; + if (_storage.capacity() < newSize) // custom memory allocation rules + { + if (newSize < 100) + _storage.reserve(300); + else if (newSize < 750) + _storage.reserve(2500); + else if (newSize < 6000) + _storage.reserve(10000); + else + _storage.reserve(400000); + } + + if (_storage.size() < newSize) + _storage.resize(newSize); + std::memcpy(&_storage[_wpos], src, cnt); + _wpos = newSize; +} + +void ByteBuffer::AppendPackedTime(time_t time) +{ + tm lt; + localtime_r(&time, <); + append((lt.tm_year - 100) << 24 | lt.tm_mon << 20 | (lt.tm_mday - 1) << 14 | lt.tm_wday << 11 | lt.tm_hour << 6 | lt.tm_min); +} + +void ByteBuffer::put(size_t pos, uint8 const* src, size_t cnt) +{ + ASSERT(pos + cnt <= size(), "Attempted to put value with size: " SZFMTD " in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", cnt, pos, size()); + ASSERT(src, "Attempted to put a NULL-pointer in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", pos, size()); + ASSERT(cnt, "Attempted to put a zero-sized value in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", pos, size()); + + std::memcpy(&_storage[pos], src, cnt); +} + void ByteBuffer::print_storage() const { if (!sLog->ShouldLog("network", LOG_LEVEL_TRACE)) // optimize disabled trace output diff --git a/src/server/shared/Packets/ByteBuffer.h b/src/server/shared/Packets/ByteBuffer.h index 1dc5fee6a12..77f09455cc7 100644 --- a/src/server/shared/Packets/ByteBuffer.h +++ b/src/server/shared/Packets/ByteBuffer.h @@ -20,9 +20,9 @@ #define _BYTEBUFFER_H #include "Define.h" -#include "Errors.h" #include "ByteConverter.h" -#include "Util.h" +#include +#include #include class MessageBuffer; @@ -109,7 +109,8 @@ class TC_SHARED_API ByteBuffer append((uint8 *)&value, sizeof(value)); } - template void put(size_t pos, T value) + template + void put(std::size_t pos, T value) { static_assert(std::is_fundamental::value, "append(compound)"); EndianConvert(value); @@ -249,21 +250,8 @@ class TC_SHARED_API ByteBuffer return *this; } - ByteBuffer &operator>>(float &value) - { - value = read(); - if (!std::isfinite(value)) - throw ByteBufferException(); - return *this; - } - - ByteBuffer &operator>>(double &value) - { - value = read(); - if (!std::isfinite(value)) - throw ByteBufferException(); - return *this; - } + ByteBuffer &operator>>(float &value); + ByteBuffer &operator>>(double &value); ByteBuffer &operator>>(std::string& value) { @@ -371,20 +359,7 @@ class TC_SHARED_API ByteBuffer } } - uint32 ReadPackedTime() - { - uint32 packedDate = read(); - tm lt = tm(); - - lt.tm_min = packedDate & 0x3F; - lt.tm_hour = (packedDate >> 6) & 0x1F; - //lt.tm_wday = (packedDate >> 11) & 7; - lt.tm_mday = ((packedDate >> 14) & 0x3F) + 1; - lt.tm_mon = (packedDate >> 20) & 0xF; - lt.tm_year = ((packedDate >> 24) & 0x1F) + 100; - - return uint32(mktime(<)); - } + uint32 ReadPackedTime(); ByteBuffer& ReadPackedTime(uint32& time) { @@ -432,36 +407,9 @@ class TC_SHARED_API ByteBuffer return append((const uint8 *)src, cnt * sizeof(T)); } - void append(const uint8 *src, size_t cnt) - { - if (!cnt) - throw ByteBufferSourceException(_wpos, size(), cnt); - - if (!src) - throw ByteBufferSourceException(_wpos, size(), cnt); + void append(uint8 const* src, size_t cnt); - ASSERT(size() < 10000000); - - size_t const newSize = _wpos + cnt; - if (_storage.capacity() < newSize) // custom memory allocation rules - { - if (newSize < 100) - _storage.reserve(300); - else if (newSize < 750) - _storage.reserve(2500); - else if (newSize < 6000) - _storage.reserve(10000); - else - _storage.reserve(400000); - } - - if (_storage.size() < newSize) - _storage.resize(newSize); - std::memcpy(&_storage[_wpos], src, cnt); - _wpos = newSize; - } - - void append(const ByteBuffer& buffer) + void append(ByteBuffer const& buffer) { if (buffer.wpos()) append(buffer.contents(), buffer.wpos()); @@ -496,23 +444,9 @@ class TC_SHARED_API ByteBuffer append(packGUID, size); } - void AppendPackedTime(time_t time) - { - tm lt; - localtime_r(&time, <); - append((lt.tm_year - 100) << 24 | lt.tm_mon << 20 | (lt.tm_mday - 1) << 14 | lt.tm_wday << 11 | lt.tm_hour << 6 | lt.tm_min); - } + void AppendPackedTime(time_t time); - void put(size_t pos, const uint8 *src, size_t cnt) - { - if (pos + cnt > size()) - throw ByteBufferPositionException(true, pos, cnt, size()); - - if (!src) - throw ByteBufferSourceException(_wpos, size(), cnt); - - std::memcpy(&_storage[pos], src, cnt); - } + void put(size_t pos, const uint8 *src, size_t cnt); void print_storage() const; @@ -525,85 +459,6 @@ class TC_SHARED_API ByteBuffer std::vector _storage; }; -template -inline ByteBuffer &operator<<(ByteBuffer &b, std::vector v) -{ - b << (uint32)v.size(); - for (typename std::vector::iterator i = v.begin(); i != v.end(); ++i) - { - b << *i; - } - return b; -} - -template -inline ByteBuffer &operator>>(ByteBuffer &b, std::vector &v) -{ - uint32 vsize; - b >> vsize; - v.clear(); - while (vsize--) - { - T t; - b >> t; - v.push_back(t); - } - return b; -} - -template -inline ByteBuffer &operator<<(ByteBuffer &b, std::list v) -{ - b << (uint32)v.size(); - for (typename std::list::iterator i = v.begin(); i != v.end(); ++i) - { - b << *i; - } - return b; -} - -template -inline ByteBuffer &operator>>(ByteBuffer &b, std::list &v) -{ - uint32 vsize; - b >> vsize; - v.clear(); - while (vsize--) - { - T t; - b >> t; - v.push_back(t); - } - return b; -} - -template -inline ByteBuffer &operator<<(ByteBuffer &b, std::map &m) -{ - b << (uint32)m.size(); - for (typename std::map::iterator i = m.begin(); i != m.end(); ++i) - { - b << i->first << i->second; - } - return b; -} - -template -inline ByteBuffer &operator>>(ByteBuffer &b, std::map &m) -{ - uint32 msize; - b >> msize; - m.clear(); - while (msize--) - { - K k; - V v; - b >> k >> v; - m.insert(make_pair(k, v)); - } - return b; -} - /// @todo Make a ByteBuffer.cpp and move all this inlining to it. template<> inline std::string ByteBuffer::read() { diff --git a/src/server/shared/PrecompiledHeaders/sharedPCH.cpp b/src/server/shared/PrecompiledHeaders/sharedPCH.cpp index 36eb3a877f0..3b045ac537a 100644 --- a/src/server/shared/PrecompiledHeaders/sharedPCH.cpp +++ b/src/server/shared/PrecompiledHeaders/sharedPCH.cpp @@ -1 +1,18 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "sharedPCH.h" diff --git a/src/server/shared/PrecompiledHeaders/sharedPCH.h b/src/server/shared/PrecompiledHeaders/sharedPCH.h index f864674d5ad..436b0453c30 100644 --- a/src/server/shared/PrecompiledHeaders/sharedPCH.h +++ b/src/server/shared/PrecompiledHeaders/sharedPCH.h @@ -1,4 +1,28 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + //add here most rarely modified headers to speed up debug build compilation -#include "TypeList.h" -#include "GitRevision.h" +#include "Common.h" +#include "Define.h" +#include "Errors.h" +#include "Log.h" +#include +#include +#include +#include +#include diff --git a/src/server/shared/Realm/Realm.cpp b/src/server/shared/Realm/Realm.cpp index 2768e17848b..571e798cc76 100644 --- a/src/server/shared/Realm/Realm.cpp +++ b/src/server/shared/Realm/Realm.cpp @@ -16,8 +16,9 @@ */ #include "Realm.h" +#include -boost::asio::ip::tcp::endpoint Realm::GetAddressForClient(boost::asio::ip::address const& clientAddr) const +boost::asio::ip::tcp_endpoint Realm::GetAddressForClient(boost::asio::ip::address const& clientAddr) const { boost::asio::ip::address realmIp; @@ -25,29 +26,27 @@ boost::asio::ip::tcp::endpoint Realm::GetAddressForClient(boost::asio::ip::addre if (clientAddr.is_loopback()) { // Try guessing if realm is also connected locally - if (LocalAddress.is_loopback() || ExternalAddress.is_loopback()) + if (LocalAddress->is_loopback() || ExternalAddress->is_loopback()) realmIp = clientAddr; else { // Assume that user connecting from the machine that bnetserver is located on // has all realms available in his local network - realmIp = LocalAddress; + realmIp = *LocalAddress; } } else { if (clientAddr.is_v4() && - (clientAddr.to_v4().to_ulong() & LocalSubnetMask.to_v4().to_ulong()) == - (LocalAddress.to_v4().to_ulong() & LocalSubnetMask.to_v4().to_ulong())) + (clientAddr.to_v4().to_ulong() & LocalSubnetMask->to_v4().to_ulong()) == + (LocalAddress->to_v4().to_ulong() & LocalSubnetMask->to_v4().to_ulong())) { - realmIp = LocalAddress; + realmIp = *LocalAddress; } else - realmIp = ExternalAddress; + realmIp = *ExternalAddress; } - boost::asio::ip::tcp::endpoint endpoint(realmIp, Port); - // Return external IP - return endpoint; + return boost::asio::ip::tcp_endpoint(realmIp, Port); } diff --git a/src/server/shared/Realm/Realm.h b/src/server/shared/Realm/Realm.h index e3cf181c120..b9b70592f0f 100644 --- a/src/server/shared/Realm/Realm.h +++ b/src/server/shared/Realm/Realm.h @@ -19,8 +19,7 @@ #define Realm_h__ #include "Common.h" -#include -#include +#include "AsioHacksFwd.h" enum RealmFlags { @@ -68,9 +67,9 @@ struct TC_SHARED_API Realm { RealmHandle Id; uint32 Build; - boost::asio::ip::address ExternalAddress; - boost::asio::ip::address LocalAddress; - boost::asio::ip::address LocalSubnetMask; + std::unique_ptr ExternalAddress; + std::unique_ptr LocalAddress; + std::unique_ptr LocalSubnetMask; uint16 Port; std::string Name; uint8 Type; @@ -79,7 +78,7 @@ struct TC_SHARED_API Realm AccountTypes AllowedSecurityLevel; float PopulationLevel; - boost::asio::ip::tcp::endpoint GetAddressForClient(boost::asio::ip::address const& clientAddr) const; + boost::asio::ip::tcp_endpoint GetAddressForClient(boost::asio::ip::address const& clientAddr) const; }; #endif // Realm_h__ diff --git a/src/server/shared/Realm/RealmList.cpp b/src/server/shared/Realm/RealmList.cpp index 37dd6bbaa17..a4a92ce0ec0 100644 --- a/src/server/shared/Realm/RealmList.cpp +++ b/src/server/shared/Realm/RealmList.cpp @@ -17,16 +17,18 @@ */ #include "RealmList.h" -#include "Database/DatabaseEnv.h" +#include "DatabaseEnv.h" +#include "Log.h" #include "Util.h" +#include +#include -RealmList::RealmList() : _updateInterval(0), _updateTimer(nullptr), _resolver(nullptr) +RealmList::RealmList() : _updateInterval(0) { } RealmList::~RealmList() { - delete _updateTimer; } RealmList* RealmList::Instance() @@ -39,8 +41,8 @@ RealmList* RealmList::Instance() void RealmList::Initialize(boost::asio::io_service& ioService, uint32 updateInterval) { _updateInterval = updateInterval; - _updateTimer = new boost::asio::deadline_timer(ioService); - _resolver = new boost::asio::ip::tcp::resolver(ioService); + _updateTimer = Trinity::make_unique(ioService); + _resolver = Trinity::make_unique(ioService); // Get the content of the realmlist table in the database UpdateRealms(boost::system::error_code()); @@ -51,9 +53,9 @@ void RealmList::Close() _updateTimer->cancel(); } -void RealmList::UpdateRealm(RealmHandle const& id, uint32 build, const std::string& name, boost::asio::ip::address const& address, boost::asio::ip::address const& localAddr, - boost::asio::ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, - float population) +void RealmList::UpdateRealm(RealmHandle const& id, uint32 build, std::string const& name, + boost::asio::ip::address const& address, boost::asio::ip::address const& localAddr, boost::asio::ip::address const& localSubmask, + uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population) { // Create new if not exist or update existed Realm& realm = _realms[id]; @@ -66,9 +68,12 @@ void RealmList::UpdateRealm(RealmHandle const& id, uint32 build, const std::stri realm.Timezone = timezone; realm.AllowedSecurityLevel = allowedSecurityLevel; realm.PopulationLevel = population; - realm.ExternalAddress = address; - realm.LocalAddress = localAddr; - realm.LocalSubnetMask = localSubmask; + if (!realm.ExternalAddress || *realm.ExternalAddress != address) + realm.ExternalAddress = Trinity::make_unique(address); + if (!realm.LocalAddress || *realm.LocalAddress != localAddr) + realm.LocalAddress = Trinity::make_unique(localAddr); + if (!realm.LocalSubnetMask || *realm.LocalSubnetMask != localSubmask) + realm.LocalSubnetMask = Trinity::make_unique(localSubmask); realm.Port = port; } @@ -110,7 +115,7 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) continue; } - boost::asio::ip::address externalAddress = (*endPoint).endpoint().address(); + boost::asio::ip::address externalAddress = endPoint->endpoint().address(); boost::asio::ip::tcp::resolver::query localAddressQuery(boost::asio::ip::tcp::v4(), fields[3].GetString(), ""); endPoint = _resolver->resolve(localAddressQuery, ec); @@ -120,7 +125,7 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) continue; } - boost::asio::ip::address localAddress = (*endPoint).endpoint().address(); + boost::asio::ip::address localAddress = endPoint->endpoint().address(); boost::asio::ip::tcp::resolver::query localSubmaskQuery(boost::asio::ip::tcp::v4(), fields[4].GetString(), ""); endPoint = _resolver->resolve(localSubmaskQuery, ec); @@ -130,7 +135,7 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) continue; } - boost::asio::ip::address localSubmask = (*endPoint).endpoint().address(); + boost::asio::ip::address localSubmask = endPoint->endpoint().address(); uint16 port = fields[5].GetUInt16(); uint8 icon = fields[6].GetUInt8(); @@ -181,5 +186,5 @@ Realm const* RealmList::GetRealm(RealmHandle const& id) const if (itr != _realms.end()) return &itr->second; - return NULL; + return nullptr; } diff --git a/src/server/shared/Realm/RealmList.h b/src/server/shared/Realm/RealmList.h index 7878779b736..5d6d2c16151 100644 --- a/src/server/shared/Realm/RealmList.h +++ b/src/server/shared/Realm/RealmList.h @@ -19,12 +19,24 @@ #ifndef _REALMLIST_H #define _REALMLIST_H -#include "Common.h" -#include "Realm/Realm.h" -#include -#include -#include -#include +#include "Define.h" +#include "Realm.h" +#include +#include +#include + +namespace boost +{ + namespace asio + { + class io_service; + } + + namespace system + { + class error_code; + } +} /// Storage object for the list of realms on the server class TC_SHARED_API RealmList @@ -46,13 +58,14 @@ private: RealmList(); void UpdateRealms(boost::system::error_code const& error); - void UpdateRealm(RealmHandle const& id, uint32 build, const std::string& name, boost::asio::ip::address const& address, boost::asio::ip::address const& localAddr, - boost::asio::ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population); + void UpdateRealm(RealmHandle const& id, uint32 build, std::string const& name, + boost::asio::ip::address const& address, boost::asio::ip::address const& localAddr, boost::asio::ip::address const& localSubmask, + uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population); RealmMap _realms; uint32 _updateInterval; - boost::asio::deadline_timer* _updateTimer; - boost::asio::ip::tcp::resolver* _resolver; + std::unique_ptr _updateTimer; + std::unique_ptr _resolver; }; #define sRealmList RealmList::Instance() diff --git a/src/server/worldserver/CommandLine/CliRunnable.cpp b/src/server/worldserver/CommandLine/CliRunnable.cpp index d5e03edbd04..8c05a47608d 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.cpp +++ b/src/server/worldserver/CommandLine/CliRunnable.cpp @@ -34,10 +34,10 @@ #include #include "Chat.h" -char* command_finder(const char* text, int state) +char* command_finder(char const* text, int state) { static size_t idx, len; - const char* ret; + char const* ret; std::vector const& cmd = ChatHandler::getCommandTable(); if (!state) @@ -61,12 +61,12 @@ char* command_finder(const char* text, int state) return strdup(ret); } - return ((char*)NULL); + return ((char*)nullptr); } -char** cli_completion(const char* text, int start, int /*end*/) +char** cli_completion(char const* text, int start, int /*end*/) { - char** matches = NULL; + char** matches = nullptr; if (start) rl_bind_key('\t', rl_abort); @@ -84,7 +84,7 @@ int cli_hook_func() #endif -void utf8print(void* /*arg*/, const char* str) +void utf8print(void* /*arg*/, char const* str) { #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS wchar_t wtemp_buf[6000]; @@ -92,9 +92,7 @@ void utf8print(void* /*arg*/, const char* str) if (!Utf8toWStr(str, strlen(str), wtemp_buf, wtemp_len)) return; - char temp_buf[6000]; - CharToOemBuffW(&wtemp_buf[0], &temp_buf[0], wtemp_len+1); - printf(temp_buf); + wprintf(L"%s", wtemp_buf); #else { printf("%s", str); @@ -119,7 +117,7 @@ int kb_hit_return() tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); - select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); + select(STDIN_FILENO+1, &fds, nullptr, nullptr, &tv); return FD_ISSET(STDIN_FILENO, &fds); } #endif @@ -156,7 +154,7 @@ void CliThread() rl_bind_key('\t', rl_complete); #endif - if (command_str != NULL) + if (command_str != nullptr) { for (int x=0; command_str[x]; ++x) if (command_str[x] == '\r' || command_str[x] == '\n') @@ -187,7 +185,7 @@ void CliThread() } fflush(stdout); - sWorld->QueueCliCommand(new CliCommandHolder(NULL, command.c_str(), &utf8print, &commandFinished)); + sWorld->QueueCliCommand(new CliCommandHolder(nullptr, command.c_str(), &utf8print, &commandFinished)); #if TRINITY_PLATFORM != TRINITY_PLATFORM_WINDOWS add_history(command.c_str()); free(command_str); diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index 5f0df199418..bbda89aad03 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -20,39 +20,43 @@ /// @{ /// \file -#include -#include -#include -#include -#include -#include - #include "Common.h" -#include "DatabaseEnv.h" +#include "AppenderDB.h" #include "AsyncAcceptor.h" -#include "RASession.h" -#include "Configuration/Config.h" -#include "OpenSSLCrypto.h" -#include "ProcessPriority.h" +#include "Banner.h" +#include "BattlegroundMgr.h" #include "BigNumber.h" -#include "World.h" -#include "MapManager.h" +#include "CliRunnable.h" +#include "Configuration/Config.h" +#include "DatabaseEnv.h" +#include "DatabaseLoader.h" +#include "GitRevision.h" #include "InstanceSaveMgr.h" +#include "MapManager.h" +#include "Metric.h" +#include "MySQLThreading.h" #include "ObjectAccessor.h" +#include "OpenSSLCrypto.h" +#include "OutdoorPvP/OutdoorPvPMgr.h" +#include "ProcessPriority.h" +#include "RASession.h" +#include "RealmList.h" +#include "ScriptLoader.h" #include "ScriptMgr.h" #include "ScriptReloadMgr.h" -#include "ScriptLoader.h" -#include "OutdoorPvP/OutdoorPvPMgr.h" -#include "BattlegroundMgr.h" #include "TCSoap.h" -#include "CliRunnable.h" -#include "GitRevision.h" +#include "World.h" #include "WorldSocket.h" #include "WorldSocketMgr.h" -#include "Realm/Realm.h" -#include "DatabaseLoader.h" -#include "AppenderDB.h" -#include "Metric.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include using namespace boost::program_options; namespace fs = boost::filesystem; @@ -145,20 +149,18 @@ extern int main(int argc, char** argv) // If logs are supposed to be handled async then we need to pass the io_service into the Log singleton sLog->Initialize(sConfigMgr->GetBoolDefault("Log.Async.Enable", false) ? ioService.get() : nullptr); - TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon)", GitRevision::GetFullVersion()); - TC_LOG_INFO("server.worldserver", " to stop.\n"); - TC_LOG_INFO("server.worldserver", " ______ __"); - TC_LOG_INFO("server.worldserver", "/\\__ _\\ __ __/\\ \\__"); - TC_LOG_INFO("server.worldserver", "\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); - TC_LOG_INFO("server.worldserver", " \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); - TC_LOG_INFO("server.worldserver", " \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); - TC_LOG_INFO("server.worldserver", " \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); - TC_LOG_INFO("server.worldserver", " \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); - TC_LOG_INFO("server.worldserver", " C O R E /\\___/"); - TC_LOG_INFO("server.worldserver", "http://TrinityCore.org \\/__/\n"); - TC_LOG_INFO("server.worldserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); - TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); - TC_LOG_INFO("server.worldserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + Trinity::Banner::Show("worldserver-daemon", + [](char const* text) + { + TC_LOG_INFO("server.worldserver", "%s", text); + }, + []() + { + TC_LOG_INFO("server.worldserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); + TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); + TC_LOG_INFO("server.worldserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + } + ); OpenSSLCrypto::threadsSetup(); @@ -207,7 +209,7 @@ extern int main(int argc, char** argv) threadPool->push_back(std::thread([ioService]() { ioService->run(); })); // Set process priority according to configuration settings - SetProcessPriority("server.worldserver"); + SetProcessPriority("server.worldserver", sConfigMgr->GetIntDefault(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetBoolDefault(CONFIG_HIGH_PRIORITY, false)); // Start the databases if (!StartDB()) @@ -513,7 +515,7 @@ bool LoadRealmInfo(boost::asio::io_service& ioService) return false; } - realm.ExternalAddress = (*endPoint).endpoint().address(); + realm.ExternalAddress = Trinity::make_unique((*endPoint).endpoint().address()); boost::asio::ip::tcp::resolver::query localAddressQuery(boost::asio::ip::tcp::v4(), fields[3].GetString(), ""); endPoint = resolver.resolve(localAddressQuery, ec); @@ -523,7 +525,7 @@ bool LoadRealmInfo(boost::asio::io_service& ioService) return false; } - realm.LocalAddress = (*endPoint).endpoint().address(); + realm.LocalAddress = Trinity::make_unique((*endPoint).endpoint().address()); boost::asio::ip::tcp::resolver::query localSubmaskQuery(boost::asio::ip::tcp::v4(), fields[4].GetString(), ""); endPoint = resolver.resolve(localSubmaskQuery, ec); @@ -533,7 +535,7 @@ bool LoadRealmInfo(boost::asio::io_service& ioService) return false; } - realm.LocalSubnetMask = (*endPoint).endpoint().address(); + realm.LocalSubnetMask = Trinity::make_unique((*endPoint).endpoint().address()); realm.Port = fields[5].GetUInt16(); realm.Type = fields[6].GetUInt8(); diff --git a/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp b/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp index 99c2400eccf..c0824b5423f 100644 --- a/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp +++ b/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp @@ -1 +1,18 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "worldPCH.h" diff --git a/src/server/worldserver/PrecompiledHeaders/worldPCH.h b/src/server/worldserver/PrecompiledHeaders/worldPCH.h index 6407485f70b..09f5e8a9c75 100644 --- a/src/server/worldserver/PrecompiledHeaders/worldPCH.h +++ b/src/server/worldserver/PrecompiledHeaders/worldPCH.h @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + #include "Common.h" #include "World.h" #include "Log.h" diff --git a/src/server/worldserver/RemoteAccess/RASession.cpp b/src/server/worldserver/RemoteAccess/RASession.cpp index 3df9556c73d..136814743a0 100644 --- a/src/server/worldserver/RemoteAccess/RASession.cpp +++ b/src/server/worldserver/RemoteAccess/RASession.cpp @@ -16,17 +16,17 @@ * with this program. If not, see . */ -#include -#include -#include -#include #include "RASession.h" #include "AccountMgr.h" -#include "Log.h" +#include "Config.h" #include "DatabaseEnv.h" +#include "Log.h" +#include "Util.h" #include "World.h" -#include "Config.h" #include "ServerMotd.h" +#include +#include +#include using boost::asio::ip::tcp; @@ -40,7 +40,7 @@ void RASession::Start() if (_socket.available() > 0) { // Handle subnegotiation - boost::array buf; + char buf[1024] = { }; _socket.read_some(boost::asio::buffer(buf)); // Send the end-of-negotiation packet @@ -89,7 +89,7 @@ void RASession::Start() _socket.close(); } -int RASession::Send(const char* data) +int RASession::Send(char const* data) { std::ostream os(&_writeBuffer); os << data; @@ -205,7 +205,7 @@ bool RASession::ProcessCommand(std::string& command) return false; } -void RASession::CommandPrint(void* callbackArg, const char* text) +void RASession::CommandPrint(void* callbackArg, char const* text) { if (!text || !*text) return; diff --git a/src/server/worldserver/RemoteAccess/RASession.h b/src/server/worldserver/RemoteAccess/RASession.h index be40c80c5d4..a2e39888212 100644 --- a/src/server/worldserver/RemoteAccess/RASession.h +++ b/src/server/worldserver/RemoteAccess/RASession.h @@ -43,13 +43,13 @@ public: unsigned short GetRemotePort() const { return _socket.remote_endpoint().port(); } private: - int Send(const char* data); + int Send(char const* data); std::string ReadString(); bool CheckAccessLevel(const std::string& user); bool CheckPassword(const std::string& user, const std::string& pass); bool ProcessCommand(std::string& command); - static void CommandPrint(void* callbackArg, const char* text); + static void CommandPrint(void* callbackArg, char const* text); static void CommandFinished(void* callbackArg, bool); tcp::socket _socket; diff --git a/src/server/worldserver/TCSoap/TCSoap.h b/src/server/worldserver/TCSoap/TCSoap.h index e342c154964..3ccbe134e21 100644 --- a/src/server/worldserver/TCSoap/TCSoap.h +++ b/src/server/worldserver/TCSoap/TCSoap.h @@ -38,7 +38,7 @@ class SOAPCommand { } - void appendToPrintBuffer(const char* msg) + void appendToPrintBuffer(char const* msg) { m_printBuffer += msg; } @@ -54,7 +54,7 @@ class SOAPCommand return m_success; } - static void print(void* callbackArg, const char* msg) + static void print(void* callbackArg, char const* msg) { ((SOAPCommand*)callbackArg)->appendToPrintBuffer(msg); } diff --git a/src/tools/map_extractor/CMakeLists.txt b/src/tools/map_extractor/CMakeLists.txt index 52da3adf127..87ad3ff5089 100644 --- a/src/tools/map_extractor/CMakeLists.txt +++ b/src/tools/map_extractor/CMakeLists.txt @@ -13,6 +13,10 @@ CollectSourceFiles( ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE_SOURCES) +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() + add_executable(mapextractor ${PRIVATE_SOURCES} ) diff --git a/src/tools/map_extractor/System.cpp b/src/tools/map_extractor/System.cpp index c681e669ebe..1fbf831e20f 100644 --- a/src/tools/map_extractor/System.cpp +++ b/src/tools/map_extractor/System.cpp @@ -16,8 +16,6 @@ * with this program. If not, see . */ -#define _CRT_SECURE_NO_DEPRECATE - #include #include #include @@ -25,6 +23,7 @@ #include #include "dbcfile.h" +#include "Banner.h" #include "mpq_libmpq04.h" #include "StringFormat.h" @@ -84,7 +83,7 @@ const char *CONF_mpq_list[]={ "patch-5.MPQ", }; -static const char* const langs[] = {"enGB", "enUS", "deDE", "esES", "frFR", "koKR", "zhCN", "zhTW", "enCN", "enTW", "esMX", "ruRU" }; +static char const* const langs[] = {"enGB", "enUS", "deDE", "esES", "frFR", "koKR", "zhCN", "zhTW", "enCN", "enTW", "esMX", "ruRU" }; #define LANG_COUNT 12 void CreateDir(boost::filesystem::path const& path) @@ -122,7 +121,7 @@ void HandleArgs(int argc, char * arg[]) if(arg[c][0] != '-') Usage(arg[0]); - switch(arg[c][1]) + switch (arg[c][1]) { case 'i': if (c + 1 < argc && strlen(arg[c + 1]) < MAX_PATH_LENGTH) // all ok @@ -143,16 +142,16 @@ void HandleArgs(int argc, char * arg[]) Usage(arg[0]); break; case 'f': - if(c + 1 < argc) // all ok - CONF_allow_float_to_int=atoi(arg[(c++) + 1])!=0; + 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 + if (c + 1 < argc) // all ok { - CONF_extract=atoi(arg[(c++) + 1]); - if(!(CONF_extract > 0 && CONF_extract < 8)) + CONF_extract = atoi(arg[(c++) + 1]); + if (!(CONF_extract > 0 && CONF_extract < 8)) Usage(arg[0]); } else @@ -216,7 +215,7 @@ uint32 ReadMapDBC() { map_ids[x].id = dbc.getRecord(x).getUInt(0); - const char* map_name = dbc.getRecord(x).getString(1); + char const* map_name = dbc.getRecord(x).getString(1); size_t max_map_name_length = sizeof(map_ids[x].name); if (strlen(map_name) >= max_map_name_length) { @@ -567,12 +566,12 @@ bool ConvertADT(std::string const& inputPath, std::string const& outputPath, int float diff = maxHeight - minHeight; if (diff < CONF_float_to_int8_limit) // As uint8 (max accuracy = CONF_float_to_int8_limit/256) { - heightHeader.flags|=MAP_HEIGHT_AS_INT8; + heightHeader.flags |= MAP_HEIGHT_AS_INT8; step = selectUInt8StepStore(diff); } - else if (diff(&map), sizeof(map)); + outFile.write(reinterpret_cast(&map), sizeof(map)); // Store area data - outFile.write(reinterpret_cast(&areaHeader), sizeof(areaHeader)); + outFile.write(reinterpret_cast(&areaHeader), sizeof(areaHeader)); if (!(areaHeader.flags & MAP_AREA_NO_AREA)) - outFile.write(reinterpret_cast(area_ids), sizeof(area_ids)); + outFile.write(reinterpret_cast(area_ids), sizeof(area_ids)); // Store height data - outFile.write(reinterpret_cast(&heightHeader), sizeof(heightHeader)); + outFile.write(reinterpret_cast(&heightHeader), sizeof(heightHeader)); if (!(heightHeader.flags & MAP_HEIGHT_NO_HEIGHT)) { if (heightHeader.flags & MAP_HEIGHT_AS_INT16) { - outFile.write(reinterpret_cast(uint16_V9), sizeof(uint16_V9)); - outFile.write(reinterpret_cast(uint16_V8), sizeof(uint16_V8)); + outFile.write(reinterpret_cast(uint16_V9), sizeof(uint16_V9)); + outFile.write(reinterpret_cast(uint16_V8), sizeof(uint16_V8)); } else if (heightHeader.flags & MAP_HEIGHT_AS_INT8) { - outFile.write(reinterpret_cast(uint8_V9), sizeof(uint8_V9)); - outFile.write(reinterpret_cast(uint8_V8), sizeof(uint8_V8)); + outFile.write(reinterpret_cast(uint8_V9), sizeof(uint8_V9)); + outFile.write(reinterpret_cast(uint8_V8), sizeof(uint8_V8)); } else { - outFile.write(reinterpret_cast(V9), sizeof(V9)); - outFile.write(reinterpret_cast(V8), sizeof(V8)); + outFile.write(reinterpret_cast(V9), sizeof(V9)); + outFile.write(reinterpret_cast(V8), sizeof(V8)); } } @@ -888,24 +887,24 @@ bool ConvertADT(std::string const& inputPath, std::string const& outputPath, int // Store liquid data if need if (map.liquidMapOffset) { - outFile.write(reinterpret_cast(&liquidHeader), sizeof(liquidHeader)); + outFile.write(reinterpret_cast(&liquidHeader), sizeof(liquidHeader)); if (!(liquidHeader.flags&MAP_LIQUID_NO_TYPE)) { - outFile.write(reinterpret_cast(liquid_entry), sizeof(liquid_entry)); - outFile.write(reinterpret_cast(liquid_flags), sizeof(liquid_flags)); + outFile.write(reinterpret_cast(liquid_entry), sizeof(liquid_entry)); + outFile.write(reinterpret_cast(liquid_flags), sizeof(liquid_flags)); } if (!(liquidHeader.flags&MAP_LIQUID_NO_HEIGHT)) { for (int y = 0; y < liquidHeader.height; y++) - outFile.write(reinterpret_cast(&liquid_height[y + liquidHeader.offsetY][liquidHeader.offsetX]), sizeof(float) * liquidHeader.width); + outFile.write(reinterpret_cast(&liquid_height[y + liquidHeader.offsetY][liquidHeader.offsetX]), sizeof(float) * liquidHeader.width); } } // store hole data if (hasHoles) - outFile.write(reinterpret_cast(holes), map.holesSize); + outFile.write(reinterpret_cast(holes), map.holesSize); outFile.close(); return true; @@ -1114,8 +1113,7 @@ inline void CloseMPQFiles() int main(int argc, char * arg[]) { - printf("Map & DBC Extractor\n"); - printf("===================\n\n"); + Trinity::Banner::Show("Map & DBC Extractor", [](char const* text) { printf("%s\n", text); }, nullptr); HandleArgs(argc, arg); diff --git a/src/tools/map_extractor/dbcfile.cpp b/src/tools/map_extractor/dbcfile.cpp index b8a504877a3..25ded3e6c60 100644 --- a/src/tools/map_extractor/dbcfile.cpp +++ b/src/tools/map_extractor/dbcfile.cpp @@ -22,7 +22,7 @@ #include "mpq_libmpq04.h" DBCFile::DBCFile(const std::string& filename): - filename(filename), recordSize(0), recordCount(0), fieldCount(0), stringSize(0), data(NULL), stringTable(NULL) + filename(filename), recordSize(0), recordCount(0), fieldCount(0), stringSize(0), data(nullptr), stringTable(nullptr) { } diff --git a/src/tools/map_extractor/dbcfile.h b/src/tools/map_extractor/dbcfile.h index f490544d9d6..5130469b5f3 100644 --- a/src/tools/map_extractor/dbcfile.h +++ b/src/tools/map_extractor/dbcfile.h @@ -99,15 +99,15 @@ public: } /// Return address of current instance Record const & operator*() const { return record; } - const Record* operator->() const { + Record const* operator->() const { return &record; } /// Comparison - bool operator==(const Iterator &b) const + bool operator==(Iterator const& b) const { return record.offset == b.record.offset; } - bool operator!=(const Iterator &b) const + bool operator!=(Iterator const& b) const { return record.offset != b.record.offset; } diff --git a/src/tools/map_extractor/mpq_libmpq.cpp b/src/tools/map_extractor/mpq_libmpq.cpp index 5891a1be49b..120fa9731b7 100644 --- a/src/tools/map_extractor/mpq_libmpq.cpp +++ b/src/tools/map_extractor/mpq_libmpq.cpp @@ -22,7 +22,7 @@ ArchiveSet gOpenArchives; -MPQArchive::MPQArchive(const char* filename) +MPQArchive::MPQArchive(char const* filename) { int result = libmpq__archive_open(&mpq_a, filename, -1); printf("Opening %s\n", filename); @@ -58,7 +58,7 @@ void MPQArchive::close() libmpq__archive_close(mpq_a); } -MPQFile::MPQFile(const char* filename): +MPQFile::MPQFile(char const* filename): eof(false), buffer(0), pointer(0), diff --git a/src/tools/map_extractor/mpq_libmpq04.h b/src/tools/map_extractor/mpq_libmpq04.h index b03ae7b7639..589ce0b31d1 100644 --- a/src/tools/map_extractor/mpq_libmpq04.h +++ b/src/tools/map_extractor/mpq_libmpq04.h @@ -33,7 +33,7 @@ class MPQArchive public: mpq_archive_s *mpq_a; - MPQArchive(const char* filename); + MPQArchive(char const* filename); ~MPQArchive() { close(); } void close(); @@ -53,13 +53,13 @@ public: token = strtok( buffer, seps ); uint32 counter = 0; - while ((token != NULL) && (counter < size)) { + while ((token != nullptr) && (counter < size)) { //cout << token << endl; token[strlen(token) - 1] = 0; std::string s = token; filelist.push_back(s); counter += strlen(token) + 2; - token = strtok(NULL, seps); + token = strtok(nullptr, seps); } delete[] buffer; @@ -75,11 +75,11 @@ class MPQFile libmpq__off_t pointer,size; // disable copying - MPQFile(const MPQFile& /*f*/) {} - void operator=(const MPQFile& /*f*/) {} + MPQFile(MPQFile const& /*f*/) = delete; + void operator=(MPQFile const& /*f*/) = delete; public: - MPQFile(const char* filename); // filenames are not case sensitive + MPQFile(char const* filename); // filenames are not case sensitive ~MPQFile() { close(); } size_t read(void* dest, size_t bytes); size_t getSize() { return size; } diff --git a/src/tools/mmaps_generator/CMakeLists.txt b/src/tools/mmaps_generator/CMakeLists.txt index d55920690ad..593a6737210 100644 --- a/src/tools/mmaps_generator/CMakeLists.txt +++ b/src/tools/mmaps_generator/CMakeLists.txt @@ -12,6 +12,10 @@ CollectSourceFiles( ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE_SOURCES) +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() + add_executable(mmaps_generator ${PRIVATE_SOURCES}) target_link_libraries(mmaps_generator diff --git a/src/tools/mmaps_generator/IntermediateValues.cpp b/src/tools/mmaps_generator/IntermediateValues.cpp index 6a802ff1059..7be5cdaf3f3 100644 --- a/src/tools/mmaps_generator/IntermediateValues.cpp +++ b/src/tools/mmaps_generator/IntermediateValues.cpp @@ -69,7 +69,7 @@ namespace MMAP #undef DEBUG_WRITE } - void IntermediateValues::debugWrite(FILE* file, const rcHeightfield* mesh) + void IntermediateValues::debugWrite(FILE* file, rcHeightfield const* mesh) { if (!file || !mesh) return; @@ -107,7 +107,7 @@ namespace MMAP } } - void IntermediateValues::debugWrite(FILE* file, const rcCompactHeightfield* chf) + void IntermediateValues::debugWrite(FILE* file, rcCompactHeightfield const* chf) { if (!file | !chf) return; @@ -146,7 +146,7 @@ namespace MMAP fwrite(chf->areas, sizeof(unsigned char), chf->spanCount, file); } - void IntermediateValues::debugWrite(FILE* file, const rcContourSet* cs) + void IntermediateValues::debugWrite(FILE* file, rcContourSet const* cs) { if (!file || !cs) return; @@ -167,7 +167,7 @@ namespace MMAP } } - void IntermediateValues::debugWrite(FILE* file, const rcPolyMesh* mesh) + void IntermediateValues::debugWrite(FILE* file, rcPolyMesh const* mesh) { if (!file || !mesh) return; @@ -186,7 +186,7 @@ namespace MMAP fwrite(mesh->regs, sizeof(unsigned short), mesh->npolys, file); } - void IntermediateValues::debugWrite(FILE* file, const rcPolyMeshDetail* mesh) + void IntermediateValues::debugWrite(FILE* file, rcPolyMeshDetail const* mesh) { if (!file || !mesh) return; diff --git a/src/tools/mmaps_generator/IntermediateValues.h b/src/tools/mmaps_generator/IntermediateValues.h index edcf372e376..d93e7eabb11 100644 --- a/src/tools/mmaps_generator/IntermediateValues.h +++ b/src/tools/mmaps_generator/IntermediateValues.h @@ -34,17 +34,17 @@ namespace MMAP rcPolyMesh* polyMesh; rcPolyMeshDetail* polyMeshDetail; - IntermediateValues() : heightfield(NULL), compactHeightfield(NULL), - contours(NULL), polyMesh(NULL), polyMeshDetail(NULL) {} + IntermediateValues() : heightfield(nullptr), compactHeightfield(nullptr), + contours(nullptr), polyMesh(nullptr), polyMeshDetail(nullptr) {} ~IntermediateValues(); void writeIV(uint32 mapID, uint32 tileX, uint32 tileY); - void debugWrite(FILE* file, const rcHeightfield* mesh); - void debugWrite(FILE* file, const rcCompactHeightfield* chf); - void debugWrite(FILE* file, const rcContourSet* cs); - void debugWrite(FILE* file, const rcPolyMesh* mesh); - void debugWrite(FILE* file, const rcPolyMeshDetail* mesh); + void debugWrite(FILE* file, rcHeightfield const* mesh); + void debugWrite(FILE* file, rcCompactHeightfield const* chf); + void debugWrite(FILE* file, rcContourSet const* cs); + void debugWrite(FILE* file, rcPolyMesh const* mesh); + void debugWrite(FILE* file, rcPolyMeshDetail const* mesh); void generateObjFile(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData); }; diff --git a/src/tools/mmaps_generator/MapBuilder.cpp b/src/tools/mmaps_generator/MapBuilder.cpp index 097d3d3932c..91b139a29ea 100644 --- a/src/tools/mmaps_generator/MapBuilder.cpp +++ b/src/tools/mmaps_generator/MapBuilder.cpp @@ -54,8 +54,8 @@ namespace MMAP { MapBuilder::MapBuilder(float maxWalkableAngle, bool skipLiquid, bool skipContinents, bool skipJunkMaps, bool skipBattlegrounds, - bool debugOutput, bool bigBaseUnit, const char* offMeshFilePath) : - m_terrainBuilder (NULL), + bool debugOutput, bool bigBaseUnit, char const* offMeshFilePath) : + m_terrainBuilder (nullptr), m_debugOutput (debugOutput), m_offMeshFilePath (offMeshFilePath), m_skipContinents (skipContinents), @@ -65,7 +65,7 @@ namespace MMAP m_bigBaseUnit (bigBaseUnit), m_totalTiles (0u), m_totalTilesProcessed(0u), - m_rcContext (NULL), + m_rcContext (nullptr), _cancelationToken (false) { m_terrainBuilder = new TerrainBuilder(skipLiquid); @@ -295,7 +295,7 @@ namespace MMAP return; } - dtNavMesh* navMesh = NULL; + dtNavMesh* navMesh = nullptr; buildNavMesh(mapId, navMesh); if (!navMesh) { @@ -359,7 +359,7 @@ namespace MMAP /**************************************************************************/ void MapBuilder::buildSingleTile(uint32 mapID, uint32 tileX, uint32 tileY) { - dtNavMesh* navMesh = NULL; + dtNavMesh* navMesh = nullptr; buildNavMesh(mapID, navMesh); if (!navMesh) { @@ -397,7 +397,7 @@ namespace MMAP if (!tiles->empty()) { // build navMesh - dtNavMesh* navMesh = NULL; + dtNavMesh* navMesh = nullptr; buildNavMesh(mapID, navMesh); if (!navMesh) { @@ -503,7 +503,7 @@ namespace MMAP // use Max because '32 - tileX' is negative for values over 32 float bmin[3], bmax[3]; - getTileBounds(tileXMax, tileYMax, NULL, 0, bmin, bmax); + getTileBounds(tileXMax, tileYMax, nullptr, 0, bmin, bmax); /*** now create the navmesh ***/ @@ -701,11 +701,11 @@ namespace MMAP // we may want to keep them in the future for debug // but right now, we don't have the code to merge them rcFreeHeightField(tile.solid); - tile.solid = NULL; + tile.solid = nullptr; rcFreeCompactHeightfield(tile.chf); - tile.chf = NULL; + tile.chf = nullptr; rcFreeContourSet(tile.cset); - tile.cset = NULL; + tile.cset = nullptr; pmmerge[nmerge] = tile.pmesh; dmmerge[nmerge] = tile.dmesh; @@ -782,7 +782,7 @@ namespace MMAP params.buildBvTree = true; // will hold final navmesh - unsigned char* navData = NULL; + unsigned char* navData = nullptr; int navDataSize = 0; do @@ -850,7 +850,7 @@ namespace MMAP char message[1024]; sprintf(message, "[Map %03i] Failed to open %s for writing!\n", mapID, fileName); perror(message); - navMesh->removeTile(tileRef, NULL, NULL); + navMesh->removeTile(tileRef, nullptr, nullptr); break; } @@ -867,7 +867,7 @@ namespace MMAP fclose(file); // now that tile is written to disk, we can unload it - navMesh->removeTile(tileRef, NULL, NULL); + navMesh->removeTile(tileRef, nullptr, nullptr); } while (0); diff --git a/src/tools/mmaps_generator/MapBuilder.h b/src/tools/mmaps_generator/MapBuilder.h index 2f47fdd0ff6..5d79951f856 100644 --- a/src/tools/mmaps_generator/MapBuilder.h +++ b/src/tools/mmaps_generator/MapBuilder.h @@ -37,7 +37,7 @@ namespace MMAP { struct MapTiles { - MapTiles() : m_mapId(uint32(-1)), m_tiles(NULL) {} + MapTiles() : m_mapId(uint32(-1)), m_tiles(nullptr) {} MapTiles(uint32 id, std::set* tiles) : m_mapId(id), m_tiles(tiles) {} ~MapTiles() {} @@ -55,7 +55,7 @@ namespace MMAP struct Tile { - Tile() : chf(NULL), solid(NULL), cset(NULL), pmesh(NULL), dmesh(NULL) {} + Tile() : chf(nullptr), solid(nullptr), cset(nullptr), pmesh(nullptr), dmesh(nullptr) {} ~Tile() { rcFreeCompactHeightfield(chf); @@ -81,7 +81,7 @@ namespace MMAP bool skipBattlegrounds = false, bool debugOutput = false, bool bigBaseUnit = false, - const char* offMeshFilePath = NULL); + char const* offMeshFilePath = nullptr); ~MapBuilder(); @@ -131,7 +131,7 @@ namespace MMAP bool m_debugOutput; - const char* m_offMeshFilePath; + char const* m_offMeshFilePath; bool m_skipContinents; bool m_skipJunkMaps; bool m_skipBattlegrounds; diff --git a/src/tools/mmaps_generator/PathCommon.h b/src/tools/mmaps_generator/PathCommon.h index 1ddb5a8009c..f09ec0f0e29 100644 --- a/src/tools/mmaps_generator/PathCommon.h +++ b/src/tools/mmaps_generator/PathCommon.h @@ -20,16 +20,18 @@ #define _MMAP_COMMON_H #include "Common.h" - +#include #include #ifndef _WIN32 - #include + #include #include +#else + #include #endif -#ifdef __linux__ - #include +#ifndef _WIN32 + #include #endif enum NavTerrain @@ -48,7 +50,7 @@ enum NavTerrain namespace MMAP { - inline bool matchWildcardFilter(const char* filter, const char* str) + inline bool matchWildcardFilter(char const* filter, char const* str) { if (!filter || !str) return false; @@ -116,7 +118,7 @@ namespace MMAP while (dirp) { errno = 0; - if ((dp = readdir(dirp)) != NULL) + if ((dp = readdir(dirp)) != nullptr) { if (matchWildcardFilter(filter.c_str(), dp->d_name)) fileList.push_back(std::string(dp->d_name)); diff --git a/src/tools/mmaps_generator/PathGenerator.cpp b/src/tools/mmaps_generator/PathGenerator.cpp index 1e907909737..0a97fe59f34 100644 --- a/src/tools/mmaps_generator/PathGenerator.cpp +++ b/src/tools/mmaps_generator/PathGenerator.cpp @@ -19,6 +19,7 @@ #include "PathCommon.h" #include "MapBuilder.h" #include "Timer.h" +#include "Banner.h" using namespace MMAP; @@ -75,7 +76,7 @@ bool handleArgs(int argc, char** argv, char* &file, int& threads) { - char* param = NULL; + char* param = nullptr; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--maxAngle") == 0) @@ -112,7 +113,7 @@ bool handleArgs(int argc, char** argv, return false; char* stileX = strtok(param, ","); - char* stileY = strtok(NULL, ","); + char* stileY = strtok(nullptr, ","); int tilex = atoi(stileX); int tiley = atoi(stileY); @@ -233,7 +234,7 @@ bool handleArgs(int argc, char** argv, return true; } -int finish(const char* message, int returnValue) +int finish(char const* message, int returnValue) { printf("%s", message); getchar(); // Wait for user input @@ -242,6 +243,8 @@ int finish(const char* message, int returnValue) int main(int argc, char** argv) { + Trinity::Banner::Show("MMAP generator", [](char const* text) { printf("%s\n", text); }, nullptr); + int threads = 3, mapnum = -1; float maxAngle = 70.0f; int tileX = -1, tileY = -1; @@ -252,8 +255,8 @@ int main(int argc, char** argv) debugOutput = false, silent = false, bigBaseUnit = false; - char* offMeshInputPath = NULL; - char* file = NULL; + char* offMeshInputPath = nullptr; + char* file = nullptr; bool validParam = handleArgs(argc, argv, mapnum, tileX, tileY, maxAngle, diff --git a/src/tools/mmaps_generator/TerrainBuilder.cpp b/src/tools/mmaps_generator/TerrainBuilder.cpp index 09ad5eec819..b367a282bfe 100644 --- a/src/tools/mmaps_generator/TerrainBuilder.cpp +++ b/src/tools/mmaps_generator/TerrainBuilder.cpp @@ -23,6 +23,7 @@ #include "VMapManager2.h" #include "MapTree.h" #include "ModelInstance.h" +#include // ****************************************** // Map file format defines @@ -280,7 +281,7 @@ namespace MMAP printf("TerrainBuilder::loadMap: Failed to read some data expected 1, read 0\n"); - float* liquid_map = NULL; + float* liquid_map = nullptr; if (!(lheader.flags & MAP_LIQUID_NO_TYPE)) if (fread(liquid_type, sizeof(liquid_type), 1, mapFile) != 1) @@ -373,7 +374,7 @@ namespace MMAP // make a copy of liquid vertices // used to pad right-bottom frame due to lost vertex data at extraction - float* lverts_copy = NULL; + float* lverts_copy = nullptr; if (meshData.liquidVerts.size()) { lverts_copy = new float[meshData.liquidVerts.size()]; @@ -646,7 +647,7 @@ namespace MMAP if (!instanceTrees[mapID]) break; - ModelInstance* models = NULL; + ModelInstance* models = nullptr; uint32 count = 0; instanceTrees[mapID]->getModelInstances(models, count); @@ -673,17 +674,17 @@ namespace MMAP // transform data float scale = instance.iScale; - G3D::Matrix3 rotation = G3D::Matrix3::fromEulerAnglesXYZ(G3D::pi()*instance.iRot.z/-180.f, G3D::pi()*instance.iRot.x/-180.f, G3D::pi()*instance.iRot.y/-180.f); + G3D::Matrix3 rotation = G3D::Matrix3::fromEulerAnglesXYZ(G3D::pi()*instance.iRot.z / -180.f, G3D::pi() * instance.iRot.x / -180.f, G3D::pi() * instance.iRot.y / -180.f); G3D::Vector3 position = instance.iPos; - position.x -= 32*GRID_SIZE; - position.y -= 32*GRID_SIZE; + position.x -= 32 * GRID_SIZE; + position.y -= 32 * GRID_SIZE; for (std::vector::iterator it = groupModels.begin(); it != groupModels.end(); ++it) { std::vector tempVertices; std::vector transformedVertices; std::vector tempTriangles; - WmoLiquid* liquid = NULL; + WmoLiquid* liquid = nullptr; it->getMeshData(tempVertices, tempTriangles, liquid); @@ -712,16 +713,16 @@ namespace MMAP // convert liquid type to NavTerrain switch (liquid->GetType() & 3) { - case 0: - case 1: - type = NAV_WATER; - break; - case 2: - type = NAV_MAGMA; - break; - case 3: - type = NAV_SLIME; - break; + case 0: + case 1: + type = NAV_WATER; + break; + case 2: + type = NAV_MAGMA; + break; + case 3: + type = NAV_SLIME; + break; } // indexing is weird... @@ -732,6 +733,7 @@ namespace MMAP G3D::Vector3 vert; for (uint32 x = 0; x < vertsX; ++x) + { for (uint32 y = 0; y < vertsY; ++y) { vert = G3D::Vector3(corner.x + x * GRID_PART_SIZE, corner.y + y * GRID_PART_SIZE, data[y*vertsX + x]); @@ -740,38 +742,43 @@ namespace MMAP vert.y *= -1.f; liqVerts.push_back(vert); } + } - int idx1, idx2, idx3, idx4; - uint32 square; - for (uint32 x = 0; x < tilesX; ++x) - for (uint32 y = 0; y < tilesY; ++y) - if ((flags[x+y*tilesX] & 0x0f) != 0x0f) - { - square = x * tilesY + y; - idx1 = square+x; - idx2 = square+1+x; - idx3 = square+tilesY+1+1+x; - idx4 = square+tilesY+1+x; - - // top triangle - liqTris.push_back(idx3); - liqTris.push_back(idx2); - liqTris.push_back(idx1); - // bottom triangle - liqTris.push_back(idx4); - liqTris.push_back(idx3); - liqTris.push_back(idx1); - } - - uint32 liqOffset = meshData.liquidVerts.size() / 3; - for (uint32 j = 0; j < liqVerts.size(); ++j) - meshData.liquidVerts.append(liqVerts[j].y, liqVerts[j].z, liqVerts[j].x); - - for (uint32 j = 0; j < liqTris.size() / 3; ++j) - { - meshData.liquidTris.append(liqTris[j*3+1] + liqOffset, liqTris[j*3+2] + liqOffset, liqTris[j*3] + liqOffset); - meshData.liquidType.append(type); - } + int idx1, idx2, idx3, idx4; + uint32 square; + for (uint32 x = 0; x < tilesX; ++x) + { + for (uint32 y = 0; y < tilesY; ++y) + { + if ((flags[x + y*tilesX] & 0x0f) != 0x0f) + { + square = x * tilesY + y; + idx1 = square + x; + idx2 = square + 1 + x; + idx3 = square + tilesY + 1 + 1 + x; + idx4 = square + tilesY + 1 + x; + + // top triangle + liqTris.push_back(idx3); + liqTris.push_back(idx2); + liqTris.push_back(idx1); + // bottom triangle + liqTris.push_back(idx4); + liqTris.push_back(idx3); + liqTris.push_back(idx1); + } + } + } + + uint32 liqOffset = meshData.liquidVerts.size() / 3; + for (uint32 j = 0; j < liqVerts.size(); ++j) + meshData.liquidVerts.append(liqVerts[j].y, liqVerts[j].z, liqVerts[j].x); + + for (uint32 j = 0; j < liqTris.size() / 3; ++j) + { + meshData.liquidTris.append(liqTris[j * 3 + 1] + liqOffset, liqTris[j * 3 + 2] + liqOffset, liqTris[j * 3] + liqOffset); + meshData.liquidType.append(type); + } } } } @@ -883,10 +890,10 @@ namespace MMAP } /**************************************************************************/ - void TerrainBuilder::loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, const char* offMeshFilePath) + void TerrainBuilder::loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, char const* offMeshFilePath) { // no meshfile input given? - if (offMeshFilePath == NULL) + if (offMeshFilePath == nullptr) return; FILE* fp = fopen(offMeshFilePath, "rb"); diff --git a/src/tools/mmaps_generator/TerrainBuilder.h b/src/tools/mmaps_generator/TerrainBuilder.h index c85dd850fec..4dcca5f15fe 100644 --- a/src/tools/mmaps_generator/TerrainBuilder.h +++ b/src/tools/mmaps_generator/TerrainBuilder.h @@ -22,9 +22,9 @@ #include "PathCommon.h" #include "WorldModel.h" -#include "G3D/Array.h" -#include "G3D/Vector3.h" -#include "G3D/Matrix3.h" +#include +#include +#include namespace MMAP { @@ -81,11 +81,11 @@ namespace MMAP TerrainBuilder(bool skipLiquid); ~TerrainBuilder(); - TerrainBuilder(const TerrainBuilder &tb) = delete; + TerrainBuilder(TerrainBuilder const& tb) = delete; void loadMap(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData); bool loadVMap(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData); - void loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, const char* offMeshFilePath); + void loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, char const* offMeshFilePath); bool usesLiquids() const { return !m_skipLiquid; } diff --git a/src/tools/vmap4_assembler/CMakeLists.txt b/src/tools/vmap4_assembler/CMakeLists.txt index 57c351f2ebc..520c07793fb 100644 --- a/src/tools/vmap4_assembler/CMakeLists.txt +++ b/src/tools/vmap4_assembler/CMakeLists.txt @@ -9,7 +9,13 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -add_executable(vmap4assembler VMapAssembler.cpp) +set(PRIVATE_SOURCES VMapAssembler.cpp) + +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() + +add_executable(vmap4assembler ${PRIVATE_SOURCES}) if(CMAKE_SYSTEM_NAME MATCHES "Darwin") set_target_properties(vmap4assembler PROPERTIES LINK_FLAGS "-framework Carbon") diff --git a/src/tools/vmap4_assembler/VMapAssembler.cpp b/src/tools/vmap4_assembler/VMapAssembler.cpp index d5a6f95ea53..170ce80fcb2 100644 --- a/src/tools/vmap4_assembler/VMapAssembler.cpp +++ b/src/tools/vmap4_assembler/VMapAssembler.cpp @@ -20,9 +20,12 @@ #include #include "TileAssembler.h" +#include "Banner.h" int main(int argc, char* argv[]) { + Trinity::Banner::Show("VMAP assembler", [](char const* text) { std::cout << text << std::endl; }, nullptr); + if (argc != 3) { std::cout << "usage: " << argv[0] << " " << std::endl; diff --git a/src/tools/vmap4_extractor/CMakeLists.txt b/src/tools/vmap4_extractor/CMakeLists.txt index 848b9d089d0..42bff330d0b 100644 --- a/src/tools/vmap4_extractor/CMakeLists.txt +++ b/src/tools/vmap4_extractor/CMakeLists.txt @@ -13,21 +13,15 @@ CollectSourceFiles( ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE_SOURCES) +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() + add_executable(vmap4extractor ${PRIVATE_SOURCES}) target_link_libraries(vmap4extractor - PUBLIC - mpq) - -CollectIncludeDirectories( - ${CMAKE_CURRENT_SOURCE_DIR} - PUBLIC_INCLUDES) - -target_include_directories(vmap4extractor - PUBLIC - ${PUBLIC_INCLUDES} - PRIVATE - ${CMAKE_CURRENT_BINARY_DIR}) + common + mpq) set_target_properties(vmap4extractor PROPERTIES diff --git a/src/tools/vmap4_extractor/adtfile.cpp b/src/tools/vmap4_extractor/adtfile.cpp index bb9f69f4be7..ee9a93fd3ff 100644 --- a/src/tools/vmap4_extractor/adtfile.cpp +++ b/src/tools/vmap4_extractor/adtfile.cpp @@ -30,7 +30,7 @@ char const* GetPlainName(char const* FileName) { const char * szTemp; - if((szTemp = strrchr(FileName, '\\')) != NULL) + if((szTemp = strrchr(FileName, '\\')) != nullptr) FileName = szTemp + 1; return FileName; } @@ -39,7 +39,7 @@ char* GetPlainName(char* FileName) { char * szTemp; - if((szTemp = strrchr(FileName, '\\')) != NULL) + if((szTemp = strrchr(FileName, '\\')) != nullptr) FileName = szTemp + 1; return FileName; } @@ -71,10 +71,10 @@ char* GetExtension(char* FileName) { if (char* szTemp = strrchr(FileName, '.')) return szTemp; - return NULL; + return nullptr; } -ADTFile::ADTFile(char* filename): ADT(filename), nWMO(0), nMDX(0), WmoInstansName(NULL), ModelInstansName(NULL) +ADTFile::ADTFile(char* filename): ADT(filename), nWMO(0), nMDX(0), WmoInstansName(nullptr), ModelInstansName(nullptr) { Adtfilename.append(filename); } @@ -184,7 +184,7 @@ bool ADTFile::init(uint32 map_num, uint32 tileX, uint32 tileY) ModelInstance inst(ADT,ModelInstansName[id].c_str(), map_num, tileX, tileY, dirfile); } delete[] ModelInstansName; - ModelInstansName = NULL; + ModelInstansName = nullptr; } } else if (!strcmp(fourcc,"MODF")) @@ -199,7 +199,7 @@ bool ADTFile::init(uint32 map_num, uint32 tileX, uint32 tileY) WMOInstance inst(ADT,WmoInstansName[id].c_str(), map_num, tileX, tileY, dirfile); } delete[] WmoInstansName; - WmoInstansName = NULL; + WmoInstansName = nullptr; } } //====================== diff --git a/src/tools/vmap4_extractor/adtfile.h b/src/tools/vmap4_extractor/adtfile.h index 72ee528640a..2b03b9d7b1e 100644 --- a/src/tools/vmap4_extractor/adtfile.h +++ b/src/tools/vmap4_extractor/adtfile.h @@ -126,7 +126,7 @@ public: //uint32 wmo_count; /* - const mcell& Getmcell() const + mcell const& Getmcell() const { return Mcell; } diff --git a/src/tools/vmap4_extractor/dbcfile.cpp b/src/tools/vmap4_extractor/dbcfile.cpp index d12e279e2fc..25612818e44 100644 --- a/src/tools/vmap4_extractor/dbcfile.cpp +++ b/src/tools/vmap4_extractor/dbcfile.cpp @@ -24,7 +24,7 @@ #include DBCFile::DBCFile(const std::string& filename): - filename(filename), recordSize(0), recordCount(0), fieldCount(0), stringSize(0), data(NULL), stringTable(NULL) + filename(filename), recordSize(0), recordCount(0), fieldCount(0), stringSize(0), data(nullptr), stringTable(nullptr) { } @@ -46,7 +46,7 @@ bool DBCFile::open() if (header[0]!='W' || header[1]!='D' || header[2]!='B' || header[3] != 'C') { f.close(); - data = NULL; + data = nullptr; printf("Critical Error: An error occured while trying to read the DBCFile %s.", filename.c_str()); return false; } diff --git a/src/tools/vmap4_extractor/dbcfile.h b/src/tools/vmap4_extractor/dbcfile.h index 6246f5b7708..cdee4b8ee9e 100644 --- a/src/tools/vmap4_extractor/dbcfile.h +++ b/src/tools/vmap4_extractor/dbcfile.h @@ -59,7 +59,7 @@ public: class Record { public: - Record& operator= (const Record& r) + Record& operator= (Record const& r) { file = r.file; offset = r.offset; @@ -116,15 +116,15 @@ public: } /// Return address of current instance Record const & operator*() const { return record; } - const Record* operator->() const { + Record const* operator->() const { return &record; } /// Comparison - bool operator==(const Iterator &b) const + bool operator==(Iterator const& b) const { return record.offset == b.record.offset; } - bool operator!=(const Iterator &b) const + bool operator!=(Iterator const& b) const { return record.offset != b.record.offset; } diff --git a/src/tools/vmap4_extractor/loadlib/loadlib.h b/src/tools/vmap4_extractor/loadlib/loadlib.h index 2e66892da1c..6d2d07b06de 100644 --- a/src/tools/vmap4_extractor/loadlib/loadlib.h +++ b/src/tools/vmap4_extractor/loadlib/loadlib.h @@ -19,31 +19,7 @@ #ifndef LOAD_LIB_H #define LOAD_LIB_H -#ifdef WIN32 -typedef __int64 int64; -typedef __int32 int32; -typedef __int16 int16; -typedef __int8 int8; -typedef unsigned __int64 uint64; -typedef unsigned __int32 uint32; -typedef unsigned __int16 uint16; -typedef unsigned __int8 uint8; -#else -#include -#ifndef uint64_t -#ifdef __linux__ -#include -#endif -#endif -typedef int64_t int64; -typedef int32_t int32; -typedef int16_t int16; -typedef int8_t int8; -typedef uint64_t uint64; -typedef uint32_t uint32; -typedef uint16_t uint16; -typedef uint8_t uint8; -#endif +#include "Define.h" #define FILE_FORMAT_VERSION 18 diff --git a/src/tools/vmap4_extractor/model.cpp b/src/tools/vmap4_extractor/model.cpp index 3b2f8368cab..4a4ff052433 100644 --- a/src/tools/vmap4_extractor/model.cpp +++ b/src/tools/vmap4_extractor/model.cpp @@ -69,30 +69,30 @@ bool Model::open() bool Model::ConvertToVMAPModel(const char * outfilename) { - int N[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; - FILE* output=fopen(outfilename, "wb"); + int N[12] = { }; + FILE* output = fopen(outfilename, "wb"); if (!output) { - printf("Can't create the output file '%s'\n",outfilename); + printf("Can't create the output file '%s'\n", outfilename); return false; } fwrite(szRawVMAPMagic, 8, 1, output); uint32 nVertices = header.nBoundingVertices; fwrite(&nVertices, sizeof(int), 1, output); uint32 nofgroups = 1; - fwrite(&nofgroups,sizeof(uint32), 1, output); - fwrite(N,4*3,1,output);// rootwmoid, flags, groupid - fwrite(N,sizeof(float),3*2,output);//bbox, only needed for WMO currently - fwrite(N,4,1,output);// liquidflags - fwrite("GRP ",4,1,output); + fwrite(&nofgroups, sizeof(uint32), 1, output); + fwrite(N, 4 * 3, 1, output);// rootwmoid, flags, groupid + fwrite(N, sizeof(float), 3 * 2, output);//bbox, only needed for WMO currently + fwrite(N, 4, 1, output);// liquidflags + fwrite("GRP ", 4, 1, output); uint32 branches = 1; int wsize; wsize = sizeof(branches) + sizeof(uint32) * branches; fwrite(&wsize, sizeof(int), 1, output); - fwrite(&branches,sizeof(branches), 1, output); + fwrite(&branches, sizeof(branches), 1, output); uint32 nIndexes = header.nBoundingTriangles; - fwrite(&nIndexes,sizeof(uint32), 1, output); - fwrite("INDX",4, 1, output); + fwrite(&nIndexes, sizeof(uint32), 1, output); + fwrite("INDX", 4, 1, output); wsize = sizeof(uint32) + sizeof(unsigned short) * nIndexes; fwrite(&wsize, sizeof(int), 1, output); fwrite(&nIndexes, sizeof(uint32), 1, output); @@ -114,7 +114,7 @@ bool Model::ConvertToVMAPModel(const char * outfilename) wsize = sizeof(int) + sizeof(float) * 3 * nVertices; fwrite(&wsize, sizeof(int), 1, output); fwrite(&nVertices, sizeof(int), 1, output); - if (nVertices >0) + if (nVertices > 0) { for (uint32 vpos = 0; vpos < nVertices; ++vpos) { @@ -123,7 +123,7 @@ bool Model::ConvertToVMAPModel(const char * outfilename) vertices[vpos].z = tmp; } - fwrite(vertices, sizeof(float)*3, nVertices, output); + fwrite(vertices, sizeof(float) * 3, nVertices, output); } fclose(output); @@ -168,7 +168,7 @@ ModelInstance::ModelInstance(MPQFile& f, char const* ModelInstName, uint32 mapID fseek(input, 8, SEEK_SET); // get the correct no of vertices int nVertices; - int count = fread(&nVertices, sizeof (int), 1, input); + int count = fread(&nVertices, sizeof(int), 1, input); fclose(input); if (count != 1 || nVertices == 0) @@ -189,7 +189,7 @@ ModelInstance::ModelInstance(MPQFile& f, char const* ModelInstName, uint32 mapID fwrite(&pos, sizeof(float), 3, pDirfile); fwrite(&rot, sizeof(float), 3, pDirfile); fwrite(&sc, sizeof(float), 1, pDirfile); - uint32 nlen=strlen(ModelInstName); + uint32 nlen = strlen(ModelInstName); fwrite(&nlen, sizeof(uint32), 1, pDirfile); fwrite(ModelInstName, sizeof(char), nlen, pDirfile); diff --git a/src/tools/vmap4_extractor/model.h b/src/tools/vmap4_extractor/model.h index c86f13be337..39322e63288 100644 --- a/src/tools/vmap4_extractor/model.h +++ b/src/tools/vmap4_extractor/model.h @@ -35,8 +35,8 @@ private: { delete[] vertices; delete[] indices; - vertices = NULL; - indices = NULL; + vertices = nullptr; + indices = nullptr; } std::string filename; public: diff --git a/src/tools/vmap4_extractor/mpq_libmpq.cpp b/src/tools/vmap4_extractor/mpq_libmpq.cpp index 09f05d28ce1..7253b718c09 100644 --- a/src/tools/vmap4_extractor/mpq_libmpq.cpp +++ b/src/tools/vmap4_extractor/mpq_libmpq.cpp @@ -23,7 +23,7 @@ ArchiveSet gOpenArchives; -MPQArchive::MPQArchive(const char* filename) +MPQArchive::MPQArchive(char const* filename) { int result = libmpq__archive_open(&mpq_a, filename, -1); printf("Opening %s\n", filename); @@ -64,7 +64,7 @@ void MPQArchive::close() libmpq__archive_close(mpq_a); } -MPQFile::MPQFile(const char* filename): +MPQFile::MPQFile(char const* filename): eof(false), buffer(0), pointer(0), diff --git a/src/tools/vmap4_extractor/mpq_libmpq04.h b/src/tools/vmap4_extractor/mpq_libmpq04.h index dea79961602..c4c473acd9f 100644 --- a/src/tools/vmap4_extractor/mpq_libmpq04.h +++ b/src/tools/vmap4_extractor/mpq_libmpq04.h @@ -33,7 +33,7 @@ class MPQArchive public: mpq_archive_s *mpq_a; - MPQArchive(const char* filename); + MPQArchive(char const* filename); ~MPQArchive() { if (isOpened()) close(); } void GetFileListTo(std::vector& filelist) { @@ -52,13 +52,13 @@ public: token = strtok( buffer, seps ); uint32 counter = 0; - while ((token != NULL) && (counter < size)) { + while ((token != nullptr) && (counter < size)) { //cout << token << endl; token[strlen(token) - 1] = 0; std::string s = token; filelist.push_back(s); counter += strlen(token) + 2; - token = strtok(NULL, seps); + token = strtok(nullptr, seps); } delete[] buffer; @@ -77,11 +77,11 @@ class MPQFile char *buffer; libmpq__off_t pointer,size; - MPQFile(const MPQFile& /*f*/) = delete; - void operator=(const MPQFile& /*f*/) = delete; + MPQFile(MPQFile const& /*f*/) = delete; + void operator=(MPQFile const& /*f*/) = delete; public: - MPQFile(const char* filename); // filenames are not case sensitive + MPQFile(char const* filename); // filenames are not case sensitive ~MPQFile() { close(); } size_t read(void* dest, size_t bytes); size_t getSize() { return size; } diff --git a/src/tools/vmap4_extractor/vec3d.h b/src/tools/vmap4_extractor/vec3d.h index dd89bc1afb7..0b25d2f60b5 100644 --- a/src/tools/vmap4_extractor/vec3d.h +++ b/src/tools/vmap4_extractor/vec3d.h @@ -25,54 +25,55 @@ class Vec3D { public: - float x,y,z; + float x, y, z; - Vec3D(float x0 = 0.0f, float y0 = 0.0f, float z0 = 0.0f) : x(x0), y(y0), z(z0) {} + Vec3D(float x0 = 0.0f, float y0 = 0.0f, float z0 = 0.0f) : x(x0), y(y0), z(z0) { } - Vec3D(const Vec3D& v) : x(v.x), y(v.y), z(v.z) {} + Vec3D(Vec3D const& v) : x(v.x), y(v.y), z(v.z) { } - Vec3D& operator= (const Vec3D &v) { + Vec3D& operator=(Vec3D const& v) + { x = v.x; y = v.y; z = v.z; return *this; } - Vec3D operator+ (const Vec3D &v) const + Vec3D operator+(Vec3D const& v) const { - Vec3D r(x+v.x,y+v.y,z+v.z); + Vec3D r(x + v.x, y + v.y, z + v.z); return r; } - Vec3D operator- (const Vec3D &v) const + Vec3D operator-(Vec3D const& v) const { - Vec3D r(x-v.x,y-v.y,z-v.z); + Vec3D r(x - v.x, y - v.y, z - v.z); return r; } - float operator* (const Vec3D &v) const + float operator*(Vec3D const& v) const { - return x*v.x + y*v.y + z*v.z; + return x * v.x + y * v.y + z * v.z; } - Vec3D operator* (float d) const + Vec3D operator*(float d) const { - Vec3D r(x*d,y*d,z*d); + Vec3D r(x * d, y * d, z * d); return r; } - friend Vec3D operator* (float d, const Vec3D& v) + friend Vec3D operator*(float d, Vec3D const& v) { return v * d; } - Vec3D operator% (const Vec3D &v) const + Vec3D operator%(Vec3D const& v) const { - Vec3D r(y*v.z-z*v.y, z*v.x-x*v.z, x*v.y-y*v.x); + Vec3D r(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); return r; } - Vec3D& operator+= (const Vec3D &v) + Vec3D& operator+=(Vec3D const& v) { x += v.x; y += v.y; @@ -80,7 +81,7 @@ public: return *this; } - Vec3D& operator-= (const Vec3D &v) + Vec3D& operator-=(Vec3D const& v) { x -= v.x; y -= v.y; @@ -88,7 +89,7 @@ public: return *this; } - Vec3D& operator*= (float d) + Vec3D& operator*=(float d) { x *= d; y *= d; @@ -98,21 +99,21 @@ public: float lengthSquared() const { - return x*x+y*y+z*z; + return x * x + y * y + z * z; } float length() const { - return std::sqrt(x*x+y*y+z*z); + return std::sqrt(lengthSquared()); } Vec3D& normalize() { - this->operator*= (1.0f/length()); + *this *= (1.0f / length()); return *this; } - Vec3D operator~ () const + Vec3D operator~() const { Vec3D r(*this); r.normalize(); @@ -125,7 +126,7 @@ public: return in; } - friend std::ostream& operator<<(std::ostream& out, const Vec3D& v) + friend std::ostream& operator<<(std::ostream& out, Vec3D const& v) { out << v.x << " " << v.y << " " << v.z; return out; @@ -137,65 +138,65 @@ public: } }; - class Vec2D { public: - float x,y; + float x, y; - Vec2D(float x0 = 0.0f, float y0 = 0.0f) : x(x0), y(y0) {} + Vec2D(float x0 = 0.0f, float y0 = 0.0f) : x(x0), y(y0) { } - Vec2D(const Vec2D& v) : x(v.x), y(v.y) {} + Vec2D(Vec2D const& v) : x(v.x), y(v.y) { } - Vec2D& operator= (const Vec2D &v) { + Vec2D& operator=(Vec2D const& v) + { x = v.x; y = v.y; return *this; } - Vec2D operator+ (const Vec2D &v) const + Vec2D operator+(Vec2D const& v) const { - Vec2D r(x+v.x,y+v.y); + Vec2D r(x + v.x, y + v.y); return r; } - Vec2D operator- (const Vec2D &v) const + Vec2D operator-(Vec2D const& v) const { - Vec2D r(x-v.x,y-v.y); + Vec2D r(x - v.x, y - v.y); return r; } - float operator* (const Vec2D &v) const + float operator*(Vec2D const& v) const { - return x*v.x + y*v.y; + return x * v.x + y * v.y; } - Vec2D operator* (float d) const + Vec2D operator*(float d) const { - Vec2D r(x*d,y*d); + Vec2D r(x * d, y * d); return r; } - friend Vec2D operator* (float d, const Vec2D& v) + friend Vec2D operator*(float d, Vec2D const& v) { return v * d; } - Vec2D& operator+= (const Vec2D &v) + Vec2D& operator+=(Vec2D const& v) { x += v.x; y += v.y; return *this; } - Vec2D& operator-= (const Vec2D &v) + Vec2D& operator-=(Vec2D const& v) { x -= v.x; y -= v.y; return *this; } - Vec2D& operator*= (float d) + Vec2D& operator*=(float d) { x *= d; y *= d; @@ -204,28 +205,27 @@ public: float lengthSquared() const { - return x*x+y*y; + return x * x + y * y; } float length() const { - return std::sqrt(x*x+y*y); + return std::sqrt(lengthSquared()); } Vec2D& normalize() { - this->operator*= (1.0f/length()); + *this *= (1.0f / length()); return *this; } - Vec2D operator~ () const + Vec2D operator~() const { Vec2D r(*this); r.normalize(); return r; } - friend std::istream& operator>>(std::istream& in, Vec2D& v) { in >> v.x >> v.y; @@ -238,9 +238,10 @@ public: } }; -inline void rotate(float x0, float y0, float *x, float *y, float angle) +inline void rotate(float x0, float y0, float* x, float* y, float angle) { - float xa = *x - x0, ya = *y - y0; + float xa = *x - x0; + float ya = *y - y0; *x = xa*cosf(angle) - ya*sinf(angle) + x0; *y = xa*sinf(angle) + ya*cosf(angle) + y0; } diff --git a/src/tools/vmap4_extractor/vmapexport.cpp b/src/tools/vmap4_extractor/vmapexport.cpp index a93e0f88308..aeac69b6751 100644 --- a/src/tools/vmap4_extractor/vmapexport.cpp +++ b/src/tools/vmap4_extractor/vmapexport.cpp @@ -16,21 +16,18 @@ * with this program. If not, see . */ -#define _CRT_SECURE_NO_DEPRECATE - #include "adtfile.h" #include "wdtfile.h" #include "dbcfile.h" #include "wmo.h" #include "mpq_libmpq04.h" #include "vmapexport.h" +#include "Banner.h" +#include #ifdef WIN32 - #include #include #define mkdir _mkdir -#else - #include #endif #include @@ -67,12 +64,12 @@ bool preciseVectorData = false; // Constants //static const char * szWorkDirMaps = ".\\Maps"; -const char* szWorkDirWmo = "./Buildings"; -const char* szRawVMAPMagic = "VMAP043"; +char const* szWorkDirWmo = "./Buildings"; +char const* szRawVMAPMagic = "VMAP043"; // Local testing functions -bool FileExists(const char* file) +bool FileExists(char const* file) { if (FILE* n = fopen(file, "rb")) { @@ -84,9 +81,9 @@ bool FileExists(const char* file) void strToLower(char* str) { - while(*str) + while (*str) { - *str=tolower(*str); + *str = tolower(*str); ++str; } } @@ -117,7 +114,7 @@ bool ExtractWmo() { bool success = true; - //const char* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"}; + //char const* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"}; for (ArchiveSet::const_iterator ar_itr = gOpenArchives.begin(); ar_itr != gOpenArchives.end() && success; ++ar_itr) { @@ -152,7 +149,7 @@ bool ExtractSingleWmo(std::string& fname) int p = 0; // Select root wmo files char const* rchr = strrchr(plain_name, '_'); - if (rchr != NULL) + if (rchr != nullptr) { char cpy[4]; memcpy(cpy, rchr, 4); @@ -437,7 +434,9 @@ bool processArgv(int argc, char ** argv, const char *versionString) int main(int argc, char ** argv) { - bool success=true; + Trinity::Banner::Show("VMAP data extractor", [](char const* text) { printf("%s\n", text); }, nullptr); + + bool success = true; const char *versionString = "V4.00 2012_02"; // Use command line arguments, when some @@ -459,7 +458,7 @@ int main(int argc, char ** argv) } } - printf("Extract %s. Beginning work ....\n",versionString); + printf("Extract %s. Beginning work ....\n", versionString); //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // Create the working directory if (mkdir(szWorkDirWmo @@ -472,7 +471,7 @@ int main(int argc, char ** argv) // prepare archive name list std::vector archiveNames; fillArchiveNameVector(archiveNames); - for (size_t i=0; i < archiveNames.size(); ++i) + for (size_t i = 0; i < archiveNames.size(); ++i) { MPQArchive *archive = new MPQArchive(archiveNames[i].c_str()); if (gOpenArchives.empty() || gOpenArchives.front() != archive) @@ -481,7 +480,7 @@ int main(int argc, char ** argv) if (gOpenArchives.empty()) { - printf("FATAL ERROR: None MPQ archive found by path '%s'. Use -d option with proper path.\n",input_path); + printf("FATAL ERROR: None MPQ archive found by path '%s'. Use -d option with proper path.\n", input_path); return 1; } ReadLiquidTypeTableDBC(); @@ -501,13 +500,13 @@ int main(int argc, char ** argv) printf("FATAL ERROR: Map.dbc not found in data file.\n"); return 1; } - map_count=dbc->getRecordCount (); - map_ids=new map_id[map_count]; - for (unsigned int x=0;xgetRecordCount(); + map_ids = new map_id[map_count]; + for (unsigned int x = 0; x < map_count; ++x) { map_ids[x].id = dbc->getRecord(x).getUInt(0); - const char* map_name = dbc->getRecord(x).getString(1); + char const* map_name = dbc->getRecord(x).getString(1); size_t max_map_name_length = sizeof(map_ids[x].name); if (strlen(map_name) >= max_map_name_length) { @@ -524,7 +523,7 @@ int main(int argc, char ** argv) delete dbc; ParsMapFiles(); - delete [] map_ids; + delete[] map_ids; //nError = ERROR_SUCCESS; // Extract models, listed in DameObjectDisplayInfo.dbc ExtractGameobjectModels(); @@ -533,11 +532,11 @@ int main(int argc, char ** argv) printf("\n"); if (!success) { - printf("ERROR: Extract %s. Work NOT complete.\n Precise vector data=%d.\nPress any key.\n",versionString, preciseVectorData); + printf("ERROR: Extract %s. Work NOT complete.\n Precise vector data=%d.\nPress any key.\n", versionString, preciseVectorData); getchar(); } - printf("Extract %s. Work complete. No errors.\n",versionString); - delete [] LiqType; + printf("Extract %s. Work complete. No errors.\n", versionString); + delete[] LiqType; return 0; } diff --git a/src/tools/vmap4_extractor/wdtfile.cpp b/src/tools/vmap4_extractor/wdtfile.cpp index d4265311fe3..fe045d36600 100644 --- a/src/tools/vmap4_extractor/wdtfile.cpp +++ b/src/tools/vmap4_extractor/wdtfile.cpp @@ -26,12 +26,12 @@ char * wdtGetPlainName(char * FileName) { char * szTemp; - if((szTemp = strrchr(FileName, '\\')) != NULL) + if((szTemp = strrchr(FileName, '\\')) != nullptr) FileName = szTemp + 1; return FileName; } -WDTFile::WDTFile(char* file_name, char* file_name1) : gWmoInstansName(NULL), gnWMO(0), WDT(file_name) +WDTFile::WDTFile(char* file_name, char* file_name1) : gWmoInstansName(nullptr), gnWMO(0), WDT(file_name) { filename.append(file_name1,strlen(file_name1)); } @@ -104,7 +104,7 @@ bool WDTFile::init(char* /*map_id*/, unsigned int mapID) } delete[] gWmoInstansName; - gWmoInstansName = NULL; + gWmoInstansName = nullptr; } } WDT.seek((int)nextpos); @@ -123,7 +123,7 @@ WDTFile::~WDTFile(void) ADTFile* WDTFile::GetMap(int x, int z) { if(!(x>=0 && z >= 0 && x<64 && z<64)) - return NULL; + return nullptr; char name[512]; diff --git a/src/tools/vmap4_extractor/wmo.cpp b/src/tools/vmap4_extractor/wmo.cpp index a46e786bef5..441fe281c04 100644 --- a/src/tools/vmap4_extractor/wmo.cpp +++ b/src/tools/vmap4_extractor/wmo.cpp @@ -486,18 +486,18 @@ WMOGroup::~WMOGroup() } WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE* pDirfile) - : currx(0), curry(0), wmo(NULL), doodadset(0), pos(), indx(0), id(0) + : currx(0), curry(0), wmo(nullptr), doodadset(0), pos(), indx(0), id(0) { float ff[3]; f.read(&id, 4); - f.read(ff,12); - pos = Vec3D(ff[0],ff[1],ff[2]); - f.read(ff,12); - rot = Vec3D(ff[0],ff[1],ff[2]); - f.read(ff,12); - pos2 = Vec3D(ff[0],ff[1],ff[2]); // bounding box corners - f.read(ff,12); - pos3 = Vec3D(ff[0],ff[1],ff[2]); // bounding box corners + f.read(ff, 12); + pos = Vec3D(ff[0], ff[1], ff[2]); + f.read(ff, 12); + rot = Vec3D(ff[0], ff[1], ff[2]); + f.read(ff, 12); + pos2 = Vec3D(ff[0], ff[1], ff[2]); // bounding box corners + f.read(ff, 12); + pos3 = Vec3D(ff[0], ff[1], ff[2]); // bounding box corners uint16 fflags; f.read(&fflags, 2); @@ -505,9 +505,9 @@ WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint uint16 doodadSet; f.read(&doodadSet, 2); - uint16 trash,adtId; - f.read(&adtId,2); - f.read(&trash,2); + uint16 trash, adtId; + f.read(&adtId, 2); + f.read(&trash, 2); // destructible wmo, do not dump. we can handle the vmap for these // in dynamic tree (gameobject vmaps) @@ -521,7 +521,7 @@ WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint FILE *input; input = fopen(tempname, "r+b"); - if(!input) + if (!input) { printf("WMOInstance::WMOInstance: couldn't open %s\n", tempname); return; @@ -529,19 +529,19 @@ WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint fseek(input, 8, SEEK_SET); // get the correct no of vertices int nVertices; - int count = fread(&nVertices, sizeof (int), 1, input); + int count = fread(&nVertices, sizeof(int), 1, input); fclose(input); if (count != 1 || nVertices == 0) return; - float x,z; + float x, z; x = pos.x; z = pos.z; - if(x==0 && z == 0) + if (x == 0 && z == 0) { - pos.x = 533.33333f*32; - pos.z = 533.33333f*32; + pos.x = 533.33333f * 32; + pos.z = 533.33333f * 32; } pos = fixCoords(pos); pos2 = fixCoords(pos2); @@ -549,7 +549,7 @@ WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint float scale = 1.0f; uint32 flags = MOD_HAS_BOUND; - if(tileX == 65 && tileY == 65) flags |= MOD_WORLDSPAWN; + if (tileX == 65 && tileY == 65) flags |= MOD_WORLDSPAWN; //write mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, Bound_lo, Bound_hi, name fwrite(&mapID, sizeof(uint32), 1, pDirfile); fwrite(&tileX, sizeof(uint32), 1, pDirfile); @@ -562,7 +562,7 @@ WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint fwrite(&scale, sizeof(float), 1, pDirfile); fwrite(&pos2, sizeof(float), 3, pDirfile); fwrite(&pos3, sizeof(float), 3, pDirfile); - uint32 nlen=strlen(WmoInstName); + uint32 nlen = strlen(WmoInstName); fwrite(&nlen, sizeof(uint32), 1, pDirfile); fwrite(WmoInstName, sizeof(char), nlen, pDirfile); diff --git a/src/tools/vmap4_extractor/wmo.h b/src/tools/vmap4_extractor/wmo.h index 813ff50d756..74be0b05fa8 100644 --- a/src/tools/vmap4_extractor/wmo.h +++ b/src/tools/vmap4_extractor/wmo.h @@ -44,7 +44,7 @@ class WMOManager; class MPQFile; /* for whatever reason a certain company just can't stick to one coordinate system... */ -static inline Vec3D fixCoords(const Vec3D &v){ return Vec3D(v.z, v.x, v.y); } +static inline Vec3D fixCoords(Vec3D const& v){ return Vec3D(v.z, v.x, v.y); } class WMORoot { -- cgit v1.2.3