From 3d0103776caae093669ea22f3e59656641269420 Mon Sep 17 00:00:00 2001 From: eir Date: Mon, 17 Apr 2017 21:01:37 -0700 Subject: [PATCH 01/16] Scepter Blue: Various Fixes (#419) * Scepter Blue: Quest Fixes Varius fixes that make the line completable Number Two is now immune to most mechanics * Scepter Blue: Add Narain's Letter of Apology --- sql/migrations/20170416095611_world.sql | 27 +++++++++++++++++++++++++ src/game/Language.h | 1 + src/scripts/world/boss_anachronos.cpp | 27 +++++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 sql/migrations/20170416095611_world.sql diff --git a/sql/migrations/20170416095611_world.sql b/sql/migrations/20170416095611_world.sql new file mode 100644 index 000000000..5e9517d3e --- /dev/null +++ b/sql/migrations/20170416095611_world.sql @@ -0,0 +1,27 @@ +INSERT INTO `migrations` VALUES ('20170416095611'); + +-- Update Meredith's menu option +UPDATE `gossip_menu_option` SET `option_text` = 'A kiss!', `condition_id` = 57 WHERE `menu_id` = 15526; + +-- Make Narain cry when completing "Love Song for Narain" +UPDATE `quest_template` SET `OfferRewardEmote1` = 18, `OfferRewardEmoteDelay1` = 1500 WHERE `entry` = 8599; + +-- Make "The Only Perscription" obtainable at neutral rep +UPDATE `quest_template` SET `RequiredMinRepValue` = 0 WHERE `entry` = 8620; + +-- Make "The Good News and the Bad News" obtainable at neutral rep +UPDATE `quest_template` SET `RequiredMinRepValue` = 0 WHERE `entry` = 8728; + +-- Make "Number Two" immune to most mechanics +UPDATE `creature_template` SET `MechanicImmuneMask` = (1 | 2 | 4 | 16 | 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 8192 | 65536 | 8388608) +WHERE `entry` = 15554; + +-- Add Narain's Letter +INSERT INTO `mangos_string` (`entry`, `content_default`, `content_loc1`, `content_loc2`, `content_loc3`, `content_loc4`, `content_loc5`, `content_loc6`, `content_loc7`, `content_loc8`) VALUES +(667, 'Champion,\r\n\r\nThe Blue Dragonflight believes that you are fated for greater things than even I could predict.\r\n\r\nDespite what some would have you believe, our world needs heroes. In your darkest hour, when you face the blight of Kalimdor, recall the epic journies, trials, and tribulations that you undertook for an old gnome and let those memories lift your spirits.\r\n\r\nHumbly,\r\n\r\nNarain Soothfancy\r\n\r\nP.S. Sorry about the repair costs.', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); + +-- Add condition "Love Song for Narain" done +INSERT INTO `conditions` (`condition_entry`, `type`, `value1`, `value2`) VALUES +(57, 8, 8599, 0); + + diff --git a/src/game/Language.h b/src/game/Language.h index 4e5300bc2..4424c2848 100644 --- a/src/game/Language.h +++ b/src/game/Language.h @@ -670,6 +670,7 @@ enum MangosStrings LANG_BG_AB_A_NEAR_VICTORY = 664, LANG_BG_AB_H_NEAR_VICTORY = 665, LANG_BG_MARK_BY_MAIL = 666, + LANG_NARAIN_LETTER = 667, //LANG_BG_EY_HAS_TAKEN_A_M_TOWER = 667, //LANG_BG_EY_HAS_TAKEN_H_M_TOWER = 668, diff --git a/src/scripts/world/boss_anachronos.cpp b/src/scripts/world/boss_anachronos.cpp index c447216d8..619840c38 100644 --- a/src/scripts/world/boss_anachronos.cpp +++ b/src/scripts/world/boss_anachronos.cpp @@ -20,12 +20,16 @@ EndScriptData */ enum { NPC_ANACHRONOS = 15192, + NPC_NARAIN = 11811, // Anachronos's spells // ------------------- SPELL_DIVINESHIELD = 1020, SPELL_HOMESTONE = 8690, + + QUEST_WRATH_OF_NEPTULON = 8729, + LANG_NARAIN_LETTER = 667, }; // Anachronos script @@ -95,6 +99,28 @@ struct boss_anachronosAI : public ScriptedAI } }; +bool QuestRewarded_boss_anachronos(Player* player, Creature* npc, Quest const* quest) +{ + if (quest->GetQuestId() != QUEST_WRATH_OF_NEPTULON) + return false; + + if (npc->GetEntry() != NPC_ANACHRONOS) + return false; + + if (!player) + return false; + + std::string letterText = player->GetSession()->GetMangosString(LANG_NARAIN_LETTER); + + // Send Narain's letter with 36 hour delay + MailDraft("", letterText.c_str()) + // Attach 100g + .SetMoney(1000001) + .SendMailTo(player, MailSender(MAIL_CREATURE, (uint32)NPC_NARAIN), MAIL_CHECK_MASK_NONE, 1.5 * DAY, 30 * DAY); + + return true; +} + CreatureAI* GetAI_boss_anachronos(Creature* pCreature) { return new boss_anachronosAI(pCreature); @@ -107,5 +133,6 @@ void AddSC_boss_anachronos() newscript = new Script; newscript->Name = "boss_anachronos"; newscript->GetAI = &GetAI_boss_anachronos; + newscript->pQuestRewardedNPC = &QuestRewarded_boss_anachronos; newscript->RegisterSelf(); } From 6068a5356c63fd76d8e515fe4f123c936eb45359 Mon Sep 17 00:00:00 2001 From: eir Date: Mon, 17 Apr 2017 20:19:46 -0700 Subject: [PATCH 02/16] Scripts/Ahn'Qiraj: Possible Fix for Skeram's MC (#417) * Fixed Unit error in NefariusAI --- .../blackwing_lair/boss_victor_nefarius.cpp | 2 +- .../temple_of_ahnqiraj/boss_skeram.cpp | 122 ++++++++++-------- 2 files changed, 66 insertions(+), 58 deletions(-) diff --git a/src/scripts/eastern_kingdoms/burning_steppes/blackwing_lair/boss_victor_nefarius.cpp b/src/scripts/eastern_kingdoms/burning_steppes/blackwing_lair/boss_victor_nefarius.cpp index bc796d8d9..e82d38f55 100644 --- a/src/scripts/eastern_kingdoms/burning_steppes/blackwing_lair/boss_victor_nefarius.cpp +++ b/src/scripts/eastern_kingdoms/burning_steppes/blackwing_lair/boss_victor_nefarius.cpp @@ -127,7 +127,7 @@ struct boss_victor_nefariusAI : ScriptedAI boss_victor_nefariusAI::Reset(); } - const uint32 MAX_SCEPTER_RUN_TIME = 1.5 * HOUR * MINUTE * IN_MILLISECONDS; + const uint32 MAX_SCEPTER_RUN_TIME = 1.5 * HOUR * IN_MILLISECONDS; const uint32 SCEPTER_TAUNT_INTERVAL = MAX_SCEPTER_RUN_TIME / MAX_SCEPTER_TAUNTS; const uint32 SCEPTER_TAUNT_OFFSET = SCEPTER_TAUNT_INTERVAL / 2; diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp index 8d409b25f..863b5c9b3 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp @@ -6,12 +6,12 @@ EndScriptData */ #include "scriptPCH.h" #include "temple_of_ahnqiraj.h" -#define SAY_AGGRO_1 -1531000 -#define SAY_AGGRO_2 -1531001 -#define SAY_AGGRO_3 -1531002 -#define SAY_SLAY_1 -1531003 -#define SAY_SLAY_2 -1531004 -#define SAY_SLAY_3 -1531005 +#define SAY_AGGRO_0 -1531000 +#define SAY_AGGRO_1 -1531001 +#define SAY_AGGRO_2 -1531002 +#define SAY_SLAY_0 -1531003 +#define SAY_SLAY_1 -1531004 +#define SAY_SLAY_2 -1531005 #define SAY_SPLIT -1531006 #define SAY_DEATH -1531007 @@ -19,14 +19,15 @@ EndScriptData */ #define SPELL_EARTH_SHOCK 26194 #define SPELL_TRUE_FULFILLMENT 785 +#define FULFILLMENT_RANGE 90.0f #define SPELL_TF_HASTE 2313 #define SPELL_TF_MOD_HEAL 26525 #define SPELL_TF_IMMUNITY 26526 -#define SPELL_TF_CANCEL 26589 +#define SPELL_TF_CANCEL 26589 -#define SPELL_BLINK_1 4801 -#define SPELL_BLINK_2 8195 -#define SPELL_BLINK_3 20449 +#define SPELL_BLINK_0 4801 +#define SPELL_BLINK_1 8195 +#define SPELL_BLINK_2 20449 #define SPELL_SUMMON_IMAGES 747 @@ -49,6 +50,7 @@ struct boss_skeramAI : public ScriptedAI float NextSplitPercent; Creature *ImageA, *ImageB; + ObjectGuid ControlledPlayerGUID; bool IsImage; @@ -65,56 +67,56 @@ struct boss_skeramAI : public ScriptedAI ImageA = nullptr; ImageA = nullptr; + ControlledPlayerGUID.Clear(); + } + + void CancelFulfillment() + { + if (Player* FulfilledPlayer = m_creature->GetMap()->GetPlayer(ControlledPlayerGUID)) + { + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TRUE_FULFILLMENT); + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_HASTE); + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_MOD_HEAL); + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_IMMUNITY); + } } void KilledUnit(Unit* victim) { - if (IsImage) - return; - - switch (urand(0,5)) + switch (urand(0,8)) { - case 0: DoScriptText(SAY_SLAY_1, m_creature); break; - case 1: DoScriptText(SAY_SLAY_2, m_creature); break; - case 2: DoScriptText(SAY_SLAY_3, m_creature); break; + case 0: DoScriptText(SAY_SLAY_0, m_creature); break; + case 1: DoScriptText(SAY_SLAY_1, m_creature); break; + case 2: DoScriptText(SAY_SLAY_2, m_creature); break; } - } void JustDied(Unit* Killer) { if (IsImage) { - if (Unit* victim = m_creature->GetCharm()) - { - victim->RemoveAurasDueToSpellByCancel(SPELL_TF_HASTE); - victim->RemoveAurasDueToSpellByCancel(SPELL_TF_MOD_HEAL); - victim->RemoveAurasDueToSpellByCancel(SPELL_TF_IMMUNITY); - } - + CancelFulfillment(); m_creature->ForcedDespawn(); return; } - + // Leave up to 20s of instant casts as reward for vaniquishing the True Prophet DoScriptText(SAY_DEATH, m_creature); + m_creature->SetRespawnDelay(7 * DAY); if (m_pInstance) - m_pInstance->SetData(TYPE_SKERAM, DONE); + m_pInstance->SetData(TYPE_SKERAM, DONE); } void Aggro(Unit *who) { - if (IsImage) - return; - if (m_pInstance && m_pInstance->GetData(TYPE_SKERAM) == IN_PROGRESS) return; switch (urand(0,2)) { - case 0: DoScriptText(SAY_AGGRO_1, m_creature); break; - case 1: DoScriptText(SAY_AGGRO_2, m_creature); break; - case 2: DoScriptText(SAY_AGGRO_3, m_creature); break; + case 0: DoScriptText(SAY_AGGRO_0, m_creature); break; + case 1: DoScriptText(SAY_AGGRO_1, m_creature); break; + case 2: DoScriptText(SAY_AGGRO_2, m_creature); break; } if (m_pInstance) @@ -123,24 +125,25 @@ struct boss_skeramAI : public ScriptedAI void JustReachedHome() { - if (m_pInstance) - m_pInstance->SetData(TYPE_SKERAM, FAIL); + CancelFulfillment(); if (IsImage) - m_creature->ForcedDespawn(); + m_creature->DoKillUnit(); + + if (m_pInstance) + m_pInstance->SetData(TYPE_SKERAM, FAIL); } void UpdateAI(const uint32 diff) { // Despawn Images instantly if the True Prophet died if (IsImage && m_pInstance && m_pInstance->GetData(TYPE_SKERAM) == DONE) - m_creature->ForcedDespawn(); + m_creature->DoKillUnit(); //Return since we have no target if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; - //ArcaneExplosion_Timer if (ArcaneExplosion_Timer < diff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ARCANE_EXPLOSION) == CAST_OK) @@ -148,10 +151,10 @@ struct boss_skeramAI : public ScriptedAI } else ArcaneExplosion_Timer -= diff; - //If we are within range melee the target + //If we are within range, melee the target if (m_creature->IsWithinMeleeRange(m_creature->getVictim())) DoMeleeAttackIfReady(); - else + else // Target not in melee range. Spam Earthshock { if (EarthShock_Timer < diff) @@ -159,35 +162,40 @@ struct boss_skeramAI : public ScriptedAI if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_EARTH_SHOCK) == CAST_OK) EarthShock_Timer = 1000; } - else + else EarthShock_Timer -= diff; } if (FullFillment_Timer < diff) { - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) // Get random target except highest threat + // Get random target excluding highest threat who is not MCed + if (Unit* MCTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) { - if (DoCastSpellIfCan(pTarget, SPELL_TRUE_FULFILLMENT, CAST_AURA_NOT_PRESENT) == CAST_OK) + if (DoCastSpellIfCan(MCTarget, SPELL_TRUE_FULFILLMENT, CAST_AURA_NOT_PRESENT) == CAST_OK) { - pTarget->CastSpell(pTarget, SPELL_TF_HASTE, true); - pTarget->CastSpell(pTarget, SPELL_TF_MOD_HEAL, true); - pTarget->CastSpell(pTarget, SPELL_TF_IMMUNITY, true); - FullFillment_Timer = urand(20000, 25000); + // Cancel buffs on previous victim + CancelFulfillment(); + + m_creature->CastSpell(MCTarget, SPELL_TF_HASTE, true); + m_creature->CastSpell(MCTarget, SPELL_TF_MOD_HEAL, true); + m_creature->CastSpell(MCTarget, SPELL_TF_IMMUNITY, true); + + FullFillment_Timer = urand(20500, 25000); + ControlledPlayerGUID = MCTarget->GetObjectGuid(); } } } else FullFillment_Timer -= diff; - //Blink_Timer if (Blink_Timer < diff) { CastBlink(m_creature); Blink_Timer = urand(10000, 18000); } - else + else Blink_Timer -= diff; - //Summon 2 Images and teleport for every 25% hp lost + // Summon 2 Images and teleport for every 25% hp lost if (!IsImage && m_creature->GetHealthPercent() < NextSplitPercent) if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_IMAGES) == CAST_OK) { @@ -209,7 +217,7 @@ struct boss_skeramAI : public ScriptedAI float skeramPercent = m_creature->GetHealthPercent(); - // Set health to look like the True Prophet. Will have 12.5%, 25%, finally 50% of max Skeram HP. + // Set health to look like the True Prophet. Will have 12.5%, 25%, finally 50% of max Skeram HP. skeramImage->SetMaxHealth(m_creature->GetMaxHealth() * (12.5f / skeramPercent) * (100 / (int)skeramPercent)); skeramImage->SetHealthPercent(skeramPercent); skeramImage->SetInCombatWithZone(); @@ -220,9 +228,9 @@ struct boss_skeramAI : public ScriptedAI else { ImageB = skeramImage; - UnisonBlink(); + UnisonBlink(); } - + } void UnisonBlink() @@ -254,7 +262,7 @@ struct boss_skeramAI : public ScriptedAI // Teleport to a random position in mask // Can teleport to any position if mask = 0x7 { - uint32 position = urand(0,2); + uint32 position = urand(0,2); while (!(1 << position & choiceMask)) // Bogo select position = urand(0, 2); @@ -266,9 +274,9 @@ struct boss_skeramAI : public ScriptedAI // Blink to one of the three platforms switch (position) { - case 0: caster->CastSpell(caster, SPELL_BLINK_1, true); break; - case 1: caster->CastSpell(caster, SPELL_BLINK_2, true); break; - case 2: caster->CastSpell(caster, SPELL_BLINK_3, true); break; + case 0: caster->CastSpell(caster, SPELL_BLINK_0, true); break; + case 1: caster->CastSpell(caster, SPELL_BLINK_1, true); break; + case 2: caster->CastSpell(caster, SPELL_BLINK_2, true); break; } DoResetThreat(); From 999c73f5e7ebe81d04e38b08cd994bba5d5b5f75 Mon Sep 17 00:00:00 2001 From: Ryan Cheung Date: Sun, 16 Apr 2017 10:47:38 -0500 Subject: [PATCH 03/16] Fix a exploit on dupe items using WPE (#404) --- src/game/Handlers/LootHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/game/Handlers/LootHandler.cpp b/src/game/Handlers/LootHandler.cpp index 2e0ef83e0..f5056adcd 100644 --- a/src/game/Handlers/LootHandler.cpp +++ b/src/game/Handlers/LootHandler.cpp @@ -458,7 +458,7 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) default: { // must be destroyed only if no loot - if (pItem->loot.isLooted()) + if (pItem->loot.isLooted() && !pItem->IsBag()) { pItem->SetLootState(ITEM_LOOT_REMOVED); player->DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), true); From 4df65b8f108552c6d03b736d48542b2d635e9436 Mon Sep 17 00:00:00 2001 From: GuybrushGit Date: Sun, 16 Apr 2017 23:17:44 +0100 Subject: [PATCH 04/16] Fix to NPC pets pull request (#410) * Revert fix to pets attacking when right clicked * PetAI fix to attacking when right clicked --- src/game/AI/PetAI.cpp | 15 +++++++++------ src/game/Handlers/CombatHandler.cpp | 2 +- src/game/Objects/Unit.cpp | 8 +++----- src/game/Objects/Unit.h | 2 +- 4 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/game/AI/PetAI.cpp b/src/game/AI/PetAI.cpp index d90d080a2..535e65083 100644 --- a/src/game/AI/PetAI.cpp +++ b/src/game/AI/PetAI.cpp @@ -157,7 +157,11 @@ void PetAI::UpdateAI(const uint32 diff) if (nextTarget) AttackStart(nextTarget); else + { + if (m_creature->isInCombat()) + m_creature->CombatStop(); HandleReturnMovement(); + } } else HandleReturnMovement(); @@ -379,7 +383,11 @@ void PetAI::KilledUnit(Unit* victim) if (Unit* nextTarget = SelectNextTarget(false)) AttackStart(nextTarget); else + { + if (m_creature->isInCombat()) + m_creature->CombatStop(); HandleReturnMovement(); // Return + } } void PetAI::AttackStart(Unit* target) @@ -464,11 +472,6 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const if (m_creature->HasReactState(REACT_PASSIVE)) return NULL; - // Check pet attackers first so we don't drag a bunch of targets to the owner - if (Unit* myAttacker = m_creature->getAttackerForHelper()) - if (!myAttacker->HasBreakableByDamageCrowdControlAura()) - return myAttacker; - // Not sure why we wouldn't have an owner but just in case... Unit* owner = m_creature->GetCharmerOrOwner(); if (!owner) @@ -476,7 +479,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const // Check owner attackers if (Unit* ownerAttacker = owner->getAttackerForHelper()) - if (!ownerAttacker->HasBreakableByDamageCrowdControlAura()) + if (!ownerAttacker->HasBreakableByDamageCrowdControlAura() && owner->isInCombat()) return ownerAttacker; // Check owner victim diff --git a/src/game/Handlers/CombatHandler.cpp b/src/game/Handlers/CombatHandler.cpp index db5d90e82..64b9ddd9e 100644 --- a/src/game/Handlers/CombatHandler.cpp +++ b/src/game/Handlers/CombatHandler.cpp @@ -61,7 +61,7 @@ void WorldSession::HandleAttackSwingOpcode(WorldPacket & recv_data) return; } - _player->Attack(pEnemy, true, _player->CanReachWithMeleeAttack(pEnemy)); + _player->Attack(pEnemy, true); } void WorldSession::HandleAttackStopOpcode(WorldPacket & /*recv_data*/) diff --git a/src/game/Objects/Unit.cpp b/src/game/Objects/Unit.cpp index 1cf6ed986..d47b6960d 100644 --- a/src/game/Objects/Unit.cpp +++ b/src/game/Objects/Unit.cpp @@ -808,7 +808,7 @@ uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDa if (damagetype != DOT) { - if (!getVictim() || !getVictim()->getAttackerForHelper()) + if (!getVictim()) { // if not have main target then attack state with target (including AI call) //start melee attacks only after melee hit @@ -5498,7 +5498,7 @@ bool Unit::IsNeutralToAll() const return my_faction->IsNeutralToAll(); } -bool Unit::Attack(Unit *victim, bool meleeAttack, bool triggerAIReaction) +bool Unit::Attack(Unit *victim, bool meleeAttack) { if (!victim || victim == this) return false; @@ -5557,9 +5557,7 @@ bool Unit::Attack(Unit *victim, bool meleeAttack, bool triggerAIReaction) addUnitState(UNIT_STAT_MELEE_ATTACKING); m_attacking = victim; - - if (triggerAIReaction) - m_attacking->_addAttacker(this); + m_attacking->_addAttacker(this); if (GetTypeId() == TYPEID_UNIT) // && !((Creature*)this)->GetLinkGroup()) { diff --git a/src/game/Objects/Unit.h b/src/game/Objects/Unit.h index a074546ab..832d392b4 100644 --- a/src/game/Objects/Unit.h +++ b/src/game/Objects/Unit.h @@ -1041,7 +1041,7 @@ class MANGOS_DLL_SPEC Unit : public WorldObject return nullptr; } - bool Attack(Unit *victim, bool meleeAttack, bool triggerAIReaction = true); + bool Attack(Unit *victim, bool meleeAttack); void AttackedBy(Unit* attacker); void CastStop(uint32 except_spellid = 0); bool AttackStop(bool targetSwitch = false); From 0f909fd8ee1aa8abcef0325098f73977ddcec1f5 Mon Sep 17 00:00:00 2001 From: Staden Date: Tue, 16 May 2017 10:45:58 +0100 Subject: [PATCH 05/16] AQ merge --- sql/migrations/20170516091651_world.sql | 577 + src/game/AI/CreatureAI.h | 2 +- src/game/AI/CreatureEventAIMgr.cpp | 2 +- src/game/AI/ScriptedAI.cpp | 16 +- src/game/AI/ScriptedAI.h | 2 +- src/game/AI/ScriptedInstance.cpp | 157 + src/game/AI/ScriptedInstance.h | 68 + src/game/Chat/Chat.cpp | 7640 ++--- src/game/Chat/Chat.h | 5 + src/game/Commands/Level3.cpp | 30 + src/game/Group/Group.cpp | 18 +- src/game/Handlers/LootHandler.cpp | 3 +- src/game/Maps/GridNotifiers.h | 43 +- src/game/Maps/GridSearchers.cpp | 9 + src/game/Maps/GridSearchers.h | 1 + src/game/ObjectMgr.cpp | 42 +- src/game/ObjectMgr.h | 18 +- src/game/Objects/Creature.cpp | 17 +- src/game/Objects/Creature.h | 2 + src/game/Objects/Object.cpp | 12 +- src/game/Objects/Object.h | 14 +- src/game/Objects/Player.cpp | 7 +- src/game/Objects/Unit.cpp | 23046 ++++++++-------- src/game/ScriptMgr.cpp | 67 +- src/game/ScriptMgr.h | 3 +- src/game/Spells/Spell.cpp | 61 +- src/game/Spells/SpellEffects.cpp | 14 +- src/game/Spells/SpellEntry.cpp | 6 + src/game/UnitAuraProcHandler.cpp | 14 +- .../boss_emperor_dagran_thaurissan.cpp | 2 +- .../zulgurub/boss_jindo.cpp | 2 +- .../ruins_of_ahnqiraj/boss_rajaxx.cpp | 41 + .../temple_of_ahnqiraj/boss_bug_trio.cpp | 684 +- .../temple_of_ahnqiraj/boss_cthun.cpp | 2787 +- .../temple_of_ahnqiraj/boss_fankriss.cpp | 581 +- .../temple_of_ahnqiraj/boss_huhuran.cpp | 149 +- .../silithus/temple_of_ahnqiraj/boss_ouro.cpp | 620 +- .../temple_of_ahnqiraj/boss_sartura.cpp | 418 +- .../temple_of_ahnqiraj/boss_skeram.cpp | 607 +- .../temple_of_ahnqiraj/boss_twinemperors.cpp | 1347 +- .../temple_of_ahnqiraj/boss_viscidus.cpp | 522 +- .../instance_temple_of_ahnqiraj.cpp | 922 +- .../mob_anubisath_sentinel.cpp | 182 +- .../temple_of_ahnqiraj/temple_of_ahnqiraj.h | 178 +- src/shared/Log.h | 9 + 45 files changed, 22231 insertions(+), 18716 deletions(-) create mode 100644 sql/migrations/20170516091651_world.sql diff --git a/sql/migrations/20170516091651_world.sql b/sql/migrations/20170516091651_world.sql new file mode 100644 index 000000000..644ba6c78 --- /dev/null +++ b/sql/migrations/20170516091651_world.sql @@ -0,0 +1,577 @@ +INSERT INTO `migrations` VALUES ('20170516091651'); + +# aq_script_texts.txt + + +-- for type, 0=CHAT_TYPE_SAY, 1=CHAT_TYPE_YELL, 2=CHAT_TYPE_TEXT_EMOTE, 3=CHAT_TYPE_BOSS_EMOTE, 4=CHAT_TYPE_WHISPER, 5=CHAT_TYPE_BOSS_WHISPER (4 and 5 are handled equally) + +-- Found a much more complete list of aq text scripts here: https://github.com/scriptdev2/scriptdev2-classic/blob/master/sql/scriptdev2_script_full.sql +-- These are copied from there, with some modifcations: + +-- -1531012: changed type to 3, todo: make sure it actually works... 2(prev val) worked, but 3 should have higher distance + +-- NOTE FOR ELYSIUM: QUick and dirty delete and replace. There are some french translations in the nost database. If you want to keep these, make a more fancy update +DELETE FROM script_texts WHERE entry BETWEEN -1531046 AND -1531000; +INSERT INTO script_texts (entry, content_default, sound, type, language, emote, comment) VALUES + + +-- Skeram +(-1531000,'Are you so eager to die? I would be happy to accomodate you.',8615,1,0,0,'skeram SAY_AGGRO1'), +(-1531001,'Cower mortals! The age of darkness is at hand.', 8616,1,0,0,'skeram SAY_AGGRO2'), +(-1531002,'Tremble! The end is upon you.', 8621,1,0,0,'skeram SAY_AGGRO3'), +(-1531003,'Let your death serve as an example!', 8617,1,0,0,'skeram SAY_SLAY1'), +(-1531004,'Spineless wretches! You will drown in rivers of blood!',8619,1,0,0,'skeram SAY_SLAY2'), +(-1531005,'The screams of the dying will fill the air. A symphony of terror is about to begin!',8620,1,0,0,'skeram SAY_SLAY3'), +(-1531006,'Prepare for the return of the ancient ones!', 8618,1,0,0,'skeram SAY_SPLIT'), +(-1531007,'You only delay... the inevetable.', 8622,1,0,0,'skeram SAY_DEATH'), + +-- Sartura +(-1531008,'You will be judged for defiling these sacred grounds! The laws of the Ancients will not be challenged! Trespassers will be annihilated!',8646,1,0,0,'sartura SAY_AGGRO'), +(-1531009,'I sentence you to death!', 8647,1,0,0,'sartura SAY_SLAY'), +(-1531010,'I serve to the last!', 8648,1,0,0,'sartura SAY_DEATH'), + +-- C'thun weakened +(-1531011,'%s is weakened!', 0,2,0,0,'cthun EMOTE_WEAKENED'), + +-- Twin emperors intro +(-1531012,'The massive floating eyeball in the center of the chamber turns its gaze upon you. You stand before a god.', 0,3,0,0,'eye cthun EMOTE_INTRO'), +(-1531013,'Only flesh and bone. Mortals are such easy prey...', 0,1,0,0,'veklor SAY_INTRO_1'), +(-1531014,'Where are your manners, brother. Let us properly welcome our guests.', 0,1,0,0,'veknilash SAY_INTRO_2'), +(-1531015,'There will be pain...', 0,1,0,0,'veklor SAY_INTRO_3'), +(-1531016,'Oh so much pain...', 0,1,0,0,'veknilash SAY_INTRO_4'), +(-1531017,'Come, little ones.', 0,1,0,0,'veklor SAY_INTRO_5'), +(-1531018,'The feast of souls begins now...', 0,1,0,0,'veknilash SAY_INTRO_6'), + +-- Vek'lor yells +(-1531019,'It\'s too late to turn away.', 8623,1,0,0,'veklor SAY_AGGRO_1'), +(-1531020,'Prepare to embrace oblivion!', 8626,1,0,0,'veklor SAY_AGGRO_2'), +(-1531021,'Like a fly to the web.', 8624,1,0,0,'veklor SAY_AGGRO_3'), +(-1531022,'Your brash arrogance!', 8628,1,0,0,'veklor SAY_AGGRO_4'), +(-1531023,'You will not escape death!', 8629,1,0,0,'veklor SAY_SLAY'), +(-1531024,'My brother...NO!', 8625,1,0,0,'veklor SAY_DEATH'), +(-1531025,'To decorate our halls!', 8627,1,0,0,'veklor SAY_SPECIAL'), + +-- Vek'nilash yells +(-1531026,'Ah, lambs to the slaughter!', 8630,1,0,0,'veknilash SAY_AGGRO_1'), +(-1531027,'Let none survive!', 8632,1,0,0,'veknilash SAY_AGGRO_2'), +(-1531028,'Join me brother, there is blood to be shed!', 8631,1,0,0,'veknilash SAY_AGGRO_3'), +(-1531029,'Look brother, fresh blood!', 8633,1,0,0,'veknilash SAY_AGGRO_4'), +(-1531030,'Your fate is sealed!', 8635,1,0,0,'veknilash SAY_SLAY'), +(-1531031,'Vek\'lor, I feel your pain!', 8636,1,0,0,'veknilash SAY_DEATH'), +(-1531032,'Shall be your undoing!', 8634,3,0,0,'veknilash SAY_SPECIAL'), + +-- C'thun whispers +(-1531033,'Death is close...', 8580,4,0,0,'cthun SAY_WHISPER_1'), +(-1531034,'You are already dead.', 8581,4,0,0,'cthun SAY_WHISPER_2'), +(-1531035,'Your courage will fail.', 8582,4,0,0,'cthun SAY_WHISPER_3'), +(-1531036,'Your friends will abandon you.', 8583,4,0,0,'cthun SAY_WHISPER_4'), +(-1531037,'You will betray your friends.', 8584,4,0,0,'cthun SAY_WHISPER_5'), +(-1531038,'You will die.', 8585,4,0,0,'cthun SAY_WHISPER_6'), +(-1531039,'You are weak.', 8586,4,0,0,'cthun SAY_WHISPER_7'), +(-1531040,'Your heart will explode.', 8587,4,0,0,'cthun SAY_WHISPER_8'), + +-- Viscidus emotes +(-1531041,'%s begins to slow!', 0,3,0,0,'viscidus EMOTE_SLOW'), +(-1531042,'%s is freezing up!', 0,3,0,0,'viscidus EMOTE_FREEZE'), +(-1531043,'%s is frozen solid!', 0,3,0,0,'viscidus EMOTE_FROZEN'), +(-1531044,'%s begins to crack!', 0,3,0,0,'viscidus EMOTE_CRACK'), +(-1531045,'%s looks ready to shatter!', 0,3,0,0,'viscidus EMOTE_SHATTER'), +(-1531046,'%s explodes!', 0,3,0,0,'viscidus EMOTE_EXPLODE'); + +# viscidus.sql + +-- cmangos unit flags Viscidus trigger TOD : search flags name +UPDATE creature_template SET unit_flags = unit_flags | 33587968 WHERE entry = 15922; + +-- Viscidus trigger aren't targettable and can't fight players +UPDATE creature_template SET minlevel = 63, maxlevel = 63, unit_flags = unit_flags | (33554432 + 512), scriptname = "boss_viscidus_trigger" WHERE entry = 15922; + +-- Viscidus trigger must be hostile (faction 14 = moster) to work, both in viscidus logic and in c'thuns stomach. +UPDATE creature_template SET faction_A = 14, faction_H= 14 WHERE entry=15922; + +-- Summon glob of Viscidus spell target position +DELETE FROM spell_target_position WHERE id BETWEEN 25865 AND 25884; +INSERT INTO spell_target_position (id , target_map, target_position_x, target_position_y, target_position_z, target_orientation) VALUES +(25865, 531, -8023.59, 964.772, -41.229, 5.376), +(25866, 531, -8042.13, 911.263, -42.841, 6.2), +(25867, 531, -7999.36, 860.525, -47.206, 1.417), +(25868, 531, -7971.3, 862.581, -48.099, 2.148), +(25869, 531, -7943.21, 903.804, -48.473, 3.078), +(25870, 531, -7954.38, 958.562, -41.609, 3.962), +(25871, 531, -7997.19, 979.192, -41.653, 4.896), +(25872, 531, -8037.89, 929.679, -43.416, 6.024), +(25873, 531, -8015.41, 867.734, -45.607, 1.103), +(25874, 531, -7982.8, 857.172, -48.212, 1.5), +(25875, 531, -7952.12, 883.183, -48.194, 2.43), +(25876, 531, -7947.22, 939.122, -44.014, 3.718), +(25877, 531, -7975.77, 974.82, -41.584, 4.417), +(25878, 531, -8032.75, 948.274, -41.919, 5.595), +(25879, 531, -8037.08, 887.268, -43.581, 0.675), +(25880, 531, -7992.21, 857.5, -47.762, 1.664), +(25881, 531, -7960.71, 872.483, -48.759, 2.36), +(25882, 531, -7942.98, 918.616, -46.401, 3.306), +(25883, 531, -7964.32, 967.879, -42.112, 4.087), +(25884, 531, -8015.24, 976.553, -41.647, 4.947); + +-- correct glob of Viscidus modelid and unit flags +UPDATE creature_template SET modelid_1 = 12349, unit_flags = 32768 WHERE entry = 15667; + +-- Remove silver drops from Glob of Viscidus +UPDATE creature_template SET mingold = 0, maxgold = 0 WHERE entry = 15667; + +-- Update Glob of Viscidus immunities +UPDATE creature_template SET MechanicImmuneMask = 617299803 WHERE entry = 15667; + +-- Viscidus teleport spell +INSERT INTO spell_target_position (id, target_map, target_position_x, target_position_y, target_position_z, target_orientation) VALUES (25904, 531, -7992.36, 908.19, -52.62, 1.68); + +-- Not tauntable +UPDATE creature_template SET flags_extra = 257 WHERE entry = 15299; + +-- Update speed +UPDATE creature_template SET speed_walk = 3, speed_run = 3 WHERE entry = 15299; +UPDATE creature_template SET speed_run = 1 WHERE entry = 15667; + +# Twins.sql +-- Moved the masters eye up in the air and turned it around to face the emperors. Script will turn it towards players +UPDATE `creature` SET `position_z`='-102.44', `orientation`='4.896' WHERE `guid`='88072'; + +-- Added ScriptName, made unit non-attackable and experimented with some other flags for floating, but they should be back to what they were. +UPDATE `creature_template` SET `unit_flags`=(2) , `AIName`='EventAI', `MovementType` = '0',`InhabitType` = '3', `ScriptName`='mob_masters_eye' WHERE `entry`='15963'; + + +DELETE FROM spell_mod WHERE Id = 800; +INSERT INTO spell_mod (`Id`, `DurationIndex`,`Comment`) VALUES ('800', '39','Spell twins teleport stun 2 sec'); + +-- Increased their runspeed. No idea exactly what it should be, but absolutely more than their default one +UPDATE creature_template SET speed_run=1.8 WHERE entry=15275; +UPDATE creature_template SET speed_run=1.8 WHERE entry=15276; + + -- 15761 0.558 2 2 0 0 + -- 15778 7.1 10 2 0 0 +UPDATE creature_model_info SET `bounding_radius`='1.2', `combat_reach`='6' WHERE `modelid`='15761'; +UPDATE creature_model_info SET `bounding_radius`='1.2', `combat_reach`='6' WHERE `modelid`='15778'; + + +-- scripted ai for bugs on twins to robustify resetting +UPDATE creature_template SET `ScriptName`='mob_twins_bug' WHERE `entry`='15317'; +UPDATE creature_template SET `ScriptName`='mob_twins_bug' WHERE `entry`='15316'; + +-- creating creature_equip_template entry for Vek'lors scepter +DELETE FROM creature_equip_template WHERE entry = 16000; +INSERT INTO creature_equip_template (entry, equipentry1) VALUES (16000, 21796); + +-- Giving Vek'lor the scepter equip template +UPDATE creature_template SET equipment_id=16000 WHERE entry=15276; + +-- making emperors immune to disarm +UPDATE creature_template SET MechanicImmuneMask = (MechanicImmuneMask | 4) WHERE entry = 15275; +UPDATE creature_template SET MechanicImmuneMask = (MechanicImmuneMask | 4) WHERE entry = 15276; + +-- Vek'nilash should drop Belt of the Fallen Emperor for alliance only, and Grasp of the Fallen Emperor for horde only +UPDATE reference_loot_template SET condition_id = 3 WHERE entry = 328943 and item = 21606; +UPDATE reference_loot_template SET condition_id = 2 WHERE entry = 328943 and item = 21607; + +# Trash.sql + +-- Meteors for anubisath defenders had event_param1 and 2 swapped +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527732'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527728'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527724'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527720'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527716'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527712'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527708'; +UPDATE `creature_ai_scripts` SET `event_param1`='5000', `event_param2`='6000' WHERE `id`='1527704'; + +-- Add detect invis/stealth and taunt immune aura +INSERT INTO `creature_template_addon` (`entry`, `mount`, `bytes1`, `b2_0_sheath`, `b2_1_flags`, `emote`, `moveflags`, `auras`) VALUES ('15246', '0', '0', '1', '16', '0', '0', '18950 26602'); +INSERT INTO `creature_template_addon` (`entry`, `mount`, `bytes1`, `b2_0_sheath`, `b2_1_flags`, `emote`, `moveflags`, `auras`) VALUES ('15247', '0', '0', '1', '16', '0', '0', '18950'); +INSERT INTO `creature_template_addon` (`entry`, `mount`, `bytes1`, `b2_0_sheath`, `b2_1_flags`, `emote`, `moveflags`, `auras`) VALUES ('15233', '0', '0', '1', '16', '0', '0', '18950'); + +-- Position adjustments +UPDATE `creature` SET `position_y`='1759.77' WHERE `guid`='88027'; +UPDATE `creature` SET `position_y`='1780.08', `position_z`='-42.6571' WHERE `guid`='88024'; +UPDATE `creature` SET `position_x`='-900.787109', `position_y`='1916.039063', `position_z`='-43.814262' WHERE `guid`='88063'; + +-- Replace qiraji mindslayers eventAI with scripted ai. Script is located in instance_temple_of_ahnqiraj.cpp. +UPDATE `creature_template` SET `AIName`='', `ScriptName`='mob_qiraji_mindslayer' WHERE `entry`='15246'; + +-- In reference to issue #551 https://github.com/elysium-project/server/issues/551 +-- Anubisath Warders, Obsidian Nullfiers, QIraji Slayers, Qiraji Champions and Qiraji Mindslayers should not respawn +-- during the same save-ID once killed. Setting spawntimersecs to 7 days. +UPDATE `creature` SET `spawntimesecs`='604800' where id IN(15311, 15312, 15250, 15252, 15246); + +# Spells.sql + +# 1.9.0 spell values +INSERT INTO `spell_effect_mod` (`Id`, `EffectIndex`, `Effect`, `EffectDieSides`, `EffectBaseDice`, `EffectDicePerLevel`, `EffectRealPointsPerLevel`, `EffectBasePoints`, `EffectAmplitude`, `EffectPointsPerComboPoint`, `EffectChainTarget`, `EffectMultipleValue`, `EffectMechanic`, `EffectImplicitTargetA`, `EffectImplicitTargetB`, `EffectRadiusIndex`, `EffectApplyAuraName`, `EffectItemType`, `EffectMiscValue`, `EffectTriggerSpell`, `Comment`) VALUES ('26478', '0', '-1', '-1', '-1', '-1', '-1', '3149', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', 'C\'Thun Giant Tentacle Ground Rupture 1.9.0 Damage'); +INSERT INTO `spell_effect_mod` (`Id`, `EffectIndex`, `Effect`, `EffectDieSides`, `EffectBaseDice`, `EffectDicePerLevel`, `EffectRealPointsPerLevel`, `EffectBasePoints`, `EffectAmplitude`, `EffectPointsPerComboPoint`, `EffectChainTarget`, `EffectMultipleValue`, `EffectMechanic`, `EffectImplicitTargetA`, `EffectImplicitTargetB`, `EffectRadiusIndex`, `EffectApplyAuraName`, `EffectItemType`, `EffectMiscValue`, `EffectTriggerSpell`, `Comment`) VALUES ('26478', '1', '-1', '-1', '-1', '-1', '-1', '249', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', 'C\'Thun Giant Tentacle Ground Rupture 1.9.0 Knockback'); +INSERT INTO `spell_effect_mod` (`Id`, `EffectIndex`, `Effect`, `EffectDieSides`, `EffectBaseDice`, `EffectDicePerLevel`, `EffectRealPointsPerLevel`, `EffectBasePoints`, `EffectAmplitude`, `EffectPointsPerComboPoint`, `EffectChainTarget`, `EffectMultipleValue`, `EffectMechanic`, `EffectImplicitTargetA`, `EffectImplicitTargetB`, `EffectRadiusIndex`, `EffectApplyAuraName`, `EffectItemType`, `EffectMiscValue`, `EffectTriggerSpell`, `Comment`) VALUES ('26093', '0', '-1', '-1', '-1', '-1', '-1', '1349', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', 'Ouro\'s Dirt Mound Quake 1.9.0 Damage'); +INSERT INTO `spell_effect_mod` (`Id`, `EffectIndex`, `Effect`, `EffectDieSides`, `EffectBaseDice`, `EffectDicePerLevel`, `EffectRealPointsPerLevel`, `EffectBasePoints`, `EffectAmplitude`, `EffectPointsPerComboPoint`, `EffectChainTarget`, `EffectMultipleValue`, `EffectMechanic`, `EffectImplicitTargetA`, `EffectImplicitTargetB`, `EffectRadiusIndex`, `EffectApplyAuraName`, `EffectItemType`, `EffectMiscValue`, `EffectTriggerSpell`, `Comment`) VALUES ('24318', '0', '-1', '-1', '-1', '-1', '-1', '249', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', 'Enrage 1.9.0 Damage (nerfed in 1.9.3)'); +INSERT INTO `spell_effect_mod` (`Id`, `EffectIndex`, `Effect`, `EffectDieSides`, `EffectBaseDice`, `EffectDicePerLevel`, `EffectRealPointsPerLevel`, `EffectBasePoints`, `EffectAmplitude`, `EffectPointsPerComboPoint`, `EffectChainTarget`, `EffectMultipleValue`, `EffectMechanic`, `EffectImplicitTargetA`, `EffectImplicitTargetB`, `EffectRadiusIndex`, `EffectApplyAuraName`, `EffectItemType`, `EffectMiscValue`, `EffectTriggerSpell`, `Comment`) VALUES ('24318', '1', '-1', '-1', '-1', '-1', '-1', '59', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1', 'Enrage 1.9.0 Haste (slightly buffed in 1.9.3)'); + +# Sartura.sql + +-- Make immune to disarm +UPDATE creature_template SET MechanicImmuneMask = 617297759 WHERE entry = 15516; + +# Reputation.sql + +-- factions: 609=CC, 910=brood + +-- =================== AQ 40 ================================================================================================= +-- =========================================================================================================================== +-- Anubisath Defender 100 rep with brood, 0 with CC +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15277'; + +-- Anubisath Sentinel 100 rep with brood, 0 with CC +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15264'; + +-- Obsidian Eradicator 100 rep with brood, 0 with CC + UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15262'; + +-- Qiraji Lasher 100 rep with brood, 0 with CC + UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15249'; + +-- Vekniss Solider 100 rep with brood, 0 with CC + UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15229'; + +-- Vekniss Stinger 100 rep with brood, 0 with CC + UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15235'; + +-- Vekniss Warrior 100 rep with brood, 0 with CC + UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15230'; + +-- Vekniss Wasp 100 rep with brood, 0 with CC +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15236'; + +-- Vekniss hive crawler 100 rep with brood, 0 with CC +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='0' WHERE `creature_id`='15240'; + +-- C'thun gives 2500rep until exalted with brood, and 500 with cenarion circle +DELETE FROM creature_onkill_reputation where creature_id = 15727; +INSERT INTO `creature_onkill_reputation` (`creature_id`, `RewOnKillRepFaction1`, `RewOnKillRepFaction2`, `MaxStanding1`, `IsTeamAward1`, `RewOnKillRepValue1`, `MaxStanding2`, `IsTeamAward2`, `RewOnKillRepValue2`, `TeamDependent`) +VALUES ('15727', '910', '609', '7', '0', '2500', '7', '0', '500', '0'); + +-- Shows rep of cthun and above mentioned trashmobs +-- SELECT * FROM creature_onkill_reputation where creature_id IN (15727, 15277, 15264, 15262, 15249, 15229, 15235, 15230, 15236, 15240); + +-- Twin emperors each give 210 rep, seems about right. +-- SELECT * FROM creature_onkill_reputation where creature_id IN (15276, 15275); + +-- No bosses except cthun and twins should give rep with brood, can controll with this select +-- SELECT * FROM creature_onkill_reputation where creature_id IN (15263, 15544, 15510, 15299, 15509, 15516, 15517, 15543, 15511); + +-- Everything above is mentioned on wowwiki, hive crawlers are additionally mentioned here: +-- http://wow.gamepedia.com/Brood_of_Nozdormu also mentions Vekniss hive crawler: + + + +-- ================ AQ 20 =================================================================================================== +-- ========================================================================================================================== +-- AQ20 bosses gives 300 (600 ossirian) according to http://wowwiki.wikia.com/wiki/Cenarion_Circle_reputation_guide +-- but if you check each individual boss they are said to give 150CC and 50 Brood rep (100/300 Ossirian). Presumably +-- the latter is a pre-"nerf" value. I am unable to find anything about when they stop giving rep, other than wowwiki +-- saying they give rep with both CC and Brood until exalted. + +-- buru 15370 +-- moam 15340 +-- kurinaxx 15348 +-- ayamiss 15369 +-- ossirian 15339 +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='50', `RewOnKillRepValue2`='150' WHERE `creature_id`='15370'; +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='50', `RewOnKillRepValue2`='150' WHERE `creature_id`='15340'; +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='50', `RewOnKillRepValue2`='150' WHERE `creature_id`='15348'; +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='50', `RewOnKillRepValue2`='150' WHERE `creature_id`='15369'; +UPDATE `creature_onkill_reputation` SET `RewOnKillRepValue1`='100', `RewOnKillRepValue2`='300' WHERE `creature_id`='15339'; + -- SELECT * FROM creature_onkill_reputation where creature_id IN (15370, 15340, 15348, 15369, 15339); + +-- C'thuns legacy gives 500 CC rep and 500 Brood rep. +UPDATE `quest_template` SET `RewRepFaction2`='910', `RewRepValue1`='500', `RewRepValue2`='500' WHERE `entry`='8801'; + +-- The Saviour of Kalimdor gives 500 CC rep and 1000 Brood rep. +UPDATE `quest_template` SET `RewRepFaction2`='910', `RewRepValue1`='500', `RewRepValue2`='1000' WHERE `entry`='8802'; + +# Ouro.sql + +-- Replace Ouro by it's spawner +UPDATE creature SET id = 15957 WHERE id = 15517; + +-- Give AI to Ouro spawner +UPDATE creature_template SET ScriptName = "npc_ouro_spawner" WHERE entry = 15957; + +-- Give invisible model to Ouro spawner +UPDATE creature_template SET modelid_1 = 11686 WHERE entry = 15957; +UPDATE creature SET modelid = 11686 WHERE id = 15957; + +-- Give AI to Ouro dirt mound +UPDATE creature_template SET ScriptName = "npc_dirt_mound" WHERE entry = 15712; + +-- Corect faction for Ouro dirt mound +UPDATE creature_template SET faction_H = 14, faction_A = 14 WHERE entry = 15712; + +-- Correct level for Ouro dirt mound +UPDATE creature_template SET minlevel = 63, maxlevel = 63 WHERE entry = 15712; + +-- Ouro dirt mound are not targettable +UPDATE creature_template SET unit_flags = unit_flags | 33554432 WHERE entry = 15712; + +-- cmangos unit flags Ouro spawner TOD : search flags name +UPDATE creature_template SET unit_flags = unit_flags | 33587200 WHERE entry = 15957; + +-- Ouro trigger is not targettable +UPDATE creature_template SET unit_flags = unit_flags | 33554432 WHERE entry = 15717; + +-- Add scriptname to Ouro scarab +UPDATE creature_template SET ScriptName = "npc_ouro_scarab" WHERE entry = 15718; + +-- Ouro sandblast should be a debuff +DELETE FROM spell_mod where Id = 26102; +INSERT INTO spell_mod (Id, Custom, Comment) VALUES (26102, 2, "Ouro's sandblast should be negative"); + +-- Add scripted target for Despawn Base spell +DELETE FROM spell_script_target WHERE entry = 26594; +INSERT INTO spell_script_target (entry, type, targetEntry) VALUES (26594, 0, 180795); + +-- Ouro base shouldn't be targettable by players and should despawn after sending animation on use +UPDATE gameobject_template SET data3 = 65536 * 900, data4 = 1, data5 = 1 WHERE entry = 180795; + +-- Add scriptname to Ouro base +UPDATE gameobject_template SET scriptname = "go_sandworm_base" WHERE entry = 180795; + +-- Update model combat reach +UPDATE creature_model_info SET combat_reach = '20' WHERE modelid = 15509; + +-- Fix spell effect target for base desummoning +INSERT INTO spell_script_target (`entry`, `type`, `targetEntry`) VALUES (26063, 0, 180795); + +# Mount.sql + +# Black Qiraji mount fixes +DELETE FROM spell_mod WHERE Id = 25863; +UPDATE item_template SET spellid_1 = 26656 WHERE entry = 21176; +UPDATE item_template SET spellcooldown_1 =1 WHERE entry = 21176; + +# Instance.sql + + +-- Setting 7day respawn timer on all AQ bosses. Note for ouro it's the spawner creature we need to set the respawn timer on. +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='88075'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='88076'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='88077'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87938'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='88014'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87911'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87602'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87648'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87601'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87603'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='87559'; +UPDATE `creature` SET `spawntimesecs`='604800' WHERE `guid`='88073'; + +/* +SELECT * FROM mangos.creature where id in( +15275, -- twins +15276, -- twins +15263, -- skeram +15299, -- viscidus +15509, -- huhuran +15510, -- fankriss +15511, -- kri +15516, -- sartura +15517, -- ouro +15543, -- yauj +15544, -- vem +15727, -- cthun +15957) -- ouro spawner +*/ + +# Huhuran.sql + +-- Change damage of Huhuran Wyvern Sting casted on dispelled Wyvern Sting +DELETE FROM spell_effect_mod WHERE Id = 26233; +INSERT INTO spell_effect_mod (Id, EffectBasePoints, Comment) VALUES (26233, 3000, "Huhuran wyvern sting should do 3-4k damage on dispelled"); + +-- add flag SPELL_ATTR_EX4_IGNORE_RESISTANCES to Huhuran acid spit +DELETE FROM spell_mod WHERE Id = 26050; +INSERT INTO spell_mod (Id, AttributesEx4, Comment) VALUES (26050, 1, "Huhuran acid spit ignore resistances"); + +# Fankriss.sql + + +-- Spawn of Fankriss enrage happens, seemingly, at a random point between 10 and 20 seconds after spawn. +-- Some sources say 10 sec, some 15 and some 20. From videos I can see it happening at any point aproximately +-- between 10 and 20 seconds. I therefore conclude it is either rand(10,20) sec, OR it should be based on something +-- else which is not yet understood. +-- EDIT: db ai no longer used. Creature has its own script. +-- UPDATE creature_ai_scripts SET event_param1=10000, event_param2=20000 WHERE id=1563001; + + + +UPDATE `creature_template` SET `AIName`='', `speed_walk`='1.4', `ScriptName`='creature_spawn_fankriss' WHERE `entry`='15630'; + +UPDATE `creature_template` SET `ScriptName`='creature_vekniss_hatchling' WHERE `entry`='15962'; + +# CThunGrasp.sql + +-- Update creatures position +UPDATE creature SET position_x = -8652.2, position_y = 2020.92, position_z = 108.58, orientation = 3.65 WHERE id = 15378; +UPDATE creature SET position_x = -8660.63, position_y = 2022.4, position_z = 108.58, orientation = 4.09 WHERE id = 15379; +UPDATE creature SET position_x = -8663.34, position_y = 2029.9, position_z = 108.58, orientation = 4.31 WHERE id = 15380; + +-- Apply faction brood of Nozdormu to npcs after C'Thun +UPDATE creature_template SET faction_H = 35, faction_A = 35 WHERE entry BETWEEN 15378 AND 15380; + +-- Add Grasps +DELETE FROM gameobject WHERE guid BETWEEN 21797 AND 21799; +INSERT INTO gameobject (guid, id, map, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnFlags) VALUES +(21797, 180745, 531, -8660.63, 2022.4, 108.577, 3.64774, 0, 0, -0.968147, 0.250381, 7200, 100, 1, 0), +(21798, 180745, 531, -8652.2, 2020.92, 108.577, 0.244346, 0, 0, 0.121869, 0.992546, 7200, 100, 1, 0), +(21799, 180745, 531, -8663.34, 2029.9, 108.577, 4.45059, 0, 0, -0.793353, 0.608762, 7200, 100, 1, 0); + +-- Set Grasps untargettables +UPDATE gameobject_template SET data1 = 0 WHERE entry = 180745; + +-- Add a scriptname to caelestrasz in aq, used to handle gossip text +UPDATE creature_template SET `ScriptName`='aq_caelestrasz_ai' WHERE `entry`='15379'; + +-- npc texts for Caelestrasz in AQ +DELETE FROM npc_text WHERE ID BETWEEN '40100' AND '40101'; +INSERT INTO npc_text (`ID`, `text0_0`) VALUES ('40100', 'Even if you somehow manage to free us without defeating C\'Thun, we would focus all our powers to see the beast banished back to the hell from whence it came - AT ANY COST.'); +INSERT INTO npc_text (`ID`, `text0_0`) VALUES ('40101', 'Our freedom would have meant nothing if C\'Thun had survived. You are truly a champion of prophecy.'); + +# Doors.sql + +-- Spawn AQ doors +DELETE FROM gameobject WHERE guid BETWEEN 21783 AND 21785; +INSERT INTO gameobject (guid, id, map, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state, spawnFlags) VALUES +(21783, 180634, 531, -8929.61, 1344.38, -104.211, 3.84846, 0, 0, -0.938191, 0.346119, 7200, 100, 1, 0), +(21784, 180635, 531, -9016.36, 1330.68, -104.211, 2.80125, 0, 0, 0.985556, 0.169352, 7200, 100, 1, 0), +(21785, 180636, 531, -8429.59, 2048.81, 153.309, 3.51685, 0, 0, -0.982449, 0.186529, 7200, 100, 1, 0); + +-- Makes doors untargettable and no despawn +UPDATE gameobject_template SET flags = 36 WHERE entry BETWEEN 180634 AND 180636; + +# CThun.sql + +-- C'Thun portals aren't targettable +UPDATE creature_template SET unit_flags = unit_flags | 33554432 WHERE entry IN (15896, 15904, 15910); + +-- Correct eye tentacle model +UPDATE creature_template SET modelid_1 = 15788 WHERE entry = 15726; + +-- Correct giant eye tentacle scale +UPDATE creature_template SET scale = 5 WHERE entry = 15334; +-- Correct eye tentacle scale +UPDATE creature_template SET `scale`='1' WHERE `entry`='15726'; + +-- Correct giant claw tentacle scale +UPDATE creature_template SET scale = 5 WHERE entry = 15728; + +-- Setting correct scale of claw tentacle +UPDATE creature_template SET `scale`='2' WHERE `entry`='15725'; + + + + -- cmangos unit flags C'Thun tentacles TOD : search flags name + UPDATE creature_template SET unit_flags = unit_flags | 32768 WHERE entry IN (15334, 15725, 15726, 15728, 15802); + + -- Bigger melee range for c'thun in p1 + UPDATE creature_model_info set `combat_reach` = 15, `bounding_radius` = 15 where `modelid` = 15556; + + + -- flesh tentacle fix melee range + UPDATE creature_model_info set `combat_reach` = 10, `bounding_radius` = 1.2 where `modelid` = 15793; + + -- Giant claw tentacle fix melee range + UPDATE creature_model_info set `combat_reach` = 10, `bounding_radius` = 1.2 where `modelid` = 15790; + -- Claw tentacle fix melee range + UPDATE creature_model_info set `combat_reach` = 3.5, `bounding_radius` = 1.89 where `modelid` = 15789; + + -- combat reach fixes for eye tentacles. Since they use same modelId atm it may need to be overwritten in code + -- if 2 and 10 seems wrong. + -- Giant Eye tentacle fix melee range + UPDATE creature_model_info set `combat_reach` = 2, `bounding_radius` = 1.2 where `modelid` = 15788; + -- Eye tentacle + -- UPDATE creature_model_info set `combat_reach` = 3.5, `bounding_radius` = 1.2 where `modelid` = 15788; + + + + + -- moved c'thun eye and body slightly towards entrance +UPDATE creature SET `position_x`='-8577.270', `position_y`='1986.942' WHERE `guid`='87560'; + +UPDATE creature SET `position_x`='-8577.270', `position_y`='1986.942' WHERE `guid`='87559'; + + +-- Set Giant claw dmg to around 2500 dmg per hit on a full t2 geared tank, with demo shout up. ~3200 without demo shout. +UPDATE creature_template SET `mindmg`='8500', `maxdmg`='9500' WHERE `entry`='15728'; + +-- Set Giant eye dmg to around 2500 dmg per hit on a full t2 geared tank, with demo shout up. ~3200 without demo shout. +UPDATE creature_template SET `mindmg`='8500', `maxdmg`='9500', `baseattacktime`='2000' WHERE `entry`='15334'; + +-- Set eye tentacle damage 350-450 on 38% armor (need a good source for what this dmg should be) +UPDATE creature_template SET `mindmg`='500', `maxdmg`='800', `baseattacktime`='2000' WHERE `entry`='15726'; + +-- Claw tentacle damage 350-450 on 38% armor (french pdf say top 200-300dmg, so maybe reduce) +UPDATE creature_template SET `mindmg`='500', `maxdmg`='800', `baseattacktime`='2000' WHERE `entry`='15725'; + + +-- stomach of cthun area triggers +DELETE FROM scripted_areatrigger WHERE entry IN (4033, 4034, 4036); +INSERT INTO scripted_areatrigger (`entry`, `ScriptName`) VALUES ('4033', 'at_temple_ahnqiraj'); +INSERT INTO scripted_areatrigger (`entry`, `ScriptName`) VALUES ('4034', 'at_temple_ahnqiraj'); +INSERT INTO scripted_areatrigger (`entry`, `ScriptName`) VALUES ('4036', 'at_temple_ahnqiraj'); + +-- flags update on trigger unit used to knock players out of cthuns body after being ported. Flags copied from viscidus trigger. +-- UPDATE `creature_template` SET `unit_flags`='33587968', `ScriptName`='boss cthun knockback trigger' WHERE `entry`='15800'; + + +-- to remove c'thuns eye +DELETE FROM `creature` WHERE `guid`='87560'; + +-- to re-add c'thuns eye +-- INSERT INTO `creature` (`guid`, `id`, `map`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `curhealth`, `curmana`, `DeathState`, `MovementType`, `spawnFlags`) +-- VALUES ('87560', '15589 ', '531', '15556', '0', '-8577.27', '1986.94', '100.4', '3.44', '6380', '0', '0', '1269434', '0', '0', '0'); + + +-- Remove CREATURE_FLAG_EXTRA_AGGRO_ZONE from C'thun as we want to manually handle his combat with zone. +UPDATE creature_template SET flags_extra = flags_extra & ~512 WHERE entry = 15727; + +-- Taunt-immunity for both c'thuns body and the eye. Fixes eye being able to turn during dark glare +UPDATE creature_template SET flags_extra = flags_extra | 256 where entry in (15589, 15727); + +-- Fix mechanic immunities for adds +UPDATE creature_template SET MechanicImmuneMask = MechanicImmuneMask | (2 | 16 | 4096 | 512) WHERE entry IN (15728, 15334, 15725, 15726, 15802); + +# Chests.sql + +-- key requirement added to Large scarab coffer +UPDATE `gameobject_template` SET `flags`='2' WHERE `entry`='180690'; + +-- large scarab coffer drop 1-3 idols, all 25% chance to drop from what I can find (some sources give varying droprates, but i cant see why that would be the case) +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20874'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20875'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20876'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20877'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20878'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20879'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20881'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='25', `maxcount`='3' WHERE `entry`='17533' and`item`='20882'; + +-- large scarab coffer can drop 1-3 bags, and always drop one +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='100', `maxcount`='3' WHERE `entry`='17533' and`item`='21156'; + +-- regular scarab coffer bag droprate set to 85% +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='85' WHERE `entry`='17532' and`item`='21156'; + +-- regular scarab coffer fixed droprate of 14% for 1-2 idols +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20866'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20867'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20868'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20869'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20870'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20871'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20872'; +UPDATE `gameobject_loot_template` SET `ChanceOrQuestChance`='14' WHERE `entry`='17532' and`item`='20873'; diff --git a/src/game/AI/CreatureAI.h b/src/game/AI/CreatureAI.h index a3c52c620..90d3b1aec 100644 --- a/src/game/AI/CreatureAI.h +++ b/src/game/AI/CreatureAI.h @@ -97,7 +97,7 @@ class MANGOS_DLL_SPEC CreatureAI virtual void JustReachedHome() {} // Called at any heal cast/item used (call non implemented) - virtual void HealBy(Unit * /*healer*/, uint32 /*amount_healed*/) {} + virtual void HealedBy(Unit * /*healer*/, uint32 /*amount_healed*/) {} // Helper functions for cast spell virtual CanCastResult CanCastSpell(Unit* pTarget, const SpellEntry *pSpell, bool isTriggered); diff --git a/src/game/AI/CreatureEventAIMgr.cpp b/src/game/AI/CreatureEventAIMgr.cpp index d55329f5c..99096967a 100644 --- a/src/game/AI/CreatureEventAIMgr.cpp +++ b/src/game/AI/CreatureEventAIMgr.cpp @@ -39,7 +39,7 @@ void CreatureEventAIMgr::LoadCreatureEventAI_Texts(bool check_entry_use) m_CreatureEventAI_TextMap.clear(); // Load EventAI Text - sObjectMgr.LoadMangosStrings(WorldDatabase, "creature_ai_texts", MIN_CREATURE_AI_TEXT_STRING_ID, MAX_CREATURE_AI_TEXT_STRING_ID); + sObjectMgr.LoadMangosStrings(WorldDatabase, "creature_ai_texts", MIN_CREATURE_AI_TEXT_STRING_ID, MAX_CREATURE_AI_TEXT_STRING_ID, false); // Gather Additional data from EventAI Texts QueryResult *result = WorldDatabase.Query("SELECT entry, sound, type, language, emote FROM creature_ai_texts"); diff --git a/src/game/AI/ScriptedAI.cpp b/src/game/AI/ScriptedAI.cpp index 7fa0b8bd3..3655fd3b3 100644 --- a/src/game/AI/ScriptedAI.cpp +++ b/src/game/AI/ScriptedAI.cpp @@ -381,9 +381,7 @@ void ScriptedAI::SetCombatMovement(bool bCombatMove) enum { NPC_BROODLORD = 12017, - NPC_VOID_REAVER = 19516, - NPC_JAN_ALAI = 23578, - NPC_SARTHARION = 28860 + NPC_VISCIDUS = 15299 }; bool ScriptedAI::EnterEvadeIfOutOfCombatArea(const uint32 uiDiff) @@ -409,16 +407,8 @@ bool ScriptedAI::EnterEvadeIfOutOfCombatArea(const uint32 uiDiff) if (fZ > 448.60f) return false; break; - case NPC_VOID_REAVER: // void reaver (calculate from center of room) - if (m_creature->GetDistance2d(432.59f, 371.93f) < 105.0f) - return false; - break; - case NPC_JAN_ALAI: // jan'alai (calculate by Z) - if (fZ > 12.0f) - return false; - break; - case NPC_SARTHARION: // sartharion (calculate box) - if (fX > 3218.86f && fX < 3275.69f && fY < 572.40f && fY > 484.68f) + case NPC_VISCIDUS: + if (fZ < -30.0f) return false; break; default: diff --git a/src/game/AI/ScriptedAI.h b/src/game/AI/ScriptedAI.h index 325385610..9476a4938 100644 --- a/src/game/AI/ScriptedAI.h +++ b/src/game/AI/ScriptedAI.h @@ -46,7 +46,7 @@ struct MANGOS_DLL_DECL ScriptedAI : CreatureAI void EnterEvadeMode() override; //Called at any heal cast/item used (call non implemented in mangos) - void HealBy(Unit* /*pHealer*/, uint32 /*uiAmountHealed*/) override {} + void HealedBy(Unit* /*pHealer*/, uint32 /*uiAmountHealed*/) override {} // Called at any Damage to any victim (before damage apply) void DamageDeal(Unit* /*pDoneTo*/, uint32& /*uiDamage*/) override {} diff --git a/src/game/AI/ScriptedInstance.cpp b/src/game/AI/ScriptedInstance.cpp index 1f7243da0..235446f82 100644 --- a/src/game/AI/ScriptedInstance.cpp +++ b/src/game/AI/ScriptedInstance.cpp @@ -123,6 +123,22 @@ void ScriptedInstance::LoadSaveData(const char* pStr, uint32* encounters, uint32 } } + +/// Get the first found Player* (with requested properties) in the map. Can return nullptr. +Player* ScriptedInstance::GetPlayerInMap(bool bOnlyAlive /*=false*/, bool bCanBeGamemaster /*=true*/) +{ + Map::PlayerList const& lPlayers = instance->GetPlayers(); + + for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) + { + Player* pPlayer = itr->getSource(); + if (pPlayer && (!bOnlyAlive || pPlayer->isAlive()) && (bCanBeGamemaster || !pPlayer->isGameMaster())) + return pPlayer; + } + + return nullptr; +} + /// Returns a pointer to a loaded GameObject that was stored in m_mGoEntryGuidStore. Can return NULL GameObject* ScriptedInstance::GetSingleGameObjectFromStorage(uint32 uiEntry) { @@ -182,3 +198,144 @@ void ScriptedInstance_PTR::Update(uint32 diff) } ScriptedInstance::Update(diff); } + +/** + Constructor for DialogueHelper + @param pDialogueArray The static const array of DialogueEntry holding the information about the dialogue. This array MUST be terminated by {0,0,0} +*/ +DialogueHelper::DialogueHelper(SIDialogueEntry const* pDialogueArray) : + m_pInstance(nullptr), + m_pDialogueArray(pDialogueArray), + m_pCurrentEntry(nullptr), + m_pDialogueTwoSideArray(nullptr), + m_pCurrentEntryTwoSide(nullptr), + m_uiTimer(0), + m_bIsFirstSide(true), + m_bCanSimulate(false) +{} + +/** + Constructor for DialogueHelper (Two Sides) + @param pDialogueTwoSideArray The static const array of DialogueEntryTwoSide holding the information about the dialogue. This array MUST be terminated by {0,0,0,0,0} +*/ +DialogueHelper::DialogueHelper(SIDialogueEntryTwoSide const* pDialogueTwoSideArray) : + m_pInstance(nullptr), + m_pDialogueArray(nullptr), + m_pCurrentEntry(nullptr), + m_pDialogueTwoSideArray(pDialogueTwoSideArray), + m_pCurrentEntryTwoSide(nullptr), + m_uiTimer(0), + m_bIsFirstSide(true), + m_bCanSimulate(false) +{} + +/** + Function to start a (part of a) dialogue + @param iTextEntry The TextEntry of the dialogue that will be started (must be always the entry of first side) +*/ +void DialogueHelper::StartNextDialogueText(int32 iTextEntry) +{ + // Find iTextEntry + bool bFound = false; + + if (m_pDialogueArray) // One Side + { + for (SIDialogueEntry const* pEntry = m_pDialogueArray; pEntry->iTextEntry; ++pEntry) + { + if (pEntry->iTextEntry == iTextEntry) + { + m_pCurrentEntry = pEntry; + bFound = true; + break; + } + } + } + else // Two Sides + { + for (SIDialogueEntryTwoSide const* pEntry = m_pDialogueTwoSideArray; pEntry->iTextEntry; ++pEntry) + { + if (pEntry->iTextEntry == iTextEntry) + { + m_pCurrentEntryTwoSide = pEntry; + bFound = true; + break; + } + } + } + + if (!bFound) + { + sLog.outError("Script call DialogueHelper::StartNextDialogueText, but textEntry %i is not in provided dialogue (on map id %u)", iTextEntry, m_pInstance ? m_pInstance->instance->GetId() : 0); + return; + } + + DoNextDialogueStep(); +} + +/// Internal helper function to do the actual say of a DialogueEntry +void DialogueHelper::DoNextDialogueStep() +{ + // Last Dialogue Entry done? + if ((m_pCurrentEntry && !m_pCurrentEntry->iTextEntry) || (m_pCurrentEntryTwoSide && !m_pCurrentEntryTwoSide->iTextEntry)) + { + m_uiTimer = 0; + return; + } + + // Get Text, SpeakerEntry and Timer + int32 iTextEntry = 0; + uint32 uiSpeakerEntry = 0; + + if (m_pDialogueArray) // One Side + { + uiSpeakerEntry = m_pCurrentEntry->uiSayerEntry; + iTextEntry = m_pCurrentEntry->iTextEntry; + + m_uiTimer = m_pCurrentEntry->uiTimer; + } + else // Two Sides + { + // Second Entries can be 0, if they are the entry from first side will be taken + uiSpeakerEntry = !m_bIsFirstSide && m_pCurrentEntryTwoSide->uiSayerEntryAlt ? m_pCurrentEntryTwoSide->uiSayerEntryAlt : m_pCurrentEntryTwoSide->uiSayerEntry; + iTextEntry = !m_bIsFirstSide && m_pCurrentEntryTwoSide->iTextEntryAlt ? m_pCurrentEntryTwoSide->iTextEntryAlt : m_pCurrentEntryTwoSide->iTextEntry; + + m_uiTimer = m_pCurrentEntryTwoSide->uiTimer; + } + + // Simulate Case + if (uiSpeakerEntry && iTextEntry < 0) + { + // Use Speaker if directly provided + Creature* pSpeaker = GetSpeakerByEntry(uiSpeakerEntry); + if (m_pInstance && !pSpeaker) // Get Speaker from instance + { + if (m_bCanSimulate) // Simulate case + m_pInstance->DoOrSimulateScriptTextForThisInstance(iTextEntry, uiSpeakerEntry); + else + pSpeaker = m_pInstance->GetSingleCreatureFromStorage(uiSpeakerEntry); + } + + if (pSpeaker) + DoScriptText(iTextEntry, pSpeaker); + } + + JustDidDialogueStep(m_pDialogueArray ? m_pCurrentEntry->iTextEntry : m_pCurrentEntryTwoSide->iTextEntry); + + // Increment position + if (m_pDialogueArray) + ++m_pCurrentEntry; + else + ++m_pCurrentEntryTwoSide; +} + +/// Call this function within any DialogueUpdate method. This is required for saying next steps in a dialogue +void DialogueHelper::DialogueUpdate(uint32 uiDiff) +{ + if (m_uiTimer) + { + if (m_uiTimer <= uiDiff) + DoNextDialogueStep(); + else + m_uiTimer -= uiDiff; + } +} diff --git a/src/game/AI/ScriptedInstance.h b/src/game/AI/ScriptedInstance.h index 65a55aa69..fe030079c 100644 --- a/src/game/AI/ScriptedInstance.h +++ b/src/game/AI/ScriptedInstance.h @@ -49,6 +49,15 @@ class MANGOS_DLL_DECL ScriptedInstance : public InstanceData std::string GenSaveData(uint32* encounters, uint32 maxIndex); void LoadSaveData(const char* pStr, uint32* encounters, uint32 maxIndex); + // Get a Player from map + Player* GetPlayerInMap(bool bOnlyAlive = false, bool bCanBeGamemaster = true); + + /// Wrapper for simulating map-wide text in this instance. It is expected that the Creature is stored in m_mNpcEntryGuidStore if loaded. + void DoOrSimulateScriptTextForThisInstance(int32 iTextEntry, uint32 uiCreatureEntry) + { + // Prevent debug output in GetSingleCreatureFromStorage + DoOrSimulateScriptTextForMap(iTextEntry, uiCreatureEntry, instance, GetSingleCreatureFromStorage(uiCreatureEntry, true)); + } protected: // Storage for GO-Guids and NPC-Guids typedef std::map EntryGuidMap; @@ -66,4 +75,63 @@ protected: std::map boss_expirations; // For PTR testes }; + +/// A static const array of this structure must be handled to DialogueHelper +struct SIDialogueEntry +{ + int32 iTextEntry; ///< To be said text entry + uint32 uiSayerEntry; ///< Entry of the mob who should say + uint32 uiTimer; ///< Time delay until next text of array is said (0 stops) +}; + +/// A static const array of this structure must be handled to DialogueHelper +struct SIDialogueEntryTwoSide +{ + int32 iTextEntry; ///< To be said text entry (first side) + uint32 uiSayerEntry; ///< Entry of the mob who should say (first side) + int32 iTextEntryAlt; ///< To be said text entry (second side) + uint32 uiSayerEntryAlt; ///< Entry of the mob who should say (second side) + uint32 uiTimer; ///< Time delay until next text of array is said (0 stops) +}; + +/// Helper class handling a dialogue given as static const array of DialogueEntry or DialogueEntryTwoSide +class DialogueHelper +{ +public: + // The array MUST be terminated by {0,0,0} + DialogueHelper(SIDialogueEntry const* pDialogueArray); + // The array MUST be terminated by {0,0,0,0,0} + DialogueHelper(SIDialogueEntryTwoSide const* aDialogueTwoSide); + + /// Function to initialize the dialogue helper for instances. If not used with instances, GetSpeakerByEntry MUST be overwritten to obtain the speakers + void InitializeDialogueHelper(ScriptedInstance* pInstance, bool bCanSimulateText = false) { m_pInstance = pInstance; m_bCanSimulate = bCanSimulateText; } + /// Set if take first entries or second entries + void SetDialogueSide(bool bIsFirstSide) { m_bIsFirstSide = bIsFirstSide; } + + void StartNextDialogueText(int32 iTextEntry); + + void DialogueUpdate(uint32 uiDiff); + +protected: + /// Will be called when a dialogue step was done + virtual void JustDidDialogueStep(int32 /*iEntry*/) {} + /// Will be called to get a speaker, MUST be implemented if not used in instances + virtual Creature* GetSpeakerByEntry(uint32 /*uiEntry*/) { return nullptr; } + + ScriptedInstance* m_pInstance; + +private: + void DoNextDialogueStep(); + + + SIDialogueEntry const* m_pDialogueArray; + SIDialogueEntry const* m_pCurrentEntry; + SIDialogueEntryTwoSide const* m_pDialogueTwoSideArray; + SIDialogueEntryTwoSide const* m_pCurrentEntryTwoSide; + + uint32 m_uiTimer; + bool m_bIsFirstSide; + bool m_bCanSimulate; +}; + #endif diff --git a/src/game/Chat/Chat.cpp b/src/game/Chat/Chat.cpp index 430873f68..ac27f3fed 100644 --- a/src/game/Chat/Chat.cpp +++ b/src/game/Chat/Chat.cpp @@ -1,3819 +1,3821 @@ -/* - * Copyright (C) 2005-2011 MaNGOS - * Copyright (C) 2009-2011 MaNGOSZero - * Copyright (C) 2011-2016 Nostalrius - * Copyright (C) 2016-2017 Elysium Project - * - * 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 - */ - -#include "Chat.h" -#include "Language.h" -#include "Database/DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Opcodes.h" -#include "Log.h" -#include "World.h" -#include "ObjectMgr.h" -#include "ObjectGuid.h" -#include "Player.h" -#include "UpdateMask.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" -#include "AccountMgr.h" -#include "SpellMgr.h" -#include "PoolManager.h" -#include "GameEventMgr.h" - -// Supported shift-links (client generated and server side) -// |color|Harea:area_id|h[name]|h|r -// |color|Hareatrigger:id|h[name]|h|r -// |color|Hareatrigger_target:id|h[name]|h|r -// |color|Hcreature:creature_guid|h[name]|h|r -// |color|Hcreature_entry:creature_id|h[name]|h|r -// |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r - client, at shift click in recipes list dialog -// |color|Hgameevent:id|h[name]|h|r -// |color|Hgameobject:go_guid|h[name]|h|r -// |color|Hgameobject_entry:go_id|h[name]|h|r -// |color|Hitem:item_id:perm_ench_id:gem1:gem2:gem3:0:0:0:0|h[name]|h|r - client, item icon shift click -// |color|Hitemset:itemset_id|h[name]|h|r -// |color|Hplayer:name|h[name]|h|r - client, in some messages, at click copy only name instead link, so no way generate it in client string send to server -// |color|Hpool:pool_id|h[name]|h|r -// |color|Hquest:quest_id:quest_level|h[name]|h|r - client, quest list name shift-click -// |color|Hskill:skill_id|h[name]|h|r -// |color|Hspell:spell_id|h[name]|h|r - client, spellbook spell icon shift-click -// |color|Htalent:talent_id,rank|h[name]|h|r - client, talent icon shift-click rank==-1 if shift-copy unlearned talent -// |color|Htaxinode:id|h[name]|h|r -// |color|Htele:id|h[name]|h|r - -bool ChatHandler::load_command_table = true; - -ChatCommand * ChatHandler::getCommandTable() -{ - static ChatCommand groupSpellCommandTable[] = - { - { NODE, "add", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGroupAddSpellCommand, "", nullptr}, - { NODE, "rule", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGroupSetRuleCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - static ChatCommand ahbotCommandTable[] = - { - { MSTR, "reload", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAHBotReloadCommand, "Recharger le bot de l'HdV", nullptr}, - { MSTR, "update", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAHBotUpdateCommand, "Ajouter des items en vente", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - static ChatCommand botCommandTable[] = - { - { NODE, "add", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotAddCommand, "", nullptr }, - { NODE, "add_all", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotAddAllCommand, "", nullptr }, - { NODE, "delete", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotDeleteCommand, "", nullptr }, - { NODE, "info", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotInfoCommand, "", nullptr }, - { NODE, "reload", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotReloadCommand, "", nullptr }, - { NODE, "stop", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotStopCommand, "", nullptr }, - { NODE, "start", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotStartCommand, "", nullptr }, - { NODE, "ranadd", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotAddRandomCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr }, - }; - static ChatCommand accountSetCommandTable[] = - { - { NODE, "addon", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAccountSetAddonCommand, "", nullptr }, - { NODE, "gmlevel", SEC_CONSOLE, true, &ChatHandler::HandleAccountSetGmLevelCommand, "", nullptr }, - { NODE, "password", SEC_CONSOLE, true, &ChatHandler::HandleAccountSetPasswordCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand accountCommandTable[] = - { - { NODE, "characters", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAccountCharactersCommand, "", nullptr }, - { NODE, "create", SEC_CONSOLE, true, &ChatHandler::HandleAccountCreateCommand, "", nullptr }, - { NODE, "delete", SEC_CONSOLE, true, &ChatHandler::HandleAccountDeleteCommand, "", nullptr }, - { NODE, "onlinelist", SEC_CONSOLE, true, &ChatHandler::HandleAccountOnlineListCommand, "", nullptr }, - { NODE, "lock", SEC_PLAYER, true, &ChatHandler::HandleAccountLockCommand, "", nullptr }, - { NODE, "set", SEC_ADMINISTRATOR, true, nullptr, "", accountSetCommandTable }, - { NODE, "password", SEC_PLAYER, true, &ChatHandler::HandleAccountPasswordCommand, "", nullptr }, - { NODE, "", SEC_PLAYER, true, &ChatHandler::HandleAccountCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand auctionCommandTable[] = - { - { NODE, "alliance", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionAllianceCommand, "", nullptr }, - { NODE, "goblin", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionGoblinCommand, "", nullptr }, - { NODE, "horde", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionHordeCommand, "", nullptr }, - { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand banCommandTable[] = - { - { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanAccountCommand, "", nullptr }, - { NODE, "allip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanAllIPCommand, "", nullptr }, - { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanCharacterCommand, "", nullptr }, - { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanIPCommand, "", nullptr }, - { NODE, "note", SEC_GAMEMASTER, true, &ChatHandler::HandleAddCharacterNoteCommand, "", nullptr }, - { NODE, "warn", SEC_GAMEMASTER, true, &ChatHandler::HandleWarnCharacterCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand baninfoCommandTable[] = - { - { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanInfoAccountCommand, "", nullptr }, - { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanInfoCharacterCommand, "", nullptr }, - { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanInfoIPCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand banlistCommandTable[] = - { - { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanListAccountCommand, "", nullptr }, - { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanListCharacterCommand, "", nullptr }, - { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanListIPCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand castCommandTable[] = - { - { NODE, "back", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastBackCommand, "", nullptr }, - { NODE, "dist", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastDistCommand, "", nullptr }, - { NODE, "self", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastSelfCommand, "", nullptr }, - { NODE, "target", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastTargetCommand, "", nullptr }, - { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand characterDeletedCommandTable[] = - { - { NODE, "delete", SEC_CONSOLE, true, &ChatHandler::HandleCharacterDeletedDeleteCommand, "", nullptr }, - { NODE, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCharacterDeletedListCommand, "", nullptr }, - { NODE, "restore", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCharacterDeletedRestoreCommand, "", nullptr }, - { NODE, "old", SEC_CONSOLE, true, &ChatHandler::HandleCharacterDeletedOldCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand characterCleanCommandTable[] = - { - { NODE, "todelete", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCleanCharactersToDeleteCommand, "", nullptr }, - { NODE, "items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCleanCharactersItemsCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand characterCommandTable[] = - { - { NODE, "deleted", SEC_GAMEMASTER, true, nullptr, "", characterDeletedCommandTable}, - { NODE, "erase", SEC_CONSOLE, true, &ChatHandler::HandleCharacterEraseCommand, "", nullptr }, - { NODE, "level", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCharacterLevelCommand, "", nullptr }, - { NODE, "rename", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterRenameCommand, "", nullptr }, - { NODE, "reputation", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterReputationCommand, "", nullptr }, - { NODE, "hasitem", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterHasItemCommand, "", nullptr }, - { NODE, "race", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterChangeRaceCommand, "", nullptr }, - { NODE, "skin", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterCopySkinCommand, "", nullptr }, - { NODE, "fillflys", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterFillFlysCommand, "", nullptr }, - { NODE, "flags", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterFlagsCommand, "", nullptr }, - { NODE, "recup", SEC_ADMINISTRATOR, false, &ChatHandler::HandleRecupCommand, "", nullptr }, - { NODE, "clean", SEC_ADMINISTRATOR, true, nullptr, "", characterCleanCommandTable }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand debugPlayCommandTable[] = - { - { NODE, "cinematic", SEC_MODERATOR, false, &ChatHandler::HandleDebugPlayCinematicCommand, "", nullptr }, - { NODE, "sound", SEC_MODERATOR, false, &ChatHandler::HandleDebugPlaySoundCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand debugLosCommandTable[] = - { - { NODE, "check", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugLoSCommand, "", nullptr }, - { NODE, "allow", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugLoSAllowCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand debugSendCommandTable[] = - { - { NODE, "buyerror", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendBuyErrorCommand, "", nullptr }, - { NODE, "channelnotify", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendChannelNotifyCommand, "", nullptr }, - { NODE, "chatmmessage", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendChatMsgCommand, "", nullptr }, - { NODE, "equiperror", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendEquipErrorCommand, "", nullptr }, - { NODE, "opcode", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendOpcodeCommand, "", nullptr }, - { NODE, "poi", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendPoiCommand, "", nullptr }, - { NODE, "qpartymsg", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendQuestPartyMsgCommand, "", nullptr }, - { NODE, "qinvalidmsg", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendQuestInvalidMsgCommand, "", nullptr }, - { NODE, "sellerror", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendSellErrorCommand, "", nullptr }, - { NODE, "spellfail", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendSpellFailCommand, "", nullptr }, - { NODE, "visual", SEC_GAMEMASTER, true, &ChatHandler::HandleSendSpellVisualCommand, "", nullptr }, - { NODE, "impact", SEC_GAMEMASTER, true, &ChatHandler::HandleSendSpellImpactCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand debugCommandTable[] = - { - { NODE, "anim", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugAnimCommand, "", nullptr }, - { NODE, "bg", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugBattlegroundCommand, "", nullptr }, - { NODE, "getitemstate", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugGetItemStateCommand, "", nullptr }, - { NODE, "lrecipient", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugGetLootRecipientCommand, "", nullptr }, - { NODE, "getitemvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugGetItemValueCommand, "", nullptr }, - { NODE, "getvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugGetValueCommand, "", nullptr }, - { NODE, "moditemvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugModItemValueCommand, "", nullptr }, - { NODE, "modvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugModValueCommand, "", nullptr }, - { NODE, "play", SEC_MODERATOR, false, nullptr, "", debugPlayCommandTable }, - { NODE, "send", SEC_ADMINISTRATOR, false, nullptr, "", debugSendCommandTable }, - { NODE, "setaurastate", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSetAuraStateCommand, "", nullptr }, - { NODE, "setitemvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSetItemValueCommand, "", nullptr }, - { NODE, "setvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSetValueCommand, "", nullptr }, - { NODE, "spellcheck", SEC_CONSOLE, true, &ChatHandler::HandleDebugSpellCheckCommand, "", nullptr }, - { NODE, "spellcoefs", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugSpellCoefsCommand, "", nullptr }, - { NODE, "spellmods", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSpellModsCommand, "", nullptr }, - { NODE, "uws", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugUpdateWorldStateCommand, "", nullptr }, - // Nostalrius - { NODE, "update", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugUpdateCommand, "", nullptr }, - { NODE, "forceupdate", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugForceUpdateCommand, "", nullptr }, - { NODE, "los", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugLoSCommand, "", debugLosCommandTable }, - { NODE, "moveto", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMoveToCommand, "", nullptr }, - { NODE, "assert", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugAssertFalseCommand, "", nullptr }, - { NODE, "pvpcredit", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugPvPCreditCommand, "", nullptr }, - { NODE, "unitstate", SEC_GAMEMASTER, false, &ChatHandler::HandleUnitStatCommand, "", nullptr }, - { NODE, "control", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugControlCommand, "", nullptr }, - { NODE, "monster", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMonsterChatCommand, "", nullptr }, - { NODE, "target", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugUnitCommand, "", nullptr }, - { NODE, "time", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugTimeCommand, "", nullptr }, - { NODE, "moveflags", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMoveFlagsCommand, "", nullptr }, - { NODE, "movespline", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMoveSplineCommand, "", nullptr }, - { NODE, "dump", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugRecvPacketDumpWrite, "", nullptr }, - { NODE, "movemotion", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugMoveCommand, "", nullptr }, - { NODE, "factionchange_items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleFactionChangeItemsCommand, "", nullptr }, - { NODE, "loottable", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugLootTableCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand eventCommandTable[] = - { - { NODE, "list", SEC_GAMEMASTER, true, &ChatHandler::HandleEventListCommand, "", nullptr }, - { NODE, "start", SEC_GAMEMASTER, true, &ChatHandler::HandleEventStartCommand, "", nullptr }, - { NODE, "stop", SEC_GAMEMASTER, true, &ChatHandler::HandleEventStopCommand, "", nullptr }, - { NODE, "enable", SEC_ADMINISTRATOR, true, &ChatHandler::HandleEventEnableCommand, "", nullptr }, - { NODE, "disable", SEC_ADMINISTRATOR, true, &ChatHandler::HandleEventDisableCommand, "", nullptr }, - { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleEventInfoCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand gmCommandTable[] = - { - { NODE, "chat", SEC_MODERATOR, false, &ChatHandler::HandleGMChatCommand, "", nullptr }, - { NODE, "fly", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGMFlyCommand, "", nullptr }, - { NODE, "ingame", SEC_PLAYER, true, &ChatHandler::HandleGMListIngameCommand, "", nullptr }, - { NODE, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGMListFullCommand, "", nullptr }, - { NODE, "visible", SEC_MODERATOR, false, &ChatHandler::HandleGMVisibleCommand, "", nullptr }, - { NODE, "options", SEC_GAMEMASTER, false, &ChatHandler::HandleGMOptionsCommand, "", nullptr }, - { NODE, "setview", SEC_MODERATOR, false, &ChatHandler::HandleSetViewCommand, "", nullptr }, - { NODE, "", SEC_MODERATOR, false, &ChatHandler::HandleGMCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand goCommandTable[] = - { - { NODE, "creature", SEC_MODERATOR, false, &ChatHandler::HandleGoCreatureCommand, "", nullptr }, - { NODE, "graveyard", SEC_MODERATOR, false, &ChatHandler::HandleGoGraveyardCommand, "", nullptr }, - { NODE, "grid", SEC_MODERATOR, false, &ChatHandler::HandleGoGridCommand, "", nullptr }, - { NODE, "object", SEC_MODERATOR, false, &ChatHandler::HandleGoObjectCommand, "", nullptr }, - { NODE, "taxinode", SEC_MODERATOR, false, &ChatHandler::HandleGoTaxinodeCommand, "", nullptr }, - { NODE, "trigger", SEC_MODERATOR, false, &ChatHandler::HandleGoTriggerCommand, "", nullptr }, - { NODE, "zonexy", SEC_MODERATOR, false, &ChatHandler::HandleGoZoneXYCommand, "", nullptr }, - { NODE, "xy", SEC_MODERATOR, false, &ChatHandler::HandleGoXYCommand, "", nullptr }, - { NODE, "xyz", SEC_MODERATOR, false, &ChatHandler::HandleGoXYZCommand, "", nullptr }, - { NODE, "xyzo", SEC_MODERATOR, false, &ChatHandler::HandleGoXYZOCommand, "", nullptr }, - // Nostalrius - { NODE, "forward", SEC_GAMEMASTER, false, &ChatHandler::HandleGoForwardCommand, "", nullptr }, - { NODE, "up", SEC_GAMEMASTER, false, &ChatHandler::HandleGoUpCommand, "", nullptr }, - { NODE, "relative", SEC_GAMEMASTER, false, &ChatHandler::HandleGoRelativeCommand, "", nullptr }, - // Battleground join - { NODE, "warsong", SEC_PLAYER, false, &ChatHandler::HandleGoWarsongCommand, "", nullptr }, - { NODE, "arathi", SEC_PLAYER, false, &ChatHandler::HandleGoArathiCommand, "", nullptr }, - { NODE, "alterac", SEC_PLAYER, false, &ChatHandler::HandleGoAlteracCommand, "", nullptr }, - { NODE, "", SEC_MODERATOR, false, &ChatHandler::HandleGoCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand gobjectCommandTable[] = - { - { NODE, "add", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectAddCommand, "", nullptr }, - { NODE, "tmpadd", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectTempAddCommand, "", nullptr }, - { NODE, "delete", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectDeleteCommand, "", nullptr }, - { NODE, "move", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectMoveCommand, "", nullptr }, - { NODE, "near", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectNearCommand, "", nullptr }, - { NODE, "target", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectTargetCommand, "", nullptr }, - { NODE, "turn", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectTurnCommand, "", nullptr }, - { NODE, "select", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectSelectCommand, "", nullptr }, - { NODE, "despawn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectDespawnCommand, "", nullptr }, - { NODE, "toggle", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectToggleCommand, "", nullptr }, - { NODE, "reset", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectResetCommand, "", nullptr }, - { NODE, "respawn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectRespawnCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand guildCommandTable[] = - { - { NODE, "create", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildCreateCommand, "", nullptr }, - { NODE, "delete", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildDeleteCommand, "", nullptr }, - { NODE, "invite", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildInviteCommand, "", nullptr }, - { NODE, "uninvite", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildUninviteCommand, "", nullptr }, - { NODE, "rank", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildRankCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand honorCommandTable[] = - { - { NODE, "add", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHonorAddCommand, "", nullptr }, - { NODE, "addkill", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHonorAddKillCommand, "", nullptr }, - { NODE, "show", SEC_GAMEMASTER, false, &ChatHandler::HandleHonorShow, "", nullptr }, - { NODE, "debug", SEC_ADMINISTRATOR, true, &ChatHandler::HandleHonorDebugScoresCommand, "", nullptr }, - { NODE, "setrp", SEC_ADMINISTRATOR, true, &ChatHandler::HandleHonorSetRPCommand, "", nullptr }, - { NODE, "reset", SEC_ADMINISTRATOR, true, &ChatHandler::HandleHonorResetCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand instanceCommandTable[] = - { - { NODE, "continents", SEC_ADMINISTRATOR, true, &ChatHandler::HandleInstanceContinentsCommand, "", nullptr }, - { NODE, "listbinds", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceListBindsCommand, "", nullptr }, - { NODE, "unbind", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceUnbindCommand, "", nullptr }, - { NODE, "stats", SEC_ADMINISTRATOR, true, &ChatHandler::HandleInstanceStatsCommand, "", nullptr }, - { NODE, "savedata", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceSaveDataCommand, "", nullptr }, - { NODE, "switch", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceSwitchCommand, "", nullptr }, - { NODE, "perfinfos", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstancePerfInfosCommand, "", nullptr }, - { NODE, "smartrebind", SEC_MODERATOR, false, &ChatHandler::HandleInstanceBindingMode, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand learnCommandTable[] = - { - { NODE, "all", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllCommand, "", nullptr }, - { NODE, "all_gm", SEC_GAMEMASTER, false, &ChatHandler::HandleLearnAllGMCommand, "", nullptr }, - { NODE, "all_crafts", SEC_GAMEMASTER, false, &ChatHandler::HandleLearnAllCraftsCommand, "", nullptr }, - { NODE, "all_default", SEC_MODERATOR, false, &ChatHandler::HandleLearnAllDefaultCommand, "", nullptr }, - { NODE, "all_lang", SEC_MODERATOR, false, &ChatHandler::HandleLearnAllLangCommand, "", nullptr }, - { NODE, "all_myclass", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllMyClassCommand, "", nullptr }, - { NODE, "all_myspells", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllMySpellsCommand, "", nullptr }, - { NODE, "all_mytalents", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllMyTalentsCommand, "", nullptr }, - { NODE, "all_recipes", SEC_GAMEMASTER, false, &ChatHandler::HandleLearnAllRecipesCommand, "", nullptr }, - { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand listCommandTable[] = - { - { NODE, "auras", SEC_ADMINISTRATOR, false, &ChatHandler::HandleListAurasCommand, "", nullptr }, - { NODE, "creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleListCreatureCommand, "", nullptr }, - { NODE, "item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleListItemCommand, "", nullptr }, - { NODE, "object", SEC_ADMINISTRATOR, true, &ChatHandler::HandleListObjectCommand, "", nullptr }, - { NODE, "talents", SEC_ADMINISTRATOR, false, &ChatHandler::HandleListTalentsCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand lookupAccountCommandTable[] = - { - { NODE, "email", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountEmailCommand, "", nullptr }, - { NODE, "ip", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountIpCommand, "", nullptr }, - { NODE, "iponline", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountIponlineCommand, "", nullptr }, - { NODE, "name", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountNameCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand lookupPlayerCommandTable[] = - { - { NODE, "account", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerAccountCommand, "", nullptr }, - { NODE, "email", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerEmailCommand, "", nullptr }, - { NODE, "ip", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerIpCommand, "", nullptr }, - { NODE, "name", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerNameCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand lookupCommandTable[] = - { - { NODE, "account", SEC_GAMEMASTER, true, nullptr, "", lookupAccountCommandTable }, - { NODE, "area", SEC_MODERATOR, true, &ChatHandler::HandleLookupAreaCommand, "", nullptr }, - { NODE, "creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupCreatureCommand, "", nullptr }, - { NODE, "event", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupEventCommand, "", nullptr }, - { NODE, "faction", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupFactionCommand, "", nullptr }, - { NODE, "item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupItemCommand, "", nullptr }, - { NODE, "itemset", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupItemSetCommand, "", nullptr }, - { NODE, "object", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupObjectCommand, "", nullptr }, - { NODE, "quest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupQuestCommand, "", nullptr }, - { NODE, "player", SEC_GAMEMASTER, true, nullptr, "", lookupPlayerCommandTable }, - { NODE, "pool", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPoolCommand, "", nullptr }, - { NODE, "skill", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupSkillCommand, "", nullptr }, - { NODE, "spell", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupSpellCommand, "", nullptr }, - { NODE, "taxinode", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupTaxiNodeCommand, "", nullptr }, - { NODE, "tele", SEC_MODERATOR, true, &ChatHandler::HandleLookupTeleCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand modifyCommandTable[] = - { - { NODE, "hp", SEC_MODERATOR, false, &ChatHandler::HandleModifyHPCommand, "", nullptr }, - { NODE, "mana", SEC_MODERATOR, false, &ChatHandler::HandleModifyManaCommand, "", nullptr }, - { NODE, "rage", SEC_MODERATOR, false, &ChatHandler::HandleModifyRageCommand, "", nullptr }, - { NODE, "energy", SEC_MODERATOR, false, &ChatHandler::HandleModifyEnergyCommand, "", nullptr }, - { NODE, "money", SEC_MODERATOR, false, &ChatHandler::HandleModifyMoneyCommand, "", nullptr }, - { NODE, "speed", SEC_MODERATOR, false, &ChatHandler::HandleModifySpeedCommand, "", nullptr }, - { NODE, "swim", SEC_MODERATOR, false, &ChatHandler::HandleModifySwimCommand, "", nullptr }, - { NODE, "scale", SEC_MODERATOR, false, &ChatHandler::HandleModifyScaleCommand, "", nullptr }, - { NODE, "bwalk", SEC_MODERATOR, false, &ChatHandler::HandleModifyBWalkCommand, "", nullptr }, - { NODE, "aspeed", SEC_MODERATOR, false, &ChatHandler::HandleModifyASpeedCommand, "", nullptr }, - { NODE, "faction", SEC_MODERATOR, false, &ChatHandler::HandleModifyFactionCommand, "", nullptr }, - { NODE, "tp", SEC_MODERATOR, false, &ChatHandler::HandleModifyTalentCommand, "", nullptr }, - { NODE, "mount", SEC_MODERATOR, false, &ChatHandler::HandleModifyMountCommand, "", nullptr }, - { NODE, "honor", SEC_MODERATOR, false, &ChatHandler::HandleModifyHonorCommand, "", nullptr }, - { NODE, "rep", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRepCommand, "", nullptr }, - { NODE, "drunk", SEC_MODERATOR, false, &ChatHandler::HandleModifyDrunkCommand, "", nullptr }, - { NODE, "standstate", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyStandStateCommand, "", nullptr }, - { NODE, "morph", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMorphCommand, "", nullptr }, - { NODE, "gender", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyGenderCommand, "", nullptr }, - { NODE, "strength", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyStrengthCommand, "", nullptr }, - { NODE, "agility", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyAgilityCommand, "", nullptr }, - { NODE, "stamina", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyStaminaCommand, "", nullptr }, - { NODE, "intellect", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyIntellectCommand, "", nullptr }, - { NODE, "spirit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifySpiritCommand, "", nullptr }, - { NODE, "armor", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyArmorCommand, "", nullptr }, - { NODE, "holy", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyHolyCommand, "", nullptr }, - { NODE, "fire", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyFireCommand, "", nullptr }, - { NODE, "nature", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyNatureCommand, "", nullptr }, - { NODE, "frost", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyFrostCommand, "", nullptr }, - { NODE, "shadow", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyShadowCommand, "", nullptr }, - { NODE, "arcane", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyArcaneCommand, "", nullptr }, - { NODE, "ap", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMeleeApCommand, "", nullptr }, - { NODE, "rangeap", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRangedApCommand, "", nullptr }, - { NODE, "spellpower", SEC_GAMEMASTER, false, &ChatHandler::HandleModifySpellPowerCommand, "", nullptr }, - { NODE, "crit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMeleeCritCommand, "", nullptr }, - { NODE, "rangecrit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRangedCritCommand, "", nullptr }, - { NODE, "spellcrit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifySpellCritCommand, "", nullptr }, - { NODE, "mainspeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMainSpeedCommand, "", nullptr }, - { NODE, "offspeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyOffSpeedCommand, "", nullptr }, - { NODE, "rangespeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRangedSpeedCommand, "", nullptr }, - { NODE, "castspeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyCastSpeedCommand, "", nullptr }, - { NODE, "block", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyBlockCommand, "", nullptr }, - { NODE, "dodge", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyDodgeCommand, "", nullptr }, - { NODE, "parry", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyParryCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand creatureGroupsCommandTable[] = - { - { NODE, "add", SEC_MODERATOR, false, &ChatHandler::HandleNpcGroupAddCommand, "", nullptr }, - { NODE, "del", SEC_MODERATOR, false, &ChatHandler::HandleNpcGroupDelCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand npcCommandTable[] = - { - { NODE, "add", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAddCommand, "", nullptr }, - { NODE, "additem", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAddVendorItemCommand, "", nullptr }, - { NODE, "addmove", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAddMoveCommand, "", nullptr }, - { NODE, "aiinfo", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAIInfoCommand, "", nullptr }, - { NODE, "allowmove", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcAllowMovementCommand, "", nullptr }, - { NODE, "changeentry", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcChangeEntryCommand, "", nullptr }, - { NODE, "changelevel", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcChangeLevelCommand, "", nullptr }, - { NODE, "delete", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcDeleteCommand, "", nullptr }, - { NODE, "delitem", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcDelVendorItemCommand, "", nullptr }, - { NODE, "factionid", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcFactionIdCommand, "", nullptr }, - { NODE, "flag", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcFlagCommand, "", nullptr }, - { NODE, "follow", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcFollowCommand, "", nullptr }, - { NODE, "info", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcInfoCommand, "", nullptr }, - { NODE, "move", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcMoveCommand, "", nullptr }, - { NODE, "playemote", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcPlayEmoteCommand, "", nullptr }, - { NODE, "setmodel", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSetModelCommand, "", nullptr }, - { NODE, "setmovetype", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSetMoveTypeCommand, "", nullptr }, - { NODE, "spawndist", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSpawnDistCommand, "", nullptr }, - { NODE, "spawntime", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSpawnTimeCommand, "", nullptr }, - { NODE, "say", SEC_MODERATOR, false, &ChatHandler::HandleNpcSayCommand, "", nullptr }, - { NODE, "summon", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSummonCommand, "", nullptr }, - { NODE, "textemote", SEC_MODERATOR, false, &ChatHandler::HandleNpcTextEmoteCommand, "", nullptr }, - { NODE, "unfollow", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcUnFollowCommand, "", nullptr }, - { NODE, "whisper", SEC_MODERATOR, false, &ChatHandler::HandleNpcWhisperCommand, "", nullptr }, - { NODE, "yell", SEC_MODERATOR, false, &ChatHandler::HandleNpcYellCommand, "", nullptr }, - { NODE, "tame", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcTameCommand, "", nullptr }, - { NODE, "setdeathstate", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSetDeathStateCommand, "", nullptr }, - { NODE, "group", SEC_GAMEMASTER, false, nullptr, "", creatureGroupsCommandTable }, - - - //{ TODO: fix or remove this commands - { NODE, "addweapon", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcAddWeaponCommand, "", nullptr }, - { NODE, "name", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcNameCommand, "", nullptr }, - { NODE, "subname", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSubNameCommand, "", nullptr }, - //} - - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand pbcastCommandTable[] = - { - { MSTR, "stats", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePBCastStatsCommand, "", nullptr }, - { MSTR, "setthreads", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePBCastSetThreadsCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand pdumpCommandTable[] = - { - { NODE, "load", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePDumpLoadCommand, "", nullptr }, - { NODE, "write", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePDumpWriteCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand poolCommandTable[] = - { - { NODE, "list", SEC_GAMEMASTER, false, &ChatHandler::HandlePoolListCommand, "", nullptr }, - { NODE, "update", SEC_ADMINISTRATOR, false, &ChatHandler::HandlePoolUpdateCommand, "", nullptr }, - { NODE, "spawns", SEC_GAMEMASTER, false, &ChatHandler::HandlePoolSpawnsCommand, "", nullptr }, - { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandlePoolInfoCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand questCommandTable[] = - { - { NODE, "add", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestAddCommand, "", nullptr }, - { NODE, "complete", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestCompleteCommand, "", nullptr }, - { NODE, "status", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestStatusCommand, "", nullptr }, - { NODE, "remove", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestRemoveCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand petCommandTable[] = - { - { MSTR, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePetListCommand, "", nullptr }, - { MSTR, "rename", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePetRenameCommand, "", nullptr }, - { MSTR, "delete", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePetDeleteCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand reloadCommandTable[] = - { - { MSTR, "all", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllCommand, "", nullptr }, - { MSTR, "all_area", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllAreaCommand, "", nullptr }, - { MSTR, "all_eventai", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllEventAICommand, "", nullptr }, - { MSTR, "all_gossips", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllGossipsCommand, "", nullptr }, - { MSTR, "all_item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllItemCommand, "", nullptr }, - { MSTR, "all_locales", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllLocalesCommand, "", nullptr }, - { MSTR, "all_loot", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllLootCommand, "", nullptr }, - { MSTR, "all_npc", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllNpcCommand, "", nullptr }, - { MSTR, "all_quest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllQuestCommand, "", nullptr }, - { MSTR, "all_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllScriptsCommand, "", nullptr }, - { MSTR, "all_spell", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllSpellCommand, "", nullptr }, - - { MSTR, "anticheat", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAnticheatCommand, "", nullptr }, - { MSTR, "config", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadConfigCommand, "", nullptr }, - - { MSTR, "areatrigger_involvedrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestAreaTriggersCommand, "", nullptr }, - { MSTR, "areatrigger_tavern", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAreaTriggerTavernCommand, "", nullptr }, - { MSTR, "areatrigger_teleport", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAreaTriggerTeleportCommand, "", nullptr }, - { MSTR, "character_pet", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCharacterPetCommand, "", nullptr }, - { MSTR, "command", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCommandCommand, "", nullptr }, - { MSTR, "conditions", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadConditionsCommand, "", nullptr }, - { MSTR, "creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureCommand, "", nullptr }, - { MSTR, "creature_ai_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventAIScriptsCommand, "", nullptr }, - { MSTR, "creature_ai_summons", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventAISummonsCommand, "", nullptr }, - { MSTR, "creature_ai_texts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventAITextsCommand, "", nullptr }, - { MSTR, "creature_battleground", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadBattleEventCommand, "", nullptr }, - { MSTR, "creature_involvedrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureQuestInvRelationsCommand, "", nullptr }, - { MSTR, "creature_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesCreatureCommand, "", nullptr }, - { MSTR, "creature_questrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureQuestRelationsCommand, "", nullptr }, - { MSTR, "db_script_string", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadDbScriptStringCommand, "", nullptr }, - { MSTR, "disenchant_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesDisenchantCommand, "", nullptr }, - { MSTR, "event_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventScriptsCommand, "", nullptr }, - { MSTR, "fishing_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesFishingCommand, "", nullptr }, - { MSTR, "game_graveyard_zone", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameGraveyardZoneCommand, "", nullptr }, - { MSTR, "game_tele", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameTeleCommand, "", nullptr }, - { MSTR, "gameobject", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameObjectCommand, "", nullptr }, - { MSTR, "gameobject_involvedrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGOQuestInvRelationsCommand, "", nullptr }, - { MSTR, "gameobject_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesGameobjectCommand, "", nullptr }, - { MSTR, "gameobject_questrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGOQuestRelationsCommand, "", nullptr }, - { MSTR, "gameobject_requirement", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGORequirementsCommand, "", nullptr }, - { MSTR, "gameobject_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameObjectScriptsCommand, "", nullptr }, - { MSTR, "gameobject_battleground", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadBattleEventCommand, "", nullptr }, - { MSTR, "gossip_menu", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGossipMenuCommand, "", nullptr }, - { MSTR, "gossip_menu_option", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGossipMenuOptionCommand, "", nullptr }, - { MSTR, "gossip_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGossipScriptsCommand, "", nullptr }, - { MSTR, "item_enchantment_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadItemEnchantementsCommand, "", nullptr }, - { MSTR, "item_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesItemCommand, "", nullptr }, - { MSTR, "item_required_target", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadItemRequiredTragetCommand, "", nullptr }, - { MSTR, "locales_creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesCreatureCommand, "", nullptr }, - { MSTR, "locales_gameobject", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesGameobjectCommand, "", nullptr }, - { MSTR, "locales_gossip_menu_option", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesGossipMenuOptionCommand, "", nullptr }, - { MSTR, "locales_item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesItemCommand, "", nullptr }, - { MSTR, "locales_npc_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesNpcTextCommand, "", nullptr }, - { MSTR, "locales_page_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesPageTextCommand, "", nullptr }, - { MSTR, "locales_points_of_interest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesPointsOfInterestCommand, "", nullptr }, - { MSTR, "locales_quest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesQuestCommand, "", nullptr }, - { MSTR, "mail_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesMailCommand, "", nullptr }, - { MSTR, "mangos_string", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadMangosStringCommand, "", nullptr }, - { MSTR, "npc_gossip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcGossipCommand, "", nullptr }, - { MSTR, "npc_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcTextCommand, "", nullptr }, - { MSTR, "npc_trainer", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcTrainerCommand, "", nullptr }, - { MSTR, "npc_vendor", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcVendorCommand, "", nullptr }, - { MSTR, "page_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadPageTextsCommand, "", nullptr }, - { MSTR, "pickpocketing_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesPickpocketingCommand, "", nullptr}, - { MSTR, "points_of_interest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadPointsOfInterestCommand, "", nullptr }, - { MSTR, "quest_end_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestEndScriptsCommand, "", nullptr }, - { MSTR, "quest_start_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestStartScriptsCommand, "", nullptr }, - { MSTR, "quest_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestTemplateCommand, "", nullptr }, - { MSTR, "reference_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesReferenceCommand, "", nullptr }, - { MSTR, "reserved_name", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadReservedNameCommand, "", nullptr }, - { MSTR, "reputation_reward_rate", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadReputationRewardRateCommand, "", nullptr }, - { MSTR, "reputation_spillover_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadReputationSpilloverTemplateCommand, "", nullptr }, - { MSTR, "skill_discovery_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSkillDiscoveryTemplateCommand, "", nullptr }, - { MSTR, "skill_extra_item_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSkillExtraItemTemplateCommand, "", nullptr }, - { MSTR, "skill_fishing_base_level", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSkillFishingBaseLevelCommand, "", nullptr }, - { MSTR, "skinning_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesSkinningCommand, "", nullptr }, - { MSTR, "spell_affect", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellAffectCommand, "", nullptr }, - { MSTR, "spell_area", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellAreaCommand, "", nullptr }, - { MSTR, "spell_bonus_data", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellBonusesCommand, "", nullptr }, - { MSTR, "spell_chain", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellChainCommand, "", nullptr }, - { MSTR, "spell_elixir", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellElixirCommand, "", nullptr }, - { MSTR, "spell_learn_spell", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellLearnSpellCommand, "", nullptr }, - { MSTR, "spell_pet_auras", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellPetAurasCommand, "", nullptr }, - { MSTR, "spell_proc_event", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellProcEventCommand, "", nullptr }, - { MSTR, "spell_proc_item_enchant", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellProcItemEnchantCommand, "", nullptr }, - { MSTR, "spell_script_target", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellScriptTargetCommand, "", nullptr }, - { MSTR, "spell_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellScriptsCommand, "", nullptr }, - { MSTR, "spell_target_position", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellTargetPositionCommand, "", nullptr }, - { MSTR, "spell_threats", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellThreatsCommand, "", nullptr }, - { MSTR, "spell_disabled", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellDisabledCommand, "", nullptr }, - { MSTR, "autobroadcast", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAutoBroadcastCommand, "", nullptr }, - { MSTR, "spell_mod", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellModsCommand, "", nullptr }, - { MSTR, "map_loot_disabled", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadMapLootDisabledCommand, "", nullptr }, - { MSTR, "cinematic_waypoints", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCinematicWaypointsCommand, "", nullptr }, - { MSTR, "variables", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadVariablesCommand, "", nullptr }, - { MSTR, "spell_group", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellGroupCommand, "", nullptr }, - { MSTR, "spell_group_stack_rules", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellGroupStackRulesCommand, "", nullptr }, - { MSTR, "creature_groups", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureGroupsCommand, "", nullptr }, - - { MSTR, "creature_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureTemplate, "", nullptr }, - { MSTR, "item_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadItemTemplate, "", nullptr }, - { MSTR, "map_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadMapTemplate, "", nullptr }, - { MSTR, "gameobject_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameObjectTemplate, "", nullptr }, - { MSTR, "exploration_basexp", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadExplorationBaseXp, "", nullptr }, - { MSTR, "pet_name_generation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadPetNameGeneration, "", nullptr }, - { MSTR, "creature_onkill_reputation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureOnKillReputation, "", nullptr }, - { MSTR, "game_weather", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameWeather, "", nullptr }, - { MSTR, "player_factionchange_reputations", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeReputations, "", nullptr }, - { MSTR, "player_factionchange_spells", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeSpells, "", nullptr }, - { MSTR, "player_factionchange_items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeItems, "", nullptr }, - { MSTR, "player_factionchange_quests", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeQuests, "", nullptr }, - { MSTR, "player_factionchange_mounts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeMounts, "", nullptr }, - { MSTR, "creature_model_info", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureModelInfo, "", nullptr }, - { MSTR, "nostalrius_string", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNostalriusStrings, "", nullptr }, - { MSTR, "ip_banned", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadIPBanList, "", nullptr }, - { MSTR, "account_banned", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAccountBanList, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand resetCommandTable[] = - { - { NODE, "honor", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetHonorCommand, "", nullptr }, - { NODE, "level", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetLevelCommand, "", nullptr }, - { NODE, "spells", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetSpellsCommand, "", nullptr }, - { NODE, "stats", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetStatsCommand, "", nullptr }, - { NODE, "talents", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetTalentsCommand, "", nullptr }, - { NODE, "all", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetAllCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand sendMassCommandTable[] = - { - { NODE, "items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMassItemsCommand, "", nullptr }, - { NODE, "mail", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMassMailCommand, "", nullptr }, - { NODE, "money", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMassMoneyCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand sendCommandTable[] = - { - { NODE, "mass", SEC_ADMINISTRATOR, true, nullptr, "", sendMassCommandTable }, - - { MSTR, "items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendItemsCommand, "", nullptr }, - { MSTR, "mail", SEC_MODERATOR, true, &ChatHandler::HandleSendMailCommand, "", nullptr }, - { MSTR, "message", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMessageCommand, "", nullptr }, - { MSTR, "money", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMoneyCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverIdleRestartCommandTable[] = - { - { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, - { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerIdleRestartCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverIdleShutdownCommandTable[] = - { - { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, - { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerIdleShutDownCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverRestartCommandTable[] = - { - { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, - { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerRestartCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverShutdownCommandTable[] = - { - { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, - { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverLogCommandTable[] = - { - { NODE, "filter", SEC_CONSOLE, true, &ChatHandler::HandleServerLogFilterCommand, "", nullptr }, - { NODE, "level", SEC_CONSOLE, true, &ChatHandler::HandleServerLogLevelCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverSetCommandTable[] = - { - { MSTR, "motd", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerSetMotdCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand serverCommandTable[] = - { - { NODE, "corpses", SEC_GAMEMASTER, true, &ChatHandler::HandleServerCorpsesCommand, "", nullptr }, - { NODE, "exit", SEC_CONSOLE, true, &ChatHandler::HandleServerExitCommand, "", nullptr }, - { NODE, "idlerestart", SEC_ADMINISTRATOR, true, nullptr, "", serverIdleRestartCommandTable }, - { NODE, "idleshutdown", SEC_ADMINISTRATOR, true, nullptr, "", serverShutdownCommandTable }, - { NODE, "info", SEC_PLAYER, true, &ChatHandler::HandleServerInfoCommand, "", nullptr }, - { NODE, "log", SEC_CONSOLE, true, nullptr, "", serverLogCommandTable }, - { NODE, "motd", SEC_PLAYER, true, &ChatHandler::HandleServerMotdCommand, "", nullptr }, - { NODE, "plimit", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerPLimitCommand, "", nullptr }, - { NODE, "restart", SEC_ADMINISTRATOR, true, nullptr, "", serverRestartCommandTable }, - { NODE, "shutdown", SEC_ADMINISTRATOR, true, nullptr, "", serverShutdownCommandTable }, - { NODE, "set", SEC_ADMINISTRATOR, true, nullptr, "", serverSetCommandTable }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand teleCommandTable[] = - { - { NODE, "add", SEC_ADMINISTRATOR, false, &ChatHandler::HandleTeleAddCommand, "", nullptr }, - { NODE, "del", SEC_ADMINISTRATOR, true, &ChatHandler::HandleTeleDelCommand, "", nullptr }, - { NODE, "name", SEC_MODERATOR, true, &ChatHandler::HandleTeleNameCommand, "", nullptr }, - { NODE, "group", SEC_MODERATOR, false, &ChatHandler::HandleTeleGroupCommand, "", nullptr }, - { NODE, "", SEC_MODERATOR, false, &ChatHandler::HandleTeleCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand triggerCommandTable[] = - { - { NODE, "active", SEC_GAMEMASTER, false, &ChatHandler::HandleTriggerActiveCommand, "", nullptr }, - { NODE, "near", SEC_GAMEMASTER, false, &ChatHandler::HandleTriggerNearCommand, "", nullptr }, - { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleTriggerCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand unbanCommandTable[] = - { - { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleUnBanAccountCommand, "", nullptr }, - { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleUnBanCharacterCommand, "", nullptr }, - { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleUnBanIPCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand wpCommandTable[] = - { - { NODE, "show", SEC_GAMEMASTER, false, &ChatHandler::HandleWpShowCommand, "", nullptr }, - { NODE, "add", SEC_GAMEMASTER, false, &ChatHandler::HandleWpAddCommand, "", nullptr }, - { NODE, "modify", SEC_GAMEMASTER, false, &ChatHandler::HandleWpModifyCommand, "", nullptr }, - { NODE, "export", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWpExportCommand, "", nullptr }, - { NODE, "import", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWpImportCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand exportCommandTable[] = - { - { NODE, "spell", SEC_CONSOLE, true, &ChatHandler::HandleDbcExportSpellCommand, "", nullptr}, - { NODE, "effects", SEC_CONSOLE, true, &ChatHandler::HandleDbcExportSpellEffectsCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - - static ChatCommand worldCommandTable[] = - { - { NODE, "update", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWorldUpdateCommand, "", nullptr}, - { NODE, "cansee", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWorldTestCommand, "", nullptr}, - { NODE, "detail", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWorldDetailCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - - static ChatCommand cinematicCommandTable[] = - { - { NODE, "addwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCinematicAddWpCommand, "", nullptr}, - { NODE, "gotime", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCinematicGoTimeCommand, "", nullptr}, - { NODE, "listwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCinematicListWpCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - - static ChatCommand escortCommandTable[] = - { - { NODE, "create", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortCreateCommand, "", nullptr}, - { NODE, "addwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortAddWpCommand, "", nullptr}, - { NODE, "modwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortModifyWpCommand, "", nullptr}, - { NODE, "clearwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortClearWpCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - static ChatCommand worldStateCommandTable[] = - { - { NODE, "test", SEC_ADMINISTRATOR, false, &ChatHandler::HandleUpdateWorldStateCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - static ChatCommand bgCommandTable[] = - { - { NODE, "status", SEC_GAMEMASTER, false, &ChatHandler::HandleBGStatusCommand, "", nullptr}, - { NODE, "start", SEC_GAMEMASTER, false, &ChatHandler::HandleBGStartCommand, "", nullptr}, - { NODE, "stop", SEC_GAMEMASTER, false, &ChatHandler::HandleBGStopCommand, "", nullptr}, - { NODE, "", SEC_GAMEMASTER, false, &ChatHandler::HandleBGCustomCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - static ChatCommand spellCommandTable[] = - { - { NODE, "effects", SEC_GAMEMASTER, true, &ChatHandler::HandleSpellEffectsCommand, "", nullptr}, - { NODE, "info", SEC_GAMEMASTER, true, &ChatHandler::HandleSpellInfosCommand, "", nullptr}, - { NODE, "search", SEC_GAMEMASTER, true, &ChatHandler::HandleSpellSearchCommand, "", nullptr}, - { NODE, "iconfix", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSpellIconFixCommand, "", nullptr}, - { MSTR, nullptr, 0, false, nullptr, "", nullptr} - }; - static ChatCommand mmapCommandTable[] = - { - { NODE, "path", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapPathCommand, "", nullptr }, - { NODE, "loc", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapLocCommand, "", nullptr }, - { NODE, "loadedtiles", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapLoadedTilesCommand, "", nullptr }, - { NODE, "stats", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapStatsCommand, "", nullptr }, - { NODE, "testarea", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapTestArea, "", nullptr }, - { NODE, "connect", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmapConnection, "", nullptr }, - { NODE, "reload", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmapLoad, "", nullptr }, - { NODE, "unload", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmapUnload, "", nullptr }, - { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmap, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand videosCommandTable[] = - { - { NODE, "expendables", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugExp, "", nullptr }, - { NODE, "turn", SEC_GAMEMASTER, false, &ChatHandler::HandleVideoTurn, "", nullptr }, - { NODE, "", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugExp, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand anticheatClientCommandTable[] = - { - { NODE, "find", SEC_GAMEMASTER, true, &ChatHandler::HandleClientSearchCommand, "", nullptr }, - { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleClientInfosCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand anticheatWardenCommandTable[] = - { - { NODE, "read", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWardenReadCommand, "", nullptr }, - { NODE, "", SEC_ADMINISTRATOR, true, &ChatHandler::HandleWardenCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand anticheatCommandTable[] = - { - { NODE, "server", SEC_GAMEMASTER, true, &ChatHandler::HandleAnticheatCommand, "", nullptr }, - { NODE, "warden", SEC_GAMEMASTER, true, nullptr, "", anticheatWardenCommandTable }, - { NODE, "client", SEC_ADMINISTRATOR, true, nullptr, "", anticheatClientCommandTable }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - static ChatCommand replayCommandTable[] = - { - { NODE, "play", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayPlayCommand, "", nullptr }, - { NODE, "forward", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayForwardCommand, "", nullptr }, - { NODE, "stop", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayStopCommand, "", nullptr }, - { NODE, "record", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayRecordCommand, "", nullptr }, - { NODE, "speed", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplaySpeedCommand, "", nullptr }, - { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayPlayCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - static ChatCommand channelCommandTable[] = - { - { NODE, "join", SEC_GAMEMASTER, false, &ChatHandler::HandleChannelJoinCommand, "", nullptr }, - { NODE, "leave", SEC_GAMEMASTER, false, &ChatHandler::HandleChannelLeaveCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - static ChatCommand ticketResponseCommandTable[] = - { - { NODE, "reset", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResponseResetCommand, "", nullptr }, - { NODE, "append", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResponseAppendCommand, "", nullptr }, - { NODE, "appendln", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResponseAppendLnCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - static ChatCommand nodeServersCommandTable[] = - { - { NODE, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandleNodeServersListCommand, "", nullptr }, - { NODE, "switch", SEC_ADMINISTRATOR, true, &ChatHandler::HandleNodeServersSwitchCommand, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - static ChatCommand ticketCommandTable[] = - { - { NODE, "assign", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketAssignToCommand, "", nullptr }, - { NODE, "close", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCloseByIdCommand, "", nullptr }, - { NODE, "closedlist", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListClosedCommand, "", nullptr }, - { NODE, "counter", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCounterCommand, "", nullptr }, - { NODE, "comment", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCommentCommand, "", nullptr }, - { NODE, "complete", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCompleteCommand, "", nullptr }, - { NODE, "delete", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketDeleteByIdCommand, "", nullptr }, - { NODE, "escalate", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketEscalateCommand, "", nullptr }, - { NODE, "escalatedlist", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListEscalatedCommand, "", nullptr }, - { NODE, "list", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListCommand, "", nullptr }, - { NODE, "next", SEC_GAMEMASTER, false,&ChatHandler::HandleGMTicketNextCommand, "", nullptr }, - { NODE, "notify", SEC_GAMEMASTER, false,&ChatHandler::HandleGMTicketNotifyCommand, "", nullptr }, - { NODE, "onlinelist", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListOnlineCommand, "", nullptr }, - { NODE, "previous", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketPreviousCommand, "", nullptr }, - { NODE, "reload", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketReloadCommand, "", nullptr }, - { NODE, "reset", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResetCommand, "", nullptr }, - { NODE, "response", SEC_GAMEMASTER, true, nullptr, "", ticketResponseCommandTable }, - { NODE, "togglesystem", SEC_GAMEMASTER, true, &ChatHandler::HandleToggleGMTicketSystem, "", nullptr }, - { NODE, "unassign", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketUnAssignCommand, "", nullptr }, - { NODE, "viewid", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketGetByIdCommand, "", nullptr }, - { NODE, "viewname", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketGetByNameCommand, "", nullptr }, - { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketGetByIdOrNameCommand, "", nullptr }, - { MSTR, nullptr, 0, false,nullptr, "", nullptr } - }; - - static ChatCommand serviceCommandTable[] = - { - { NODE, "del_characters", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServiceDeleteCharacters, "", nullptr }, - { NODE, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand spamerCommandTable[] = - { - { MSTR, "mute", SEC_GAMEMASTER, true, &ChatHandler::HandleSpamerMute, "", nullptr }, - { MSTR, "unmute", SEC_GAMEMASTER, true, &ChatHandler::HandleSpamerUnmute, "", nullptr }, - { MSTR, "list", SEC_GAMEMASTER, true, &ChatHandler::HandleSpamerList, "", nullptr }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - static ChatCommand goldCommandTable[] = - { - { MSTR, "remove", SEC_GAMEMASTER, true, &ChatHandler::HandleGoldRemoval, "", nullptr }, - }; - - static ChatCommand commandTable[] = - { - { NODE, "account", SEC_PLAYER, true, nullptr, "", accountCommandTable }, - { NODE, "auction", SEC_ADMINISTRATOR, false, nullptr, "", auctionCommandTable }, - { NODE, "cast", SEC_ADMINISTRATOR, false, nullptr, "", castCommandTable }, - { NODE, "character", SEC_GAMEMASTER, true, nullptr, "", characterCommandTable}, - { NODE, "debug", SEC_GAMEMASTER, true, nullptr, "", debugCommandTable }, - { NODE, "replay", SEC_GAMEMASTER, false, nullptr, "", replayCommandTable }, - { NODE, "event", SEC_GAMEMASTER, false, nullptr, "", eventCommandTable }, - { NODE, "gm", SEC_PLAYER, true, nullptr, "", gmCommandTable }, - { NODE, "honor", SEC_GAMEMASTER, false, nullptr, "", honorCommandTable }, - { NODE, "go", SEC_MODERATOR, false, nullptr, "", goCommandTable }, - { NODE, "gobject", SEC_GAMEMASTER, false, nullptr, "", gobjectCommandTable }, - { NODE, "guild", SEC_ADMINISTRATOR, true, nullptr, "", guildCommandTable }, - { NODE, "instance", SEC_ADMINISTRATOR, true, nullptr, "", instanceCommandTable }, - { NODE, "learn", SEC_MODERATOR, false, nullptr, "", learnCommandTable }, - { NODE, "list", SEC_ADMINISTRATOR, true, nullptr, "", listCommandTable }, - { NODE, "lookup", SEC_MODERATOR, true, nullptr, "", lookupCommandTable }, - { NODE, "modify", SEC_MODERATOR, false, nullptr, "", modifyCommandTable }, - { NODE, "npc", SEC_MODERATOR, false, nullptr, "", npcCommandTable }, - { NODE, "pool", SEC_GAMEMASTER, true, nullptr, "", poolCommandTable }, - { NODE, "pdump", SEC_ADMINISTRATOR, true, nullptr, "", pdumpCommandTable }, - { NODE, "quest", SEC_ADMINISTRATOR, false, nullptr, "", questCommandTable }, - { NODE, "reload", SEC_ADMINISTRATOR, true, nullptr, "", reloadCommandTable }, - { NODE, "reset", SEC_ADMINISTRATOR, true, nullptr, "", resetCommandTable }, - { NODE, "server", SEC_PLAYER, true, nullptr, "", serverCommandTable }, - { NODE, "tele", SEC_MODERATOR, true, nullptr, "", teleCommandTable }, - { NODE, "trigger", SEC_GAMEMASTER, false, nullptr, "", triggerCommandTable }, - { NODE, "wp", SEC_GAMEMASTER, false, nullptr, "", wpCommandTable }, - { NODE, "service", SEC_ADMINISTRATOR, true, nullptr, "", serviceCommandTable }, - - { NODE, "export", SEC_CONSOLE, true, nullptr, "Export DBC files to database", exportCommandTable}, - { NODE, "bot", SEC_GAMEMASTER, true, nullptr, "Manage bots", botCommandTable}, - { NODE, "ahbot", SEC_GAMEMASTER, true, nullptr, "Manage AH bot", ahbotCommandTable}, - { NODE, "world", SEC_GAMEMASTER, false, nullptr, "", worldCommandTable }, - { NODE, "possess", SEC_GAMEMASTER, false, &ChatHandler::HandlePossessCommand, "", nullptr}, - { NODE, "cinematic", SEC_GAMEMASTER, false, nullptr, "", cinematicCommandTable}, - { NODE, "escorte", SEC_GAMEMASTER, false, nullptr, "", escortCommandTable}, - { NODE, "worldstate", SEC_GAMEMASTER, false, nullptr, "", worldStateCommandTable}, - { NODE, "bg", SEC_GAMEMASTER, false, nullptr, "", bgCommandTable}, - { NODE, "spell", SEC_GAMEMASTER, true, nullptr, "", spellCommandTable}, - { NODE, "variable", SEC_GAMEMASTER, true, &ChatHandler::HandleVariableCommand, "", nullptr}, - { NODE, "god", SEC_GAMEMASTER, false, &ChatHandler::HandleGodCommand, "", nullptr }, - { NODE, "aura", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuraCommand, "", nullptr }, - { NODE, "unaura", SEC_ADMINISTRATOR, false, &ChatHandler::HandleUnAuraCommand, "", nullptr }, - { NODE, "announce", SEC_MODERATOR, true, &ChatHandler::HandleAnnounceCommand, "", nullptr }, - { NODE, "notify", SEC_MODERATOR, true, &ChatHandler::HandleNotifyCommand, "", nullptr }, - { NODE, "goname", SEC_MODERATOR, false, &ChatHandler::HandleGonameCommand, "", nullptr }, - { NODE, "namego", SEC_MODERATOR, false, &ChatHandler::HandleNamegoCommand, "", nullptr }, - { NODE, "groupgo", SEC_MODERATOR, false, &ChatHandler::HandleGroupgoCommand, "", nullptr }, - { NODE, "gocorpse", SEC_MODERATOR, false, &ChatHandler::HandleGocorpseCommand, "", nullptr }, - { NODE, "commands", SEC_PLAYER, true, &ChatHandler::HandleCommandsCommand, "", nullptr }, - { NODE, "demorph", SEC_GAMEMASTER, false, &ChatHandler::HandleDeMorphCommand, "", nullptr }, - { NODE, "die", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDieCommand, "", nullptr }, - { NODE, "revive", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReviveCommand, "", nullptr }, - { NODE, "dismount", SEC_PLAYER, false, &ChatHandler::HandleDismountCommand, "", nullptr }, - { NODE, "gps", SEC_MODERATOR, false, &ChatHandler::HandleGPSCommand, "", nullptr }, - { NODE, "guid", SEC_GAMEMASTER, false, &ChatHandler::HandleGUIDCommand, "", nullptr }, - { NODE, "help", SEC_PLAYER, true, &ChatHandler::HandleHelpCommand, "", nullptr }, - { NODE, "itemmove", SEC_GAMEMASTER, false, &ChatHandler::HandleItemMoveCommand, "", nullptr }, - { NODE, "cooldown", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCooldownCommand, "", nullptr }, - { NODE, "unlearn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleUnLearnCommand, "", nullptr }, - { NODE, "distance", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGetDistanceCommand, "", nullptr }, - { NODE, "recall", SEC_MODERATOR, false, &ChatHandler::HandleRecallCommand, "", nullptr }, - { NODE, "save", SEC_PLAYER, false, &ChatHandler::HandleSaveCommand, "", nullptr }, - { MSTR, "wareffortget", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGetWarEffortResource, "", nullptr }, - { MSTR, "wareffortset", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSetWarEffortResource, "", nullptr }, - { MSTR, "saveall", SEC_MODERATOR, true, &ChatHandler::HandleSaveAllCommand, "", nullptr }, - { MSTR, "kick", SEC_GAMEMASTER, true, &ChatHandler::HandleKickPlayerCommand, "", nullptr }, - { MSTR, "ban", SEC_ADMINISTRATOR, true, nullptr, "", banCommandTable }, - { MSTR, "unban", SEC_ADMINISTRATOR, true, nullptr, "", unbanCommandTable }, - { MSTR, "baninfo", SEC_ADMINISTRATOR, false, nullptr, "", baninfoCommandTable }, - { MSTR, "banlist", SEC_ADMINISTRATOR, true, nullptr, "", banlistCommandTable }, - { NODE, "start", SEC_PLAYER, false, &ChatHandler::HandleStartCommand, "", nullptr }, - { NODE, "taxicheat", SEC_MODERATOR, false, &ChatHandler::HandleTaxiCheatCommand, "", nullptr }, - { NODE, "linkgrave", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLinkGraveCommand, "", nullptr }, - { NODE, "neargrave", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNearGraveCommand, "", nullptr }, - { NODE, "explorecheat", SEC_ADMINISTRATOR, false, &ChatHandler::HandleExploreCheatCommand, "", nullptr }, - { NODE, "hover", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHoverCommand, "", nullptr }, - { NODE, "levelup", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLevelUpCommand, "", nullptr }, - { NODE, "showarea", SEC_ADMINISTRATOR, false, &ChatHandler::HandleShowAreaCommand, "", nullptr }, - { NODE, "hidearea", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHideAreaCommand, "", nullptr }, - { NODE, "additem", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAddItemCommand, "", nullptr }, - { NODE, "additemset", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAddItemSetCommand, "", nullptr }, - { NODE, "bank", SEC_ADMINISTRATOR, false, &ChatHandler::HandleBankCommand, "", nullptr }, - { NODE, "wchange", SEC_ADMINISTRATOR, false, &ChatHandler::HandleChangeWeatherCommand, "", nullptr }, - { NODE, "ticket", SEC_GAMEMASTER, true, nullptr, "",ticketCommandTable }, - { NODE, "maxskill", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMaxSkillCommand, "", nullptr }, - { NODE, "setskill", SEC_ADMINISTRATOR, false, &ChatHandler::HandleSetSkillCommand, "", nullptr }, - { MSTR, "whispers", SEC_MODERATOR, false, &ChatHandler::HandleWhispersCommand, "", nullptr }, - { MSTR, "wr", SEC_PLAYER, false, &ChatHandler::HandleWhisperRestrictionCommand, "", nullptr }, - { MSTR, "pinfo", SEC_GAMEMASTER, true, &ChatHandler::HandlePInfoCommand, "", nullptr }, - { MSTR, "groupinfo", SEC_GAMEMASTER, true, &ChatHandler::HandleGroupInfoCommand, "", nullptr }, - { MSTR, "pbcast", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePBCastStatsCommand, "", pbcastCommandTable }, - { NODE, "addons", SEC_ADMINISTRATOR, false, &ChatHandler::HandleListAddonsCommand, "", nullptr }, - { NODE, "respawn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleRespawnCommand, "", nullptr }, - { NODE, "send", SEC_MODERATOR, true, nullptr, "", sendCommandTable }, - { NODE, "mute", SEC_MODERATOR, true, &ChatHandler::HandleMuteCommand, "", nullptr }, - { NODE, "unmute", SEC_MODERATOR, true, &ChatHandler::HandleUnmuteCommand, "", nullptr }, - { NODE, "movegens", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMovegensCommand, "", nullptr }, - { NODE, "cometome", SEC_ADMINISTRATOR, false, &ChatHandler::HandleComeToMeCommand, "", nullptr }, - { NODE, "damage", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDamageCommand, "", nullptr }, - { NODE, "combatstop", SEC_GAMEMASTER, false, &ChatHandler::HandleCombatStopCommand, "", nullptr }, - { NODE, "repairitems", SEC_GAMEMASTER, true, &ChatHandler::HandleRepairitemsCommand, "", nullptr }, - { NODE, "stable", SEC_ADMINISTRATOR, false, &ChatHandler::HandleStableCommand, "", nullptr }, - { NODE, "waterwalk", SEC_GAMEMASTER, false, &ChatHandler::HandleWaterwalkCommand, "", nullptr }, - { NODE, "quit", SEC_CONSOLE, true, &ChatHandler::HandleQuitCommand, "", nullptr }, - { NODE, "mmap", SEC_GAMEMASTER, false, nullptr, "", mmapCommandTable }, - { NODE, "video", SEC_GAMEMASTER, false, nullptr, "", videosCommandTable }, - { NODE, "freez", SEC_GAMEMASTER, false, &ChatHandler::HandleFreezCommand, "", nullptr }, - { NODE, "anticheat", SEC_GAMEMASTER, false, nullptr, "", anticheatCommandTable }, - { NODE, "groupspell", SEC_ADMINISTRATOR, true, nullptr, "", groupSpellCommandTable}, - { NODE, "pet", SEC_ADMINISTRATOR, true, nullptr, "", petCommandTable}, - { NODE, "channel", SEC_GAMEMASTER, false, nullptr, "", channelCommandTable}, - { NODE, "nodes", SEC_GAMEMASTER, true, nullptr, "", nodeServersCommandTable}, - { MSTR, "runtest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleRunTestCommand, "", nullptr }, - { MSTR, "log", SEC_GAMEMASTER, true, &ChatHandler::HandleViewLogCommand, "", nullptr }, - { MSTR, "spamer", SEC_GAMEMASTER, true, nullptr, "", spamerCommandTable }, - { MSTR, "gold", SEC_GAMEMASTER, true, nullptr, "", goldCommandTable }, - { MSTR, nullptr, 0, false, nullptr, "", nullptr } - }; - - if (load_command_table) - { - load_command_table = false; - - // check hardcoded part integrity - //CheckIntegrity(commandTable, NULL); - FillFullCommandsName(commandTable, ""); - - QueryResult *result = WorldDatabase.Query("SELECT name,security,help,flags FROM command"); - if (result) - { - do - { - Field *fields = result->Fetch(); - std::string name = fields[0].GetCppString(); - - SetDataForCommandInTable(commandTable, name.c_str(), fields[1].GetUInt16(), fields[2].GetCppString(), fields[3].GetUInt32()); - - } - while (result->NextRow()); - delete result; - } - } - - return commandTable; -} - -ChatHandler::ChatHandler(WorldSession* session) : - m_session(session), sentErrorMessage(false), - m_cluster_is_master(true), m_cluster_is_node(true) -{ - if (session) - { - m_cluster_is_master = session->IsMaster(); - m_cluster_is_node = session->IsNode(); - } -} - -ChatHandler::ChatHandler(Player* player) : ChatHandler(player->GetSession()) {} - -ChatHandler::~ChatHandler() {} - -const char *ChatHandler::GetMangosString(int32 entry) const -{ - return m_session->GetMangosString(entry); -} - -const char *ChatHandler::GetOnOffStr(bool value) const -{ - return value ? GetMangosString(LANG_ON) : GetMangosString(LANG_OFF); -} - -uint32 ChatHandler::GetAccountId() const -{ - return m_session->GetAccountId(); -} - -AccountTypes ChatHandler::GetAccessLevel() const -{ - return m_session->GetSecurity(); -} - -bool ChatHandler::isAvailable(ChatCommand const& cmd) const -{ - // check security level only for simple command (without child commands) - return GetAccessLevel() >= (AccountTypes)cmd.SecurityLevel; -} - -std::string ChatHandler::GetNameLink() const -{ - return GetNameLink(m_session->GetPlayer()); -} - -bool ChatHandler::HasLowerSecurity(Player* target, ObjectGuid guid, bool strong) -{ - WorldSession* target_session = nullptr; - uint32 target_account = 0; - - if (target) - target_session = target->GetSession(); - else if (guid) - target_account = sObjectMgr.GetPlayerAccountIdByGUID(guid); - - if (!target_session && !target_account) - { - SendSysMessage(LANG_PLAYER_NOT_FOUND); - SetSentErrorMessage(true); - return true; - } - - return HasLowerSecurityAccount(target_session, target_account, strong); -} - -bool ChatHandler::HasLowerSecurityAccount(WorldSession* target, uint32 target_account, bool strong) -{ - AccountTypes target_sec; - - // ignore only for non-players for non strong checks (when allow apply command at least to same sec level) - if (GetAccessLevel() > SEC_PLAYER && !strong && !sWorld.getConfig(CONFIG_BOOL_GM_LOWER_SECURITY)) - return false; - - if (target) - target_sec = target->GetSecurity(); - else if (target_account) - target_sec = sAccountMgr.GetSecurity(target_account); - else - return true; // caller must report error for (target==NULL && target_account==0) - - if (GetAccessLevel() < target_sec || (strong && GetAccessLevel() <= target_sec)) - { - SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); - SetSentErrorMessage(true); - return true; - } - - return false; -} - -bool ChatHandler::hasStringAbbr(const char* name, const char* part) -{ - // non "" command - if (*name) - { - // "" part from non-"" command - if (!*part) - return false; - - for (;;) - { - if (!*part) - return true; - else if (!*name) - return false; - else if (tolower(*name) != tolower(*part)) - return false; - ++name; - ++part; - } - } - // allow with any for "" - - return true; -} - -void ChatHandler::SendSysMessage(const char *str) -{ - WorldPacket data; - - // need copy to prevent corruption by strtok call in LineFromMessage original string - char* buf = mangos_strdup(str); - char* pos = buf; - - while (char* line = LineFromMessage(pos)) - { - FillSystemMessageData(&data, line); - m_session->SendPacket(&data); - } - - delete [] buf; - SetSentErrorMessage(true); -} - -void ChatHandler::SendGlobalSysMessage(const char *str) -{ - // Chat output - WorldPacket data; - - // need copy to prevent corruption by strtok call in LineFromMessage original string - char* buf = mangos_strdup(str); - char* pos = buf; - - while (char* line = LineFromMessage(pos)) - { - FillSystemMessageData(&data, line); - sWorld.SendGlobalMessage(&data); - } - - delete [] buf; -} - -void ChatHandler::SendSysMessage(int32 entry) -{ - SendSysMessage(GetMangosString(entry)); -} - -void ChatHandler::PSendSysMessage(int32 entry, ...) -{ - const char *format = GetMangosString(entry); - va_list ap; - char str [2048]; - va_start(ap, entry); - vsnprintf(str, 2048, format, ap); - va_end(ap); - SendSysMessage(str); -} - -void ChatHandler::PSendSysMessage(const char *format, ...) -{ - va_list ap; - char str [2048]; - va_start(ap, format); - vsnprintf(str, 2048, format, ap); - va_end(ap); - SendSysMessage(str); -} - -std::string ChatHandler::PGetParseString(int32 entry, ...) -{ - const char *format = GetMangosString(entry); - va_list ap; - char str [2048]; - va_start(ap, entry); - vsnprintf(str, 2048, format, ap); - va_end(ap); - return std::string(str); -} - -void ChatHandler::FillFullCommandsName(ChatCommand* table, std::string prefix) -{ - for (uint32 i = 0; table[i].Name != nullptr; ++i) - { - std::string newPrefix = prefix; - if (newPrefix != "") - newPrefix += " "; - newPrefix += table[i].Name; - table[i].FullName = newPrefix; - if (table[i].ChildCommands) - FillFullCommandsName(table[i].ChildCommands, newPrefix); - - } -} - -void ChatHandler::CheckIntegrity(ChatCommand *table, ChatCommand *parentCommand) -{ - for (uint32 i = 0; table[i].Name != nullptr; ++i) - { - ChatCommand* command = &table[i]; - - if (parentCommand && command->SecurityLevel < parentCommand->SecurityLevel) - sLog.outError("Subcommand '%s' of command '%s' have less access level (%u) that parent (%u)", - command->Name, parentCommand->Name, command->SecurityLevel, parentCommand->SecurityLevel); - - if (!parentCommand && strlen(command->Name) == 0) - sLog.outError("Subcommand '' at top level"); - - if (command->ChildCommands) - { - if (command->Handler) - { - if (parentCommand) - sLog.outError("Subcommand '%s' of command '%s' have handler and subcommands in same time, must be used '' subcommand for handler instead.", - command->Name, parentCommand->Name); - else - sLog.outError("First level command '%s' have handler and subcommands in same time, must be used '' subcommand for handler instead.", - command->Name); - } - - if (parentCommand && strlen(command->Name) == 0) - sLog.outError("Subcommand '' of command '%s' have subcommands", parentCommand->Name); - - CheckIntegrity(command->ChildCommands, command); - } - else if (!command->Handler) - { - if (parentCommand) - sLog.outError("Subcommand '%s' of command '%s' not have handler and subcommands in same time. Must have some from its!", - command->Name, parentCommand->Name); - else - sLog.outError("First level command '%s' not have handler and subcommands in same time. Must have some from its!", - command->Name); - } - } -} - -/** - * Search (sub)command for command line available for chat handler access level - * - * @param text Command line string that will parsed for (sub)command search - * - * @return Pointer to found command structure or NULL if appropriate command not found - */ -ChatCommand const* ChatHandler::FindCommand(char const* text) -{ - ChatCommand* command = nullptr; - char const* textPtr = text; - - return FindCommand(getCommandTable(), textPtr, command) == CHAT_COMMAND_OK ? command : NULL; -} - -/** - * Search (sub)command for command line available for chat handler access level with options and fail case additional info - * - * @param table Pointer to command C-style array first level command where will be searched - * @param text Command line string that will parsed for (sub)command search, - * it modified at return from function and pointed to not parsed tail - * @param command At success this is found command, at other cases this is last found parent command - * before subcommand search fail - * @param parentCommand Output arg for optional return parent command for command arg. - * @param cmdNamePtr Output arg for optional return last parsed command name. - * @param allAvailable Optional arg (with false default value) control use command access level checks while command search. - * @param exactlyName Optional arg (with false default value) control use exactly name in checks while command search. - * - * @return one from enum value of ChatCommandSearchResult. Output args return values highly dependent from this return result: - * - * CHAT_COMMAND_OK - Command found! - * text point to non parsed tail with possible command specific data, command store found command pointer, - * parentCommand have parent of found command or NULL if command found in table array directly - * cmdNamePtr store found command name in original form from command line - * CHAT_COMMAND_UNKNOWN - Command not found in table directly - * text only skip possible whitespaces, - * command is NULL - * parentCommand is NULL - * cmdNamePtr store command name that not found as it extracted from command line - * CHAT_COMMAND_UNKNOWN_SUBCOMMAND - Subcommand not found in some deed subcomand lists - * text point to non parsed tail including not found command name in command line, - * command store last found parent command if any - * parentCommand have parent of command in command arg or NULL - * cmdNamePtr store command name that not found as it extracted from command line - */ -ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* &text, ChatCommand*& command, ChatCommand** parentCommand /*= NULL*/, std::string* cmdNamePtr /*= NULL*/, bool allAvailable /*= false*/, bool exactlyName /*= false*/) -{ - std::string cmd = ""; - - // skip whitespaces - while (*text != ' ' && *text != '\0') - { - cmd += *text; - ++text; - } - - while (*text == ' ') ++text; - - // search first level command in table - for (uint32 i = 0; table[i].Name != nullptr; ++i) - { - if (exactlyName) - { - size_t len = strlen(table[i].Name); - if (strncmp(table[i].Name, cmd.c_str(), len + 1) != 0) - continue; - } - else - { - if (!hasStringAbbr(table[i].Name, cmd.c_str())) - continue; - } - // select subcommand from child commands list - if (table[i].ChildCommands != nullptr) - { - char const* oldchildtext = text; - ChatCommand* parentSubcommand = nullptr; - ChatCommandSearchResult res = FindCommand(table[i].ChildCommands, text, command, &parentSubcommand, cmdNamePtr, allAvailable, exactlyName); - - switch (res) - { - case CHAT_COMMAND_OK: - { - // if subcommand success search not return parent command, then this parent command is owner of child commands - if (parentCommand) - *parentCommand = parentSubcommand ? parentSubcommand : &table[i]; - - // Name == "" is special case: restore original command text for next level "" (where parentSubcommand==NULL) - if (strlen(command->Name) == 0 && !parentSubcommand) - text = oldchildtext; - - return CHAT_COMMAND_OK; - } - case CHAT_COMMAND_UNKNOWN: - { - // command not found directly in child command list, return child command list owner - command = &table[i]; - if (parentCommand) - *parentCommand = nullptr; // we don't known parent of table list at this point - - text = oldchildtext; // restore text to stated just after parse found parent command - return CHAT_COMMAND_UNKNOWN_SUBCOMMAND; // we not found subcommand for table[i] - } - case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: - default: - { - // some deep subcommand not found, if this second level subcommand then parentCommand can be NULL, use known value for it - if (parentCommand) - *parentCommand = parentSubcommand ? parentSubcommand : &table[i]; - return res; - } - } - } - - // must be available (not checked for subcommands case because parent command expected have most low access that all subcommands always - if (!allAvailable && !isAvailable(table[i])) - continue; - - // must be have handler is explicitly selected - if (!table[i].Handler) - continue; - - // command found directly in to table - command = &table[i]; - - // unknown table owner at this point - if (parentCommand) - *parentCommand = nullptr; - - if (cmdNamePtr) - *cmdNamePtr = cmd; - - return CHAT_COMMAND_OK; - } - - // command not found in table directly - command = nullptr; - - // unknown table owner at this point - if (parentCommand) - *parentCommand = nullptr; - - if (cmdNamePtr) - *cmdNamePtr = cmd; - - return CHAT_COMMAND_UNKNOWN; -} - -/** - * Execute (sub)command available for chat handler access level with options in command line string - * - * @param text Command line string that will parsed for (sub)command search and command specific data - * - * Command output and errors in command execution will send to chat handler. - */ -void ChatHandler::ExecuteCommand(const char* text) -{ - std::string fullcmd = text; // original `text` can't be used. It content destroyed in command code processing. - - ChatCommand* command = nullptr; - ChatCommand* parentCommand = nullptr; - - ChatCommandSearchResult res = FindCommand(getCommandTable(), text, command, &parentCommand); - - switch (res) - { - case CHAT_COMMAND_OK: - { - std::string realCommandFull = command->FullName; - - if (command->server == NODE) - ForwardCommandToNode(); - else if (command->server == MSTR) - ForwardCommandToMaster(); - - if (text[0]) - { - realCommandFull += " "; - realCommandFull += text; - } - if (m_session && command->Flags & COMMAND_FLAGS_ONLY_ON_SELF) - { - ObjectGuid selGuid = m_session->GetPlayer()->GetSelectionGuid(); - if (!selGuid.IsEmpty() && selGuid != m_session->GetPlayer()->GetObjectGuid()) - { - PSendSysMessage("|cFF8DE2FFYou can use the command [%s] only on yourself|r", command->FullName.c_str()); - return; - } - } - SetSentErrorMessage(false); - if ((this->*(command->Handler))((char*)text)) // text content destroyed at call - { - if (m_session && command->Flags & COMMAND_FLAGS_CRITICAL) - { - if (Unit* target = getSelectedUnit()) - sLog.out(LOG_GM_CRITICAL, "%s: %s. Selected %s. Map %u", m_session->GetUsername().c_str(), realCommandFull.c_str(), target->GetObjectGuid().GetString().c_str(), target->GetMapId()); - else - sLog.out(LOG_GM_CRITICAL, "%s: %s.", m_session->GetUsername().c_str(), realCommandFull.c_str()); - } - if (command->SecurityLevel > SEC_PLAYER) - { - // chat case - if (m_session && m_session->GetPlayer()) - { - Player* p = m_session->GetPlayer(); - ObjectGuid sel_guid = p->GetSelectionGuid(); - sLog.outCommand(GetAccountId(), "Command: %s [Player: %s (Group Leader \"%s\", Account: %u) X: %f Y: %f Z: %f Map: %u Selected: %s]", - realCommandFull.c_str(), p->GetName(), p->GetGroup() ? p->GetGroup()->GetLeaderGuid().GetString().c_str() : "NULL", GetAccountId(), p->GetPositionX(), p->GetPositionY(), p->GetPositionZ(), p->GetMapId(), - sel_guid.GetString().c_str()); - } - else // 0 account -> console - { - sLog.outCommand(GetAccountId(), "Command: %s [Account: %u from %s]", - realCommandFull.c_str(), GetAccountId(), GetAccountId() ? "RA-connection" : "Console"); - } - } - } - // some commands have custom error messages. Don't send the default one in these cases. - else if (!HasSentErrorMessage()) - { - if (!command->Help.empty()) - SendSysMessage(command->Help.c_str()); - else - SendSysMessage(LANG_CMD_SYNTAX); - - if (ChatCommand* showCommand = (strlen(command->Name) == 0 && parentCommand ? parentCommand : command)) - if (ChatCommand* childs = showCommand->ChildCommands) - ShowHelpForSubCommands(childs, showCommand->Name); - - SetSentErrorMessage(true); - } - break; - } - case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: - { - SendSysMessage(LANG_NO_SUBCMD); - ShowHelpForCommand(command->ChildCommands, text); - SetSentErrorMessage(true); - break; - } - case CHAT_COMMAND_UNKNOWN: - { - SendSysMessage(LANG_NO_CMD); - SetSentErrorMessage(true); - break; - } - } -} - -/** - * Function find appropriate command and update command security level and help text - * - * @param commandTable Table for first level command search - * @param text Command line string that will parsed for (sub)command search - * @param security New security level for command - * @param help New help text for command - * - * @return true if command has been found, and false in other case - * - * All problems found while command search and updated output as to DB errors log - */ -bool ChatHandler::SetDataForCommandInTable(ChatCommand *commandTable, const char* text, uint32 security, std::string const& help, uint32 flags) -{ - std::string fullcommand = text; // original `text` can't be used. It content destroyed in command code processing. - - ChatCommand* command = nullptr; - std::string cmdName; - - ChatCommandSearchResult res = FindCommand(commandTable, text, command, nullptr, &cmdName, true, true); - - switch (res) - { - case CHAT_COMMAND_OK: - { - if (command->SecurityLevel != security) - DETAIL_LOG("Table `command` overwrite for command '%s' default security (%u) by %u", - fullcommand.c_str(), command->SecurityLevel, security); - - command->SecurityLevel = security; - command->Help = help; - command->Flags = flags; - return true; - } - case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: - { - // command have subcommands, but not '' subcommand and then any data in `command` useless for it. - if (cmdName.empty()) - sLog.outErrorDb("Table `command` have command '%s' that only used with some subcommand selection, it can't have help or overwritten access level, skip.", cmdName.c_str()); - else - sLog.outErrorDb("Table `command` have unexpected subcommand '%s' in command '%s', skip.", cmdName.c_str(), fullcommand.c_str()); - return false; - } - case CHAT_COMMAND_UNKNOWN: - { - sLog.outErrorDb("Table `command` have nonexistent command '%s', skip.", cmdName.c_str()); - return false; - } - } - - return false; -} - -bool ChatHandler::ParseCommands(const char* text) -{ - MANGOS_ASSERT(text); - MANGOS_ASSERT(*text); - - //if(m_session->GetSecurity() == SEC_PLAYER) - // return false; - - /// chat case (.command or !command format) - if (m_session) - { - if (text[0] != '!' && text[0] != '.') - return false; - - /// ignore single . and ! in line - if (strlen(text) < 2) - return false; - } - - /// ignore messages staring from many dots. - if ((text[0] == '.' && text[1] == '.') || (text[0] == '!' && text[1] == '!')) - return false; - - /// skip first . or ! (in console allowed use command with . and ! and without its) - if (text[0] == '!' || text[0] == '.') - ++text; - - ExecuteCommand(text); - - return true; -} - -bool ChatHandler::ShowHelpForSubCommands(ChatCommand *table, char const* cmd) -{ - std::string list; - for (uint32 i = 0; table[i].Name != nullptr; ++i) - { - // must be available (ignore handler existence for show command with possible available subcommands - if (!isAvailable(table[i])) - continue; - - if (m_session) - list += "\n "; - else - list += "\n\r "; - - list += table[i].Name; - - if (table[i].ChildCommands) - list += " ..."; - } - - if (list.empty()) - return false; - - if (table == getCommandTable()) - { - SendSysMessage(LANG_AVIABLE_CMD); - SendSysMessage(list.c_str()); - } - else - { - PSendSysMessage(LANG_SUBCMDS_LIST, cmd); - SendSysMessage(list.c_str()); - } - return true; -} - -bool ChatHandler::ShowHelpForCommand(ChatCommand *table, const char* cmd) -{ - char const* oldCmd = cmd; - ChatCommand* command = nullptr; - ChatCommand* parentCommand = nullptr; - - ChatCommand* showCommand = nullptr; - ChatCommand* childCommands = nullptr; - - ChatCommandSearchResult res = FindCommand(table, cmd, command, &parentCommand); - - switch (res) - { - case CHAT_COMMAND_OK: - { - // for "" subcommand use parent command if any for subcommands list output - if (strlen(command->Name) == 0 && parentCommand) - showCommand = parentCommand; - else - showCommand = command; - - childCommands = showCommand->ChildCommands; - break; - } - case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: - showCommand = command; - childCommands = showCommand->ChildCommands; - break; - case CHAT_COMMAND_UNKNOWN: - // not show command list at error in first level command find fail - childCommands = table != getCommandTable() || strlen(oldCmd) == 0 ? table : NULL; - command = nullptr; - break; - } - - if (command && !command->Help.empty()) - SendSysMessage(command->Help.c_str()); - - if (childCommands) - if (ShowHelpForSubCommands(childCommands, showCommand ? showCommand->Name : "")) - return true; - - if (command && command->Help.empty()) - SendSysMessage(LANG_NO_HELP_CMD); - - return command || childCommands; -} - -bool ChatHandler::isValidChatMessage(const char* message) -{ - /* - - valid examples: - |cffa335ee|Hitem:812:0:0:0:0:0:0:0:70|h[Glowing Brightwood Staff]|h|r - |cff808080|Hquest:2278:47|h[The Platinum Discs]|h|r - |cff4e96f7|Htalent:2232:-1|h[Taste for Blood]|h|r - |cff71d5ff|Hspell:21563|h[Command]|h|r - |cffffd000|Henchant:3919|h[Engineering: Rough Dynamite]|h|r - - | will be escaped to || - */ - - if (strlen(message) > 255) - return false; - - const char validSequence[6] = "cHhhr"; - const char* validSequenceIterator = validSequence; - - // more simple checks - if (sWorld.getConfig(CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY) < 3) - { - const std::string validCommands = "cHhr|"; - - while (*message) - { - // find next pipe command - message = strchr(message, '|'); - - if (!message) - return true; - - ++message; - char commandChar = *message; - if (validCommands.find(commandChar) == std::string::npos) - return false; - - ++message; - // validate sequence - if (sWorld.getConfig(CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY) == 2) - { - if (commandChar == *validSequenceIterator) - { - if (validSequenceIterator == validSequence + 4) - validSequenceIterator = validSequence; - else - ++validSequenceIterator; - } - else if (commandChar != '|') - return false; - } - } - return true; - } - - std::istringstream reader(message); - char buffer[256]; - - uint32 color = 0; - - ItemPrototype const* linkedItem = nullptr; - Quest const* linkedQuest = nullptr; - SpellEntry const *linkedSpell = nullptr; - ItemRandomPropertiesEntry const* itemProperty = nullptr; - - while (!reader.eof()) - { - if (validSequence == validSequenceIterator) - { - linkedItem = nullptr; - linkedQuest = nullptr; - linkedSpell = nullptr; - itemProperty = nullptr; - - reader.ignore(255, '|'); - } - else if (reader.get() != '|') - { - DEBUG_LOG("ChatHandler::isValidChatMessage sequence aborted unexpectedly"); - return false; - } - - // pipe has always to be followed by at least one char - if (reader.peek() == '\0') - { - DEBUG_LOG("ChatHandler::isValidChatMessage pipe followed by \\0"); - return false; - } - - // no further pipe commands - if (reader.eof()) - break; - - char commandChar; - reader >> commandChar; - - // | in normal messages is escaped by || - if (commandChar != '|') - { - if (commandChar == *validSequenceIterator) - { - if (validSequenceIterator == validSequence + 4) - validSequenceIterator = validSequence; - else - ++validSequenceIterator; - } - else - { - DEBUG_LOG("ChatHandler::isValidChatMessage invalid sequence, expected %c but got %c", *validSequenceIterator, commandChar); - return false; - } - } - else if (validSequence != validSequenceIterator) - { - // no escaped pipes in sequences - DEBUG_LOG("ChatHandler::isValidChatMessage got escaped pipe in sequence"); - return false; - } - - switch (commandChar) - { - case 'c': - color = 0; - // validate color, expect 8 hex chars - for (int i = 0; i < 8; i++) - { - char c; - reader >> c; - if (!c) - { - DEBUG_LOG("ChatHandler::isValidChatMessage got \\0 while reading color in |c command"); - return false; - } - - color <<= 4; - // check for hex char - if (c >= '0' && c <= '9') - { - color |= c - '0'; - continue; - } - if (c >= 'a' && c <= 'f') - { - color |= 10 + c - 'a'; - continue; - } - DEBUG_LOG("ChatHandler::isValidChatMessage got non hex char '%c' while reading color", c); - return false; - } - break; - case 'H': - // read chars up to colon = link type - reader.getline(buffer, 256, ':'); - if (reader.eof()) // : must be - return false; - - if (strcmp(buffer, "item") == 0) - { - // read item entry - reader.getline(buffer, 256, ':'); - if (reader.eof()) // : must be - return false; - - linkedItem = ObjectMgr::GetItemPrototype(atoi(buffer)); - if (!linkedItem) - { - DEBUG_LOG("ChatHandler::isValidChatMessage got invalid itemID %u in |item command", atoi(buffer)); - return false; - } - - if (color != ItemQualityColors[linkedItem->Quality]) - { - DEBUG_LOG("ChatHandler::isValidChatMessage linked item has color %u, but user claims %u", ItemQualityColors[linkedItem->Quality], - color); - return false; - } - - // the itementry is followed by several integers which describe an instance of this item - - // position relative after itemEntry - const uint8 randomPropertyPosition = 6; - - int32 propertyId = 0; - bool negativeNumber = false; - char c; - for (uint8 i = 0; i < randomPropertyPosition; ++i) - { - propertyId = 0; - negativeNumber = false; - while ((c = reader.get()) != ':') - { - if (c >= '0' && c <= '9') - { - propertyId *= 10; - propertyId += c - '0'; - } - else if (c == '-') - negativeNumber = true; - else - return false; - } - } - if (negativeNumber) - propertyId *= -1; - - if (propertyId > 0) - { - itemProperty = sItemRandomPropertiesStore.LookupEntry(propertyId); - if (!itemProperty) - return false; - } - - // ignore other integers - while ((c >= '0' && c <= '9') || c == ':') - { - reader.ignore(1); - c = reader.peek(); - } - } - else if (strcmp(buffer, "quest") == 0) - { - // no color check for questlinks, each client will adapt it anyway - uint32 questid = 0; - // read questid - char c = reader.peek(); - while (c >= '0' && c <= '9') - { - reader.ignore(1); - questid *= 10; - questid += c - '0'; - c = reader.peek(); - } - - linkedQuest = sObjectMgr.GetQuestTemplate(questid); - - if (!linkedQuest) - { - DEBUG_LOG("ChatHandler::isValidChatMessage Questtemplate %u not found", questid); - return false; - } - - if (c != ':') - { - DEBUG_LOG("ChatHandler::isValidChatMessage Invalid quest link structure"); - return false; - } - - reader.ignore(1); - c = reader.peek(); - // level - uint32 questlevel = 0; - while (c >= '0' && c <= '9') - { - reader.ignore(1); - questlevel *= 10; - questlevel += c - '0'; - c = reader.peek(); - } - - if (questlevel >= STRONG_MAX_LEVEL) - { - DEBUG_LOG("ChatHandler::isValidChatMessage Quest level %u too big", questlevel); - return false; - } - - if (c != '|') - { - DEBUG_LOG("ChatHandler::isValidChatMessage Invalid quest link structure"); - return false; - } - } - else if (strcmp(buffer, "talent") == 0) - { - // talent links are always supposed to be blue - if (color != CHAT_LINK_COLOR_TALENT) - return false; - - // read talent entry - reader.getline(buffer, 256, ':'); - if (reader.eof()) // : must be - return false; - - TalentEntry const *talentInfo = sTalentStore.LookupEntry(atoi(buffer)); - if (!talentInfo) - return false; - - linkedSpell = sSpellMgr.GetSpellEntry(talentInfo->RankID[0]); - if (!linkedSpell) - return false; - - char c = reader.peek(); - // skillpoints? whatever, drop it - while (c != '|' && c != '\0') - { - reader.ignore(1); - c = reader.peek(); - } - } - else if (strcmp(buffer, "spell") == 0) - { - if (color != CHAT_LINK_COLOR_SPELL) - return false; - - uint32 spellid = 0; - // read spell entry - char c = reader.peek(); - while (c >= '0' && c <= '9') - { - reader.ignore(1); - spellid *= 10; - spellid += c - '0'; - c = reader.peek(); - } - linkedSpell = sSpellMgr.GetSpellEntry(spellid); - if (!linkedSpell) - return false; - } - else if (strcmp(buffer, "enchant") == 0) - { - if (color != CHAT_LINK_COLOR_ENCHANT) - return false; - - uint32 spellid = 0; - // read spell entry - char c = reader.peek(); - while (c >= '0' && c <= '9') - { - reader.ignore(1); - spellid *= 10; - spellid += c - '0'; - c = reader.peek(); - } - linkedSpell = sSpellMgr.GetSpellEntry(spellid); - if (!linkedSpell) - return false; - } - else - { - DEBUG_LOG("ChatHandler::isValidChatMessage user sent unsupported link type '%s'", buffer); - return false; - } - break; - case 'h': - // if h is next element in sequence, this one must contain the linked text :) - if (*validSequenceIterator == 'h') - { - // links start with '[' - if (reader.get() != '[') - { - DEBUG_LOG("ChatHandler::isValidChatMessage link caption doesn't start with '['"); - return false; - } - reader.getline(buffer, 256, ']'); - if (reader.eof()) // ] must be - return false; - - // verify the link name - if (linkedSpell) - { - // spells with that flag have a prefix of "$PROFESSION: " - if (linkedSpell->Attributes & SPELL_ATTR_TRADESPELL) - { - // lookup skillid - SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(linkedSpell->Id); - if (bounds.first == bounds.second) - return false; - - SkillLineAbilityEntry const *skillInfo = bounds.first->second; - - if (!skillInfo) - return false; - - SkillLineEntry const *skillLine = sSkillLineStore.LookupEntry(skillInfo->skillId); - if (!skillLine) - return false; - - for (uint8 i = 0; i < MAX_DBC_LOCALE; ++i) - { - uint32 skillLineNameLength = strlen(skillLine->name[i]); - if (skillLineNameLength > 0 && strncmp(skillLine->name[i], buffer, skillLineNameLength) == 0) - { - // found the prefix, remove it to perform spellname validation below - // -2 = strlen(": ") - uint32 spellNameLength = strlen(buffer) - skillLineNameLength - 2; - memmove(buffer, buffer + skillLineNameLength + 2, spellNameLength + 1); - } - } - } - bool foundName = false; - for (uint8 i = 0; i < MAX_DBC_LOCALE; ++i) - { - if (*linkedSpell->SpellName[i] && strcmp(linkedSpell->SpellName[i], buffer) == 0) - { - foundName = true; - break; - } - } - if (!foundName) - return false; - } - else if (linkedQuest) - { - if (linkedQuest->GetTitle() != buffer) - { - QuestLocale const *ql = sObjectMgr.GetQuestLocale(linkedQuest->GetQuestId()); - - if (!ql) - { - DEBUG_LOG("ChatHandler::isValidChatMessage default questname didn't match and there is no locale"); - return false; - } - - bool foundName = false; - for (uint8 i = 0; i < ql->Title.size(); i++) - { - if (ql->Title[i] == buffer) - { - foundName = true; - break; - } - } - if (!foundName) - { - DEBUG_LOG("ChatHandler::isValidChatMessage no quest locale title matched"); - return false; - } - } - } - else if (linkedItem) - { - std::string expectedName = std::string(linkedItem->Name1); - - if (expectedName != buffer) - { - ItemLocale const *il = sObjectMgr.GetItemLocale(linkedItem->ItemId); - - bool foundName = false; - for (uint8 i = LOCALE_koKR; i < MAX_LOCALE; ++i) - { - int8 dbIndex = sObjectMgr.GetIndexForLocale(LocaleConstant(i)); - if (dbIndex == -1 || il == nullptr || (size_t)dbIndex >= il->Name.size()) - // using strange database/client combinations can lead to this case - expectedName = linkedItem->Name1; - else - expectedName = il->Name[dbIndex]; - - if (expectedName == buffer) - { - foundName = true; - break; - } - } - if (!foundName) - { - DEBUG_LOG("ChatHandler::isValidChatMessage linked item name wasn't found in any localization"); - return false; - } - } - } - // that place should never be reached - if nothing linked has been set in |H - // it will return false before - else - return false; - } - break; - case 'r': - case '|': - // no further payload - break; - default: - DEBUG_LOG("ChatHandler::isValidChatMessage got invalid command |%c", commandChar); - return false; - } - } - - // check if every opened sequence was also closed properly - if (validSequence != validSequenceIterator) - DEBUG_LOG("ChatHandler::isValidChatMessage EOF in active sequence"); - - return validSequence == validSequenceIterator; -} - -//Note: target_guid used only in CHAT_MSG_WHISPER_INFORM mode (in this case channelName ignored) -void ChatHandler::FillMessageData(WorldPacket *data, WorldSession* session, uint8 type, uint32 language, const char *channelName, ObjectGuid targetGuid, const char *message, Unit *speaker) -{ - uint32 messageLength = (message ? strlen(message) : 0) + 1; - - data->Initialize(SMSG_MESSAGECHAT, 100); // guess size - *data << uint8(type); - if ((type != CHAT_MSG_CHANNEL && type != CHAT_MSG_WHISPER) || language == LANG_ADDON) - *data << uint32(language); - else - *data << uint32(LANG_UNIVERSAL); - - if (type == CHAT_MSG_CHANNEL) - { - MANGOS_ASSERT(channelName); - *data << channelName; - } - - switch (type) - { - case CHAT_MSG_SAY: - case CHAT_MSG_PARTY: - case CHAT_MSG_RAID: - case CHAT_MSG_GUILD: - case CHAT_MSG_OFFICER: - case CHAT_MSG_YELL: - case CHAT_MSG_WHISPER: - case CHAT_MSG_CHANNEL: - case CHAT_MSG_RAID_LEADER: - case CHAT_MSG_RAID_WARNING: - case CHAT_MSG_BG_SYSTEM_NEUTRAL: - case CHAT_MSG_BG_SYSTEM_ALLIANCE: - case CHAT_MSG_BG_SYSTEM_HORDE: - case CHAT_MSG_BATTLEGROUND: - case CHAT_MSG_BATTLEGROUND_LEADER: - targetGuid = session ? session->GetPlayer()->GetObjectGuid() : ObjectGuid(); - break; - case CHAT_MSG_MONSTER_SAY: - case CHAT_MSG_MONSTER_PARTY: - case CHAT_MSG_MONSTER_YELL: - case CHAT_MSG_MONSTER_WHISPER: - case CHAT_MSG_MONSTER_EMOTE: -// case CHAT_MSG_RAID_BOSS_WHISPER: // Nostalrius : Pas en 1.12 - case CHAT_MSG_RAID_BOSS_EMOTE: - { - // Nostalrius : fix structure - switch (type) - { - case CHAT_MSG_MONSTER_EMOTE: - case CHAT_MSG_RAID_BOSS_EMOTE: - case CHAT_MSG_MONSTER_WHISPER: - break; - default: - *data << ObjectGuid(speaker->GetObjectGuid()); - } - *data << uint32(strlen(speaker->GetName()) + 1); - *data << speaker->GetName(); - ObjectGuid listener_guid; - *data << listener_guid; - if (listener_guid && !listener_guid.IsPlayer()) - { - *data << uint32(1); // string listener_name_length - *data << uint8(0); // string listener_name - } - *data << uint32(messageLength); - *data << message; - *data << uint8(0); - return; - } - default: - if (type != CHAT_MSG_REPLY && type != CHAT_MSG_IGNORED && type != CHAT_MSG_DND && type != CHAT_MSG_AFK) - targetGuid.Clear(); // only for CHAT_MSG_WHISPER_INFORM used original value target_guid - break; - } - - *data << ObjectGuid(targetGuid); // there 0 for BG messages - if (type == CHAT_MSG_SAY || type == CHAT_MSG_YELL || type == CHAT_MSG_PARTY) - *data << ObjectGuid(targetGuid); - *data << uint32(messageLength); - *data << message; - if (session != nullptr && type != CHAT_MSG_REPLY && type != CHAT_MSG_DND && type != CHAT_MSG_AFK) - *data << uint8(session->GetPlayer()->chatTag()); - else - *data << uint8(0); -} - -Player * ChatHandler::getSelectedPlayer() -{ - if (!m_session) - return nullptr; - - ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid(); - - if (!guid) - return m_session->GetPlayer(); - - return sObjectMgr.GetPlayer(guid); -} - -Unit* ChatHandler::getSelectedUnit() -{ - if (!m_session) - return nullptr; - - ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid(); - - if (!guid) - return m_session->GetPlayer(); - - // can be selected player at another map - return ObjectAccessor::GetUnit(*m_session->GetPlayer(), guid); -} - -Creature* ChatHandler::getSelectedCreature() -{ - if (!m_session) - return nullptr; - - return m_session->GetPlayer()->GetMap()->GetAnyTypeCreature(m_session->GetPlayer()->GetSelectionGuid()); -} - -/** - * Function skip all whitespaces in args string - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * allowed NULL string pointer stored in *args - */ -void ChatHandler::SkipWhiteSpaces(char** args) -{ - if (!*args) - return; - - while (isWhiteSpace(**args)) - ++(*args); -} - -/** - * Function extract to val arg signed integer value or fail - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @return true if value extraction successful - */ -bool ChatHandler::ExtractInt32(char** args, int32& val) -{ - if (!*args || !**args) - return false; - - char* tail = *args; - - long valRaw = strtol(*args, &tail, 10); - - if (tail != *args && isWhiteSpace(*tail)) - *(tail++) = '\0'; - else if (tail && *tail) // some not whitespace symbol - return false; // args not modified and can be re-parsed - - if (valRaw < std::numeric_limits::min() || valRaw > std::numeric_limits::max()) - return false; - - // value successfully extracted - val = int32(valRaw); - *args = tail; - return true; -} - -/** - * Function extract to val arg optional signed integer value or use default value. Fail if extracted not signed integer. - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @param defVal default value used if no data for extraction in args - * @return true if value extraction successful - */ -bool ChatHandler::ExtractOptInt32(char** args, int32& val, int32 defVal) -{ - if (!*args || !**args) - { - val = defVal; - return true; - } - - return ExtractInt32(args, val); -} - -/** - * Function extract to val arg unsigned integer value or fail - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @param base set used base for extracted value format (10 for decimal, 16 for hex, etc), 0 let auto select by system internal function - * @return true if value extraction successful - */ -bool ChatHandler::ExtractUInt32Base(char** args, uint32& val, uint32 base) -{ - if (!*args || !**args) - return false; - - char* tail = *args; - - unsigned long valRaw = strtoul(*args, &tail, base); - - if (tail != *args && isWhiteSpace(*tail)) - *(tail++) = '\0'; - else if (tail && *tail) // some not whitespace symbol - return false; // args not modified and can be re-parsed - - if (valRaw > std::numeric_limits::max()) - return false; - - // value successfully extracted - val = uint32(valRaw); - *args = tail; - - SkipWhiteSpaces(args); - return true; -} - -/** - * Function extract to val arg optional unsigned integer value or use default value. Fail if extracted not unsigned integer. - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @param defVal default value used if no data for extraction in args - * @return true if value extraction successful - */ -bool ChatHandler::ExtractOptUInt32(char** args, uint32& val, uint32 defVal) -{ - if (!*args || !**args) - { - val = defVal; - return true; - } - - return ExtractUInt32(args, val); -} - -/** - * Function extract to val arg float value or fail - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @return true if value extraction successful - */ -bool ChatHandler::ExtractFloat(char** args, float& val) -{ - if (!*args || !**args) - return false; - - char* tail = *args; - - double valRaw = strtod(*args, &tail); - - if (tail != *args && isWhiteSpace(*tail)) - *(tail++) = '\0'; - else if (tail && *tail) // some not whitespace symbol - return false; // args not modified and can be re-parsed - - // value successfully extracted - val = float(valRaw); - *args = tail; - - SkipWhiteSpaces(args); - return true; -} - -/** - * Function extract to val arg optional float value or use default value. Fail if extracted not float. - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @param defVal default value used if no data for extraction in args - * @return true if value extraction successful - */ -bool ChatHandler::ExtractOptFloat(char** args, float& val, float defVal) -{ - if (!*args || !**args) - { - val = defVal; - return true; - } - - return ExtractFloat(args, val); -} - -/** - * Function extract name-like string (from non-numeric or special symbol until whitespace) - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param lit optional explicit literal requirement. function fail if literal is not starting substring of lit. - * Note: function in same way fail if no any literal or literal not fit in this case. Need additional check for select specific fail case - * @return name/number-like string without whitespaces, or NULL if args empty or not appropriate content. - */ -char* ChatHandler::ExtractLiteralArg(char** args, char const* lit /*= NULL*/) -{ - if (!*args || !**args) - return nullptr; - - char* head = *args; - - // reject quoted string or link (|-started text) - switch (head[0]) - { - // reject quoted string - case '[': - case '\'': - case '"': - return nullptr; - // reject link (|-started text) - case '|': - // client replace all | by || in raw text - if (head[1] != '|') - return nullptr; - ++head; // skip one | - break; - default: - break; - } - - if (lit) - { - int l = strlen(lit); - int diff = strncmp(head, lit, l); - - if (diff != 0) - return nullptr; - - if (head[l] && !isWhiteSpace(head[l])) - return nullptr; - - char* arg = head; - - if (head[l]) - { - head[l] = '\0'; - - head += l + 1; - - *args = head; - } - else - *args = head + l; - - SkipWhiteSpaces(args); - return arg; - } - - char* name = strtok(head, " "); - - char* tail = strtok(nullptr, ""); - - *args = tail ? tail : (char*)""; // *args don't must be NULL - - SkipWhiteSpaces(args); - - return name; -} - -/** - * Function extract quote-like string (any characters guarded by some special character, in our cases ['") - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param asis control save quote string wrappers - * @return quote-like string, or NULL if args empty or not appropriate content. - */ -char* ChatHandler::ExtractQuotedArg(char** args, bool asis /*= false*/) -{ - if (!*args || !**args) - return nullptr; - - if (**args != '\'' && **args != '"' && **args != '[') - return nullptr; - - char guard = (*args)[0]; - - if (guard == '[') - guard = ']'; - - char* tail = (*args) + 1; // start scan after first quote symbol - char* head = asis ? *args : tail; // start arg - - while (*tail && *tail != guard) - ++tail; - - if (!*tail || (tail[1] && !isWhiteSpace(tail[1]))) // fail - return nullptr; - - if (!tail[1]) // quote is last char in string - { - if (!asis) - *tail = '\0'; - } - else // quote isn't last char - { - if (asis) - ++tail; - - *tail = '\0'; - } - - *args = tail + 1; - - SkipWhiteSpaces(args); - - return head; -} - -/** - * Function extract quote-like string or literal if quote not detected - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param asis control save quote string wrappers - * @return quote/literal string, or NULL if args empty or not appropriate content. - */ -char* ChatHandler::ExtractQuotedOrLiteralArg(char** args, bool asis /*= false*/) -{ - char *arg = ExtractQuotedArg(args, asis); - if (!arg) - arg = ExtractLiteralArg(args); - return arg; -} - -/** - * Function extract on/off literals as boolean values - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param val return extracted value if function success, in fail case original value unmodified - * @return true at success - */ -bool ChatHandler::ExtractOnOff(char** args, bool& value) -{ - char* arg = ExtractLiteralArg(args); - if (!arg) - return false; - - if (strncmp(arg, "on", 3) == 0 || strncmp(arg, "ON", 3) == 0) - value = true; - else if (strncmp(arg, "off", 4) == 0 || strncmp(arg, "OFF", 4) == 0) - value = false; - else - return false; - - return true; -} - -/** - * Function extract shift-link-like string (any characters guarded by | and |h|r with some additional internal structure check) - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * - * @param linkTypes optional NULL-terminated array of link types, shift-link must fit one from link type from array if provided or extraction fail - * - * @param found_idx if not NULL then at return index in linkTypes that fit shift-link type, if extraction fail then non modified - * - * @param keyPair if not NULL then pointer to 2-elements array for return start and end pointer for found key - * if extraction fail then non modified - * - * @param somethingPair then pointer to 2-elements array for return start and end pointer if found. - * if not NULL then shift-link must have data field, if extraction fail then non modified - * - * @return shift-link-like string, or NULL if args empty or not appropriate content. - */ -char* ChatHandler::ExtractLinkArg(char** args, char const* const* linkTypes /*= NULL*/, int* foundIdx /*= NULL*/, char** keyPair /*= NULL*/, char** somethingPair /*= NULL*/) -{ - if (!*args || !**args) - return nullptr; - - // skip if not linked started or encoded single | (doubled by client) - if ((*args)[0] != '|' || (*args)[1] == '|') - return nullptr; - - // |color|Hlinktype:key:data...|h[name]|h|r - - char* head = *args; - - // [name] Shift-click form |color|linkType:key|h[name]|h|r - // or - // [name] Shift-click form |color|linkType:key:something1:...:somethingN|h[name]|h|r - // or - // [name] Shift-click form |linkType:key|h[name]|h|r - - // |color|Hlinktype:key:data...|h[name]|h|r - - char* tail = (*args) + 1; // skip | - - if (*tail != 'H') // skip color part, some links can not have color part - { - while (*tail && *tail != '|') - ++tail; - - if (!*tail) - return nullptr; - - // |Hlinktype:key:data...|h[name]|h|r - - ++tail; // skip | - } - - // Hlinktype:key:data...|h[name]|h|r - - if (*tail != 'H') - return nullptr; - - int linktype_idx = 0; - - if (linkTypes) // check link type if provided - { - // check linktypes (its include H in name) - for (; linkTypes[linktype_idx]; ++linktype_idx) - { - // exactly string with follow : or | - int l = strlen(linkTypes[linktype_idx]); - if (strncmp(tail, linkTypes[linktype_idx], l) == 0 && - (tail[l] == ':' || tail[l] == '|')) - break; - } - - // is search fail? - if (!linkTypes[linktype_idx]) // NULL terminator in last element - return nullptr; - - tail += strlen(linkTypes[linktype_idx]); // skip linktype string - - // :key:data...|h[name]|h|r - - if (*tail != ':') - return nullptr; - } - else - { - while (*tail && *tail != ':') // skip linktype string - ++tail; - - if (!*tail) - return nullptr; - } - - ++tail; - - // key:data...|h[name]|h|r - char* keyStart = tail; // remember key start for return - char* keyEnd = tail; // key end for truncate, will updated - - while (*tail && *tail != '|' && *tail != ':') - ++tail; - - if (!*tail) - return nullptr; - - keyEnd = tail; // remember key end for truncate - - // |h[name]|h|r or :something...|h[name]|h|r - - char* somethingStart = tail + 1; - char* somethingEnd = tail + 1; // will updated later if need - - if (*tail == ':' && somethingPair) // optional data extraction - { - // :something...|h[name]|h|r - - if (*tail == ':') - ++tail; - - // something|h[name]|h|r or something:something2...|h[name]|h|r - - while (*tail && *tail != '|' && *tail != ':') - ++tail; - - if (!*tail) - return nullptr; - - somethingEnd = tail; // remember data end for truncate - } - - // |h[name]|h|r or :something2...|h[name]|h|r - - while (*tail && (*tail != '|' || *(tail + 1) != 'h')) // skip ... part if exist - ++tail; - - if (!*tail) - return nullptr; - - // |h[name]|h|r - - tail += 2; // skip |h - - // [name]|h|r - if (!*tail || *tail != '[') - return nullptr; - - while (*tail && (*tail != ']' || *(tail + 1) != '|')) // skip name part - ++tail; - - tail += 2; // skip ]| - - // h|r - if (!*tail || *tail != 'h' || *(tail + 1) != '|') - return nullptr; - - tail += 2; // skip h| - - // r - if (!*tail || *tail != 'r' || (*(tail + 1) && !isWhiteSpace(*(tail + 1)))) - return nullptr; - - ++tail; // skip r - - // success - - if (*tail) // truncate all link string - *(tail++) = '\0'; - - if (foundIdx) - *foundIdx = linktype_idx; - - if (keyPair) - { - keyPair[0] = keyStart; - keyPair[1] = keyEnd; - } - - if (somethingPair) - { - somethingPair[0] = somethingStart; - somethingPair[1] = somethingEnd; - } - - *args = tail; - - SkipWhiteSpaces(args); - - return head; -} - -/** - * Function extract name/number/quote/shift-link-like string - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * @param asis control save quote string wrappers - * @return extracted arg string, or NULL if args empty or not appropriate content. - */ -char* ChatHandler::ExtractArg(char** args, bool asis /*= false*/) -{ - if (!*args || !**args) - return nullptr; - - char* arg = ExtractQuotedOrLiteralArg(args, asis); - if (!arg) - arg = ExtractLinkArg(args); - - return arg; -} - -/** - * Function extract name/quote/number/shift-link-like string, and return it if args have more non-whitespace data - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * if args have only single arg then args still pointing to this arg (unmodified pointer) - * @return extracted string, or NULL if args empty or not appropriate content or have single arg totally. - */ -char* ChatHandler::ExtractOptNotLastArg(char** args) -{ - char* arg = ExtractArg(args, true); - - // have more data - if (*args && **args) - return arg; - - // optional name not found - *args = arg ? arg : (char*)""; // *args don't must be NULL - - return nullptr; -} - -/** - * Function extract data from shift-link "|color|LINKTYPE:RETURN:SOMETHING1|h[name]|h|r if linkType == LINKTYPE - * It also extract literal/quote if not shift-link in args - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * if args have sift link with linkType != LINKTYPE then args still pointing to this arg (unmodified pointer) - * - * @param linkType shift-link must fit by link type to this arg value or extraction fail - * - * @param something1 if not NULL then shift-link must have data field and it returned into this arg - * if extraction fail then non modified - * - * @return extracted key, or NULL if args empty or not appropriate content or not fit to linkType. - */ -char* ChatHandler::ExtractKeyFromLink(char** text, char const* linkType, char** something1 /*= NULL*/) -{ - char const* linkTypes[2]; - linkTypes[0] = linkType; - linkTypes[1] = nullptr; - - int foundIdx; - - return ExtractKeyFromLink(text, linkTypes, &foundIdx, something1); -} - -/** - * Function extract data from shift-link "|color|LINKTYPE:RETURN:SOMETHING1|h[name]|h|r if LINKTYPE in linkTypes array - * It also extract literal/quote if not shift-link in args - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * if args have sift link with linkType != LINKTYPE then args still pointing to this arg (unmodified pointer) - * - * @param linkTypes NULL-terminated array of link types, shift-link must fit one from link type from array or extraction fail - * - * @param found_idx if not NULL then at return index in linkTypes that fit shift-link type, for non-link case return -1 - * if extraction fail then non modified - * - * @param something1 if not NULL then shift-link must have data field and it returned into this arg - * if extraction fail then non modified - * - * @return extracted key, or NULL if args empty or not appropriate content or not fit to linkType. - */ -char* ChatHandler::ExtractKeyFromLink(char** text, char const* const* linkTypes, int* found_idx, char** something1 /*= NULL*/) -{ - // skip empty - if (!*text || !**text) - return nullptr; - - // return non link case - char* arg = ExtractQuotedOrLiteralArg(text); - if (arg) - { - if (found_idx) - *found_idx = -1; // special index case - - return arg; - } - - char* keyPair[2]; - char* somethingPair[2]; - - arg = ExtractLinkArg(text, linkTypes, found_idx, keyPair, something1 ? somethingPair : NULL); - if (!arg) - return nullptr; - - *keyPair[1] = '\0'; // truncate key string - - if (something1) - { - *somethingPair[1] = '\0'; // truncate data string - *something1 = somethingPair[0]; - } - - return keyPair[0]; -} - -/** - * Function extract uint32 key from shift-link "|color|LINKTYPE:RETURN|h[name]|h|r if linkType == LINKTYPE - * It also extract direct number if not shift-link in args - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * if args have sift link with linkType != LINKTYPE then args still pointing to this arg (unmodified pointer) - * - * @param linkType shift-link must fit by link type to this arg value or extraction fail - * - * @param value store result value at success return, not modified at fail - * - * @return true if extraction succesful - */ -bool ChatHandler::ExtractUint32KeyFromLink(char** text, char const* linkType, uint32& value) -{ - char* arg = ExtractKeyFromLink(text, linkType); - if (!arg) - return false; - - return ExtractUInt32(&arg, value); -} - -GameObject* ChatHandler::GetGameObjectWithGuid(uint32 lowguid, uint32 entry) -{ - if (!m_session) - return nullptr; - - Player* pl = m_session->GetPlayer(); - - return pl->GetMap()->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, entry, lowguid)); -} - -enum SpellLinkType -{ - SPELL_LINK_RAW = -1, // non-link case - SPELL_LINK_SPELL = 0, - SPELL_LINK_TALENT = 1, - SPELL_LINK_ENCHANT = 2, -}; - -static char const* const spellKeys[] = -{ - "Hspell", // normal spell - "Htalent", // talent spell - "Henchant", // enchanting recipe spell - nullptr -}; - -uint32 ChatHandler::ExtractSpellIdFromLink(char** text) -{ - // number or [name] Shift-click form |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r - // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r - // number or [name] Shift-click form |color|Htalent:talent_id,rank|h[name]|h|r - int type; - char* param1_str = nullptr; - char* idS = ExtractKeyFromLink(text, spellKeys, &type, ¶m1_str); - if (!idS) - return 0; - - uint32 id; - if (!ExtractUInt32(&idS, id)) - return 0; - - switch (type) - { - case SPELL_LINK_RAW: - case SPELL_LINK_SPELL: - case SPELL_LINK_ENCHANT: - return id; - case SPELL_LINK_TALENT: - { - // talent - TalentEntry const* talentEntry = sTalentStore.LookupEntry(id); - if (!talentEntry) - return 0; - - int32 rank; - if (!ExtractInt32(¶m1_str, rank)) - return 0; - - if (rank < 0) // unlearned talent have in shift-link field -1 as rank - rank = 0; - - return rank < MAX_TALENT_RANK ? talentEntry->RankID[rank] : 0; - } - } - - // unknown type? - return 0; -} - -GameTele const* ChatHandler::ExtractGameTeleFromLink(char** text) -{ - // id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r - char* cId = ExtractKeyFromLink(text, "Htele"); - if (!cId) - return nullptr; - - // id case (explicit or from shift link) - uint32 id; - if (ExtractUInt32(&cId, id)) - return sObjectMgr.GetGameTele(id); - else - return sObjectMgr.GetGameTele(cId); -} - -enum GuidLinkType -{ - GUID_LINK_RAW = -1, // non-link case - GUID_LINK_PLAYER = 0, - GUID_LINK_CREATURE = 1, - GUID_LINK_GAMEOBJECT = 2, -}; - -static char const* const guidKeys[] = -{ - "Hplayer", - "Hcreature", - "Hgameobject", - nullptr -}; - -ObjectGuid ChatHandler::ExtractGuidFromLink(char** text) -{ - int type = 0; - - // |color|Hcreature:creature_guid|h[name]|h|r - // |color|Hgameobject:go_guid|h[name]|h|r - // |color|Hplayer:name|h[name]|h|r - char* idS = ExtractKeyFromLink(text, guidKeys, &type); - if (!idS) - return ObjectGuid(); - - switch (type) - { - case GUID_LINK_RAW: - case GUID_LINK_PLAYER: - { - std::string name = idS; - if (!normalizePlayerName(name)) - return ObjectGuid(); - - if (Player* player = sObjectMgr.GetPlayer(name.c_str())) - return player->GetObjectGuid(); - - return sObjectMgr.GetPlayerGuidByName(name); - } - case GUID_LINK_CREATURE: - { - uint32 lowguid; - if (!ExtractUInt32(&idS, lowguid)) - return ObjectGuid(); - - if (CreatureData const* data = sObjectMgr.GetCreatureData(lowguid)) - return data->GetObjectGuid(lowguid); - else - return ObjectGuid(); - } - case GUID_LINK_GAMEOBJECT: - { - uint32 lowguid; - if (!ExtractUInt32(&idS, lowguid)) - return ObjectGuid(); - - if (GameObjectData const* data = sObjectMgr.GetGOData(lowguid)) - return ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, lowguid); - else - return ObjectGuid(); - } - } - - // unknown type? - return ObjectGuid(); -} - -enum LocationLinkType -{ - LOCATION_LINK_RAW = -1, // non-link case - LOCATION_LINK_PLAYER = 0, - LOCATION_LINK_TELE = 1, - LOCATION_LINK_TAXINODE = 2, - LOCATION_LINK_CREATURE = 3, - LOCATION_LINK_GAMEOBJECT = 4, - LOCATION_LINK_CREATURE_ENTRY = 5, - LOCATION_LINK_GAMEOBJECT_ENTRY = 6, - LOCATION_LINK_AREATRIGGER = 7, - LOCATION_LINK_AREATRIGGER_TARGET = 8, -}; - -static char const* const locationKeys[] = -{ - "Htele", - "Htaxinode", - "Hplayer", - "Hcreature", - "Hgameobject", - "Hcreature_entry", - "Hgameobject_entry", - "Hareatrigger", - "Hareatrigger_target", - nullptr -}; - -bool ChatHandler::ExtractLocationFromLink(char** text, uint32& mapid, float& x, float& y, float& z) -{ - int type = 0; - - // |color|Hplayer:name|h[name]|h|r - // |color|Htele:id|h[name]|h|r - // |color|Htaxinode:id|h[name]|h|r - // |color|Hcreature:creature_guid|h[name]|h|r - // |color|Hgameobject:go_guid|h[name]|h|r - // |color|Hcreature_entry:creature_id|h[name]|h|r - // |color|Hgameobject_entry:go_id|h[name]|h|r - // |color|Hareatrigger:id|h[name]|h|r - // |color|Hareatrigger_target:id|h[name]|h|r - char* idS = ExtractKeyFromLink(text, locationKeys, &type); - if (!idS) - return false; - - switch (type) - { - case LOCATION_LINK_RAW: - case LOCATION_LINK_PLAYER: - { - std::string name = idS; - if (!normalizePlayerName(name)) - return false; - - if (Player* player = sObjectMgr.GetPlayer(name.c_str())) - { - mapid = player->GetMapId(); - x = player->GetPositionX(); - y = player->GetPositionY(); - z = player->GetPositionZ(); - return true; - } - - if (ObjectGuid guid = sObjectMgr.GetPlayerGuidByName(name)) - { - // to point where player stay (if loaded) - float o; - bool in_flight; - return Player::LoadPositionFromDB(guid, mapid, x, y, z, o, in_flight); - } - - return false; - } - case LOCATION_LINK_TELE: - { - uint32 id; - if (!ExtractUInt32(&idS, id)) - return false; - - GameTele const* tele = sObjectMgr.GetGameTele(id); - if (!tele) - return false; - mapid = tele->mapId; - x = tele->position_x; - y = tele->position_y; - z = tele->position_z; - return true; - } - case LOCATION_LINK_TAXINODE: - { - uint32 id; - if (!ExtractUInt32(&idS, id)) - return false; - - TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id); - if (!node) - return false; - mapid = node->map_id; - x = node->x; - y = node->y; - z = node->z; - return true; - } - case LOCATION_LINK_CREATURE: - { - uint32 lowguid; - if (!ExtractUInt32(&idS, lowguid)) - return false; - - if (CreatureData const* data = sObjectMgr.GetCreatureData(lowguid)) - { - mapid = data->mapid; - x = data->posX; - y = data->posY; - z = data->posZ; - return true; - } - else - return false; - } - case LOCATION_LINK_GAMEOBJECT: - { - uint32 lowguid; - if (!ExtractUInt32(&idS, lowguid)) - return false; - - if (GameObjectData const* data = sObjectMgr.GetGOData(lowguid)) - { - mapid = data->mapid; - x = data->posX; - y = data->posY; - z = data->posZ; - return true; - } - else - return false; - } - case LOCATION_LINK_CREATURE_ENTRY: - { - uint32 id; - if (!ExtractUInt32(&idS, id)) - return false; - - if (ObjectMgr::GetCreatureTemplate(id)) - { - FindCreatureData worker(id, m_session ? m_session->GetPlayer() : NULL); - - sObjectMgr.DoCreatureData(worker); - - if (CreatureDataPair const* dataPair = worker.GetResult()) - { - mapid = dataPair->second.mapid; - x = dataPair->second.posX; - y = dataPair->second.posY; - z = dataPair->second.posZ; - return true; - } - else - return false; - } - else - return false; - } - case LOCATION_LINK_GAMEOBJECT_ENTRY: - { - uint32 id; - if (!ExtractUInt32(&idS, id)) - return false; - - if (ObjectMgr::GetGameObjectInfo(id)) - { - FindGOData worker(id, m_session ? m_session->GetPlayer() : NULL); - - sObjectMgr.DoGOData(worker); - - if (GameObjectDataPair const* dataPair = worker.GetResult()) - { - mapid = dataPair->second.mapid; - x = dataPair->second.posX; - y = dataPair->second.posY; - z = dataPair->second.posZ; - return true; - } - else - return false; - } - else - return false; - } - case LOCATION_LINK_AREATRIGGER: - { - uint32 id; - if (!ExtractUInt32(&idS, id)) - return false; - - AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(id); - if (!atEntry) - { - PSendSysMessage(LANG_COMMAND_GOAREATRNOTFOUND, id); - SetSentErrorMessage(true); - return false; - } - - mapid = atEntry->mapid; - x = atEntry->x; - y = atEntry->y; - z = atEntry->z; - return true; - } - case LOCATION_LINK_AREATRIGGER_TARGET: - { - uint32 id; - if (!ExtractUInt32(&idS, id)) - return false; - - if (!sAreaTriggerStore.LookupEntry(id)) - { - PSendSysMessage(LANG_COMMAND_GOAREATRNOTFOUND, id); - SetSentErrorMessage(true); - return false; - } - - AreaTrigger const* at = sObjectMgr.GetAreaTrigger(id); - if (!at) - { - PSendSysMessage(LANG_AREATRIGER_NOT_HAS_TARGET, id); - SetSentErrorMessage(true); - return false; - } - - mapid = at->target_mapId; - x = at->target_X; - y = at->target_Y; - z = at->target_Z; - return true; - } - } - - // unknown type? - return false; -} - -std::string ChatHandler::ExtractPlayerNameFromLink(char** text) -{ - // |color|Hplayer:name|h[name]|h|r - char* name_str = ExtractKeyFromLink(text, "Hplayer"); - if (!name_str) - return ""; - - std::string name = name_str; - if (!normalizePlayerName(name)) - return ""; - - return name; -} - -/** - * Function extract at least one from request player data (pointer/guid/name) from args name/shift-link or selected player if no args - * - * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) - * - * @param player optional arg One from 3 optional args must be provided at least (or more). - * @param player_guid optional arg For function success only one from provided args need get result - * @param player_name optional arg But if early arg get value then all later args will have its (if requested) - * if player_guid requested and not found then name also will not found - * So at success can be returned 2 cases: (player/guid/name) or (guid/name) - * - * @return true if extraction successful - */ -bool ChatHandler::ExtractPlayerTarget(char** args, Player** player /*= NULL*/, ObjectGuid* player_guid /*= NULL*/, std::string* player_name /*= NULL*/) -{ - if (*args && **args) - { - std::string name = ExtractPlayerNameFromLink(args); - if (name.empty()) - { - SendSysMessage(LANG_PLAYER_NOT_FOUND); - SetSentErrorMessage(true); - return false; - } - - Player* pl = sObjectMgr.GetPlayer(name.c_str()); - - // if allowed player pointer - if (player) - *player = pl; - - // if need guid value from DB (in name case for check player existence) - ObjectGuid guid = !pl && (player_guid || player_name) ? sObjectMgr.GetPlayerGuidByName(name) : ObjectGuid(); - - // if allowed player guid (if no then only online players allowed) - if (player_guid) - *player_guid = pl ? pl->GetObjectGuid() : guid; - - if (player_name) - *player_name = pl || guid ? name : ""; - } - else - { - Player* pl = getSelectedPlayer(); - // if allowed player pointer - if (player) - *player = pl; - // if allowed player guid (if no then only online players allowed) - if (player_guid) - *player_guid = pl ? pl->GetObjectGuid() : ObjectGuid(); - - if (player_name) - *player_name = pl ? pl->GetName() : ""; - } - - // some from req. data must be provided (note: name is empty if player not exist) - if ((!player || !*player) && (!player_guid || !*player_guid) && (!player_name || player_name->empty())) - { - SendSysMessage(LANG_PLAYER_NOT_FOUND); - SetSentErrorMessage(true); - return false; - } - - return true; -} - -uint32 ChatHandler::ExtractAccountId(char** args, std::string* accountName /*= NULL*/, Player** targetIfNullArg /*= NULL*/) -{ - uint32 account_id = 0; - - ///- Get the account name from the command line - char* account_str = ExtractLiteralArg(args); - - if (!account_str) - { - if (!targetIfNullArg) - return 0; - - /// only target player different from self allowed (if targetPlayer!=NULL then not console) - Player* targetPlayer = getSelectedPlayer(); - if (!targetPlayer) - return 0; - - account_id = targetPlayer->GetSession()->GetAccountId(); - - if (accountName) - sAccountMgr.GetName(account_id, *accountName); - - if (targetIfNullArg) - *targetIfNullArg = targetPlayer; - - return account_id; - } - - std::string account_name; - - if (ExtractUInt32(&account_str, account_id)) - { - if (!sAccountMgr.GetName(account_id, account_name)) - { - PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_str); - SetSentErrorMessage(true); - return 0; - } - } - else - { - account_name = account_str; - if (!AccountMgr::normalizeString(account_name)) - { - PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); - SetSentErrorMessage(true); - return 0; - } - - account_id = sAccountMgr.GetId(account_name); - if (!account_id) - { - PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); - SetSentErrorMessage(true); - return 0; - } - } - - if (accountName) - *accountName = account_name; - - if (targetIfNullArg) - *targetIfNullArg = nullptr; - - return account_id; -} - -struct RaceMaskName -{ - char const* literal; - uint32 raceMask; -}; - -static RaceMaskName const raceMaskNames[] = -{ - // races - { "human", (1 << (RACE_HUMAN - 1)) }, - { "orc", (1 << (RACE_ORC - 1)) }, - { "dwarf", (1 << (RACE_DWARF - 1)) }, - { "nightelf", (1 << (RACE_NIGHTELF - 1))}, - { "undead", (1 << (RACE_UNDEAD - 1)) }, - { "tauren", (1 << (RACE_TAUREN - 1)) }, - { "gnome", (1 << (RACE_GNOME - 1)) }, - { "troll", (1 << (RACE_TROLL - 1)) }, - - // masks - { "alliance", RACEMASK_ALLIANCE }, - { "horde", RACEMASK_HORDE }, - { "all", RACEMASK_ALL_PLAYABLE }, - - // terminator - {nullptr, 0 } -}; - -bool ChatHandler::ExtractRaceMask(char** text, uint32& raceMask, char const** maskName /*=NULL*/) -{ - if (ExtractUInt32(text, raceMask)) - { - if (maskName) - *maskName = "custom mask"; - } - else - { - for (RaceMaskName const* itr = raceMaskNames; itr->literal; ++itr) - { - if (ExtractLiteralArg(text, itr->literal)) - { - raceMask = itr->raceMask; - - if (maskName) - *maskName = itr->literal; - break; - } - } - - if (!raceMask) - return false; - } - - return true; -} - -std::string ChatHandler::GetNameLink(Player* chr) const -{ - return playerLink(chr->GetName()); -} - -std::string ChatHandler::GetItemLink(ItemPrototype const* pItem) const -{ - return m_session ? "|cffffffff|Hitem:" + std::to_string(pItem->ItemId) + ":0:0:0:0:0:0:0|h[" + pItem->Name1 + "]|h|r" : pItem->Name1; -} - -bool ChatHandler::needReportToTarget(Player* chr) const -{ - Player* pl = m_session->GetPlayer(); - return pl != chr && pl->IsVisibleGloballyFor(chr); -} - -LocaleConstant ChatHandler::GetSessionDbcLocale() const -{ - return m_session->GetSessionDbcLocale(); -} - -int ChatHandler::GetSessionDbLocaleIndex() const -{ - return m_session->GetSessionDbLocaleIndex(); -} - -const char *CliHandler::GetMangosString(int32 entry) const -{ - return sObjectMgr.GetMangosStringForDBCLocale(entry); -} - -uint32 CliHandler::GetAccountId() const -{ - return m_accountId; -} - -AccountTypes CliHandler::GetAccessLevel() const -{ - return m_loginAccessLevel; -} - -bool CliHandler::isAvailable(ChatCommand const& cmd) const -{ - // skip non-console commands in console case - if (!cmd.AllowConsole) - return false; - - // normal case - return GetAccessLevel() >= (AccountTypes)cmd.SecurityLevel; -} - -void CliHandler::SendSysMessage(const char *str) -{ - m_print(m_callbackArg, str); - m_print(m_callbackArg, "\r\n"); -} - -std::string CliHandler::GetNameLink() const -{ - return GetMangosString(LANG_CONSOLE_COMMAND); -} - -bool CliHandler::needReportToTarget(Player* /*chr*/) const -{ - return true; -} - -LocaleConstant CliHandler::GetSessionDbcLocale() const -{ - return sWorld.GetDefaultDbcLocale(); -} - -int CliHandler::GetSessionDbLocaleIndex() const -{ - return sObjectMgr.GetDBCLocaleIndex(); -} - -// Check/ Output if a NPC or GO (by guid) is part of a pool or game event -template -void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid) -{ - if (uint16 pool_id = sPoolMgr.IsPartOfAPool(guid)) - { - uint16 top_pool_id = sPoolMgr.IsPartOfTopPool(pool_id); - if (!top_pool_id || top_pool_id == pool_id) - PSendSysMessage(LANG_NPC_GO_INFO_POOL, pool_id); - else - PSendSysMessage(LANG_NPC_GO_INFO_TOP_POOL, pool_id, top_pool_id); - - if (int16 event_id = sGameEventMgr.GetGameEventId(top_pool_id)) - { - GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap(); - GameEventData const& eventData = events[std::abs(event_id)]; - - if (event_id > 0) - PSendSysMessage(LANG_NPC_GO_INFO_POOL_GAME_EVENT_S, top_pool_id, std::abs(event_id), eventData.description.c_str()); - else - PSendSysMessage(LANG_NPC_GO_INFO_POOL_GAME_EVENT_D, top_pool_id, std::abs(event_id), eventData.description.c_str()); - } - } - else if (int16 event_id = sGameEventMgr.GetGameEventId(guid)) - { - GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap(); - GameEventData const& eventData = events[std::abs(event_id)]; - - if (event_id > 0) - PSendSysMessage(LANG_NPC_GO_INFO_GAME_EVENT_S, uint32(event_id), eventData.description.c_str()); - else - PSendSysMessage(LANG_NPC_GO_INFO_GAME_EVENT_D, uint32(-event_id), eventData.description.c_str()); - } -} - -// Prepare ShortString for a NPC or GO (by guid) with pool or game event IDs -template -std::string ChatHandler::PrepareStringNpcOrGoSpawnInformation(uint32 guid) -{ - std::string str = ""; - if (uint16 pool_id = sPoolMgr.IsPartOfAPool(guid)) - { - uint16 top_pool_id = sPoolMgr.IsPartOfTopPool(guid); - if (int16 event_id = sGameEventMgr.GetGameEventId(top_pool_id)) - { - char buffer[100]; - const char* format = GetMangosString(LANG_NPC_GO_INFO_POOL_EVENT_STRING); - sprintf(buffer, format, pool_id, event_id); - str = buffer; - } - else - { - char buffer[100]; - const char* format = GetMangosString(LANG_NPC_GO_INFO_POOL_STRING); - sprintf(buffer, format, pool_id); - str = buffer; - } - } - else if (int16 event_id = sGameEventMgr.GetGameEventId(guid)) - { - char buffer[100]; - const char* format = GetMangosString(LANG_NPC_GO_INFO_EVENT_STRING); - sprintf(buffer, format, event_id); - str = buffer; - } - - return str; -} - -void ChatHandler::ForwardCommandToNode() -{ - if (!m_cluster_is_node) - throw ForwardToNode_Exception(); -} - -void ChatHandler::ForwardCommandToMaster() -{ - if (!m_cluster_is_master) - throw ForwardToMaster_Exception(); -} - -// Instantiate template for helper function -template void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid); -template void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid); - -template std::string ChatHandler::PrepareStringNpcOrGoSpawnInformation(uint32 guid); -template std::string ChatHandler::PrepareStringNpcOrGoSpawnInformation(uint32 guid); - - -LocaleConstant NullChatHandler::GetSessionDbcLocale() const -{ - return sWorld.GetDefaultDbcLocale(); -} - -int NullChatHandler::GetSessionDbLocaleIndex() const -{ - return sObjectMgr.GetDBCLocaleIndex(); -} - -const char *NullChatHandler::GetMangosString(int32 entry) const -{ - return sObjectMgr.GetMangosStringForDBCLocale(entry); -} +/* + * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2009-2011 MaNGOSZero + * Copyright (C) 2011-2016 Nostalrius + * Copyright (C) 2016-2017 Elysium Project + * + * 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 + */ + +#include "Chat.h" +#include "Language.h" +#include "Database/DatabaseEnv.h" +#include "WorldPacket.h" +#include "WorldSession.h" +#include "Opcodes.h" +#include "Log.h" +#include "World.h" +#include "ObjectMgr.h" +#include "ObjectGuid.h" +#include "Player.h" +#include "UpdateMask.h" +#include "GridNotifiersImpl.h" +#include "CellImpl.h" +#include "AccountMgr.h" +#include "SpellMgr.h" +#include "PoolManager.h" +#include "GameEventMgr.h" + +// Supported shift-links (client generated and server side) +// |color|Harea:area_id|h[name]|h|r +// |color|Hareatrigger:id|h[name]|h|r +// |color|Hareatrigger_target:id|h[name]|h|r +// |color|Hcreature:creature_guid|h[name]|h|r +// |color|Hcreature_entry:creature_id|h[name]|h|r +// |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r - client, at shift click in recipes list dialog +// |color|Hgameevent:id|h[name]|h|r +// |color|Hgameobject:go_guid|h[name]|h|r +// |color|Hgameobject_entry:go_id|h[name]|h|r +// |color|Hitem:item_id:perm_ench_id:gem1:gem2:gem3:0:0:0:0|h[name]|h|r - client, item icon shift click +// |color|Hitemset:itemset_id|h[name]|h|r +// |color|Hplayer:name|h[name]|h|r - client, in some messages, at click copy only name instead link, so no way generate it in client string send to server +// |color|Hpool:pool_id|h[name]|h|r +// |color|Hquest:quest_id:quest_level|h[name]|h|r - client, quest list name shift-click +// |color|Hskill:skill_id|h[name]|h|r +// |color|Hspell:spell_id|h[name]|h|r - client, spellbook spell icon shift-click +// |color|Htalent:talent_id,rank|h[name]|h|r - client, talent icon shift-click rank==-1 if shift-copy unlearned talent +// |color|Htaxinode:id|h[name]|h|r +// |color|Htele:id|h[name]|h|r + +bool ChatHandler::load_command_table = true; + +ChatCommand * ChatHandler::getCommandTable() +{ + static ChatCommand groupSpellCommandTable[] = + { + { NODE, "add", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGroupAddSpellCommand, "", nullptr}, + { NODE, "rule", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGroupSetRuleCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + static ChatCommand ahbotCommandTable[] = + { + { MSTR, "reload", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAHBotReloadCommand, "Recharger le bot de l'HdV", nullptr}, + { MSTR, "update", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAHBotUpdateCommand, "Ajouter des items en vente", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + static ChatCommand botCommandTable[] = + { + { NODE, "add", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotAddCommand, "", nullptr }, + { NODE, "add_all", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotAddAllCommand, "", nullptr }, + { NODE, "delete", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotDeleteCommand, "", nullptr }, + { NODE, "info", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotInfoCommand, "", nullptr }, + { NODE, "reload", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotReloadCommand, "", nullptr }, + { NODE, "stop", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotStopCommand, "", nullptr }, + { NODE, "start", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotStartCommand, "", nullptr }, + { NODE, "ranadd", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBotAddRandomCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr }, + }; + static ChatCommand accountSetCommandTable[] = + { + { NODE, "addon", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAccountSetAddonCommand, "", nullptr }, + { NODE, "gmlevel", SEC_CONSOLE, true, &ChatHandler::HandleAccountSetGmLevelCommand, "", nullptr }, + { NODE, "password", SEC_CONSOLE, true, &ChatHandler::HandleAccountSetPasswordCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand accountCommandTable[] = + { + { NODE, "characters", SEC_ADMINISTRATOR, true, &ChatHandler::HandleAccountCharactersCommand, "", nullptr }, + { NODE, "create", SEC_CONSOLE, true, &ChatHandler::HandleAccountCreateCommand, "", nullptr }, + { NODE, "delete", SEC_CONSOLE, true, &ChatHandler::HandleAccountDeleteCommand, "", nullptr }, + { NODE, "onlinelist", SEC_CONSOLE, true, &ChatHandler::HandleAccountOnlineListCommand, "", nullptr }, + { NODE, "lock", SEC_PLAYER, true, &ChatHandler::HandleAccountLockCommand, "", nullptr }, + { NODE, "set", SEC_ADMINISTRATOR, true, nullptr, "", accountSetCommandTable }, + { NODE, "password", SEC_PLAYER, true, &ChatHandler::HandleAccountPasswordCommand, "", nullptr }, + { NODE, "", SEC_PLAYER, true, &ChatHandler::HandleAccountCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand auctionCommandTable[] = + { + { NODE, "alliance", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionAllianceCommand, "", nullptr }, + { NODE, "goblin", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionGoblinCommand, "", nullptr }, + { NODE, "horde", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionHordeCommand, "", nullptr }, + { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuctionCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand banCommandTable[] = + { + { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanAccountCommand, "", nullptr }, + { NODE, "allip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanAllIPCommand, "", nullptr }, + { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanCharacterCommand, "", nullptr }, + { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanIPCommand, "", nullptr }, + { NODE, "note", SEC_GAMEMASTER, true, &ChatHandler::HandleAddCharacterNoteCommand, "", nullptr }, + { NODE, "warn", SEC_GAMEMASTER, true, &ChatHandler::HandleWarnCharacterCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand baninfoCommandTable[] = + { + { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanInfoAccountCommand, "", nullptr }, + { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanInfoCharacterCommand, "", nullptr }, + { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanInfoIPCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand banlistCommandTable[] = + { + { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanListAccountCommand, "", nullptr }, + { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanListCharacterCommand, "", nullptr }, + { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleBanListIPCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand castCommandTable[] = + { + { NODE, "back", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastBackCommand, "", nullptr }, + { NODE, "dist", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastDistCommand, "", nullptr }, + { NODE, "self", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastSelfCommand, "", nullptr }, + { NODE, "target", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastTargetCommand, "", nullptr }, + { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCastCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand characterDeletedCommandTable[] = + { + { NODE, "delete", SEC_CONSOLE, true, &ChatHandler::HandleCharacterDeletedDeleteCommand, "", nullptr }, + { NODE, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCharacterDeletedListCommand, "", nullptr }, + { NODE, "restore", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCharacterDeletedRestoreCommand, "", nullptr }, + { NODE, "old", SEC_CONSOLE, true, &ChatHandler::HandleCharacterDeletedOldCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand characterCleanCommandTable[] = + { + { NODE, "todelete", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCleanCharactersToDeleteCommand, "", nullptr }, + { NODE, "items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCleanCharactersItemsCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand characterCommandTable[] = + { + { NODE, "deleted", SEC_GAMEMASTER, true, nullptr, "", characterDeletedCommandTable}, + { NODE, "erase", SEC_CONSOLE, true, &ChatHandler::HandleCharacterEraseCommand, "", nullptr }, + { NODE, "level", SEC_ADMINISTRATOR, true, &ChatHandler::HandleCharacterLevelCommand, "", nullptr }, + { NODE, "rename", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterRenameCommand, "", nullptr }, + { NODE, "reputation", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterReputationCommand, "", nullptr }, + { NODE, "hasitem", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterHasItemCommand, "", nullptr }, + { NODE, "race", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterChangeRaceCommand, "", nullptr }, + { NODE, "skin", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterCopySkinCommand, "", nullptr }, + { NODE, "fillflys", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterFillFlysCommand, "", nullptr }, + { NODE, "flags", SEC_GAMEMASTER, true, &ChatHandler::HandleCharacterFlagsCommand, "", nullptr }, + { NODE, "recup", SEC_ADMINISTRATOR, false, &ChatHandler::HandleRecupCommand, "", nullptr }, + { NODE, "clean", SEC_ADMINISTRATOR, true, nullptr, "", characterCleanCommandTable }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand debugPlayCommandTable[] = + { + { NODE, "cinematic", SEC_MODERATOR, false, &ChatHandler::HandleDebugPlayCinematicCommand, "", nullptr }, + { NODE, "sound", SEC_MODERATOR, false, &ChatHandler::HandleDebugPlaySoundCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand debugLosCommandTable[] = + { + { NODE, "check", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugLoSCommand, "", nullptr }, + { NODE, "allow", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugLoSAllowCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand debugSendCommandTable[] = + { + { NODE, "buyerror", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendBuyErrorCommand, "", nullptr }, + { NODE, "channelnotify", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendChannelNotifyCommand, "", nullptr }, + { NODE, "chatmmessage", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendChatMsgCommand, "", nullptr }, + { NODE, "equiperror", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendEquipErrorCommand, "", nullptr }, + { NODE, "opcode", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendOpcodeCommand, "", nullptr }, + { NODE, "poi", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendPoiCommand, "", nullptr }, + { NODE, "qpartymsg", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendQuestPartyMsgCommand, "", nullptr }, + { NODE, "qinvalidmsg", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendQuestInvalidMsgCommand, "", nullptr }, + { NODE, "sellerror", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendSellErrorCommand, "", nullptr }, + { NODE, "spellfail", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSendSpellFailCommand, "", nullptr }, + { NODE, "visual", SEC_GAMEMASTER, true, &ChatHandler::HandleSendSpellVisualCommand, "", nullptr }, + { NODE, "impact", SEC_GAMEMASTER, true, &ChatHandler::HandleSendSpellImpactCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand debugCommandTable[] = + { + { NODE, "anim", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugAnimCommand, "", nullptr }, + { NODE, "bg", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugBattlegroundCommand, "", nullptr }, + { NODE, "getitemstate", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugGetItemStateCommand, "", nullptr }, + { NODE, "lrecipient", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugGetLootRecipientCommand, "", nullptr }, + { NODE, "getitemvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugGetItemValueCommand, "", nullptr }, + { NODE, "getvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugGetValueCommand, "", nullptr }, + { NODE, "moditemvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugModItemValueCommand, "", nullptr }, + { NODE, "modvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugModValueCommand, "", nullptr }, + { NODE, "play", SEC_MODERATOR, false, nullptr, "", debugPlayCommandTable }, + { NODE, "send", SEC_ADMINISTRATOR, false, nullptr, "", debugSendCommandTable }, + { NODE, "setaurastate", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSetAuraStateCommand, "", nullptr }, + { NODE, "setitemvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSetItemValueCommand, "", nullptr }, + { NODE, "setvalue", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSetValueCommand, "", nullptr }, + { NODE, "spellcheck", SEC_CONSOLE, true, &ChatHandler::HandleDebugSpellCheckCommand, "", nullptr }, + { NODE, "spellcoefs", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugSpellCoefsCommand, "", nullptr }, + { NODE, "spellmods", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugSpellModsCommand, "", nullptr }, + { NODE, "uws", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugUpdateWorldStateCommand, "", nullptr }, + // Nostalrius + { NODE, "update", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugUpdateCommand, "", nullptr }, + { NODE, "forceupdate", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugForceUpdateCommand, "", nullptr }, + { NODE, "los", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugLoSCommand, "", debugLosCommandTable }, + { NODE, "moveto", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMoveToCommand, "", nullptr }, + { NODE, "assert", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugAssertFalseCommand, "", nullptr }, + { NODE, "pvpcredit", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugPvPCreditCommand, "", nullptr }, + { NODE, "unitstate", SEC_GAMEMASTER, false, &ChatHandler::HandleUnitStatCommand, "", nullptr }, + { NODE, "control", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugControlCommand, "", nullptr }, + { NODE, "monster", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMonsterChatCommand, "", nullptr }, + { NODE, "target", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugUnitCommand, "", nullptr }, + { NODE, "time", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugTimeCommand, "", nullptr }, + { NODE, "moveflags", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMoveFlagsCommand, "", nullptr }, + { NODE, "movespline", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugMoveSplineCommand, "", nullptr }, + { NODE, "dump", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugRecvPacketDumpWrite, "", nullptr }, + { NODE, "movemotion", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDebugMoveCommand, "", nullptr }, + { NODE, "factionchange_items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleFactionChangeItemsCommand, "", nullptr }, + { NODE, "loottable", SEC_ADMINISTRATOR, true, &ChatHandler::HandleDebugLootTableCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand eventCommandTable[] = + { + { NODE, "list", SEC_GAMEMASTER, true, &ChatHandler::HandleEventListCommand, "", nullptr }, + { NODE, "start", SEC_GAMEMASTER, true, &ChatHandler::HandleEventStartCommand, "", nullptr }, + { NODE, "stop", SEC_GAMEMASTER, true, &ChatHandler::HandleEventStopCommand, "", nullptr }, + { NODE, "enable", SEC_ADMINISTRATOR, true, &ChatHandler::HandleEventEnableCommand, "", nullptr }, + { NODE, "disable", SEC_ADMINISTRATOR, true, &ChatHandler::HandleEventDisableCommand, "", nullptr }, + { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleEventInfoCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand gmCommandTable[] = + { + { NODE, "chat", SEC_MODERATOR, false, &ChatHandler::HandleGMChatCommand, "", nullptr }, + { NODE, "fly", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGMFlyCommand, "", nullptr }, + { NODE, "ingame", SEC_PLAYER, true, &ChatHandler::HandleGMListIngameCommand, "", nullptr }, + { NODE, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGMListFullCommand, "", nullptr }, + { NODE, "visible", SEC_MODERATOR, false, &ChatHandler::HandleGMVisibleCommand, "", nullptr }, + { NODE, "options", SEC_GAMEMASTER, false, &ChatHandler::HandleGMOptionsCommand, "", nullptr }, + { NODE, "setview", SEC_MODERATOR, false, &ChatHandler::HandleSetViewCommand, "", nullptr }, + { NODE, "", SEC_MODERATOR, false, &ChatHandler::HandleGMCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand goCommandTable[] = + { + { NODE, "creature", SEC_MODERATOR, false, &ChatHandler::HandleGoCreatureCommand, "", nullptr }, + { NODE, "graveyard", SEC_MODERATOR, false, &ChatHandler::HandleGoGraveyardCommand, "", nullptr }, + { NODE, "grid", SEC_MODERATOR, false, &ChatHandler::HandleGoGridCommand, "", nullptr }, + { NODE, "object", SEC_MODERATOR, false, &ChatHandler::HandleGoObjectCommand, "", nullptr }, + { NODE, "taxinode", SEC_MODERATOR, false, &ChatHandler::HandleGoTaxinodeCommand, "", nullptr }, + { NODE, "trigger", SEC_MODERATOR, false, &ChatHandler::HandleGoTriggerCommand, "", nullptr }, + { NODE, "zonexy", SEC_MODERATOR, false, &ChatHandler::HandleGoZoneXYCommand, "", nullptr }, + { NODE, "xy", SEC_MODERATOR, false, &ChatHandler::HandleGoXYCommand, "", nullptr }, + { NODE, "xyz", SEC_MODERATOR, false, &ChatHandler::HandleGoXYZCommand, "", nullptr }, + { NODE, "xyzo", SEC_MODERATOR, false, &ChatHandler::HandleGoXYZOCommand, "", nullptr }, + // Nostalrius + { NODE, "forward", SEC_GAMEMASTER, false, &ChatHandler::HandleGoForwardCommand, "", nullptr }, + { NODE, "up", SEC_GAMEMASTER, false, &ChatHandler::HandleGoUpCommand, "", nullptr }, + { NODE, "relative", SEC_GAMEMASTER, false, &ChatHandler::HandleGoRelativeCommand, "", nullptr }, + // Battleground join + { NODE, "warsong", SEC_PLAYER, false, &ChatHandler::HandleGoWarsongCommand, "", nullptr }, + { NODE, "arathi", SEC_PLAYER, false, &ChatHandler::HandleGoArathiCommand, "", nullptr }, + { NODE, "alterac", SEC_PLAYER, false, &ChatHandler::HandleGoAlteracCommand, "", nullptr }, + { NODE, "", SEC_MODERATOR, false, &ChatHandler::HandleGoCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand gobjectCommandTable[] = + { + { NODE, "add", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectAddCommand, "", nullptr }, + { NODE, "tmpadd", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectTempAddCommand, "", nullptr }, + { NODE, "delete", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectDeleteCommand, "", nullptr }, + { NODE, "move", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectMoveCommand, "", nullptr }, + { NODE, "near", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectNearCommand, "", nullptr }, + { NODE, "target", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectTargetCommand, "", nullptr }, + { NODE, "turn", SEC_GAMEMASTER, false, &ChatHandler::HandleGameObjectTurnCommand, "", nullptr }, + { NODE, "select", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectSelectCommand, "", nullptr }, + { NODE, "despawn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectDespawnCommand, "", nullptr }, + { NODE, "toggle", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectToggleCommand, "", nullptr }, + { NODE, "reset", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectResetCommand, "", nullptr }, + { NODE, "respawn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGameObjectRespawnCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand guildCommandTable[] = + { + { NODE, "create", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildCreateCommand, "", nullptr }, + { NODE, "delete", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildDeleteCommand, "", nullptr }, + { NODE, "invite", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildInviteCommand, "", nullptr }, + { NODE, "uninvite", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildUninviteCommand, "", nullptr }, + { NODE, "rank", SEC_GAMEMASTER, true, &ChatHandler::HandleGuildRankCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand honorCommandTable[] = + { + { NODE, "add", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHonorAddCommand, "", nullptr }, + { NODE, "addkill", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHonorAddKillCommand, "", nullptr }, + { NODE, "show", SEC_GAMEMASTER, false, &ChatHandler::HandleHonorShow, "", nullptr }, + { NODE, "debug", SEC_ADMINISTRATOR, true, &ChatHandler::HandleHonorDebugScoresCommand, "", nullptr }, + { NODE, "setrp", SEC_ADMINISTRATOR, true, &ChatHandler::HandleHonorSetRPCommand, "", nullptr }, + { NODE, "reset", SEC_ADMINISTRATOR, true, &ChatHandler::HandleHonorResetCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand instanceCommandTable[] = + { + { NODE, "continents", SEC_ADMINISTRATOR, true, &ChatHandler::HandleInstanceContinentsCommand, "", nullptr }, + { NODE, "listbinds", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceListBindsCommand, "", nullptr }, + { NODE, "unbind", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceUnbindCommand, "", nullptr }, + { NODE, "stats", SEC_ADMINISTRATOR, true, &ChatHandler::HandleInstanceStatsCommand, "", nullptr }, + { NODE, "savedata", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceSaveDataCommand, "", nullptr }, + { NODE, "switch", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstanceSwitchCommand, "", nullptr }, + { NODE, "perfinfos", SEC_ADMINISTRATOR, false, &ChatHandler::HandleInstancePerfInfosCommand, "", nullptr }, + { NODE, "smartrebind", SEC_MODERATOR, false, &ChatHandler::HandleInstanceBindingMode, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand learnCommandTable[] = + { + { NODE, "all", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllCommand, "", nullptr }, + { NODE, "all_gm", SEC_GAMEMASTER, false, &ChatHandler::HandleLearnAllGMCommand, "", nullptr }, + { NODE, "all_crafts", SEC_GAMEMASTER, false, &ChatHandler::HandleLearnAllCraftsCommand, "", nullptr }, + { NODE, "all_default", SEC_MODERATOR, false, &ChatHandler::HandleLearnAllDefaultCommand, "", nullptr }, + { NODE, "all_lang", SEC_MODERATOR, false, &ChatHandler::HandleLearnAllLangCommand, "", nullptr }, + { NODE, "all_myclass", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllMyClassCommand, "", nullptr }, + { NODE, "all_myspells", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllMySpellsCommand, "", nullptr }, + { NODE, "all_mytalents", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnAllMyTalentsCommand, "", nullptr }, + { NODE, "all_recipes", SEC_GAMEMASTER, false, &ChatHandler::HandleLearnAllRecipesCommand, "", nullptr }, + { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLearnCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand listCommandTable[] = + { + { NODE, "auras", SEC_ADMINISTRATOR, false, &ChatHandler::HandleListAurasCommand, "", nullptr }, + { NODE, "creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleListCreatureCommand, "", nullptr }, + { NODE, "item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleListItemCommand, "", nullptr }, + { NODE, "object", SEC_ADMINISTRATOR, true, &ChatHandler::HandleListObjectCommand, "", nullptr }, + { NODE, "talents", SEC_ADMINISTRATOR, false, &ChatHandler::HandleListTalentsCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand lookupAccountCommandTable[] = + { + { NODE, "email", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountEmailCommand, "", nullptr }, + { NODE, "ip", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountIpCommand, "", nullptr }, + { NODE, "iponline", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountIponlineCommand, "", nullptr }, + { NODE, "name", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupAccountNameCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand lookupPlayerCommandTable[] = + { + { NODE, "account", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerAccountCommand, "", nullptr }, + { NODE, "email", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerEmailCommand, "", nullptr }, + { NODE, "ip", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerIpCommand, "", nullptr }, + { NODE, "name", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPlayerNameCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand lookupCommandTable[] = + { + { NODE, "account", SEC_GAMEMASTER, true, nullptr, "", lookupAccountCommandTable }, + { NODE, "area", SEC_MODERATOR, true, &ChatHandler::HandleLookupAreaCommand, "", nullptr }, + { NODE, "creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupCreatureCommand, "", nullptr }, + { NODE, "event", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupEventCommand, "", nullptr }, + { NODE, "faction", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupFactionCommand, "", nullptr }, + { NODE, "item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupItemCommand, "", nullptr }, + { NODE, "itemset", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupItemSetCommand, "", nullptr }, + { NODE, "object", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupObjectCommand, "", nullptr }, + { NODE, "quest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupQuestCommand, "", nullptr }, + { NODE, "player", SEC_GAMEMASTER, true, nullptr, "", lookupPlayerCommandTable }, + { NODE, "pool", SEC_GAMEMASTER, true, &ChatHandler::HandleLookupPoolCommand, "", nullptr }, + { NODE, "skill", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupSkillCommand, "", nullptr }, + { NODE, "spell", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupSpellCommand, "", nullptr }, + { NODE, "taxinode", SEC_ADMINISTRATOR, true, &ChatHandler::HandleLookupTaxiNodeCommand, "", nullptr }, + { NODE, "tele", SEC_MODERATOR, true, &ChatHandler::HandleLookupTeleCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand modifyCommandTable[] = + { + { NODE, "hp", SEC_MODERATOR, false, &ChatHandler::HandleModifyHPCommand, "", nullptr }, + { NODE, "mana", SEC_MODERATOR, false, &ChatHandler::HandleModifyManaCommand, "", nullptr }, + { NODE, "rage", SEC_MODERATOR, false, &ChatHandler::HandleModifyRageCommand, "", nullptr }, + { NODE, "energy", SEC_MODERATOR, false, &ChatHandler::HandleModifyEnergyCommand, "", nullptr }, + { NODE, "money", SEC_MODERATOR, false, &ChatHandler::HandleModifyMoneyCommand, "", nullptr }, + { NODE, "speed", SEC_MODERATOR, false, &ChatHandler::HandleModifySpeedCommand, "", nullptr }, + { NODE, "swim", SEC_MODERATOR, false, &ChatHandler::HandleModifySwimCommand, "", nullptr }, + { NODE, "scale", SEC_MODERATOR, false, &ChatHandler::HandleModifyScaleCommand, "", nullptr }, + { NODE, "bwalk", SEC_MODERATOR, false, &ChatHandler::HandleModifyBWalkCommand, "", nullptr }, + { NODE, "aspeed", SEC_MODERATOR, false, &ChatHandler::HandleModifyASpeedCommand, "", nullptr }, + { NODE, "faction", SEC_MODERATOR, false, &ChatHandler::HandleModifyFactionCommand, "", nullptr }, + { NODE, "tp", SEC_MODERATOR, false, &ChatHandler::HandleModifyTalentCommand, "", nullptr }, + { NODE, "mount", SEC_MODERATOR, false, &ChatHandler::HandleModifyMountCommand, "", nullptr }, + { NODE, "honor", SEC_MODERATOR, false, &ChatHandler::HandleModifyHonorCommand, "", nullptr }, + { NODE, "rep", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRepCommand, "", nullptr }, + { NODE, "drunk", SEC_MODERATOR, false, &ChatHandler::HandleModifyDrunkCommand, "", nullptr }, + { NODE, "standstate", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyStandStateCommand, "", nullptr }, + { NODE, "morph", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMorphCommand, "", nullptr }, + { NODE, "gender", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyGenderCommand, "", nullptr }, + { NODE, "strength", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyStrengthCommand, "", nullptr }, + { NODE, "agility", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyAgilityCommand, "", nullptr }, + { NODE, "stamina", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyStaminaCommand, "", nullptr }, + { NODE, "intellect", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyIntellectCommand, "", nullptr }, + { NODE, "spirit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifySpiritCommand, "", nullptr }, + { NODE, "armor", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyArmorCommand, "", nullptr }, + { NODE, "holy", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyHolyCommand, "", nullptr }, + { NODE, "fire", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyFireCommand, "", nullptr }, + { NODE, "nature", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyNatureCommand, "", nullptr }, + { NODE, "frost", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyFrostCommand, "", nullptr }, + { NODE, "shadow", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyShadowCommand, "", nullptr }, + { NODE, "arcane", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyArcaneCommand, "", nullptr }, + { NODE, "ap", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMeleeApCommand, "", nullptr }, + { NODE, "rangeap", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRangedApCommand, "", nullptr }, + { NODE, "spellpower", SEC_GAMEMASTER, false, &ChatHandler::HandleModifySpellPowerCommand, "", nullptr }, + { NODE, "crit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMeleeCritCommand, "", nullptr }, + { NODE, "rangecrit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRangedCritCommand, "", nullptr }, + { NODE, "spellcrit", SEC_GAMEMASTER, false, &ChatHandler::HandleModifySpellCritCommand, "", nullptr }, + { NODE, "mainspeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyMainSpeedCommand, "", nullptr }, + { NODE, "offspeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyOffSpeedCommand, "", nullptr }, + { NODE, "rangespeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyRangedSpeedCommand, "", nullptr }, + { NODE, "castspeed", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyCastSpeedCommand, "", nullptr }, + { NODE, "block", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyBlockCommand, "", nullptr }, + { NODE, "dodge", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyDodgeCommand, "", nullptr }, + { NODE, "parry", SEC_GAMEMASTER, false, &ChatHandler::HandleModifyParryCommand, "", nullptr }, + { NODE, "cr", SEC_ADMINISTRATOR, false, &ChatHandler::HandleModifyCrCommand, "", nullptr }, + { NODE, "br", SEC_ADMINISTRATOR, false, &ChatHandler::HandleModifyBrCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand creatureGroupsCommandTable[] = + { + { NODE, "add", SEC_MODERATOR, false, &ChatHandler::HandleNpcGroupAddCommand, "", nullptr }, + { NODE, "del", SEC_MODERATOR, false, &ChatHandler::HandleNpcGroupDelCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand npcCommandTable[] = + { + { NODE, "add", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAddCommand, "", nullptr }, + { NODE, "additem", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAddVendorItemCommand, "", nullptr }, + { NODE, "addmove", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAddMoveCommand, "", nullptr }, + { NODE, "aiinfo", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcAIInfoCommand, "", nullptr }, + { NODE, "allowmove", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcAllowMovementCommand, "", nullptr }, + { NODE, "changeentry", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcChangeEntryCommand, "", nullptr }, + { NODE, "changelevel", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcChangeLevelCommand, "", nullptr }, + { NODE, "delete", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcDeleteCommand, "", nullptr }, + { NODE, "delitem", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcDelVendorItemCommand, "", nullptr }, + { NODE, "factionid", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcFactionIdCommand, "", nullptr }, + { NODE, "flag", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcFlagCommand, "", nullptr }, + { NODE, "follow", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcFollowCommand, "", nullptr }, + { NODE, "info", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcInfoCommand, "", nullptr }, + { NODE, "move", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcMoveCommand, "", nullptr }, + { NODE, "playemote", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcPlayEmoteCommand, "", nullptr }, + { NODE, "setmodel", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSetModelCommand, "", nullptr }, + { NODE, "setmovetype", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSetMoveTypeCommand, "", nullptr }, + { NODE, "spawndist", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSpawnDistCommand, "", nullptr }, + { NODE, "spawntime", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSpawnTimeCommand, "", nullptr }, + { NODE, "say", SEC_MODERATOR, false, &ChatHandler::HandleNpcSayCommand, "", nullptr }, + { NODE, "summon", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSummonCommand, "", nullptr }, + { NODE, "textemote", SEC_MODERATOR, false, &ChatHandler::HandleNpcTextEmoteCommand, "", nullptr }, + { NODE, "unfollow", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcUnFollowCommand, "", nullptr }, + { NODE, "whisper", SEC_MODERATOR, false, &ChatHandler::HandleNpcWhisperCommand, "", nullptr }, + { NODE, "yell", SEC_MODERATOR, false, &ChatHandler::HandleNpcYellCommand, "", nullptr }, + { NODE, "tame", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcTameCommand, "", nullptr }, + { NODE, "setdeathstate", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSetDeathStateCommand, "", nullptr }, + { NODE, "group", SEC_GAMEMASTER, false, nullptr, "", creatureGroupsCommandTable }, + + + //{ TODO: fix or remove this commands + { NODE, "addweapon", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNpcAddWeaponCommand, "", nullptr }, + { NODE, "name", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcNameCommand, "", nullptr }, + { NODE, "subname", SEC_GAMEMASTER, false, &ChatHandler::HandleNpcSubNameCommand, "", nullptr }, + //} + + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand pbcastCommandTable[] = + { + { MSTR, "stats", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePBCastStatsCommand, "", nullptr }, + { MSTR, "setthreads", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePBCastSetThreadsCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand pdumpCommandTable[] = + { + { NODE, "load", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePDumpLoadCommand, "", nullptr }, + { NODE, "write", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePDumpWriteCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand poolCommandTable[] = + { + { NODE, "list", SEC_GAMEMASTER, false, &ChatHandler::HandlePoolListCommand, "", nullptr }, + { NODE, "update", SEC_ADMINISTRATOR, false, &ChatHandler::HandlePoolUpdateCommand, "", nullptr }, + { NODE, "spawns", SEC_GAMEMASTER, false, &ChatHandler::HandlePoolSpawnsCommand, "", nullptr }, + { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandlePoolInfoCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand questCommandTable[] = + { + { NODE, "add", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestAddCommand, "", nullptr }, + { NODE, "complete", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestCompleteCommand, "", nullptr }, + { NODE, "status", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestStatusCommand, "", nullptr }, + { NODE, "remove", SEC_ADMINISTRATOR, false, &ChatHandler::HandleQuestRemoveCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand petCommandTable[] = + { + { MSTR, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePetListCommand, "", nullptr }, + { MSTR, "rename", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePetRenameCommand, "", nullptr }, + { MSTR, "delete", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePetDeleteCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand reloadCommandTable[] = + { + { MSTR, "all", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllCommand, "", nullptr }, + { MSTR, "all_area", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllAreaCommand, "", nullptr }, + { MSTR, "all_eventai", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllEventAICommand, "", nullptr }, + { MSTR, "all_gossips", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllGossipsCommand, "", nullptr }, + { MSTR, "all_item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllItemCommand, "", nullptr }, + { MSTR, "all_locales", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllLocalesCommand, "", nullptr }, + { MSTR, "all_loot", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllLootCommand, "", nullptr }, + { MSTR, "all_npc", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllNpcCommand, "", nullptr }, + { MSTR, "all_quest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllQuestCommand, "", nullptr }, + { MSTR, "all_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllScriptsCommand, "", nullptr }, + { MSTR, "all_spell", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAllSpellCommand, "", nullptr }, + + { MSTR, "anticheat", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAnticheatCommand, "", nullptr }, + { MSTR, "config", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadConfigCommand, "", nullptr }, + + { MSTR, "areatrigger_involvedrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestAreaTriggersCommand, "", nullptr }, + { MSTR, "areatrigger_tavern", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAreaTriggerTavernCommand, "", nullptr }, + { MSTR, "areatrigger_teleport", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAreaTriggerTeleportCommand, "", nullptr }, + { MSTR, "character_pet", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCharacterPetCommand, "", nullptr }, + { MSTR, "command", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCommandCommand, "", nullptr }, + { MSTR, "conditions", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadConditionsCommand, "", nullptr }, + { MSTR, "creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureCommand, "", nullptr }, + { MSTR, "creature_ai_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventAIScriptsCommand, "", nullptr }, + { MSTR, "creature_ai_summons", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventAISummonsCommand, "", nullptr }, + { MSTR, "creature_ai_texts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventAITextsCommand, "", nullptr }, + { MSTR, "creature_battleground", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadBattleEventCommand, "", nullptr }, + { MSTR, "creature_involvedrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureQuestInvRelationsCommand, "", nullptr }, + { MSTR, "creature_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesCreatureCommand, "", nullptr }, + { MSTR, "creature_questrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureQuestRelationsCommand, "", nullptr }, + { MSTR, "db_script_string", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadDbScriptStringCommand, "", nullptr }, + { MSTR, "disenchant_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesDisenchantCommand, "", nullptr }, + { MSTR, "event_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadEventScriptsCommand, "", nullptr }, + { MSTR, "fishing_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesFishingCommand, "", nullptr }, + { MSTR, "game_graveyard_zone", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameGraveyardZoneCommand, "", nullptr }, + { MSTR, "game_tele", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameTeleCommand, "", nullptr }, + { MSTR, "gameobject", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameObjectCommand, "", nullptr }, + { MSTR, "gameobject_involvedrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGOQuestInvRelationsCommand, "", nullptr }, + { MSTR, "gameobject_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesGameobjectCommand, "", nullptr }, + { MSTR, "gameobject_questrelation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGOQuestRelationsCommand, "", nullptr }, + { MSTR, "gameobject_requirement", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGORequirementsCommand, "", nullptr }, + { MSTR, "gameobject_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameObjectScriptsCommand, "", nullptr }, + { MSTR, "gameobject_battleground", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadBattleEventCommand, "", nullptr }, + { MSTR, "gossip_menu", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGossipMenuCommand, "", nullptr }, + { MSTR, "gossip_menu_option", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGossipMenuOptionCommand, "", nullptr }, + { MSTR, "gossip_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGossipScriptsCommand, "", nullptr }, + { MSTR, "item_enchantment_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadItemEnchantementsCommand, "", nullptr }, + { MSTR, "item_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesItemCommand, "", nullptr }, + { MSTR, "item_required_target", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadItemRequiredTragetCommand, "", nullptr }, + { MSTR, "locales_creature", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesCreatureCommand, "", nullptr }, + { MSTR, "locales_gameobject", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesGameobjectCommand, "", nullptr }, + { MSTR, "locales_gossip_menu_option", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesGossipMenuOptionCommand, "", nullptr }, + { MSTR, "locales_item", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesItemCommand, "", nullptr }, + { MSTR, "locales_npc_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesNpcTextCommand, "", nullptr }, + { MSTR, "locales_page_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesPageTextCommand, "", nullptr }, + { MSTR, "locales_points_of_interest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesPointsOfInterestCommand, "", nullptr }, + { MSTR, "locales_quest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLocalesQuestCommand, "", nullptr }, + { MSTR, "mail_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesMailCommand, "", nullptr }, + { MSTR, "mangos_string", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadMangosStringCommand, "", nullptr }, + { MSTR, "npc_gossip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcGossipCommand, "", nullptr }, + { MSTR, "npc_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcTextCommand, "", nullptr }, + { MSTR, "npc_trainer", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcTrainerCommand, "", nullptr }, + { MSTR, "npc_vendor", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNpcVendorCommand, "", nullptr }, + { MSTR, "page_text", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadPageTextsCommand, "", nullptr }, + { MSTR, "pickpocketing_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesPickpocketingCommand, "", nullptr}, + { MSTR, "points_of_interest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadPointsOfInterestCommand, "", nullptr }, + { MSTR, "quest_end_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestEndScriptsCommand, "", nullptr }, + { MSTR, "quest_start_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestStartScriptsCommand, "", nullptr }, + { MSTR, "quest_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadQuestTemplateCommand, "", nullptr }, + { MSTR, "reference_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesReferenceCommand, "", nullptr }, + { MSTR, "reserved_name", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadReservedNameCommand, "", nullptr }, + { MSTR, "reputation_reward_rate", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadReputationRewardRateCommand, "", nullptr }, + { MSTR, "reputation_spillover_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadReputationSpilloverTemplateCommand, "", nullptr }, + { MSTR, "skill_discovery_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSkillDiscoveryTemplateCommand, "", nullptr }, + { MSTR, "skill_extra_item_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSkillExtraItemTemplateCommand, "", nullptr }, + { MSTR, "skill_fishing_base_level", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSkillFishingBaseLevelCommand, "", nullptr }, + { MSTR, "skinning_loot_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadLootTemplatesSkinningCommand, "", nullptr }, + { MSTR, "spell_affect", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellAffectCommand, "", nullptr }, + { MSTR, "spell_area", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellAreaCommand, "", nullptr }, + { MSTR, "spell_bonus_data", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellBonusesCommand, "", nullptr }, + { MSTR, "spell_chain", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellChainCommand, "", nullptr }, + { MSTR, "spell_elixir", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellElixirCommand, "", nullptr }, + { MSTR, "spell_learn_spell", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellLearnSpellCommand, "", nullptr }, + { MSTR, "spell_pet_auras", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellPetAurasCommand, "", nullptr }, + { MSTR, "spell_proc_event", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellProcEventCommand, "", nullptr }, + { MSTR, "spell_proc_item_enchant", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellProcItemEnchantCommand, "", nullptr }, + { MSTR, "spell_script_target", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellScriptTargetCommand, "", nullptr }, + { MSTR, "spell_scripts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellScriptsCommand, "", nullptr }, + { MSTR, "spell_target_position", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellTargetPositionCommand, "", nullptr }, + { MSTR, "spell_threats", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellThreatsCommand, "", nullptr }, + { MSTR, "spell_disabled", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellDisabledCommand, "", nullptr }, + { MSTR, "autobroadcast", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAutoBroadcastCommand, "", nullptr }, + { MSTR, "spell_mod", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellModsCommand, "", nullptr }, + { MSTR, "map_loot_disabled", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadMapLootDisabledCommand, "", nullptr }, + { MSTR, "cinematic_waypoints", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCinematicWaypointsCommand, "", nullptr }, + { MSTR, "variables", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadVariablesCommand, "", nullptr }, + { MSTR, "spell_group", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellGroupCommand, "", nullptr }, + { MSTR, "spell_group_stack_rules", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadSpellGroupStackRulesCommand, "", nullptr }, + { MSTR, "creature_groups", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureGroupsCommand, "", nullptr }, + + { MSTR, "creature_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureTemplate, "", nullptr }, + { MSTR, "item_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadItemTemplate, "", nullptr }, + { MSTR, "map_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadMapTemplate, "", nullptr }, + { MSTR, "gameobject_template", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameObjectTemplate, "", nullptr }, + { MSTR, "exploration_basexp", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadExplorationBaseXp, "", nullptr }, + { MSTR, "pet_name_generation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadPetNameGeneration, "", nullptr }, + { MSTR, "creature_onkill_reputation", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureOnKillReputation, "", nullptr }, + { MSTR, "game_weather", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadGameWeather, "", nullptr }, + { MSTR, "player_factionchange_reputations", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeReputations, "", nullptr }, + { MSTR, "player_factionchange_spells", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeSpells, "", nullptr }, + { MSTR, "player_factionchange_items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeItems, "", nullptr }, + { MSTR, "player_factionchange_quests", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeQuests, "", nullptr }, + { MSTR, "player_factionchange_mounts", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadFactionChangeMounts, "", nullptr }, + { MSTR, "creature_model_info", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadCreatureModelInfo, "", nullptr }, + { MSTR, "nostalrius_string", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadNostalriusStrings, "", nullptr }, + { MSTR, "ip_banned", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadIPBanList, "", nullptr }, + { MSTR, "account_banned", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReloadAccountBanList, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand resetCommandTable[] = + { + { NODE, "honor", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetHonorCommand, "", nullptr }, + { NODE, "level", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetLevelCommand, "", nullptr }, + { NODE, "spells", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetSpellsCommand, "", nullptr }, + { NODE, "stats", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetStatsCommand, "", nullptr }, + { NODE, "talents", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetTalentsCommand, "", nullptr }, + { NODE, "all", SEC_ADMINISTRATOR, true, &ChatHandler::HandleResetAllCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand sendMassCommandTable[] = + { + { NODE, "items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMassItemsCommand, "", nullptr }, + { NODE, "mail", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMassMailCommand, "", nullptr }, + { NODE, "money", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMassMoneyCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand sendCommandTable[] = + { + { NODE, "mass", SEC_ADMINISTRATOR, true, nullptr, "", sendMassCommandTable }, + + { MSTR, "items", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendItemsCommand, "", nullptr }, + { MSTR, "mail", SEC_MODERATOR, true, &ChatHandler::HandleSendMailCommand, "", nullptr }, + { MSTR, "message", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMessageCommand, "", nullptr }, + { MSTR, "money", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSendMoneyCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverIdleRestartCommandTable[] = + { + { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, + { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerIdleRestartCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverIdleShutdownCommandTable[] = + { + { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, + { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerIdleShutDownCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverRestartCommandTable[] = + { + { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, + { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerRestartCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverShutdownCommandTable[] = + { + { NODE, "cancel", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCancelCommand, "", nullptr }, + { NODE, "" , SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerShutDownCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverLogCommandTable[] = + { + { NODE, "filter", SEC_CONSOLE, true, &ChatHandler::HandleServerLogFilterCommand, "", nullptr }, + { NODE, "level", SEC_CONSOLE, true, &ChatHandler::HandleServerLogLevelCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverSetCommandTable[] = + { + { MSTR, "motd", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerSetMotdCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand serverCommandTable[] = + { + { NODE, "corpses", SEC_GAMEMASTER, true, &ChatHandler::HandleServerCorpsesCommand, "", nullptr }, + { NODE, "exit", SEC_CONSOLE, true, &ChatHandler::HandleServerExitCommand, "", nullptr }, + { NODE, "idlerestart", SEC_ADMINISTRATOR, true, nullptr, "", serverIdleRestartCommandTable }, + { NODE, "idleshutdown", SEC_ADMINISTRATOR, true, nullptr, "", serverShutdownCommandTable }, + { NODE, "info", SEC_PLAYER, true, &ChatHandler::HandleServerInfoCommand, "", nullptr }, + { NODE, "log", SEC_CONSOLE, true, nullptr, "", serverLogCommandTable }, + { NODE, "motd", SEC_PLAYER, true, &ChatHandler::HandleServerMotdCommand, "", nullptr }, + { NODE, "plimit", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServerPLimitCommand, "", nullptr }, + { NODE, "restart", SEC_ADMINISTRATOR, true, nullptr, "", serverRestartCommandTable }, + { NODE, "shutdown", SEC_ADMINISTRATOR, true, nullptr, "", serverShutdownCommandTable }, + { NODE, "set", SEC_ADMINISTRATOR, true, nullptr, "", serverSetCommandTable }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand teleCommandTable[] = + { + { NODE, "add", SEC_ADMINISTRATOR, false, &ChatHandler::HandleTeleAddCommand, "", nullptr }, + { NODE, "del", SEC_ADMINISTRATOR, true, &ChatHandler::HandleTeleDelCommand, "", nullptr }, + { NODE, "name", SEC_MODERATOR, true, &ChatHandler::HandleTeleNameCommand, "", nullptr }, + { NODE, "group", SEC_MODERATOR, false, &ChatHandler::HandleTeleGroupCommand, "", nullptr }, + { NODE, "", SEC_MODERATOR, false, &ChatHandler::HandleTeleCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand triggerCommandTable[] = + { + { NODE, "active", SEC_GAMEMASTER, false, &ChatHandler::HandleTriggerActiveCommand, "", nullptr }, + { NODE, "near", SEC_GAMEMASTER, false, &ChatHandler::HandleTriggerNearCommand, "", nullptr }, + { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleTriggerCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand unbanCommandTable[] = + { + { NODE, "account", SEC_ADMINISTRATOR, true, &ChatHandler::HandleUnBanAccountCommand, "", nullptr }, + { NODE, "character", SEC_ADMINISTRATOR, true, &ChatHandler::HandleUnBanCharacterCommand, "", nullptr }, + { NODE, "ip", SEC_ADMINISTRATOR, true, &ChatHandler::HandleUnBanIPCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand wpCommandTable[] = + { + { NODE, "show", SEC_GAMEMASTER, false, &ChatHandler::HandleWpShowCommand, "", nullptr }, + { NODE, "add", SEC_GAMEMASTER, false, &ChatHandler::HandleWpAddCommand, "", nullptr }, + { NODE, "modify", SEC_GAMEMASTER, false, &ChatHandler::HandleWpModifyCommand, "", nullptr }, + { NODE, "export", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWpExportCommand, "", nullptr }, + { NODE, "import", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWpImportCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand exportCommandTable[] = + { + { NODE, "spell", SEC_CONSOLE, true, &ChatHandler::HandleDbcExportSpellCommand, "", nullptr}, + { NODE, "effects", SEC_CONSOLE, true, &ChatHandler::HandleDbcExportSpellEffectsCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + + static ChatCommand worldCommandTable[] = + { + { NODE, "update", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWorldUpdateCommand, "", nullptr}, + { NODE, "cansee", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWorldTestCommand, "", nullptr}, + { NODE, "detail", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWorldDetailCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + + static ChatCommand cinematicCommandTable[] = + { + { NODE, "addwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCinematicAddWpCommand, "", nullptr}, + { NODE, "gotime", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCinematicGoTimeCommand, "", nullptr}, + { NODE, "listwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCinematicListWpCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + + static ChatCommand escortCommandTable[] = + { + { NODE, "create", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortCreateCommand, "", nullptr}, + { NODE, "addwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortAddWpCommand, "", nullptr}, + { NODE, "modwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortModifyWpCommand, "", nullptr}, + { NODE, "clearwp", SEC_ADMINISTRATOR, false, &ChatHandler::HandleEscortClearWpCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + static ChatCommand worldStateCommandTable[] = + { + { NODE, "test", SEC_ADMINISTRATOR, false, &ChatHandler::HandleUpdateWorldStateCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + static ChatCommand bgCommandTable[] = + { + { NODE, "status", SEC_GAMEMASTER, false, &ChatHandler::HandleBGStatusCommand, "", nullptr}, + { NODE, "start", SEC_GAMEMASTER, false, &ChatHandler::HandleBGStartCommand, "", nullptr}, + { NODE, "stop", SEC_GAMEMASTER, false, &ChatHandler::HandleBGStopCommand, "", nullptr}, + { NODE, "", SEC_GAMEMASTER, false, &ChatHandler::HandleBGCustomCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + static ChatCommand spellCommandTable[] = + { + { NODE, "effects", SEC_GAMEMASTER, true, &ChatHandler::HandleSpellEffectsCommand, "", nullptr}, + { NODE, "info", SEC_GAMEMASTER, true, &ChatHandler::HandleSpellInfosCommand, "", nullptr}, + { NODE, "search", SEC_GAMEMASTER, true, &ChatHandler::HandleSpellSearchCommand, "", nullptr}, + { NODE, "iconfix", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSpellIconFixCommand, "", nullptr}, + { MSTR, nullptr, 0, false, nullptr, "", nullptr} + }; + static ChatCommand mmapCommandTable[] = + { + { NODE, "path", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapPathCommand, "", nullptr }, + { NODE, "loc", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapLocCommand, "", nullptr }, + { NODE, "loadedtiles", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapLoadedTilesCommand, "", nullptr }, + { NODE, "stats", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapStatsCommand, "", nullptr }, + { NODE, "testarea", SEC_GAMEMASTER, false, &ChatHandler::HandleMmapTestArea, "", nullptr }, + { NODE, "connect", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmapConnection, "", nullptr }, + { NODE, "reload", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmapLoad, "", nullptr }, + { NODE, "unload", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmapUnload, "", nullptr }, + { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMmap, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand videosCommandTable[] = + { + { NODE, "expendables", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugExp, "", nullptr }, + { NODE, "turn", SEC_GAMEMASTER, false, &ChatHandler::HandleVideoTurn, "", nullptr }, + { NODE, "", SEC_GAMEMASTER, false, &ChatHandler::HandleDebugExp, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand anticheatClientCommandTable[] = + { + { NODE, "find", SEC_GAMEMASTER, true, &ChatHandler::HandleClientSearchCommand, "", nullptr }, + { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleClientInfosCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand anticheatWardenCommandTable[] = + { + { NODE, "read", SEC_ADMINISTRATOR, false, &ChatHandler::HandleWardenReadCommand, "", nullptr }, + { NODE, "", SEC_ADMINISTRATOR, true, &ChatHandler::HandleWardenCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand anticheatCommandTable[] = + { + { NODE, "server", SEC_GAMEMASTER, true, &ChatHandler::HandleAnticheatCommand, "", nullptr }, + { NODE, "warden", SEC_GAMEMASTER, true, nullptr, "", anticheatWardenCommandTable }, + { NODE, "client", SEC_ADMINISTRATOR, true, nullptr, "", anticheatClientCommandTable }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + static ChatCommand replayCommandTable[] = + { + { NODE, "play", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayPlayCommand, "", nullptr }, + { NODE, "forward", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayForwardCommand, "", nullptr }, + { NODE, "stop", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayStopCommand, "", nullptr }, + { NODE, "record", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayRecordCommand, "", nullptr }, + { NODE, "speed", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplaySpeedCommand, "", nullptr }, + { NODE, "", SEC_ADMINISTRATOR, false, &ChatHandler::HandleReplayPlayCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + static ChatCommand channelCommandTable[] = + { + { NODE, "join", SEC_GAMEMASTER, false, &ChatHandler::HandleChannelJoinCommand, "", nullptr }, + { NODE, "leave", SEC_GAMEMASTER, false, &ChatHandler::HandleChannelLeaveCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + static ChatCommand ticketResponseCommandTable[] = + { + { NODE, "reset", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResponseResetCommand, "", nullptr }, + { NODE, "append", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResponseAppendCommand, "", nullptr }, + { NODE, "appendln", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResponseAppendLnCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + static ChatCommand nodeServersCommandTable[] = + { + { NODE, "list", SEC_ADMINISTRATOR, true, &ChatHandler::HandleNodeServersListCommand, "", nullptr }, + { NODE, "switch", SEC_ADMINISTRATOR, true, &ChatHandler::HandleNodeServersSwitchCommand, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + static ChatCommand ticketCommandTable[] = + { + { NODE, "assign", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketAssignToCommand, "", nullptr }, + { NODE, "close", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCloseByIdCommand, "", nullptr }, + { NODE, "closedlist", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListClosedCommand, "", nullptr }, + { NODE, "counter", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCounterCommand, "", nullptr }, + { NODE, "comment", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCommentCommand, "", nullptr }, + { NODE, "complete", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketCompleteCommand, "", nullptr }, + { NODE, "delete", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketDeleteByIdCommand, "", nullptr }, + { NODE, "escalate", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketEscalateCommand, "", nullptr }, + { NODE, "escalatedlist", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListEscalatedCommand, "", nullptr }, + { NODE, "list", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListCommand, "", nullptr }, + { NODE, "next", SEC_GAMEMASTER, false,&ChatHandler::HandleGMTicketNextCommand, "", nullptr }, + { NODE, "notify", SEC_GAMEMASTER, false,&ChatHandler::HandleGMTicketNotifyCommand, "", nullptr }, + { NODE, "onlinelist", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketListOnlineCommand, "", nullptr }, + { NODE, "previous", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketPreviousCommand, "", nullptr }, + { NODE, "reload", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketReloadCommand, "", nullptr }, + { NODE, "reset", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketResetCommand, "", nullptr }, + { NODE, "response", SEC_GAMEMASTER, true, nullptr, "", ticketResponseCommandTable }, + { NODE, "togglesystem", SEC_GAMEMASTER, true, &ChatHandler::HandleToggleGMTicketSystem, "", nullptr }, + { NODE, "unassign", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketUnAssignCommand, "", nullptr }, + { NODE, "viewid", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketGetByIdCommand, "", nullptr }, + { NODE, "viewname", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketGetByNameCommand, "", nullptr }, + { NODE, "", SEC_GAMEMASTER, true, &ChatHandler::HandleGMTicketGetByIdOrNameCommand, "", nullptr }, + { MSTR, nullptr, 0, false,nullptr, "", nullptr } + }; + + static ChatCommand serviceCommandTable[] = + { + { NODE, "del_characters", SEC_ADMINISTRATOR, true, &ChatHandler::HandleServiceDeleteCharacters, "", nullptr }, + { NODE, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand spamerCommandTable[] = + { + { MSTR, "mute", SEC_GAMEMASTER, true, &ChatHandler::HandleSpamerMute, "", nullptr }, + { MSTR, "unmute", SEC_GAMEMASTER, true, &ChatHandler::HandleSpamerUnmute, "", nullptr }, + { MSTR, "list", SEC_GAMEMASTER, true, &ChatHandler::HandleSpamerList, "", nullptr }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + static ChatCommand goldCommandTable[] = + { + { MSTR, "remove", SEC_GAMEMASTER, true, &ChatHandler::HandleGoldRemoval, "", nullptr }, + }; + + static ChatCommand commandTable[] = + { + { NODE, "account", SEC_PLAYER, true, nullptr, "", accountCommandTable }, + { NODE, "auction", SEC_ADMINISTRATOR, false, nullptr, "", auctionCommandTable }, + { NODE, "cast", SEC_ADMINISTRATOR, false, nullptr, "", castCommandTable }, + { NODE, "character", SEC_GAMEMASTER, true, nullptr, "", characterCommandTable}, + { NODE, "debug", SEC_GAMEMASTER, true, nullptr, "", debugCommandTable }, + { NODE, "replay", SEC_GAMEMASTER, false, nullptr, "", replayCommandTable }, + { NODE, "event", SEC_GAMEMASTER, false, nullptr, "", eventCommandTable }, + { NODE, "gm", SEC_PLAYER, true, nullptr, "", gmCommandTable }, + { NODE, "honor", SEC_GAMEMASTER, false, nullptr, "", honorCommandTable }, + { NODE, "go", SEC_MODERATOR, false, nullptr, "", goCommandTable }, + { NODE, "gobject", SEC_GAMEMASTER, false, nullptr, "", gobjectCommandTable }, + { NODE, "guild", SEC_ADMINISTRATOR, true, nullptr, "", guildCommandTable }, + { NODE, "instance", SEC_ADMINISTRATOR, true, nullptr, "", instanceCommandTable }, + { NODE, "learn", SEC_MODERATOR, false, nullptr, "", learnCommandTable }, + { NODE, "list", SEC_ADMINISTRATOR, true, nullptr, "", listCommandTable }, + { NODE, "lookup", SEC_MODERATOR, true, nullptr, "", lookupCommandTable }, + { NODE, "modify", SEC_MODERATOR, false, nullptr, "", modifyCommandTable }, + { NODE, "npc", SEC_MODERATOR, false, nullptr, "", npcCommandTable }, + { NODE, "pool", SEC_GAMEMASTER, true, nullptr, "", poolCommandTable }, + { NODE, "pdump", SEC_ADMINISTRATOR, true, nullptr, "", pdumpCommandTable }, + { NODE, "quest", SEC_ADMINISTRATOR, false, nullptr, "", questCommandTable }, + { NODE, "reload", SEC_ADMINISTRATOR, true, nullptr, "", reloadCommandTable }, + { NODE, "reset", SEC_ADMINISTRATOR, true, nullptr, "", resetCommandTable }, + { NODE, "server", SEC_PLAYER, true, nullptr, "", serverCommandTable }, + { NODE, "tele", SEC_MODERATOR, true, nullptr, "", teleCommandTable }, + { NODE, "trigger", SEC_GAMEMASTER, false, nullptr, "", triggerCommandTable }, + { NODE, "wp", SEC_GAMEMASTER, false, nullptr, "", wpCommandTable }, + { NODE, "service", SEC_ADMINISTRATOR, true, nullptr, "", serviceCommandTable }, + + { NODE, "export", SEC_CONSOLE, true, nullptr, "Export DBC files to database", exportCommandTable}, + { NODE, "bot", SEC_GAMEMASTER, true, nullptr, "Manage bots", botCommandTable}, + { NODE, "ahbot", SEC_GAMEMASTER, true, nullptr, "Manage AH bot", ahbotCommandTable}, + { NODE, "world", SEC_GAMEMASTER, false, nullptr, "", worldCommandTable }, + { NODE, "possess", SEC_GAMEMASTER, false, &ChatHandler::HandlePossessCommand, "", nullptr}, + { NODE, "cinematic", SEC_GAMEMASTER, false, nullptr, "", cinematicCommandTable}, + { NODE, "escorte", SEC_GAMEMASTER, false, nullptr, "", escortCommandTable}, + { NODE, "worldstate", SEC_GAMEMASTER, false, nullptr, "", worldStateCommandTable}, + { NODE, "bg", SEC_GAMEMASTER, false, nullptr, "", bgCommandTable}, + { NODE, "spell", SEC_GAMEMASTER, true, nullptr, "", spellCommandTable}, + { NODE, "variable", SEC_GAMEMASTER, true, &ChatHandler::HandleVariableCommand, "", nullptr}, + { NODE, "god", SEC_GAMEMASTER, false, &ChatHandler::HandleGodCommand, "", nullptr }, + { NODE, "aura", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAuraCommand, "", nullptr }, + { NODE, "unaura", SEC_ADMINISTRATOR, false, &ChatHandler::HandleUnAuraCommand, "", nullptr }, + { NODE, "announce", SEC_MODERATOR, true, &ChatHandler::HandleAnnounceCommand, "", nullptr }, + { NODE, "notify", SEC_MODERATOR, true, &ChatHandler::HandleNotifyCommand, "", nullptr }, + { NODE, "goname", SEC_MODERATOR, false, &ChatHandler::HandleGonameCommand, "", nullptr }, + { NODE, "namego", SEC_MODERATOR, false, &ChatHandler::HandleNamegoCommand, "", nullptr }, + { NODE, "groupgo", SEC_MODERATOR, false, &ChatHandler::HandleGroupgoCommand, "", nullptr }, + { NODE, "gocorpse", SEC_MODERATOR, false, &ChatHandler::HandleGocorpseCommand, "", nullptr }, + { NODE, "commands", SEC_PLAYER, true, &ChatHandler::HandleCommandsCommand, "", nullptr }, + { NODE, "demorph", SEC_GAMEMASTER, false, &ChatHandler::HandleDeMorphCommand, "", nullptr }, + { NODE, "die", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDieCommand, "", nullptr }, + { NODE, "revive", SEC_ADMINISTRATOR, true, &ChatHandler::HandleReviveCommand, "", nullptr }, + { NODE, "dismount", SEC_PLAYER, false, &ChatHandler::HandleDismountCommand, "", nullptr }, + { NODE, "gps", SEC_MODERATOR, false, &ChatHandler::HandleGPSCommand, "", nullptr }, + { NODE, "guid", SEC_GAMEMASTER, false, &ChatHandler::HandleGUIDCommand, "", nullptr }, + { NODE, "help", SEC_PLAYER, true, &ChatHandler::HandleHelpCommand, "", nullptr }, + { NODE, "itemmove", SEC_GAMEMASTER, false, &ChatHandler::HandleItemMoveCommand, "", nullptr }, + { NODE, "cooldown", SEC_ADMINISTRATOR, false, &ChatHandler::HandleCooldownCommand, "", nullptr }, + { NODE, "unlearn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleUnLearnCommand, "", nullptr }, + { NODE, "distance", SEC_ADMINISTRATOR, false, &ChatHandler::HandleGetDistanceCommand, "", nullptr }, + { NODE, "recall", SEC_MODERATOR, false, &ChatHandler::HandleRecallCommand, "", nullptr }, + { NODE, "save", SEC_PLAYER, false, &ChatHandler::HandleSaveCommand, "", nullptr }, + { MSTR, "wareffortget", SEC_ADMINISTRATOR, true, &ChatHandler::HandleGetWarEffortResource, "", nullptr }, + { MSTR, "wareffortset", SEC_ADMINISTRATOR, true, &ChatHandler::HandleSetWarEffortResource, "", nullptr }, + { MSTR, "saveall", SEC_MODERATOR, true, &ChatHandler::HandleSaveAllCommand, "", nullptr }, + { MSTR, "kick", SEC_GAMEMASTER, true, &ChatHandler::HandleKickPlayerCommand, "", nullptr }, + { MSTR, "ban", SEC_ADMINISTRATOR, true, nullptr, "", banCommandTable }, + { MSTR, "unban", SEC_ADMINISTRATOR, true, nullptr, "", unbanCommandTable }, + { MSTR, "baninfo", SEC_ADMINISTRATOR, false, nullptr, "", baninfoCommandTable }, + { MSTR, "banlist", SEC_ADMINISTRATOR, true, nullptr, "", banlistCommandTable }, + { NODE, "start", SEC_PLAYER, false, &ChatHandler::HandleStartCommand, "", nullptr }, + { NODE, "taxicheat", SEC_MODERATOR, false, &ChatHandler::HandleTaxiCheatCommand, "", nullptr }, + { NODE, "linkgrave", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLinkGraveCommand, "", nullptr }, + { NODE, "neargrave", SEC_ADMINISTRATOR, false, &ChatHandler::HandleNearGraveCommand, "", nullptr }, + { NODE, "explorecheat", SEC_ADMINISTRATOR, false, &ChatHandler::HandleExploreCheatCommand, "", nullptr }, + { NODE, "hover", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHoverCommand, "", nullptr }, + { NODE, "levelup", SEC_ADMINISTRATOR, false, &ChatHandler::HandleLevelUpCommand, "", nullptr }, + { NODE, "showarea", SEC_ADMINISTRATOR, false, &ChatHandler::HandleShowAreaCommand, "", nullptr }, + { NODE, "hidearea", SEC_ADMINISTRATOR, false, &ChatHandler::HandleHideAreaCommand, "", nullptr }, + { NODE, "additem", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAddItemCommand, "", nullptr }, + { NODE, "additemset", SEC_ADMINISTRATOR, false, &ChatHandler::HandleAddItemSetCommand, "", nullptr }, + { NODE, "bank", SEC_ADMINISTRATOR, false, &ChatHandler::HandleBankCommand, "", nullptr }, + { NODE, "wchange", SEC_ADMINISTRATOR, false, &ChatHandler::HandleChangeWeatherCommand, "", nullptr }, + { NODE, "ticket", SEC_GAMEMASTER, true, nullptr, "",ticketCommandTable }, + { NODE, "maxskill", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMaxSkillCommand, "", nullptr }, + { NODE, "setskill", SEC_ADMINISTRATOR, false, &ChatHandler::HandleSetSkillCommand, "", nullptr }, + { MSTR, "whispers", SEC_MODERATOR, false, &ChatHandler::HandleWhispersCommand, "", nullptr }, + { MSTR, "wr", SEC_PLAYER, false, &ChatHandler::HandleWhisperRestrictionCommand, "", nullptr }, + { MSTR, "pinfo", SEC_GAMEMASTER, true, &ChatHandler::HandlePInfoCommand, "", nullptr }, + { MSTR, "groupinfo", SEC_GAMEMASTER, true, &ChatHandler::HandleGroupInfoCommand, "", nullptr }, + { MSTR, "pbcast", SEC_ADMINISTRATOR, true, &ChatHandler::HandlePBCastStatsCommand, "", pbcastCommandTable }, + { NODE, "addons", SEC_ADMINISTRATOR, false, &ChatHandler::HandleListAddonsCommand, "", nullptr }, + { NODE, "respawn", SEC_ADMINISTRATOR, false, &ChatHandler::HandleRespawnCommand, "", nullptr }, + { NODE, "send", SEC_MODERATOR, true, nullptr, "", sendCommandTable }, + { NODE, "mute", SEC_MODERATOR, true, &ChatHandler::HandleMuteCommand, "", nullptr }, + { NODE, "unmute", SEC_MODERATOR, true, &ChatHandler::HandleUnmuteCommand, "", nullptr }, + { NODE, "movegens", SEC_ADMINISTRATOR, false, &ChatHandler::HandleMovegensCommand, "", nullptr }, + { NODE, "cometome", SEC_ADMINISTRATOR, false, &ChatHandler::HandleComeToMeCommand, "", nullptr }, + { NODE, "damage", SEC_ADMINISTRATOR, false, &ChatHandler::HandleDamageCommand, "", nullptr }, + { NODE, "combatstop", SEC_GAMEMASTER, false, &ChatHandler::HandleCombatStopCommand, "", nullptr }, + { NODE, "repairitems", SEC_GAMEMASTER, true, &ChatHandler::HandleRepairitemsCommand, "", nullptr }, + { NODE, "stable", SEC_ADMINISTRATOR, false, &ChatHandler::HandleStableCommand, "", nullptr }, + { NODE, "waterwalk", SEC_GAMEMASTER, false, &ChatHandler::HandleWaterwalkCommand, "", nullptr }, + { NODE, "quit", SEC_CONSOLE, true, &ChatHandler::HandleQuitCommand, "", nullptr }, + { NODE, "mmap", SEC_GAMEMASTER, false, nullptr, "", mmapCommandTable }, + { NODE, "video", SEC_GAMEMASTER, false, nullptr, "", videosCommandTable }, + { NODE, "freez", SEC_GAMEMASTER, false, &ChatHandler::HandleFreezCommand, "", nullptr }, + { NODE, "anticheat", SEC_GAMEMASTER, false, nullptr, "", anticheatCommandTable }, + { NODE, "groupspell", SEC_ADMINISTRATOR, true, nullptr, "", groupSpellCommandTable}, + { NODE, "pet", SEC_ADMINISTRATOR, true, nullptr, "", petCommandTable}, + { NODE, "channel", SEC_GAMEMASTER, false, nullptr, "", channelCommandTable}, + { NODE, "nodes", SEC_GAMEMASTER, true, nullptr, "", nodeServersCommandTable}, + { MSTR, "runtest", SEC_ADMINISTRATOR, true, &ChatHandler::HandleRunTestCommand, "", nullptr }, + { MSTR, "log", SEC_GAMEMASTER, true, &ChatHandler::HandleViewLogCommand, "", nullptr }, + { MSTR, "spamer", SEC_GAMEMASTER, true, nullptr, "", spamerCommandTable }, + { MSTR, "gold", SEC_GAMEMASTER, true, nullptr, "", goldCommandTable }, + { MSTR, nullptr, 0, false, nullptr, "", nullptr } + }; + + if (load_command_table) + { + load_command_table = false; + + // check hardcoded part integrity + //CheckIntegrity(commandTable, NULL); + FillFullCommandsName(commandTable, ""); + + QueryResult *result = WorldDatabase.Query("SELECT name,security,help,flags FROM command"); + if (result) + { + do + { + Field *fields = result->Fetch(); + std::string name = fields[0].GetCppString(); + + SetDataForCommandInTable(commandTable, name.c_str(), fields[1].GetUInt16(), fields[2].GetCppString(), fields[3].GetUInt32()); + + } + while (result->NextRow()); + delete result; + } + } + + return commandTable; +} + +ChatHandler::ChatHandler(WorldSession* session) : + m_session(session), sentErrorMessage(false), + m_cluster_is_master(true), m_cluster_is_node(true) +{ + if (session) + { + m_cluster_is_master = session->IsMaster(); + m_cluster_is_node = session->IsNode(); + } +} + +ChatHandler::ChatHandler(Player* player) : ChatHandler(player->GetSession()) {} + +ChatHandler::~ChatHandler() {} + +const char *ChatHandler::GetMangosString(int32 entry) const +{ + return m_session->GetMangosString(entry); +} + +const char *ChatHandler::GetOnOffStr(bool value) const +{ + return value ? GetMangosString(LANG_ON) : GetMangosString(LANG_OFF); +} + +uint32 ChatHandler::GetAccountId() const +{ + return m_session->GetAccountId(); +} + +AccountTypes ChatHandler::GetAccessLevel() const +{ + return m_session->GetSecurity(); +} + +bool ChatHandler::isAvailable(ChatCommand const& cmd) const +{ + // check security level only for simple command (without child commands) + return GetAccessLevel() >= (AccountTypes)cmd.SecurityLevel; +} + +std::string ChatHandler::GetNameLink() const +{ + return GetNameLink(m_session->GetPlayer()); +} + +bool ChatHandler::HasLowerSecurity(Player* target, ObjectGuid guid, bool strong) +{ + WorldSession* target_session = nullptr; + uint32 target_account = 0; + + if (target) + target_session = target->GetSession(); + else if (guid) + target_account = sObjectMgr.GetPlayerAccountIdByGUID(guid); + + if (!target_session && !target_account) + { + SendSysMessage(LANG_PLAYER_NOT_FOUND); + SetSentErrorMessage(true); + return true; + } + + return HasLowerSecurityAccount(target_session, target_account, strong); +} + +bool ChatHandler::HasLowerSecurityAccount(WorldSession* target, uint32 target_account, bool strong) +{ + AccountTypes target_sec; + + // ignore only for non-players for non strong checks (when allow apply command at least to same sec level) + if (GetAccessLevel() > SEC_PLAYER && !strong && !sWorld.getConfig(CONFIG_BOOL_GM_LOWER_SECURITY)) + return false; + + if (target) + target_sec = target->GetSecurity(); + else if (target_account) + target_sec = sAccountMgr.GetSecurity(target_account); + else + return true; // caller must report error for (target==NULL && target_account==0) + + if (GetAccessLevel() < target_sec || (strong && GetAccessLevel() <= target_sec)) + { + SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); + SetSentErrorMessage(true); + return true; + } + + return false; +} + +bool ChatHandler::hasStringAbbr(const char* name, const char* part) +{ + // non "" command + if (*name) + { + // "" part from non-"" command + if (!*part) + return false; + + for (;;) + { + if (!*part) + return true; + else if (!*name) + return false; + else if (tolower(*name) != tolower(*part)) + return false; + ++name; + ++part; + } + } + // allow with any for "" + + return true; +} + +void ChatHandler::SendSysMessage(const char *str) +{ + WorldPacket data; + + // need copy to prevent corruption by strtok call in LineFromMessage original string + char* buf = mangos_strdup(str); + char* pos = buf; + + while (char* line = LineFromMessage(pos)) + { + FillSystemMessageData(&data, line); + m_session->SendPacket(&data); + } + + delete [] buf; + SetSentErrorMessage(true); +} + +void ChatHandler::SendGlobalSysMessage(const char *str) +{ + // Chat output + WorldPacket data; + + // need copy to prevent corruption by strtok call in LineFromMessage original string + char* buf = mangos_strdup(str); + char* pos = buf; + + while (char* line = LineFromMessage(pos)) + { + FillSystemMessageData(&data, line); + sWorld.SendGlobalMessage(&data); + } + + delete [] buf; +} + +void ChatHandler::SendSysMessage(int32 entry) +{ + SendSysMessage(GetMangosString(entry)); +} + +void ChatHandler::PSendSysMessage(int32 entry, ...) +{ + const char *format = GetMangosString(entry); + va_list ap; + char str [2048]; + va_start(ap, entry); + vsnprintf(str, 2048, format, ap); + va_end(ap); + SendSysMessage(str); +} + +void ChatHandler::PSendSysMessage(const char *format, ...) +{ + va_list ap; + char str [2048]; + va_start(ap, format); + vsnprintf(str, 2048, format, ap); + va_end(ap); + SendSysMessage(str); +} + +std::string ChatHandler::PGetParseString(int32 entry, ...) +{ + const char *format = GetMangosString(entry); + va_list ap; + char str [2048]; + va_start(ap, entry); + vsnprintf(str, 2048, format, ap); + va_end(ap); + return std::string(str); +} + +void ChatHandler::FillFullCommandsName(ChatCommand* table, std::string prefix) +{ + for (uint32 i = 0; table[i].Name != nullptr; ++i) + { + std::string newPrefix = prefix; + if (newPrefix != "") + newPrefix += " "; + newPrefix += table[i].Name; + table[i].FullName = newPrefix; + if (table[i].ChildCommands) + FillFullCommandsName(table[i].ChildCommands, newPrefix); + + } +} + +void ChatHandler::CheckIntegrity(ChatCommand *table, ChatCommand *parentCommand) +{ + for (uint32 i = 0; table[i].Name != nullptr; ++i) + { + ChatCommand* command = &table[i]; + + if (parentCommand && command->SecurityLevel < parentCommand->SecurityLevel) + sLog.outError("Subcommand '%s' of command '%s' have less access level (%u) that parent (%u)", + command->Name, parentCommand->Name, command->SecurityLevel, parentCommand->SecurityLevel); + + if (!parentCommand && strlen(command->Name) == 0) + sLog.outError("Subcommand '' at top level"); + + if (command->ChildCommands) + { + if (command->Handler) + { + if (parentCommand) + sLog.outError("Subcommand '%s' of command '%s' have handler and subcommands in same time, must be used '' subcommand for handler instead.", + command->Name, parentCommand->Name); + else + sLog.outError("First level command '%s' have handler and subcommands in same time, must be used '' subcommand for handler instead.", + command->Name); + } + + if (parentCommand && strlen(command->Name) == 0) + sLog.outError("Subcommand '' of command '%s' have subcommands", parentCommand->Name); + + CheckIntegrity(command->ChildCommands, command); + } + else if (!command->Handler) + { + if (parentCommand) + sLog.outError("Subcommand '%s' of command '%s' not have handler and subcommands in same time. Must have some from its!", + command->Name, parentCommand->Name); + else + sLog.outError("First level command '%s' not have handler and subcommands in same time. Must have some from its!", + command->Name); + } + } +} + +/** + * Search (sub)command for command line available for chat handler access level + * + * @param text Command line string that will parsed for (sub)command search + * + * @return Pointer to found command structure or NULL if appropriate command not found + */ +ChatCommand const* ChatHandler::FindCommand(char const* text) +{ + ChatCommand* command = nullptr; + char const* textPtr = text; + + return FindCommand(getCommandTable(), textPtr, command) == CHAT_COMMAND_OK ? command : NULL; +} + +/** + * Search (sub)command for command line available for chat handler access level with options and fail case additional info + * + * @param table Pointer to command C-style array first level command where will be searched + * @param text Command line string that will parsed for (sub)command search, + * it modified at return from function and pointed to not parsed tail + * @param command At success this is found command, at other cases this is last found parent command + * before subcommand search fail + * @param parentCommand Output arg for optional return parent command for command arg. + * @param cmdNamePtr Output arg for optional return last parsed command name. + * @param allAvailable Optional arg (with false default value) control use command access level checks while command search. + * @param exactlyName Optional arg (with false default value) control use exactly name in checks while command search. + * + * @return one from enum value of ChatCommandSearchResult. Output args return values highly dependent from this return result: + * + * CHAT_COMMAND_OK - Command found! + * text point to non parsed tail with possible command specific data, command store found command pointer, + * parentCommand have parent of found command or NULL if command found in table array directly + * cmdNamePtr store found command name in original form from command line + * CHAT_COMMAND_UNKNOWN - Command not found in table directly + * text only skip possible whitespaces, + * command is NULL + * parentCommand is NULL + * cmdNamePtr store command name that not found as it extracted from command line + * CHAT_COMMAND_UNKNOWN_SUBCOMMAND - Subcommand not found in some deed subcomand lists + * text point to non parsed tail including not found command name in command line, + * command store last found parent command if any + * parentCommand have parent of command in command arg or NULL + * cmdNamePtr store command name that not found as it extracted from command line + */ +ChatCommandSearchResult ChatHandler::FindCommand(ChatCommand* table, char const* &text, ChatCommand*& command, ChatCommand** parentCommand /*= NULL*/, std::string* cmdNamePtr /*= NULL*/, bool allAvailable /*= false*/, bool exactlyName /*= false*/) +{ + std::string cmd = ""; + + // skip whitespaces + while (*text != ' ' && *text != '\0') + { + cmd += *text; + ++text; + } + + while (*text == ' ') ++text; + + // search first level command in table + for (uint32 i = 0; table[i].Name != nullptr; ++i) + { + if (exactlyName) + { + size_t len = strlen(table[i].Name); + if (strncmp(table[i].Name, cmd.c_str(), len + 1) != 0) + continue; + } + else + { + if (!hasStringAbbr(table[i].Name, cmd.c_str())) + continue; + } + // select subcommand from child commands list + if (table[i].ChildCommands != nullptr) + { + char const* oldchildtext = text; + ChatCommand* parentSubcommand = nullptr; + ChatCommandSearchResult res = FindCommand(table[i].ChildCommands, text, command, &parentSubcommand, cmdNamePtr, allAvailable, exactlyName); + + switch (res) + { + case CHAT_COMMAND_OK: + { + // if subcommand success search not return parent command, then this parent command is owner of child commands + if (parentCommand) + *parentCommand = parentSubcommand ? parentSubcommand : &table[i]; + + // Name == "" is special case: restore original command text for next level "" (where parentSubcommand==NULL) + if (strlen(command->Name) == 0 && !parentSubcommand) + text = oldchildtext; + + return CHAT_COMMAND_OK; + } + case CHAT_COMMAND_UNKNOWN: + { + // command not found directly in child command list, return child command list owner + command = &table[i]; + if (parentCommand) + *parentCommand = nullptr; // we don't known parent of table list at this point + + text = oldchildtext; // restore text to stated just after parse found parent command + return CHAT_COMMAND_UNKNOWN_SUBCOMMAND; // we not found subcommand for table[i] + } + case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: + default: + { + // some deep subcommand not found, if this second level subcommand then parentCommand can be NULL, use known value for it + if (parentCommand) + *parentCommand = parentSubcommand ? parentSubcommand : &table[i]; + return res; + } + } + } + + // must be available (not checked for subcommands case because parent command expected have most low access that all subcommands always + if (!allAvailable && !isAvailable(table[i])) + continue; + + // must be have handler is explicitly selected + if (!table[i].Handler) + continue; + + // command found directly in to table + command = &table[i]; + + // unknown table owner at this point + if (parentCommand) + *parentCommand = nullptr; + + if (cmdNamePtr) + *cmdNamePtr = cmd; + + return CHAT_COMMAND_OK; + } + + // command not found in table directly + command = nullptr; + + // unknown table owner at this point + if (parentCommand) + *parentCommand = nullptr; + + if (cmdNamePtr) + *cmdNamePtr = cmd; + + return CHAT_COMMAND_UNKNOWN; +} + +/** + * Execute (sub)command available for chat handler access level with options in command line string + * + * @param text Command line string that will parsed for (sub)command search and command specific data + * + * Command output and errors in command execution will send to chat handler. + */ +void ChatHandler::ExecuteCommand(const char* text) +{ + std::string fullcmd = text; // original `text` can't be used. It content destroyed in command code processing. + + ChatCommand* command = nullptr; + ChatCommand* parentCommand = nullptr; + + ChatCommandSearchResult res = FindCommand(getCommandTable(), text, command, &parentCommand); + + switch (res) + { + case CHAT_COMMAND_OK: + { + std::string realCommandFull = command->FullName; + + if (command->server == NODE) + ForwardCommandToNode(); + else if (command->server == MSTR) + ForwardCommandToMaster(); + + if (text[0]) + { + realCommandFull += " "; + realCommandFull += text; + } + if (m_session && command->Flags & COMMAND_FLAGS_ONLY_ON_SELF) + { + ObjectGuid selGuid = m_session->GetPlayer()->GetSelectionGuid(); + if (!selGuid.IsEmpty() && selGuid != m_session->GetPlayer()->GetObjectGuid()) + { + PSendSysMessage("|cFF8DE2FFYou can use the command [%s] only on yourself|r", command->FullName.c_str()); + return; + } + } + SetSentErrorMessage(false); + if ((this->*(command->Handler))((char*)text)) // text content destroyed at call + { + if (m_session && command->Flags & COMMAND_FLAGS_CRITICAL) + { + if (Unit* target = getSelectedUnit()) + sLog.out(LOG_GM_CRITICAL, "%s: %s. Selected %s. Map %u", m_session->GetUsername().c_str(), realCommandFull.c_str(), target->GetObjectGuid().GetString().c_str(), target->GetMapId()); + else + sLog.out(LOG_GM_CRITICAL, "%s: %s.", m_session->GetUsername().c_str(), realCommandFull.c_str()); + } + if (command->SecurityLevel > SEC_PLAYER) + { + // chat case + if (m_session && m_session->GetPlayer()) + { + Player* p = m_session->GetPlayer(); + ObjectGuid sel_guid = p->GetSelectionGuid(); + sLog.outCommand(GetAccountId(), "Command: %s [Player: %s (Group Leader \"%s\", Account: %u) X: %f Y: %f Z: %f Map: %u Selected: %s]", + realCommandFull.c_str(), p->GetName(), p->GetGroup() ? p->GetGroup()->GetLeaderGuid().GetString().c_str() : "NULL", GetAccountId(), p->GetPositionX(), p->GetPositionY(), p->GetPositionZ(), p->GetMapId(), + sel_guid.GetString().c_str()); + } + else // 0 account -> console + { + sLog.outCommand(GetAccountId(), "Command: %s [Account: %u from %s]", + realCommandFull.c_str(), GetAccountId(), GetAccountId() ? "RA-connection" : "Console"); + } + } + } + // some commands have custom error messages. Don't send the default one in these cases. + else if (!HasSentErrorMessage()) + { + if (!command->Help.empty()) + SendSysMessage(command->Help.c_str()); + else + SendSysMessage(LANG_CMD_SYNTAX); + + if (ChatCommand* showCommand = (strlen(command->Name) == 0 && parentCommand ? parentCommand : command)) + if (ChatCommand* childs = showCommand->ChildCommands) + ShowHelpForSubCommands(childs, showCommand->Name); + + SetSentErrorMessage(true); + } + break; + } + case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: + { + SendSysMessage(LANG_NO_SUBCMD); + ShowHelpForCommand(command->ChildCommands, text); + SetSentErrorMessage(true); + break; + } + case CHAT_COMMAND_UNKNOWN: + { + SendSysMessage(LANG_NO_CMD); + SetSentErrorMessage(true); + break; + } + } +} + +/** + * Function find appropriate command and update command security level and help text + * + * @param commandTable Table for first level command search + * @param text Command line string that will parsed for (sub)command search + * @param security New security level for command + * @param help New help text for command + * + * @return true if command has been found, and false in other case + * + * All problems found while command search and updated output as to DB errors log + */ +bool ChatHandler::SetDataForCommandInTable(ChatCommand *commandTable, const char* text, uint32 security, std::string const& help, uint32 flags) +{ + std::string fullcommand = text; // original `text` can't be used. It content destroyed in command code processing. + + ChatCommand* command = nullptr; + std::string cmdName; + + ChatCommandSearchResult res = FindCommand(commandTable, text, command, nullptr, &cmdName, true, true); + + switch (res) + { + case CHAT_COMMAND_OK: + { + if (command->SecurityLevel != security) + DETAIL_LOG("Table `command` overwrite for command '%s' default security (%u) by %u", + fullcommand.c_str(), command->SecurityLevel, security); + + command->SecurityLevel = security; + command->Help = help; + command->Flags = flags; + return true; + } + case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: + { + // command have subcommands, but not '' subcommand and then any data in `command` useless for it. + if (cmdName.empty()) + sLog.outErrorDb("Table `command` have command '%s' that only used with some subcommand selection, it can't have help or overwritten access level, skip.", cmdName.c_str()); + else + sLog.outErrorDb("Table `command` have unexpected subcommand '%s' in command '%s', skip.", cmdName.c_str(), fullcommand.c_str()); + return false; + } + case CHAT_COMMAND_UNKNOWN: + { + sLog.outErrorDb("Table `command` have nonexistent command '%s', skip.", cmdName.c_str()); + return false; + } + } + + return false; +} + +bool ChatHandler::ParseCommands(const char* text) +{ + MANGOS_ASSERT(text); + MANGOS_ASSERT(*text); + + //if(m_session->GetSecurity() == SEC_PLAYER) + // return false; + + /// chat case (.command or !command format) + if (m_session) + { + if (text[0] != '!' && text[0] != '.') + return false; + + /// ignore single . and ! in line + if (strlen(text) < 2) + return false; + } + + /// ignore messages staring from many dots. + if ((text[0] == '.' && text[1] == '.') || (text[0] == '!' && text[1] == '!')) + return false; + + /// skip first . or ! (in console allowed use command with . and ! and without its) + if (text[0] == '!' || text[0] == '.') + ++text; + + ExecuteCommand(text); + + return true; +} + +bool ChatHandler::ShowHelpForSubCommands(ChatCommand *table, char const* cmd) +{ + std::string list; + for (uint32 i = 0; table[i].Name != nullptr; ++i) + { + // must be available (ignore handler existence for show command with possible available subcommands + if (!isAvailable(table[i])) + continue; + + if (m_session) + list += "\n "; + else + list += "\n\r "; + + list += table[i].Name; + + if (table[i].ChildCommands) + list += " ..."; + } + + if (list.empty()) + return false; + + if (table == getCommandTable()) + { + SendSysMessage(LANG_AVIABLE_CMD); + SendSysMessage(list.c_str()); + } + else + { + PSendSysMessage(LANG_SUBCMDS_LIST, cmd); + SendSysMessage(list.c_str()); + } + return true; +} + +bool ChatHandler::ShowHelpForCommand(ChatCommand *table, const char* cmd) +{ + char const* oldCmd = cmd; + ChatCommand* command = nullptr; + ChatCommand* parentCommand = nullptr; + + ChatCommand* showCommand = nullptr; + ChatCommand* childCommands = nullptr; + + ChatCommandSearchResult res = FindCommand(table, cmd, command, &parentCommand); + + switch (res) + { + case CHAT_COMMAND_OK: + { + // for "" subcommand use parent command if any for subcommands list output + if (strlen(command->Name) == 0 && parentCommand) + showCommand = parentCommand; + else + showCommand = command; + + childCommands = showCommand->ChildCommands; + break; + } + case CHAT_COMMAND_UNKNOWN_SUBCOMMAND: + showCommand = command; + childCommands = showCommand->ChildCommands; + break; + case CHAT_COMMAND_UNKNOWN: + // not show command list at error in first level command find fail + childCommands = table != getCommandTable() || strlen(oldCmd) == 0 ? table : NULL; + command = nullptr; + break; + } + + if (command && !command->Help.empty()) + SendSysMessage(command->Help.c_str()); + + if (childCommands) + if (ShowHelpForSubCommands(childCommands, showCommand ? showCommand->Name : "")) + return true; + + if (command && command->Help.empty()) + SendSysMessage(LANG_NO_HELP_CMD); + + return command || childCommands; +} + +bool ChatHandler::isValidChatMessage(const char* message) +{ + /* + + valid examples: + |cffa335ee|Hitem:812:0:0:0:0:0:0:0:70|h[Glowing Brightwood Staff]|h|r + |cff808080|Hquest:2278:47|h[The Platinum Discs]|h|r + |cff4e96f7|Htalent:2232:-1|h[Taste for Blood]|h|r + |cff71d5ff|Hspell:21563|h[Command]|h|r + |cffffd000|Henchant:3919|h[Engineering: Rough Dynamite]|h|r + + | will be escaped to || + */ + + if (strlen(message) > 255) + return false; + + const char validSequence[6] = "cHhhr"; + const char* validSequenceIterator = validSequence; + + // more simple checks + if (sWorld.getConfig(CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY) < 3) + { + const std::string validCommands = "cHhr|"; + + while (*message) + { + // find next pipe command + message = strchr(message, '|'); + + if (!message) + return true; + + ++message; + char commandChar = *message; + if (validCommands.find(commandChar) == std::string::npos) + return false; + + ++message; + // validate sequence + if (sWorld.getConfig(CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY) == 2) + { + if (commandChar == *validSequenceIterator) + { + if (validSequenceIterator == validSequence + 4) + validSequenceIterator = validSequence; + else + ++validSequenceIterator; + } + else if (commandChar != '|') + return false; + } + } + return true; + } + + std::istringstream reader(message); + char buffer[256]; + + uint32 color = 0; + + ItemPrototype const* linkedItem = nullptr; + Quest const* linkedQuest = nullptr; + SpellEntry const *linkedSpell = nullptr; + ItemRandomPropertiesEntry const* itemProperty = nullptr; + + while (!reader.eof()) + { + if (validSequence == validSequenceIterator) + { + linkedItem = nullptr; + linkedQuest = nullptr; + linkedSpell = nullptr; + itemProperty = nullptr; + + reader.ignore(255, '|'); + } + else if (reader.get() != '|') + { + DEBUG_LOG("ChatHandler::isValidChatMessage sequence aborted unexpectedly"); + return false; + } + + // pipe has always to be followed by at least one char + if (reader.peek() == '\0') + { + DEBUG_LOG("ChatHandler::isValidChatMessage pipe followed by \\0"); + return false; + } + + // no further pipe commands + if (reader.eof()) + break; + + char commandChar; + reader >> commandChar; + + // | in normal messages is escaped by || + if (commandChar != '|') + { + if (commandChar == *validSequenceIterator) + { + if (validSequenceIterator == validSequence + 4) + validSequenceIterator = validSequence; + else + ++validSequenceIterator; + } + else + { + DEBUG_LOG("ChatHandler::isValidChatMessage invalid sequence, expected %c but got %c", *validSequenceIterator, commandChar); + return false; + } + } + else if (validSequence != validSequenceIterator) + { + // no escaped pipes in sequences + DEBUG_LOG("ChatHandler::isValidChatMessage got escaped pipe in sequence"); + return false; + } + + switch (commandChar) + { + case 'c': + color = 0; + // validate color, expect 8 hex chars + for (int i = 0; i < 8; i++) + { + char c; + reader >> c; + if (!c) + { + DEBUG_LOG("ChatHandler::isValidChatMessage got \\0 while reading color in |c command"); + return false; + } + + color <<= 4; + // check for hex char + if (c >= '0' && c <= '9') + { + color |= c - '0'; + continue; + } + if (c >= 'a' && c <= 'f') + { + color |= 10 + c - 'a'; + continue; + } + DEBUG_LOG("ChatHandler::isValidChatMessage got non hex char '%c' while reading color", c); + return false; + } + break; + case 'H': + // read chars up to colon = link type + reader.getline(buffer, 256, ':'); + if (reader.eof()) // : must be + return false; + + if (strcmp(buffer, "item") == 0) + { + // read item entry + reader.getline(buffer, 256, ':'); + if (reader.eof()) // : must be + return false; + + linkedItem = ObjectMgr::GetItemPrototype(atoi(buffer)); + if (!linkedItem) + { + DEBUG_LOG("ChatHandler::isValidChatMessage got invalid itemID %u in |item command", atoi(buffer)); + return false; + } + + if (color != ItemQualityColors[linkedItem->Quality]) + { + DEBUG_LOG("ChatHandler::isValidChatMessage linked item has color %u, but user claims %u", ItemQualityColors[linkedItem->Quality], + color); + return false; + } + + // the itementry is followed by several integers which describe an instance of this item + + // position relative after itemEntry + const uint8 randomPropertyPosition = 6; + + int32 propertyId = 0; + bool negativeNumber = false; + char c; + for (uint8 i = 0; i < randomPropertyPosition; ++i) + { + propertyId = 0; + negativeNumber = false; + while ((c = reader.get()) != ':') + { + if (c >= '0' && c <= '9') + { + propertyId *= 10; + propertyId += c - '0'; + } + else if (c == '-') + negativeNumber = true; + else + return false; + } + } + if (negativeNumber) + propertyId *= -1; + + if (propertyId > 0) + { + itemProperty = sItemRandomPropertiesStore.LookupEntry(propertyId); + if (!itemProperty) + return false; + } + + // ignore other integers + while ((c >= '0' && c <= '9') || c == ':') + { + reader.ignore(1); + c = reader.peek(); + } + } + else if (strcmp(buffer, "quest") == 0) + { + // no color check for questlinks, each client will adapt it anyway + uint32 questid = 0; + // read questid + char c = reader.peek(); + while (c >= '0' && c <= '9') + { + reader.ignore(1); + questid *= 10; + questid += c - '0'; + c = reader.peek(); + } + + linkedQuest = sObjectMgr.GetQuestTemplate(questid); + + if (!linkedQuest) + { + DEBUG_LOG("ChatHandler::isValidChatMessage Questtemplate %u not found", questid); + return false; + } + + if (c != ':') + { + DEBUG_LOG("ChatHandler::isValidChatMessage Invalid quest link structure"); + return false; + } + + reader.ignore(1); + c = reader.peek(); + // level + uint32 questlevel = 0; + while (c >= '0' && c <= '9') + { + reader.ignore(1); + questlevel *= 10; + questlevel += c - '0'; + c = reader.peek(); + } + + if (questlevel >= STRONG_MAX_LEVEL) + { + DEBUG_LOG("ChatHandler::isValidChatMessage Quest level %u too big", questlevel); + return false; + } + + if (c != '|') + { + DEBUG_LOG("ChatHandler::isValidChatMessage Invalid quest link structure"); + return false; + } + } + else if (strcmp(buffer, "talent") == 0) + { + // talent links are always supposed to be blue + if (color != CHAT_LINK_COLOR_TALENT) + return false; + + // read talent entry + reader.getline(buffer, 256, ':'); + if (reader.eof()) // : must be + return false; + + TalentEntry const *talentInfo = sTalentStore.LookupEntry(atoi(buffer)); + if (!talentInfo) + return false; + + linkedSpell = sSpellMgr.GetSpellEntry(talentInfo->RankID[0]); + if (!linkedSpell) + return false; + + char c = reader.peek(); + // skillpoints? whatever, drop it + while (c != '|' && c != '\0') + { + reader.ignore(1); + c = reader.peek(); + } + } + else if (strcmp(buffer, "spell") == 0) + { + if (color != CHAT_LINK_COLOR_SPELL) + return false; + + uint32 spellid = 0; + // read spell entry + char c = reader.peek(); + while (c >= '0' && c <= '9') + { + reader.ignore(1); + spellid *= 10; + spellid += c - '0'; + c = reader.peek(); + } + linkedSpell = sSpellMgr.GetSpellEntry(spellid); + if (!linkedSpell) + return false; + } + else if (strcmp(buffer, "enchant") == 0) + { + if (color != CHAT_LINK_COLOR_ENCHANT) + return false; + + uint32 spellid = 0; + // read spell entry + char c = reader.peek(); + while (c >= '0' && c <= '9') + { + reader.ignore(1); + spellid *= 10; + spellid += c - '0'; + c = reader.peek(); + } + linkedSpell = sSpellMgr.GetSpellEntry(spellid); + if (!linkedSpell) + return false; + } + else + { + DEBUG_LOG("ChatHandler::isValidChatMessage user sent unsupported link type '%s'", buffer); + return false; + } + break; + case 'h': + // if h is next element in sequence, this one must contain the linked text :) + if (*validSequenceIterator == 'h') + { + // links start with '[' + if (reader.get() != '[') + { + DEBUG_LOG("ChatHandler::isValidChatMessage link caption doesn't start with '['"); + return false; + } + reader.getline(buffer, 256, ']'); + if (reader.eof()) // ] must be + return false; + + // verify the link name + if (linkedSpell) + { + // spells with that flag have a prefix of "$PROFESSION: " + if (linkedSpell->Attributes & SPELL_ATTR_TRADESPELL) + { + // lookup skillid + SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(linkedSpell->Id); + if (bounds.first == bounds.second) + return false; + + SkillLineAbilityEntry const *skillInfo = bounds.first->second; + + if (!skillInfo) + return false; + + SkillLineEntry const *skillLine = sSkillLineStore.LookupEntry(skillInfo->skillId); + if (!skillLine) + return false; + + for (uint8 i = 0; i < MAX_DBC_LOCALE; ++i) + { + uint32 skillLineNameLength = strlen(skillLine->name[i]); + if (skillLineNameLength > 0 && strncmp(skillLine->name[i], buffer, skillLineNameLength) == 0) + { + // found the prefix, remove it to perform spellname validation below + // -2 = strlen(": ") + uint32 spellNameLength = strlen(buffer) - skillLineNameLength - 2; + memmove(buffer, buffer + skillLineNameLength + 2, spellNameLength + 1); + } + } + } + bool foundName = false; + for (uint8 i = 0; i < MAX_DBC_LOCALE; ++i) + { + if (*linkedSpell->SpellName[i] && strcmp(linkedSpell->SpellName[i], buffer) == 0) + { + foundName = true; + break; + } + } + if (!foundName) + return false; + } + else if (linkedQuest) + { + if (linkedQuest->GetTitle() != buffer) + { + QuestLocale const *ql = sObjectMgr.GetQuestLocale(linkedQuest->GetQuestId()); + + if (!ql) + { + DEBUG_LOG("ChatHandler::isValidChatMessage default questname didn't match and there is no locale"); + return false; + } + + bool foundName = false; + for (uint8 i = 0; i < ql->Title.size(); i++) + { + if (ql->Title[i] == buffer) + { + foundName = true; + break; + } + } + if (!foundName) + { + DEBUG_LOG("ChatHandler::isValidChatMessage no quest locale title matched"); + return false; + } + } + } + else if (linkedItem) + { + std::string expectedName = std::string(linkedItem->Name1); + + if (expectedName != buffer) + { + ItemLocale const *il = sObjectMgr.GetItemLocale(linkedItem->ItemId); + + bool foundName = false; + for (uint8 i = LOCALE_koKR; i < MAX_LOCALE; ++i) + { + int8 dbIndex = sObjectMgr.GetIndexForLocale(LocaleConstant(i)); + if (dbIndex == -1 || il == nullptr || (size_t)dbIndex >= il->Name.size()) + // using strange database/client combinations can lead to this case + expectedName = linkedItem->Name1; + else + expectedName = il->Name[dbIndex]; + + if (expectedName == buffer) + { + foundName = true; + break; + } + } + if (!foundName) + { + DEBUG_LOG("ChatHandler::isValidChatMessage linked item name wasn't found in any localization"); + return false; + } + } + } + // that place should never be reached - if nothing linked has been set in |H + // it will return false before + else + return false; + } + break; + case 'r': + case '|': + // no further payload + break; + default: + DEBUG_LOG("ChatHandler::isValidChatMessage got invalid command |%c", commandChar); + return false; + } + } + + // check if every opened sequence was also closed properly + if (validSequence != validSequenceIterator) + DEBUG_LOG("ChatHandler::isValidChatMessage EOF in active sequence"); + + return validSequence == validSequenceIterator; +} + +//Note: target_guid used only in CHAT_MSG_WHISPER_INFORM mode (in this case channelName ignored) +void ChatHandler::FillMessageData(WorldPacket *data, WorldSession* session, uint8 type, uint32 language, const char *channelName, ObjectGuid targetGuid, const char *message, Unit *speaker) +{ + uint32 messageLength = (message ? strlen(message) : 0) + 1; + + data->Initialize(SMSG_MESSAGECHAT, 100); // guess size + *data << uint8(type); + if ((type != CHAT_MSG_CHANNEL && type != CHAT_MSG_WHISPER) || language == LANG_ADDON) + *data << uint32(language); + else + *data << uint32(LANG_UNIVERSAL); + + if (type == CHAT_MSG_CHANNEL) + { + MANGOS_ASSERT(channelName); + *data << channelName; + } + + switch (type) + { + case CHAT_MSG_SAY: + case CHAT_MSG_PARTY: + case CHAT_MSG_RAID: + case CHAT_MSG_GUILD: + case CHAT_MSG_OFFICER: + case CHAT_MSG_YELL: + case CHAT_MSG_WHISPER: + case CHAT_MSG_CHANNEL: + case CHAT_MSG_RAID_LEADER: + case CHAT_MSG_RAID_WARNING: + case CHAT_MSG_BG_SYSTEM_NEUTRAL: + case CHAT_MSG_BG_SYSTEM_ALLIANCE: + case CHAT_MSG_BG_SYSTEM_HORDE: + case CHAT_MSG_BATTLEGROUND: + case CHAT_MSG_BATTLEGROUND_LEADER: + targetGuid = session ? session->GetPlayer()->GetObjectGuid() : ObjectGuid(); + break; + case CHAT_MSG_MONSTER_SAY: + case CHAT_MSG_MONSTER_PARTY: + case CHAT_MSG_MONSTER_YELL: + case CHAT_MSG_MONSTER_WHISPER: + case CHAT_MSG_MONSTER_EMOTE: +// case CHAT_MSG_RAID_BOSS_WHISPER: // Nostalrius : Pas en 1.12 + case CHAT_MSG_RAID_BOSS_EMOTE: + { + // Nostalrius : fix structure + switch (type) + { + case CHAT_MSG_MONSTER_EMOTE: + case CHAT_MSG_RAID_BOSS_EMOTE: + case CHAT_MSG_MONSTER_WHISPER: + break; + default: + *data << ObjectGuid(speaker->GetObjectGuid()); + } + *data << uint32(strlen(speaker->GetName()) + 1); + *data << speaker->GetName(); + ObjectGuid listener_guid; + *data << listener_guid; + if (listener_guid && !listener_guid.IsPlayer()) + { + *data << uint32(1); // string listener_name_length + *data << uint8(0); // string listener_name + } + *data << uint32(messageLength); + *data << message; + *data << uint8(0); + return; + } + default: + if (type != CHAT_MSG_REPLY && type != CHAT_MSG_IGNORED && type != CHAT_MSG_DND && type != CHAT_MSG_AFK) + targetGuid.Clear(); // only for CHAT_MSG_WHISPER_INFORM used original value target_guid + break; + } + + *data << ObjectGuid(targetGuid); // there 0 for BG messages + if (type == CHAT_MSG_SAY || type == CHAT_MSG_YELL || type == CHAT_MSG_PARTY) + *data << ObjectGuid(targetGuid); + *data << uint32(messageLength); + *data << message; + if (session != nullptr && type != CHAT_MSG_REPLY && type != CHAT_MSG_DND && type != CHAT_MSG_AFK) + *data << uint8(session->GetPlayer()->chatTag()); + else + *data << uint8(0); +} + +Player * ChatHandler::getSelectedPlayer() +{ + if (!m_session) + return nullptr; + + ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid(); + + if (!guid) + return m_session->GetPlayer(); + + return sObjectMgr.GetPlayer(guid); +} + +Unit* ChatHandler::getSelectedUnit() +{ + if (!m_session) + return nullptr; + + ObjectGuid guid = m_session->GetPlayer()->GetSelectionGuid(); + + if (!guid) + return m_session->GetPlayer(); + + // can be selected player at another map + return ObjectAccessor::GetUnit(*m_session->GetPlayer(), guid); +} + +Creature* ChatHandler::getSelectedCreature() +{ + if (!m_session) + return nullptr; + + return m_session->GetPlayer()->GetMap()->GetAnyTypeCreature(m_session->GetPlayer()->GetSelectionGuid()); +} + +/** + * Function skip all whitespaces in args string + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * allowed NULL string pointer stored in *args + */ +void ChatHandler::SkipWhiteSpaces(char** args) +{ + if (!*args) + return; + + while (isWhiteSpace(**args)) + ++(*args); +} + +/** + * Function extract to val arg signed integer value or fail + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @return true if value extraction successful + */ +bool ChatHandler::ExtractInt32(char** args, int32& val) +{ + if (!*args || !**args) + return false; + + char* tail = *args; + + long valRaw = strtol(*args, &tail, 10); + + if (tail != *args && isWhiteSpace(*tail)) + *(tail++) = '\0'; + else if (tail && *tail) // some not whitespace symbol + return false; // args not modified and can be re-parsed + + if (valRaw < std::numeric_limits::min() || valRaw > std::numeric_limits::max()) + return false; + + // value successfully extracted + val = int32(valRaw); + *args = tail; + return true; +} + +/** + * Function extract to val arg optional signed integer value or use default value. Fail if extracted not signed integer. + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @param defVal default value used if no data for extraction in args + * @return true if value extraction successful + */ +bool ChatHandler::ExtractOptInt32(char** args, int32& val, int32 defVal) +{ + if (!*args || !**args) + { + val = defVal; + return true; + } + + return ExtractInt32(args, val); +} + +/** + * Function extract to val arg unsigned integer value or fail + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @param base set used base for extracted value format (10 for decimal, 16 for hex, etc), 0 let auto select by system internal function + * @return true if value extraction successful + */ +bool ChatHandler::ExtractUInt32Base(char** args, uint32& val, uint32 base) +{ + if (!*args || !**args) + return false; + + char* tail = *args; + + unsigned long valRaw = strtoul(*args, &tail, base); + + if (tail != *args && isWhiteSpace(*tail)) + *(tail++) = '\0'; + else if (tail && *tail) // some not whitespace symbol + return false; // args not modified and can be re-parsed + + if (valRaw > std::numeric_limits::max()) + return false; + + // value successfully extracted + val = uint32(valRaw); + *args = tail; + + SkipWhiteSpaces(args); + return true; +} + +/** + * Function extract to val arg optional unsigned integer value or use default value. Fail if extracted not unsigned integer. + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @param defVal default value used if no data for extraction in args + * @return true if value extraction successful + */ +bool ChatHandler::ExtractOptUInt32(char** args, uint32& val, uint32 defVal) +{ + if (!*args || !**args) + { + val = defVal; + return true; + } + + return ExtractUInt32(args, val); +} + +/** + * Function extract to val arg float value or fail + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @return true if value extraction successful + */ +bool ChatHandler::ExtractFloat(char** args, float& val) +{ + if (!*args || !**args) + return false; + + char* tail = *args; + + double valRaw = strtod(*args, &tail); + + if (tail != *args && isWhiteSpace(*tail)) + *(tail++) = '\0'; + else if (tail && *tail) // some not whitespace symbol + return false; // args not modified and can be re-parsed + + // value successfully extracted + val = float(valRaw); + *args = tail; + + SkipWhiteSpaces(args); + return true; +} + +/** + * Function extract to val arg optional float value or use default value. Fail if extracted not float. + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @param defVal default value used if no data for extraction in args + * @return true if value extraction successful + */ +bool ChatHandler::ExtractOptFloat(char** args, float& val, float defVal) +{ + if (!*args || !**args) + { + val = defVal; + return true; + } + + return ExtractFloat(args, val); +} + +/** + * Function extract name-like string (from non-numeric or special symbol until whitespace) + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param lit optional explicit literal requirement. function fail if literal is not starting substring of lit. + * Note: function in same way fail if no any literal or literal not fit in this case. Need additional check for select specific fail case + * @return name/number-like string without whitespaces, or NULL if args empty or not appropriate content. + */ +char* ChatHandler::ExtractLiteralArg(char** args, char const* lit /*= NULL*/) +{ + if (!*args || !**args) + return nullptr; + + char* head = *args; + + // reject quoted string or link (|-started text) + switch (head[0]) + { + // reject quoted string + case '[': + case '\'': + case '"': + return nullptr; + // reject link (|-started text) + case '|': + // client replace all | by || in raw text + if (head[1] != '|') + return nullptr; + ++head; // skip one | + break; + default: + break; + } + + if (lit) + { + int l = strlen(lit); + int diff = strncmp(head, lit, l); + + if (diff != 0) + return nullptr; + + if (head[l] && !isWhiteSpace(head[l])) + return nullptr; + + char* arg = head; + + if (head[l]) + { + head[l] = '\0'; + + head += l + 1; + + *args = head; + } + else + *args = head + l; + + SkipWhiteSpaces(args); + return arg; + } + + char* name = strtok(head, " "); + + char* tail = strtok(nullptr, ""); + + *args = tail ? tail : (char*)""; // *args don't must be NULL + + SkipWhiteSpaces(args); + + return name; +} + +/** + * Function extract quote-like string (any characters guarded by some special character, in our cases ['") + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param asis control save quote string wrappers + * @return quote-like string, or NULL if args empty or not appropriate content. + */ +char* ChatHandler::ExtractQuotedArg(char** args, bool asis /*= false*/) +{ + if (!*args || !**args) + return nullptr; + + if (**args != '\'' && **args != '"' && **args != '[') + return nullptr; + + char guard = (*args)[0]; + + if (guard == '[') + guard = ']'; + + char* tail = (*args) + 1; // start scan after first quote symbol + char* head = asis ? *args : tail; // start arg + + while (*tail && *tail != guard) + ++tail; + + if (!*tail || (tail[1] && !isWhiteSpace(tail[1]))) // fail + return nullptr; + + if (!tail[1]) // quote is last char in string + { + if (!asis) + *tail = '\0'; + } + else // quote isn't last char + { + if (asis) + ++tail; + + *tail = '\0'; + } + + *args = tail + 1; + + SkipWhiteSpaces(args); + + return head; +} + +/** + * Function extract quote-like string or literal if quote not detected + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param asis control save quote string wrappers + * @return quote/literal string, or NULL if args empty or not appropriate content. + */ +char* ChatHandler::ExtractQuotedOrLiteralArg(char** args, bool asis /*= false*/) +{ + char *arg = ExtractQuotedArg(args, asis); + if (!arg) + arg = ExtractLiteralArg(args); + return arg; +} + +/** + * Function extract on/off literals as boolean values + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param val return extracted value if function success, in fail case original value unmodified + * @return true at success + */ +bool ChatHandler::ExtractOnOff(char** args, bool& value) +{ + char* arg = ExtractLiteralArg(args); + if (!arg) + return false; + + if (strncmp(arg, "on", 3) == 0 || strncmp(arg, "ON", 3) == 0) + value = true; + else if (strncmp(arg, "off", 4) == 0 || strncmp(arg, "OFF", 4) == 0) + value = false; + else + return false; + + return true; +} + +/** + * Function extract shift-link-like string (any characters guarded by | and |h|r with some additional internal structure check) + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * + * @param linkTypes optional NULL-terminated array of link types, shift-link must fit one from link type from array if provided or extraction fail + * + * @param found_idx if not NULL then at return index in linkTypes that fit shift-link type, if extraction fail then non modified + * + * @param keyPair if not NULL then pointer to 2-elements array for return start and end pointer for found key + * if extraction fail then non modified + * + * @param somethingPair then pointer to 2-elements array for return start and end pointer if found. + * if not NULL then shift-link must have data field, if extraction fail then non modified + * + * @return shift-link-like string, or NULL if args empty or not appropriate content. + */ +char* ChatHandler::ExtractLinkArg(char** args, char const* const* linkTypes /*= NULL*/, int* foundIdx /*= NULL*/, char** keyPair /*= NULL*/, char** somethingPair /*= NULL*/) +{ + if (!*args || !**args) + return nullptr; + + // skip if not linked started or encoded single | (doubled by client) + if ((*args)[0] != '|' || (*args)[1] == '|') + return nullptr; + + // |color|Hlinktype:key:data...|h[name]|h|r + + char* head = *args; + + // [name] Shift-click form |color|linkType:key|h[name]|h|r + // or + // [name] Shift-click form |color|linkType:key:something1:...:somethingN|h[name]|h|r + // or + // [name] Shift-click form |linkType:key|h[name]|h|r + + // |color|Hlinktype:key:data...|h[name]|h|r + + char* tail = (*args) + 1; // skip | + + if (*tail != 'H') // skip color part, some links can not have color part + { + while (*tail && *tail != '|') + ++tail; + + if (!*tail) + return nullptr; + + // |Hlinktype:key:data...|h[name]|h|r + + ++tail; // skip | + } + + // Hlinktype:key:data...|h[name]|h|r + + if (*tail != 'H') + return nullptr; + + int linktype_idx = 0; + + if (linkTypes) // check link type if provided + { + // check linktypes (its include H in name) + for (; linkTypes[linktype_idx]; ++linktype_idx) + { + // exactly string with follow : or | + int l = strlen(linkTypes[linktype_idx]); + if (strncmp(tail, linkTypes[linktype_idx], l) == 0 && + (tail[l] == ':' || tail[l] == '|')) + break; + } + + // is search fail? + if (!linkTypes[linktype_idx]) // NULL terminator in last element + return nullptr; + + tail += strlen(linkTypes[linktype_idx]); // skip linktype string + + // :key:data...|h[name]|h|r + + if (*tail != ':') + return nullptr; + } + else + { + while (*tail && *tail != ':') // skip linktype string + ++tail; + + if (!*tail) + return nullptr; + } + + ++tail; + + // key:data...|h[name]|h|r + char* keyStart = tail; // remember key start for return + char* keyEnd = tail; // key end for truncate, will updated + + while (*tail && *tail != '|' && *tail != ':') + ++tail; + + if (!*tail) + return nullptr; + + keyEnd = tail; // remember key end for truncate + + // |h[name]|h|r or :something...|h[name]|h|r + + char* somethingStart = tail + 1; + char* somethingEnd = tail + 1; // will updated later if need + + if (*tail == ':' && somethingPair) // optional data extraction + { + // :something...|h[name]|h|r + + if (*tail == ':') + ++tail; + + // something|h[name]|h|r or something:something2...|h[name]|h|r + + while (*tail && *tail != '|' && *tail != ':') + ++tail; + + if (!*tail) + return nullptr; + + somethingEnd = tail; // remember data end for truncate + } + + // |h[name]|h|r or :something2...|h[name]|h|r + + while (*tail && (*tail != '|' || *(tail + 1) != 'h')) // skip ... part if exist + ++tail; + + if (!*tail) + return nullptr; + + // |h[name]|h|r + + tail += 2; // skip |h + + // [name]|h|r + if (!*tail || *tail != '[') + return nullptr; + + while (*tail && (*tail != ']' || *(tail + 1) != '|')) // skip name part + ++tail; + + tail += 2; // skip ]| + + // h|r + if (!*tail || *tail != 'h' || *(tail + 1) != '|') + return nullptr; + + tail += 2; // skip h| + + // r + if (!*tail || *tail != 'r' || (*(tail + 1) && !isWhiteSpace(*(tail + 1)))) + return nullptr; + + ++tail; // skip r + + // success + + if (*tail) // truncate all link string + *(tail++) = '\0'; + + if (foundIdx) + *foundIdx = linktype_idx; + + if (keyPair) + { + keyPair[0] = keyStart; + keyPair[1] = keyEnd; + } + + if (somethingPair) + { + somethingPair[0] = somethingStart; + somethingPair[1] = somethingEnd; + } + + *args = tail; + + SkipWhiteSpaces(args); + + return head; +} + +/** + * Function extract name/number/quote/shift-link-like string + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * @param asis control save quote string wrappers + * @return extracted arg string, or NULL if args empty or not appropriate content. + */ +char* ChatHandler::ExtractArg(char** args, bool asis /*= false*/) +{ + if (!*args || !**args) + return nullptr; + + char* arg = ExtractQuotedOrLiteralArg(args, asis); + if (!arg) + arg = ExtractLinkArg(args); + + return arg; +} + +/** + * Function extract name/quote/number/shift-link-like string, and return it if args have more non-whitespace data + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * if args have only single arg then args still pointing to this arg (unmodified pointer) + * @return extracted string, or NULL if args empty or not appropriate content or have single arg totally. + */ +char* ChatHandler::ExtractOptNotLastArg(char** args) +{ + char* arg = ExtractArg(args, true); + + // have more data + if (*args && **args) + return arg; + + // optional name not found + *args = arg ? arg : (char*)""; // *args don't must be NULL + + return nullptr; +} + +/** + * Function extract data from shift-link "|color|LINKTYPE:RETURN:SOMETHING1|h[name]|h|r if linkType == LINKTYPE + * It also extract literal/quote if not shift-link in args + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * if args have sift link with linkType != LINKTYPE then args still pointing to this arg (unmodified pointer) + * + * @param linkType shift-link must fit by link type to this arg value or extraction fail + * + * @param something1 if not NULL then shift-link must have data field and it returned into this arg + * if extraction fail then non modified + * + * @return extracted key, or NULL if args empty or not appropriate content or not fit to linkType. + */ +char* ChatHandler::ExtractKeyFromLink(char** text, char const* linkType, char** something1 /*= NULL*/) +{ + char const* linkTypes[2]; + linkTypes[0] = linkType; + linkTypes[1] = nullptr; + + int foundIdx; + + return ExtractKeyFromLink(text, linkTypes, &foundIdx, something1); +} + +/** + * Function extract data from shift-link "|color|LINKTYPE:RETURN:SOMETHING1|h[name]|h|r if LINKTYPE in linkTypes array + * It also extract literal/quote if not shift-link in args + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * if args have sift link with linkType != LINKTYPE then args still pointing to this arg (unmodified pointer) + * + * @param linkTypes NULL-terminated array of link types, shift-link must fit one from link type from array or extraction fail + * + * @param found_idx if not NULL then at return index in linkTypes that fit shift-link type, for non-link case return -1 + * if extraction fail then non modified + * + * @param something1 if not NULL then shift-link must have data field and it returned into this arg + * if extraction fail then non modified + * + * @return extracted key, or NULL if args empty or not appropriate content or not fit to linkType. + */ +char* ChatHandler::ExtractKeyFromLink(char** text, char const* const* linkTypes, int* found_idx, char** something1 /*= NULL*/) +{ + // skip empty + if (!*text || !**text) + return nullptr; + + // return non link case + char* arg = ExtractQuotedOrLiteralArg(text); + if (arg) + { + if (found_idx) + *found_idx = -1; // special index case + + return arg; + } + + char* keyPair[2]; + char* somethingPair[2]; + + arg = ExtractLinkArg(text, linkTypes, found_idx, keyPair, something1 ? somethingPair : NULL); + if (!arg) + return nullptr; + + *keyPair[1] = '\0'; // truncate key string + + if (something1) + { + *somethingPair[1] = '\0'; // truncate data string + *something1 = somethingPair[0]; + } + + return keyPair[0]; +} + +/** + * Function extract uint32 key from shift-link "|color|LINKTYPE:RETURN|h[name]|h|r if linkType == LINKTYPE + * It also extract direct number if not shift-link in args + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * if args have sift link with linkType != LINKTYPE then args still pointing to this arg (unmodified pointer) + * + * @param linkType shift-link must fit by link type to this arg value or extraction fail + * + * @param value store result value at success return, not modified at fail + * + * @return true if extraction succesful + */ +bool ChatHandler::ExtractUint32KeyFromLink(char** text, char const* linkType, uint32& value) +{ + char* arg = ExtractKeyFromLink(text, linkType); + if (!arg) + return false; + + return ExtractUInt32(&arg, value); +} + +GameObject* ChatHandler::GetGameObjectWithGuid(uint32 lowguid, uint32 entry) +{ + if (!m_session) + return nullptr; + + Player* pl = m_session->GetPlayer(); + + return pl->GetMap()->GetGameObject(ObjectGuid(HIGHGUID_GAMEOBJECT, entry, lowguid)); +} + +enum SpellLinkType +{ + SPELL_LINK_RAW = -1, // non-link case + SPELL_LINK_SPELL = 0, + SPELL_LINK_TALENT = 1, + SPELL_LINK_ENCHANT = 2, +}; + +static char const* const spellKeys[] = +{ + "Hspell", // normal spell + "Htalent", // talent spell + "Henchant", // enchanting recipe spell + nullptr +}; + +uint32 ChatHandler::ExtractSpellIdFromLink(char** text) +{ + // number or [name] Shift-click form |color|Henchant:recipe_spell_id|h[prof_name: recipe_name]|h|r + // number or [name] Shift-click form |color|Hspell:spell_id|h[name]|h|r + // number or [name] Shift-click form |color|Htalent:talent_id,rank|h[name]|h|r + int type; + char* param1_str = nullptr; + char* idS = ExtractKeyFromLink(text, spellKeys, &type, ¶m1_str); + if (!idS) + return 0; + + uint32 id; + if (!ExtractUInt32(&idS, id)) + return 0; + + switch (type) + { + case SPELL_LINK_RAW: + case SPELL_LINK_SPELL: + case SPELL_LINK_ENCHANT: + return id; + case SPELL_LINK_TALENT: + { + // talent + TalentEntry const* talentEntry = sTalentStore.LookupEntry(id); + if (!talentEntry) + return 0; + + int32 rank; + if (!ExtractInt32(¶m1_str, rank)) + return 0; + + if (rank < 0) // unlearned talent have in shift-link field -1 as rank + rank = 0; + + return rank < MAX_TALENT_RANK ? talentEntry->RankID[rank] : 0; + } + } + + // unknown type? + return 0; +} + +GameTele const* ChatHandler::ExtractGameTeleFromLink(char** text) +{ + // id, or string, or [name] Shift-click form |color|Htele:id|h[name]|h|r + char* cId = ExtractKeyFromLink(text, "Htele"); + if (!cId) + return nullptr; + + // id case (explicit or from shift link) + uint32 id; + if (ExtractUInt32(&cId, id)) + return sObjectMgr.GetGameTele(id); + else + return sObjectMgr.GetGameTele(cId); +} + +enum GuidLinkType +{ + GUID_LINK_RAW = -1, // non-link case + GUID_LINK_PLAYER = 0, + GUID_LINK_CREATURE = 1, + GUID_LINK_GAMEOBJECT = 2, +}; + +static char const* const guidKeys[] = +{ + "Hplayer", + "Hcreature", + "Hgameobject", + nullptr +}; + +ObjectGuid ChatHandler::ExtractGuidFromLink(char** text) +{ + int type = 0; + + // |color|Hcreature:creature_guid|h[name]|h|r + // |color|Hgameobject:go_guid|h[name]|h|r + // |color|Hplayer:name|h[name]|h|r + char* idS = ExtractKeyFromLink(text, guidKeys, &type); + if (!idS) + return ObjectGuid(); + + switch (type) + { + case GUID_LINK_RAW: + case GUID_LINK_PLAYER: + { + std::string name = idS; + if (!normalizePlayerName(name)) + return ObjectGuid(); + + if (Player* player = sObjectMgr.GetPlayer(name.c_str())) + return player->GetObjectGuid(); + + return sObjectMgr.GetPlayerGuidByName(name); + } + case GUID_LINK_CREATURE: + { + uint32 lowguid; + if (!ExtractUInt32(&idS, lowguid)) + return ObjectGuid(); + + if (CreatureData const* data = sObjectMgr.GetCreatureData(lowguid)) + return data->GetObjectGuid(lowguid); + else + return ObjectGuid(); + } + case GUID_LINK_GAMEOBJECT: + { + uint32 lowguid; + if (!ExtractUInt32(&idS, lowguid)) + return ObjectGuid(); + + if (GameObjectData const* data = sObjectMgr.GetGOData(lowguid)) + return ObjectGuid(HIGHGUID_GAMEOBJECT, data->id, lowguid); + else + return ObjectGuid(); + } + } + + // unknown type? + return ObjectGuid(); +} + +enum LocationLinkType +{ + LOCATION_LINK_RAW = -1, // non-link case + LOCATION_LINK_PLAYER = 0, + LOCATION_LINK_TELE = 1, + LOCATION_LINK_TAXINODE = 2, + LOCATION_LINK_CREATURE = 3, + LOCATION_LINK_GAMEOBJECT = 4, + LOCATION_LINK_CREATURE_ENTRY = 5, + LOCATION_LINK_GAMEOBJECT_ENTRY = 6, + LOCATION_LINK_AREATRIGGER = 7, + LOCATION_LINK_AREATRIGGER_TARGET = 8, +}; + +static char const* const locationKeys[] = +{ + "Htele", + "Htaxinode", + "Hplayer", + "Hcreature", + "Hgameobject", + "Hcreature_entry", + "Hgameobject_entry", + "Hareatrigger", + "Hareatrigger_target", + nullptr +}; + +bool ChatHandler::ExtractLocationFromLink(char** text, uint32& mapid, float& x, float& y, float& z) +{ + int type = 0; + + // |color|Hplayer:name|h[name]|h|r + // |color|Htele:id|h[name]|h|r + // |color|Htaxinode:id|h[name]|h|r + // |color|Hcreature:creature_guid|h[name]|h|r + // |color|Hgameobject:go_guid|h[name]|h|r + // |color|Hcreature_entry:creature_id|h[name]|h|r + // |color|Hgameobject_entry:go_id|h[name]|h|r + // |color|Hareatrigger:id|h[name]|h|r + // |color|Hareatrigger_target:id|h[name]|h|r + char* idS = ExtractKeyFromLink(text, locationKeys, &type); + if (!idS) + return false; + + switch (type) + { + case LOCATION_LINK_RAW: + case LOCATION_LINK_PLAYER: + { + std::string name = idS; + if (!normalizePlayerName(name)) + return false; + + if (Player* player = sObjectMgr.GetPlayer(name.c_str())) + { + mapid = player->GetMapId(); + x = player->GetPositionX(); + y = player->GetPositionY(); + z = player->GetPositionZ(); + return true; + } + + if (ObjectGuid guid = sObjectMgr.GetPlayerGuidByName(name)) + { + // to point where player stay (if loaded) + float o; + bool in_flight; + return Player::LoadPositionFromDB(guid, mapid, x, y, z, o, in_flight); + } + + return false; + } + case LOCATION_LINK_TELE: + { + uint32 id; + if (!ExtractUInt32(&idS, id)) + return false; + + GameTele const* tele = sObjectMgr.GetGameTele(id); + if (!tele) + return false; + mapid = tele->mapId; + x = tele->position_x; + y = tele->position_y; + z = tele->position_z; + return true; + } + case LOCATION_LINK_TAXINODE: + { + uint32 id; + if (!ExtractUInt32(&idS, id)) + return false; + + TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id); + if (!node) + return false; + mapid = node->map_id; + x = node->x; + y = node->y; + z = node->z; + return true; + } + case LOCATION_LINK_CREATURE: + { + uint32 lowguid; + if (!ExtractUInt32(&idS, lowguid)) + return false; + + if (CreatureData const* data = sObjectMgr.GetCreatureData(lowguid)) + { + mapid = data->mapid; + x = data->posX; + y = data->posY; + z = data->posZ; + return true; + } + else + return false; + } + case LOCATION_LINK_GAMEOBJECT: + { + uint32 lowguid; + if (!ExtractUInt32(&idS, lowguid)) + return false; + + if (GameObjectData const* data = sObjectMgr.GetGOData(lowguid)) + { + mapid = data->mapid; + x = data->posX; + y = data->posY; + z = data->posZ; + return true; + } + else + return false; + } + case LOCATION_LINK_CREATURE_ENTRY: + { + uint32 id; + if (!ExtractUInt32(&idS, id)) + return false; + + if (ObjectMgr::GetCreatureTemplate(id)) + { + FindCreatureData worker(id, m_session ? m_session->GetPlayer() : NULL); + + sObjectMgr.DoCreatureData(worker); + + if (CreatureDataPair const* dataPair = worker.GetResult()) + { + mapid = dataPair->second.mapid; + x = dataPair->second.posX; + y = dataPair->second.posY; + z = dataPair->second.posZ; + return true; + } + else + return false; + } + else + return false; + } + case LOCATION_LINK_GAMEOBJECT_ENTRY: + { + uint32 id; + if (!ExtractUInt32(&idS, id)) + return false; + + if (ObjectMgr::GetGameObjectInfo(id)) + { + FindGOData worker(id, m_session ? m_session->GetPlayer() : NULL); + + sObjectMgr.DoGOData(worker); + + if (GameObjectDataPair const* dataPair = worker.GetResult()) + { + mapid = dataPair->second.mapid; + x = dataPair->second.posX; + y = dataPair->second.posY; + z = dataPair->second.posZ; + return true; + } + else + return false; + } + else + return false; + } + case LOCATION_LINK_AREATRIGGER: + { + uint32 id; + if (!ExtractUInt32(&idS, id)) + return false; + + AreaTriggerEntry const* atEntry = sAreaTriggerStore.LookupEntry(id); + if (!atEntry) + { + PSendSysMessage(LANG_COMMAND_GOAREATRNOTFOUND, id); + SetSentErrorMessage(true); + return false; + } + + mapid = atEntry->mapid; + x = atEntry->x; + y = atEntry->y; + z = atEntry->z; + return true; + } + case LOCATION_LINK_AREATRIGGER_TARGET: + { + uint32 id; + if (!ExtractUInt32(&idS, id)) + return false; + + if (!sAreaTriggerStore.LookupEntry(id)) + { + PSendSysMessage(LANG_COMMAND_GOAREATRNOTFOUND, id); + SetSentErrorMessage(true); + return false; + } + + AreaTrigger const* at = sObjectMgr.GetAreaTrigger(id); + if (!at) + { + PSendSysMessage(LANG_AREATRIGER_NOT_HAS_TARGET, id); + SetSentErrorMessage(true); + return false; + } + + mapid = at->target_mapId; + x = at->target_X; + y = at->target_Y; + z = at->target_Z; + return true; + } + } + + // unknown type? + return false; +} + +std::string ChatHandler::ExtractPlayerNameFromLink(char** text) +{ + // |color|Hplayer:name|h[name]|h|r + char* name_str = ExtractKeyFromLink(text, "Hplayer"); + if (!name_str) + return ""; + + std::string name = name_str; + if (!normalizePlayerName(name)) + return ""; + + return name; +} + +/** + * Function extract at least one from request player data (pointer/guid/name) from args name/shift-link or selected player if no args + * + * @param args variable pointer to non parsed args string, updated at function call to new position (with skipped white spaces) + * + * @param player optional arg One from 3 optional args must be provided at least (or more). + * @param player_guid optional arg For function success only one from provided args need get result + * @param player_name optional arg But if early arg get value then all later args will have its (if requested) + * if player_guid requested and not found then name also will not found + * So at success can be returned 2 cases: (player/guid/name) or (guid/name) + * + * @return true if extraction successful + */ +bool ChatHandler::ExtractPlayerTarget(char** args, Player** player /*= NULL*/, ObjectGuid* player_guid /*= NULL*/, std::string* player_name /*= NULL*/) +{ + if (*args && **args) + { + std::string name = ExtractPlayerNameFromLink(args); + if (name.empty()) + { + SendSysMessage(LANG_PLAYER_NOT_FOUND); + SetSentErrorMessage(true); + return false; + } + + Player* pl = sObjectMgr.GetPlayer(name.c_str()); + + // if allowed player pointer + if (player) + *player = pl; + + // if need guid value from DB (in name case for check player existence) + ObjectGuid guid = !pl && (player_guid || player_name) ? sObjectMgr.GetPlayerGuidByName(name) : ObjectGuid(); + + // if allowed player guid (if no then only online players allowed) + if (player_guid) + *player_guid = pl ? pl->GetObjectGuid() : guid; + + if (player_name) + *player_name = pl || guid ? name : ""; + } + else + { + Player* pl = getSelectedPlayer(); + // if allowed player pointer + if (player) + *player = pl; + // if allowed player guid (if no then only online players allowed) + if (player_guid) + *player_guid = pl ? pl->GetObjectGuid() : ObjectGuid(); + + if (player_name) + *player_name = pl ? pl->GetName() : ""; + } + + // some from req. data must be provided (note: name is empty if player not exist) + if ((!player || !*player) && (!player_guid || !*player_guid) && (!player_name || player_name->empty())) + { + SendSysMessage(LANG_PLAYER_NOT_FOUND); + SetSentErrorMessage(true); + return false; + } + + return true; +} + +uint32 ChatHandler::ExtractAccountId(char** args, std::string* accountName /*= NULL*/, Player** targetIfNullArg /*= NULL*/) +{ + uint32 account_id = 0; + + ///- Get the account name from the command line + char* account_str = ExtractLiteralArg(args); + + if (!account_str) + { + if (!targetIfNullArg) + return 0; + + /// only target player different from self allowed (if targetPlayer!=NULL then not console) + Player* targetPlayer = getSelectedPlayer(); + if (!targetPlayer) + return 0; + + account_id = targetPlayer->GetSession()->GetAccountId(); + + if (accountName) + sAccountMgr.GetName(account_id, *accountName); + + if (targetIfNullArg) + *targetIfNullArg = targetPlayer; + + return account_id; + } + + std::string account_name; + + if (ExtractUInt32(&account_str, account_id)) + { + if (!sAccountMgr.GetName(account_id, account_name)) + { + PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_str); + SetSentErrorMessage(true); + return 0; + } + } + else + { + account_name = account_str; + if (!AccountMgr::normalizeString(account_name)) + { + PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); + SetSentErrorMessage(true); + return 0; + } + + account_id = sAccountMgr.GetId(account_name); + if (!account_id) + { + PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, account_name.c_str()); + SetSentErrorMessage(true); + return 0; + } + } + + if (accountName) + *accountName = account_name; + + if (targetIfNullArg) + *targetIfNullArg = nullptr; + + return account_id; +} + +struct RaceMaskName +{ + char const* literal; + uint32 raceMask; +}; + +static RaceMaskName const raceMaskNames[] = +{ + // races + { "human", (1 << (RACE_HUMAN - 1)) }, + { "orc", (1 << (RACE_ORC - 1)) }, + { "dwarf", (1 << (RACE_DWARF - 1)) }, + { "nightelf", (1 << (RACE_NIGHTELF - 1))}, + { "undead", (1 << (RACE_UNDEAD - 1)) }, + { "tauren", (1 << (RACE_TAUREN - 1)) }, + { "gnome", (1 << (RACE_GNOME - 1)) }, + { "troll", (1 << (RACE_TROLL - 1)) }, + + // masks + { "alliance", RACEMASK_ALLIANCE }, + { "horde", RACEMASK_HORDE }, + { "all", RACEMASK_ALL_PLAYABLE }, + + // terminator + {nullptr, 0 } +}; + +bool ChatHandler::ExtractRaceMask(char** text, uint32& raceMask, char const** maskName /*=NULL*/) +{ + if (ExtractUInt32(text, raceMask)) + { + if (maskName) + *maskName = "custom mask"; + } + else + { + for (RaceMaskName const* itr = raceMaskNames; itr->literal; ++itr) + { + if (ExtractLiteralArg(text, itr->literal)) + { + raceMask = itr->raceMask; + + if (maskName) + *maskName = itr->literal; + break; + } + } + + if (!raceMask) + return false; + } + + return true; +} + +std::string ChatHandler::GetNameLink(Player* chr) const +{ + return playerLink(chr->GetName()); +} + +std::string ChatHandler::GetItemLink(ItemPrototype const* pItem) const +{ + return m_session ? "|cffffffff|Hitem:" + std::to_string(pItem->ItemId) + ":0:0:0:0:0:0:0|h[" + pItem->Name1 + "]|h|r" : pItem->Name1; +} + +bool ChatHandler::needReportToTarget(Player* chr) const +{ + Player* pl = m_session->GetPlayer(); + return pl != chr && pl->IsVisibleGloballyFor(chr); +} + +LocaleConstant ChatHandler::GetSessionDbcLocale() const +{ + return m_session->GetSessionDbcLocale(); +} + +int ChatHandler::GetSessionDbLocaleIndex() const +{ + return m_session->GetSessionDbLocaleIndex(); +} + +const char *CliHandler::GetMangosString(int32 entry) const +{ + return sObjectMgr.GetMangosStringForDBCLocale(entry); +} + +uint32 CliHandler::GetAccountId() const +{ + return m_accountId; +} + +AccountTypes CliHandler::GetAccessLevel() const +{ + return m_loginAccessLevel; +} + +bool CliHandler::isAvailable(ChatCommand const& cmd) const +{ + // skip non-console commands in console case + if (!cmd.AllowConsole) + return false; + + // normal case + return GetAccessLevel() >= (AccountTypes)cmd.SecurityLevel; +} + +void CliHandler::SendSysMessage(const char *str) +{ + m_print(m_callbackArg, str); + m_print(m_callbackArg, "\r\n"); +} + +std::string CliHandler::GetNameLink() const +{ + return GetMangosString(LANG_CONSOLE_COMMAND); +} + +bool CliHandler::needReportToTarget(Player* /*chr*/) const +{ + return true; +} + +LocaleConstant CliHandler::GetSessionDbcLocale() const +{ + return sWorld.GetDefaultDbcLocale(); +} + +int CliHandler::GetSessionDbLocaleIndex() const +{ + return sObjectMgr.GetDBCLocaleIndex(); +} + +// Check/ Output if a NPC or GO (by guid) is part of a pool or game event +template +void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid) +{ + if (uint16 pool_id = sPoolMgr.IsPartOfAPool(guid)) + { + uint16 top_pool_id = sPoolMgr.IsPartOfTopPool(pool_id); + if (!top_pool_id || top_pool_id == pool_id) + PSendSysMessage(LANG_NPC_GO_INFO_POOL, pool_id); + else + PSendSysMessage(LANG_NPC_GO_INFO_TOP_POOL, pool_id, top_pool_id); + + if (int16 event_id = sGameEventMgr.GetGameEventId(top_pool_id)) + { + GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap(); + GameEventData const& eventData = events[std::abs(event_id)]; + + if (event_id > 0) + PSendSysMessage(LANG_NPC_GO_INFO_POOL_GAME_EVENT_S, top_pool_id, std::abs(event_id), eventData.description.c_str()); + else + PSendSysMessage(LANG_NPC_GO_INFO_POOL_GAME_EVENT_D, top_pool_id, std::abs(event_id), eventData.description.c_str()); + } + } + else if (int16 event_id = sGameEventMgr.GetGameEventId(guid)) + { + GameEventMgr::GameEventDataMap const& events = sGameEventMgr.GetEventMap(); + GameEventData const& eventData = events[std::abs(event_id)]; + + if (event_id > 0) + PSendSysMessage(LANG_NPC_GO_INFO_GAME_EVENT_S, uint32(event_id), eventData.description.c_str()); + else + PSendSysMessage(LANG_NPC_GO_INFO_GAME_EVENT_D, uint32(-event_id), eventData.description.c_str()); + } +} + +// Prepare ShortString for a NPC or GO (by guid) with pool or game event IDs +template +std::string ChatHandler::PrepareStringNpcOrGoSpawnInformation(uint32 guid) +{ + std::string str = ""; + if (uint16 pool_id = sPoolMgr.IsPartOfAPool(guid)) + { + uint16 top_pool_id = sPoolMgr.IsPartOfTopPool(guid); + if (int16 event_id = sGameEventMgr.GetGameEventId(top_pool_id)) + { + char buffer[100]; + const char* format = GetMangosString(LANG_NPC_GO_INFO_POOL_EVENT_STRING); + sprintf(buffer, format, pool_id, event_id); + str = buffer; + } + else + { + char buffer[100]; + const char* format = GetMangosString(LANG_NPC_GO_INFO_POOL_STRING); + sprintf(buffer, format, pool_id); + str = buffer; + } + } + else if (int16 event_id = sGameEventMgr.GetGameEventId(guid)) + { + char buffer[100]; + const char* format = GetMangosString(LANG_NPC_GO_INFO_EVENT_STRING); + sprintf(buffer, format, event_id); + str = buffer; + } + + return str; +} + +void ChatHandler::ForwardCommandToNode() +{ + if (!m_cluster_is_node) + throw ForwardToNode_Exception(); +} + +void ChatHandler::ForwardCommandToMaster() +{ + if (!m_cluster_is_master) + throw ForwardToMaster_Exception(); +} + +// Instantiate template for helper function +template void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid); +template void ChatHandler::ShowNpcOrGoSpawnInformation(uint32 guid); + +template std::string ChatHandler::PrepareStringNpcOrGoSpawnInformation(uint32 guid); +template std::string ChatHandler::PrepareStringNpcOrGoSpawnInformation(uint32 guid); + + +LocaleConstant NullChatHandler::GetSessionDbcLocale() const +{ + return sWorld.GetDefaultDbcLocale(); +} + +int NullChatHandler::GetSessionDbLocaleIndex() const +{ + return sObjectMgr.GetDBCLocaleIndex(); +} + +const char *NullChatHandler::GetMangosString(int32 entry) const +{ + return sObjectMgr.GetMangosStringForDBCLocale(entry); +} diff --git a/src/game/Chat/Chat.h b/src/game/Chat/Chat.h index ca14de3b9..f957f888b 100644 --- a/src/game/Chat/Chat.h +++ b/src/game/Chat/Chat.h @@ -552,6 +552,10 @@ class MANGOS_DLL_SPEC ChatHandler bool HandleModifyDodgeCommand(char* args); bool HandleModifyParryCommand(char* args); + bool HandleModifyCrCommand(char *args); + bool HandleModifyBrCommand(char *args); + + //-----------------------Npc Commands----------------------- bool HandleNpcAddCommand(char* args); bool HandleNpcSummonCommand(char* args); @@ -618,6 +622,7 @@ class MANGOS_DLL_SPEC ChatHandler bool HandleReloadConfigCommand(char* args); + bool HandleReloadAreaTriggerTavernCommand(char* args); bool HandleReloadAreaTriggerTeleportCommand(char* args); bool HandleReloadEventScriptsCommand(char* args); diff --git a/src/game/Commands/Level3.cpp b/src/game/Commands/Level3.cpp index 429eb0f8b..055f4785f 100644 --- a/src/game/Commands/Level3.cpp +++ b/src/game/Commands/Level3.cpp @@ -6370,6 +6370,36 @@ bool ChatHandler::HandleSendMessageCommand(char* args) return true; } +bool ChatHandler::HandleModifyCrCommand(char *args) +{ + if (!*args) + return false; + + Unit* target = getSelectedUnit(); + if (!target) return false; + float f; + if (!ExtractFloat(&args, f)) + return false; + + target->SetFloatValue(UNIT_FIELD_COMBATREACH, f); + return true; +} + +bool ChatHandler::HandleModifyBrCommand(char *args) +{ + if (!*args) + return false; + + Unit* target = getSelectedUnit(); + if (!target) return false; + float f; + if (!ExtractFloat(&args, f)) + return false; + + target->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, f); + return true; +} + bool ChatHandler::HandleModifyGenderCommand(char *args) { if (!*args) diff --git a/src/game/Group/Group.cpp b/src/game/Group/Group.cpp index f6f8fbf3b..5e348f7d6 100644 --- a/src/game/Group/Group.cpp +++ b/src/game/Group/Group.cpp @@ -644,7 +644,8 @@ void Group::MasterLoot(Creature *creature, Loot* loot) if (!looter->IsInWorld()) continue; - if (looter->IsWithinDistInMap(creature, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (looter->IsWithinDistInMap(creature, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if(looter->IsWithinLootXPDist(creature)) { data << looter->GetObjectGuid(); ++real_count; @@ -658,7 +659,8 @@ void Group::MasterLoot(Creature *creature, Loot* loot) Player *looter = itr->getSource(); if (!looter->IsInWorld()) continue; - if (looter->IsWithinDistInMap(creature, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (looter->IsWithinDistInMap(creature, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if (looter->IsWithinLootXPDist(creature)) looter->GetSession()->SendPacket(&data); } } @@ -746,7 +748,8 @@ void Group::StartLootRoll(Creature* lootTarget, LootMethod method, Loot* loot, u if ((method != NEED_BEFORE_GREED || playerToRoll->CanUseItem(item) == EQUIP_ERR_OK) && lootItem.AllowedForPlayer(playerToRoll, lootTarget)) { - if (playerToRoll->IsWithinDistInMap(lootTarget, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (playerToRoll->IsWithinDistInMap(lootTarget, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if (playerToRoll->IsWithinLootXPDist(lootTarget)) { r->playerVote[playerToRoll->GetObjectGuid()] = ROLL_NOT_EMITED_YET; ++r->totalPlayersRolling; @@ -1921,7 +1924,8 @@ void Group::UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed) { // not update if only update if need and ok Player* looter = ObjectAccessor::FindPlayer(guid_itr->guid); - if (looter && looter->IsWithinDistInMap(pLootedObject, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (looter && looter->IsWithinDistInMap(pLootedObject, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if (looter && looter->IsWithinLootXPDist(pLootedObject)) return; } ++guid_itr; @@ -1932,7 +1936,8 @@ void Group::UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed) for (member_citerator itr = guid_itr; itr != m_memberSlots.end(); ++itr) { if (Player* player = ObjectAccessor::FindPlayer(itr->guid)) - if (player->IsWithinDistInMap(pLootedObject, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (player->IsWithinDistInMap(pLootedObject, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if (player->IsWithinLootXPDist(pLootedObject)) { pNewLooter = player; break; @@ -1945,7 +1950,8 @@ void Group::UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed) for (member_citerator itr = m_memberSlots.begin(); itr != guid_itr; ++itr) { if (Player* player = ObjectAccessor::FindPlayer(itr->guid)) - if (player->IsWithinDistInMap(pLootedObject, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (player->IsWithinDistInMap(pLootedObject, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if (player->IsWithinLootXPDist(pLootedObject)) { pNewLooter = player; break; diff --git a/src/game/Handlers/LootHandler.cpp b/src/game/Handlers/LootHandler.cpp index ee078cd20..b940dca13 100644 --- a/src/game/Handlers/LootHandler.cpp +++ b/src/game/Handlers/LootHandler.cpp @@ -264,7 +264,8 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket & /*recv_data*/) Player* playerGroup = itr->getSource(); if (!playerGroup) continue; - if (player->IsWithinDistInMap(playerGroup, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + //if (player->IsWithinDistInMap(playerGroup, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE), false)) + if(player->IsWithinLootXPDist(playerGroup)) playersNear.push_back(playerGroup); } diff --git a/src/game/Maps/GridNotifiers.h b/src/game/Maps/GridNotifiers.h index ca4915e5a..895721d02 100644 --- a/src/game/Maps/GridNotifiers.h +++ b/src/game/Maps/GridNotifiers.h @@ -1199,20 +1199,41 @@ namespace MaNGOS class AllCreaturesOfEntryInRange { - public: - AllCreaturesOfEntryInRange(const WorldObject* pObject, uint32 uiEntry, float fMaxRange) : m_pObject(pObject), m_uiEntry(uiEntry), m_fRange(fMaxRange) {} - bool operator() (Unit* pUnit) - { - if (pUnit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(pUnit,m_fRange,false)) + public: + AllCreaturesOfEntryInRange(const WorldObject* pObject, uint32 uiEntry, float fMaxRange) : m_pObject(pObject), m_uiEntry(uiEntry), m_fRange(fMaxRange) {} + bool operator() (Unit* pUnit) + { + if (pUnit->GetEntry() == m_uiEntry && m_pObject->IsWithinDist(pUnit, m_fRange, false)) + return true; + + return false; + } + + private: + const WorldObject* m_pObject; + uint32 m_uiEntry; + float m_fRange; + }; + + class AllCreaturesMatchingOneEntryInRange + { + public: + AllCreaturesMatchingOneEntryInRange(const WorldObject* pObject, const std::vector& entries, float fMaxRange) + : m_pObject(pObject), entries(entries), m_fRange(fMaxRange) {} + bool operator() (Unit* pUnit) + { + for (auto it = entries.cbegin(); it != entries.cend(); ++it) { + if (pUnit->GetEntry() == (*it) && m_pObject->IsWithinDist(pUnit, m_fRange, false)) { return true; - - return false; + } } + return false; + } - private: - const WorldObject* m_pObject; - uint32 m_uiEntry; - float m_fRange; + private: + const WorldObject* m_pObject; + std::vector entries; + float m_fRange; }; class PlayerAtMinimumRangeAway diff --git a/src/game/Maps/GridSearchers.cpp b/src/game/Maps/GridSearchers.cpp index d0d7caa39..32dfadc36 100644 --- a/src/game/Maps/GridSearchers.cpp +++ b/src/game/Maps/GridSearchers.cpp @@ -49,3 +49,12 @@ void GetCreatureListWithEntryInGrid(std::list& lList, WorldObject* pS Cell::VisitGridObjects(pSource, searcher, fMaxSearchRange); } + +void GetCreatureListWithEntryInGrid(std::list& lList, WorldObject* pSource, const std::vector& entries, float fMaxSearchRange) +{ + ASSERT(pSource); + MaNGOS::AllCreaturesMatchingOneEntryInRange check(pSource, entries, fMaxSearchRange); + MaNGOS::CreatureListSearcher searcher(lList, check); + + Cell::VisitGridObjects(pSource, searcher, fMaxSearchRange); +} \ No newline at end of file diff --git a/src/game/Maps/GridSearchers.h b/src/game/Maps/GridSearchers.h index b706537e3..b2388487d 100644 --- a/src/game/Maps/GridSearchers.h +++ b/src/game/Maps/GridSearchers.h @@ -42,6 +42,7 @@ Creature* GetClosestCreatureWithEntry(WorldObject* pSource, uint32 uiEntry, floa void GetGameObjectListWithEntryInGrid(std::list& lList , WorldObject* pSource, uint32 uiEntry, float fMaxSearchRange); void GetCreatureListWithEntryInGrid(std::list& lList, WorldObject* pSource, uint32 uiEntry, float fMaxSearchRange); +void GetCreatureListWithEntryInGrid(std::list& lList, WorldObject* pSource, const std::vector& entries, float fMaxSearchRange); /* //Used in: diff --git a/src/game/ObjectMgr.cpp b/src/game/ObjectMgr.cpp index f82a10e7e..4f6ce42e4 100644 --- a/src/game/ObjectMgr.cpp +++ b/src/game/ObjectMgr.cpp @@ -6877,7 +6877,7 @@ void ObjectMgr::LoadGameObjectForQuests() sLog.outString(">> Loaded %u GameObjects for quests", count); } -bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value) +bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value, bool extra_content) { int32 start_value = min_value; int32 end_value = max_value; @@ -6913,7 +6913,7 @@ bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min ++itr; } - QueryResult *result = db.PQuery("SELECT entry,content_default,content_loc1,content_loc2,content_loc3,content_loc4,content_loc5,content_loc6,content_loc7,content_loc8 FROM %s", table); + QueryResult *result = db.PQuery("SELECT entry,content_default,content_loc1,content_loc2,content_loc3,content_loc4,content_loc5,content_loc6,content_loc7,content_loc8 %s FROM %s", extra_content ? ",sound,type,language,emote" : "", table); if (!result) { @@ -6981,6 +6981,40 @@ bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min } } } + + + // Load additional string content if necessary + if (extra_content) + { + data.SoundId = fields[10].GetUInt32(); + data.Type = fields[11].GetUInt32(); + data.LanguageId = Language(fields[12].GetUInt32()); + data.Emote = fields[13].GetUInt32(); + + if (data.SoundId && !sSoundEntriesStore.LookupEntry(data.SoundId)) + { + sLog.outErrorDb("Entry %i in table `%s` has soundId %u but sound does not exist.", entry, table, data.SoundId); + data.SoundId = 0; + } + + if (!GetLanguageDescByID(data.LanguageId)) + { + sLog.outErrorDb("Entry %i in table `%s` using Language %u but Language does not exist.", entry, table, uint32(data.LanguageId)); + data.LanguageId = LANG_UNIVERSAL; + } + + if (data.Type > CHAT_TYPE_ZONE_YELL) + { + sLog.outErrorDb("Entry %i in table `%s` has Type %u but this Chat Type does not exist.", entry, table, data.Type); + data.Type = CHAT_TYPE_SAY; + } + + if (data.Emote && !sEmotesStore.LookupEntry(data.Emote)) + { + sLog.outErrorDb("Entry %i in table `%s` has Emote %u but emote does not exist.", entry, table, data.Emote); + data.Emote = EMOTE_ONESHOT_NONE; + } + } } while (result->NextRow()); @@ -8006,7 +8040,7 @@ void ObjectMgr::RemoveGroup(Group* group) } // Functions for scripting access -bool LoadMangosStrings(DatabaseType& db, char const* table, int32 start_value, int32 end_value) +bool LoadMangosStrings(DatabaseType& db, char const* table, int32 start_value, int32 end_value, bool extra_content) { // MAX_DB_SCRIPT_STRING_ID is max allowed negative value for scripts (scrpts can use only more deep negative values // start/end reversed for negative values @@ -8016,7 +8050,7 @@ bool LoadMangosStrings(DatabaseType& db, char const* table, int32 start_value, i return false; } - return sObjectMgr.LoadMangosStrings(db, table, start_value, end_value); + return sObjectMgr.LoadMangosStrings(db, table, start_value, end_value, extra_content); } CreatureInfo const* GetCreatureTemplateStore(uint32 entry) diff --git a/src/game/ObjectMgr.h b/src/game/ObjectMgr.h index 8ca539cf7..126555387 100644 --- a/src/game/ObjectMgr.h +++ b/src/game/ObjectMgr.h @@ -1,8 +1,6 @@ /* * Copyright (C) 2005-2011 MaNGOS * Copyright (C) 2009-2011 MaNGOSZero - * Copyright (C) 2011-2016 Nostalrius - * Copyright (C) 2016-2017 Elysium Project * * 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 @@ -110,7 +108,13 @@ typedef UNORDERED_MAP MapObjectGuids; struct MangosStringLocale { + MangosStringLocale() : SoundId(0), Type(0), LanguageId(LANG_UNIVERSAL), Emote(0) { } + std::vector Content; // 0 -> default, i -> i-1 locale index + uint32 SoundId; + uint8 Type; + Language LanguageId; + uint32 Emote; }; typedef UNORDERED_MAP CreatureDataMap; @@ -485,8 +489,8 @@ enum PermVariables DEF_STOP_DELAY = 5, // default times event check will not stop the event NPC_YSONDRE = 14887, - NPC_LETHON = 14888, - NPC_EMERISS = 14889, + NPC_LETHON = 14888, + NPC_EMERISS = 14889, NPC_TAERAR = 14890, GUID_YSONDRE = 52350, @@ -739,8 +743,8 @@ class ObjectMgr void LoadCreatureQuestRelations(); void LoadCreatureInvolvedRelations(); - bool LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value); - bool LoadMangosStrings() { return LoadMangosStrings(WorldDatabase,"mangos_string",MIN_MANGOS_STRING_ID,MAX_MANGOS_STRING_ID); } + bool LoadMangosStrings(DatabaseType& db, char const* table, int32 min_value, int32 max_value, bool extra_content); + bool LoadMangosStrings() { return LoadMangosStrings(WorldDatabase,"mangos_string",MIN_MANGOS_STRING_ID,MAX_MANGOS_STRING_ID, false); } bool LoadNostalriusStrings(); void LoadPetCreateSpells(); void LoadCreatureLocales(); @@ -1337,7 +1341,7 @@ class ObjectMgr #define sObjectMgr MaNGOS::Singleton::Instance() // scripting access functions -MANGOS_DLL_SPEC bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value = MAX_CREATURE_AI_TEXT_STRING_ID, int32 end_value = std::numeric_limits::min()); +MANGOS_DLL_SPEC bool LoadMangosStrings(DatabaseType& db, char const* table,int32 start_value = MAX_CREATURE_AI_TEXT_STRING_ID, int32 end_value = std::numeric_limits::min(), bool extra_content = false); MANGOS_DLL_SPEC CreatureInfo const* GetCreatureTemplateStore(uint32 entry); MANGOS_DLL_SPEC Quest const* GetQuestTemplateStore(uint32 entry); diff --git a/src/game/Objects/Creature.cpp b/src/game/Objects/Creature.cpp index 27e7ec834..b4a72e9f4 100644 --- a/src/game/Objects/Creature.cpp +++ b/src/game/Objects/Creature.cpp @@ -1889,6 +1889,21 @@ bool Creature::IsImmuneToDamage(SpellSchoolMask meleeSchoolMask) return Unit::IsImmuneToDamage(meleeSchoolMask); } +// hacky - seems to be the only way of doing this without wasting more time +void Creature::SetTauntImmunity(bool immune) +{ + if (immune) + { + auto info = const_cast(m_creatureInfo); + info->flags_extra |= CREATURE_FLAG_EXTRA_NOT_TAUNTABLE; + } + else + { + auto info = const_cast(m_creatureInfo); + info->flags_extra ^= CREATURE_FLAG_EXTRA_NOT_TAUNTABLE; + } +} + bool Creature::IsImmuneToSpellEffect(SpellEntry const *spellInfo, SpellEffectIndex index, bool castOnSelf) const { if (!castOnSelf && spellInfo->EffectMechanic[index] && GetCreatureInfo()->MechanicImmuneMask & (1 << (spellInfo->EffectMechanic[index] - 1))) @@ -3083,7 +3098,7 @@ Unit* Creature::GetNearestVictimInRange(float min, float max) continue; float currRange = GetDistance(pTarget); - if (currRange < bestRange && currRange > min) + if (currRange <= bestRange && currRange >= min) { bestRange = currRange; pUnit = pTarget; diff --git a/src/game/Objects/Creature.h b/src/game/Objects/Creature.h index 11ec5652e..a0d28a612 100644 --- a/src/game/Objects/Creature.h +++ b/src/game/Objects/Creature.h @@ -656,6 +656,8 @@ class MANGOS_DLL_SPEC Creature : public Unit bool CanAssistTo(const Unit* u, const Unit* enemy, bool checkfaction = true) const; bool CanInitiateAttack(); + void SetTauntImmunity(bool immune); + MovementGeneratorType GetDefaultMovementType() const { return m_defaultMovementType; } void SetDefaultMovementType(MovementGeneratorType mgt) { m_defaultMovementType = mgt; } diff --git a/src/game/Objects/Object.cpp b/src/game/Objects/Object.cpp index 69ea4d367..6e44fee73 100644 --- a/src/game/Objects/Object.cpp +++ b/src/game/Objects/Object.cpp @@ -1083,8 +1083,18 @@ void Object::ExecuteDelayedActions() } } +bool WorldObject::IsWithinLootXPDist(WorldObject const * objToLoot) const +{ + return objToLoot && IsInMap(objToLoot) && _IsWithinDist(objToLoot, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE) + objToLoot->m_lootAndXPRangeModifier, false); +} + +void WorldObject::SetLootAndXPModDist(float val) +{ + m_lootAndXPRangeModifier = val; +} + WorldObject::WorldObject() - : m_isActiveObject(false), m_currMap(nullptr), m_mapId(0), m_InstanceId(0) + : m_isActiveObject(false), m_currMap(nullptr), m_mapId(0), m_InstanceId(0), m_lootAndXPRangeModifier(0) { // Phasing worldMask = WORLD_DEFAULT_OBJECT; diff --git a/src/game/Objects/Object.h b/src/game/Objects/Object.h index 8d4267bb9..54eaa09b8 100644 --- a/src/game/Objects/Object.h +++ b/src/game/Objects/Object.h @@ -651,13 +651,13 @@ class MANGOS_DLL_SPEC WorldObject : public Object void Update(uint32 time_diff) { - m_obj->Update( m_obj->m_updateTracker.timeElapsed(), time_diff); - m_obj->m_updateTracker.Reset(); +m_obj->Update(m_obj->m_updateTracker.timeElapsed(), time_diff); +m_obj->m_updateTracker.Reset(); } void UpdateRealTime(uint32 now, uint32 time_diff) { - m_obj->Update( m_obj->m_updateTracker.timeElapsed(now), time_diff); + m_obj->Update(m_obj->m_updateTracker.timeElapsed(now), time_diff); m_obj->m_updateTracker.ResetTo(now); } @@ -908,6 +908,12 @@ class MANGOS_DLL_SPEC WorldObject : public Object void SetLocationMapId(uint32 _mapId) { m_mapId = _mapId; } void SetLocationInstanceId(uint32 _instanceId) { m_InstanceId = _instanceId; } + bool IsWithinLootXPDist(WorldObject const* objToLoot) const; + + // val is added to CONFIG_FLOAT_GROUP_XP_DISTANCE when calculating + // if player should be eligible for loot and XP from this object. + void SetLootAndXPModDist(float val); + protected: explicit WorldObject(); @@ -925,6 +931,8 @@ class MANGOS_DLL_SPEC WorldObject : public Object ViewPoint m_viewPoint; WorldUpdateCounter m_updateTracker; + + float m_lootAndXPRangeModifier; }; #endif diff --git a/src/game/Objects/Player.cpp b/src/game/Objects/Player.cpp index 4298cd5f0..395e5ca51 100644 --- a/src/game/Objects/Player.cpp +++ b/src/game/Objects/Player.cpp @@ -6008,7 +6008,7 @@ int32 Player::CalculateReputationGain(ReputationSource source, int32 rep, int32 percent *= repRate; } - return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN) * rep * percent / 100.0f); + return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN) * rep * percent / 100.0f); } //Calculates how many reputation points player gains in victim's enemy factions @@ -18319,7 +18319,8 @@ bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const if (!pRewardSource) return false; - if (pRewardSource->IsWithinDistInMap(this, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE))) + //if (pRewardSource->IsWithinDistInMap(this, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE))) + if (IsWithinLootXPDist(pRewardSource)) return true; if (isAlive()) @@ -18329,7 +18330,7 @@ bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const if (!corpse) return false; - return pRewardSource->IsWithinDistInMap(corpse, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)); + return IsWithinLootXPDist(pRewardSource); // pRewardSource->IsWithinDistInMap(corpse, sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)); } uint32 Player::GetBaseWeaponSkillValue(WeaponAttackType attType) const diff --git a/src/game/Objects/Unit.cpp b/src/game/Objects/Unit.cpp index 360fb3755..b623414de 100644 --- a/src/game/Objects/Unit.cpp +++ b/src/game/Objects/Unit.cpp @@ -1,11508 +1,11538 @@ -/* - * Copyright (C) 2005-2011 MaNGOS - * Copyright (C) 2009-2011 MaNGOSZero - * - * - * 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 - */ - -#include "Unit.h" -#include "Log.h" -#include "Opcodes.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "World.h" -#include "ObjectMgr.h" -#include "ObjectGuid.h" -#include "SpellMgr.h" -#include "QuestDef.h" -#include "Player.h" -#include "Creature.h" -#include "Spell.h" -#include "Group.h" -#include "SpellAuras.h" -#include "MapManager.h" -#include "ObjectAccessor.h" -#include "CreatureAI.h" -#include "TemporarySummon.h" -#include "Formulas.h" -#include "Pet.h" -#include "Util.h" -#include "Totem.h" -#include "BattleGround.h" -#include "InstanceData.h" -#include "MapPersistentStateMgr.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" -#include "DBCStores.h" -#include "VMapFactory.h" -#include "MovementGenerator.h" -#include "Transport.h" - -#include "ZoneScript.h" -#include "Nostalrius.h" -#include "InstanceData.h" - -#include "PathFinder.h" -#include "MoveSplineInit.h" -#include "MoveSpline.h" -#include "packet_builder.h" -#include "Chat.h" -#include "Anticheat.h" - -#include -#include - -//#define DEBUG_DEBUFF_LIMIT - -float baseMoveSpeed[MAX_MOVE_TYPE] = -{ - 2.5f, // MOVE_WALK - 7.0f, // MOVE_RUN - 4.5f, // MOVE_RUN_BACK - 4.722222f, // MOVE_SWIM - 2.5f, // MOVE_SWIM_BACK - 3.141594f, // MOVE_TURN_RATE -}; - - -//////////////////////////////////////////////////////////// -// Methods of class GlobalCooldownMgr - -bool GlobalCooldownMgr::HasGlobalCooldown(SpellEntry const* spellInfo) const -{ - GlobalCooldownList::const_iterator itr = m_GlobalCooldowns.find(spellInfo->StartRecoveryCategory); - return itr != m_GlobalCooldowns.end() && itr->second.duration && WorldTimer::getMSTimeDiff(itr->second.cast_time, WorldTimer::getMSTime()) < itr->second.duration; -} - -void GlobalCooldownMgr::AddGlobalCooldown(SpellEntry const* spellInfo, uint32 gcd) -{ - m_GlobalCooldowns[spellInfo->StartRecoveryCategory] = GlobalCooldown(gcd, WorldTimer::getMSTime()); -} - -void GlobalCooldownMgr::CancelGlobalCooldown(SpellEntry const* spellInfo) -{ - m_GlobalCooldowns[spellInfo->StartRecoveryCategory].duration = 0; -} - -//////////////////////////////////////////////////////////// -// Methods of class Unit - -Unit::Unit() - : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostileRefManager(this), - movespline(new Movement::MoveSpline()), _debugFlags(0), m_needUpdateVisibility(false), - m_AutoRepeatFirstCast(true), m_castingSpell(0), m_regenTimer(0), _lastDamageTaken(0) -{ - m_objectType |= TYPEMASK_UNIT; - m_objectTypeId = TYPEID_UNIT; - m_updateFlag = (UPDATEFLAG_ALL | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION); - - m_attackTimer[BASE_ATTACK] = 0; - m_attackTimer[OFF_ATTACK] = 0; - m_attackTimer[RANGED_ATTACK] = 0; - m_modAttackSpeedPct[BASE_ATTACK] = 1.0f; - m_modAttackSpeedPct[OFF_ATTACK] = 1.0f; - m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f; - - m_modRecalcDamagePct[BASE_ATTACK] = 1.0f; - m_modRecalcDamagePct[OFF_ATTACK] = 1.0f; - m_modRecalcDamagePct[RANGED_ATTACK] = 1.0f; - - m_extraAttacks = 0; - m_extraMute = false; - - m_state = 0; - m_deathState = ALIVE; - - for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) - m_currentSpells[i] = nullptr; - - m_castCounter = 0; - - //m_Aura = NULL; - //m_AurasCheck = 2000; - //m_removeAuraTimer = 4; - m_spellAuraHoldersUpdateIterator = m_spellAuraHolders.end(); - m_AuraFlags = 0; - - m_Visibility = VISIBILITY_ON; - m_AINotifyScheduled = false; - - m_detectInvisibilityMask = 0; - m_invisibilityMask = 0; - m_transform = 0; - m_canModifyStats = false; - - for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i) - m_spellImmune[i].clear(); - for (int i = 0; i < UNIT_MOD_END; ++i) - { - m_auraModifiersGroup[i][BASE_VALUE] = 0.0f; - m_auraModifiersGroup[i][BASE_PCT] = 1.0f; - m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f; - m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f; - } - // implement 50% base damage from offhand - m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f; - - for (uint8 i = 0; i < MAX_ATTACK; ++i) - { - for (uint8 j = 0; j < MAX_ITEM_PROTO_DAMAGES; j++) - { - m_weaponDamage[i][j].damage[MINDAMAGE] = (j == 0) ? BASE_MINDAMAGE : 0; - m_weaponDamage[i][j].damage[MAXDAMAGE] = (j == 0) ? BASE_MAXDAMAGE : 0; - m_weaponDamage[i][j].school = SPELL_SCHOOL_NORMAL; - } - - m_weaponDamageCount[i] = 1; - } - - for (int i = 0; i < MAX_STATS; ++i) - m_createStats[i] = 0.0f; - - m_attacking = nullptr; - m_modMeleeHitChance = 0.0f; - m_modRangedHitChance = 0.0f; - m_modSpellHitChance = 0.0f; - m_baseSpellCritChance = 5; - - m_CombatTimer = 0; - m_lastManaUseTimer = 0; - - //m_victimThreat = 0.0f; - for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) - m_threatModifier[i] = 1.0f; - m_isSorted = true; - for (int i = 0; i < MAX_MOVE_TYPE; ++i) - m_speed_rate[i] = 1.0f; - - m_charmInfo = nullptr; - - // remove aurastates allowing special moves - for (int i = 0; i < MAX_REACTIVE; ++i) - { - m_reactiveTimer[i] = 0; - m_reactiveTarget[i].Clear(); - } - // Phasing - worldMask = WORLD_DEFAULT_UNIT; - - // Nostalrius : Ivina - m_lastCastedSpellID = 0; - m_lastAttackType = MAX_ATTACK; - _casterChaseDistance = 0.0f; - - m_doExtraAttacks = false; -} - -Unit::~Unit() -{ - // set current spells as deletable - for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) - { - if (m_currentSpells[i]) - { - m_currentSpells[i]->SetReferencedFromCurrent(false); - m_currentSpells[i] = nullptr; - } - } - - delete m_charmInfo; - delete movespline; - - // those should be already removed at "RemoveFromWorld()" call - MANGOS_ASSERT(m_gameObj.size() == 0); - MANGOS_ASSERT(m_dynObjGUIDs.size() == 0); - MANGOS_ASSERT(m_deletedAuras.size() == 0); - MANGOS_ASSERT(m_deletedHolders.size() == 0); - MANGOS_ASSERT(!m_needUpdateVisibility); -} - -void Unit::Update(uint32 update_diff, uint32 p_time) -{ - if (!IsInWorld()) - return; - - // Nostalrius : systeme de contresort des mobs. - // Boucle 1 pour regler les timers - for (ProhibitSpellList::iterator it = m_prohibitSpell.begin(); it != m_prohibitSpell.end(); ++it) - { - if (it->RestingMsTime < update_diff) - it->RestingMsTime = 0; - else - it->RestingMsTime -= update_diff; - } - // Boucle 2 : supprimer les sorts avec Timer=0 - for (ProhibitSpellList::iterator it = m_prohibitSpell.begin(); it != m_prohibitSpell.end();) - { - if (it->RestingMsTime == 0) - { - m_prohibitSpell.erase(it); - it = m_prohibitSpell.begin(); - continue; - } - ++it; - } - - // WARNING! Order of execution here is important, do not change. - // Spells must be processed with event system BEFORE they go to _UpdateSpells. - // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad. - m_Events.Update(update_diff); - _UpdateSpells(update_diff); - - CleanupDeletedAuras(); - - if (m_lastManaUseTimer) - { - if (update_diff >= m_lastManaUseTimer) - m_lastManaUseTimer = 0; - else - m_lastManaUseTimer -= update_diff; - } - - // update combat timer only for players and pets - if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->IsPet() || ((Creature*)this)->isCharmed())) - { - // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away - // targets without stopping half way there and running off. - // These flags are reset after target dies or another command is given. - if (GetCharmerGuid().IsPlayer() || GetOwnerGuid().IsPlayer() || GetTypeId() == TYPEID_PLAYER) - { - // Pet in combat ? - Pet* myPet = GetPet(); - if (!myPet || myPet->getHostileRefManager().isEmpty()) - { - if (m_HostileRefManager.isEmpty()) - { - // m_CombatTimer set at aura start and it will be freeze until aura removing - if (m_CombatTimer <= update_diff) - { - // Rage berzerker laisse en combat. - if (!HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) - ClearInCombat(); - } - else - m_CombatTimer -= update_diff; - } - } - } - } - - // extra attack - Unit* victim = getVictim(); - if (isInCombat() && m_doExtraAttacks && GetExtraAttacks() && victim && CanReachWithMeleeAttack(victim)) - { - m_doExtraAttacks = false; - - ExtraAttacksLocked(true); - - while (m_extraAttacks) - { - AttackerStateUpdate(victim, BASE_ATTACK, true); - if (m_extraAttacks > 0) - --m_extraAttacks; - } - resetAttackTimer(BASE_ATTACK); - - ExtraAttacksLocked(false); - } - - if (uint32 base_att = getAttackTimer(BASE_ATTACK)) - setAttackTimer(BASE_ATTACK, (update_diff >= base_att ? 0 : base_att - update_diff)); - - if (uint32 base_att = getAttackTimer(OFF_ATTACK)) - setAttackTimer(OFF_ATTACK, (update_diff >= base_att ? 0 : base_att - update_diff)); - - if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK)) - setAttackTimer(RANGED_ATTACK, (update_diff >= ranged_att ? 0 : ranged_att - update_diff)); - - // update abilities available only for fraction of time - UpdateReactives(update_diff); - - if (isAlive()) - ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth() * 0.20f); - - UpdateSplineMovement(p_time); - GetMotionMaster()->UpdateMotion(p_time); - if (GetMotionMaster()->NeedsAsyncUpdate() && IsInWorld()) - { - if (sWorld.getConfig(CONFIG_UINT32_CONTINENTS_MOTIONUPDATE_THREADS) && GetMap()->IsContinent()) - GetMap()->AddUnitToMovementUpdate(this); - else - GetMotionMaster()->UpdateMotionAsync(p_time); - } - WorldObject::Update(update_diff, p_time); - if (_delayedActions & OBJECT_DELAYED_ADD_TO_RELOCATED_LIST) - { - if (IsInWorld() && !m_needUpdateVisibility) - { - m_needUpdateVisibility = true; - GetMap()->AddRelocatedUnit(this); - } - _delayedActions &= ~OBJECT_DELAYED_ADD_TO_RELOCATED_LIST; - } - - _lastDamageTaken += p_time; - if (_lastDamageTaken > 60000) - _damageTakenHistory.clear(); -} - -bool Unit::UpdateMeleeAttackingState() -{ - Unit* victim = getVictim(); - if (!victim || IsNonMeleeSpellCasted(false)) - return false; - - if (!isAttackReady(BASE_ATTACK) && !(isAttackReady(OFF_ATTACK) && haveOffhandWeapon())) - return false; - - uint8 swingError = 0; - if (!CanReachWithMeleeAttack(victim)) - { - setAttackTimer(BASE_ATTACK, 100); - setAttackTimer(OFF_ATTACK, 100); - swingError = 1; - } - // 120 degrees of radiant range - else if (!HasInArc(2 * M_PI_F / 3, victim)) - { - setAttackTimer(BASE_ATTACK, 100); - setAttackTimer(OFF_ATTACK, 100); - swingError = 2; - } - else - { - if (isAttackReady(BASE_ATTACK)) - { - // prevent base and off attack in same time, delay attack at 0.2 sec - if (haveOffhandWeapon()) - { - if (getAttackTimer(OFF_ATTACK) < ATTACK_DISPLAY_DELAY) - setAttackTimer(OFF_ATTACK, ATTACK_DISPLAY_DELAY); - } - AttackerStateUpdate(victim, BASE_ATTACK); - resetAttackTimer(BASE_ATTACK); - } - if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK)) - { - // prevent base and off attack in same time, delay attack at 0.2 sec - uint32 base_att = getAttackTimer(BASE_ATTACK); - if (base_att < ATTACK_DISPLAY_DELAY) - setAttackTimer(BASE_ATTACK, ATTACK_DISPLAY_DELAY); - // do attack - AttackerStateUpdate(victim, OFF_ATTACK); - resetAttackTimer(OFF_ATTACK); - } - } - - Player* player = (GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL); - if (player && swingError != player->LastSwingErrorMsg()) - { - if (swingError == 1) - player->SendAttackSwingNotInRange(); - else if (swingError == 2) - player->SendAttackSwingBadFacingAttack(); - player->SwingErrorMsg(swingError); - } - - return swingError == 0; -} - -bool Unit::haveOffhandWeapon() const -{ - if (!CanUseEquippedWeapon(OFF_ATTACK)) - return false; - - if (GetTypeId() == TYPEID_PLAYER) - return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK, true, true); - else - { - uint8 itemClass = GetByteValue(UNIT_VIRTUAL_ITEM_INFO + (1 * 2) + 0, VIRTUAL_ITEM_INFO_0_OFFSET_CLASS); - if (itemClass == ITEM_CLASS_WEAPON) - return true; - - return false; - } -} - -void Unit::SendHeartBeat(bool includingSelf) -{ - //m_movementInfo.ChangePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); - m_movementInfo.UpdateTime(WorldTimer::getMSTime()); - WorldPacket data(MSG_MOVE_HEARTBEAT, 31); - data << GetPackGUID(); - data << m_movementInfo; - SendMovementMessageToSet(std::move(data), includingSelf); -} - -void Unit::resetAttackTimer(WeaponAttackType type) -{ - m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]); -} - -void Unit::RemoveSpellsCausingAura(AuraType auraType) -{ - for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) - { - RemoveAurasDueToSpell((*iter)->GetId()); - iter = m_modAuras[auraType].begin(); - } -} - -bool Unit::HasAuraTypeByCaster(AuraType auraType, ObjectGuid casterGuid) const -{ - for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); ++iter) - if ((*iter)->GetCasterGuid() == casterGuid) - return true; - return false; -} - -uint64 Unit::GetAuraApplicationMask() const -{ - if (!IsInWorld()) - return 0; - - uint64 mask = 0x0; - for (uint64 i = MAX_POSITIVE_AURAS; i < MAX_AURAS; ++i) - if (GetUInt32Value(UNIT_FIELD_AURA + i)) - mask |= uint64(1) << i; - return mask; -} - -uint32 Unit::GetFirstAuraBySpellIconAndVisual(uint32 spellIconId, uint32 spellVisual) const -{ - for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) - { - if ((*i).second->GetSpellProto()->SpellIconID == spellIconId && (*i).second->GetSpellProto()->SpellVisual == spellVisual) - return (*i).second->GetId(); - } - return 0; -} - -void Unit::RemoveSpellsCausingAura(AuraType auraType, SpellAuraHolder* except) -{ - for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) - { - // skip `except` aura - if ((*iter)->GetHolder() == except) - { - ++iter; - continue; - } - - RemoveAurasDueToSpell((*iter)->GetId(), except); - iter = m_modAuras[auraType].begin(); - } -} - -/* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */ -void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage) -{ - if (!HasAuraType(auraType)) - return; - if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) - return; - - // The chance to dispel an aura depends on the damage taken with respect to the casters level. - uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50; - float chance = float(damage) / max_dmg * 100.0f; - if (roll_chance_f(chance)) - { - for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) - { - if ((*iter)->GetSpellProto()->procFlags) - { - RemoveAurasDueToSpell((*iter)->GetId()); - iter = m_modAuras[auraType].begin(); - } - else - ++iter; - } - } -} - -// Nostalrius -void Unit::RemoveFearEffectsByDamageTaken(uint32 damage, uint32 exceptSpellId, DamageEffectType damagetype) -{ - if (!HasAuraType(SPELL_AURA_MOD_FEAR)) - return; - if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) - return; - - // Formula derived from Youfie's post here: - // https://forum.nostalrius.org/viewtopic.php?f=5&t=17424#p119432 - - // The chance to dispel an aura depends on the damage taken with respect to the caster's level. - uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50; - - // Players are 3x more likely to break fears - if (GetTypeId() == TYPEID_PLAYER) - max_dmg *= 0.333f; - // DOT spells are 3x less likely to break fears - if (damagetype == DOT) - max_dmg *= 3; - - // for players, this means max_dmg = 450 at level 60, or 1350 if the damage source is a dot - // for mobs, this means max_dmg = 1350 at level 60, or 4050 if the damage source is a dot - - float chance = float(damage) / float(max_dmg) * 100.0f; - - if (!roll_chance_f(chance)) - return; - - for (AuraList::const_iterator iter = m_modAuras[SPELL_AURA_MOD_FEAR].begin(); iter != m_modAuras[SPELL_AURA_MOD_FEAR].end();) - { - // skip `except` aura - if ((*iter)->GetId() == exceptSpellId) - { - ++iter; - continue; - } - bool canRemoveAura = false; - switch ((*iter)->GetSpellProto()->Mechanic) - { - case MECHANIC_FEAR: - case MECHANIC_TURN: // [Turn Undead] #2878 - canRemoveAura = true; - break; - } - if (!canRemoveAura) - { - ++iter; - continue; - } - RemoveAurasDueToSpell((*iter)->GetId()); - iter = m_modAuras[SPELL_AURA_MOD_FEAR].begin(); - } -} - -void Unit::DoKillUnit(Unit* victim) -{ - if (!victim) - victim = this; - if (!victim->isAlive()) - return; - DealDamage(victim, victim->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); -} - -void Unit::DealDamageMods(Unit *victim, uint32 &damage, uint32* absorb) -{ - // [Nostalrius] Pas de degats sous esprit de redemption - if (!victim->isAlive() || victim->IsTaxiFlying() || (victim->GetTypeId() == TYPEID_UNIT && ((Creature*)victim)->IsInEvadeMode()) || - (getClass() == CLASS_PRIEST && HasAura(27827))) - { - if (absorb) - *absorb += damage; - damage = 0; - return; - } - - uint32 originalDamage = damage; - - //Script Event damage Deal - if (GetTypeId() == TYPEID_UNIT && ((Creature *)this)->AI()) - ((Creature *)this)->AI()->DamageDeal(victim, damage); - //Script Event damage taken - if (victim->GetTypeId() == TYPEID_UNIT && ((Creature *)victim)->AI()) - ((Creature *)victim)->AI()->DamageTaken(this, damage); - - if (absorb && originalDamage > damage) - *absorb += (originalDamage - damage); -} - -uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss, Spell* spell) -{ - // remove affects from victim (including from 0 damage and DoTs) - if (pVictim != this) - pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); - - // remove affects from attacker at any non-DoT damage (including 0 damage) - if (damagetype != DOT) - { - RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); - RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); - - if (pVictim != this) - RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY); - - if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) - pVictim->SetStandState(UNIT_STAND_STATE_STAND); - } - - if (!damage) - { - if (cleanDamage) - { - //sLog.outString("[ABSORB] Deal Damage sur %s (Dam%u|Absorb%u|Resist%u)", pVictim->GetName(), cleanDamage->damage, cleanDamage->absorb, cleanDamage->resist); - - // Rage on outgoing parry/dodge - if (cleanDamage->hitOutCome == MELEE_HIT_PARRY || cleanDamage->hitOutCome == MELEE_HIT_DODGE) - { - if (cleanDamage->damage && damagetype == DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE)) - ((Player*)this)->RewardRage(cleanDamage->damage*0.75, true); - } - - // Degats recus sous bouclier par exemple. - if (cleanDamage->absorb) - { - if (!spellProto || !spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR)) - { - if (!(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsWorldBoss())) - pVictim->RemoveFearEffectsByDamageTaken(cleanDamage->absorb, spellProto ? spellProto->Id : 0, damagetype); - } - - if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT))) - pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, cleanDamage->absorb); - - pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DAMAGE, spellProto ? spellProto->Id : 0); - - // interrupt spells like trying to mount even through absorb shields - if (pVictim->GetTypeId() == TYPEID_PLAYER && damagetype != DOT) - pVictim->InterruptSpellsWithInterruptFlags(SPELL_INTERRUPT_FLAG_ABORT_ON_DMG, spellProto ? spellProto->Id : 0); - } - if (damagetype != DOT) - { - SetInCombatWith(pVictim); - pVictim->SetInCombatWith(this); - } - - //PMonsterSay("-> Absorb %5u | Resist %5u. AttackType %u", cleanDamage->absorb, cleanDamage->resist, cleanDamage->hitOutCome); - if (Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself()) - SetContestedPvP(attackedPlayer); - } - return 0; - } - //else if (cleanDamage) - // sLog.outString("[NORMAL] Deal Damage sur %s (Dam%u|Absorb%u|Resist%u)", pVictim->GetName(), cleanDamage->damage, cleanDamage->absorb, cleanDamage->resist); - - if (!spellProto || !spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR)) - { - if (!(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsWorldBoss())) - pVictim->RemoveFearEffectsByDamageTaken(damage, spellProto ? spellProto->Id : 0, damagetype); - } - - // root type spells do not dispel the root effect - if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT))) - pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage); - - // no xp,health if type 8 /critters/ - uint32 victimEntry = pVictim->GetEntry(); - if (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER && victimEntry != 10441 && victimEntry != 10461 && victimEntry != 10536) - { - // TODO: fix this part - // Critter may not die of damage taken, instead expect it to run away (no fighting back) - // If (this) is TYPEID_PLAYER, (this) will enter combat w/victim, but after some time, automatically leave combat. - // It is unclear how it should work for other cases. - - Creature* creature = pVictim->ToCreature(); - creature->SetLootRecipient(this); - - pVictim->SetDeathState(JUST_DIED); - pVictim->SetHealth(0); - - if (!creature->IsPet()) - { - creature->DeleteThreatList(); - if (CreatureInfo const *cinfo = creature->GetCreatureInfo()) - if (cinfo->lootid || cinfo->maxgold > 0) - creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); - } - // some critters required for quests - if (GetTypeId() == TYPEID_PLAYER) - if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry())) - ((Player*)this)->KilledMonster(normalInfo, pVictim->GetObjectGuid()); - // Nostalrius : ajout de 'JustDied' pour les CRITTER. - if (CreatureAI* pAi = pVictim->AI()) - pAi->JustDied(this); - - if (InstanceData* mapInstance = pVictim->GetInstanceData()) - mapInstance->OnCreatureDeath(((Creature*)pVictim)); - - DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamage critter, critter dies"); - - // Rage from Damage made vs critters (only from direct weapon damage) - if (damage && damagetype == DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE)) - ((Player*)this)->RewardRage(damage, true); - - return damage; - } - - uint32 health = pVictim->GetHealth(); - // duel ends when player has 1 or less hp - bool duel_hasEnded = false; - if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health - 1)) - { - // prevent kill only if killed in duel and killed by opponent or opponent controlled creature - if (((Player*)pVictim)->duel->opponent == this || ((Player*)pVictim)->duel->opponent->GetObjectGuid() == GetOwnerGuid()) - damage = health - 1; - - duel_hasEnded = true; - } - //Get in CombatState - if ((pVictim != this) && (damagetype != DOT) && - (!spellProto || !spellProto->IsAuraAddedBySpell(SPELL_AURA_DAMAGE_SHIELD))) - { - SetInCombatWith(pVictim); - pVictim->SetInCombatWith(this); - if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_UNIT) - pVictim->ToCreature()->ResetLastDamageTakenTime(); - - if (Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself()) - SetContestedPvP(attackedPlayer); - } - if (pVictim->GetTypeId() == TYPEID_UNIT) - pVictim->ToCreature()->CountDamageTaken(damage, GetCharmerOrOwnerOrOwnGuid().IsPlayer() || pVictim == this); - else if (pVictim != this) - { - if (Player* attackerPlayer = GetAffectingPlayer()) - pVictim->UnitDamaged(attackerPlayer->GetObjectGuid(), damage); - else - pVictim->UnitDamaged(ObjectGuid(), damage); - } - - // Rage from Damage made (only from direct weapon damage) - if (damage && damagetype == DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE)) - ((Player*)this)->RewardRage(damage, true); - - if (Creature* creaVictim = pVictim->ToCreature()) - if (!creaVictim->IsPet() && !creaVictim->HasLootRecipient()) - creaVictim->SetLootRecipient(this); - if (health <= damage) - { - // Can't kill gods - if (Player* pPlayer = pVictim->ToPlayer()) - if (pPlayer->IsGod()) - return 0; - - DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamage: victim just died"); - Kill(pVictim, spellProto, durabilityLoss); // Function too long, we cut - // last damage from non duel opponent or opponent controlled creature - if (duel_hasEnded) - { - MANGOS_ASSERT(pVictim->GetTypeId() == TYPEID_PLAYER); - Player *he = (Player*)pVictim; - - MANGOS_ASSERT(he->duel); - - he->duel->opponent->CombatStopWithPets(true); - he->CombatStopWithPets(true); - - he->DuelComplete(DUEL_INTERUPTED); - } - } - else // if (health <= damage) - { - pVictim->ModifyHealth(- (int32)damage); - - if (damagetype != DOT) - { - if (!getVictim()) - { - // if not have main target then attack state with target (including AI call) - //start melee attacks only after melee hit - Attack(pVictim, (damagetype == DIRECT_DAMAGE)); - } - - // if damage pVictim call AI reaction - if (!spell) // AttackedBy already handled at spell cast - pVictim->AttackedBy(this); - } - - // polymorphed, hex and other negative transformed cases - uint32 morphSpell = pVictim->getTransForm(); - if (morphSpell && !IsPositiveSpell(morphSpell)) - { - if (SpellEntry const* morphEntry = sSpellMgr.GetSpellEntry(morphSpell)) - { - if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_CONFUSE)) - pVictim->RemoveAurasDueToSpell(morphSpell); - else if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_PACIFY_SILENCE)) - pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_PACIFY_SILENCE, damage); - } - } - - if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE) - { - if (!spellProto || !(spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DIRECT_DAMAGE)) - pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE); - } - if (pVictim->GetTypeId() != TYPEID_PLAYER) - { - float threat = damage * sSpellMgr.GetSpellThreatMultiplier(spellProto); - pVictim->AddThreat(this, threat, (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto); - } - else // victim is a player - { - // Rage from damage received - if (this != pVictim && pVictim->getPowerType() == POWER_RAGE) - { - ((Player*)pVictim)->RewardRage(damage, false); - } - - // random durability for items (HIT TAKEN) - if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE))) - { - EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END - 1)); - ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot); - } - } - - if (GetTypeId() == TYPEID_PLAYER) - { - // random durability for items (HIT DONE) - if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE))) - { - EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END - 1)); - ((Player*)this)->DurabilityPointLossForEquipSlot(slot); - } - } - - pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DAMAGE, spellProto ? spellProto->Id : 0); - - if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER) - { - if (damagetype != DOT) - { - for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) - { - // skip channeled spell (processed differently below) - if (i == CURRENT_CHANNELED_SPELL) - continue; - - if (Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i))) - { - if (spell->getState() == SPELL_STATE_PREPARING) - { - if (spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG) - pVictim->InterruptSpell(CurrentSpellTypes(i)); - else - spell->Delayed(); - } - } - } - - if (Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL]) - { - if (spell->getState() == SPELL_STATE_CASTING) - { - uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags; - if (channelInterruptFlags & CHANNEL_FLAG_DELAY) - { - if (pVictim != this) //don't shorten the duration of channeling if you damage yourself - spell->DelayedChannel(); - } - else if ((channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2))) - { - DETAIL_LOG("Spell %u canceled at damage!", spell->m_spellInfo->Id); - pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL); - } - } - else if (spell->getState() == SPELL_STATE_DELAYED) - // break channeled spell in delayed state on damage - { - DETAIL_LOG("Spell %u canceled at damage!", spell->m_spellInfo->Id); - pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL); - } - } - } - } - - // last damage from duel opponent - if (duel_hasEnded) - { - MANGOS_ASSERT(pVictim->GetTypeId() == TYPEID_PLAYER); - Player *he = (Player*)pVictim; - - MANGOS_ASSERT(he->duel); - - he->SetHealth(1); - - he->duel->opponent->CombatStopWithPets(true); - he->CombatStopWithPets(true); - - he->CastSpell(he, 7267, true); // beg - he->DuelComplete(DUEL_WON); - } - } - - return damage; -} - -void Unit::Kill(Unit* pVictim, SpellEntry const *spellProto, bool durabilityLoss) -{ - // find player: owner of controlled `this` or `this` itself maybe - // for loot will be sued only if group_tap==NULL - Player *player_tap = GetCharmerOrOwnerPlayerOrPlayerItself(); - Creature* creature = pVictim->ToCreature(); - Group *group_tap = nullptr; - - // find owner of pVictim, used for creature cases, AI calls - Unit* pOwner = pVictim->GetCharmerOrOwner(); - - // in creature kill case group/player tap stored for creature - if (creature) - { - if (creature->IsLootAllowedDueToDamageOrigin()) - { - group_tap = creature->GetGroupLootRecipient(); - - if (Player* recipient = creature->GetOriginalLootRecipient()) - player_tap = recipient; - // Set correct group_tap if player entered a group - if (player_tap && !group_tap) - group_tap = player_tap->GetGroup(); - } - else if (creature->lootForCreator && creature->GetCreatorGuid()) - { - Unit* creator = GetUnit(*this, creature->GetCreatorGuid()); - if (creator->IsPlayer()) - player_tap = (Player*)creator; - } - else - creature->SetLootRecipient(nullptr); - } - // in player kill case group tap selected by player_tap (killer-player itself, or charmer, or owner, etc) - else - { - if (player_tap) - group_tap = player_tap->GetGroup(); - } - - // Nostalrius: Loots desactives / map (retire ici l'XP et les reputs) - bool allowLoot = !sObjectMgr.IsMapLootDisabled(GetMapId()); - // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop) - if (allowLoot && player_tap && player_tap != pVictim) - { - WorldPacket data(SMSG_PARTYKILLLOG, (8 + 8)); //send event PARTY_KILL - data << player_tap->GetObjectGuid(); //player with killing blow - data << pVictim->GetObjectGuid(); //victim - - Player* looter = player_tap; - if (group_tap) - { - group_tap->BroadcastPacket(&data, false, group_tap->GetMemberGroup(player_tap->GetObjectGuid()), player_tap->GetObjectGuid()); - - if (creature) - { - group_tap->UpdateLooterGuid(creature, true); - if (group_tap->GetLooterGuid()) - { - looter = ObjectAccessor::FindPlayer(group_tap->GetLooterGuid()); - if (looter) - { - creature->SetLootRecipient(looter); // update creature loot recipient to the allowed looter. - group_tap->SendLooter(creature, looter); - } - else - group_tap->SendLooter(creature, nullptr); - } - else - group_tap->SendLooter(creature, nullptr); - - group_tap->UpdateLooterGuid(creature); - } - } - - player_tap->SendDirectMessage(&data); - - if (creature) - { - Loot* loot = &creature->loot; - if (creature->lootForPickPocketed) - creature->lootForPickPocketed = false; - - loot->clear(); - if (creature->AI() || !creature->AI()->FillLoot(loot, looter)) - if (uint32 lootid = creature->GetCreatureInfo()->lootid) - { - loot->SetTeam(group_tap ? group_tap->GetTeam() : looter->GetTeam()); - loot->FillLoot(lootid, LootTemplates_Creature, looter, false, false, creature); - } - - loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold, creature->GetCreatureInfo()->maxgold); - } - - if (group_tap) - group_tap->RewardGroupAtKill(pVictim, player_tap); - else if (player_tap) - player_tap->RewardSinglePlayerAtKill(pVictim); - } - if (Player* playerVictim = pVictim->ToPlayer()) - playerVictim->RewardHonorOnDeath(); - - // To be replaced if possible using ProcDamageAndSpell - if (pVictim != this) // The one who has the fatal blow - ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0); - - DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageAttackStop"); - - // before the stop of combat, the auras of type CM are withdrawn. We must be able to redirect the mobs to the caster. - // You should specify 'AURA_REMOVE_BY_DEATH', but this is not useful for these auras. - pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM); - pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS); - - // stop combat - pVictim->CombatStop(); - pVictim->getHostileRefManager().deleteReferences(); - - bool damageFromSpiritOfRedemtionTalent = (spellProto && spellProto->Id == 27795); - - // if talent known but not triggered (check priest class for speedup check) - bool spiritOfRedemtionTalentImmune = false; - if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST) - { - if (!damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION - pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST) - { - AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY); - for (AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr) - { - if ((*itr)->GetSpellProto()->SpellIconID == 1654) - { - spiritOfRedemtionTalentImmune = true; - break; - } - } - } - - // Already applied spirit of redemption. Fix stuck in ANGEL form. - if (!spiritOfRedemtionTalentImmune && HasAura(27827)) - return; - } - - if (!spiritOfRedemtionTalentImmune) - { - pVictim->SetHealth(0); - DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "SET JUST_DIED"); - pVictim->SetDeathState(JUST_DIED); - // Nostalrius: Instantly send values update for health - if (pVictim->ToPlayer() && pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL)) - pVictim->DirectSendPublicValueUpdate(PLAYER_SELF_RES_SPELL); - pVictim->DirectSendPublicValueUpdate(UNIT_FIELD_HEALTH); - } - - // outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh... - // handle player kill only if not suicide (spirit of redemption for example) - if (GetTypeId() == TYPEID_PLAYER && this != pVictim) - if (ZoneScript * pZoneScript = ((Player*)this)->GetZoneScript()) - pZoneScript->HandleKill((Player*)this, pVictim); - - DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageHealth1"); - - if (spiritOfRedemtionTalentImmune) - { - // save value before aura remove - uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL); - if (!ressSpellId) - ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId(); - - //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers) - pVictim->RemoveAllAurasOnDeath(); - - // restore for use at real death - pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); - - // FORM_SPIRITOFREDEMPTION and related auras - pVictim->AddAura(27827, ADD_AURA_NO_OPTION, pVictim); - pVictim->InterruptNonMeleeSpells(false); - } - else - pVictim->SetHealth(0); - - // remember victim PvP death for corpse type and corpse reclaim delay - // at original death (not at SpiritOfRedemtionTalent timeout) - if (pVictim->GetTypeId() == TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent) - ((Player*)pVictim)->SetPvPDeath(player_tap != nullptr); - - // Call KilledUnit for creatures - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI()) - ((Creature*)this)->AI()->KilledUnit(pVictim); - - // Call AI OwnerKilledUnit (for any current summoned minipet/guardian/protector) - PetOwnerKilledUnit(pVictim); - - // 10% durability loss on death - // clean InHateListOf - if (pVictim->GetTypeId() == TYPEID_PLAYER) - { - // only if not player and not controlled by player pet. And not at BG - if (durabilityLoss && !player_tap && !((Player*)pVictim)->InBattleGround()) - { - DEBUG_LOG("We are dead, loosing 10 percents durability"); - ((Player*)pVictim)->DurabilityLossAll(0.10f, false); - // durability lost message - WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0); - ((Player*)pVictim)->GetSession()->SendPacket(&data); - } - } - else // creature died - { - DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageNotPlayer"); - - if (!creature->IsPet()) - { - creature->LogDeath(this); - creature->UpdateCombatState(false); - - creature->DeleteThreatList(); - if (CreatureInfo const *cinfo = creature->GetCreatureInfo()) - if (cinfo->lootid || cinfo->maxgold > 0) - creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); - } - - // Call creature just died function - if (creature->AI()) - creature->AI()->JustDied(this); - - if (creature->IsTemporarySummon()) - { - TemporarySummon* pSummon = (TemporarySummon*)creature; - if (pSummon->GetSummonerGuid().IsCreature()) - if (Creature* pSummoner = creature->GetMap()->GetCreature(pSummon->GetSummonerGuid())) - if (pSummoner->AI()) - pSummoner->AI()->SummonedCreatureJustDied(creature); - } - else if (pOwner && pOwner->GetTypeId() == TYPEID_UNIT) - { - if (((Creature*)pOwner)->AI()) - ((Creature*)pOwner)->AI()->SummonedCreatureJustDied(creature); - } - - if (ZoneScript* pScript = creature->GetZoneScript()) - pScript->OnCreatureDeath(creature); - - // Dungeon specific stuff, only applies to players killing creatures - if (creature->GetInstanceId() && creature->GetMapId() > 1) - if (Player* playerKiller = GetCharmerOrOwnerPlayerOrPlayerItself()) - creature->GetMap()->BindToInstanceOrRaid(playerKiller, creature->GetRespawnTimeEx(), creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND); - } - - // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill) - if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround()) - { - Player *killed = ((Player*)pVictim); - if (BattleGround *bg = killed->GetBattleGround()) - bg->HandleKillPlayer(killed, player_tap); - } - else if (pVictim->GetTypeId() == TYPEID_UNIT) - { - if (player_tap) - if (BattleGround *bg = player_tap->GetBattleGround()) - bg->HandleKillUnit((Creature*)pVictim, player_tap); - } - // Nostalrius: interrupt non melee spell casted - pVictim->InterruptSpellsCastedOnMe(false, true); - if (player_tap) - ALL_SESSION_SCRIPTS(player_tap->GetSession(), OnUnitKilled(pVictim->GetObjectGuid())); -} - -struct PetOwnerKilledUnitHelper -{ - explicit PetOwnerKilledUnitHelper(Unit* pVictim) : m_victim(pVictim) {} - void operator()(Unit* pTarget) const - { - if (pTarget->GetTypeId() == TYPEID_UNIT) - { - if (((Creature*)pTarget)->AI()) - ((Creature*)pTarget)->AI()->OwnerKilledUnit(m_victim); - } - } - - Unit* m_victim; -}; - -void Unit::PetOwnerKilledUnit(Unit* pVictim) -{ - // for minipet and guardians (including protector) - CallForAllControlledUnits(PetOwnerKilledUnitHelper(pVictim), CONTROLLED_MINIPET | CONTROLLED_GUARDIANS); -} - -void Unit::CastStop(uint32 except_spellid) -{ - for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) - if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) - if (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) - InterruptSpell(CurrentSpellTypes(i), false); -} - -void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) -{ - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); - - if (!spellInfo) - { - if (triggeredByAura) - sLog.outError("CastSpell: unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); - else - sLog.outError("CastSpell: unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); - return; - } - - CastSpell(Victim, spellInfo, triggered, castItem, triggeredByAura, originalCaster, triggeredBy); -} - -void Unit::CastSpell(Unit* Victim, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) -{ - if (!spellInfo) - { - if (triggeredByAura) - sLog.outError("CastSpell: unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); - else - sLog.outError("CastSpell: unknown spell by caster: %s", GetGuidStr().c_str()); - return; - } - - if (castItem) - DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id); - - if (triggeredByAura) - { - if (!originalCaster) - originalCaster = triggeredByAura->GetCasterGuid(); - - triggeredBy = triggeredByAura->GetSpellProto(); - } - - Spell *spell = new Spell(this, spellInfo, triggered, originalCaster, triggeredBy); - - SpellCastTargets targets; - targets.setUnitTarget(Victim); - - if (spellInfo->Targets & TARGET_FLAG_DEST_LOCATION) - targets.setDestination(Victim->GetPositionX(), Victim->GetPositionY(), Victim->GetPositionZ()); - if (spellInfo->Targets & TARGET_FLAG_SOURCE_LOCATION) - if (WorldObject* caster = spell->GetCastingObject()) - targets.setSource(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ()); - - spell->SetCastItem(castItem); - spell->prepare(&targets, triggeredByAura); -} - -void Unit::CastCustomSpell(Unit* Victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) -{ - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); - - if (!spellInfo) - { - if (triggeredByAura) - sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); - else - sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); - return; - } - - CastCustomSpell(Victim, spellInfo, bp0, bp1, bp2, triggered, castItem, triggeredByAura, originalCaster, triggeredBy); -} - -void Unit::CastCustomSpell(Unit* Victim, SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) -{ - if (!spellInfo) - { - if (triggeredByAura) - sLog.outError("CastCustomSpell: unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); - else - sLog.outError("CastCustomSpell: unknown spell by caster: %s", GetGuidStr().c_str()); - return; - } - - if (castItem) - DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id); - - if (triggeredByAura) - { - if (!originalCaster) - originalCaster = triggeredByAura->GetCasterGuid(); - - triggeredBy = triggeredByAura->GetSpellProto(); - } - - Spell *spell = new Spell(this, spellInfo, triggered, originalCaster, triggeredBy); - - if (bp0) - spell->m_currentBasePoints[EFFECT_INDEX_0] = *bp0; - - if (bp1) - spell->m_currentBasePoints[EFFECT_INDEX_1] = *bp1; - - if (bp2) - spell->m_currentBasePoints[EFFECT_INDEX_2] = *bp2; - - SpellCastTargets targets; - targets.setUnitTarget(Victim); - spell->SetCastItem(castItem); - spell->prepare(&targets, triggeredByAura); -} - -// used for scripting -void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) -{ - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); - - if (!spellInfo) - { - if (triggeredByAura) - sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); - else - sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); - return; - } - - CastSpell(x, y, z, spellInfo, triggered, castItem, triggeredByAura, originalCaster, triggeredBy); -} - -// used for scripting -void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) -{ - if (!spellInfo) - { - if (triggeredByAura) - sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); - else - sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s", GetGuidStr().c_str()); - return; - } - - if (castItem) - DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id); - - if (triggeredByAura) - { - if (!originalCaster) - originalCaster = triggeredByAura->GetCasterGuid(); - - triggeredBy = triggeredByAura->GetSpellProto(); - } - - Spell *spell = new Spell(this, spellInfo, triggered, originalCaster, triggeredBy); - - SpellCastTargets targets; - targets.setDestination(x, y, z); - spell->SetCastItem(castItem); - spell->prepare(&targets, triggeredByAura); -} - -// Obsolete func need remove, here only for comotability vs another patches -uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage) -{ - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellID); - SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, SpellSchools(spellInfo->School)); - CalculateSpellDamage(&damageInfo, damage, spellInfo); - damageInfo.target->CalculateAbsorbResistBlock(this, &damageInfo, spellInfo); - DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); - SendSpellNonMeleeDamageLog(&damageInfo); - DealSpellDamage(&damageInfo, true); - return damageInfo.damage; -} - -void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType, Spell* spell) -{ - SpellSchoolMask damageSchoolMask = GetSchoolMask(damageInfo->school); - Unit *pVictim = damageInfo->target; - if (!pVictim) - return; - - if (damage < 0) - return; - - if (!pVictim->isAlive()) - return; - - // Check spell crit chance - bool crit = IsSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType, spell); - - // damage bonus (per damage class) - switch (spellInfo->DmgClass) - { - // Melee and Ranged Spells - case SPELL_DAMAGE_CLASS_RANGED: - case SPELL_DAMAGE_CLASS_MELEE: - { - //Calculate damage bonus - damage = MeleeDamageBonusDone(pVictim, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE, 1, spell); - damage = pVictim->MeleeDamageBonusTaken(this, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE, 1, spell); - - // if crit add critical bonus - if (crit) - { - damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; - damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim, spell); - } - } - break; - // Magical Attacks - case SPELL_DAMAGE_CLASS_NONE: - case SPELL_DAMAGE_CLASS_MAGIC: - { - // Calculate damage bonus - damage = SpellDamageBonusDone(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE, 1, spell); - damage = pVictim->SpellDamageBonusTaken(this, spellInfo, damage, SPELL_DIRECT_DAMAGE, 1, spell); - - // If crit add critical bonus - if (crit) - { - damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; - damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim, spell); - } - } - break; - } - - // damage mitigation - if (damage > 0) - { - // physical damage => armor - if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL && !(spellInfo->Custom & SPELL_CUSTOM_IGNORE_ARMOR)) - damage = CalcArmorReducedDamage(pVictim, damage); - } - else - damage = 0; - damageInfo->damage = damage; -} - -void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss) -{ - if (!damageInfo) - return; - - Unit *pVictim = damageInfo->target; - - if (!pVictim) - return; - - if (!pVictim->isAlive() || pVictim->IsTaxiFlying() || (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())) - return; - - SpellEntry const *spellProto = sSpellMgr.GetSpellEntry(damageInfo->SpellID); - if (spellProto == nullptr) - { - sLog.outError("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID); - return; - } - - // Call default DealDamage (send critical in hit info for threat calculation) - CleanDamage cleanDamage(0, BASE_ATTACK, damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT ? MELEE_HIT_CRIT : MELEE_HIT_NORMAL, damageInfo->absorb, damageInfo->resist); - DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, GetSchoolMask(damageInfo->school), spellProto, durabilityLoss, damageInfo->spell); -} - -//TODO for melee need create structure as in -void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType) -{ - if (!pVictim) - return; - if (!isAlive() || !pVictim->isAlive()) - return; - - damageInfo->attacker = this; - damageInfo->target = pVictim; - damageInfo->attackType = attackType; - damageInfo->totalDamage = 0; - damageInfo->cleanDamage = 0; - damageInfo->totalAbsorb = 0; - damageInfo->totalResist = 0; - damageInfo->blocked_amount = 0; - - damageInfo->TargetState = VICTIMSTATE_UNAFFECTED; - damageInfo->HitInfo = HITINFO_NORMALSWING; - damageInfo->procAttacker = PROC_FLAG_NONE; - damageInfo->procVictim = PROC_FLAG_NONE; - damageInfo->procEx = PROC_EX_NONE; - damageInfo->hitOutCome = MELEE_HIT_EVADE; - - // Select HitInfo/procAttacker/procVictim flag based on attack type - switch (attackType) - { - case BASE_ATTACK: - damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT; - damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT; - damageInfo->HitInfo = HITINFO_NORMALSWING2; - SetLastAttackType(0); // Nostalrius : Ivina (lastAttackType) - break; - case OFF_ATTACK: - damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT; - damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used - damageInfo->HitInfo = HITINFO_LEFTSWING; - SetLastAttackType(1); - break; - case RANGED_ATTACK: - damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT; - damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT; - damageInfo->HitInfo = HITINFO_UNK3; // test (dev note: test what? HitInfo flag possibly not confirmed.) - SetLastAttackType(2); - break; - default: - break; - } - - bool immune = true; - bool feral = IsInFeralForm(); - - // Only get one damage type for feral druids so they don't receive incorrect benefits - // from weapons with multiple types of damage - uint8 actualDamageCount = feral ? 1 : m_weaponDamageCount[damageInfo->attackType]; - for (uint8 i = 0; i < actualDamageCount; i++) - { - SubDamageInfo *subDamage = &damageInfo->subDamage[i]; - - // feral only allowed melee school - subDamage->damageSchoolMask = GetTypeId() == TYPEID_PLAYER && !feral - ? GetSchoolMask(GetWeaponDamageSchool(damageInfo->attackType, i)) - : GetMeleeDamageSchoolMask(); - - if (damageInfo->target->IsImmuneToDamage(subDamage->damageSchoolMask)) - { - subDamage->damage = 0; - continue; - } - else - immune = false; - - subDamage->damage = CalculateDamage(damageInfo->attackType, false, i); - // Add melee damage bonus - subDamage->damage = MeleeDamageBonusDone(damageInfo->target, subDamage->damage, damageInfo->attackType, nullptr, DIRECT_DAMAGE, 1, nullptr, i == 0); - subDamage->damage = damageInfo->target->MeleeDamageBonusTaken(this, subDamage->damage, damageInfo->attackType, nullptr, DIRECT_DAMAGE, 1, nullptr, i == 0); - - // Calculate armor reduction - if(subDamage->damageSchoolMask == SPELL_SCHOOL_MASK_NORMAL) - { - damageInfo->cleanDamage += subDamage->damage; - subDamage->damage = CalcArmorReducedDamage(damageInfo->target, subDamage->damage); - damageInfo->cleanDamage -= subDamage->damage; - } - - damageInfo->totalDamage += subDamage->damage; - } - - // Physical Immune check - if (immune) - { - damageInfo->HitInfo |= HITINFO_NORMALSWING; - damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE; - - damageInfo->procEx |= PROC_EX_IMMUNE; - damageInfo->totalDamage = 0; - damageInfo->cleanDamage = 0; - return; - } - - damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType); - - // Disable parry or dodge for ranged attack - if (damageInfo->attackType == RANGED_ATTACK) - { - if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL; - if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS; - } - - switch (damageInfo->hitOutCome) - { - case MELEE_HIT_EVADE: - { - damageInfo->HitInfo |= HITINFO_MISS | HITINFO_SWINGNOHITSOUND; - damageInfo->TargetState = VICTIMSTATE_EVADES; - - damageInfo->procEx |= PROC_EX_EVADE; - damageInfo->totalDamage = 0; - damageInfo->cleanDamage = 0; - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage = 0; - - return; - } - case MELEE_HIT_MISS: - { - damageInfo->HitInfo |= HITINFO_MISS; - damageInfo->TargetState = VICTIMSTATE_UNAFFECTED; - - damageInfo->procEx |= PROC_EX_MISS; - damageInfo->totalDamage = 0; - damageInfo->cleanDamage = 0; - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage = 0; - - break; - } - case MELEE_HIT_NORMAL: - { - damageInfo->TargetState = VICTIMSTATE_NORMAL; - damageInfo->procEx |= PROC_EX_NORMAL_HIT; - break; - } - case MELEE_HIT_CRIT: - { - damageInfo->HitInfo |= HITINFO_CRITICALHIT; - damageInfo->TargetState = VICTIMSTATE_NORMAL; - - damageInfo->procEx |= PROC_EX_CRITICAL_HIT; - - uint32 creatureTypeMask = damageInfo->target->GetCreatureTypeMask(); - - int32 mod = GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask); - - damageInfo->totalDamage = uint32((damageInfo->totalDamage) * float((200.0f + mod) / 100.0f)); - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage = uint32((damageInfo->subDamage[i].damage) * float((200.0f + mod) / 100.0f)); - - break; - } - case MELEE_HIT_PARRY: - { - damageInfo->TargetState = VICTIMSTATE_PARRY; - damageInfo->procEx |= PROC_EX_PARRY; - damageInfo->cleanDamage += damageInfo->totalDamage; - damageInfo->totalDamage = 0; - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage = 0; - - break; - } - case MELEE_HIT_DODGE: - { - damageInfo->TargetState = VICTIMSTATE_DODGE; - damageInfo->procEx |= PROC_EX_DODGE; - damageInfo->cleanDamage += damageInfo->totalDamage; - damageInfo->totalDamage = 0; - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage = 0; - - break; - } - case MELEE_HIT_BLOCK: - { - damageInfo->TargetState = VICTIMSTATE_NORMAL; - damageInfo->procEx |= PROC_EX_BLOCK; - damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue(); - if (damageInfo->blocked_amount >= damageInfo->subDamage[0].damage) - { - damageInfo->TargetState = VICTIMSTATE_BLOCKS; - damageInfo->blocked_amount = damageInfo->subDamage[0].damage; - } - else - damageInfo->procEx |= PROC_EX_NORMAL_HIT; // Partial blocks can still cause attacker procs - - damageInfo->totalDamage -= damageInfo->blocked_amount; - damageInfo->subDamage[0].damage -= damageInfo->blocked_amount; - damageInfo->cleanDamage += damageInfo->blocked_amount; - break; - } - case MELEE_HIT_GLANCING: - { - damageInfo->HitInfo |= HITINFO_GLANCING; - damageInfo->TargetState = VICTIMSTATE_NORMAL; - damageInfo->procEx |= PROC_EX_NORMAL_HIT; - // int32 attackerWeaponSkill = GetWeaponSkillValue(damageInfo->attackType,pVictim); - // int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this); - int SkillDiff = 0; - SkillDiff = pVictim->GetDefenseSkillValue(this) - GetWeaponSkillValue(damageInfo->attackType, pVictim); - float reducePercent = 1.0f; - // (Youfie) Formule de calcul de la réduction de dégâts des érafles, influencée en pré-BC par le +skill au delà de [niveau du joueur * 5] - // Formule d'Athan retenue et supposée comme Blizz-like au regard des multiples sources et tests concordants - // float reducePercent = 1 - (5*(pow(2,(victimDefenseSkill/5) - (attackerWeaponSkill/5) - 1))/100); - // Après tentative d'implémentation "propre" de la formule et de nombreux échecs, mise en place de celle-ci après calcul manuel des différentes valeurs - // cf. http://nostalrius.org/forum/viewtopic.php?p=43964#p43964 pour infos et sources - if (SkillDiff >= 15) - reducePercent = 0.6500f; - if (SkillDiff <= 0) - reducePercent = 1; - switch (SkillDiff) - { - case 14 : - reducePercent = 0.7018f; - break; - case 13 : - reducePercent = 0.7469f; - break; - case 12 : - reducePercent = 0.7860f; - break; - case 11 : - reducePercent = 0.8203f; - break; - case 10 : - reducePercent = 0.8500f; - break; - case 9 : - reducePercent = 0.8759f; - break; - case 8 : - reducePercent = 0.8984f; - break; - case 7 : - reducePercent = 0.9180f; - break; - case 6 : - reducePercent = 0.9351f; - break; - case 5 : - reducePercent = 0.9500f; - break; - case 4 : - reducePercent = 0.9629f; - break; - case 3 : - reducePercent = 0.9742f; - break; - case 2 : - reducePercent = 0.9840f; - break; - case 1 : - reducePercent = 0.9926f; - break; - } - - // sLog.outString("SkillDiff = %i, reducePercent = %f", SkillDiff, reducePercent); // Pour tests & débug via la console - - damageInfo->cleanDamage += uint32((1.0f - reducePercent) * damageInfo->totalDamage); - damageInfo->totalDamage = uint32(reducePercent * damageInfo->totalDamage); - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage = uint32(reducePercent * damageInfo->subDamage[i].damage); - - break; - } - case MELEE_HIT_CRUSHING: - { - damageInfo->HitInfo |= HITINFO_CRUSHING; - damageInfo->TargetState = VICTIMSTATE_NORMAL; - damageInfo->procEx |= PROC_EX_NORMAL_HIT; - - // 150% of normal damage - damageInfo->totalDamage += damageInfo->totalDamage / 2; - - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - damageInfo->subDamage[i].damage += damageInfo->subDamage[i].damage / 2; - - break; - } - default: - break; - } - - // Calculate absorb resist - if (int32(damageInfo->totalDamage) > 0) - { - damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE; - - // Calculate absorb & resists - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - { - SubDamageInfo *subDamage = &damageInfo->subDamage[i]; - - damageInfo->target->CalculateDamageAbsorbAndResist(this, subDamage->damageSchoolMask, DIRECT_DAMAGE, subDamage->damage, &subDamage->absorb, &subDamage->resist, nullptr); - damageInfo->totalDamage -= subDamage->absorb + subDamage->resist; - subDamage->damage -= subDamage->absorb + subDamage->resist; - - damageInfo->totalAbsorb += subDamage->absorb; - damageInfo->totalResist += subDamage->resist; - - if (subDamage->absorb) - { - damageInfo->HitInfo |= HITINFO_ABSORB; - damageInfo->procEx |= PROC_EX_ABSORB; - } - - if (subDamage->resist) - damageInfo->HitInfo |= HITINFO_RESIST; - } - } - else - damageInfo->totalDamage = 0; -} - -void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss) -{ - if (damageInfo == nullptr) return; - Unit *pVictim = damageInfo->target; - - if (!pVictim) - return; - - if (!pVictim->isAlive() || pVictim->IsTaxiFlying() || (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())) - return; - - // Hmmmm dont like this emotes client must by self do all animations - if (damageInfo->HitInfo & HITINFO_CRITICALHIT) - pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL); - if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS) - pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD); - - if (damageInfo->TargetState == VICTIMSTATE_PARRY) - { - // Get attack timers - float offtime = float(pVictim->getAttackTimer(OFF_ATTACK)); - float basetime = float(pVictim->getAttackTimer(BASE_ATTACK)); - // Reduce attack time - if (pVictim->haveOffhandWeapon() && offtime < basetime) - { - float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f; - float percent60 = 3.0f * percent20; - if (offtime > percent20 && offtime <= percent60) - pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20)); - else if (offtime > percent60) - { - offtime -= 2.0f * percent20; - pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime)); - } - } - else - { - float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20f; - float percent60 = 3.0f * percent20; - if (basetime > percent20 && basetime <= percent60) - pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20)); - else if (basetime > percent60) - { - basetime -= 2.0f * percent20; - pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime)); - } - } - } - - // Call default DealDamage - CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->attackType, damageInfo->hitOutCome, damageInfo->totalAbsorb, damageInfo->totalResist); - DealDamage(pVictim, damageInfo->totalDamage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->subDamage[0].damageSchoolMask), nullptr, durabilityLoss); - - // If this is a creature and it attacks from behind it has a probability to daze it's victim - if (damageInfo->totalDamage && GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGuid() && !pVictim->HasInArc(M_PI_F, this)) - { - // -probability is between 0% and 40% - // 20% base chance - uint32 VictimDefense = pVictim->GetDefenseSkillValue(); - uint32 AttackerMeleeSkill = GetUnitMeleeSkill(); - - float Probability = 0.0f; - - //there is a newbie protection, at level 10 just 7% base chance; assuming linear function - if (pVictim->getLevel() < 30) - Probability = 0.65f * pVictim->getLevel() + 0.5f + ((float)AttackerMeleeSkill - (float)VictimDefense) * 0.2f; - else - Probability = 20.0f + ((float)AttackerMeleeSkill - (float)VictimDefense) * 0.2f; - - if (Probability > 40.0f) - Probability = 40.0f; - - if (Player* pPlayer = pVictim->ToPlayer()) - if (pPlayer->IsGod()) - Probability = 0.0f; - - if (roll_chance_f(Probability)) - CastSpell(pVictim, 1604, true); - } - - // update at damage Judgement aura duration that applied by attacker at victim - if (damageInfo->totalDamage) - { - SpellAuraHolderMap const& vAuras = pVictim->GetSpellAuraHolderMap(); - for (SpellAuraHolderMap::const_iterator itr = vAuras.begin(); itr != vAuras.end(); ++itr) - { - SpellEntry const *spellInfo = (*itr).second->GetSpellProto(); - if (spellInfo->AttributesEx3 & 0x40000 && spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && ((*itr).second->GetCasterGuid() == GetObjectGuid())) - (*itr).second->RefreshHolder(); - } - } - - // If not miss - if (!(damageInfo->HitInfo & HITINFO_MISS) && damageInfo->TargetState != VICTIMSTATE_PARRY && damageInfo->TargetState != VICTIMSTATE_DODGE) - { - // on weapon hit casts - if (GetTypeId() == TYPEID_PLAYER && pVictim->isAlive()) - ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType); - - // victim's damage shield - std::set alreadyDone; - AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD); - for (AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();) - { - if (alreadyDone.find(*i) == alreadyDone.end()) - { - alreadyDone.insert(*i); - uint32 damage = (*i)->GetModifier()->m_amount; - SpellEntry const *i_spellProto = (*i)->GetSpellProto(); - - // apply SpellBaseDamageBonusTaken for mobs only - // for example, Death Talon Seethers with Aura of Flames reflect 1200 damage to tanks with Mark of Flame - if (pVictim->GetTypeId() == TYPEID_UNIT) - { - int32 spellDmgTakenBonus = this->SpellBaseDamageBonusTaken(GetSpellSchoolMask(i_spellProto)); - // don't allow damage shields to be reduced by Blessing of Sanctuary, etc. - if (spellDmgTakenBonus > 0) damage += spellDmgTakenBonus; - } - - //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist? - //uint32 absorb; - //uint32 resist; - //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist); - //damage-=absorb + resist; - - pVictim->DealDamageMods(this, damage, nullptr); - - WorldPacket data(SMSG_SPELLDAMAGESHIELD, (8 + 8 + 4 + 4)); - data << pVictim->GetObjectGuid(); - data << GetObjectGuid(); - data << uint32(damage); - data << uint32(i_spellProto->School); - pVictim->SendObjectMessageToSet(&data, true); - - pVictim->DealDamage(this, damage, nullptr, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true); - - i = vDamageShields.begin(); - } - else - ++i; - } - } -} - -void Unit::HandleEmoteCommand(uint32 emote_id) -{ - WorldPacket data(SMSG_EMOTE, 4 + 8); - data << uint32(emote_id); - data << GetObjectGuid(); - SendObjectMessageToSet(&data, true); -} - -void Unit::HandleEmoteState(uint32 emote_id) -{ - SetUInt32Value(UNIT_NPC_EMOTESTATE, emote_id); -} - -void Unit::HandleEmote(uint32 emote_id) -{ - if (!emote_id) - HandleEmoteState(0); - else if (EmotesEntry const* emoteEntry = sEmotesStore.LookupEntry(emote_id)) - { - if (emoteEntry->EmoteType) // 1,2 states, 0 command - HandleEmoteState(emote_id); - else - HandleEmoteCommand(emote_id); - } -} - -uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage) -{ - uint32 newdamage = 0; - float armor = (float)pVictim->GetArmor(); - - // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura - armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL); - - if (armor < 0.0f) - armor = 0.0f; - - float levelModifier = (float)getLevel(); - if (levelModifier > 59) - levelModifier = levelModifier + (4.5f * (levelModifier - 59)); - - float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40); - tmpvalue = tmpvalue / (1.0f + tmpvalue); - - if (tmpvalue < 0.0f) - tmpvalue = 0.0f; - if (tmpvalue > 0.75f) - tmpvalue = 0.75f; - - newdamage = uint32(damage - (damage * tmpvalue)); - - return (newdamage > 1) ? newdamage : 1; -} - -// NOSTALRIUS: Provient d'un tableau du forum (http://www.hostingpics.net/viewer.php?id=995056Resistances.jpg) -struct ResistanceValues -{ - int32 resist100; - int32 resist75; - int32 resist50; - int32 resist25; - int32 resist0; - uint32 chanceResist; -}; - -static ResistanceValues resistValues[] = -{ - {0, 0, 0, 0, 100, 0}, // 0 - {0, 0, 2, 6, 92, 3}, // 10 - {0, 1, 4, 12, 84, 5}, // 20 - {0, 1, 5, 18, 76, 8}, // 30 - {0, 1, 7, 23, 69, 10}, // 40 - {0, 2, 9, 28, 61, 13}, // 50 - {0, 2, 11, 33, 54, 15}, // 60 - {0, 2, 13, 37, 37, 18}, // 70 - {0, 3, 15, 41, 41, 20}, // 80 - {1, 3, 17, 46, 36, 23}, // 90 - {1, 4, 19, 47, 29, 25}, // 100 - {1, 5, 21, 48, 24, 28}, // 110 - {1, 6, 24, 49, 20, 30}, // 120 - {1, 8, 28, 47, 17, 33}, // 130 - {1, 9, 33, 43, 14, 35}, // 140 - {1, 11, 37, 39, 12, 38}, // 150 - {1, 13, 41, 35, 10, 40}, // 160 - {1, 16, 45, 30, 8, 43}, // 170 - {1, 18, 48, 26, 7, 45}, // 180 - {2, 20, 48, 24, 6, 43}, // 190 - {4, 23, 48, 21, 4, 50}, // 200 - {5, 25, 47, 19, 3, 53}, // 210 - {7, 28, 45, 17, 2, 55}, // 220 - {9, 31, 43, 16, 2, 58}, // 230 - {11, 34, 40, 14, 1, 60}, // 240 - {13, 37, 37, 12, 1, 62}, // 250 - {15, 41, 33, 10, 1, 65}, // 260 - {18, 44, 29, 8, 1, 68}, // 270 - {20, 48, 25, 7, 1, 70}, // 280 - {23, 51, 20, 5, 1, 73}, // 290 - {25, 55, 16, 3, 1, 75} // 300 -}; - -void Unit::CalculateDamageAbsorbAndResist(Unit *pCaster, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellEntry const* spellProto, Spell* spell) -{ - if (!pCaster || !isAlive() || !damage) - return; - - if (spell) - schoolMask = spell->m_spellSchoolMask; - - // Nostalrius : immune ? - if (IsImmuneToSchoolMask(schoolMask) && !(spellProto && (spellProto->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY))) - { - (*absorb) = damage; - return; - } - /* - if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || - (pCaster->IsPlayer() && pCaster->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) - return; - */ - - // Magic damage, check for resists - bool canResist = (schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0; - - // NOSTALRIUS: Sorts binaires ne sont pas résistés. - if (canResist && spellProto && spellProto->IsBinary()) - canResist = false; - else if (spellProto && spellProto->AttributesEx4 & SPELL_ATTR_EX4_IGNORE_RESISTANCES) - canResist = false; - - DEBUG_UNIT_IF(spellProto, this, DEBUG_SPELL_COMPUTE_RESISTS, "%s : Binary [%s]. Partial resists %s", spellProto->SpellName[2], spellProto->IsBinary() ? "YES" : "NO", canResist ? "possible" : "impossible"); - - if (canResist) - { - float resistanceChance = pCaster->GetSpellResistChance(this, schoolMask, true); - resistanceChance *= 100.0f; - - // DoTs - // The mechanic for this is strange in classic - most dots can be seen exhibiting partial resists in videos, but only very rarely, - // and almost never more than 25% resists. How this should work exactly is somewhat a guess. - // Kalgan post-2.0 dot nerf: "Previously, dots in general were 1/10th as likely to be resisted as normal spells." - // http://web.archive.org/web/20080601184008/http://forums.worldofwarcraft.com/thread.html?topicId=65457765&pageNo=18&sid=1#348 - if (damagetype == DOT && spellProto) - { - switch (spellProto->Id) - { - // NOSTALRIUS: Some DoTs follow normal resist rules. Need to find which ones, why and how. - // We have a video proof for the following ones. - case 23461: // Vaelastrasz's Flame Breath - case 24818: // Nightmare Dragon's Noxious Breath - case 25812: // Lord Kri's Toxic Volley - break; - default: - resistanceChance *= 0.1f; - } - } - - ResistanceValues* prev = nullptr; - ResistanceValues* next = nullptr; - for (int i = 1; i < 31; ++i) - { - // On depasse la valeur cherchee. - if (resistValues[i].chanceResist >= resistanceChance) - { - prev = &resistValues[i - 1]; - next = &resistValues[i]; - break; - } - } - ASSERT(next && prev); - float coeff = float(resistanceChance - prev->chanceResist) / float(next->chanceResist - prev->chanceResist); - float resist0 = prev->resist0 + (next->resist0 - prev->resist0) * coeff; - float resist25 = prev->resist25 + (next->resist25 - prev->resist25) * coeff; - float resist50 = prev->resist50 + (next->resist50 - prev->resist50) * coeff; - float resist75 = prev->resist75 + (next->resist75 - prev->resist75) * coeff; - float resist100 = prev->resist100 + (next->resist100 - prev->resist100) * coeff; - uint32 ran = urand(0, 99); - float resistCnt = 0.0f; - // Players CANNOT resist 100% of damage, it is always rounded down to 75%, despite what Blizzard's table sugests. - // The true magic damage resist cap is therefore actually ~68-70% because of this mechanic. - // http://web.archive.org/web/20110808083353/http://elitistjerks.com/f15/t10712-resisting_magical_damage_its_relation_resistance_levels/p4/ - if (ran < resist100 + resist75) - resistCnt = 0.75f; - else if (ran < resist100 + resist75 + resist50) - resistCnt = 0.5f; - else if (ran < resist100 + resist75 + resist50 + resist25) - resistCnt = 0.25f; - - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "Partial resist : chances %.2f:%.2f:%.2f:%.2f:%.2f. Hit resist chance %f", - resist0, resist25, resist50, resist75, resist100, resistanceChance); - *resist += uint32(damage * resistCnt); - if (*resist > damage) - *resist = damage; - } - else - *resist = 0; - - int32 RemainingDamage = damage - *resist; - - // Need remove expired auras after - bool existExpired = false; - - // absorb without mana cost - AuraList const& vSchoolAbsorb = GetAurasByType(SPELL_AURA_SCHOOL_ABSORB); - for (AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (!(mod->m_miscvalue & schoolMask)) - continue; - - // Max Amount can be absorbed by this aura - int32 currentAbsorb = mod->m_amount; - - // Found empty aura (impossible but..) - if (currentAbsorb <= 0) - { - existExpired = true; - continue; - } - - // currentAbsorb - damage can be absorbed by shield - // If need absorb less damage - if (RemainingDamage < currentAbsorb) - currentAbsorb = RemainingDamage; - - RemainingDamage -= currentAbsorb; - - // Reduce shield amount - mod->m_amount -= currentAbsorb; - if ((*i)->GetHolder()->DropAuraCharge()) - mod->m_amount = 0; - // Need remove it later - if (mod->m_amount <= 0) - existExpired = true; - } - - // Remove all expired absorb auras - if (existExpired) - { - for (AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();) - { - if ((*i)->GetModifier()->m_amount <= 0) - { - RemoveAurasDueToSpell((*i)->GetId(), nullptr, AURA_REMOVE_BY_SHIELD_BREAK); - i = vSchoolAbsorb.begin(); - } - else - ++i; - } - } - - // absorb by mana cost - AuraList const& vManaShield = GetAurasByType(SPELL_AURA_MANA_SHIELD); - for (AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next) - { - next = i; - ++next; - - // check damage school mask - if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) - continue; - - int32 currentAbsorb; - if (RemainingDamage >= (*i)->GetModifier()->m_amount) - currentAbsorb = (*i)->GetModifier()->m_amount; - else - currentAbsorb = RemainingDamage; - - if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()]) - { - if (Player *modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier, spell); - - int32 maxAbsorb = int32(GetPower(POWER_MANA) / manaMultiplier); - if (currentAbsorb > maxAbsorb) - currentAbsorb = maxAbsorb; - - int32 manaReduction = int32(currentAbsorb * manaMultiplier); - ApplyPowerMod(POWER_MANA, manaReduction, false); - } - - (*i)->GetModifier()->m_amount -= currentAbsorb; - if ((*i)->GetModifier()->m_amount <= 0) - { - RemoveAurasDueToSpell((*i)->GetId()); - next = vManaShield.begin(); - } - - RemainingDamage -= currentAbsorb; - } - - // only split damage if not damaging yourself - if (pCaster != this) - { - AuraList const& vSplitDamageFlat = GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT); - for (AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next) - { - next = i; - ++next; - - // check damage school mask - if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) - continue; - - // Damage can be splitted only if aura has an alive caster - Unit* reflectTo = (*i)->GetCaster(); - if (!reflectTo || reflectTo == this || !reflectTo->IsInWorld() || !reflectTo->isAlive()) - continue; - - int32 currentAbsorb; - if (RemainingDamage >= (*i)->GetModifier()->m_amount) - currentAbsorb = (*i)->GetModifier()->m_amount; - else - currentAbsorb = RemainingDamage; - - RemainingDamage -= currentAbsorb; - - uint32 splitted = currentAbsorb; - uint32 splitted_absorb = 0; - // Nostalrius : la reflection (bene de sacrifice par exemple) ne fait pas forcement des degats (si pala sous bouclier divin) - uint32 reflectAbsorb = 0, reflectResist = 0; - // On evite une boucle infinie - if (!reflectTo->HasAuraType(SPELL_AURA_SPLIT_DAMAGE_FLAT)) - reflectTo->CalculateDamageAbsorbAndResist(pCaster, schoolMask, DOT, splitted, &reflectAbsorb, &reflectResist, spellProto); - splitted -= (reflectAbsorb + reflectResist); - pCaster->DealDamageMods(reflectTo, splitted, &splitted_absorb); - pCaster->SendSpellNonMeleeDamageLog(reflectTo, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false); - CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL, reflectAbsorb, reflectResist); - pCaster->DealDamage(reflectTo, splitted, &cleanDamage, DOT, schoolMask, (*i)->GetSpellProto(), false); - } - - AuraList const& vSplitDamagePct = GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT); - for (AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next) - { - next = i; - ++next; - - // check damage school mask - if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) - continue; - - // Damage can be splitted only if aura has an alive caster - Unit *caster = (*i)->GetCaster(); - if (!caster || caster == this || !caster->IsInWorld() || !caster->isAlive()) - continue; - - uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f); - - RemainingDamage -= int32(splitted); - - uint32 split_absorb = 0; - pCaster->DealDamageMods(caster, splitted, &split_absorb); - - pCaster->SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false); - - CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL, 0, 0); - pCaster->DealDamage(caster, splitted, &cleanDamage, DOT, schoolMask, (*i)->GetSpellProto(), false); - } - } - - *absorb = damage - RemainingDamage - *resist; -} - -void Unit::CalculateAbsorbResistBlock(Unit *pCaster, SpellNonMeleeDamage *damageInfo, SpellEntry const* spellProto, WeaponAttackType attType, Spell* spell) -{ - bool blocked = false; - // Get blocked status - switch (spellProto->DmgClass) - { - // Melee and Ranged Spells - case SPELL_DAMAGE_CLASS_RANGED: - case SPELL_DAMAGE_CLASS_MELEE: - blocked = IsSpellBlocked(pCaster, spellProto, attType); - break; - default: - break; - } - - if (blocked) - { - damageInfo->blocked = GetShieldBlockValue(); - if (damageInfo->damage < damageInfo->blocked) - damageInfo->blocked = damageInfo->damage; - damageInfo->damage -= damageInfo->blocked; - } - - CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), SPELL_DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist, spellProto, spell); - damageInfo->damage -= damageInfo->absorb + damageInfo->resist; -} - -void Unit::AttackerStateUpdate(Unit *pVictim, WeaponAttackType attType, bool extra) -{ - if (hasUnitState(UNIT_STAT_CAN_NOT_REACT) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED)) - return; - - if (!pVictim->isAlive() || !isAlive()) - return; - - if (!extra && IsNonMeleeSpellCasted(false)) - return; - - uint32 hitInfo; - if (attType == BASE_ATTACK) - hitInfo = HITINFO_NORMALSWING2; - else if (attType == OFF_ATTACK) - hitInfo = HITINFO_LEFTSWING; - else - return; // ignore ranged case - - // Nostalrius: check ligne de vision - if (!IsWithinLOSInMap(pVictim)) - return; - - if (GetExtraAttacks() && !extra) - AddExtraAttackOnUpdate(); - - // melee attack spell casted at main hand attack only - if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL]) - { - m_currentSpells[CURRENT_MELEE_SPELL]->cast(); - Spell* spell = m_currentSpells[CURRENT_MELEE_SPELL]; - if (!spell || !spell->IsNextMeleeSwingSpell() || spell->isSuccessCast()) - return; - } - - CalcDamageInfo damageInfo; - CalculateMeleeDamage(pVictim, 0, &damageInfo, attType); - // Send log damage message to client - for (uint8 i = 0; i < m_weaponDamageCount[attType]; i++) - { - damageInfo.totalDamage -= damageInfo.subDamage[i].damage; - DealDamageMods(pVictim, damageInfo.subDamage[i].damage, &damageInfo.subDamage[i].absorb); - damageInfo.totalDamage += damageInfo.subDamage[i].damage; - } - - SendAttackStateUpdate(&damageInfo); - ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.totalDamage, damageInfo.attackType); - - DealMeleeDamage(&damageInfo, true); - - if (GetTypeId() == TYPEID_PLAYER) - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", - GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.totalDamage, damageInfo.totalAbsorb, damageInfo.blocked_amount, damageInfo.totalResist); - else - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", - GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.totalDamage, damageInfo.totalAbsorb, damageInfo.blocked_amount, damageInfo.totalResist); - - // if damage pVictim call AI reaction - pVictim->AttackedBy(this); - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK); -} - -MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const -{ - // This is only wrapper - - // Miss chance based on melee - float miss_chance = MeleeMissChanceCalc(pVictim, attType); - - // Critical hit chance - float crit_chance = GetUnitCriticalChance(attType, pVictim); - - // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case) - float dodge_chance = pVictim->GetUnitDodgeChance(); - float block_chance = pVictim->GetUnitBlockChance(); - float parry_chance = pVictim->GetUnitParryChance(); - - // Useful if want to specify crit & miss chances for melee, else it could be removed - //DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance, crit_chance, dodge_chance, parry_chance, block_chance); - - return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance * 100), int32(miss_chance * 100), int32(dodge_chance * 100), int32(parry_chance * 100), int32(block_chance * 100), false); -} - -MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance, bool SpellCasted) const -{ - // Nostalrius : cheat. - if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_ALWAYS_CRIT)) - return MELEE_HIT_CRIT; - - if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode()) - return MELEE_HIT_EVADE; - - int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim); - int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this); - - int32 attackerWeaponSkill = GetWeaponSkillValue(attType, pVictim); - int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this); - - // bonus from skills is 0.04% - int32 skillBonus = 4 * (attackerWeaponSkill - victimMaxSkillValueForLevel); - int32 sum = 0, tmp = 0; - int32 roll = urand(0, 10000); - - //DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus); - //DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d", roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance); - - tmp = miss_chance; - - if (tmp > 0 && roll < (sum += tmp)) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: MISS"); - return MELEE_HIT_MISS; - } - - // always crit against a sitting target (except 0 crit chance) - if (pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState()) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRIT (sitting victim)"); - return MELEE_HIT_CRIT; - } - - bool from_behind = !pVictim->HasInArc(M_PI_F, this); - - if (from_behind) - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: attack came from behind."); - - // Dodge chance - - // only players can't dodge if attacker is behind - if (pVictim->GetTypeId() != TYPEID_PLAYER || !from_behind) - { - tmp = dodge_chance; - if ((tmp > 0) // check if unit _can_ dodge - && ((tmp -= skillBonus) > 0) - && roll < (sum += tmp)) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum - tmp, sum); - return MELEE_HIT_DODGE; - } - } - - // parry chances - // check if attack comes from behind, nobody can parry or block if attacker is behind - if (!from_behind) - { - if (parry_chance > 0 && (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY))) - { - parry_chance -= skillBonus; - - if (parry_chance > 0 && // check if unit _can_ parry - (roll < (sum += parry_chance))) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum - parry_chance, sum); - return MELEE_HIT_PARRY; - } - } - } - - // Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon) - if (attType != RANGED_ATTACK && !SpellCasted && - (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->IsPet()) && - pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->IsPet() && !((Creature*)pVictim)->IsTotem()) - { - // cap possible value (with bonuses > max skill) - int32 skill = attackerWeaponSkill; - int32 maxskill = attackerMaxSkillValueForLevel; - skill = (skill > maxskill) ? maxskill : skill; - - // (Youfie) Le +skill avant BC ne permet pas de réduire la fréquence des glancing blows une fois qu'il est égal au niveau du joueur*5 - if (attackerWeaponSkill > maxskill) - attackerWeaponSkill = maxskill; - - // (Youfie) Chance de glance en Vanilla (inchangée par le +skill au delà de maxskill, cf. au dessus) : - tmp = (10 + ((victimDefenseSkill - attackerWeaponSkill) * 2)) * 100; - tmp = tmp > 4000 ? 4000 : tmp; - if (tmp < 0) - tmp = 0; - // sLog.outString("tmp = %i, Skill = %i, Max Skill = %i", tmp, attackerWeaponSkill, attackerMaxSkillValueForLevel); //Pour tests & débug via la console - - if (roll < (sum += tmp)) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum - 4000, sum); - return MELEE_HIT_GLANCING; - } - } - - // block chances - // check if attack comes from behind, nobody can parry or block if attacker is behind - if (!from_behind) - { - if ((pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK)) - && !(GetTypeId() == TYPEID_UNIT && GetMeleeDamageSchoolMask() != SPELL_SCHOOL_MASK_NORMAL)) // can't block elemental melee attacks from mobs - { - tmp = block_chance; - if ((tmp > 0) // check if unit _can_ block - && ((tmp -= skillBonus) > 0) - && (roll < (sum += tmp))) - { - // Critical chance - tmp = crit_chance; - if (GetTypeId() == TYPEID_PLAYER && SpellCasted && tmp > 0) - { - if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || - (pVictim->IsPlayer() && pVictim->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) - tmp = 0; - if (roll_chance_i(tmp / 100)) - { - DEBUG_LOG("RollMeleeOutcomeAgainst: BLOCKED CRIT"); - return MELEE_HIT_BLOCK_CRIT; - } - } - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum - tmp, sum); - return MELEE_HIT_BLOCK; - } - } - } - - // Critical chance - tmp = crit_chance; - - if (tmp > 0 && roll < (sum += tmp)) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum - tmp, sum); - return MELEE_HIT_CRIT; - } - - if ((GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->IsPet()) && - !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) && - !SpellCasted /*Only autoattack can be crashing blow*/) - { - // mobs can score crushing blows if they're 3 or more levels above victim - // or when their weapon skill is 15 or more above victim's defense skill - tmp = victimDefenseSkill; - int32 tmpmax = victimMaxSkillValueForLevel; - // having defense above your maximum (from items, talents etc.) has no effect - tmp = tmp > tmpmax ? tmpmax : tmp; - // tmp = mob's level * 5 - player's current defense skill - tmp = attackerMaxSkillValueForLevel - tmp; - if (tmp >= 15) - { - // add 2% chance per lacking skill point, min. is 15% - tmp = tmp * 200 - 1500; - if (roll < (sum += tmp)) - { - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum - tmp, sum); - return MELEE_HIT_CRUSHING; - } - } - } - - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: NORMAL"); - return MELEE_HIT_NORMAL; -} - -uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, uint8 index) -{ - float min_damage, max_damage; - - if (GetTypeId() != TYPEID_PLAYER && index != 0) - return 0; - - if ((normalized || index != 0) && GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->CalculateMinMaxDamage(attType, normalized, min_damage, max_damage, index); - else - { - switch (attType) - { - case RANGED_ATTACK: - min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE); - max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE); - break; - case BASE_ATTACK: - min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE); - max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE); - break; - case OFF_ATTACK: - min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE); - max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE); - break; - // Just for good manner - default: - min_damage = 0.0f; - max_damage = 0.0f; - break; - } - } - - if (min_damage > max_damage) - std::swap(min_damage, max_damage); - - if (max_damage == 0.0f) - max_damage = 5.0f; - - return urand((uint32)min_damage, (uint32)max_damage); -} - -float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const -{ - // Fix Nostalrius. La formule de MaNGOSZero est BC. - uint32 spellLevel = spellProto->spellLevel; - if (spellLevel <= 0 || spellLevel > 20) - return 1.0f; - return 1 - ((20.0f - spellLevel) * 0.0375f); - - /* - float LvlPenalty = 0.0f; - - if(spellLevel < 20) - LvlPenalty = 20.0f - spellLevel * 3.75f; - float LvlFactor = (float(spellLevel) + 6.0f) / float(getLevel()); - if(LvlFactor > 1.0f) - LvlFactor = 1.0f; - - return (100.0f - LvlPenalty) * LvlFactor / 100.0f; - */ -} - -void Unit::SendMeleeAttackStart(Unit* pVictim) -{ - WorldPacket data(SMSG_ATTACKSTART, 8 + 8); - data << GetObjectGuid(); - data << pVictim->GetObjectGuid(); - - SendObjectMessageToSet(&data, true); - DEBUG_LOG("WORLD: Sent SMSG_ATTACKSTART"); -} - -void Unit::SendMeleeAttackStop(Unit* victim) -{ - if (!victim) - return; - - WorldPacket data(SMSG_ATTACKSTOP, (4 + 16)); // we guess size - data << GetPackGUID(); - data << victim->GetPackGUID(); // can be 0x00... - data << uint32(0); // can be 0x1 - SendObjectMessageToSet(&data, true); - DETAIL_FILTER_LOG(LOG_FILTER_COMBAT, "%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), victim->GetGUIDLow()); - - /*if(victim->GetTypeId() == TYPEID_UNIT) - ((Creature*)victim)->AI().EnterEvadeMode(this);*/ -} - -bool Unit::IsSpellBlocked(Unit *pCaster, SpellEntry const *spellEntry, WeaponAttackType attackType) -{ - if (!HasInArc(M_PI_F, pCaster)) - return false; - - if (spellEntry) - { - // Some spells cannot be blocked - if (spellEntry->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK) - return false; - } - - // Check creatures flags_extra for disable block - if (GetTypeId() == TYPEID_UNIT) - { - if (((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) - return false; - } - - float blockChance = GetUnitBlockChance(); - blockChance += (int32(pCaster->GetWeaponSkillValue(attackType)) - int32(GetMaxSkillValueForLevel())) * 0.04f; - - if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || - (pCaster->IsPlayer() && pCaster->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) - blockChance = 0; - return roll_chance_f(blockChance); -} - -// Melee based spells can be miss, parry or dodge on this step -// Crit or block - determined on damage calculation phase! (and can be both in some time) -float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell, Spell* spellPtr) -{ - // Calculate hit chance (more correct for chance mod) - float hitChance = 0.0f; - - // PvP - PvE melee chances - if (pVictim->GetTypeId() == TYPEID_PLAYER) - hitChance = 95.0f + skillDiff * 0.04f; - else if (skillDiff < -10) - hitChance = 93.0f + (skillDiff + 10) * 0.4f; // 7% base chance to miss for big skill diff (%6 in 3.x) - else - hitChance = 95.0f + skillDiff * 0.1f; - - // Hit chance depends from victim auras - if (attType == RANGED_ATTACK) - hitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); - else - hitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); - - // Spellmod from SPELLMOD_RESIST_MISS_CHANCE - if (Player *modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, hitChance, spellPtr); - - // Miss = 100 - hit - float missChance = 100.0f - hitChance; - - // Bonuses from attacker aura and ratings - if (attType == RANGED_ATTACK) - missChance -= m_modRangedHitChance; - else - missChance -= m_modMeleeHitChance; - - // Limit miss chance from 0 to 60% - if (missChance < 0.0f) - return 0.0f; - if (missChance > 60.0f) - return 60.0f; - return missChance; -} - -// Melee based spells hit result calculations -SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell, Spell* spellPtr) -{ - WeaponAttackType attType = BASE_ATTACK; - - if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED) - attType = RANGED_ATTACK; - - // Warrior spell Execute (5308) should never dodge, miss, resist ... Only the trigger can (20647) - if (spell->IsFitToFamily() && spell->Id != 20647) - return SPELL_MISS_NONE; - - // bonus from skills is 0.04% per skill Diff - int32 attackerWeaponSkill = (spell->EquippedItemClass == ITEM_CLASS_WEAPON) ? int32(GetWeaponSkillValue(attType, pVictim)) : GetMaxSkillValueForLevel(); - int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this)); - int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this)); - - uint32 roll = urand(0, 10000); - - uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell, spellPtr) * 100.0f); - // Roll miss - uint32 tmp = spell->AttributesEx3 & SPELL_ATTR_EX3_CANT_MISS ? 0 : missChance; - if (roll < tmp) - return SPELL_MISS_MISS; - - // Chance resist mechanic (select max value from every mechanic spell effect) - int32 resist_mech = 0; - // Get effects mechanic and chance - if (spell->Mechanic) - resist_mech = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, spell->Mechanic) * 100; - // Roll chance - tmp += resist_mech; - if (roll < tmp) - return SPELL_MISS_RESIST; - - bool canDodge = true; - bool canParry = true; - - // Same spells cannot be parry/dodge - if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK) - return SPELL_MISS_NONE; - - // Ranged attack cannot be parry/dodge - if (attType == RANGED_ATTACK) - return SPELL_MISS_NONE; - - bool from_behind = !pVictim->HasInArc(M_PI_F, this); - - // Check for attack from behind - if (from_behind) - { - // Can`t dodge from behind in PvP (but its possible in PvE) - if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER) - canDodge = false; - // Can`t parry - canParry = false; - } - // Check creatures flags_extra for disable parry - if (pVictim->GetTypeId() == TYPEID_UNIT) - { - uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra; - if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY) - canParry = false; - } - - // Check if the player can parry - if (pVictim->GetTypeId() == TYPEID_PLAYER) - { - if (!((Player*)pVictim)->CanParry()) - canParry = false; - } - - if (canDodge) - { - // Roll dodge - int32 dodgeChance = int32(pVictim->GetUnitDodgeChance() * 100.0f) - skillDiff * 4; - - if (dodgeChance < 0) - dodgeChance = 0; - - - tmp += dodgeChance; - if (roll < tmp) - return SPELL_MISS_DODGE; - } - - if (canParry) - { - // Roll parry - int32 parryChance = int32(pVictim->GetUnitParryChance() * 100.0f) - skillDiff * 4; - // Can`t parry from behind - if (parryChance < 0) - parryChance = 0; - - tmp += parryChance; - if (roll < tmp) - return SPELL_MISS_PARRY; - } - - return SPELL_MISS_NONE; -} - -SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell, Spell* spellPtr) -{ - // Can`t miss on dead target (on skinning for example) - if (!pVictim->isAlive()) - return SPELL_MISS_NONE; - - int32 hitChance = MagicSpellHitChance(pVictim, spell, spellPtr); - int32 missChance = 10000 - hitChance; - int32 rand = irand(0, 10000); - - if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || - (pVictim->IsPlayer() && pVictim->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) - missChance = 0; - - if (rand < missChance) - return SPELL_MISS_RESIST; - - return SPELL_MISS_NONE; -} - -float Unit::GetSpellResistChance(Unit* victim, uint32 schoolMask, bool innateResists) const -{ - // Get base victim resistance for school - float resistModHitChance = victim->GetResistance(GetFirstSchoolInMask(SpellSchoolMask(schoolMask))); - // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura - resistModHitChance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask); - // No "negative" resist chance. Applied before innate resists. - if (resistModHitChance < 0) - resistModHitChance = 0.0f; - - // Computing innate resists, resistance bonus when attacking a creature higher level. Not affected by modifiers. - if (innateResists && victim->GetTypeId() == TYPEID_UNIT) - { - int32 leveldiff = int32(victim->GetLevelForTarget(this)) - int32(GetLevelForTarget(victim)); - resistModHitChance += int32((8.0f * leveldiff) * getLevel() / 63.0f); - } - resistModHitChance *= (float)(0.15f / getLevel()); - - if (resistModHitChance < 0.0f) - resistModHitChance = 0.0f; - if (resistModHitChance > 0.75f) - resistModHitChance = 0.75f; - - return resistModHitChance; -} - -int32 Unit::MagicSpellHitChance(Unit *pVictim, SpellEntry const *spell, Spell* spellPtr) -{ - if (spell->AttributesEx3 & SPELL_ATTR_EX3_CANT_MISS) - return 10000; - - SpellSchoolMask schoolMask = GetSpellSchoolMask(spell); - // PvP - PvE spell misschances per leveldif > 2 - int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11; - int32 leveldif = int32(pVictim->GetLevelForTarget(this)) - int32(GetLevelForTarget(pVictim)); - - // Base hit chance from attacker and victim levels - float modHitChance; - if (leveldif < 3) - modHitChance = 96 - leveldif; - else - modHitChance = 94 - (leveldif - 2) * lchance; - - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "%s [%u] : Binary [%s]. Base hit chance %f, level diff: %d", spell->SpellName[2], spell->Id, spell->IsBinary() ? "YES" : "NO", modHitChance, leveldif); - - // Spellmod from SPELLMOD_RESIST_MISS_CHANCE - if (Player *modOwner = GetSpellModOwner()) - { - modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance, spellPtr); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELLMOD_RESIST_MISS_CHANCE : %f", modHitChance); - } - // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras - modHitChance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE (+ %i) : %f", pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask), modHitChance); - - // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura - if (IsAreaOfEffectSpell(spell)) - { - modHitChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_AOE_AVOIDANCE (- %i) : %f", pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE), modHitChance); - } - - // Chance resist mechanic - int32 resist_mech = 0; - // Get effects mechanic and chance - if (spell->Mechanic) - resist_mech = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, spell->Mechanic); - // Apply mod - modHitChance -= resist_mech; - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_MECHANIC_RESISTANCE (- %i) : %f", resist_mech, modHitChance); - - // Chance resist debuff - modHitChance -= pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_DEBUFF_RESISTANCE (- %i) : %f", pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)), modHitChance); - - // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings - modHitChance += int32(m_modSpellHitChance); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_SPELL_HIT_CHANCE (+ %i) : %f", int32(m_modSpellHitChance), modHitChance); - - // Nostalrius: sorts binaires. - if (spell->IsBinary()) - { - // Get base victim resistance for school - float resistModHitChance = GetSpellResistChance(pVictim, schoolMask, false); - modHitChance *= (1 - resistModHitChance); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "x %f : HitChance = %f", (1 - resistModHitChance), modHitChance); - } - - int32 HitChance = modHitChance * 100; - if (HitChance < 100) HitChance = 100; - if (HitChance > 9900) HitChance = 9900; - return HitChance; -} -// Calculate spell hit result can be: -// Every spell can: Evade/Immune/Reflect/Sucesful hit -// For melee based spells: -// Miss -// Dodge -// Parry -// For spells -// Resist -SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, SpellEffectIndex effIndex, bool CanReflect, Spell* spellPtr) -{ - // Return evade for units in evade mode - if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode()) - return SPELL_MISS_EVADE; - - // Check for immune (use charges) - if (pVictim != this && pVictim->IsImmuneToSpell(spell, pVictim == this)) - return SPELL_MISS_IMMUNE; - - // All positive spells can`t miss - // TODO: client not show miss log for this spells - so need find info for this in dbc and use it! - if (IsPositiveSpell(spell->Id, this, pVictim) || IsPositiveEffect(spell, effIndex)) - return SPELL_MISS_NONE; - - // Check for immune (use charges) - SpellSchoolMask schoolMask; - if (spellPtr) - schoolMask = spellPtr->m_spellSchoolMask; - else - schoolMask = GetSpellSchoolMask(spell); - - if (pVictim != this && pVictim->IsImmuneToDamage(schoolMask)) - return SPELL_MISS_IMMUNE; - - // Try victim reflect spell - if (CanReflect) - { - int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS); - Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL); - for (Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i) - if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell)) - reflectchance += (*i)->GetModifier()->m_amount; - if (reflectchance > 0 && roll_chance_i(reflectchance)) - { - // Start triggers for remove charges if need (trigger only for victim, and mark as active spell) - ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell); - return SPELL_MISS_REFLECT; - } - } - - switch (spell->DmgClass) - { - case SPELL_DAMAGE_CLASS_NONE: - return SPELL_MISS_NONE; - case SPELL_DAMAGE_CLASS_MAGIC: - return MagicSpellHitResult(pVictim, spell, spellPtr); - case SPELL_DAMAGE_CLASS_MELEE: - case SPELL_DAMAGE_CLASS_RANGED: - return MeleeSpellHitResult(pVictim, spell, spellPtr); - } - return SPELL_MISS_NONE; -} - -bool Unit::IsAuraResist(SpellEntry const* spell) -{ - // Chance resist mechanic (select max value from every mechanic spell effect) - int32 resist_mech = 0; - int32 rand = urand(0, 99); - // Get effects mechanic and chance => Aura side (Nostalrius) - for (int eff = 0; eff < MAX_EFFECT_INDEX; ++eff) - { - if (spell->Effect[eff] != SPELL_EFFECT_APPLY_AURA) - continue; - int32 effect_mech = spell->EffectMechanic[eff]; - if (effect_mech && effect_mech != spell->Mechanic) - { - int32 temp = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "Spell %u Eff %u: MechanicResistChance %i", spell->Id, eff, temp); - if (resist_mech < temp) - resist_mech = temp; - } - } - return (rand < resist_mech); -} - -float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const -{ - if (!pVictim) - return 0.0f; - - // Base misschance 5% - float missChance = 5.0f; - - // DualWield - white damage has additional 19% miss penalty - if (haveOffhandWeapon() && attType != RANGED_ATTACK) - { - bool isNormal = false; - for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) - { - if (m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL)) - { - isNormal = true; - break; - } - } - if (!isNormal && !m_currentSpells[CURRENT_MELEE_SPELL]) - missChance += 19.0f; - } - - int32 skillDiff = int32(GetWeaponSkillValue(attType, pVictim)) - int32(pVictim->GetDefenseSkillValue(this)); - - // PvP - PvE melee chances - if (pVictim->GetTypeId() == TYPEID_PLAYER) - missChance -= skillDiff * 0.04f; - else if (skillDiff < -10) - missChance -= (skillDiff + 10) * 0.4f - 2.0f; // 7% base chance to miss for big skill diff (%6 in 3.x) - else - missChance -= skillDiff * 0.1f; - - // Hit chance bonus from attacker based on ratings and auras - if (attType == RANGED_ATTACK) - missChance -= m_modRangedHitChance; - else - missChance -= m_modMeleeHitChance; - - // Modify miss chance by victim auras - if (attType == RANGED_ATTACK) - missChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); - else - missChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); - - // Limit miss chance from 0 to 60% - if (missChance < 0.0f) - return 0.0f; - if (missChance > 60.0f) - return 60.0f; - - return missChance; -} - -uint32 Unit::GetDefenseSkillValue(Unit const* target) const -{ - if (GetTypeId() == TYPEID_PLAYER) - { - // in PvP use full skill instead current skill value - uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER) - ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE) - : ((Player*)this)->GetSkillValue(SKILL_DEFENSE); - return value; - } - else - return GetUnitMeleeSkill(target); -} - -float Unit::GetUnitDodgeChance() const -{ - if (IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) - return 0.0f; - if (GetTypeId() == TYPEID_PLAYER) - return GetFloatValue(PLAYER_DODGE_PERCENTAGE); - else - { - if (((Creature const*)this)->IsTotem()) - return 0.0f; - else - { - float dodge = 5.0f; - dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT); - return dodge > 0.0f ? dodge : 0.0f; - } - } -} - -float Unit::GetUnitParryChance() const -{ - if (IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) - return 0.0f; - - float chance = 0.0f; - - if (GetTypeId() == TYPEID_PLAYER) - { - Player const* player = (Player const*)this; - if (player->CanParry()) - { - Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK, true, true); - if (!tmpitem) - tmpitem = player->GetWeaponForAttack(OFF_ATTACK, true, true); - - if (tmpitem) - chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE); - } - } - else if (GetTypeId() == TYPEID_UNIT) - { - if (GetCreatureType() == CREATURE_TYPE_HUMANOID) - { - chance = 5.0f; - chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT); - } - } - - return chance > 0.0f ? chance : 0.0f; -} - -float Unit::GetUnitBlockChance() const -{ - if (IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) - return 0.0f; - - if (GetTypeId() == TYPEID_PLAYER) - { - Player const* player = (Player const*)this; - if (player->CanBlock() && player->CanUseEquippedWeapon(OFF_ATTACK)) - { - Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); - if (tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block) - return GetFloatValue(PLAYER_BLOCK_PERCENTAGE); - } - // is player but has no block ability or no not broken shield equipped - return 0.0f; - } - else - { - if (((Creature const*)this)->IsTotem()) - return 0.0f; - else - { - float block = 5.0f; - block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT); - return block > 0.0f ? block : 0.0f; - } - } -} - -float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const -{ - float crit; - - if (GetTypeId() == TYPEID_PLAYER) - { - switch (attackType) - { - case OFF_ATTACK: - case BASE_ATTACK: - crit = GetFloatValue(PLAYER_CRIT_PERCENTAGE); - break; - case RANGED_ATTACK: - crit = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE); - break; - // Just for good manner - default: - crit = 0.0f; - break; - } - } - else - { - crit = 5.0f; - crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT); - } - - // flat aura mods - if (attackType == RANGED_ATTACK) - crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE); - else - crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); - - // Apply crit chance from defence skill - crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f; - - if (crit < 0.0f) - crit = 0.0f; - return crit; -} - -uint32 Unit::GetWeaponSkillValue(WeaponAttackType attType, Unit const* target) const -{ - uint32 value = 0; - if (GetTypeId() == TYPEID_PLAYER) - { - Item* item = ((Player*)this)->GetWeaponForAttack(attType, true, true); - - // feral or unarmed skill only for base attack - if (attType != BASE_ATTACK && !item) - return 0; - - if (IsInFeralForm()) - return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact - - // weapon skill or (unarmed for base attack) - uint32 skill = item ? item->GetSkill() : SKILL_UNARMED; - -// Daemon: pas en preBC ! -// // in PvP use full skill instead current skill value -// value = (target && target->GetTypeId() == TYPEID_PLAYER) -// ? ((Player*)this)->GetMaxSkillValue(skill) -// : ((Player*)this)->GetSkillValue(skill); - value = ToPlayer()->GetSkillValue(skill); - } - else - value = GetUnitMeleeSkill(target); - return value; -} - -void Unit::_UpdateSpells(uint32 time) -{ - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) - _UpdateAutoRepeatSpell(); - - // remove finished spells from current pointers - for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) - { - if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED) - { - m_currentSpells[i]->SetReferencedFromCurrent(false); - m_currentSpells[i] = nullptr; // remove pointer - } - } - - // update auras - // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras - for (m_spellAuraHoldersUpdateIterator = m_spellAuraHolders.begin(); m_spellAuraHoldersUpdateIterator != m_spellAuraHolders.end();) - { - SpellAuraHolder* i_holder = m_spellAuraHoldersUpdateIterator->second; - ++m_spellAuraHoldersUpdateIterator; // need shift to next for allow update if need into aura update - i_holder->UpdateHolder(time); - } - - // remove expired auras - for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) - { - SpellAuraHolder *holder = iter->second; - - if (!(holder->IsPermanent() || holder->IsPassive()) && holder->GetAuraDuration() == 0) - { - RemoveSpellAuraHolder(holder, AURA_REMOVE_BY_EXPIRE); - iter = m_spellAuraHolders.begin(); - } - else - ++iter; - } - - if (!m_gameObj.empty()) - { - GameObjectList::iterator ite1, dnext1; - for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1) - { - dnext1 = ite1; - //(*i)->Update( difftime ); - if (!(*ite1)->isSpawned()) - { - (*ite1)->SetOwnerGuid(ObjectGuid()); - (*ite1)->SetRespawnTime(0); - (*ite1)->Delete(); - dnext1 = m_gameObj.erase(ite1); - } - else - ++dnext1; - } - } -} - -void Unit::_UpdateAutoRepeatSpell() -{ - //check "realtime" interrupts - if ((GetTypeId() == TYPEID_PLAYER && ((Player*)this)->IsMoving()) || IsNonMeleeSpellCasted(false, false, true)) - { - // cancel wand shoot - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Category == 351) - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - m_AutoRepeatFirstCast = true; - return; - } - - //apply delay - if (m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500) - setAttackTimer(RANGED_ATTACK, 500); - m_AutoRepeatFirstCast = false; - - //castroutine - if (isAttackReady(RANGED_ATTACK)) - { - // Check if able to cast - // We need to update pointers before calling CheckCast ! - m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->UpdatePointers(); - SpellCastResult result = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true); - if (result == SPELL_FAILED_MOVING) // Just delay it if moving - return; - - if (result != SPELL_CAST_OK) - { - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - return; - } - - // we want to shoot - Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true); - spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets)); - - // all went good, reset attack - resetAttackTimer(RANGED_ATTACK); - SetStandState(UNIT_STAND_STATE_STAND); - } -} - -void Unit::SetCurrentCastedSpell(Spell * pSpell) -{ - MANGOS_ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells - - CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer(); - - if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self - - // break same type spell if it is not delayed - InterruptSpell(CSpellType, false); - - // special breakage effects: - switch (CSpellType) - { - case CURRENT_GENERIC_SPELL: - { - // generic spells always break channeled not delayed spells - InterruptSpell(CURRENT_CHANNELED_SPELL, false); - - // autorepeat breaking - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) - { - // break autorepeat if not Auto Shot - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Category == 351) - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - m_AutoRepeatFirstCast = true; - } - } - break; - - case CURRENT_CHANNELED_SPELL: - { - // channel spells always break generic non-delayed and any channeled spells - InterruptSpell(CURRENT_GENERIC_SPELL, false); - InterruptSpell(CURRENT_CHANNELED_SPELL); - - // it also does break autorepeat if not Auto Shot - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && - m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Category == 351) - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - } - break; - - case CURRENT_AUTOREPEAT_SPELL: - { - // only Auto Shoot does not break anything - if (pSpell->m_spellInfo->Category == 351) - { - // generic autorepeats break generic non-delayed and channeled non-delayed spells - InterruptSpell(CURRENT_GENERIC_SPELL, false); - InterruptSpell(CURRENT_CHANNELED_SPELL, false); - } - // special action: set first cast flag - m_AutoRepeatFirstCast = true; - } - break; - - default: - { - // other spell types don't break anything now - } break; - } - - // current spell (if it is still here) may be safely deleted now - if (m_currentSpells[CSpellType]) - m_currentSpells[CSpellType]->SetReferencedFromCurrent(false); - - // set new current spell - m_currentSpells[CSpellType] = pSpell; - pSpell->SetReferencedFromCurrent(true); - - pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]); -} - -void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed) -{ - MANGOS_ASSERT(spellType < CURRENT_MAX_SPELL); - - if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED)) - { - // send autorepeat cancel message for autorepeat spells - if (spellType == CURRENT_AUTOREPEAT_SPELL) - { - if (GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->SendAutoRepeatCancel(); - } - - if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED) - m_currentSpells[spellType]->cancel(); - - // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt) - if (m_currentSpells[spellType]) - { - m_currentSpells[spellType]->SetReferencedFromCurrent(false); - m_currentSpells[spellType] = nullptr; - } - } -} - -void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/) -{ - Spell* spell = m_currentSpells[spellType]; - if (!spell) - return; - - spell->finish(ok); - - if (spellType == CURRENT_CHANNELED_SPELL) - spell->SendChannelUpdate(0); -} - - -bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const -{ - // We don't do loop here to explicitly show that melee spell is excluded. - // Maybe later some special spells will be excluded too. - - // generic spells are casted when they are not finished and not delayed - if (m_currentSpells[CURRENT_GENERIC_SPELL] && - (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && - (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED)) - return (true); - - // channeled spells may be delayed, but they are still considered casted - else if (!skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] && - (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)) - return (true); - - // autorepeat spells may be finished or delayed, but they are still considered casted - else if (!skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) - return (true); - - return (false); -} - -bool Unit::IsNoMovementSpellCasted() const -{ - if (m_currentSpells[CURRENT_GENERIC_SPELL] && - (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && - m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED && - m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) - return (true); - else if (m_currentSpells[CURRENT_CHANNELED_SPELL] && - m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED && - m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) - return (true); - // don't need to check for AUTOREPEAT_SPELL - - return (false); -} - -void Unit::InterruptSpellsWithInterruptFlags(uint32 flags, uint32 except) -{ - for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) - if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) - if (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) - if (!spell->IsNextMeleeSwingSpell() && !spell->IsAutoRepeat() && !spell->IsTriggered() && (spell->m_spellInfo->InterruptFlags & flags) && spell->m_spellInfo->Id != except) - InterruptSpell(CurrentSpellTypes(i)); -} - - -void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id) -{ - // generic spells are interrupted if they are not finished or delayed - if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id == spell_id)) - InterruptSpell(CURRENT_GENERIC_SPELL, withDelayed); - - // autorepeat spells are interrupted if they are not finished or delayed - if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == spell_id)) - InterruptSpell(CURRENT_AUTOREPEAT_SPELL, withDelayed); - - // channeled spells are interrupted if they are not finished, even if they are delayed - if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id == spell_id)) - InterruptSpell(CURRENT_CHANNELED_SPELL, true); -} - - -Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const -{ - 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 nullptr; -} - -void Unit::SetInFront(Unit const* target) -{ - SetOrientation(GetAngle(target)); -} - -void Unit::SetFacingTo(float ori) -{ - m_movementInfo.ChangeOrientation(ori); - - Movement::MoveSplineInit init(*this, "SetFacingTo"); - init.SetFacing(ori); - init.Launch(); -} - -void Unit::SetFacingToObject(WorldObject* pObject) -{ - // never face when already moving - if (!IsStopped()) - return; - - // TODO: figure out under what conditions creature will move towards object instead of facing it where it currently is. - SetFacingTo(GetAngle(pObject)); -} - -bool Unit::isInAccessablePlaceFor(Creature const* c) const -{ - if (IsInWater()) - return c->CanSwim(); - else - return c->CanWalk() || c->CanFly(); -} - -bool Unit::IsInWater() const -{ - return GetTerrain()->IsInWater(GetPositionX(), GetPositionY(), GetPositionZ()); -} - -bool Unit::IsUnderWater() const -{ - return GetTerrain()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ()); -} - -void Unit::DeMorph() -{ - SetDisplayId(GetNativeDisplayId()); -} - -int32 Unit::GetTotalAuraModifier(AuraType auratype) const -{ - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - // Exception for stealth detection, remove hidden trap detection (id:2836) from stealth modifier (should not be taken into account) - // If it was the cast, rogue will see others rogue at 40 meters - if ((*i)->GetId() != 2836) - modifier += (*i)->GetModifier()->m_amount; - } - - - return modifier; -} - -float Unit::GetTotalAuraMultiplier(AuraType auratype) const -{ - float multiplier = 1.0f; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - multiplier *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; - - return multiplier; -} - -int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const -{ - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - if ((*i)->GetModifier()->m_amount > modifier) - modifier = (*i)->GetModifier()->m_amount; - - return modifier; -} - -int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const -{ - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - if ((*i)->GetModifier()->m_amount < modifier) - modifier = (*i)->GetModifier()->m_amount; - - return modifier; -} - -int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const -{ - if (!misc_mask) - return 0; - - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue & misc_mask) - modifier += mod->m_amount; - } - return modifier; -} - -float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const -{ - if (!misc_mask) - return 1.0f; - - float multiplier = 1.0f; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue & misc_mask) - multiplier *= (100.0f + mod->m_amount) / 100.0f; - } - return multiplier; -} - -int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const -{ - if (!misc_mask) - return 0; - - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier) - modifier = mod->m_amount; - } - - return modifier; -} - -int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const -{ - if (!misc_mask) - return 0; - - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier) - modifier = mod->m_amount; - } - - return modifier; -} - -int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const -{ - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue == misc_value) - modifier += mod->m_amount; - } - return modifier; -} - -float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const -{ - float multiplier = 1.0f; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue == misc_value) - multiplier *= (100.0f + mod->m_amount) / 100.0f; - } - return multiplier; -} - -int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const -{ - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue == misc_value && mod->m_amount > modifier) - modifier = mod->m_amount; - } - - return modifier; -} - -int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const -{ - int32 modifier = 0; - - AuraList const& mTotalAuraList = GetAurasByType(auratype); - for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - { - Modifier* mod = (*i)->GetModifier(); - if (mod->m_miscvalue == misc_value && mod->m_amount < modifier) - modifier = mod->m_amount; - } - - return modifier; -} - -bool Unit::AddSpellAuraHolder(SpellAuraHolder *holder) -{ - SpellEntry const* aurSpellInfo = holder->GetSpellProto(); - - // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load) - if (!isAlive() && !IsDeathPersistentSpell(aurSpellInfo) && - !IsDeathOnlySpell(aurSpellInfo) && - (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading())) - { - delete holder; - return false; - } - - if (holder->GetTarget() != this) - { - sLog.outError("Holder (spell %u) add to spell aura holder list of %s (lowguid: %u) but spell aura holder target is %s (lowguid: %u)", - holder->GetId(), (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), - (holder->GetTarget()->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), holder->GetTarget()->GetGUIDLow()); - delete holder; - return false; - } - - // passive and persistent auras can stack with themselves any number of times - if ((!holder->IsPassive() && !holder->IsPersistent()) || holder->IsAreaAura()) - { - SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(aurSpellInfo->Id); - - // take out same spell - for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second; ++iter) - { - SpellAuraHolder *foundHolder = iter->second; - if ((foundHolder->GetCasterGuid() == holder->GetCasterGuid() && foundHolder->GetCastItemGuid() == holder->GetCastItemGuid()) - || aurSpellInfo->Custom & SPELL_CUSTOM_ALLOW_STACK_BETWEEN_CASTER) - { - if (foundHolder->CanBeRefreshedBy(holder)) - { - Unit* pAuraCaster = foundHolder->GetCaster(); - if (pAuraCaster) - { - foundHolder->Refresh(pAuraCaster, this, holder); - delete holder; - return false; - } - } - - // Aura can stack on self -> Stack it; - if (aurSpellInfo->StackAmount) - { - // can be created with >1 stack by some spell mods - foundHolder->ModStackAmount(holder->GetStackAmount()); - delete holder; - return false; - } - - // Check for coexisting Weapon-proced Auras - if (holder->IsWeaponBuffCoexistableWith(foundHolder)) - continue; - - // can be only single - RemoveSpellAuraHolder(foundHolder, AURA_REMOVE_BY_STACK); - break; - } - - // Skip channeled spells (Arcane missile, ...) so two casters can channel at the same time - if (IsChanneledSpell(aurSpellInfo)) - continue; - bool stop = false; - - for (int32 i = 0; i < MAX_EFFECT_INDEX && !stop; ++i) - { - // no need to check non stacking auras that weren't/won't be applied on this target - if (!foundHolder->m_auras[i] || !holder->m_auras[i]) - continue; - - // Croise - if (aurSpellInfo->Id == 20007) - break; - - // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original - AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[i]); - - switch (aurNameReal) - { - // DoT/HoT/etc - case SPELL_AURA_DUMMY: // allow stack (HoTs checked later) - case SPELL_AURA_PERIODIC_DAMAGE: - case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: - case SPELL_AURA_PERIODIC_LEECH: - case SPELL_AURA_PERIODIC_HEAL: - case SPELL_AURA_OBS_MOD_HEALTH: - case SPELL_AURA_PERIODIC_MANA_LEECH: - case SPELL_AURA_OBS_MOD_MANA: - case SPELL_AURA_POWER_BURN_MANA: - case SPELL_AURA_CHANNEL_DEATH_ITEM: - break; - case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable - default: // not allow - // can be only single (this check done at _each_ aura add - stop = true; - break; - } - } - - if (stop) - { - RemoveSpellAuraHolder(foundHolder, AURA_REMOVE_BY_STACK); - break; - } - } - } - - // passive auras not stackable with other ranks - if (!IsPassiveSpellStackableWithRanks(aurSpellInfo) && !holder->IsPersistent()) - { - if (!RemoveNoStackAurasDueToAuraHolder(holder)) - { - DETAIL_LOG("[STACK] Annulation de l'aura en cours : %u.", holder->GetId()); - delete holder; - return false; // couldn't remove conflicting aura with higher rank - } - } - - // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura) - if (holder->IsSingleTarget()) - { - if (Unit* caster = holder->GetCaster()) // caster not in world - { - SingleCastSpellTargetMap& scTargets = caster->GetSingleCastSpellTargets(); - for (SingleCastSpellTargetMap::iterator itr = scTargets.begin(); itr != scTargets.end();) - { - SpellEntry const* itr_spellEntry = itr->first; - ObjectGuid itr_targetGuid = itr->second; - - if (itr_targetGuid != GetObjectGuid() && - IsSingleTargetSpells(itr_spellEntry, aurSpellInfo)) - { - scTargets.erase(itr); // remove for caster in any case - - // remove from target if target found - if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) - itr_target->RemoveAurasDueToSpell(itr_spellEntry->Id); - - itr = scTargets.begin(); // list can be chnaged at remove aura - continue; - } - - ++itr; - } - - // register spell holder single target - scTargets[aurSpellInfo] = GetObjectGuid(); - } - } - - if (holder->IsDeleted()) - { - sLog.outInfo("[Crash/Auras] Adding aura %u on player %s, but aura marked as deleted !", holder->GetId(), GetName()); - return false; - } - // add aura, register in lists and arrays - m_spellAuraHolders.insert(SpellAuraHolderMap::value_type(holder->GetId(), holder)); - - for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) - if (Aura *aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i))) - AddAuraToModList(aur); - - holder->ApplyAuraModifiers(true, true); - DEBUG_LOG("Holder of spell %u now is in use", holder->GetId()); - - // if aura deleted before boosts apply ignore - // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier - if (holder->IsDeleted()) - { - DETAIL_LOG(">> Aura %u is deleted", holder->GetId()); - return false; - } - holder->HandleSpellSpecificBoosts(true); - - // Check debuff limit - //DEBUG_LOG("AddSpellAuraHolder: Adding spell %d, debuff limit affected: %d", holder->GetId(), holder->IsAffectedByDebuffLimit()); - if (holder->IsAffectedByDebuffLimit()) - { - uint32 negativeAuras = GetNegativeAurasCount(); - if (negativeAuras > sWorld.getConfig(CONFIG_UINT32_DEBUFF_LIMIT)) - { - // We may have removed the aura we just applied ... - if (RemoveAuraDueToDebuffLimit(holder)) - return false; // The holder has been deleted with 'RemoveSpellAuraHolder' - } - } - // When we call _AddSpellAuraHolder, we must have a free aura slot - holder->_AddSpellAuraHolder(); - return true; -} - -// Debuff limit -uint32 Unit::GetNegativeAurasCount() -{ - uint32 count = 0; - for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) - { - if (!i->second || !i->second->IsAffectedByDebuffLimit()) - continue; - - ++count; - } - return count; -} - -bool Unit::RemoveAuraDueToDebuffLimit(SpellAuraHolder* currentAura) -{ - SpellAuraHolderMap::const_iterator i, uselessDebuff; - uselessDebuff = m_spellAuraHolders.end(); - for (i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) - { - if (!i->second || !i->second->IsAffectedByDebuffLimit() || i->second->IsInUse()) - continue; - - if (uselessDebuff == m_spellAuraHolders.end() || uselessDebuff->second->IsMoreImportantDebuffThan(i->second)) - uselessDebuff = i; - } - - SpellAuraHolder* removeAuraHolder = currentAura; - if (uselessDebuff != m_spellAuraHolders.end()) - removeAuraHolder = uselessDebuff->second; - RemoveSpellAuraHolder(removeAuraHolder); - return currentAura == removeAuraHolder; -} - -void Unit::AddAuraToModList(Aura *aura) -{ - if (aura->GetModifier()->m_auraname < TOTAL_AURAS) - m_modAuras[aura->GetModifier()->m_auraname].push_back(aura); -} - -void Unit::RemoveRankAurasDueToSpell(uint32 spellId) -{ - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); - if (!spellInfo) - return; - SpellAuraHolderMap::const_iterator i, next; - for (i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); i = next) - { - next = i; - ++next; - uint32 i_spellId = (*i).second->GetId(); - if ((*i).second && i_spellId && i_spellId != spellId) - { - if (sSpellMgr.IsRankSpellDueToSpell(spellInfo, i_spellId)) - { - RemoveAurasDueToSpell(i_spellId); - - if (m_spellAuraHolders.empty()) - break; - else - next = m_spellAuraHolders.begin(); - } - } - } -} - -bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder *holder) -{ - if (!holder) - return false; - - SpellEntry const* spellProto = holder->GetSpellProto(); - if (!spellProto) - return false; - - uint32 spellId = holder->GetId(); - - // passive spell special case (only non stackable with ranks) - if (spellProto->Attributes & (SPELL_ATTR_PASSIVE | 0x80)) - { - if (IsPassiveSpellStackableWithRanks(spellProto)) - return true; - } - - uint32 firstInChain = 0; - for (int eff = 0; eff < MAX_EFFECT_INDEX; ++eff) - { - if (Aura* aura = holder->GetAuraByEffectIndex(SpellEffectIndex(eff))) - { - switch (aura->GetModifier()->m_auraname) - { - case SPELL_AURA_PERIODIC_HEAL: - case SPELL_AURA_OBS_MOD_HEALTH: - { - firstInChain = sSpellMgr.GetFirstSpellInChain(holder->GetId()); - break; - } - default: - break; - } - } - - if (firstInChain) - break; - } - - SpellSpecific spellId_spec = GetSpellSpecific(spellId); - - bool isAreaAura = IsSpellHaveEffect(spellProto, SPELL_EFFECT_APPLY_AREA_AURA_PARTY); - SpellAuraHolderMap::iterator i, next; - for (i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); i = next) - { - next = i; - ++next; - if (!(*i).second) continue; - - SpellEntry const* i_spellProto = (*i).second->GetSpellProto(); - - if (!i_spellProto) - continue; - - uint32 i_spellId = i_spellProto->Id; - - // early checks that spellId is passive non stackable spell - if (i_spellProto->Attributes & (SPELL_ATTR_PASSIVE | 0x80)) - { - // passive non-stackable spells not stackable only for same caster - // -> Sauf si 2 AreaAuras - if (holder->GetCasterGuid() != i->second->GetCasterGuid() && !isAreaAura && !IsSpellHaveEffect(i_spellProto, SPELL_EFFECT_APPLY_AREA_AURA_PARTY)) - continue; - - // passive non-stackable spells not stackable only with another rank of same spell - if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) - { - if (CompareAuraRanks(spellId, i_spellId) < 0) // Le sort actuel est plus puissant. - { - DETAIL_LOG("[STACK] [%u/%u] Le sort actuel est plus puissant.", spellId, i_spellId); - // On empeche la pose de l'aura. - return false; - } - } - else - continue; - } - - if (i_spellId == spellId) - { - // Nostalrius - fix stack same HoT rank / diff caster - if (firstInChain) - RemoveAurasDueToSpell(i_spellId); - else switch (spellId) - { - // Blessing of Light does not stack between casters. - case 19977: - case 19978: - case 19979: - case 25890: - RemoveAurasDueToSpell(spellId); - break; - } - continue; - } - - SpellGroup spellGroup; - SpellGroupStackRule rule = sSpellMgr.CheckSpellGroupStackRules(i_spellId, spellId, spellGroup); - if (rule != SPELL_GROUP_STACK_RULE_DEFAULT) - { - // Attempt to add apply less powerfull spell - if (rule == SPELL_GROUP_STACK_RULE_POWERFULL_CHAIN && sSpellMgr.IsMorePowerfullSpell(i_spellId, spellId, spellGroup)) - { - DETAIL_LOG("[STACK][DB] Powerfull chain %u > %u (group %u). Aura %u will not be applied.", i_spellId, spellId, spellGroup, spellId); - return false; - } - DETAIL_LOG("[STACK][DB] Unable to stack %u and %u. %u will be removed.", spellId, i_spellId, i_spellId); - RemoveAurasDueToSpell(i_spellId); - continue; - } - - bool is_triggered_by_spell = false; - // prevent triggering aura of removing aura that triggered it - for (int j = 0; j < MAX_EFFECT_INDEX; ++j) - if (i_spellProto->EffectTriggerSpell[j] == spellId) - is_triggered_by_spell = true; - - // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell - for (int j = 0; j < MAX_EFFECT_INDEX; ++j) - if (spellProto->EffectTriggerSpell[j] == i_spellId) - is_triggered_by_spell = true; - - if (is_triggered_by_spell) - continue; - - if (IsSpellHaveAura(i_spellProto, SPELL_AURA_CHANNEL_DEATH_ITEM)) // Plusieurs demo par exemple peuvent mettre un siphon d'ame. - continue; - - SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId); - - // single allowed spell specific from same caster or from any caster at target - bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec, i_spellId_spec); - - bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec, i_spellId_spec); - - // HoTs in 1.x must be per target also - if (!is_spellSpecPerTarget && firstInChain && firstInChain == sSpellMgr.GetFirstSpellInChain(i_spellId)) - is_spellSpecPerTarget = true; - - if (is_spellSpecPerTarget || (is_spellSpecPerTargetPerCaster && holder->GetCasterGuid() == (*i).second->GetCasterGuid())) - { - // cannot remove higher rank - if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) - if (CompareAuraRanks(spellId, i_spellId) < 0) - return false; - - // Its a parent aura (create this aura in ApplyModifier) - if ((*i).second->IsInUse()) - { - sLog.outError("SpellAuraHolder (Spell %u) is in process but attempt removed at SpellAuraHolder (Spell %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAuraHolder", i->second->GetId(), holder->GetId()); - continue; - } - DETAIL_LOG("[STACK][%u/%u] SpellSpecPerTarget ou SpellSpecPerCaster", spellId, i_spellId); - RemoveAurasDueToSpell(i_spellId); - - if (m_spellAuraHolders.empty()) - break; - else - next = m_spellAuraHolders.begin(); - - continue; - } - - // spell with spell specific that allow single ranks for spell from diff caster - // same caster case processed or early or later - bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec, i_spellId_spec); - if (is_spellPerTarget && holder->GetCasterGuid() != (*i).second->GetCasterGuid() && sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) - { - // cannot remove higher rank - if (CompareAuraRanks(spellId, i_spellId) < 0) - { - DETAIL_LOG("[STACK] [%u/%u] Rang plus haut.", spellId, i_spellId); - return false; - } - - // Its a parent aura (create this aura in ApplyModifier) - if ((*i).second->IsInUse()) - { - sLog.outError("SpellAuraHolder (Spell %u) is in process but attempt removed at SpellAuraHolder (Spell %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAuraHolder", i->second->GetId(), holder->GetId()); - continue; - } - DETAIL_LOG("[STACK][%u/%u] SpellPerTarget", spellId, i_spellId); - RemoveAurasDueToSpell(i_spellId); - - if (m_spellAuraHolders.empty()) - break; - else - next = m_spellAuraHolders.begin(); - - continue; - } - - // non single (per caster) per target spell specific (possible single spell per target at caster) - if (!is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && sSpellMgr.IsNoStackSpellDueToSpell(spellId, i_spellId)) - { - // Its a parent aura (create this aura in ApplyModifier) - if ((*i).second->IsInUse()) - { - sLog.outError("SpellAuraHolder (Spell %u) is in process but attempt removed at SpellAuraHolder (Spell %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAuraHolder", i->second->GetId(), holder->GetId()); - continue; - } - DETAIL_LOG("[STACK][%u/%u] NoStackSpellDueToSpell", spellId, i_spellId); - RemoveAurasDueToSpell(i_spellId); - - if (m_spellAuraHolders.empty()) - break; - else - next = m_spellAuraHolders.begin(); - - continue; - } - } - // Sorts moins puissants : - std::list lessPowerfullSpells; - if (sSpellMgr.ListLessPowerfullSpells(spellId, lessPowerfullSpells)) - for (std::list::const_iterator it = lessPowerfullSpells.begin(); it != lessPowerfullSpells.end(); ++it) - RemoveAurasDueToSpell(*it); - return true; -} - -void Unit::RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except) -{ - SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) - { - Aura *aur = iter->second->m_auras[effindex]; - if (aur && aur != except) - { - RemoveSingleAuraFromSpellAuraHolder(iter->second, effindex); - // may remove holder - spair = GetSpellAuraHolderBounds(spellId); - iter = spair.first; - } - else - ++iter; - } -} -void Unit::RemoveAurasByCasterSpell(uint32 spellId, ObjectGuid casterGuid) -{ - SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) - { - if (iter->second->GetCasterGuid() == casterGuid) - { - RemoveSpellAuraHolder(iter->second); - spair = GetSpellAuraHolderBounds(spellId); - iter = spair.first; - } - else - ++iter; - } -} - -void Unit::RemoveSingleAuraFromSpellAuraHolder(uint32 spellId, SpellEffectIndex effindex, ObjectGuid casterGuid, AuraRemoveMode mode) -{ - SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) - { - Aura *aur = iter->second->m_auras[effindex]; - if (aur && aur->GetCasterGuid() == casterGuid) - { - RemoveSingleAuraFromSpellAuraHolder(iter->second, effindex, mode); - spair = GetSpellAuraHolderBounds(spellId); - iter = spair.first; - } - else - ++iter; - } -} - -void Unit::RemoveAuraHolderDueToSpellByDispel(uint32 spellId, uint32 stackAmount, ObjectGuid casterGuid, Unit *dispeller) -{ - RemoveAuraHolderFromStack(spellId, stackAmount, casterGuid, AURA_REMOVE_BY_DISPEL); -} - -void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGuid, Unit *stealer) -{ - SpellAuraHolder *holder = GetSpellAuraHolder(spellId, casterGuid); - SpellEntry const* spellProto = sSpellMgr.GetSpellEntry(spellId); - SpellAuraHolder *new_holder = CreateSpellAuraHolder(spellProto, stealer, this); - - // set its duration and maximum duration - // max duration 2 minutes (in msecs) - int32 dur = holder->GetAuraDuration(); - int32 max_dur = 2 * MINUTE * IN_MILLISECONDS; - int32 new_max_dur = max_dur > dur ? dur : max_dur; - new_holder->SetAuraMaxDuration(new_max_dur); - new_holder->SetAuraDuration(new_max_dur); - - for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) - { - Aura *aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); - - if (!aur) - continue; - - int32 basePoints = aur->GetBasePoints(); - // construct the new aura for the attacker - will never return NULL, it's just a wrapper for - // some different constructors - Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, new_holder, stealer, this); - - // set periodic to do at least one tick (for case when original aura has been at last tick preparing) - int32 periodic = aur->GetModifier()->periodictime; - new_aur->GetModifier()->periodictime = periodic < new_max_dur ? periodic : new_max_dur; - - // add the new aura to stealer - new_holder->AddAura(new_aur, new_aur->GetEffIndex()); - } - - if (holder->ModStackAmount(-1)) - // Remove aura as dispel - RemoveSpellAuraHolder(holder, AURA_REMOVE_BY_DISPEL); - - // strange but intended behaviour: Stolen single target auras won't be treated as single targeted - new_holder->SetIsSingleTarget(false); - - stealer->AddSpellAuraHolder(new_holder); -} - -void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId) -{ - SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) - { - RemoveSpellAuraHolder(iter->second, AURA_REMOVE_BY_CANCEL); - spair = GetSpellAuraHolderBounds(spellId); - iter = spair.first; - } -} - -void Unit::RemoveAurasWithDispelType(DispelType type, ObjectGuid casterGuid) -{ - // Create dispel mask by dispel type - uint32 dispelMask = GetDispellMask(type); - // Dispel all existing auras vs current dispel type - SpellAuraHolderMap& auras = GetSpellAuraHolderMap(); - for (SpellAuraHolderMap::iterator itr = auras.begin(); itr != auras.end();) - { - SpellEntry const* spell = itr->second->GetSpellProto(); - if (((1 << spell->Dispel) & dispelMask) && (!casterGuid || casterGuid == itr->second->GetCasterGuid())) - { - // Dispel aura - RemoveAurasDueToSpell(spell->Id); - itr = auras.begin(); - } - else - ++itr; - } -} - -void Unit::RemoveAuraHolderFromStack(uint32 spellId, uint32 stackAmount, ObjectGuid casterGuid, AuraRemoveMode mode) -{ - SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second; ++iter) - { - if (!casterGuid || iter->second->GetCasterGuid() == casterGuid) - { - if (iter->second->ModStackAmount(-int32(stackAmount))) - { - RemoveSpellAuraHolder(iter->second, mode); - break; - } - } - } -} - -void Unit::RemoveSingleAuraDueToItemSet(uint32 spellId, AuraRemoveMode mode) -{ - SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second;) - { - if (!iter->second->GetCastItemGuid()) - { - RemoveSpellAuraHolder(iter->second, mode); - return; - } - else - ++iter; - } -} - -void Unit::RemoveAurasDueToSpell(uint32 spellId, SpellAuraHolder* except, AuraRemoveMode mode) -{ - SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second;) - { - if (iter->second != except) - { - RemoveSpellAuraHolder(iter->second, mode); - bounds = GetSpellAuraHolderBounds(spellId); - iter = bounds.first; - } - else - ++iter; - } -} - -void Unit::RemoveAurasDueToItemSpell(Item* castItem, uint32 spellId) -{ - SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second;) - { - if (iter->second->GetCastItemGuid() == castItem->GetObjectGuid()) - { - RemoveSpellAuraHolder(iter->second); - bounds = GetSpellAuraHolderBounds(spellId); - iter = bounds.first; - } - else - ++iter; - } -} - -void Unit::RemoveAurasWithInterruptFlags(uint32 flags, uint32 except) -{ - for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) - { - if (iter->second->GetSpellProto()->AuraInterruptFlags & flags && iter->second->GetSpellProto()->Id != except) - { - RemoveSpellAuraHolder(iter->second); - iter = m_spellAuraHolders.begin(); - } - else - ++iter; - } -} - -void Unit::RemoveAurasWithAttribute(uint32 flags) -{ - for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) - { - if (iter->second->GetSpellProto()->Attributes & flags) - { - RemoveSpellAuraHolder(iter->second); - iter = m_spellAuraHolders.begin(); - } - else - ++iter; - } -} - -void Unit::RemoveNotOwnSingleTargetAuras() -{ - // single target auras from other casters - for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) - { - if (iter->second->GetCasterGuid() != GetObjectGuid() && iter->second->IsSingleTarget()) - { - RemoveSpellAuraHolder(iter->second); - iter = m_spellAuraHolders.begin(); - continue; - } - - ++iter; - } - - // single target auras at other targets - SingleCastSpellTargetMap& scTargets = GetSingleCastSpellTargets(); - for (SingleCastSpellTargetMap::iterator itr = scTargets.begin(); itr != scTargets.end();) - { - SpellEntry const* itr_spellEntry = itr->first; - ObjectGuid itr_targetGuid = itr->second; - - if (itr_targetGuid != GetObjectGuid()) - { - scTargets.erase(itr); // remove for caster in any case - - // remove from target if target found - if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) - itr_target->RemoveAurasByCasterSpell(itr_spellEntry->Id, GetObjectGuid()); - - itr = scTargets.begin(); // list can be changed at remove aura - continue; - } - - ++itr; - } - -} - -void Unit::RemoveSpellAuraHolder(SpellAuraHolder *holder, AuraRemoveMode mode) -{ - // Statue unsummoned at holder remove - SpellEntry const* AurSpellInfo = holder->GetSpellProto(); - Totem* statue = nullptr; - Unit* caster = holder->GetCaster(); - if (IsChanneledSpell(AurSpellInfo) && caster) - if (caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem() && ((Totem*)caster)->GetTotemType() == TOTEM_STATUE) - statue = ((Totem*)caster); - - if (m_spellAuraHoldersUpdateIterator != m_spellAuraHolders.end() && m_spellAuraHoldersUpdateIterator->second == holder) - ++m_spellAuraHoldersUpdateIterator; - - SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(holder->GetId()); - bool foundInMap = false; - for (SpellAuraHolderMap::iterator itr = bounds.first; itr != bounds.second; ++itr) - { - if (itr->second == holder) - { - m_spellAuraHolders.erase(itr); - foundInMap = true; - break; - } - } - if (!foundInMap) - sLog.outInfo("[Crash/Auras] Removing aura holder *not* in holders map ! Aura %u on %s", holder->GetId(), GetName()); - holder->SetRemoveMode(mode); - holder->UnregisterSingleCastHolder(); - - for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) - { - if (Aura *aura = holder->m_auras[i]) - RemoveAura(aura, mode); - } - - holder->_RemoveSpellAuraHolder(); - - if (mode != AURA_REMOVE_BY_DELETE) - holder->HandleSpellSpecificBoosts(false); - - if (statue) - statue->UnSummon(); - - uint32 auraSpellId = holder->GetId(); - // If holder in use (removed from code that plan access to it data after return) - // store it in holder list with delayed deletion - if (holder->IsInUse()) - { - holder->SetDeleted(); - m_deletedHolders.push_back(holder); - } - else - delete holder; - - if (caster && IsChanneledSpell(AurSpellInfo) && - (mode != AURA_REMOVE_BY_EXPIRE || caster->IsControlledByPlayer())) // Player pets need to be interrupted on channel expire or else they get stuck channeling - { - Spell *channeled = caster->GetCurrentSpell(CURRENT_CHANNELED_SPELL); - if (channeled && channeled->m_spellInfo->Id == auraSpellId && channeled->m_targets.getUnitTarget() == this) - caster->InterruptSpell(CURRENT_CHANNELED_SPELL); - } -} - -void Unit::RemoveSingleAuraFromSpellAuraHolder(SpellAuraHolder *holder, SpellEffectIndex index, AuraRemoveMode mode) -{ - Aura *aura = holder->GetAuraByEffectIndex(index); - if (!aura) - return; - - if (aura->IsLastAuraOnHolder()) - RemoveSpellAuraHolder(holder, mode); - else - RemoveAura(aura, mode); -} - -void Unit::RemoveAura(Aura *Aur, AuraRemoveMode mode) -{ - // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order) - if (Aur->GetModifier()->m_auraname < TOTAL_AURAS) - m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur); - - // Set remove mode - Aur->SetRemoveMode(mode); - - // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura - // remove aura from list before to prevent deleting it before - ///m_Auras.erase(i); - - DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura %u [spell%u] now is remove mode %d. Caster %s", Aur->GetModifier()->m_auraname, Aur->GetSpellProto()->Id, mode, GetName()); - - // aura _MUST_ be remove from holder before unapply. - // un-apply code expected that aura not find by diff searches - // in another case it can be double removed for example, if target die/etc in un-apply process. - Aur->GetHolder()->RemoveAura(Aur->GetEffIndex()); - - // some auras also need to apply modifier (on caster) on remove - if (mode == AURA_REMOVE_BY_DELETE) - { - switch (Aur->GetModifier()->m_auraname) - { - // need properly undo any auras with player-caster mover set (or will crash at next caster move packet) - case SPELL_AURA_MOD_POSSESS: - case SPELL_AURA_MOD_POSSESS_PET: - Aur->ApplyModifier(false, true); - break; - default: - break; - } - } - else - Aur->ApplyModifier(false, true); - - // If aura in use (removed from code that plan access to it data after return) - // store it in aura list with delayed deletion - if (Aur->IsInUse()) - m_deletedAuras.push_back(Aur); - else - delete Aur; -} - -void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) -{ - while (!m_spellAuraHolders.empty()) - { - SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); - RemoveSpellAuraHolder(iter->second, mode); - } -} - -void Unit::RemoveAllNegativeAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) -{ - for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) - { - if (!iter->second->IsPositive()) - { - RemoveSpellAuraHolder(iter->second, mode); - iter = m_spellAuraHolders.begin(); - } - else - ++iter; - } -} - -void Unit::RemoveAurasAtReset(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) -{ - // @TODO: Some buffs should maybe not get removed ? Self casted buffs ? ... - if (Creature* c = ToCreature()) - if (CreatureInfo const* info = c->GetCreatureInfo()) - if (info->flags_extra & CREATURE_FLAG_EXTRA_KEEP_POSITIVE_AURAS_ON_EVADE) - { - RemoveAllNegativeAuras(mode); - return; - } - RemoveAllAuras(mode); -} - -void Unit::RemoveAllAurasOnDeath() -{ - // used just after dieing to remove all visible auras - // and disable the mods for the passive ones - for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) - { - if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent()) - { - RemoveSpellAuraHolder(iter->second, AURA_REMOVE_BY_DEATH); - iter = m_spellAuraHolders.begin(); - } - else - ++iter; - } -} - -void Unit::DelaySpellAuraHolder(uint32 spellId, int32 delaytime, ObjectGuid casterGuid) -{ - SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second; ++iter) - { - SpellAuraHolder* holder = iter->second; - - if (casterGuid != holder->GetCasterGuid()) - continue; - - if (holder->GetAuraDuration() < delaytime) - holder->SetAuraDuration(0); - else - holder->SetAuraDuration(holder->GetAuraDuration() - delaytime); - - holder->UpdateAuraDuration(); - - DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Spell %u partially interrupted on %s, new duration: %u ms", spellId, GetObjectGuid().GetString().c_str(), holder->GetAuraDuration()); - } -} - -void Unit::_RemoveAllAuraMods() -{ - for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) - (*i).second->ApplyAuraModifiers(false); -} - -void Unit::_ApplyAllAuraMods() -{ - for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) - (*i).second->ApplyAuraModifiers(true); -} - -bool Unit::HasAuraType(AuraType auraType) const -{ - return !GetAurasByType(auraType).empty(); -} - -bool Unit::HasAffectedAura(AuraType auraType, SpellEntry const* spellProto) const -{ - Unit::AuraList const& auras = GetAurasByType(auraType); - - for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) - { - if ((*itr)->isAffectedOnSpell(spellProto)) - return true; - } - - return false; -} - -Aura* Unit::GetAura(uint32 spellId, SpellEffectIndex effindex) -{ - SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); - if (bounds.first != bounds.second) - return bounds.first->second->GetAuraByEffectIndex(effindex); - return nullptr; -} - -Aura* Unit::GetAura(AuraType type, SpellFamily family, uint64 familyFlag, ObjectGuid casterGuid) -{ - AuraList const& auras = GetAurasByType(type); - for (AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i) - if ((*i)->GetSpellProto()->IsFitToFamily(family, familyFlag) && - (!casterGuid || (*i)->GetCasterGuid() == casterGuid)) - return *i; - - return nullptr; -} - -bool Unit::HasAura(uint32 spellId, SpellEffectIndex effIndex) const -{ - SpellAuraHolderConstBounds spair = GetSpellAuraHolderBounds(spellId); - for (SpellAuraHolderMap::const_iterator i_holder = spair.first; i_holder != spair.second; ++i_holder) - if (i_holder->second->GetAuraByEffectIndex(effIndex)) - return true; - - return false; -} - -void Unit::AddDynObject(DynamicObject* dynObj) -{ - m_dynObjGUIDs.push_back(dynObj->GetObjectGuid()); - dynObj->SetWorldMask(GetWorldMask()); // Nostalrius : phasing -} - -void Unit::RemoveDynObject(uint32 spellid) -{ - if (m_dynObjGUIDs.empty()) - return; - for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();) - { - DynamicObject* dynObj = GetMap()->GetDynamicObject(*i); - if (!dynObj) - i = m_dynObjGUIDs.erase(i); - else if (spellid == 0 || dynObj->GetSpellId() == spellid) - { - dynObj->Delete(); - i = m_dynObjGUIDs.erase(i); - } - else - ++i; - } -} - -void Unit::RemoveAllDynObjects() -{ - while (!m_dynObjGUIDs.empty()) - { - if (DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin())) - dynObj->Delete(); - m_dynObjGUIDs.erase(m_dynObjGUIDs.begin()); - } -} - -DynamicObject * Unit::GetDynObject(uint32 spellId, SpellEffectIndex effIndex) -{ - for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();) - { - DynamicObject* dynObj = GetMap()->GetDynamicObject(*i); - if (!dynObj) - { - i = m_dynObjGUIDs.erase(i); - continue; - } - - if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex) - return dynObj; - ++i; - } - return nullptr; -} - -DynamicObject * Unit::GetDynObject(uint32 spellId) -{ - for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();) - { - DynamicObject* dynObj = GetMap()->GetDynamicObject(*i); - if (!dynObj) - { - i = m_dynObjGUIDs.erase(i); - continue; - } - - if (dynObj->GetSpellId() == spellId) - return dynObj; - ++i; - } - return nullptr; -} - -GameObject* Unit::GetGameObject(uint32 spellId) const -{ - for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i) - if ((*i)->GetSpellId() == spellId) - return *i; - - return nullptr; -} - -void Unit::AddGameObject(GameObject* gameObj) -{ - MANGOS_ASSERT(gameObj && !gameObj->GetOwnerGuid()); - m_gameObj.push_back(gameObj); - gameObj->SetOwnerGuid(GetObjectGuid()); - gameObj->SetWorldMask(GetWorldMask()); - - if (GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId()) - { - SpellEntry const* createBySpell = sSpellMgr.GetSpellEntry(gameObj->GetSpellId()); - // Need disable spell use for owner - if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) - // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases) - ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell, 0, nullptr, true); - } -} - -void Unit::RemoveGameObject(GameObject* gameObj, bool del) -{ - MANGOS_ASSERT(gameObj && gameObj->GetOwnerGuid() == GetObjectGuid()); - - gameObj->SetOwnerGuid(ObjectGuid()); - - // GO created by some spell - if (uint32 spellid = gameObj->GetSpellId()) - { - RemoveAurasDueToSpell(spellid); - - SpellEntry const* createBySpell = sSpellMgr.GetSpellEntry(spellid); - // Need activate spell use for owner - if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) - // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases) - CooldownEvent(createBySpell); - } - - m_gameObj.remove(gameObj); - - if (del) - { - gameObj->SetRespawnTime(0); - gameObj->Delete(); - } -} - -void Unit::RemoveGameObject(uint32 spellid, bool del) -{ - if (m_gameObj.empty()) - return; - GameObjectList::iterator i, next; - for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next) - { - next = i; - if (spellid == 0 || (*i)->GetSpellId() == spellid) - { - (*i)->SetOwnerGuid(ObjectGuid()); - if (del) - { - (*i)->SetRespawnTime(0); - (*i)->Delete(); - } - - next = m_gameObj.erase(i); - } - else - ++next; - } -} - -void Unit::RemoveAllGameObjects() -{ - // remove references to unit - for (GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();) - { - (*i)->SetOwnerGuid(ObjectGuid()); - (*i)->SetRespawnTime(0); - (*i)->Delete(); - i = m_gameObj.erase(i); - } -} - -void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log) -{ - WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16 + 4 + 4 + 1 + 4 + 4 + 1 + 1 + 4 + 4 + 1)); // we guess size - data << log->target->GetPackGUID(); - data << log->attacker->GetPackGUID(); - data << uint32(log->SpellID); - data << uint32(log->damage); // damage amount - data << uint8(log->school); // damage school - data << uint32(log->absorb); // AbsorbedDamage - data << uint32(log->resist); // resist - data << uint8(log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name - data << uint8(log->unused); // unused - data << uint32(log->blocked); // blocked - data << uint32(log->HitInfo); - data << uint8(0); // flag to use extend data - SendMessageToSet(&data, true); -} - -void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit) -{ - SpellNonMeleeDamage log(this, target, SpellID, GetFirstSchoolInMask(damageSchoolMask)); - log.damage = Damage - AbsorbedDamage - Resist - Blocked; - log.absorb = AbsorbedDamage; - log.resist = Resist; - log.physicalLog = PhysicalDamage; - log.blocked = Blocked; - log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6; - if (CriticalHit) - log.HitInfo |= SPELL_HIT_TYPE_CRIT; - SendSpellNonMeleeDamageLog(&log); -} - -void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo, AuraType auraTypeOverride) -{ - Aura *aura = pInfo->aura; - Modifier *mod = aura->GetModifier(); - AuraType auraType = auraTypeOverride ? auraTypeOverride : mod->m_auraname; - - WorldPacket data(SMSG_PERIODICAURALOG, 30); - data << aura->GetTarget()->GetPackGUID(); - data << aura->GetCasterGuid().WriteAsPacked(); - data << uint32(aura->GetId()); // spellId - data << uint32(1); // count - data << uint32(auraType); // auraId - switch (auraType) - { - case SPELL_AURA_PERIODIC_DAMAGE: - case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: - data << uint32(pInfo->damage); // damage - data << uint32(aura->GetSpellProto()->School); - data << uint32(pInfo->absorb); // absorb - data << uint32(pInfo->resist); // resist - break; - case SPELL_AURA_PERIODIC_HEAL: - case SPELL_AURA_OBS_MOD_HEALTH: - data << uint32(pInfo->damage); // damage - break; - case SPELL_AURA_OBS_MOD_MANA: - case SPELL_AURA_PERIODIC_ENERGIZE: - data << uint32(mod->m_miscvalue); // power type - data << uint32(pInfo->damage); // damage - break; - case SPELL_AURA_PERIODIC_MANA_LEECH: - data << uint32(mod->m_miscvalue); // power type - data << uint32(pInfo->damage); // amount - data << float(pInfo->multiplier); // gain multiplier - break; - default: - sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(auraType)); - return; - } - - aura->GetTarget()->SendObjectMessageToSet(&data, true); -} - -class RemovedSpellData -{ -public: - RemovedSpellData(uint32 spell, Unit* target) : spellId(spell), unit(target) - { - } - bool operator <(const RemovedSpellData& b) const - { - return spellId < b.spellId; - } - bool operator==(const RemovedSpellData& b) const - { - return spellId == b.spellId && unit == b.unit; - } - uint32 spellId; - Unit* unit; -}; - -typedef std::list RemoveSpellList; - -void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell, Spell* spell) -{ - if (!IsInWorld()) - return; - - ProcTriggeredList procTriggered; - - // Not much to do if no flags are set. - if (procAttacker) - ProcDamageAndSpellFor(false, pVictim, procAttacker, procExtra, attType, procSpell, amount, procTriggered, spell); - - // Now go on with a victim's events'n'auras - // Not much to do if no flags are set or there is no victim - if (pVictim && pVictim->isAlive() && procVictim) - pVictim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount, procTriggered, spell); - - HandleTriggers(pVictim, procExtra, amount, procSpell, procTriggered); -} - -void Unit::HandleTriggers(Unit *pVictim, uint32 procExtra, uint32 amount, SpellEntry const *procSpell, ProcTriggeredList const& procTriggered) -{ - RemoveSpellList removedSpells; - // Nothing found - if (procTriggered.empty()) - return; - - // Handle effects proceed this time - for (ProcTriggeredList::const_iterator itr = procTriggered.begin(); itr != procTriggered.end(); ++itr) - { - // Some auras can be deleted in function called in this loop (except first, ofc) - SpellAuraHolder *triggeredByHolder = itr->triggeredByHolder; - if (triggeredByHolder->IsDeleted()) - { - triggeredByHolder->SetInUse(false); - continue; - } - - SpellProcEventEntry const *spellProcEvent = itr->spellProcEvent; - bool useCharges = triggeredByHolder->GetAuraCharges() > 0; - bool procSuccess = true; - bool anyAuraProc = false; - Unit* caster = itr->target == this ? pVictim : this; - - if (!caster || !caster->IsInWorld()) - { - triggeredByHolder->SetInUse(false); - continue; - } - - // For players set spell cooldown if need - uint32 cooldown = 0; - if (triggeredByHolder->GetTarget()->GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown) - cooldown = spellProcEvent->cooldown; - - for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) - { - Aura *triggeredByAura = triggeredByHolder->GetAuraByEffectIndex(SpellEffectIndex(i)); - if (!triggeredByAura) - continue; - - Modifier *auraModifier = triggeredByAura->GetModifier(); - - if (procSpell) - { - if (spellProcEvent) - { - if (spellProcEvent->spellFamilyMask[i]) - { - if (!procSpell->IsFitToFamilyMask(spellProcEvent->spellFamilyMask[i])) - continue; - } - // don't check dbc FamilyFlags if schoolMask exists - else if (!triggeredByAura->CanProcFrom(procSpell, spellProcEvent->procEx, procExtra, amount != 0, !spellProcEvent->schoolMask)) - continue; - } - else if (!triggeredByAura->CanProcFrom(procSpell, PROC_EX_NONE, procExtra, amount != 0, true)) - continue; - } - - SpellAuraProcResult procResult = (*caster.*AuraProcHandler[auraModifier->m_auraname])(itr->target, amount, triggeredByAura, procSpell, itr->procFlag, procExtra, cooldown); - switch (procResult) - { - case SPELL_AURA_PROC_CANT_TRIGGER: - continue; - case SPELL_AURA_PROC_FAILED: - procSuccess = false; - break; - case SPELL_AURA_PROC_OK: - break; - } - - anyAuraProc = true; - } - // Remove charge (aura can be removed by triggers) - if (useCharges && procSuccess && anyAuraProc && !triggeredByHolder->IsDeleted()) - { - // If last charge dropped add spell to remove list - if (triggeredByHolder->DropAuraCharge()) - removedSpells.push_back(RemovedSpellData(triggeredByHolder->GetId(), caster)); - } - - triggeredByHolder->SetInUse(false); - } - - if (!removedSpells.empty()) - { - // Sort spells and remove duplicates - removedSpells.sort(); - removedSpells.unique(); - // Remove auras from removedAuras - for (RemoveSpellList::iterator i = removedSpells.begin(); i != removedSpells.end(); ++i) - i->unit->RemoveAurasDueToSpell(i->spellId); - } -} - -void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo) -{ - WorldPacket data(SMSG_SPELLLOGMISS, (4 + 8 + 1 + 4 + 8 + 1)); - data << uint32(spellID); - data << GetObjectGuid(); - data << uint8(0); // unk8 - data << uint32(1); // target count - // for(i = 0; i < target count; ++i) - data << target->GetObjectGuid(); // target GUID - data << uint8(missInfo); - // Nostalrius: + 2 * float if unk8=1 - // end loop - SendObjectMessageToSet(&data, true); -} - -void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo) -{ - DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Sending SMSG_ATTACKERSTATEUPDATE"); - - WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16 + 45)); // we guess size - - data << uint32(damageInfo->HitInfo); - data << GetPackGUID(); - data << damageInfo->target->GetPackGUID(); - data << uint32(damageInfo->totalDamage); // Total damage - - data << uint8(m_weaponDamageCount[damageInfo->attackType]); // Sub damage count - - // Sub damage description - for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) - { - SubDamageInfo *subDamage = &damageInfo->subDamage[i]; - - data << uint32(GetFirstSchoolInMask(subDamage->damageSchoolMask)); - data << float(subDamage->damage)/ float(damageInfo->totalDamage); // Float coefficient of sub damage - data << uint32(subDamage->damage); - data << uint32(subDamage->absorb); - data << uint32(subDamage->resist); - } - data << uint32(damageInfo->TargetState); - data << uint32(0); - data << uint32(0); // spell id, seen with heroic strike and disarm as examples. - // HITINFO_NOACTION normally set if spell - data << uint32(damageInfo->blocked_amount); - - SendMessageToSet(&data, true); -} - -void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount) -{ - CalcDamageInfo dmgInfo; - dmgInfo.HitInfo = HitInfo; - dmgInfo.attacker = this; - dmgInfo.target = target; - dmgInfo.attackType = BASE_ATTACK; - dmgInfo.totalDamage = Damage - AbsorbDamage - Resist - BlockedAmount; - dmgInfo.totalAbsorb = AbsorbDamage; - dmgInfo.totalResist = Resist; - dmgInfo.subDamage[0].damage = dmgInfo.totalDamage; - dmgInfo.subDamage[0].damageSchoolMask = damageSchoolMask; - dmgInfo.subDamage[0].absorb = AbsorbDamage; - dmgInfo.subDamage[0].resist = Resist; - dmgInfo.TargetState = TargetState; - dmgInfo.blocked_amount = BlockedAmount; - SendAttackStateUpdate(&dmgInfo); -} - -void Unit::SetInitCreaturePowerType() -{ - if (GetTypeId() == TYPEID_PLAYER) - return; - - auto pCreature = static_cast(this); - auto pPet = pCreature->ToPet(); - - if (pPet && pPet->getPetType() == HUNTER_PET) - return; - - // a bit wrong, but have to follow the dirty database values - if (pCreature->GetCreatureInfo()->minmana > 0) - SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_MANA); - else - { - switch (getClass()) - { - case CLASS_ROGUE: - SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_ENERGY); - SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY)); - SetPower(POWER_ENERGY, 0); - break; - default: - SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_RAGE); - SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE)); - SetPower(POWER_RAGE, 0); - break; - } - } -} - -void Unit::setPowerType(Powers new_powertype) -{ - SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype); - - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE); - } - } - - switch (new_powertype) - { - default: - case POWER_MANA: - break; - case POWER_RAGE: - SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE)); - SetPower(POWER_RAGE, 0); - break; - case POWER_FOCUS: - SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS)); - SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS)); - break; - case POWER_ENERGY: - SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY)); - SetPower(POWER_ENERGY, 0); - break; - case POWER_HAPPINESS: - SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); - SetPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); - break; - } -} - -FactionTemplateEntry const* Unit::getFactionTemplateEntry() const -{ - FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction()); - if (!entry) - { - static ObjectGuid guid; // prevent repeating spam same faction problem - - if (GetObjectGuid() != guid) - { - sLog.outError("%s have invalid faction (faction template id) #%u", GetGuidStr().c_str(), getFaction()); - guid = GetObjectGuid(); - } - } - return entry; -} - -// function based on function Unit::UnitReaction from 13850 client -ReputationRank Unit::GetReactionTo(Unit const* target) const -{ - // always friendly to self - if (this == target) - return REP_FRIENDLY; - - // always friendly to charmer or owner - if (GetCharmerOrOwnerOrSelf() == target->GetCharmerOrOwnerOrSelf()) - return REP_FRIENDLY; - - Player const* selfPlayerOwner = GetAffectingPlayer(); - Player const* targetPlayerOwner = target->GetAffectingPlayer(); - - // check forced reputation to support SPELL_AURA_FORCE_REACTION - if (selfPlayerOwner) - { - if (selfPlayerOwner->isGameMaster()) - return REP_NEUTRAL; - if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) - if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) - return *repRank; - } - else if (targetPlayerOwner) - { - if (targetPlayerOwner->isGameMaster()) - return REP_NEUTRAL; - if (FactionTemplateEntry const* selfFactionTemplateEntry = getFactionTemplateEntry()) - if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(selfFactionTemplateEntry)) - return *repRank; - } - - // Interaction between pvp flagged units - if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && - target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) - { - if (selfPlayerOwner && targetPlayerOwner) - { - // always friendly to other unit controlled by player, or to the player himself - if (selfPlayerOwner == targetPlayerOwner) - return REP_FRIENDLY; - - // duel - always hostile to opponent - if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0 && !selfPlayerOwner->duel->finished) - return REP_HOSTILE; - - // same group - checks dependant only on our faction - skip FFA_PVP for example - if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner)) - return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work - // however client seems to allow mixed group parties, because in 13850 client it works like: - // return GetFactionReactionTo(getFactionTemplateEntry(), target); - - // Sanctuary - if (selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY) && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY)) - return REP_FRIENDLY; - - // Nostalrius: Hackfix because UNIT_BYTE2_FLAG_FFA_PVP is not implemented yet. - if (selfPlayerOwner->IsFFAPvP() && targetPlayerOwner->IsFFAPvP()) - return REP_HOSTILE; - } - - // check FFA_PVP - not implemented that way on MaNGOS :/ - /* - if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP - && target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) - return REP_HOSTILE; - */ - - if (selfPlayerOwner) - { - if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) - { - if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) - return *repRank; - if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) - { - if (targetFactionEntry->CanHaveReputation()) - { - // check contested flags - if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD - && selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) - return REP_HOSTILE; - - // if faction has reputation, hostile state depends only from AtWar state - if (FactionState const* factionState = selfPlayerOwner->GetReputationMgr().GetState(targetFactionEntry)) - if (factionState->Flags & FACTION_FLAG_AT_WAR) - return REP_HOSTILE; - return REP_FRIENDLY; - } - } - } - } - } - - // Player reaction against Neutral faction Creature - if (selfPlayerOwner && !targetPlayerOwner) - { - if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) - { - if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) - { - if(targetFactionEntry->CanHaveReputation()) - { - return selfPlayerOwner->GetReputationMgr().GetRank(targetFactionEntry); - } - } - } - } - - // do checks dependant only on our faction - return GetFactionReactionTo(getFactionTemplateEntry(), target); -} - -ReputationRank Unit::GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target) -{ - // always neutral when no template entry found - if (!factionTemplateEntry) - return REP_NEUTRAL; - - FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry(); - if (!targetFactionTemplateEntry) - return REP_NEUTRAL; - - if (Player const* targetPlayerOwner = target->GetAffectingPlayer()) - { - // check contested flags - if (factionTemplateEntry->IsContestedGuardFaction() - && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) - return REP_HOSTILE; - if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(factionTemplateEntry)) - return *repRank; - if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction)) - { - if (factionEntry->CanHaveReputation()) - { - // CvP case - check reputation, don't allow state higher than neutral when at war - ReputationRank repRank = targetPlayerOwner->GetReputationMgr().GetRank(factionEntry); - if (FactionState const* factionState = targetPlayerOwner->GetReputationMgr().GetState(factionEntry)) - if (factionState->Flags & FACTION_FLAG_AT_WAR) - repRank = std::min(REP_NEUTRAL, repRank); - return repRank; - } - } - } - - // common faction based check - if (factionTemplateEntry->IsHostileTo(*targetFactionTemplateEntry)) - return REP_HOSTILE; - if (factionTemplateEntry->IsFriendlyTo(*targetFactionTemplateEntry)) - return REP_FRIENDLY; - if (targetFactionTemplateEntry->IsFriendlyTo(*factionTemplateEntry)) - return REP_FRIENDLY; - if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_HOSTILE_BY_DEFAULT) - return REP_HOSTILE; - // neutral by default - return REP_NEUTRAL; -} - -bool Unit::IsHostileTo(Unit const* unit) const -{ - return GetReactionTo(unit) <= REP_HOSTILE; -} - -bool Unit::IsFriendlyTo(Unit const* unit) const -{ - return GetReactionTo(unit) >= REP_FRIENDLY; -} - -bool Unit::IsHostileToPlayers() const -{ - FactionTemplateEntry const* my_faction = getFactionTemplateEntry(); - if (!my_faction || !my_faction->faction) - return false; - - FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction); - if (raw_faction && raw_faction->reputationListID >= 0) - return false; - - return my_faction->IsHostileToPlayers(); -} - -bool Unit::IsNeutralToAll() const -{ - FactionTemplateEntry const* my_faction = getFactionTemplateEntry(); - if (!my_faction || !my_faction->faction) - return true; - - FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction); - if (raw_faction && raw_faction->reputationListID >= 0) - return false; - - return my_faction->IsNeutralToAll(); -} - -bool Unit::Attack(Unit *victim, bool meleeAttack) -{ - if (!victim || victim == this) - return false; - - // Nostalrius : verifications de bon sens - if (victim->IsDeleted() || IsDeleted()) - return false; - - // dead units can neither attack nor be attacked - if (!isAlive() || !victim->IsInWorld() || !victim->isAlive()) - return false; - - // player cannot attack in mount state - if (GetTypeId() == TYPEID_PLAYER && IsMounted()) - return false; - - // nobody can attack GM in GM-mode - if (victim->GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)victim)->isGameMaster()) - return false; - } - else - { - if (((Creature*)victim)->IsInEvadeMode()) - return false; - } - - // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack) - if (HasAuraType(SPELL_AURA_MOD_UNATTACKABLE)) - RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE); - - // in fighting already - if (m_attacking) - { - if (m_attacking == victim) - { - // switch to melee attack from ranged/magic - if (meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING)) - { - addUnitState(UNIT_STAT_MELEE_ATTACKING); - SendMeleeAttackStart(victim); - return true; - } - return false; - } - - // remove old target data - AttackStop(true); - } - - // Set our target - SetTargetGuid(victim->GetObjectGuid()); - - if (meleeAttack) - addUnitState(UNIT_STAT_MELEE_ATTACKING); - - m_attacking = victim; - m_attacking->_addAttacker(this); - - if (GetTypeId() == TYPEID_UNIT) // && !((Creature*)this)->GetLinkGroup()) - { - ((Creature*)this)->SendAIReaction(AI_REACTION_HOSTILE); - ((Creature*)this)->CallAssistance(); - } - - // delay offhand weapon attack to next attack time - if (haveOffhandWeapon()) - resetAttackTimer(OFF_ATTACK); - - if (meleeAttack) - SendMeleeAttackStart(victim); - - if (Pet* pet = GetPet()) - if (pet->isAlive()) - pet->AI()->OwnerAttacked(victim); - return true; -} - -void Unit::AttackedBy(Unit* attacker) -{ - if (Pet* pet = GetPet()) - if (pet->isAlive()) - pet->AI()->OwnerAttackedBy(attacker); - - if (!IsCreature()) - return; - - // trigger AI reaction - if (((Creature*)this)->AI()) - ((Creature*)this)->AI()->AttackedBy(attacker); - - // trigger owner AI reaction - if(Unit* owner = GetCharmerOrOwner()) - if (owner->IsCreature() && ((Creature*)owner)->AI()){ - ((Creature*)owner)->AI()->AttackedBy(attacker); - } -} - -bool Unit::AttackStop(bool targetSwitch /*=false*/) -{ - if (!m_attacking) - return false; - - Unit* victim = m_attacking; - - m_attacking->_removeAttacker(this); - m_attacking = nullptr; - - // Clear our target - SetTargetGuid(ObjectGuid()); - - clearUnitState(UNIT_STAT_MELEE_ATTACKING); - - InterruptSpell(CURRENT_MELEE_SPELL); - - // reset only at real combat stop - if (!targetSwitch) - if (Creature* me = ToCreature()) - { - me->ResetDamageTakenOrigin(); - me->SetNoCallAssistance(false); - - if (me->HasSearchedAssistance()) - { - me->SetNoSearchAssistance(false); - UpdateSpeed(MOVE_RUN, false); - } - } - - SendMeleeAttackStop(victim); - - return true; -} - -void Unit::CombatStop(bool includingCast) -{ - if (includingCast && IsNonMeleeSpellCasted(false)) - InterruptNonMeleeSpells(false); - - AttackStop(); - RemoveAllAttackers(); - - if (GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel - else if (GetTypeId() == TYPEID_UNIT) - { - ((Creature*)this)->m_TargetNotReachableTimer = 0; - if (((Creature*)this)->GetTemporaryFactionFlags() & TEMPFACTION_RESTORE_COMBAT_STOP) - ((Creature*)this)->ClearTemporaryFaction(); - } - - ClearInCombat(); -} - -struct CombatStopWithPetsHelper -{ - explicit CombatStopWithPetsHelper(bool _includingCast) : includingCast(_includingCast) {} - void operator()(Unit* unit) const - { - unit->CombatStop(includingCast); - } - bool includingCast; -}; - -void Unit::CombatStopWithPets(bool includingCast) -{ - CombatStop(includingCast); - CallForAllControlledUnits(CombatStopWithPetsHelper(includingCast), CONTROLLED_PET | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); -} - -struct IsAttackingPlayerHelper -{ - explicit IsAttackingPlayerHelper() {} - bool operator()(Unit const* unit) const - { - return unit->isAttackingPlayer(); - } -}; - -bool Unit::isAttackingPlayer() const -{ - if (hasUnitState(UNIT_STAT_ATTACK_PLAYER)) - return true; - - return CheckAllControlledUnits(IsAttackingPlayerHelper(), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); -} - -void Unit::RemoveAllAttackers() -{ - while (!m_attackers.empty()) - { - AttackerSet::iterator iter = m_attackers.begin(); - if (!(*iter)->AttackStop()) - { - sLog.outError("WORLD: Unit has an attacker that isn't attacking it!"); - m_attackers.erase(iter); - } - } -} - -void Unit::ModifyAuraState(AuraState flag, bool apply) -{ - if (apply) - { - if (!HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) - { - SetFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); - if (GetTypeId() == TYPEID_PLAYER) - { - const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap(); - for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) - { - if (itr->second.state == PLAYERSPELL_REMOVED) continue; - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(itr->first); - if (!spellInfo || !IsPassiveSpell(spellInfo)) continue; - if (AuraState(spellInfo->CasterAuraState) == flag) - CastSpell(this, itr->first, true, nullptr); - } - } - } - } - else - { - if (HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) - { - RemoveFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); - - Unit::SpellAuraHolderMap& tAuras = GetSpellAuraHolderMap(); - for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();) - { - SpellEntry const* spellProto = (*itr).second->GetSpellProto(); - if (spellProto->CasterAuraState == flag) - { - RemoveSpellAuraHolder(itr->second); - itr = tAuras.begin(); - } - else - ++itr; - } - } - } -} - -Unit *Unit::GetOwner() const -{ - if (ObjectGuid ownerid = GetOwnerGuid()) - return ObjectAccessor::GetUnit(*this, ownerid); - return nullptr; -} - -Unit *Unit::GetCharmer() const -{ - if (ObjectGuid charmerid = GetCharmerGuid()) - return ObjectAccessor::GetUnit(*this, charmerid); - return nullptr; -} - -bool Unit::IsCharmerOrOwnerPlayerOrPlayerItself() const -{ - if (GetTypeId() == TYPEID_PLAYER) - return true; - - return GetCharmerOrOwnerGuid().IsPlayer(); -} - -Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const -{ - ObjectGuid guid = GetCharmerOrOwnerGuid(); - if (guid.IsPlayer()) - return ObjectAccessor::FindPlayer(guid); - - return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL; -} - -Player* Unit::GetAffectingPlayer() const -{ - if (!GetCharmerOrOwnerGuid()) - return const_cast(this)->ToPlayer(); - - if (Unit* owner = GetCharmerOrOwner()) - return owner->GetCharmerOrOwnerPlayerOrPlayerItself(); - - return nullptr; -} - -Pet* Unit::GetPet() const -{ - if (ObjectGuid pet_guid = GetPetGuid()) - { - if (Pet* pet = GetMap()->GetPet(pet_guid)) - return pet; - - sLog.outError("Unit::GetPet: %s not exist.", pet_guid.GetString().c_str()); - const_cast(this)->SetPet(nullptr); - } - - return nullptr; -} - -Pet* Unit::_GetPet(ObjectGuid guid) const -{ - return GetMap()->GetPet(guid); -} - -Unit* Unit::GetCharm() const -{ - if (ObjectGuid charm_guid = GetCharmGuid()) - { - if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid)) - return pet; - - sLog.outError("Unit::GetCharm: Charmed %s not exist.", charm_guid.GetString().c_str()); - const_cast(this)->SetCharm(nullptr); - } - - return nullptr; -} - -void Unit::Uncharm() -{ - if (Unit* charm = GetCharm()) - { - charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM); - charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS); - charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS_PET); - } -} - -float Unit::GetCombatDistance(const Unit* target) const -{ - float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH); - float dx = GetPositionX() - target->GetPositionX(); - float dy = GetPositionY() - target->GetPositionY(); - float dz = GetPositionZ() - target->GetPositionZ(); - float dist = sqrt((dx * dx) + (dy * dy) + (dz * dz)) - radius; - return (dist > 0 ? dist : 0); -} - -float Unit::GetDistanceToCenter(const Unit* target) const -{ - float dx = GetPositionX() - target->GetPositionX(); - float dy = GetPositionY() - target->GetPositionY(); - float dz = GetPositionZ() - target->GetPositionZ(); - float dist = sqrt((dx * dx) + (dy * dy) + (dz * dz)); - return (dist > 0 ? dist : 0); -} - -void Unit::SetPet(Pet* pet) -{ - SetPetGuid(pet ? pet->GetObjectGuid() : ObjectGuid()); - if (pet) - pet->SetWorldMask(GetWorldMask()); -} - -void Unit::SetCharm(Unit* pet) -{ - SetCharmGuid(pet ? pet->GetObjectGuid() : ObjectGuid()); -} - - -void Unit::RestoreFaction() -{ - if (GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->setFactionForRace(getRace()); - else - { - if (CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo()) // normal creature - { - FactionTemplateEntry const *faction = getFactionTemplateEntry(); - setFaction((faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A); - } - } -} - -bool Unit::canAttack(Unit const* target, bool force) const -{ - ASSERT(target); - - if (force) - { - if (IsFriendlyTo(target)) - return false; - - if (GetTypeId() != TYPEID_PLAYER) - { - if (((Creature*)this)->IsPet()) - { - if (Unit *owner = GetOwner()) - if (!(owner->canAttack(target))) - return false; - } - else if (!IsHostileTo(target)) - return false; - } - } - else if (!IsHostileTo(target)) - return false; - - if (!target->isAttackableByAOE() || target->hasUnitState(UNIT_STAT_DIED)) - return false; - - // shaman totem quests: spell 8898, shaman can detect elementals but elementals cannot see shaman - if (m_invisibilityMask || target->m_invisibilityMask) - if (!canDetectInvisibilityOf(target) && !target->canDetectInvisibilityOf(this)) - return false; - - return true; -} - -void Unit::AddGuardian(Pet* pet) -{ - m_guardianPets.insert(pet->GetObjectGuid()); - pet->SetWorldMask(GetWorldMask()); // Nostalrius : phasing -} - -void Unit::RemoveGuardian(Pet* pet) -{ - m_guardianPets.erase(pet->GetObjectGuid()); -} - -void Unit::RemoveGuardians() -{ - while (!m_guardianPets.empty()) - { - ObjectGuid guid = *m_guardianPets.begin(); - - if (Pet* pet = GetMap()->GetPet(guid)) - pet->Unsummon(PET_SAVE_AS_DELETED, this); // can remove pet guid from m_guardianPets - - m_guardianPets.erase(guid); - } -} - -Pet* Unit::FindGuardianWithEntry(uint32 entry) -{ - for (GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr) - if (Pet* pet = GetMap()->GetPet(*itr)) - if (pet->GetEntry() == entry) - return pet; - - return nullptr; -} - -Unit* Unit::_GetTotem(TotemSlot slot) const -{ - return GetTotem(slot); -} - -Totem* Unit::GetTotem(TotemSlot slot) const -{ - if (slot >= MAX_TOTEM_SLOT || !IsInWorld() || !m_TotemSlot[slot]) - return nullptr; - - Creature *totem = GetMap()->GetCreature(m_TotemSlot[slot]); - return totem && totem->IsTotem() ? (Totem*)totem : NULL; -} - -bool Unit::IsAllTotemSlotsUsed() const -{ - for (int i = 0; i < MAX_TOTEM_SLOT; ++i) - if (!m_TotemSlot[i]) - return false; - return true; -} - -void Unit::_AddTotem(TotemSlot slot, Totem* totem) -{ - m_TotemSlot[slot] = totem->GetObjectGuid(); - totem->SetWorldMask(GetWorldMask()); -} - -void Unit::_RemoveTotem(Totem* totem) -{ - for (int i = 0; i < MAX_TOTEM_SLOT; ++i) - { - if (m_TotemSlot[i] == totem->GetObjectGuid()) - { - m_TotemSlot[i].Clear(); - break; - } - } -} - -void Unit::UnsummonAllTotems() -{ - for (int i = 0; i < MAX_TOTEM_SLOT; ++i) - if (Totem* totem = GetTotem(TotemSlot(i))) - totem->UnSummon(); -} - -int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical) -{ - int32 gain = pVictim->ModifyHealth(int32(addhealth)); - - Unit* unit = this; - - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) - unit = GetOwner(); - - if (unit->GetTypeId() == TYPEID_PLAYER) - unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, critical); - - return gain; -} - -Unit* Unit::SelectMagnetTarget(Unit *victim, Spell* spell, SpellEffectIndex eff) -{ - if (!victim) - return nullptr; - - SpellEntry const* pProto = spell->m_spellInfo; - if (!pProto) return nullptr; - // Example spell: Cause Insanity (Hakkar) - if (pProto->AttributesEx & SPELL_ATTR_EX_CANT_BE_REDIRECTED) - return victim; - // Magic case - - if (pProto->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) - return victim; - - if ((pProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC || pProto->SpellVisual == 7250) && pProto->Dispel != DISPEL_POISON && !(pProto->Attributes & 0x10)) - { - Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET); - for (Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr) - { - if (Unit* magnet = (*itr)->GetCaster()) - { - if (magnet->isAlive() && magnet->IsWithinLOSInMap(this) && spell->CheckTarget(magnet, eff)) - { - if (SpellAuraHolder *holder = (*itr)->GetHolder()) - if (holder->DropAuraCharge()) - { - magnet->RemoveAurasDueToSpell(holder->GetId()); // Remove from grounding totem also - victim->RemoveSpellAuraHolder(holder); - } - return magnet; - } - } - } - } - - return victim; -} - -void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical) -{ - // we guess size - WorldPacket data(SMSG_SPELLHEALLOG, (8 + 8 + 4 + 4 + 1)); - data << pVictim->GetPackGUID(); - data << GetPackGUID(); - data << uint32(SpellID); - data << uint32(Damage); - data << uint8(critical ? 1 : 0); - data << uint8(0); // unused in client? - SendMessageToSet(&data, true); -} - -void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype) -{ - WorldPacket data(SMSG_SPELLENERGIZELOG, (8 + 8 + 4 + 4 + 4 + 1)); - data << pVictim->GetPackGUID(); - data << GetPackGUID(); - data << uint32(SpellID); - data << uint32(powertype); - data << uint32(Damage); - SendMessageToSet(&data, true); -} - -void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype) -{ - SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype); - // needs to be called after sending spell log - pVictim->ModifyPower(powertype, Damage); -} - -int32 Unit::SpellBonusWithCoeffs(SpellEntry const *spellProto, int32 total, int32 benefit, int32 ap_benefit, DamageEffectType damagetype, bool donePart, Unit *pCaster, Spell* spell) -{ - // Distribute Damage over multiple effects, reduce by AoE - float coeff = 0.0f; - - // Not apply this to creature casted spells - // Daemon: n'importe quoi. Et apres on se demande pourquoi les degats du sceau du croise sont abuses ... - //if (GetTypeId()==TYPEID_UNIT && !((Creature*)this)->IsPet()) - // coeff = 1.0f; - // Check for table values - if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id)) - { - coeff = damagetype == DOT ? bonus->dot_damage : bonus->direct_damage; - - // apply ap bonus at done part calculation only (it flat total mod so common with taken) - if (donePart && (bonus->ap_bonus || bonus->ap_dot_bonus)) - { - float ap_bonus = damagetype == DOT ? bonus->ap_dot_bonus : bonus->ap_bonus; - - total += int32(ap_bonus * (GetTotalAttackPowerValue(IsSpellRequiresRangedAP(spellProto) ? RANGED_ATTACK : BASE_ATTACK) + ap_benefit)); - } - } - // Calculate default coefficient - else if (benefit) - coeff = CalculateDefaultCoefficient(spellProto, damagetype); - - if (benefit) - { - // Calculate level penalty - float LvlPenalty = CalculateLevelPenalty(spellProto); - - // Calculate custom coefficient - coeff = CalculateCustomCoefficient(spellProto, pCaster, damagetype, coeff, spell); - - // Spellmod SpellDamage - if (Player* modOwner = GetSpellModOwner()) - { - coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, coeff, spell); - coeff /= 100.0f; - } - // Nostalrius. - bool bUsePenalty = true; - // Eclair lumineux - if (spellProto->Id == 19993) - { - bUsePenalty = false; - // Libram de divinite - if (HasAura(28853)) - total += 53.0f; - } - // Lumiere sacree - //else if (spellProto->Id == 19968) - //bUsePenalty = false; - - if (bUsePenalty) - total += int32(benefit * coeff * LvlPenalty); - else - total += int32(benefit * coeff); - - } - - return total; -}; - -/** - * Calculates caster part of spell damage bonuses, - * also includes different bonuses dependent from target auras - */ -uint32 Unit::SpellDamageBonusDone(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack, Spell* spell) -{ - if (!spellProto || !pVictim || damagetype == DIRECT_DAMAGE) - return pdamage; - - // Ignite damage already includes modifiers - if (spellProto->IsFitToFamily()) - return pdamage; - - // For totems get damage bonus from owner (statue isn't totem in fact) - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) - { - if (Unit* owner = GetOwner()) - return owner->SpellDamageBonusDone(pVictim, spellProto, pdamage, damagetype, stack, spell); - } - - float DoneTotalMod = 1.0f; - int32 DoneTotal = 0; - Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(BASE_ATTACK, true, false) : NULL; - - // Creature damage - if (GetTypeId() == TYPEID_UNIT && !((Creature*)this)->IsPet()) - DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank); - - AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); - for (AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) - { - if (((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) && - (*i)->GetSpellProto()->EquippedItemClass == -1 && - // -1 == any item class (not wand then) - (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) - // 0 == any inventory type (not wand then) - DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; - - // Paladin seals benefit from weapon modifiers - else if ((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && - spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && spellProto->IsFitToFamilyMask() && - (((*i)->GetSpellProto()->EquippedItemClass == -1) || - (pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto())))) - DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; - } - - uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); - - // Add pct bonus from spell damage versus - DoneTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask); - - // Add flat bonus from spell damage creature - DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask); - - // done scripted mod (take it from owner) - Unit *owner = GetOwner(); - if (!owner) owner = this; - AuraList const& mOverrideClassScript = owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); - for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) - { - if (!(*i)->isAffectedOnSpell(spellProto)) - continue; - switch ((*i)->GetModifier()->m_miscvalue) - { - case 4418: // Increased Shock Damage - case 4554: // Increased Lightning Damage - case 4555: // Improved Moonfire - { - DoneTotal += (*i)->GetModifier()->m_amount; - break; - } - } - } - - // Pet happiness increases damage of Hunter pet spells (e.g. Lightning Breath) - if (IsPet() && ((Pet*)this)->getPetType() == HUNTER_PET) - { - if (Pet* pet = ((Pet*)this)) - { - switch (pet->GetHappinessState()) - { - case HAPPY: DoneTotalMod *= 1.25; break; - case CONTENT: break; - case UNHAPPY: DoneTotalMod *= 0.75; break; - } - } - } - - // Done fixed damage bonus auras - int32 DoneAdvertisedBenefit = SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)); - - // Add flat bonus from spell damage versus - DoneAdvertisedBenefit += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask); - - // Pets just add their bonus damage to their spell damage - // note that their spell damage is just gain of their own auras - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) - DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage(); - - // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties - DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true, this, spell); - - float tmpDamage = (int32(pdamage) + DoneTotal * int32(stack)) * DoneTotalMod; - // apply spellmod to Done damage (flat and pct) - if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage, spell); - - DEBUG_UNIT(this, DEBUG_SPELLS_DAMAGE, "SpellDmgBonus[spell=%u]: (base=%u + %i) * %f. SP=%i", spellProto->Id, pdamage, DoneTotal, DoneTotalMod, DoneAdvertisedBenefit); - return tmpDamage > 0 ? uint32(tmpDamage) : 0; -} - -/** - * Calculates target part of spell damage bonuses, - * will be called on each tick for periodic damage over time auras - */ -uint32 Unit::SpellDamageBonusTaken(Unit *pCaster, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack, Spell* spell) -{ - if (!spellProto || !pCaster || damagetype == DIRECT_DAMAGE) - return pdamage; - - uint32 schoolMask = spell ? spell->m_spellSchoolMask : GetSpellSchoolMask(spellProto); - - // Taken total percent damage auras - float TakenTotalMod = 1.0f; - int32 TakenTotal = 0; - - // ..taken - TakenTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask); - - // Taken fixed damage bonus auras - int32 TakenAdvertisedBenefit = SpellBaseDamageBonusTaken(GetSpellSchoolMask(spellProto)); - - // apply benefit affected by spell power implicit coeffs and spell level penalties - TakenTotal = SpellBonusWithCoeffs(spellProto, TakenTotal, TakenAdvertisedBenefit, 0, damagetype, false, pCaster, spell); - - float tmpDamage = (int32(pdamage) + TakenTotal * int32(stack)) * TakenTotalMod; - - return tmpDamage > 0 ? uint32(tmpDamage) : 0; -} - -int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) -{ - int32 DoneAdvertisedBenefit = 0; - - // ..done - AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE); - for (AuraList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i) - { - if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 && - (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then) - (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then) - DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount; - } - - if (GetTypeId() == TYPEID_PLAYER) - { - // Damage bonus from stats - AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT); - for (AuraList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i) - { - if ((*i)->GetModifier()->m_miscvalue & schoolMask) - { - // stat used stored in miscValueB for this aura - Stats usedStat = STAT_SPIRIT; - DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f); - } - } - } - return DoneAdvertisedBenefit; -} - -int32 Unit::SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask) -{ - int32 TakenAdvertisedBenefit = 0; - - // ..taken - AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN); - for (AuraList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) - { - if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0) - TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount; - } - - return TakenAdvertisedBenefit; -} - -bool Unit::IsSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType, Spell* spell) -{ - ASSERT(pVictim); - // Les mobs ne peuvent pas critiquer avec les sorts. Mais totems et pets peuvent. - if (GetTypeId() == TYPEID_UNIT && !GetOwnerGuid().IsPlayer()) - return false; - - if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_ALWAYS_CRIT)) - return true; - - // not critting spell - if ((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT)) - return false; - - float crit_chance = 0.0f; - // Les potions/pierres de soin peuvent critiquer avec un pourcentage de chance constant - if (spellProto->SpellFamilyName == SPELLFAMILY_POTION || - (spellProto->IsFitToFamily())) - crit_chance = 10.0f; - else - { - switch (spellProto->DmgClass) - { - case SPELL_DAMAGE_CLASS_NONE: - return false; - case SPELL_DAMAGE_CLASS_MAGIC: - { - if (schoolMask & SPELL_SCHOOL_MASK_NORMAL) - crit_chance = 0.0f; - // For other schools - else if (GetTypeId() == TYPEID_PLAYER) - crit_chance = ((Player*)this)->m_SpellCritPercentage[GetFirstSchoolInMask(schoolMask)]; - else - { - crit_chance = float(m_baseSpellCritChance); - crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); - } - // taken - if (!IsPositiveSpell(spellProto->Id)) - { - // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE - crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); - } - - // scripted (increase crit chance ... against ... target by x% - AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); - for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) - { - if (!((*i)->GetSpellProto()->SpellFamilyName == spellProto->SpellFamilyName)) - continue; - switch ((*i)->GetModifier()->m_miscvalue) - { - // Shatter - case 849: - if (pVictim->isFrozen()) crit_chance += 10.0f; - break; - case 910: - if (pVictim->isFrozen()) crit_chance += 20.0f; - break; - case 911: - if (pVictim->isFrozen()) crit_chance += 30.0f; - break; - case 912: - if (pVictim->isFrozen()) crit_chance += 40.0f; - break; - case 913: - if (pVictim->isFrozen()) crit_chance += 50.0f; - break; - default: - break; - } - } - break; - } - case SPELL_DAMAGE_CLASS_MELEE: - case SPELL_DAMAGE_CLASS_RANGED: - { - // Joueurs assis = critique obligatoire. - if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->IsSitState()) - return true; - crit_chance = GetUnitCriticalChance(attackType, pVictim); - crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); - break; - } - default: - return false; - } - } - // percent done - // only players use intelligence for critical chance computations - if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance, spell); - - crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f; - - DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "%s [ID:%u] Crit chance %f.", spellProto->SpellName[2], spellProto->Id, crit_chance); - - if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || - (pVictim->IsPlayer() && pVictim->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) - crit_chance = 0; - if (roll_chance_f(crit_chance)) - return true; - return false; -} - -uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim, Spell* spell) -{ - // Calculate critical bonus - int32 crit_bonus; - switch (spellProto->DmgClass) - { - case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100% - case SPELL_DAMAGE_CLASS_RANGED: - crit_bonus = damage; - break; - default: - crit_bonus = damage / 2; // for spells is 50% - break; - } - - // adds additional damage to crit_bonus (from talents) - if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus, spell); - - if (!pVictim) - return damage += crit_bonus; - - uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); - - float critPctDamageMod = GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask); - - damage = (damage + crit_bonus) * critPctDamageMod; - - return damage; -} - -uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim) -{ - // Calculate critical bonus - int32 crit_bonus; - switch (spellProto->DmgClass) - { - case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100% - case SPELL_DAMAGE_CLASS_RANGED: - // TODO: write here full calculation for melee/ranged spells - crit_bonus = damage; - break; - default: - crit_bonus = damage / 2; // for spells is 50% - break; - } - - if (pVictim) - { - uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); - crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask)); - } - - if (crit_bonus > 0) - damage += crit_bonus; - - return damage; -} - -/** - * Calculates caster part of healing spell bonuses, - * also includes different bonuses dependent from target auras - */ -uint32 Unit::SpellHealingBonusDone(Unit *pVictim, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack, Spell* spell) -{ - // For totems get healing bonus from owner (statue isn't totem in fact) - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) - if (Unit* owner = GetOwner()) - return owner->SpellHealingBonusDone(pVictim, spellProto, healamount, damagetype, stack, spell); - - // No heal amount for this class spells - if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->Custom & SPELL_CUSTOM_FIXED_DAMAGE) - { - DEBUG_UNIT(this, DEBUG_SPELLS_DAMAGE, "SpellHealingBonusDone[spell=%u]: has fixed damage (SPELL_DAMAGE_CLASS_NONE)", spellProto->Id); - return healamount < 0 ? 0 : healamount; - } - // Healing Done - // Done total percent damage auras - float DoneTotalMod = 1.0f; - int32 DoneTotal = 0; - - // Healing done percent - AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT); - for (AuraList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i) - DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; - - // done scripted mod (take it from owner) - Unit *owner = GetOwner(); - if (!owner) - owner = this; - AuraList const& mOverrideClassScript = owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); - for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) - { - if (!(*i)->isAffectedOnSpell(spellProto)) - continue; - switch ((*i)->GetModifier()->m_miscvalue) - { - case 4415: // Increased Rejuvenation Healing - DoneTotal += (*i)->GetModifier()->m_amount / 4; // 4 ticks - break; - case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / Savage Totem of the Third Wind - DoneTotal += (*i)->GetModifier()->m_amount; - break; - default: - break; - } - } - - // Done fixed damage bonus auras - int32 DoneAdvertisedBenefit = SpellBaseHealingBonusDone(GetSpellSchoolMask(spellProto)); - - // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties - DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true, this, spell); - - // use float as more appropriate for negative values and percent applying - float heal = (healamount + DoneTotal * int32(stack)) * DoneTotalMod; - // apply spellmod to Done amount - if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal, spell); - - DEBUG_UNIT(this, DEBUG_SPELLS_DAMAGE, "SpellHealingBonusDone[spell=%u]: (base=%u + %i) * %f. HealingPwr=%i", spellProto->Id, healamount, DoneTotal, DoneTotalMod, DoneAdvertisedBenefit); - return heal < 0 ? 0 : uint32(heal); -} - -/** - * Calculates target part of healing spell bonuses, - * will be called on each tick for periodic damage over time auras - */ -uint32 Unit::SpellHealingBonusTaken(Unit *pCaster, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack, Spell* spell) -{ - float TakenTotalMod = 1.0f; - - // Healing taken percent - float minval = float(GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT)); - if (minval) - TakenTotalMod *= (100.0f + minval) / 100.0f; - - float maxval = float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT)); - if (maxval) - TakenTotalMod *= (100.0f + maxval) / 100.0f; - - // No heal amount for this class spells - if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE) - { - healamount = int32(healamount * TakenTotalMod); - return healamount < 0 ? 0 : healamount; - } - - // Healing Done - // Done total percent damage auras - int32 TakenTotal = 0; - - // Taken fixed damage bonus auras - int32 TakenAdvertisedBenefit = SpellBaseHealingBonusTaken(GetSpellSchoolMask(spellProto)); - - // Blessing of Light dummy effects healing taken from Holy Light and Flash of Light - if (spellProto->IsFitToFamily()) - { - AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY); - for (AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) - { - // Libram of Divinity - if ((*i)->GetSpellProto()->Id == 28851 && spellProto->IsFitToFamilyMask()) - TakenTotal += (*i)->GetModifier()->m_amount; - if ((*i)->GetSpellProto()->IsFitToFamilyMask() && (*i)->GetSpellProto()->SpellVisual == 300) - { - // Holy Light - if (spellProto->IsFitToFamilyMask() && (*i)->GetEffIndex() == EFFECT_INDEX_0) - TakenTotal += (*i)->GetModifier()->m_amount; - // Flash of Light - else if (spellProto->IsFitToFamilyMask() && (*i)->GetEffIndex() == EFFECT_INDEX_1) - TakenTotal += (*i)->GetModifier()->m_amount; - } - } - } - // apply benefit affected by spell power implicit coeffs and spell level penalties - TakenTotal = SpellBonusWithCoeffs(spellProto, TakenTotal, TakenAdvertisedBenefit, 0, damagetype, false, pCaster, spell); - - // Taken mods - // Healing Wave cast - if (spellProto->IsFitToFamily()) - { - // Search for Healing Way on Victim - Unit::AuraList const& auraDummy = GetAurasByType(SPELL_AURA_DUMMY); - for (Unit::AuraList::const_iterator itr = auraDummy.begin(); itr != auraDummy.end(); ++itr) - if ((*itr)->GetId() == 29203) - TakenTotalMod *= ((*itr)->GetModifier()->m_amount + 100.0f) / 100.0f; - } - - - // use float as more appropriate for negative values and percent applying - float heal = (healamount + TakenTotal * int32(stack)) * TakenTotalMod; - - return heal < 0 ? 0 : uint32(heal); -} - -int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) -{ - int32 AdvertisedBenefit = 0; - - AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE); - for (AuraList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i) - if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0) - AdvertisedBenefit += (*i)->GetModifier()->m_amount; - - // Healing bonus of spirit, intellect and strength - if (GetTypeId() == TYPEID_PLAYER) - { - // Healing bonus from stats - AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT); - for (AuraList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i) - { - // 1.12.* have only 1 stat type support - Stats usedStat = STAT_SPIRIT; - AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f); - } - } - return AdvertisedBenefit; -} - -int32 Unit::SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask) -{ - int32 AdvertisedBenefit = 0; - AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_HEALING); - for (AuraList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) - if ((*i)->GetModifier()->m_miscvalue & schoolMask) - AdvertisedBenefit += (*i)->GetModifier()->m_amount; - - return AdvertisedBenefit; -} - -bool Unit::IsImmuneToDamage(SpellSchoolMask shoolMask) -{ - // If m_immuneToSchool type contain this school type, IMMUNE damage. - SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL]; - for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) - if (itr->type & shoolMask) - return true; - - // If m_immuneToDamage type contain magic, IMMUNE damage. - SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE]; - for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr) - if (itr->type & shoolMask) - return true; - - return false; -} - -bool Unit::IsImmuneToSpell(SpellEntry const *spellInfo, bool /*castOnSelf*/) -{ - if (!spellInfo) - return false; - - //TODO add spellEffect immunity checks!, player with flag in bg is immune to immunity buffs from other friendly players! - //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT]; - - SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL]; - for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr) - if (itr->type == spellInfo->Dispel) - return true; - - if ( !(spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) // ignore invulnerability - && !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) // unaffected by school immunity - && !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it) - { - SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL]; - for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) - if (!(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) && - (itr->type & GetSpellSchoolMask(spellInfo))) - return true; - } - - if (uint32 mechanic = spellInfo->Mechanic) - { - SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC]; - for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr) - { - if (itr->type == mechanic) - { - // always remove Fear Ward on fear immunity event, even if the unit has another fear immunity aura like Berserker Rage - if (mechanic == MECHANIC_FEAR) - RemoveAurasDueToSpell(6346); - return true; - } - } - - AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK); - for (AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter) - if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic - 1))) - return true; - } - - return false; -} - -bool Unit::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index, bool /*castOnSelf*/) const -{ - //If m_immuneToEffect type contain this effect type, IMMUNE effect. - uint32 effect = spellInfo->Effect[index]; - SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT]; - for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr) - if (itr->type == effect) - return true; - - if (uint32 mechanic = spellInfo->EffectMechanic[index]) - { - SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC]; - for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr) - if (itr->type == spellInfo->EffectMechanic[index]) - return true; - - AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK); - for (AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter) - if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic - 1))) - return true; - } - - uint32 aura = spellInfo->EffectApplyAuraName[index]; - if (aura) - { - SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE]; - for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr) - if (itr->type == aura) - return true; - } - return false; -} - -/** - * Calculates caster part of melee damage bonuses, - * also includes different bonuses dependent from target auras - */ -uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackType attType, SpellEntry const* spellProto, DamageEffectType damagetype, uint32 stack, Spell* spell, bool flat) -{ - if (!pVictim) - return pdamage; - - if (pdamage == 0) - return pdamage; - - // differentiate for weapon damage based spells - bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE))); - Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(attType, true, false) : NULL; - uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); - uint32 schoolMask = spellProto ? GetSpellSchoolMask(spellProto) : GetMeleeDamageSchoolMask(); - - // FLAT damage bonus auras - // ======================= - int32 DoneFlat = 0; - int32 APbonus = 0; - - // ..done flat, already included in weapon damage based spells - if (!isWeaponDamageBasedSpell) - { - AuraList const& mModDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE); - for (AuraList::const_iterator i = mModDamageDone.begin(); i != mModDamageDone.end(); ++i) - { - if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school - ((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() || // AND schoolmask has to fit with weapon damage school (essential for non-physical spells) - spellProto->DmgClass == SPELL_DAMAGE_CLASS_RANGED) && // Some ranged physical attacks use magic damage, ex. Arcane Shot - (((*i)->GetSpellProto()->EquippedItemClass == -1) || // general, weapon independent - (pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto())))) // OR used weapon fits aura requirements - DoneFlat += (*i)->GetModifier()->m_amount; - } - - // Pets just add their bonus damage to their melee damage - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) - DoneFlat += ((Pet*)this)->GetBonusDamage(); - } - - // ..done flat (by creature type mask) - DoneFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask); - - // ..done flat (base at attack power for marked target and base at attack power for creature type) - if (attType == RANGED_ATTACK) - { - APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS); - APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS, creatureTypeMask); - } - else - { - APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS); - APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS, creatureTypeMask); - } - - // PERCENT damage auras - // ==================== - float DonePercent = 1.0f; - - // ..done pct, already included in weapon damage based spells - if (!isWeaponDamageBasedSpell) - { - AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); - for (AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) - { - if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school - (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells) - (((*i)->GetSpellProto()->EquippedItemClass == -1) || // general, weapon independent - (pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto())))) // OR used weapon fits aura requirements - DonePercent *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; - } - - if (attType == OFF_ATTACK) - DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required - } - - // Pet happiness increases damage of Hunter pet melee spells - if (IsPet() && ((Pet*)this)->getPetType() == HUNTER_PET) - { - if (Pet* pet = ((Pet*)this)) - { - switch (pet->GetHappinessState()) - { - case HAPPY: DonePercent *= 1.25; break; - case CONTENT: break; - case UNHAPPY: DonePercent *= 0.75; break; - } - } - } - - // ..done pct (by creature type mask) - DonePercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask); - - // special dummys/class scripts and other effects - // ============================================= - Unit *owner = GetOwner(); - if (!owner) - owner = this; - - // final calculation - // ================= - - float DoneTotal = 0.0f; - - // scaling of non weapon based spells - if (!isWeaponDamageBasedSpell) - { - // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties - DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneFlat, APbonus, damagetype, true, this, spell); - } - // weapon damage based spells - else if (APbonus || DoneFlat) - { - bool normalized = spellProto ? IsSpellHaveEffect(spellProto, SPELL_EFFECT_NORMALIZED_WEAPON_DMG) : false; - DoneTotal += int32(APbonus / 14.0f * GetAPMultiplier(attType, normalized)); - - // for weapon damage based spells we still have to apply damage done percent mods - // (that are already included into pdamage) to not-yet included DoneFlat - // e.g. from doneVersusCreature, apBonusVs... - UnitMods unitMod; - switch (attType) - { - default: - case BASE_ATTACK: - unitMod = UNIT_MOD_DAMAGE_MAINHAND; - break; - case OFF_ATTACK: - unitMod = UNIT_MOD_DAMAGE_OFFHAND; - break; - case RANGED_ATTACK: - unitMod = UNIT_MOD_DAMAGE_RANGED; - break; - } - - DoneTotal += DoneFlat; - - DoneTotal *= GetModifierValue(unitMod, TOTAL_PCT); - } - - if (!flat) - DoneTotal = 0.0f; - - float tmpDamage = float(int32(pdamage) + DoneTotal * int32(stack)) * DonePercent; - - // apply spellmod to Done damage - if (spellProto) - { - if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage, spell); - } - - // bonus result can be negative - return tmpDamage > 0 ? uint32(tmpDamage) : 0; -} - -/** - * Calculates target part of melee damage bonuses, - * will be called on each tick for periodic damage over time auras - */ -uint32 Unit::MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage, WeaponAttackType attType, SpellEntry const* spellProto, DamageEffectType damagetype, uint32 stack, Spell* spell, bool flat) -{ - if (!pCaster) - return pdamage; - - if (pdamage == 0) - return pdamage; - - // Exception for Seal of Command and Seal of Righteousness - // already with coeff! - if (spellProto && (spellProto->Id == 20424 || - (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && spellProto->DmgClass == SPELL_DAMAGE_CLASS_MELEE))) // SoR is the only pala spell with melee dmg class - return pdamage; - - // differentiate for weapon damage based spells - bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE))); - uint32 schoolMask = spellProto ? GetSpellSchoolMask(spellProto) : uint32(pCaster->GetMeleeDamageSchoolMask()); - - // FLAT damage bonus auras - // ======================= - int32 TakenFlat = 0; - - // ..taken flat (base at attack power for marked target and base at attack power for creature type) - if (attType == RANGED_ATTACK) - TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN); - else - TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN); - - // ..taken flat (by school mask) - TakenFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask); - - // PERCENT damage auras - // ==================== - float TakenPercent = 1.0f; - - // ..taken pct (by school mask) - TakenPercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask); - - // ..taken pct (melee/ranged) - if (attType == RANGED_ATTACK) - TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT); - else - TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT); - - // final calculation - // ================= - - // scaling of non weapon based spells - if (!isWeaponDamageBasedSpell) - { - // apply benefit affected by spell power implicit coeffs and spell level penalties - TakenFlat = SpellBonusWithCoeffs(spellProto, 0, TakenFlat, 0, damagetype, false, pCaster, spell); - } - - if (!flat) - TakenFlat = 0.0f; - - float tmpDamage = float(int32(pdamage) + TakenFlat * int32(stack)) * TakenPercent; - - // bonus result can be negative - return tmpDamage > 0 ? uint32(tmpDamage) : 0; -} - -void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply) -{ - if (apply) - { - for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next) - { - next = itr; - ++next; - if (itr->type == type) - { - m_spellImmune[op].erase(itr); - next = m_spellImmune[op].begin(); - } - } - SpellImmune Immune; - Immune.spellId = spellId; - Immune.type = type; - m_spellImmune[op].push_back(Immune); - } - else - { - for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr) - { - if (itr->spellId == spellId) - { - m_spellImmune[op].erase(itr); - break; - } - } - } -} - -void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply) -{ - ApplySpellImmune(spellProto->Id, IMMUNITY_DISPEL, type, apply); - - if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY) - RemoveAurasWithDispelType(type); -} - -float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const -{ - // proc per minute chance calculation - if (PPM <= 0.0f) - return 0.0f; - return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60)) -} - -void Unit::Mount(uint32 mount, uint32 spellId) -{ - if (!mount) - return; - - if (SpellAuraHolder *holder = GetSpellAuraHolder(29519)) - { - if (((Player*)this)->GetZoneId() == 1377) - { - // OutdoorPVP Silithus : Perte du buff silithyste - if (ZoneScript* pScript = ((Player*)this)->GetZoneScript()) - pScript->HandleDropFlag(((Player*)this), 29519); - } - } - - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING); - SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount); - - if (GetTypeId() == TYPEID_PLAYER) - { - // Called by Taxi system / GM command - if (!spellId) - ((Player*)this)->UnsummonPetTemporaryIfAny(); - // Called by mount aura - else - { - // Normal case (Unsummon only permanent pet) - if (Pet* pet = GetPet()) - { - if (pet->IsPermanentPetFor((Player*)this) && - sWorld.getConfig(CONFIG_BOOL_PET_UNSUMMON_AT_MOUNT)) - ((Player*)this)->UnsummonPetTemporaryIfAny(); - else - pet->SetEnabled(false); - } - } - } -} - -void Unit::Unmount(bool from_aura) -{ - if (!IsMounted()) - return; - - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED); - - SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0); - - // only resummon old pet if the player is already added to a map - // this prevents adding a pet to a not created map which would otherwise cause a crash - // (it could probably happen when logging in after a previous crash) - if (GetTypeId() == TYPEID_PLAYER) - { - if (Pet* pet = GetPet()) - pet->SetEnabled(true); - else - ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny(); - } -} - -void Unit::SetInCombatWith(Unit* enemy) -{ - ASSERT(enemy); - Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf(); - ASSERT(eOwner); - if (eOwner->IsPvP()) - { - SetInCombatState(true, enemy); - return; - } - - //check for duel - if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel) - { - if (Player const* myOwner = GetCharmerOrOwnerPlayerOrPlayerItself()) - { - if (myOwner->IsInDuelWith((Player const*)eOwner)) - { - SetInCombatState(true, enemy); - return; - } - } - } - - SetInCombatState(false, enemy); -} - -void Unit::SetInCombatState(bool PvP, Unit* enemy) -{ - // only alive units can be in combat - if (!isAlive()) - return; - - if (PvP) - m_CombatTimer = 5500; - - bool wasInCombat = isInCombat(); - bool creatureNotInCombat = GetTypeId() == TYPEID_UNIT && !wasInCombat; - - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); - - if (isCharmed() || (GetTypeId() != TYPEID_PLAYER && ((Creature*)this)->IsPet())) - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); - // set pet in combat - if (Pet* pet = GetPet()) - pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); - - // interrupt all delayed non-combat casts - if (!wasInCombat) - for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) - if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) - if (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) - if (IsNonCombatSpell(spell->m_spellInfo)) - InterruptSpell(CurrentSpellTypes(i), false); - - if (creatureNotInCombat) - { - auto pCreature = ToCreature(); - - pCreature->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ()); - // should probably be removed for the attacked (+ it's party/group) only, not global - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); - - OnEnterCombat(enemy, true); - - // Some bosses are set into combat with zone - if (GetMap()->IsDungeon() && (pCreature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_AGGRO_ZONE) && enemy && enemy->IsControlledByPlayer()) - pCreature->SetInCombatWithZone(); - if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL]) - if (spell->getState() == SPELL_STATE_CASTING) - if (spell->m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_ENTER_COMBAT) - InterruptSpell(CURRENT_CHANNELED_SPELL); - } -} - -void Unit::ClearInCombat() -{ - m_CombatTimer = 0; - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); - - // Player's state will be cleared in Player::UpdateContestedPvP - if (GetTypeId() != TYPEID_PLAYER) - { - if (((Creature*)this)->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE) - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); - - clearUnitState(UNIT_STAT_ATTACK_PLAYER); - } - - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); -} - -bool Unit::isTargetableForAttack(bool inverseAlive /*=false*/) const -{ - if (!CanBeDetected()) - return false; - - if (GetTypeId() == TYPEID_PLAYER && (((Player *)this)->isGameMaster() || ((Player*)this)->watching_cinematic_entry != 0)) - return false; - - if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE)) - return false; - - // to be removed if unit by any reason enter combat - if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE)) - return false; - - // inversealive is needed for some spells which need to be casted at dead targets (aoe) - if (isAlive() == inverseAlive) - return false; - - return IsInWorld() && !hasUnitState(UNIT_STAT_DIED) && !IsTaxiFlying(); -} - -bool Unit::IsValidAttackTarget(Unit const* target) const -{ - return _IsValidAttackTarget(target, nullptr); -} - -// function based on function Unit::CanAttack from 13850 client -bool Unit::_IsValidAttackTarget(Unit const* target, SpellEntry const* bySpell, WorldObject const* obj) const -{ - ASSERT(target); - // can't attack self - if (this == target) - return false; - - if (FindMap() != target->FindMap()) - return false; - - // can't attack unattackable units or GMs - if (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster()) - return false; - - // check flags - if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_TAXI_FLIGHT | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_UNK_16)) - return false; - - // CvC case - can attack each other only when one of them is hostile - if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) - return GetReactionTo(target) <= REP_HOSTILE || target->GetReactionTo(this) <= REP_HOSTILE; - - // PvP, PvC, CvP case - // can't attack friendly targets - if (GetReactionTo(target) > REP_NEUTRAL - || target->GetReactionTo(this) > REP_NEUTRAL) - return false; - - Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : NULL; - Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : NULL; - - // Not all neutral creatures can be attacked - if (GetReactionTo(target) == REP_NEUTRAL && - target->GetReactionTo(this) == REP_NEUTRAL) - { - if (!(playerAffectingTarget && playerAffectingAttacker) && - !(!playerAffectingTarget && !playerAffectingAttacker)) - { - Player const* player = playerAffectingTarget ? playerAffectingTarget : playerAffectingAttacker; - Unit const* creature = playerAffectingTarget ? this : target; - - if (FactionTemplateEntry const* factionTemplate = creature->getFactionTemplateEntry()) - { - if (!(player->GetReputationMgr().GetForcedRankIfAny(factionTemplate))) - if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction)) - if (FactionState const* repState = player->GetReputationMgr().GetState(factionEntry)) - if (!(repState->Flags & FACTION_FLAG_AT_WAR)) - return false; - - } - } - } - - // PvP checks - if (playerAffectingAttacker && playerAffectingTarget) - { - if (playerAffectingAttacker->duel && playerAffectingAttacker->duel->opponent == playerAffectingTarget && playerAffectingAttacker->duel->startTime != 0) - return true; - - if (playerAffectingTarget->IsPvP()) - return true; - - if (playerAffectingAttacker->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP - && playerAffectingTarget->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) - return true; - - return (playerAffectingAttacker->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1) - || (playerAffectingTarget->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1); - } - return true; -} - -int32 Unit::ModifyHealth(int32 dVal) -{ - int32 gain = 0; - - if (dVal == 0) - return 0; - - int32 curHealth = (int32)GetHealth(); - - int32 val = dVal + curHealth; - if (val <= 0) - { - SetHealth(0); - return -curHealth; - } - - int32 maxHealth = (int32)GetMaxHealth(); - - if (val < maxHealth) - { - SetHealth(val); - gain = val - curHealth; - } - else if (curHealth != maxHealth) - { - SetHealth(maxHealth); - gain = maxHealth - curHealth; - } - - return gain; -} - -int32 Unit::ModifyPower(Powers power, int32 dVal) -{ - int32 gain = 0; - - if (dVal == 0) - return 0; - - int32 curPower = (int32)GetPower(power); - - int32 val = dVal + curPower; - if (val <= 0) - { - SetPower(power, 0); - return -curPower; - } - - int32 maxPower = (int32)GetMaxPower(power); - - if (val < maxPower) - { - SetPower(power, val); - gain = val - curPower; - } - else if (curPower != maxPower) - { - SetPower(power, maxPower); - gain = maxPower - curPower; - } - - return gain; -} - -bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool /*inVisibleList*/, bool* alert) const -{ - if (!u || !IsInMap(u)) - return false; - - // Always can see self - if (u == this) - return true; - - bool at_same_transport = GetTransport() && GetTransport() == u->GetTransport(); - - // not in world - if (!at_same_transport && (!IsInWorld() || !u->IsInWorld())) - return false; - - // forbidden to seen (at GM respawn command) - if (m_Visibility == VISIBILITY_RESPAWN) - return false; - - Map& _map = *u->GetMap(); - bool isTargetPlayer = u->GetTypeId() == TYPEID_PLAYER; - auto pPlayerTarget = isTargetPlayer ? (Player*)u : nullptr; - - // Grid dead/alive checks - if (isTargetPlayer) - { - // non visible at grid for any stealth state - if (!IsVisibleInGridForPlayer(pPlayerTarget)) - return false; - - // if player is dead then he can't detect anyone in any cases - if (!u->isAlive()) - detect = false; - } - else - { - // all dead creatures/players not visible for any creatures - if (!u->isAlive() || !isAlive()) - return false; - } - - // always seen by owner - if (GetCharmerOrOwnerGuid() == u->GetObjectGuid()) - return true; - - // isInvisibleForAlive() those units can only be seen by dead or if other - // unit is also invisible for alive.. if an isinvisibleforalive unit dies we - // should be able to see it too - if (u->isAlive() && isAlive() && isInvisibleForAlive() != u->isInvisibleForAlive()) - if (!isTargetPlayer || !pPlayerTarget->isGameMaster()) - return false; - - // redundant phasing - //if (!u->CanSeeInWorld(this)) - // return false; - - if (Creature* pCreature = (Creature*)ToCreature()) - { - bool bVisible = false; - if (pCreature->AI() && pCreature->AI()->IsVisibleFor(u, bVisible)) - return bVisible; - } - - // Visible units, always are visible for all units, except for units under invisibility - if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask == 0) - return true; - - // GMs see any players, not higher GMs and all units - if (isTargetPlayer && pPlayerTarget->isGameMaster()) - { - if (GetTypeId() == TYPEID_PLAYER) - return ToPlayer()->GetGMInvisibilityLevel() <= uint8(pPlayerTarget->GetSession()->GetSecurity()); - return true; - } - - // non faction visibility non-breakable for non-GMs - if (m_Visibility == VISIBILITY_OFF) - return false; - - // raw invisibility - bool invisible = m_invisibilityMask != 0; - - // detectable invisibility case - if (invisible && ( - // Invisible units, always are visible for units under same invisibility type - m_invisibilityMask & u->m_invisibilityMask || - // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect) - u->canDetectInvisibilityOf(this) || - // Units that can detect invisibility always are visible for units that can be detected - canDetectInvisibilityOf(u))) - invisible = false; - - // special cases for always overwrite invisibility/stealth - if (invisible || m_Visibility == VISIBILITY_GROUP_STEALTH) - { - // non-hostile case - if (!u->IsHostileTo(this)) - { - // player see other player with stealth/invisibility only if he in same group or raid or same team (raid/team case dependent from conf setting) - if (GetTypeId() == TYPEID_PLAYER && isTargetPlayer) - { - if (((Player*)this)->IsGroupVisibleFor(pPlayerTarget)) - return true; - - // else apply same rules as for hostile case (detecting check for stealth) - } - } - - // none other cases for detect invisibility, so invisible - if (invisible) - return false; - - // else apply stealth detecting check - } - - // unit got in stealth in this moment and must ignore old detected state - if (m_Visibility == VISIBILITY_GROUP_NO_DETECT) - return false; - - // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible - if (m_Visibility != VISIBILITY_GROUP_STEALTH) - return true; - - // NOW ONLY STEALTH CASE - //if in non-detect mode then invisible for unit - //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false) - //players detect players only in Player::HandleStealthedUnitsDetection() - // Units detect Units only in Units::HandleStealthedUnitsDetection() - if (!detect) - return isTargetPlayer ? pPlayerTarget->IsInVisibleList(this) : false; - - // Special cases - if (!u->canDetectStealthOf(this, GetDistance(viewPoint), alert)) - return false; - - // Now check if target is visible with LoS - float ox, oy, oz; - viewPoint->GetPosition(ox, oy, oz); - return IsWithinLOS(ox, oy, oz); -} - -void Unit::UpdateVisibilityAndView() -{ - - static const AuraType auratypes[] = {SPELL_AURA_BIND_SIGHT, SPELL_AURA_FAR_SIGHT, SPELL_AURA_NONE}; - for (AuraType const* type = &auratypes[0]; *type != SPELL_AURA_NONE; ++type) - { - AuraList& alist = m_modAuras[*type]; - if (alist.empty()) - continue; - - for (AuraList::iterator it = alist.begin(); it != alist.end();) - { - Aura* aura = (*it); - Unit* owner = aura->GetCaster(); - - if (!owner || !isVisibleForOrDetect(owner, this, false)) - { - alist.erase(it); - RemoveAura(aura); - it = alist.begin(); - } - else - ++it; - } - } - - GetViewPoint().Call_UpdateVisibilityForOwner(); - UpdateObjectVisibility(); - ScheduleAINotify(0); - GetViewPoint().Event_ViewPointVisibilityChanged(); -} - -void Unit::SetVisibility(UnitVisibility x) -{ - m_Visibility = x; - - if (IsInWorld()) - UpdateVisibilityAndView(); -} - -bool Unit::canDetectInvisibilityOf(Unit const* u) const -{ - if (!u->m_invisibilityMask && m_detectInvisibilityMask) - return true; - - if (const Creature* worldBoss = u->ToCreature()) - if (worldBoss->IsWorldBoss()) - return true; - - if (uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask)) - { - for (int32 i = 0; i < 32; ++i) - { - if (((1 << i) & mask) == 0) - continue; - - // find invisibility level - int32 invLevel = 0; - Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY); - for (Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr) - if ((*itr)->GetModifier()->m_miscvalue == i && invLevel < (*itr)->GetModifier()->m_amount) - invLevel = (*itr)->GetModifier()->m_amount; - - // find invisibility detect level - int32 detectLevel = 0; - Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION); - for (Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr) - if ((*itr)->GetModifier()->m_miscvalue == i && detectLevel < (*itr)->GetModifier()->m_amount) - detectLevel = (*itr)->GetModifier()->m_amount; - - if (i == 6 && GetTypeId() == TYPEID_PLAYER) // special drunk detection case - detectLevel = ((Player*)this)->GetDrunkValue(); - - if (invLevel <= detectLevel) - return true; - } - } - - return false; -} - -bool Unit::canDetectStealthOf(Unit const* target, float distance, bool *alert) const -{ - if (hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) - return false; - if (distance < 0.388f) //collision - return true; - - // Hunter mark functionality - AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_STALKED); - for (AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) - if ((*iter)->GetCasterGuid() == GetObjectGuid()) - return true; - - // set max distance - float MaxStealthDetectRange = sWorld.getConfig(CONFIG_FLOAT_MAX_PLAYERS_STEALTH_DETECT_RANGE); - float visibleDistance = IsPlayer() ? MaxStealthDetectRange : ((Creature*)this)->GetAttackDistance(target); - - //Always invisible from back (when stealth detection is on), also filter max distance cases - bool isInFront = distance < visibleDistance && HasInArc(M_PI_F, target); - if (!isInFront) - return false; - - visibleDistance = 10.5f - target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH) / 100.0f; - - //Visible distance is modified by - //-Level Diff (every level diff = 1.0f in visible distance) - int32 level_diff = int32(GetLevelForTarget(target)) - int32(target->GetLevelForTarget(this)); - if (abs(level_diff) > 3) - visibleDistance += level_diff; - else - visibleDistance += 0.5f * level_diff; - - //This allows to check talent tree and will add addition stealth dependent on used points) - int32 stealthMod = target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL); - if (stealthMod < 0) - stealthMod = 0; - - //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia) - //based on wowwiki every 5 mod we have 1 more level diff in calculation - visibleDistance += (int32(GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_STEALTH_DETECT, 0)) - stealthMod) / 5.0f; - visibleDistance = visibleDistance > MaxStealthDetectRange ? MaxStealthDetectRange : visibleDistance; - - // recheck new distance - if (visibleDistance <= 0 || distance > visibleDistance) - { - if (alert && distance < 15.0f /*TODO: add MAX ALERT DISTANCE config*/) - { - visibleDistance = visibleDistance * 1.08f + 1.5f; - *alert = distance < visibleDistance; - } - return false; - } - - return true; -} - -void Unit::UpdateSpeed(UnitMoveType mtype, bool forced, float ratio) -{ - // not in combat pet have same speed as owner - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet() && hasUnitState(UNIT_STAT_FOLLOW) && !isInCombat()) - { - if (Unit* owner = GetOwner()) - { - switch(mtype) - { - case MOVE_RUN: - case MOVE_WALK: - case MOVE_SWIM: - SetSpeedRate(mtype, owner->GetSpeedRate(mtype), forced); - return; - default: - break; - } - } - } - - int32 main_speed_mod = 0; - float stack_bonus = 1.0f; - float non_stack_bonus = 1.0f; - - switch (mtype) - { - case MOVE_WALK: - break; - case MOVE_RUN: - { - if (IsMounted()) // Use on mount auras - { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED); - stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS); - non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK)) / 100.0f; - } - else - { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED); - stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS); - non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK)) / 100.0f; - } - break; - } - case MOVE_RUN_BACK: - return; - case MOVE_SWIM: - { - main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED); - break; - } - case MOVE_SWIM_BACK: - return; - default: - sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype); - return; - } - - float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus; - // now we ready for speed calculation - float speed = main_speed_mod ? bonus * (100.0f + main_speed_mod) / 100.0f : bonus; - - switch (mtype) - { - case MOVE_RUN: - case MOVE_SWIM: - { - // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need - // TODO: possible affect only on MOVE_RUN - if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED)) - { - // Use speed from aura - float max_speed = normalization / baseMoveSpeed[mtype]; - if (speed > max_speed) - speed = max_speed; - } - break; - } - default: - break; - } - - // for creature case, we check explicit if mob searched for assistance - if (GetTypeId() == TYPEID_UNIT) - { - if (((Creature*)this)->HasSearchedAssistance()) - speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk". - } - // for player case, we look for some custom rates - else - { - if (getDeathState() == CORPSE) - speed *= sWorld.getConfig(((Player*)this)->InBattleGround() ? CONFIG_FLOAT_GHOST_RUN_SPEED_BG : CONFIG_FLOAT_GHOST_RUN_SPEED_WORLD); - } - - // Apply strongest slow aura mod to speed - int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED); - if (slow) - speed *= (100.0f + slow) / 100.0f; - - if (GetTypeId() == TYPEID_UNIT) - { - Creature* pCreature = (Creature*)this; - if (!(pCreature->IsPet() && pCreature->GetOwnerGuid().IsPlayer())) // don't use DB values for player controlled pets - { - switch (mtype) - { - case MOVE_RUN: - speed *= ((Creature*)this)->GetCreatureInfo()->speed_run; - break; - case MOVE_WALK: - speed *= ((Creature*)this)->GetCreatureInfo()->speed_walk; - break; - default: - break; - } - } - else - speed *= 1.14286f; // normalized player pet runspeed - } - - SetSpeedRate(mtype, speed * ratio, forced); -} - -float Unit::GetSpeed(UnitMoveType mtype) const -{ - return m_speed_rate[mtype] * baseMoveSpeed[mtype]; -} - -float Unit::GetXZFlagBasedSpeed(const Unit *unit) const -{ - if (!unit->HasUnitMovementFlag(MOVEFLAG_MASK_XZ)) - return 0.0f; - - if (unit->IsSwimming()) - { - if (unit->HasUnitMovementFlag(MOVEFLAG_BACKWARD)) - return unit->GetSpeed(MOVE_SWIM_BACK); - - return unit->GetSpeed(MOVE_SWIM); - } - - if (unit->IsWalking()) - { - // Seems to always be same speed forward and backward when walking - return unit->GetSpeed(MOVE_WALK); - } - - // Presumably only running left when IsMoving is true - if (unit->HasUnitMovementFlag(MOVEFLAG_BACKWARD)) - return unit->GetSpeed(MOVE_RUN_BACK); - - return unit->GetSpeed(MOVE_RUN); -} - -struct SetSpeedRateHelper -{ - explicit SetSpeedRateHelper(UnitMoveType _mtype, bool _forced) : mtype(_mtype), forced(_forced) {} - void operator()(Unit* unit) const - { - unit->UpdateSpeed(mtype, forced); - } - UnitMoveType mtype; - bool forced; -}; - -void Unit::SetSpeedRate(UnitMoveType mtype, float rate, bool forced) -{ - if (rate <= 0) - rate = 1.0f; - - // Update speed only on change - if (m_speed_rate[mtype] != rate) - { - m_speed_rate[mtype] = rate; - - const uint16 SetSpeed2Opc_table[MAX_MOVE_TYPE][2] = - { - {MSG_MOVE_SET_WALK_SPEED, SMSG_FORCE_WALK_SPEED_CHANGE}, - {MSG_MOVE_SET_RUN_SPEED, SMSG_FORCE_RUN_SPEED_CHANGE}, - {MSG_MOVE_SET_RUN_BACK_SPEED, SMSG_FORCE_RUN_BACK_SPEED_CHANGE}, - {MSG_MOVE_SET_SWIM_SPEED, SMSG_FORCE_SWIM_SPEED_CHANGE}, - {MSG_MOVE_SET_SWIM_BACK_SPEED, SMSG_FORCE_SWIM_BACK_SPEED_CHANGE}, - {MSG_MOVE_SET_TURN_RATE, SMSG_FORCE_TURN_RATE_CHANGE}, - }; - - if (forced) - { - if (Player* me = GetAffectingPlayer()) - { - WorldPacket dataForMe(SetSpeed2Opc_table[mtype][1], 18); - dataForMe << GetPackGUID(); - dataForMe << uint32(0); - dataForMe << float(GetSpeed(mtype)); - me->GetSession()->SendPacket(&dataForMe); - me->GetCheatData()->OrderSent(&dataForMe); - //if (this == me) - //if (WardenInterface* warden = me->GetSession()->GetWarden()) - //warden->SendSpeedChange(mtype, GetSpeed(mtype)); - } - } - - - // TODO: Actually such opcodes should (always?) be packed with SMSG_COMPRESSED_MOVES - // Nostalrius: (google translated) - // Unable to send here the package 'MSG_MOVE_SET _ * _ SPEED', because we do not know the flags of movements, and the position dimension client - // (update every 0.5 sec). If one sends a packet, one leads to a desynchro (in the absence of interpolation of the position) - // This package will be sent after receiving a packet type 'CMSG_FORCE _ * _ SPEED_CHANGE_ACK' (MovementHandler.cpp) - //m_updateFlag |= UPDATEFLAG_LIVING; // Mise a jour des mouvements en cours, spline, vitesses, etc ... Inutile ? - - propagateSpeedChange(); - } - - CallForAllControlledUnits(SetSpeedRateHelper(mtype, forced), CONTROLLED_PET | CONTROLLED_GUARDIANS | CONTROLLED_CHARM | CONTROLLED_MINIPET); -} - -void Unit::SetHover(bool on) -{ - if (on) - CastSpell(this, 11010, true); - else - RemoveAurasDueToSpell(11010); -} - -void Unit::SetDeathState(DeathState s) -{ - if (s != ALIVE && s != JUST_ALIVED) - { - CombatStop(); - DeleteThreatList(); - ClearComboPointHolders(); // any combo points pointed to unit lost at it death - - if (IsNonMeleeSpellCasted(false)) - InterruptNonMeleeSpells(false); - } - - m_deathState = s; - if (s == JUST_DIED) - { - RemoveAllAurasOnDeath(); - UnsummonAllTotems(); - - i_motionMaster.Clear(false, true); - i_motionMaster.MoveIdle(); - StopMoving(true); - - ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false); - // remove aurastates allowing special moves - ClearAllReactives(); - ClearDiminishings(); - } - else if (s == JUST_ALIVED || s == ALIVE) - { - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground) - } - - if (m_deathState != ALIVE && s == ALIVE) - { - //_ApplyAllAuraMods(); - } -} - -/*######################################## -######## ######## -######## AGGRO SYSTEM ######## -######## ######## -########################################*/ - -bool Unit::CanHaveThreatList() const -{ - // only creatures can have threat list - if (GetTypeId() != TYPEID_UNIT) - return false; - - // only alive units can have threat list - if (!isAlive()) - return false; - - Creature const* creature = ((Creature const*)this); - - // totems can not have threat list - if (creature->IsTotem()) - return false; - - // pets can not have a threat list, unless they are controlled by a creature - if (creature->IsPet() && creature->GetOwnerGuid().IsPlayer()) - return false; - - // charmed units can not have a threat list if charmed by player - if (creature->GetCharmerGuid().IsPlayer()) - return false; - - if (creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_THREAT_LIST) - return false; - - return true; -} - -//====================================================================== - -float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask) -{ - if (!HasAuraType(SPELL_AURA_MOD_THREAT)) - return threat; - - if (schoolMask == SPELL_SCHOOL_MASK_NONE) - return threat; - - SpellSchools school = GetFirstSchoolInMask(schoolMask); - - return threat * m_threatModifier[school]; -} - -//====================================================================== - -void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false*/, SpellSchoolMask schoolMask /*= SPELL_SCHOOL_MASK_NONE*/, SpellEntry const *threatSpell /*= NULL*/) -{ - // Only mobs can manage threat lists - if (CanHaveThreatList()) - m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell, false); -} - -//====================================================================== - -void Unit::DeleteThreatList() -{ - m_ThreatManager.clearReferences(); -} - -//====================================================================== - -void Unit::TauntApply(Unit* taunter) -{ - MANGOS_ASSERT(GetTypeId() == TYPEID_UNIT); - - if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster())) - return; - - if (!CanHaveThreatList()) - return; - - Unit *target = getVictim(); - - if (target && target == taunter) - return; - // Nostalrius : Correction bug sheep/fear - if (!HasAuraType(SPELL_AURA_MOD_FEAR) && !HasAuraType(SPELL_AURA_MOD_CONFUSE)) - { - SetInFront(taunter); - OnEnterCombat(taunter, !isInCombat()); - - if (((Creature*)this)->AI()) - ((Creature*)this)->AI()->AttackStart(taunter); - } - - m_ThreatManager.tauntApply(taunter); -} - -//====================================================================== - -void Unit::TauntFadeOut(Unit *taunter) -{ - MANGOS_ASSERT(GetTypeId() == TYPEID_UNIT); - - if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster())) - return; - - if (!CanHaveThreatList()) - return; - - Unit *target = getVictim(); - - if (!target || target != taunter) - return; - - if (m_ThreatManager.isThreatListEmpty()) - { - // Nostalrius - pas d'evade quand on charm quelque chose. - if (!GetCharmGuid()) - OnLeaveCombat(); - return; - } - - m_ThreatManager.tauntFadeOut(taunter); - target = m_ThreatManager.getHostileTarget(); - - // Nostalrius : Correction bug sheep/fear - if (target && target != taunter && !HasAuraType(SPELL_AURA_MOD_FEAR) && !HasAuraType(SPELL_AURA_MOD_CONFUSE)) - { - SetInFront(target); - OnEnterCombat(target, false); - } -} - -//====================================================================== - -bool Unit::SelectHostileTarget() -{ - //function provides main threat functionality - //next-victim-selection algorithm and evade mode are called - //threat list sorting etc. - - MANGOS_ASSERT(GetTypeId() == TYPEID_UNIT); - - if (!this->isAlive()) - return false; - - //This function only useful once AI has been initialized - if (!((Creature*)this)->AI()) - return false; - - // Nostalrius: delai de 5 sec avant attaque apres spawn. - if (ToCreature()->IsTempPacified()) - return false; - - Unit* target = nullptr; - - // First checking if we have some taunt on us - const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT); - if (!tauntAuras.empty()) - { - Unit* caster; - - // The last taunt aura caster is alive an we are happy to attack him - if ((caster = tauntAuras.back()->GetCaster()) && caster->isAlive()) - return true; - else if (tauntAuras.size() > 1) - { - // We do not have last taunt aura caster but we have more taunt auras, - // so find first available target - - // Auras are pushed_back, last caster will be on the end - AuraList::const_iterator aura = --tauntAuras.end(); - do - { - --aura; - if ((caster = (*aura)->GetCaster()) && caster->IsInMap(this) && caster->isTargetableForAttack()) - { - target = caster; - break; - } - } - while (aura != tauntAuras.begin()); - } - } - - // No taunt aura or taunt aura caster is dead, standard target selection - if (!target && !m_ThreatManager.isThreatListEmpty()) - target = m_ThreatManager.getHostileTarget(); - - if (target) - { - // Nostalrius : Correction bug sheep/fear - if (!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED | UNIT_STAT_DIED | UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING) && (!HasAuraType(SPELL_AURA_MOD_FEAR) || HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) && !HasAuraType(SPELL_AURA_MOD_CONFUSE)) - { - SetInFront(target); - ((Creature*)this)->AI()->AttackStart(target); - } - return true; - } - - // no target but something prevent go to evade mode // Nostalrius - fix evade quand CM. - if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) || GetCharmerGuid()) - return false; - - // last case when creature don't must go to evade mode: - // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list - // for example at owner command to pet attack some far away creature - // Note: creature not have targeted movement generator but have attacker in this case - if (GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE) - { - for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr) - { - if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack()) - return false; - } - } - - // enter in evade mode in other case - OnLeaveCombat(); - return false; -} - -//====================================================================== -//====================================================================== -//====================================================================== - -int32 Unit::CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, SpellEffectIndex effect_index, int32 const* effBasePoints, Spell* spell) -{ - Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL; - - uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0; - - int32 level = int32(getLevel()); - if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0) - level = (int32)spellProto->maxLevel; - else if (level < (int32)spellProto->baseLevel) - level = (int32)spellProto->baseLevel; - level -= (int32)spellProto->spellLevel; - - int32 baseDice = int32(spellProto->EffectBaseDice[effect_index]); - float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index]; - float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index]; - int32 basePoints = effBasePoints - ? *effBasePoints - baseDice - : spellProto->EffectBasePoints[effect_index]; - - basePoints += int32(level * basePointsPerLevel); - int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel); - float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index]; - - switch (randomPoints) - { - case 0: - case 1: - basePoints += baseDice; - break; // range 1..1 - default: - { - // range can have positive (1..rand) and negative (rand..1) values, so order its for irand - int32 randvalue = baseDice >= randomPoints - ? irand(randomPoints, baseDice) - : irand(baseDice, randomPoints); - - basePoints += randvalue; - break; - } - } - - int32 value = basePoints; - - // random damage - if (comboDamage != 0 && unitPlayer && target && (target->GetObjectGuid() == unitPlayer->GetComboTargetGuid())) - value += (int32)(comboDamage * comboPoints); - - if (Player* modOwner = GetSpellModOwner()) - { - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value, spell); - - switch (effect_index) - { - case EFFECT_INDEX_0: - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value, spell); - break; - case EFFECT_INDEX_1: - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value, spell); - break; - case EFFECT_INDEX_2: - modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value, spell); - break; - } - } - - if (spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel && - spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE && - spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK && - (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED)) - value = int32(value * 0.25f * exp(getLevel() * (70 - spellProto->spellLevel) / 1000.0f)); - - return value; -} - -DiminishingLevels Unit::GetDiminishing(DiminishingGroup group) -{ - for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) - { - if (i->DRGroup != group) - continue; - - if (!i->hitCount) - return DIMINISHING_LEVEL_1; - - if (!i->hitTime) - return DIMINISHING_LEVEL_1; - - // If last spell was casted more than 15 seconds ago - reset the count. - if (i->stack == 0 && WorldTimer::getMSTimeDiff(i->hitTime, WorldTimer::getMSTime()) > 15 * IN_MILLISECONDS) - { - i->hitCount = DIMINISHING_LEVEL_1; - return DIMINISHING_LEVEL_1; - } - // or else increase the count. - else - return DiminishingLevels(i->hitCount); - } - return DIMINISHING_LEVEL_1; -} - -void Unit::IncrDiminishing(DiminishingGroup group) -{ - // Checking for existing in the table - for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) - { - if (i->DRGroup != group) - continue; - if (i->hitCount < DIMINISHING_LEVEL_IMMUNE) - i->hitCount += 1; - return; - } - m_Diminishing.push_back(DiminishingReturn(group, WorldTimer::getMSTime(), DIMINISHING_LEVEL_2)); -} - -bool Unit::IsLikePlayer() const -{ - if (IsPlayer()) - return true; - if (!IsPet()) - return false; - // Pet creature. Reste a savoir si ce machin appartient a un joueur. - Pet* pet = ((Pet*)this); - if (!pet->isControlled()) - return false; - return pet->GetOwnerGuid().IsPlayer(); -} - -void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, bool isReflected) -{ - if (duration == -1 || group == DIMINISHING_NONE || (!isReflected && caster->IsFriendlyTo(this))) - return; - - float mod = 1.0f; - - // Some diminishings applies to mobs too (for example, Stun) - // Nostalrius: fix DR sur les pets. - bool pvp = (IsLikePlayer() && caster->IsLikePlayer()); - if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && pvp) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL) - { - DiminishingLevels diminish = Level; - switch (diminish) - { - case DIMINISHING_LEVEL_1: - break; - case DIMINISHING_LEVEL_2: - mod = 0.5f; - break; - case DIMINISHING_LEVEL_3: - mod = 0.25f; - break; - case DIMINISHING_LEVEL_IMMUNE: - mod = 0.0f; - break; - default: - break; - } - } - - duration = int32(duration * mod); -} - -void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) -{ - // Checking for existing in the table - for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) - { - if (i->DRGroup != group) - continue; - - if (apply) - i->stack += 1; - else if (i->stack) - { - i->stack -= 1; - // Remember time after last aura from group removed - if (i->stack == 0) - i->hitTime = WorldTimer::getMSTime(); - } - break; - } -} - -bool Unit::isVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const -{ - return isVisibleForOrDetect(u, viewPoint, false, inVisibleList); -} - -/// returns true if creature can't be seen by alive units -bool Unit::isInvisibleForAlive() const -{ - if (m_AuraFlags & UNIT_AURAFLAG_ALIVE_INVISIBLE) - return true; - // TODO: maybe spiritservices also have just an aura - return isSpiritService(); -} - -uint32 Unit::GetCreatureType() const -{ - if (GetTypeId() == TYPEID_PLAYER) - { - SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(GetShapeshiftForm()); - if (ssEntry && ssEntry->creatureType > 0) - return ssEntry->creatureType; - else - return CREATURE_TYPE_HUMANOID; - } - else - return ((Creature*)this)->GetCreatureInfo()->type; -} - -/*####################################### -######## ######## -######## STAT SYSTEM ######## -######## ######## -#######################################*/ - -bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply) -{ - if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END) - { - sLog.outError("ERROR in HandleStatModifier(): nonexistent UnitMods or wrong UnitModifierType!"); - return false; - } - - float val = 1.0f; - - switch (modifierType) - { - case BASE_VALUE: - case TOTAL_VALUE: - m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount; - break; - case BASE_PCT: - case TOTAL_PCT: - if (amount <= -100.0f) //small hack-fix for -100% modifiers - amount = -200.0f; - - val = (100.0f + amount) / 100.0f; - m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f / val); - break; - - default: - break; - } - - if (!CanModifyStats()) - return false; - - switch (unitMod) - { - case UNIT_MOD_STAT_STRENGTH: - case UNIT_MOD_STAT_AGILITY: - case UNIT_MOD_STAT_STAMINA: - case UNIT_MOD_STAT_INTELLECT: - case UNIT_MOD_STAT_SPIRIT: - UpdateStats(GetStatByAuraGroup(unitMod)); - break; - - case UNIT_MOD_ARMOR: - UpdateArmor(); - break; - case UNIT_MOD_HEALTH: - UpdateMaxHealth(); - break; - - case UNIT_MOD_MANA: - case UNIT_MOD_RAGE: - case UNIT_MOD_FOCUS: - case UNIT_MOD_ENERGY: - case UNIT_MOD_HAPPINESS: - UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); - break; - - case UNIT_MOD_RESISTANCE_HOLY: - case UNIT_MOD_RESISTANCE_FIRE: - case UNIT_MOD_RESISTANCE_NATURE: - case UNIT_MOD_RESISTANCE_FROST: - case UNIT_MOD_RESISTANCE_SHADOW: - case UNIT_MOD_RESISTANCE_ARCANE: - UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); - break; - - case UNIT_MOD_ATTACK_POWER: - UpdateAttackPowerAndDamage(); - break; - case UNIT_MOD_ATTACK_POWER_RANGED: - UpdateAttackPowerAndDamage(true); - break; - - case UNIT_MOD_DAMAGE_MAINHAND: - UpdateDamagePhysical(BASE_ATTACK); - break; - case UNIT_MOD_DAMAGE_OFFHAND: - UpdateDamagePhysical(OFF_ATTACK); - break; - case UNIT_MOD_DAMAGE_RANGED: - UpdateDamagePhysical(RANGED_ATTACK); - break; - - default: - break; - } - - return true; -} - -float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const -{ - if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END) - { - sLog.outError("attempt to access nonexistent modifier value from UnitMods!"); - return 0.0f; - } - - if (modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f) - return 0.0f; - - return m_auraModifiersGroup[unitMod][modifierType]; -} - -float Unit::GetTotalStatValue(Stats stat) const -{ - UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat); - - if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f) - return 0.0f; - - // value = ((base_value * base_pct) + total_value) * total_pct - float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat); - value *= m_auraModifiersGroup[unitMod][BASE_PCT]; - value += m_auraModifiersGroup[unitMod][TOTAL_VALUE]; - value *= m_auraModifiersGroup[unitMod][TOTAL_PCT]; - - return value; -} - -float Unit::GetTotalAuraModValue(UnitMods unitMod) const -{ - if (unitMod >= UNIT_MOD_END) - { - sLog.outError("attempt to access nonexistent UnitMods in GetTotalAuraModValue()!"); - return 0.0f; - } - - if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f) - return 0.0f; - - float value = m_auraModifiersGroup[unitMod][BASE_VALUE]; - value *= m_auraModifiersGroup[unitMod][BASE_PCT]; - value += m_auraModifiersGroup[unitMod][TOTAL_VALUE]; - value *= m_auraModifiersGroup[unitMod][TOTAL_PCT]; - - return value; -} - -SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const -{ - SpellSchools school = SPELL_SCHOOL_NORMAL; - - switch (unitMod) - { - case UNIT_MOD_RESISTANCE_HOLY: - school = SPELL_SCHOOL_HOLY; - break; - case UNIT_MOD_RESISTANCE_FIRE: - school = SPELL_SCHOOL_FIRE; - break; - case UNIT_MOD_RESISTANCE_NATURE: - school = SPELL_SCHOOL_NATURE; - break; - case UNIT_MOD_RESISTANCE_FROST: - school = SPELL_SCHOOL_FROST; - break; - case UNIT_MOD_RESISTANCE_SHADOW: - school = SPELL_SCHOOL_SHADOW; - break; - case UNIT_MOD_RESISTANCE_ARCANE: - school = SPELL_SCHOOL_ARCANE; - break; - - default: - break; - } - - return school; -} - -Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const -{ - Stats stat = STAT_STRENGTH; - - switch (unitMod) - { - case UNIT_MOD_STAT_STRENGTH: - stat = STAT_STRENGTH; - break; - case UNIT_MOD_STAT_AGILITY: - stat = STAT_AGILITY; - break; - case UNIT_MOD_STAT_STAMINA: - stat = STAT_STAMINA; - break; - case UNIT_MOD_STAT_INTELLECT: - stat = STAT_INTELLECT; - break; - case UNIT_MOD_STAT_SPIRIT: - stat = STAT_SPIRIT; - break; - - default: - break; - } - - return stat; -} - -Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const -{ - switch (unitMod) - { - case UNIT_MOD_MANA: - return POWER_MANA; - case UNIT_MOD_RAGE: - return POWER_RAGE; - case UNIT_MOD_FOCUS: - return POWER_FOCUS; - case UNIT_MOD_ENERGY: - return POWER_ENERGY; - case UNIT_MOD_HAPPINESS: - return POWER_HAPPINESS; - default: - return POWER_MANA; - } - - return POWER_MANA; -} - -float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const -{ - if (attType == RANGED_ATTACK) - { - int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS); - if (ap < 0) - return 0.0f; - return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER)); - } - else - { - int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS); - if (ap < 0) - return 0.0f; - return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER)); - } -} - -float Unit::GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange damageRange, uint8 index) const -{ - if (attType == OFF_ATTACK && !haveOffhandWeapon()) - return 0.0f; - - return m_weaponDamage[attType][index].damage[damageRange]; -} - -void Unit::SetLevel(uint32 lvl) -{ - SetUInt32Value(UNIT_FIELD_LEVEL, lvl); - - // group update - if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL); -} - -void Unit::SetHealth(uint32 val) -{ - uint32 maxHealth = GetMaxHealth(); - if (maxHealth < val) - val = maxHealth; - - SetUInt32Value(UNIT_FIELD_HEALTH, val); - ForceValuesUpdateAtIndex(UNIT_FIELD_MAXHEALTH); // Necessaire pour script qui cache PV aux joueurs. - - // group update - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP); - } - } -} - -void Unit::SetMaxHealth(uint32 val) -{ - uint32 health = GetHealth(); - SetUInt32Value(UNIT_FIELD_MAXHEALTH, val); - ForceValuesUpdateAtIndex(UNIT_FIELD_HEALTH); // Cf plus haut. - - // group update - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP); - } - } - - if (val < health) - SetHealth(val); -} - -void Unit::SetHealthPercent(float percent) -{ - uint32 newHealth = GetMaxHealth() * percent / 100.0f; - SetHealth(newHealth); -} - -void Unit::SetPower(Powers power, uint32 val) -{ - if (GetPower(power) == val) - return; - - uint32 maxPower = GetMaxPower(power); - if (maxPower < val) - val = maxPower; - - SetStatInt32Value(UNIT_FIELD_POWER1 + power, val); - - // group update - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER); - } - - // Update the pet's character sheet with happiness damage bonus - if (pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS) - pet->UpdateDamagePhysical(BASE_ATTACK); - } -} - -void Unit::SetMaxPower(Powers power, uint32 val) -{ - uint32 cur_power = GetPower(power); - SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val); - - // group update - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER); - } - } - - if (val < cur_power) - SetPower(power, val); -} - -void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply) -{ - ApplyModUInt32Value(UNIT_FIELD_POWER1 + power, val, apply); - - // group update - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER); - } - } -} - -void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply) -{ - ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1 + power, val, apply); - - // group update - if (GetTypeId() == TYPEID_PLAYER) - { - if (((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); - } - else if (((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER); - } - } -} - -void Unit::ApplyAuraProcTriggerDamage(Aura* aura, bool apply) -{ - AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE]; - if (apply) - tAuraProcTriggerDamage.push_back(aura); - else - tAuraProcTriggerDamage.remove(aura); -} - -uint32 Unit::GetCreatePowers(Powers power) const -{ - switch (power) - { - case POWER_HEALTH: - return 0; // is it really should be here? - case POWER_MANA: - return GetCreateMana(); - case POWER_RAGE: - return 1000; - case POWER_FOCUS: - return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 100); - case POWER_ENERGY: - return 100; - case POWER_HAPPINESS: - return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 1050000); - } - - return 0; -} - -void Unit::AddToWorld() -{ - Object::AddToWorld(); - ScheduleAINotify(0); -} - -void Unit::RemoveFromWorld() -{ - // cleanup - if (IsInWorld()) - { - Uncharm(); - RemoveNotOwnSingleTargetAuras(); - RemoveGuardians(); - RemoveAllGameObjects(); - RemoveAllDynObjects(); - CleanupDeletedAuras(); - GetViewPoint().Event_RemovedFromWorld(); - } - if (m_needUpdateVisibility && FindMap()) - { - FindMap()->RemoveRelocatedUnit(this); - m_needUpdateVisibility = false; - } - Object::RemoveFromWorld(); -} - -void Unit::CleanupsBeforeDelete() -{ - if (m_uint32Values) // only for fully created object - { - InterruptNonMeleeSpells(true); - m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList - CombatStop(); - ClearComboPointHolders(); - DeleteThreatList(); - if (getHostileRefManager().getOwner() == this) - { - if (GetTypeId() == TYPEID_PLAYER) - getHostileRefManager().setOnlineOfflineState(false); - else - getHostileRefManager().deleteReferences(); - } - RemoveAllAuras(AURA_REMOVE_BY_DELETE); - } - WorldObject::CleanupsBeforeDelete(); -} - -CharmInfo* Unit::InitCharmInfo(Unit *charm) -{ - if (!m_charmInfo) - m_charmInfo = new CharmInfo(charm); - return m_charmInfo; -} - -CharmInfo::CharmInfo(Unit* unit) - : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0), - _isCommandAttack(false), _isAtStay(false), _isFollowing(false), _isReturning(false), - _stayX(0.0f), _stayY(0.0f), _stayZ(0.0f), _isCommandFollow(false) -{ - for (int i = 0; i < CREATURE_MAX_SPELLS; ++i) - m_charmspells[i].SetActionAndType(0, ACT_DISABLED); -} - -void CharmInfo::InitPetActionBar() -{ - // the first 3 SpellOrActions are attack, follow and stay - for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i) - SetActionBar(ACTION_BAR_INDEX_START + i, COMMAND_ATTACK - i, ACT_COMMAND); - - // middle 4 SpellOrActions are spells/special attacks/abilities - for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END - ACTION_BAR_INDEX_PET_SPELL_START; ++i) - SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i, 0, ACT_DISABLED); - - // last 3 SpellOrActions are reactions - for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i) - SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i, COMMAND_ATTACK - i, ACT_REACTION); -} - -void CharmInfo::InitEmptyActionBar() -{ - SetActionBar(ACTION_BAR_INDEX_START, COMMAND_ATTACK, ACT_COMMAND); - for (uint32 x = ACTION_BAR_INDEX_START + 1; x < ACTION_BAR_INDEX_END; ++x) - SetActionBar(x, 0, ACT_PASSIVE); -} - -void CharmInfo::InitPossessCreateSpells() -{ - InitEmptyActionBar(); //charm action bar - - if (m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty - return; - - for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) - { - if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x])) - m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true); - else - AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE); - } -} - -void CharmInfo::InitCharmCreateSpells() -{ - if (m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells - { - //InitEmptyActionBar(); - InitPetActionBar(); - return; - } - - InitPetActionBar(); - - for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) - { - uint32 spellId = ((Creature*)m_unit)->m_spells[x]; - - if (!spellId) - { - m_charmspells[x].SetActionAndType(spellId, ACT_DISABLED); - continue; - } - - if (IsPassiveSpell(spellId)) - { - m_unit->CastSpell(m_unit, spellId, true); - m_charmspells[x].SetActionAndType(spellId, ACT_PASSIVE); - } - else - { - m_charmspells[x].SetActionAndType(spellId, ACT_DISABLED); - - ActiveStates newstate; - bool onlyselfcast = true; - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); - - if (!spellInfo) onlyselfcast = false; - for (uint32 i = 0; i < 3 && onlyselfcast; ++i) //nonexistent spell will not make any problems as onlyselfcast would be false -> break right away - { - if (spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0) - onlyselfcast = false; - } - - if (onlyselfcast || !IsPositiveSpell(spellId)) // only self cast and spells versus enemies are autocastable - newstate = ACT_DISABLED; - else - newstate = ACT_PASSIVE; - - AddSpellToActionBar(spellId, newstate); - } - } -} - -bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate) -{ - uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id); - - // new spell rank can be already listed - for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) - { - if (uint32 action = PetActionBar[i].GetAction()) - { - if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id) - { - PetActionBar[i].SetAction(spell_id); - return true; - } - } - } - - // or use empty slot in other case - for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) - { - if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell()) - { - SetActionBar(i, spell_id, newstate == ACT_DECIDE ? ACT_DISABLED : newstate); - return true; - } - } - return false; -} - -bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id) -{ - uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id); - - for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) - { - if (uint32 action = PetActionBar[i].GetAction()) - { - if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id) - { - SetActionBar(i, 0, ACT_DISABLED); - return true; - } - } - } - - return false; -} - -void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply) -{ - if (IsPassiveSpell(spellid)) - return; - - for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) - if (spellid == m_charmspells[x].GetAction()) - m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED); -} - -void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow) -{ - m_petnumber = petnumber; - if (statwindow) - m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber); - else - m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0); -} - -void CharmInfo::LoadPetActionBar(const std::string& data) -{ - InitPetActionBar(); - - Tokens tokens = StrSplit(data, " "); - - if (tokens.size() != (ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_START) * 2) - return; // non critical, will reset to default - - int index; - Tokens::iterator iter; - for (iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index) - { - // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion - uint8 type = (uint8)atol((*iter).c_str()); - ++iter; - uint32 action = atol((*iter).c_str()); - - PetActionBar[index].SetActionAndType(action, ActiveStates(type)); - - // check correctness - if (PetActionBar[index].IsActionBarForSpell() && !sSpellMgr.GetSpellEntry(PetActionBar[index].GetAction())) - SetActionBar(index, 0, ACT_DISABLED); - } -} - -void CharmInfo::BuildActionBar(WorldPacket* data) -{ - for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) - *data << uint32(PetActionBar[i].packedData); -} - -void CharmInfo::SetSpellAutocast(uint32 spell_id, bool state) -{ - for (int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) - { - if (spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell()) - { - PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED); - break; - } - } -} - -void CharmInfo::SetIsCommandAttack(bool val) -{ - _isCommandAttack = val; -} - -bool CharmInfo::IsCommandAttack() -{ - return _isCommandAttack; -} - -void CharmInfo::SetIsCommandFollow(bool val) -{ - _isCommandFollow = val; -} - -bool CharmInfo::IsCommandFollow() -{ - return _isCommandFollow; -} - -void CharmInfo::SaveStayPosition() -{ - //! At this point a new spline destination is enabled because of Unit::StopMoving() - G3D::Vector3 const stayPos = m_unit->movespline->FinalDestination(); - _stayX = stayPos.x; - _stayY = stayPos.y; - _stayZ = stayPos.z; -} - -void CharmInfo::GetStayPosition(float &x, float &y, float &z) -{ - x = _stayX; - y = _stayY; - z = _stayZ; -} - -void CharmInfo::SetIsAtStay(bool val) -{ - _isAtStay = val; -} - -bool CharmInfo::IsAtStay() -{ - return _isAtStay; -} - -void CharmInfo::SetIsFollowing(bool val) -{ - _isFollowing = val; -} - -bool CharmInfo::IsFollowing() -{ - return _isFollowing; -} - -void CharmInfo::SetIsReturning(bool val) -{ - _isReturning = val; -} - -bool CharmInfo::IsReturning() -{ - return _isReturning; -} - - -bool Unit::isFrozen() const -{ - return HasAuraState(AURA_STATE_FROZEN); -} - -uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition) -{ - uint32 procEx = PROC_EX_NONE; - switch (missCondition) - { - case SPELL_MISS_MISS: - procEx |= PROC_EX_MISS; - break; - case SPELL_MISS_RESIST: - procEx |= PROC_EX_RESIST; - break; - case SPELL_MISS_DODGE: - procEx |= PROC_EX_DODGE; - break; - case SPELL_MISS_PARRY: - procEx |= PROC_EX_PARRY; - break; - case SPELL_MISS_BLOCK: - procEx |= PROC_EX_BLOCK; - break; - case SPELL_MISS_EVADE: - procEx |= PROC_EX_EVADE; - break; - case SPELL_MISS_IMMUNE: - procEx |= PROC_EX_IMMUNE; - break; - case SPELL_MISS_IMMUNE2: - procEx |= PROC_EX_IMMUNE; - break; - case SPELL_MISS_DEFLECT: - procEx |= PROC_EX_DEFLECT; - break; - case SPELL_MISS_ABSORB: - procEx |= PROC_EX_ABSORB; - break; - case SPELL_MISS_REFLECT: - procEx |= PROC_EX_REFLECT; - // no break - case SPELL_MISS_NONE: - // On block - if (damageInfo->blocked) - procEx |= PROC_EX_BLOCK; - // On absorb - if (damageInfo->absorb) - procEx |= PROC_EX_ABSORB; - // On crit - if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT) - procEx |= PROC_EX_CRITICAL_HIT; - else - procEx |= PROC_EX_NORMAL_HIT; - break; - } - return procEx; -} - -void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const* procSpell, uint32 damage, ProcTriggeredList& triggeredList, Spell* spell) -{ - // For melee/ranged based attack need update skills and set some Aura states - if (procFlag & MELEE_BASED_TRIGGER_MASK && pTarget) - { - // Update skills here for players - if (GetTypeId() == TYPEID_PLAYER) - { - // On melee based hit/miss/resist need update skill (for victim and attacker) - if (procExtra & (PROC_EX_NORMAL_HIT | PROC_EX_MISS | PROC_EX_RESIST)) - { - if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER) - ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim); - } - // Update defence if player is victim and parry/dodge/block - if (isVictim && procExtra & (PROC_EX_DODGE | PROC_EX_PARRY | PROC_EX_BLOCK)) - ((Player*)this)->UpdateDefense(); - } - // If exist crit/parry/dodge/block need update aura state (for victim and attacker) - if (procExtra & (PROC_EX_CRITICAL_HIT | PROC_EX_PARRY | PROC_EX_DODGE | PROC_EX_BLOCK)) - { - // for victim - if (isVictim) - { - // if victim and dodge attack - if (procExtra & PROC_EX_DODGE) - { - //Update AURA_STATE on dodge - if (getClass() != CLASS_ROGUE) // skip Rogue Riposte - { - ModifyAuraState(AURA_STATE_DEFENSE, true); - StartReactiveTimer(REACTIVE_DEFENSE, pTarget->GetObjectGuid()); - } - } - // if victim and parry attack - if (procExtra & PROC_EX_PARRY) - { - // For Hunters only Counterattack (skip Mongoose bite) - if (getClass() == CLASS_HUNTER) - { - ModifyAuraState(AURA_STATE_HUNTER_PARRY, true); - StartReactiveTimer(REACTIVE_HUNTER_PARRY, pTarget->GetObjectGuid()); - ((Player*)this)->AddComboPoints(pTarget, 1); - } - else - { - ModifyAuraState(AURA_STATE_DEFENSE, true); - StartReactiveTimer(REACTIVE_DEFENSE, pTarget->GetObjectGuid()); - } - } - // if and victim block attack - if (procExtra & PROC_EX_BLOCK) - { - ModifyAuraState(AURA_STATE_DEFENSE, true); - StartReactiveTimer(REACTIVE_DEFENSE, pTarget->GetObjectGuid()); - } - } - else //For attacker - { - // Overpower on victim dodge - if (procExtra & PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR) - { - ((Player*)this)->AddComboPoints(pTarget, 1); - StartReactiveTimer(REACTIVE_OVERPOWER, pTarget->GetObjectGuid()); - } - } - } - } - DEBUG_UNIT(this, DEBUG_PROCS, "PROC: Flags 0x%.5x Ex 0x%.3x Spell %5u %s", procFlag, procExtra, procSpell ? procSpell->Id : 0, isVictim ? "[victim]" : ""); - - // Fill triggeredList list - for (SpellAuraHolderMap::const_iterator itr = GetSpellAuraHolderMap().begin(); itr != GetSpellAuraHolderMap().end(); ++itr) - { - // Can not proc on self. - if (procSpell && procSpell->Id == itr->first) - continue; - - // skip deleted auras (possible at recursive triggered call - if (itr->second->IsDeleted()) - continue; - - // Aura that applies a modifier with charges. Gere? otherwise. - bool hasmodifier = false; - for (int i = 0; i < 3; ++i) - if (itr->second->GetAuraByEffectIndex(SpellEffectIndex(i))) - if (SpellModifier* auraMod = itr->second->GetAuraByEffectIndex(SpellEffectIndex(i))->GetSpellModifier()) - if (auraMod->charges > 0 || (spell && spell->HasModifierApplied(auraMod))) - { - hasmodifier = true; - break; - } - if (hasmodifier) - continue; - - SpellProcEventEntry const* spellProcEvent = nullptr; - if (!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, spellProcEvent)) - continue; - - itr->second->SetInUse(true); // prevent holder deletion - triggeredList.push_back(ProcTriggeredData(spellProcEvent, itr->second, pTarget, procFlag)); - } -} - -SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const -{ - return SPELL_SCHOOL_MASK_NORMAL; -} - -Player* Unit::GetSpellModOwner() const -{ - if (GetTypeId() == TYPEID_PLAYER) - return (Player*)this; - if (((Creature*)this)->IsPet() || ((Creature*)this)->IsTotem()) - { - Unit* owner = GetOwner(); - if (owner && owner->GetTypeId() == TYPEID_PLAYER) - return (Player*)owner; - } - return nullptr; -} - -///----------Pet responses methods----------------- -void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg) -{ - if (msg == SPELL_CAST_OK) - return; - - Unit *owner = GetCharmerOrOwner(); - if (!owner || owner->GetTypeId() != TYPEID_PLAYER) - return; - - WorldPacket data(SMSG_PET_CAST_FAILED, 4 + 1 + 1); - data << uint32(spellid); - data << uint8(2); // 1.12: comme SMSG_CAST_FAILED je suppose. 2 = echec, 0 = reussi. - data << uint8(msg); - ((Player*)owner)->GetSession()->SendPacket(&data); -} - -void Unit::SendPetActionFeedback(uint8 msg) -{ - Unit* owner = GetOwner(); - if (!owner || owner->GetTypeId() != TYPEID_PLAYER) - return; - - WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1); - data << uint8(msg); - ((Player*)owner)->GetSession()->SendPacket(&data); -} - -void Unit::SendPetTalk(uint32 pettalk) -{ - Unit* owner = GetOwner(); - if (!owner || owner->GetTypeId() != TYPEID_PLAYER) - return; - - WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4); - data << GetObjectGuid(); - data << uint32(pettalk); - ((Player*)owner)->GetSession()->SendPacket(&data); -} - -void Unit::SendPetAIReaction() -{ - Unit* owner = GetOwner(); - if (!owner || owner->GetTypeId() != TYPEID_PLAYER) - return; - - WorldPacket data(SMSG_AI_REACTION, 8 + 4); - data << GetObjectGuid(); - data << uint32(AI_REACTION_HOSTILE); - ((Player*)owner)->GetSession()->SendPacket(&data); -} - -///----------End of Pet responses methods---------- - -void Unit::StopMoving(bool force) -{ - clearUnitState(UNIT_STAT_MOVING); - RemoveUnitMovementFlag(MOVEFLAG_MASK_MOVING); - // not need send any packets if not in world - if (!IsInWorld()) - return; - - Movement::MoveSplineInit init(*this, "StopMoving"); - if (Transport* t = GetTransport()) { - init.SetTransport(t->GetGUIDLow()); - } - - if (!movespline->Finalized() || force) { - init.SetStop(); // Will trigger CMSG_MOVE_SPLINE_DONE from client. - init.Launch(); - } - - DisableSpline(); -} - -void Unit::SetFleeing(bool apply, ObjectGuid casterGuid, uint32 spellID, uint32 time) -{ - if (apply && HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) - return; - - ModConfuseSpell(apply, casterGuid, spellID, MOV_MOD_FLEE_FOR_ASSISTANCE, time); -} - -void Unit::SetFeared(bool apply, ObjectGuid casterGuid, uint32 spellID, uint32 time) -{ - if (apply && HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) - return; - - ModConfuseSpell(apply, casterGuid, spellID, MOV_MOD_FLEE_IN_FEAR, time); -} - -void Unit::SetConfused(bool apply, ObjectGuid casterGuid, uint32 spellID) -{ - ModConfuseSpell(apply, casterGuid, spellID, MOV_MOD_CONFUSED, 0); -} - -void Unit::ModConfuseSpell(bool apply, ObjectGuid casterGuid, uint32 spellID, MovementModType modType, uint32 time) -{ - if (GetTypeId() == TYPEID_UNIT) - if (ToCreature()->IsTotem()) - return; - - bool controlFinished = true; - - if (HasAuraType(SPELL_AURA_MOD_CONFUSE)) - { - controlFinished = false; - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED); - } - else - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED); - - if (HasAuraType(SPELL_AURA_MOD_FEAR) && !HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) - { - controlFinished = false; - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); - } - else - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); - - m_movementInfo.moveFlags &= ~MOVEFLAG_MASK_MOVING_OR_TURN; - - if (apply) - { - CastStop(GetObjectGuid() == casterGuid ? spellID : 0); - - switch (modType) - { - case MOV_MOD_FLEE_FOR_ASSISTANCE: - { - Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : nullptr; - GetMotionMaster()->MoveFleeing(caster, time); - break; - } - case MOV_MOD_FLEE_IN_FEAR: - { - Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : nullptr; - GetMotionMaster()->MoveFeared(caster, time); - break; - } - case MOV_MOD_CONFUSED: - GetMotionMaster()->MoveConfused(); - break; - } - - if (casterGuid != GetObjectGuid()) - InterruptNonMeleeSpells(false); - - if (GetTypeId() == TYPEID_UNIT) - SetTargetGuid(ObjectGuid()); - } - else - { - switch (modType) - { - case MOV_MOD_FLEE_FOR_ASSISTANCE: - case MOV_MOD_FLEE_IN_FEAR: - { - if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING)) - GetMotionMaster()->ClearType(FLEEING_MOTION_TYPE); - break; - } - case MOV_MOD_CONFUSED: - if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED)) - GetMotionMaster()->ClearType(CONFUSED_MOTION_TYPE); - break; - } - - // Si spellID=0, c'est pour interrompre (par exemple male de temerite - 704) - // Donc on retire les effets meme si on a encore un aura de fear. - if (!controlFinished && spellID) - return; - - if (GetTypeId() != TYPEID_PLAYER && isAlive()) - { - Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : nullptr; - if (caster) - AttackedBy(caster); - - // restore appropriate movement generator - if (!SelectHostileTarget()) - return; - - if (getVictim()) - SetTargetGuid(getVictim()->GetObjectGuid()); - - RestoreMovement(); - } - } -} - -void Unit::SetFeignDeath(bool apply, ObjectGuid casterGuid, uint32 /*spellID*/) -{ - // [TODO] SMSG_FEIGN_DEATH_RESISTED sert a quoi ? - il affiche 'Resiste' en notify. - if (apply) - { - m_movementInfo.RemoveMovementFlag(MOVEFLAG_MASK_MOVING_OR_TURN); - if (GetTypeId() != TYPEID_PLAYER) - StopMoving(); - - - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); - SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); - - addUnitState(UNIT_STAT_DIED); - CombatStop(); - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); - - // prevent interrupt message - if (casterGuid == GetObjectGuid()) - FinishSpell(CURRENT_GENERIC_SPELL, false); - InterruptNonMeleeSpells(true); - getHostileRefManager().deleteReferences(); - } - else - { - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); - // blizz like 2.0.x - //SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); [-ZERO] remove/replace ? - - RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); - - clearUnitState(UNIT_STAT_DIED); - - RestoreMovement(); - } -} - -bool Unit::IsSitState() const -{ - uint8 s = getStandState(); - return - s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR || - s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR || - s == UNIT_STAND_STATE_SIT; -} - -bool Unit::IsStandState() const -{ - uint8 s = getStandState(); - return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL; -} - -void Unit::SetStandState(uint8 state) -{ - if (GetByteValue(UNIT_FIELD_BYTES_1, 0) == state) - return; - - SetByteValue(UNIT_FIELD_BYTES_1, 0, state); - - if (IsStandState()) - RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED); - - if (GetTypeId() == TYPEID_PLAYER) - { - WorldPacket data(SMSG_STANDSTATE_UPDATE, 1); - data << (uint8)state; - ((Player*)this)->GetSession()->SendPacket(&data); - } -} - -bool Unit::IsPolymorphed() const -{ - return GetSpellSpecific(getTransForm()) == SPELL_MAGE_POLYMORPH; -} - -bool Unit::isAttackReady(WeaponAttackType type) const -{ - return m_attackTimer[type] == 0; -} -void Unit::SetDisplayId(uint32 modelId) -{ - if (IsPlayer()) - { - float mod_x = 1; - switch (modelId) - { - case 59: - mod_x *= DEFAULT_TAUREN_MALE_SCALE; - break; - case 60: - mod_x *= DEFAULT_TAUREN_FEMALE_SCALE; - break; - // Orb of Deception Gone - case 10148: - mod_x *= DEFAULT_TAUREN_MALE_SCALE; - break; - case 10149: - mod_x *= DEFAULT_TAUREN_FEMALE_SCALE; - break; - } - switch (GetDisplayId()) - { - case 59: - mod_x /= DEFAULT_TAUREN_MALE_SCALE; - break; - case 60: - mod_x /= DEFAULT_TAUREN_FEMALE_SCALE; - break; - // Orb of Deception Gone - case 10148: - mod_x /= DEFAULT_TAUREN_MALE_SCALE; - break; - case 10149: - mod_x /= DEFAULT_TAUREN_FEMALE_SCALE; - break; - } - ApplyPercentModFloatValue(OBJECT_FIELD_SCALE_X, (mod_x -1)*100, true); - } - - SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId); - - UpdateModelData(); - - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (!pet->isControlled()) - return; - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID); - } -} - -void Unit::UpdateModelData() -{ - CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(GetDisplayId()); - CreatureModelInfo const* modelInfo = sObjectMgr.GetCreatureModelInfo(GetDisplayId()); - if (modelInfo && displayEntry && modelInfo->bounding_radius && modelInfo->combat_reach && displayEntry->scale) - { - // we expect values in database to be relative to scale = 1.0 - SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (GetObjectScale() / displayEntry->scale) * modelInfo->bounding_radius); - - // never actually update combat_reach for player, it's always the same. Below player case is for initialization - if (GetTypeId() == TYPEID_PLAYER) - SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); - else - SetFloatValue(UNIT_FIELD_COMBATREACH, (GetObjectScale() / displayEntry->scale) * modelInfo->combat_reach); - } - else - { - sLog.outError("UpdateModelData : pas / mauvaises infos pour le displayid %u de '%s'", GetDisplayId(), GetGuidStr().c_str()); - SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); - SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 1.5f); - } -} - -void Unit::ClearComboPointHolders() -{ - while (!m_ComboPointHolders.empty()) - { - uint32 lowguid = *m_ComboPointHolders.begin(); - - Player* plr = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, lowguid)); - if (plr && plr->GetComboTargetGuid() == GetObjectGuid())// recheck for safe - plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders; - else - m_ComboPointHolders.erase(lowguid); // or remove manually - } -} - -void Unit::ClearAllReactives() -{ - for (int i = 0; i < MAX_REACTIVE; ++i) - { - m_reactiveTimer[i] = 0; - m_reactiveTarget[i].Clear(); - } - - if (HasAuraState(AURA_STATE_DEFENSE)) - ModifyAuraState(AURA_STATE_DEFENSE, false); - if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) - ModifyAuraState(AURA_STATE_HUNTER_PARRY, false); - - if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->ClearComboPoints(); -} - -void Unit::UpdateReactives(uint32 p_time) -{ - for (int i = 0; i < MAX_REACTIVE; ++i) - { - ReactiveType reactive = ReactiveType(i); - - if (!m_reactiveTimer[reactive]) - continue; - - if (m_reactiveTimer[reactive] <= p_time) - { - m_reactiveTimer[reactive] = 0; - m_reactiveTarget[reactive].Clear(); - - switch (reactive) - { - case REACTIVE_DEFENSE: - if (HasAuraState(AURA_STATE_DEFENSE)) - ModifyAuraState(AURA_STATE_DEFENSE, false); - break; - case REACTIVE_HUNTER_PARRY: - if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) - ModifyAuraState(AURA_STATE_HUNTER_PARRY, false); - break; - case REACTIVE_OVERPOWER: - if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->ClearComboPoints(); - break; - default: - break; - } - } - else - m_reactiveTimer[reactive] -= p_time; - } -} - -Unit* Unit::SelectRandomUnfriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const -{ - std::list targets; - - MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, radius); - MaNGOS::UnitListSearcher searcher(targets, u_check); - Cell::VisitAllObjects(this, searcher, radius); - - // remove current target - if (except) - targets.remove(except); - - // remove not LoS targets - for (std::list::iterator tIter = targets.begin(); tIter != targets.end();) - { - if (!IsWithinLOSInMap(*tIter)) - { - std::list::iterator tIter2 = tIter; - ++tIter; - targets.erase(tIter2); - } - else - ++tIter; - } - - // no appropriate targets - if (targets.empty()) - return nullptr; - - // select random - uint32 rIdx = urand(0, targets.size() - 1); - std::list::const_iterator tcIter = targets.begin(); - for (uint32 i = 0; i < rIdx; ++i) - ++tcIter; - - return *tcIter; -} - -Unit* Unit::SelectRandomFriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const -{ - std::list targets; - - MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(this, radius); - MaNGOS::UnitListSearcher searcher(targets, u_check); - - Cell::VisitAllObjects(this, searcher, radius); - - // remove current target - if (except) - targets.remove(except); - - // remove not LoS targets - for (std::list::iterator tIter = targets.begin(); tIter != targets.end();) - { - if (!IsWithinLOSInMap(*tIter)) - { - std::list::iterator tIter2 = tIter; - ++tIter; - targets.erase(tIter2); - } - else - ++tIter; - } - - // no appropriate targets - if (targets.empty()) - return nullptr; - - // select random - uint32 rIdx = urand(0, targets.size() - 1); - std::list::const_iterator tcIter = targets.begin(); - for (uint32 i = 0; i < rIdx; ++i) - ++tcIter; - - return *tcIter; -} - -bool Unit::IsSecondaryThreatTarget() -{ - // Targets with Fear / Confuse / breakable CC - for (SpellAuraHolderMap::const_iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end(); ++iter) - { - if (iter->second->IsTargetSecondaryThreatFocus()) - return true; - } - // Totems have secondary threat priority - if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem()) - { - if (Totem* totem = ((Totem*)this)) - { - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(totem->GetSpell()); - if (!spellInfo) - return true; - - switch (spellInfo->SpellIconID) - { - // Fire Nova Totem / Magma Totem / Searing Totem / Stoneclaw Totem do have threat - case 33: - case 37: - case 680: - case 689: - break; - default: - return true; - } - } - } - return false; -} - -bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag) -{ - for (SpellAuraHolderMap::const_iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end(); ++iter) - { - if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag) - return true; - } - return false; -} - -void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply, bool recalcDamage /*= false*/) -{ - if (val > 0) - { - ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply); - ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, val, !apply); - - if (recalcDamage) - ApplyPercentModFloatVar(m_modRecalcDamagePct[att], val, !apply); - } - else - { - ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply); - ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, -val, apply); - - if (recalcDamage) - ApplyPercentModFloatVar(m_modRecalcDamagePct[att], val, apply); - } -} - -void Unit::ApplyCastTimePercentMod(float val, bool apply) -{ - ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, -val, apply); -} - -void Unit::UpdateAuraForGroup(uint8 slot) -{ - if (GetTypeId() == TYPEID_PLAYER) - { - Player* player = (Player*)this; - if (player->GetGroup()) - { - player->SetGroupUpdateFlag(slot < MAX_POSITIVE_AURAS ? GROUP_UPDATE_FLAG_AURAS : GROUP_UPDATE_FLAG_AURAS_NEGATIVE); - player->SetAuraUpdateSlot(slot); - } - } - else if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) - { - Pet *pet = ((Pet*)this); - if (pet->isControlled()) - { - Unit *owner = GetOwner(); - if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) - { - ((Player*)owner)->SetGroupUpdateFlag(slot < MAX_POSITIVE_AURAS ? GROUP_UPDATE_FLAG_PET_AURAS : GROUP_UPDATE_FLAG_PET_AURAS_NEGATIVE); - pet->SetAuraUpdateSlot(slot); - } - } - } -} - -float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized) -{ - if (!normalized || GetTypeId() != TYPEID_PLAYER) - return float(GetAttackTime(attType)) / 1000.0f; - - Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType, true, false); - if (!Weapon) - return 2.4f; // fist attack - - switch (Weapon->GetProto()->InventoryType) - { - case INVTYPE_2HWEAPON: - return 3.3f; - case INVTYPE_RANGED: - case INVTYPE_RANGEDRIGHT: - case INVTYPE_THROWN: - return 2.8f; - case INVTYPE_WEAPON: - case INVTYPE_WEAPONMAINHAND: - case INVTYPE_WEAPONOFFHAND: - default: - return Weapon->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f; - } -} - -Aura* Unit::GetDummyAura(uint32 spell_id) const -{ - Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY); - for (Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr) - if ((*itr)->GetId() == spell_id) - return *itr; - - return nullptr; -} - -void Unit::SetContestedPvP(Player *attackedPlayer) -{ - Player* player = GetCharmerOrOwnerPlayerOrPlayerItself(); - - if (!player || (attackedPlayer && (attackedPlayer == player || player->IsInDuelWith(attackedPlayer)))) - return; - - player->SetContestedPvPTimer(30000); - - if (!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER)) - { - player->addUnitState(UNIT_STAT_ATTACK_PLAYER); - player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP); - // call MoveInLineOfSight for nearby contested guards - UpdateVisibilityAndView(); - } - - if (!hasUnitState(UNIT_STAT_ATTACK_PLAYER)) - { - addUnitState(UNIT_STAT_ATTACK_PLAYER); - // call MoveInLineOfSight for nearby contested guards - UpdateVisibilityAndView(); - } -} - -void Unit::AddPetAura(PetAura const* petSpell) -{ - m_petAuras.insert(petSpell); - if (Pet* pet = GetPet()) - pet->CastPetAura(petSpell); -} - -void Unit::RemovePetAura(PetAura const* petSpell) -{ - m_petAuras.erase(petSpell); - if (Pet* pet = GetPet()) - pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry())); -} - -void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/) -{ - Unit::SpellAuraHolderMap& auras = GetSpellAuraHolderMap(); - for (Unit::SpellAuraHolderMap::iterator iter = auras.begin(); iter != auras.end();) - { - SpellEntry const *spell = iter->second->GetSpellProto(); - if (spell->Id == exceptSpellId) - ++iter; - else if (non_positive && iter->second->IsPositive()) - ++iter; - else if (spell->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) - ++iter; - else if (iter->second->HasMechanicMask(mechMask)) - { - RemoveAurasDueToSpell(spell->Id); - - if (auras.empty()) - break; - else - iter = auras.begin(); - } - else - ++iter; - } -} - -void Unit::NearTeleportTo(float x, float y, float z, float orientation, uint32 teleportOptions) -{ - DisableSpline(); - - if (GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->TeleportTo(GetMapId(), x, y, z, orientation, teleportOptions); - else - { - Creature* c = (Creature*)this; - // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly - if (!c->GetMotionMaster()->empty()) - if (MovementGenerator *movgen = c->GetMotionMaster()->top()) - movgen->Interrupt(*c); - - GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation); - SendHeartBeat(); - - // finished relocation, movegen can different from top before creature relocation, - // but apply Reset expected to be safe in any case - if (!c->GetMotionMaster()->empty()) - if (MovementGenerator *movgen = c->GetMotionMaster()->top()) - movgen->Reset(*c); - } -} - -void Unit::NearLandTo(float x, float y, float z, float orientation) -{ - m_movementInfo.RemoveMovementFlag(MOVEFLAG_JUMPING | MOVEFLAG_FALLINGFAR); - m_movementInfo.ChangePosition(x, y, z, orientation); - m_movementInfo.UpdateTime(WorldTimer::getMSTime()); - m_movementInfo.ctime = 0; // Not a client packet. Pauses interpolation. - - WorldPacket data(MSG_MOVE_FALL_LAND, 41); - data << GetPackGUID(); - data << m_movementInfo; - SendMovementMessageToSet(std::move(data), true); - TeleportPositionRelocation(x, y, z, orientation); - DisableSpline(); -} - -void Unit::TeleportPositionRelocation(float x, float y, float z, float orientation) -{ - Player* player = ToPlayer(); - Creature* crea = ToCreature(); - uint32 old_zone = 0; - if (player) - { - player->SetPosition(x, y, z, orientation, true); - player->m_movementInfo.ChangePosition(x, y, z, orientation); - player->m_movementInfo.UpdateTime(WorldTimer::getMSTime()); - } - else if (crea) - { - if (!crea->GetMotionMaster()->empty()) - if (MovementGenerator *movgen = crea->GetMotionMaster()->top()) - movgen->Interrupt(*crea); - GetMap()->CreatureRelocation(crea, x, y, z, orientation); - } - - // new zone - if (player) - { - uint32 newzone, newarea; - GetZoneAndAreaId(newzone, newarea); - if (old_zone != newzone) - player->UpdateZone(newzone, newarea); - // honorless target - if (!player->pvpInfo.inHostileArea) - player->RemoveDelayedOperation(DELAYED_CAST_HONORLESS_TARGET); - } - else if (crea) - { - if (!crea->GetMotionMaster()->empty()) - if (MovementGenerator *movgen = crea->GetMotionMaster()->top()) - movgen->Reset(*crea); - } -} - -void Unit::MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath, bool forceDestination) -{ - uint32 options = 0; - if (generatePath) - options |= MOVE_PATHFINDING; - if (forceDestination) - options |= MOVE_FORCE_DESTINATION; - Movement::MoveSplineInit init(*this, "MonsterMoveWithSpeed"); - init.MoveTo(x, y, z, options); - init.SetVelocity(speed); - init.Launch(); -} - -struct SetPvPHelper -{ - explicit SetPvPHelper(bool _state) : state(_state) {} - void operator()(Unit* unit) const - { - unit->SetPvP(state); - } - bool state; -}; - -void Unit::SetPvP(bool state) -{ - if (state) - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP); - else - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP); - - if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetGroup()) - ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_STATUS); - - CallForAllControlledUnits(SetPvPHelper(state), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); -} - -void Unit::KnockBackFrom(WorldObject* target, float horizontalSpeed, float verticalSpeed) -{ - float angle = this == target ? GetOrientation() + M_PI_F : target->GetAngle(this); - - // set immune anticheat and calculate speed - if (Player* plr = ToPlayer()) - { - plr->SetLaunched(true); - plr->SetXYSpeed(horizontalSpeed); - } - - KnockBack(angle, horizontalSpeed, verticalSpeed); -} - -void Unit::KnockBack(float angle, float horizontalSpeed, float verticalSpeed) -{ - InterruptNonMeleeSpells(false); - - // Effect properly implemented only for players - if (GetTypeId() == TYPEID_PLAYER) - { - float vsin = sin(angle); - float vcos = cos(angle); - 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 << float(horizontalSpeed); // Horizontal speed - data << float(-verticalSpeed); // Z Movement speed (vertical) - SendMovementMessageToSet(std::move(data), true); - - ToPlayer()->GetCheatData()->KnockBack(horizontalSpeed, verticalSpeed, vcos, vsin); - } -} - -struct StopAttackFactionHelper -{ - explicit StopAttackFactionHelper(uint32 _faction_id) : faction_id(_faction_id) {} - void operator()(Unit* unit) const - { - unit->StopAttackFaction(faction_id); - } - uint32 faction_id; -}; - -void Unit::StopAttackFaction(uint32 faction_id) -{ - if (Unit* victim = getVictim()) - { - if (victim->getFactionTemplateEntry()->faction == faction_id) - { - AttackStop(); - if (IsNonMeleeSpellCasted(false)) - InterruptNonMeleeSpells(false); - - // melee and ranged forced attack cancel - if (GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->SendAttackSwingCancelAttack(); - } - } - - AttackerSet const& attackers = getAttackers(); - for (AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();) - { - if ((*itr)->getFactionTemplateEntry()->faction == faction_id) - { - (*itr)->AttackStop(); - itr = attackers.begin(); - } - else - ++itr; - } - - getHostileRefManager().deleteReferencesForFaction(faction_id); - - CallForAllControlledUnits(StopAttackFactionHelper(faction_id), CONTROLLED_PET | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); -} - -void Unit::CleanupDeletedAuras() -{ - for (SpellAuraHolderList::const_iterator iter = m_deletedHolders.begin(); iter != m_deletedHolders.end(); ++iter) - { - if ((*iter)->IsInUse()) - { - // Use case: - // - Spell damage - // - Player::SetDeathState - // - Pet::AddObjectToRemoveList - // Seen happening with spells like [Health Funnel], [Tainted Blood] - ACE_Stack_Trace st; - sLog.outInfo("[Crash/Auras] Deleting aura holder %u in use (%s)", (*iter)->GetId(), GetObjectGuid().GetString().c_str()); - sLog.outInfo("%s", st.c_str()); - } - else - delete *iter; - } - m_deletedHolders.clear(); - - // really delete auras "deleted" while processing its ApplyModify code - for (AuraList::const_iterator iter = m_deletedAuras.begin(); iter != m_deletedAuras.end(); ++iter) - { - if ((*iter)->IsInUse()) - { - ACE_Stack_Trace st; - sLog.outInfo("[Crash/Auras] Deleting aura %u in use (%s)", (*iter)->GetId(), GetObjectGuid().GetString().c_str()); - sLog.outInfo("%s", st.c_str()); - } - else - delete *iter; - } - m_deletedAuras.clear(); -} - -bool Unit::CheckAndIncreaseCastCounter() -{ - uint32 maxCasts = sWorld.getConfig(CONFIG_UINT32_MAX_SPELL_CASTS_IN_CHAIN); - - if (maxCasts && m_castCounter >= maxCasts) - return false; - - ++m_castCounter; - return true; -} - -SpellAuraHolder* Unit::GetSpellAuraHolder(uint32 spellid) const -{ - SpellAuraHolderMap::const_iterator itr = m_spellAuraHolders.find(spellid); - return itr != m_spellAuraHolders.end() ? itr->second : NULL; -} - -SpellAuraHolder* Unit::GetSpellAuraHolder(uint32 spellid, ObjectGuid casterGuid) const -{ - SpellAuraHolderConstBounds bounds = GetSpellAuraHolderBounds(spellid); - for (SpellAuraHolderMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter) - if (iter->second->GetCasterGuid() == casterGuid) - return iter->second; - - return nullptr; -} - - -class RelocationNotifyEvent : public BasicEvent -{ -public: - RelocationNotifyEvent(Unit& owner) : BasicEvent(), m_owner(owner) - { - m_owner._SetAINotifyScheduled(true); - } - - bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) - { - float radius = sWorld.getConfig(CONFIG_FLOAT_MAX_CREATURE_ATTACK_RADIUS) * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO); - if (m_owner.GetTypeId() == TYPEID_PLAYER) - { - MaNGOS::PlayerRelocationNotifier notify((Player&)m_owner); - Cell::VisitAllObjects(&m_owner, notify, radius); - } - else //if(m_owner.GetTypeId() == TYPEID_UNIT) - { - MaNGOS::CreatureRelocationNotifier notify((Creature&)m_owner); - Cell::VisitAllObjects(&m_owner, notify, radius); - } - m_owner._SetAINotifyScheduled(false); - return true; - } - - void Abort(uint64) - { - m_owner._SetAINotifyScheduled(false); - } - -private: - Unit& m_owner; -}; - -void Unit::ScheduleAINotify(uint32 delay) -{ - if (!delay) - { - // Instant - RelocationNotifyEvent event(*this); - event.Execute(0, 0); - return; - } - if (!IsAINotifyScheduled()) - m_Events.AddEvent(new RelocationNotifyEvent(*this), m_Events.CalculateTime(delay)); -} - -void Unit::OnRelocated() -{ - // switch to use G3D::Vector3 is good idea, maybe - float dx = m_last_notified_position.x - GetPositionX(); - float dy = m_last_notified_position.y - GetPositionY(); - float dz = m_last_notified_position.z - GetPositionZ(); - float distsq = dx * dx + dy * dy + dz * dz; - if (distsq > World::GetRelocationLowerLimitSq()) - { - m_last_notified_position.x = GetPositionX(); - m_last_notified_position.y = GetPositionY(); - m_last_notified_position.z = GetPositionZ(); - - if (IsInWorld() && !m_needUpdateVisibility) - AddDelayedAction(OBJECT_DELAYED_ADD_TO_RELOCATED_LIST); - } - ScheduleAINotify(World::GetRelocationAINotifyDelay()); -} - -void Unit::ProcessRelocationVisibilityUpdates() -{ - m_needUpdateVisibility = false; - if (!IsInWorld()) - return; - - GetViewPoint().Call_UpdateVisibilityForOwner(); // HEAVY LOAD - UpdateObjectVisibility(); -} - -// BEGIN Nostalrius specific functions -void Unit::InterruptSpellsCastedOnMe(bool killDelayed, bool interruptPositiveSpells) -{ - std::list targets; - // Maximum spell range=100m ? - MaNGOS::AnyUnitInObjectRangeCheck u_check(this, 100.0f); - MaNGOS::UnitListSearcher searcher(targets, u_check); - Cell::VisitAllObjects(this, searcher, GetMap()->GetVisibilityDistance()); - for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) - { - if (!interruptPositiveSpells && IsFriendlyTo(*iter)) - continue; - for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++) - if (Spell *spell = (*iter)->GetCurrentSpell(CurrentSpellTypes(i))) - if (spell->m_targets.getUnitTargetGuid() == GetObjectGuid()) - if (killDelayed || (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) || i == CURRENT_CHANNELED_SPELL) - (*iter)->InterruptSpell(CurrentSpellTypes(i), true); - if (!killDelayed) - continue; - // 2/ Interruption des sorts qui ne sont plus reference, mais dont il reste un event (ceux en parcours par exemple) - auto i_Events = (*iter)->m_Events.GetEvents().begin(); - for (; i_Events != (*iter)->m_Events.GetEvents().end(); ++i_Events) - if (SpellEvent* event = dynamic_cast(i_Events->second)) - if (event && event->GetSpell()->m_targets.getUnitTargetGuid() == GetObjectGuid()) - if (event->GetSpell()->getState() != SPELL_STATE_FINISHED) - event->GetSpell()->cancel(); - } -} - -void Unit::InterruptAttacksOnMe(float dist) -{ - if (dist == 0.0f) - dist = GetMap()->GetVisibilityDistance(); - std::list targets; - MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist); - MaNGOS::UnitListSearcher searcher(targets, u_check); - Cell::VisitAllObjects(this, searcher, dist); - for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) - { - if ((*iter)->getVictim() != this) - continue; - (*iter)->AttackStop(); - if (Player* pAttacker = (*iter)->ToPlayer()) - pAttacker->SendAttackSwingCancelAttack(); - } -} - -void Unit::CombatStopInRange(float dist) -{ - if (dist == 0.0f) - dist = GetMap()->GetVisibilityDistance(); - std::list targets; - MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist); - MaNGOS::UnitListSearcher searcher(targets, u_check); - Cell::VisitAllObjects(this, searcher, dist); - for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) - (*iter)->CombatStopWithPets(true); -} - -uint32 Unit::DespawnNearCreaturesByEntry(uint32 entry, float range) -{ - std::list creatures; - GetCreatureListWithEntryInGrid(creatures, entry, range); - uint32 count = 0; - for (std::list::iterator it = creatures.begin(); it != creatures.end(); ++it) - { - if ((*it)->IsInWorld()) - { - ++count; - (*it)->DisappearAndDie(); - } - } - return count; -} - -uint32 Unit::RespawnNearCreaturesByEntry(uint32 entry, float range) -{ - if (range == 0.0f) - range = GetMap()->GetVisibilityDistance(); - uint32 count = 0; - std::list lList; - GetCreatureListWithEntryInGrid(lList, entry, range); - for (std::list::iterator it = lList.begin(); it != lList.end(); ++it) - { - if (!(*it)->isAlive()) - { - (*it)->Respawn(); - ++count; - } - } - return count; -} - - -uint32 Unit::DespawnHostileCreaturesInRange(float range) -{ - if (range == 0.0f) - range = GetMap()->GetVisibilityDistance(); - uint32 count = 0; - std::list targets; - MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, range); - MaNGOS::UnitListSearcher searcher(targets, u_check); - Cell::VisitAllObjects(this, searcher, range); - for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) - { - if ((*iter)->GetTypeId() == TYPEID_UNIT) - { - ++count; - (*iter)->AddObjectToRemoveList(); - } - } - return count; -} - -bool Unit::IsWithinMeleeRange(const Unit *obj, float dist) const -{ - if (!obj || !IsInMap(obj)) - return false; - - float dx = GetPositionX() - obj->GetPositionX(); - float dy = GetPositionY() - obj->GetPositionY(); - float dz = GetPositionZ() - obj->GetPositionZ(); - float distsq = dx * dx + dy * dy + dz * dz; - - float maxdist = dist + BASE_MELEERANGE_OFFSET + GetMeleeReach() + obj->GetObjectBoundingRadius(); - - if (maxdist < ATTACK_DISTANCE) - maxdist = ATTACK_DISTANCE; - - return distsq < maxdist * maxdist; -} - -// TriniyCore -void Unit::GetRandomAttackPoint(const Unit* attacker, float &x, float &y, float &z) const -{ - // Compute random angle - float angle = GetAngle(attacker); - float sizeFactor = GetObjectBoundingRadius() + attacker->GetObjectBoundingRadius(); - if (sizeFactor < 0.1f) - sizeFactor = DEFAULT_COMBAT_REACH; - - uint32 attacker_number = getAttackers().size(); - if (attacker_number > 0) - --attacker_number; - // Don't compute a random position for a moving player - if (GetTypeId() == TYPEID_PLAYER && IsMoving()) - attacker_number = 0; - angle += (attacker_number ? ((float(M_PI / 2) - float(M_PI) * rand_norm_f()) * attacker_number / sizeFactor) * 0.3f : 0); - - float dist = attacker->GetObjectBoundingRadius() + GetObjectBoundingRadius() + rand_norm_f() * (attacker->GetMeleeReach() - attacker->GetObjectBoundingRadius()); - float initialPosX, initialPosY, initialPosZ, o; - GetPosition(initialPosX, initialPosY, initialPosZ); - - // Moving player: try to interpolate movement a bit - if (GetTypeId() == TYPEID_PLAYER && IsMoving()) - if (!ToPlayer()->GetCheatData()->InterpolateMovement(m_movementInfo, 200, initialPosX, initialPosY, initialPosZ, o)) - GetPosition(initialPosX, initialPosY, initialPosZ); - - float attackerTargetDistance = sqrt(pow(initialPosX - attacker->GetPositionX(), 2) + - pow(initialPosY - attacker->GetPositionY(), 2) + - pow(initialPosZ - attacker->GetPositionZ(), 2)); - if (dist > attackerTargetDistance) - { - // On ne bouge pas, on est deja a portee. - attacker->GetPosition(x, y, z); - return; - } - float normalizedVectZ = (attacker->GetPositionZ() - initialPosZ) / attackerTargetDistance; - float normalizedVectXY = sqrt(1 - normalizedVectZ * normalizedVectZ); - x = initialPosX + dist * cos(angle) * normalizedVectXY; - y = initialPosY + dist * sin(angle) * normalizedVectXY; - z = initialPosZ + dist * normalizedVectZ; - - if ((attacker->CanFly() || (attacker->CanSwim() && IsInWater()))) - { - GetMap()->GetLosHitPosition(initialPosX, initialPosY, initialPosZ, x, y, z, -0.2f); - if (attacker->CanFly()) - return; - float ground = 0.0f; - float waterSurface = GetTerrain()->GetWaterLevel(x, y, z, &ground); - if (waterSurface == VMAP_INVALID_HEIGHT_VALUE) - waterSurface = GetPositionZ(); - if (z > waterSurface) - z = waterSurface; - if (z < ground) - z = ground; - } - else - { - uint32 nav = NAV_GROUND | NAV_WATER; - if (attacker->GetTypeId() != TYPEID_PLAYER) - nav |= NAV_MAGMA | NAV_SLIME; - // Try mmaps. On fail, use target position (but should not fail) - if (!GetMap()->GetWalkHitPosition(GetTransport(), initialPosX, initialPosY, initialPosZ, x, y, z, nav)) - GetPosition(x, y, z); - } -} - -float Unit::GetMeleeReach() const -{ - return GetCombatReach(true); -} - -float Unit::GetCombatReach(bool forMeleeRange /*=true*/) const -{ - float reach = GetFloatValue(UNIT_FIELD_COMBATREACH); - return (forMeleeRange && reach < 1.5f) ? 1.5f : reach; -} - -float Unit::GetCombatReach(Unit const* pVictim, bool forMeleeRange /*=true*/, float flat_mod /*=0.0f*/) const -{ - float victimReach = (pVictim && pVictim->IsInWorld()) - ? pVictim->GetCombatReach(forMeleeRange) - : 0.0f; - - float reach = GetCombatReach(forMeleeRange) + victimReach + flat_mod; - - if (forMeleeRange) - { - reach += BASE_MELEERANGE_OFFSET; - if (reach < ATTACK_DISTANCE) - reach = ATTACK_DISTANCE; - } - - // Melee leeway mechanic. - // When both player and target has > 70% of normal runspeed, and are moving, - // the player gains an additional 2.5yd of melee range. - if (IsPlayer()) - { - static const float leewayMinSpeed = 4.97f; - if (GetXZFlagBasedSpeed(this) > leewayMinSpeed && GetXZFlagBasedSpeed(pVictim) > leewayMinSpeed) - reach += 2.5f; - } - - return reach; -} - -bool Unit::CanReachWithMeleeAttack(Unit const* pVictim, float flat_mod /*= 0.0f*/) const -{ - if (!pVictim || !pVictim->IsInWorld()) - return false; - - float reach = GetCombatReach(pVictim, true, flat_mod); - - // This check is not related to bounding radius - float dx = GetPositionX() - pVictim->GetPositionX(); - float dy = GetPositionY() - pVictim->GetPositionY(); - float dz = GetPositionZ() - pVictim->GetPositionZ(); - - return (dx * dx + dy * dy < reach * reach) && ((dz * dz) < MELEE_Z_LIMIT); -} - -bool Unit::CanReachWithMeleeSpellAttack(Unit const* pVictim, float flat_mod /*= 0.0f*/) const -{ - if (!pVictim || !pVictim->IsInWorld()) - return false; - - float reach = GetCombatReach(pVictim, true, flat_mod); - - // This check is not related to bounding radius - float dx = GetPositionX() - pVictim->GetPositionX(); - float dy = GetPositionY() - pVictim->GetPositionY(); - - // melee spells ignore Z-axis checks - return dx * dx + dy * dy < reach * reach; -} - -Unit* Unit::GetUnit(WorldObject &obj, uint64 const &Guid) -{ - if (obj.IsInWorld()) - return obj.GetMap()->GetUnit(ObjectGuid(Guid)); - return nullptr; -} - -Unit* Unit::SummonCreatureAndAttack(uint32 creatureEntry, Unit* pVictim) -{ - float summonX, summonY, summonZ, summonAng; - summonX = GetPositionX(); - summonY = GetPositionY(); - summonZ = GetPositionZ(); - summonAng = GetOrientation(); - - if (!pVictim) - if (!(pVictim = getVictim())) - return nullptr; - - if (Creature *pCreature = SummonCreature(creatureEntry, summonX, summonY, summonZ, summonAng, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 25000)) - { - if (pCreature->AI()) - pCreature->AI()->AttackStart(pVictim); - return pCreature; - } - return nullptr; -} - -bool Unit::IsCaster() -{ - // Cast en cours : on est casteur. - if (IsNonMeleeSpellCasted(true, false, true)) - return true; - - switch (getClass()) - { - case CLASS_WARRIOR: - case CLASS_ROGUE: - return false; - case CLASS_MAGE: - case CLASS_PRIEST: - case CLASS_SHAMAN: - case CLASS_HUNTER: - case CLASS_WARLOCK: - return true; - // Pala heal si faveur divine. Sinon CaC. - case CLASS_PALADIN: - return HasSpell(20216); - // Druide caster ? - case CLASS_DRUID: - if (HasAura(14858)) // Forme de Selenien - return true; - if (HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) // Dans une forme (donc CaC, ou voyage ou aquatique) - return false; - return true; // Pas en changeforme, on suppose qu'il est casteur. - default: - return false; - } -} - -void Unit::EnterVanish() -{ - SetVisibility(VISIBILITY_OFF); - SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); - InterruptSpellsCastedOnMe(true); - InterruptAttacksOnMe(); - AttackStop(); - InterruptSpell(CURRENT_AUTOREPEAT_SPELL); - // DoResetThreat : - if (Creature* pCrea = ToCreature()) - { - if (!pCrea->CanHaveThreatList() || pCrea->getThreatManager().isThreatListEmpty()) - return; - - ThreatList const& tList = pCrea->getThreatManager().getThreatList(); - for (ThreatList::const_iterator itr = tList.begin(); itr != tList.end(); ++itr) - { - Unit* pUnit = pCrea->GetMap()->GetUnit((*itr)->getUnitGuid()); - - if (pUnit && pCrea->getThreatManager().getThreat(pUnit)) - pCrea->getThreatManager().modifyThreatPercent(pUnit, -100); - } - } -} - -void Unit::LeaveVanish() -{ - SetVisibility(VISIBILITY_ON); - RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FIELD_FLAGS); -} - -void Unit::Ambush(Unit* pNewVictim, uint32 embushSpellId) -{ - if (!pNewVictim) - return; - if (Creature* pCrea = ToCreature()) - { - // Se position derriere - float x, y, z; - pNewVictim->GetRelativePositions(-4.0f, 0.0f, 0.0f, x, y, z); - pCrea->NearTeleportTo(x, y, z, 0.0f); - pCrea->SetFacingToObject(pNewVictim); - // Embush - if (embushSpellId) - pCrea->CastSpell(pNewVictim, embushSpellId, true); - if (pCrea->AI()) - pCrea->AI()->AttackStart(pNewVictim); - } -} - -bool Unit::isAttackableByAOE(bool requireDeadTarget) const -{ - if (isAlive() == requireDeadTarget) - return false; - - if (HasFlag(UNIT_FIELD_FLAGS, - UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE)) - return false; - - if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->isGameMaster()) - return false; - - return true; -} - -bool Unit::IsImmuneToSchoolMask(uint32 schoolMask) const -{ - AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY); - - uint32 immuneMask = 0; - for (AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr) - { - immuneMask |= (*itr)->GetModifier()->m_miscvalue; - if (immuneMask & schoolMask) // Immunise - return true; - } - return false; -} - -void Unit::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) -{ - // Still needed ... ? - ProhibitSpellInfo inf; - inf.SchoolMask = idSchoolMask; - inf.RestingMsTime = unTimeMs; - m_prohibitSpell.push_back(inf); -} - -bool Unit::IsSpellProhibited(SpellEntry const* pSpell) -{ - uint32 spellSchoolMask = GetSpellSchoolMask(pSpell); - for (ProhibitSpellList::const_iterator it = m_prohibitSpell.begin(); it != m_prohibitSpell.end(); ++it) - { - if (it->SchoolMask & spellSchoolMask) - return true; - } - return false; -} - -bool Unit::HasProhibitedSpell() -{ - return (m_prohibitSpell.size() > 0); -} - -CreatureAI* Unit::AI() const -{ - return GetTypeId() == TYPEID_UNIT ? ((Creature*)this)->AI() : NULL; -} - -SpellAuraHolder* Unit::AddAura(uint32 spellId, uint32 addAuraFlags, Unit* pCaster) -{ - if (IsDeleted() || (pCaster && pCaster->IsDeleted())) - return nullptr; - - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); - if (!spellInfo) - return nullptr; - - if (!IsSpellAppliesAura(spellInfo, (1 << EFFECT_INDEX_0) | (1 << EFFECT_INDEX_1) | (1 << EFFECT_INDEX_2)) && - !IsSpellHaveEffect(spellInfo, SPELL_EFFECT_PERSISTENT_AREA_AURA)) - { - sLog.outError("Impossible d'appliquer le sort %u : il n'a pas d'aura !", spellInfo->Id); - return nullptr; - } - - if (!pCaster) - pCaster = this; - - SpellAuraHolder *holder = CreateSpellAuraHolder(spellInfo, this, pCaster); - if (!holder) - return nullptr; - - if (addAuraFlags & ADD_AURA_PASSIVE) - holder->SetPassive(true); - if (addAuraFlags & ADD_AURA_PERMANENT) - holder->SetPermanent(true); - - for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) - { - uint8 eff = spellInfo->Effect[i]; - if (eff >= TOTAL_SPELL_EFFECTS) - continue; - - if (IsAreaAuraEffect(eff) || - eff == SPELL_EFFECT_APPLY_AURA || - eff == SPELL_EFFECT_PERSISTENT_AREA_AURA) - { - Aura *aur = CreateAura(spellInfo, SpellEffectIndex(i), nullptr, holder, this, pCaster); - if (addAuraFlags & ADD_AURA_POSITIVE) - aur->SetPositive(true); - else if (addAuraFlags & ADD_AURA_NEGATIVE) - aur->SetPositive(true); - - holder->AddAura(aur, SpellEffectIndex(i)); - } - } - if (!AddSpellAuraHolder(holder)) - holder = nullptr; - return holder; -} - -SpellAuraHolder* Unit::RefreshAura(uint32 spellId, int32 duration) -{ - if (SpellAuraHolder *holder = GetSpellAuraHolder(spellId)) - { - holder->SetAuraDuration(duration); - holder->UpdateAuraDuration(); - return holder; - } - return nullptr; -} - -bool Unit::HasMorePowerfullSpellActive(SpellEntry const* spell) -{ - std::list morePowerfullSpells; - if (!sSpellMgr.ListMorePowerfullSpells(spell->Id, morePowerfullSpells)) - return false; - for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) - for (std::list::const_iterator it = morePowerfullSpells.begin(); it != morePowerfullSpells.end(); ++it) - if ((*it) == i->first) - return true; - return false; -} - -Aura* Unit::GetMostImportantAuraAfter(Aura const* like, Aura const* except) -{ - ASSERT(like); - AuraType auraName = like->GetModifier()->m_auraname; - - // Certains area aura (Cf AreaAura::AreaAura), exemple 8836, 10626 - if (auraName == SPELL_AURA_NONE) - return nullptr; - - if (auraName >= TOTAL_AURAS) - { - sLog.outInfo("[AURASTACK][%u] auraName %u invalide.", like->GetId(), auraName); - return nullptr; - } - - Aura* currMostImportant = nullptr; - for (AuraList::iterator iter = m_modAuras[auraName].begin(); iter != m_modAuras[auraName].end(); ++iter) - { - if (!(*iter)->IsExclusive() || (*iter) == except) - continue; - if (!currMostImportant) - { - int checkResult = (*iter)->CheckExclusiveWith(like); - // On veut un aura de meme type que 'like'. Osef qu'il soit mieux ou moins bien ici. - if (checkResult > 0) - currMostImportant = (*iter); - } - else - { - int checkResult = (*iter)->CheckExclusiveWith(currMostImportant); - // '*iter' doit etre mieux que 'currMostImportant' - if (checkResult == 1) - currMostImportant = (*iter); - } - } - if (currMostImportant) - { - // A-t-on trouve ce qu'il faut ? - // Different de 'except' - ASSERT(currMostImportant != except); - // Et de meme type que 'like'. - ASSERT(currMostImportant->CheckExclusiveWith(like) > 0); - } - return currMostImportant; -} - -// Nostalrius : Ivina -void Unit::SetLastCastedSpell(uint32 spell_id, bool byclient) -{ - if (spell_id != 23303 && spell_id != 836) - m_lastCastedSpellID = spell_id; -} - -uint32 Unit::GetLastCastedSpell(bool byclientonly) -{ - if (byclientonly) - return 0; - else - return m_lastCastedSpellID; -} - -uint32 Unit::GetLastAttackType() -{ - return m_lastAttackType; -} - -void Unit::SetLastAttackType(uint32 attackType) -{ - m_lastAttackType = attackType; -} - -void Unit::UpdateSplineMovement(uint32 t_diff) -{ - if (movespline->Finalized()) - return; - - movespline->updateState(t_diff); - bool arrived = movespline->Finalized(); - - if (arrived) - DisableSpline(); - else if (!movespline->isCyclic() && movespline->getLastPointSent() >= 0 && movespline->getLastPointSent() < (movespline->currentPathIdx() + 3)) - { - WorldPacket data(SMSG_MONSTER_MOVE, 64); - data << GetPackGUID(); - movespline->setLastPointSent(Movement::PacketBuilder::WriteMonsterMove(*movespline, data, movespline->getLastPointSent() + 1)); - SendMovementMessageToSet(std::move(data), true); - } - - Movement::Location loc = movespline->ComputePosition(); - if (Transport* t = GetTransport()) - { - m_movementInfo.GetTransportPos()->x = loc.x; - m_movementInfo.GetTransportPos()->y = loc.y; - m_movementInfo.GetTransportPos()->z = loc.z; - m_movementInfo.GetTransportPos()->o = loc.orientation; - t->CalculatePassengerPosition(loc.x, loc.y, loc.z, &loc.orientation); - } - if (!MaNGOS::IsValidMapCoord(loc.x, loc.y, loc.z)) - return; - - if (GetTypeId() == TYPEID_PLAYER) - ((Player*)this)->SetPosition(loc.x, loc.y, loc.z, loc.orientation); - else - GetMap()->CreatureRelocation((Creature*)this, loc.x, loc.y, loc.z, loc.orientation); -} - -void Unit::MonsterMove(float x, float y, float z) -{ - MonsterMoveWithSpeed(x, y, z, GetSpeed(MOVE_RUN)); -} - - -void Unit::SetWalk(bool enable, bool asDefault) -{ - if (asDefault) - { - if (enable) - clearUnitState(UNIT_STAT_RUNNING); - else - addUnitState(UNIT_STAT_RUNNING); - } - - if (enable == m_movementInfo.HasMovementFlag(MOVEFLAG_WALK_MODE)) - return; - - if (enable) - m_movementInfo.AddMovementFlag(MOVEFLAG_WALK_MODE); - else - m_movementInfo.RemoveMovementFlag(MOVEFLAG_WALK_MODE); - - WorldPacket data(enable ? SMSG_SPLINE_MOVE_SET_WALK_MODE : SMSG_SPLINE_MOVE_SET_RUN_MODE, 9); - data << GetPackGUID(); - if (Player* me = ToPlayer()) - me->GetSession()->SendPacket(&data); - else - SendObjectMessageToSet(&data, false); -} - -void Unit::SetLevitate(bool enable) -{ - if (enable) - m_movementInfo.AddMovementFlag(MOVEFLAG_LEVITATING); - else - m_movementInfo.RemoveMovementFlag(MOVEFLAG_LEVITATING); -} - -void Unit::SetFly(bool enable) -{ - if (enable) - m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING | MOVEFLAG_CAN_FLY); - else - m_movementInfo.RemoveMovementFlag(MOVEFLAG_FLYING | MOVEFLAG_CAN_FLY); -} - -void Unit::DisableSpline() -{ - if (Player* me = ToPlayer()) - me->SetFallInformation(0, me->GetPositionZ()); - m_movementInfo.RemoveMovementFlag(MovementFlags(MOVEFLAG_SPLINE_ENABLED | MOVEFLAG_FORWARD)); - movespline->_Interrupt(); -} - - -void Unit::SendSpellGo(Unit* target, uint32 spellId) -{ - SpellCastTargets targets; - targets.setUnitTarget(target); - - WorldPacket data(SMSG_SPELL_GO, 53); - data << GetPackGUID(); - - data << GetPackGUID(); - data << uint32(spellId); - data << uint16(CAST_FLAG_UNKNOWN9); - - //WriteSpellGoTargets(&data); - data << uint8(1); - data << target->GetObjectGuid(); - data << uint8(0); - - data << targets; - SendMessageToSet(&data, true); -} - -#define PRELOAD if (this == unit) return true; \ -const Unit* u1 = GetCharmerOrOwnerOrSelf(); \ -const Unit* u2 = unit->GetCharmerOrOwnerOrSelf(); \ -if (u1 == u2) return true; - - -bool Unit::IsInPartyWith(Unit const* unit) const -{ - PRELOAD - if (u1->IsPlayer() && u2->IsPlayer()) - return u1->ToPlayer()->IsInSameGroupWith(u2->ToPlayer()); - return false; -} - -bool Unit::IsInRaidWith(Unit const* unit) const -{ - PRELOAD - if (u1->IsPlayer() && u2->IsPlayer()) - return u1->ToPlayer()->IsInSameRaidWith(u2->ToPlayer()); - return false; -} - -void Unit::Debug(uint32 flags, const char* format, ...) const -{ - if (!format) - return; - if (!(flags & _debugFlags)) - return; - if (_debuggerGuid.IsEmpty()) - return; - if (!IsInWorld() || !FindMap()) - return; - Player* player = FindMap()->GetPlayer(_debuggerGuid); - if (!player) - { - Unit* me = (Unit*)this; - me->_debuggerGuid.Clear(); - me->_debugFlags = 0; - return; - } - va_list ap; - va_start(ap, format); - char str[2048]; - vsnprintf(str, 2048, format, ap); - va_end(ap); - ChatHandler(player).SendSysMessage(str); -} - -class ThreatTransferDo -{ -public: - ThreatTransferDo(Unit* from, Unit* to) : _from(from), _to(to) {} - void operator()(Unit* unit) - { - if (unit == _from || unit == _to) - return; - if (!unit->IsValidAttackTarget(_to)) - return; - - if (unit->getThreatManager().getThreat(_from) > 0.1f) - unit->AddThreat(_to, unit->getThreatManager().getThreat(_from)); - else if (unit->getVictim() == _from) // Si on aggro sans faire de degat - unit->AI()->AttackStart(_to); - else - return; - unit->getThreatManager().modifyThreatPercent(_from, -100); - } -protected: - Unit* _from; - Unit* _to; -}; - -void Unit::TransferAttackersThreatTo(Unit* unit) -{ - ThreatTransferDo u_do(this, unit); - MaNGOS::CreatureWorker worker(this, u_do); - Cell::VisitGridObjects(this, worker, 50.0f); -} - -void Unit::SetMovement(UnitMovementType pType) -{ - switch (pType) - { - case MOVE_ROOT: - m_movementInfo.ChangePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); - m_movementInfo.UpdateTime(WorldTimer::getMSTime()); - m_movementInfo.moveFlags = MOVEFLAG_ROOT | (m_movementInfo.moveFlags & ~MOVEFLAG_MASK_MOVING_OR_TURN); - break; - case MOVE_UNROOT: - m_movementInfo.ChangePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); - m_movementInfo.UpdateTime(WorldTimer::getMSTime()); - m_movementInfo.moveFlags = (m_movementInfo.moveFlags & ~(MOVEFLAG_MASK_MOVING_OR_TURN | MOVEFLAG_ROOT)); - break; - } - WorldPacket data; - if (!movespline->Finalized()) - { - // Spline roots are sent here. - MovementData mvtData(this); - switch (pType) - { - case MOVE_ROOT: - mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_ROOT, GetObjectGuid()); - return; - case MOVE_UNROOT: - mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_UNROOT, GetObjectGuid()); - break; - case MOVE_WATER_WALK: - mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_WATER_WALK, GetObjectGuid()); - break; - case MOVE_LAND_WALK: - mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_LAND_WALK, GetObjectGuid()); - break; - } - return; - } - // Inform controller - Player* mePlayer = ToPlayer(); - Player* controller = nullptr; - if (Unit* charmer = GetCharmer()) - if (Player* charmerPlayer = charmer->ToPlayer()) - if (charmerPlayer->GetCharmGuid() == GetObjectGuid()) - controller = charmerPlayer; - if (!mePlayer && !controller) - return; - - switch (pType) - { - case MOVE_ROOT: - data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size() + 4); - break; - case MOVE_UNROOT: - data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size() + 4); - break; - case MOVE_WATER_WALK: - data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size() + 4); - break; - case MOVE_LAND_WALK: - data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size() + 4); - break; - default: - sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.", pType); - return; - } - data << GetPackGUID(); - data << uint32(WorldTimer::getMSTime()); // Peut etre msTime : WorldTimer::getMSTime() ? - if (mePlayer) - { - mePlayer->GetCheatData()->OrderSent(&data); - mePlayer->GetSession()->SendPacket(&data); - - // Send root messages now rather than on acks from the force messages - // so our state is consistent - if (pType == MOVE_ROOT || pType == MOVE_UNROOT) { - WorldPacket rootData(pType == MOVE_ROOT ? MSG_MOVE_ROOT : MSG_MOVE_UNROOT, 31); - rootData << GetPackGUID(); - rootData << m_movementInfo; - - mePlayer->SendMovementMessageToSet(std::move(rootData), false); - } - } - if (controller) - controller->GetSession()->SendPacket(&data); -} - -bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const -{ - AuraList const& auras = GetAurasByType(type); - for (AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) - if ((!excludeAura || excludeAura != (*itr)->GetSpellProto()->Id) && //Avoid self interrupt of channeled Crowd Control spells like Seduction - ((*itr)->GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE)) - return true; - return false; -} - -bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) const -{ - uint32 excludeAura = 0; - if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : NULL) - excludeAura = currentChanneledSpell->m_spellInfo->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction - - return (HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura) - //|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_FEAR, excludeAura) // no breakable fears in vanilla - || HasBreakableByDamageAuraType(SPELL_AURA_MOD_STUN, excludeAura) - //|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT, excludeAura) // no breakable roots in vanilla - || HasBreakableByDamageAuraType(SPELL_AURA_TRANSFORM, excludeAura)); -} - -void Unit::UpdateControl() -{ - Player* mePlayer = ToPlayer(); - - // Inform controller - if (Unit* charmer = GetCharmer()) - if (Player* charmerPlayer = charmer->ToPlayer()) - if (charmerPlayer->GetCharmGuid() == GetObjectGuid()) - charmerPlayer->SetClientControl(this, !hasUnitState(UNIT_STAT_FLEEING | UNIT_STAT_CONFUSED)); - // Inform myself - if (mePlayer) - { - // Possessing someone ? - if (Unit* possessed = GetCharm()) - if (possessed->GetCharmerGuid() == GetObjectGuid()) - { - mePlayer->SetClientControl(possessed, !possessed->hasUnitState(UNIT_STAT_FLEEING | UNIT_STAT_CONFUSED)); - return; - } - mePlayer->SetClientControl(mePlayer, !hasUnitState(UNIT_STAT_CONTROLLED | UNIT_STAT_FLEEING | UNIT_STAT_CONFUSED) && !GetCharmerGuid()); - } -} - -// select nearest hostile unit within the given distance (regardless of threat list). -Unit* Unit::SelectNearestTarget(float dist) const -{ - CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY())); - Cell cell(p); - cell.SetNoCreate(); - - Unit *target = nullptr; - - if (dist == 0.0f || dist > MAX_VISIBILITY_DISTANCE) - dist = MAX_VISIBILITY_DISTANCE; - - MaNGOS::NearestHostileUnitCheck u_check(this, dist); - MaNGOS::UnitLastSearcher searcher(target, u_check); - - TypeContainerVisitor, WorldTypeMapContainer > world_unit_searcher(searcher); - TypeContainerVisitor, GridTypeMapContainer > grid_unit_searcher(searcher); - - cell.Visit(p, world_unit_searcher, *GetMap(), *this, dist); - cell.Visit(p, grid_unit_searcher, *GetMap(), *this, dist); - - return target; -} - -float Unit::GetMinChaseDistance(Unit* victim) const -{ - if (_casterChaseDistance > 1.0f) - return _casterChaseDistance; - return GetObjectBoundingRadius(); -} - -float Unit::GetMaxChaseDistance(Unit* victim) const -{ - if (_casterChaseDistance > 1.0f) - return _casterChaseDistance + GetObjectBoundingRadius() + victim->GetObjectBoundingRadius(); - return GetMeleeReach() + BASE_MELEERANGE_OFFSET; -} - -void Unit::RestoreMovement() -{ - if (GetTypeId() != TYPEID_UNIT) - return; - // Need restore previous movement since we have no proper states system - if (isAlive() && !hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING)) - { - if (Unit * victim = getVictim()) - GetMotionMaster()->MoveChase(victim); - else - GetMotionMaster()->Initialize(); - } -} - -/** Spell cooldown management system. Shared by Players, Creatures, Pets, ... */ -void Unit::RemoveSpellCooldown(uint32 spell_id, bool update /* = false */) -{ - m_spellCooldowns.erase(spell_id); - - if (update) - if (Player* player = GetAffectingPlayer()) - player->SendClearCooldown(spell_id, this); -} - -bool Unit::HasSpellCategoryCooldown(uint32 cat) const -{ - if (!cat) - return false; - for (SpellCooldowns::const_iterator it = m_spellCooldowns.begin(); it != m_spellCooldowns.end(); ++it) - if (it->second.cat == cat && it->second.categoryEnd > time(nullptr)) - return true; - return false; -} - -void Unit::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) -{ - SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat); - if (ct == sSpellCategoryStore.end()) - return; - - const SpellCategorySet& ct_set = ct->second; - for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();) - { - if (ct_set.find(i->first) != ct_set.end()) - RemoveSpellCooldown((i++)->first, update); - else - ++i; - } -} - -void Unit::RemoveAllSpellCooldown() -{ - if (!m_spellCooldowns.empty()) - { - if (Player* player = GetAffectingPlayer()) - for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr) - player->SendClearCooldown(itr->first, this); - - m_spellCooldowns.clear(); - } -} - -void Unit::CooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell) -{ - // start cooldowns at server side, if any - AddSpellAndCategoryCooldowns(spellInfo, itemId, spell); - - // Send activate cooldown timer (possible 0) at client side - if (Player* player = GetAffectingPlayer()) - { - WorldPacket data(SMSG_COOLDOWN_EVENT, (4 + 8)); - data << uint32(spellInfo->Id); - data << GetObjectGuid(); - player->SendDirectMessage(&data); - } -} - -void Unit::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown) -{ - // init cooldown values - uint32 cat = 0; - int32 rec = -1; - int32 catrec = -1; - - // some special item spells without correct cooldown in SpellInfo - // cooldown information stored in item prototype - // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client. - - if (itemId) - { - if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId)) - { - for (int idx = 0; idx < MAX_ITEM_PROTO_SPELLS; ++idx) - { - if (proto->Spells[idx].SpellId == spellInfo->Id) - { - cat = proto->Spells[idx].SpellCategory; - rec = proto->Spells[idx].SpellCooldown; - catrec = proto->Spells[idx].SpellCategoryCooldown; - break; - } - } - } - } - - // if no cooldown found above then base at DBC data - if (rec < 0 && catrec < 0) - { - cat = spellInfo->Category; - rec = spellInfo->RecoveryTime; - catrec = spellInfo->CategoryRecoveryTime; - } - - time_t curTime = time(nullptr); - - time_t catrecTime; - time_t recTime; - - // overwrite time for selected category - if (infinityCooldown) - { - // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped) - // but not allow ignore until reset or re-login - catrecTime = catrec > 0 ? curTime + infinityCooldownDelay : 0; - recTime = rec > 0 ? curTime + infinityCooldownDelay : catrecTime; - } - else - { - // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK) - // prevent 0 cooldowns set by another way - if (rec <= 0 && catrec <= 0 && (cat == 76 || cat == 351)) - rec = GetAttackTime(RANGED_ATTACK); - - if (rec > 0 || catrec > 0) - { - if (Player* modOwner = GetSpellModOwner()) - { - // Now we have cooldown data (if found any), time to apply mods - if (rec > 0) - modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell); - - if (catrec > 0) - modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell); - } - if (Player* player = GetAffectingPlayer()) - if (player != this) - player->SendSpellCooldown(spellInfo->Id, rec > catrec ? rec : catrec, GetObjectGuid()); - } - - // replace negative cooldowns by 0 - if (rec < 0) rec = 0; - if (catrec < 0) catrec = 0; - - // Hackfix: minimum cooldown for controlled creatures - if (!rec && !catrec && GetTypeId() == TYPEID_UNIT && GetCharmerGuid().IsPlayer()) - rec = 1500; // Global cooldown - - // no cooldown after applying spell mods - if (rec == 0 && catrec == 0) - return; - - catrecTime = catrec ? curTime + catrec / IN_MILLISECONDS : 0; - recTime = rec ? curTime + rec / IN_MILLISECONDS : catrecTime; - } - - // self spell cooldown - if (recTime > 0) - AddSpellCooldown(spellInfo->Id, itemId, recTime, catrecTime, cat); -} - -void Unit::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t endTime, time_t categoryEndTime, uint32 cat) -{ - // Do not replace longer cooldown - SpellCooldowns::iterator it = m_spellCooldowns.find(spellid); - if (it != m_spellCooldowns.end()) - { - it->second.end = endTime; - it->second.categoryEnd = categoryEndTime; - return; - } - SpellCooldown sc; - sc.end = endTime; - sc.categoryEnd = categoryEndTime; - sc.itemid = itemid; - sc.cat = cat; - m_spellCooldowns[spellid] = sc; -} - - -void Unit::WritePetSpellsCooldown(WorldPacket& data) -{ - uint8 cooldownsCount = GetSpellCooldownMap().size(); - data << uint8(cooldownsCount); - - time_t curTime = time(nullptr); - - for (SpellCooldowns::const_iterator itr = GetSpellCooldownMap().begin(); itr != GetSpellCooldownMap().end(); ++itr) - { - //time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0; - - data << uint16(itr->first); // spellid - data << uint16(0); // spell category? - data << uint32(IN_MILLISECONDS * (itr->second.end - curTime)); // cooldown - data << uint32(0); // category cooldown - } -} - - -void Unit::InitPlayerDisplayIds() -{ - PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass()); - if (!info) - return; - - uint8 gender = getGender(); - - switch (gender) - { - case GENDER_FEMALE: - SetDisplayId(info->displayId_f); - SetNativeDisplayId(info->displayId_f); - break; - case GENDER_MALE: - SetDisplayId(info->displayId_m); - SetNativeDisplayId(info->displayId_m); - break; - default: - return; - } -} +/* + * Copyright (C) 2005-2011 MaNGOS + * Copyright (C) 2009-2011 MaNGOSZero + * + * + * 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 + */ + +#include "Unit.h" +#include "Log.h" +#include "Opcodes.h" +#include "WorldPacket.h" +#include "WorldSession.h" +#include "World.h" +#include "ObjectMgr.h" +#include "ObjectGuid.h" +#include "SpellMgr.h" +#include "QuestDef.h" +#include "Player.h" +#include "Creature.h" +#include "Spell.h" +#include "Group.h" +#include "SpellAuras.h" +#include "MapManager.h" +#include "ObjectAccessor.h" +#include "CreatureAI.h" +#include "TemporarySummon.h" +#include "Formulas.h" +#include "Pet.h" +#include "Util.h" +#include "Totem.h" +#include "BattleGround.h" +#include "InstanceData.h" +#include "MapPersistentStateMgr.h" +#include "GridNotifiersImpl.h" +#include "CellImpl.h" +#include "DBCStores.h" +#include "VMapFactory.h" +#include "MovementGenerator.h" +#include "Transport.h" + +#include "ZoneScript.h" +#include "Nostalrius.h" +#include "InstanceData.h" + +#include "PathFinder.h" +#include "MoveSplineInit.h" +#include "MoveSpline.h" +#include "packet_builder.h" +#include "Chat.h" +#include "Anticheat.h" + +#include +#include + +//#define DEBUG_DEBUFF_LIMIT + +float baseMoveSpeed[MAX_MOVE_TYPE] = +{ + 2.5f, // MOVE_WALK + 7.0f, // MOVE_RUN + 4.5f, // MOVE_RUN_BACK + 4.722222f, // MOVE_SWIM + 2.5f, // MOVE_SWIM_BACK + 3.141594f, // MOVE_TURN_RATE +}; + + +//////////////////////////////////////////////////////////// +// Methods of class GlobalCooldownMgr + +bool GlobalCooldownMgr::HasGlobalCooldown(SpellEntry const* spellInfo) const +{ + GlobalCooldownList::const_iterator itr = m_GlobalCooldowns.find(spellInfo->StartRecoveryCategory); + return itr != m_GlobalCooldowns.end() && itr->second.duration && WorldTimer::getMSTimeDiff(itr->second.cast_time, WorldTimer::getMSTime()) < itr->second.duration; +} + +void GlobalCooldownMgr::AddGlobalCooldown(SpellEntry const* spellInfo, uint32 gcd) +{ + m_GlobalCooldowns[spellInfo->StartRecoveryCategory] = GlobalCooldown(gcd, WorldTimer::getMSTime()); +} + +void GlobalCooldownMgr::CancelGlobalCooldown(SpellEntry const* spellInfo) +{ + m_GlobalCooldowns[spellInfo->StartRecoveryCategory].duration = 0; +} + +//////////////////////////////////////////////////////////// +// Methods of class Unit + +Unit::Unit() + : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostileRefManager(this), + movespline(new Movement::MoveSpline()), _debugFlags(0), m_needUpdateVisibility(false), + m_AutoRepeatFirstCast(true), m_castingSpell(0), m_regenTimer(0), _lastDamageTaken(0) +{ + m_objectType |= TYPEMASK_UNIT; + m_objectTypeId = TYPEID_UNIT; + m_updateFlag = (UPDATEFLAG_ALL | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION); + + m_attackTimer[BASE_ATTACK] = 0; + m_attackTimer[OFF_ATTACK] = 0; + m_attackTimer[RANGED_ATTACK] = 0; + m_modAttackSpeedPct[BASE_ATTACK] = 1.0f; + m_modAttackSpeedPct[OFF_ATTACK] = 1.0f; + m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f; + + m_modRecalcDamagePct[BASE_ATTACK] = 1.0f; + m_modRecalcDamagePct[OFF_ATTACK] = 1.0f; + m_modRecalcDamagePct[RANGED_ATTACK] = 1.0f; + + m_extraAttacks = 0; + m_extraMute = false; + + m_state = 0; + m_deathState = ALIVE; + + for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) + m_currentSpells[i] = nullptr; + + m_castCounter = 0; + + //m_Aura = NULL; + //m_AurasCheck = 2000; + //m_removeAuraTimer = 4; + m_spellAuraHoldersUpdateIterator = m_spellAuraHolders.end(); + m_AuraFlags = 0; + + m_Visibility = VISIBILITY_ON; + m_AINotifyScheduled = false; + + m_detectInvisibilityMask = 0; + m_invisibilityMask = 0; + m_transform = 0; + m_canModifyStats = false; + + for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i) + m_spellImmune[i].clear(); + for (int i = 0; i < UNIT_MOD_END; ++i) + { + m_auraModifiersGroup[i][BASE_VALUE] = 0.0f; + m_auraModifiersGroup[i][BASE_PCT] = 1.0f; + m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f; + m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f; + } + // implement 50% base damage from offhand + m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f; + + for (uint8 i = 0; i < MAX_ATTACK; ++i) + { + for (uint8 j = 0; j < MAX_ITEM_PROTO_DAMAGES; j++) + { + m_weaponDamage[i][j].damage[MINDAMAGE] = (j == 0) ? BASE_MINDAMAGE : 0; + m_weaponDamage[i][j].damage[MAXDAMAGE] = (j == 0) ? BASE_MAXDAMAGE : 0; + m_weaponDamage[i][j].school = SPELL_SCHOOL_NORMAL; + } + + m_weaponDamageCount[i] = 1; + } + + for (int i = 0; i < MAX_STATS; ++i) + m_createStats[i] = 0.0f; + + m_attacking = nullptr; + m_modMeleeHitChance = 0.0f; + m_modRangedHitChance = 0.0f; + m_modSpellHitChance = 0.0f; + m_baseSpellCritChance = 5; + + m_CombatTimer = 0; + m_lastManaUseTimer = 0; + + //m_victimThreat = 0.0f; + for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) + m_threatModifier[i] = 1.0f; + m_isSorted = true; + for (int i = 0; i < MAX_MOVE_TYPE; ++i) + m_speed_rate[i] = 1.0f; + + m_charmInfo = nullptr; + + // remove aurastates allowing special moves + for (int i = 0; i < MAX_REACTIVE; ++i) + { + m_reactiveTimer[i] = 0; + m_reactiveTarget[i].Clear(); + } + // Phasing + worldMask = WORLD_DEFAULT_UNIT; + + // Nostalrius : Ivina + m_lastCastedSpellID = 0; + m_lastAttackType = MAX_ATTACK; + _casterChaseDistance = 0.0f; + + m_doExtraAttacks = false; +} + +Unit::~Unit() +{ + // set current spells as deletable + for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) + { + if (m_currentSpells[i]) + { + m_currentSpells[i]->SetReferencedFromCurrent(false); + m_currentSpells[i] = nullptr; + } + } + + delete m_charmInfo; + delete movespline; + + // those should be already removed at "RemoveFromWorld()" call + MANGOS_ASSERT(m_gameObj.size() == 0); + MANGOS_ASSERT(m_dynObjGUIDs.size() == 0); + MANGOS_ASSERT(m_deletedAuras.size() == 0); + MANGOS_ASSERT(m_deletedHolders.size() == 0); + MANGOS_ASSERT(!m_needUpdateVisibility); +} + +void Unit::Update(uint32 update_diff, uint32 p_time) +{ + if (!IsInWorld()) + return; + + // Nostalrius : systeme de contresort des mobs. + // Boucle 1 pour regler les timers + for (ProhibitSpellList::iterator it = m_prohibitSpell.begin(); it != m_prohibitSpell.end(); ++it) + { + if (it->RestingMsTime < update_diff) + it->RestingMsTime = 0; + else + it->RestingMsTime -= update_diff; + } + // Boucle 2 : supprimer les sorts avec Timer=0 + for (ProhibitSpellList::iterator it = m_prohibitSpell.begin(); it != m_prohibitSpell.end();) + { + if (it->RestingMsTime == 0) + { + m_prohibitSpell.erase(it); + it = m_prohibitSpell.begin(); + continue; + } + ++it; + } + + // WARNING! Order of execution here is important, do not change. + // Spells must be processed with event system BEFORE they go to _UpdateSpells. + // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad. + m_Events.Update(update_diff); + _UpdateSpells(update_diff); + + CleanupDeletedAuras(); + + if (m_lastManaUseTimer) + { + if (update_diff >= m_lastManaUseTimer) + m_lastManaUseTimer = 0; + else + m_lastManaUseTimer -= update_diff; + } + + // update combat timer only for players and pets + if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->IsPet() || ((Creature*)this)->isCharmed())) + { + // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away + // targets without stopping half way there and running off. + // These flags are reset after target dies or another command is given. + if (GetCharmerGuid().IsPlayer() || GetOwnerGuid().IsPlayer() || GetTypeId() == TYPEID_PLAYER) + { + // Pet in combat ? + Pet* myPet = GetPet(); + if (!myPet || myPet->getHostileRefManager().isEmpty()) + { + if (m_HostileRefManager.isEmpty()) + { + // m_CombatTimer set at aura start and it will be freeze until aura removing + if (m_CombatTimer <= update_diff) + { + // Rage berzerker laisse en combat. + if (!HasAuraType(SPELL_AURA_INTERRUPT_REGEN)) + ClearInCombat(); + } + else + m_CombatTimer -= update_diff; + } + } + } + } + + // extra attack + Unit* victim = getVictim(); + if (isInCombat() && m_doExtraAttacks && GetExtraAttacks() && victim && CanReachWithMeleeAttack(victim)) + { + m_doExtraAttacks = false; + + ExtraAttacksLocked(true); + + while (m_extraAttacks) + { + AttackerStateUpdate(victim, BASE_ATTACK, true); + if (m_extraAttacks > 0) + --m_extraAttacks; + } + resetAttackTimer(BASE_ATTACK); + + ExtraAttacksLocked(false); + } + + if (uint32 base_att = getAttackTimer(BASE_ATTACK)) + setAttackTimer(BASE_ATTACK, (update_diff >= base_att ? 0 : base_att - update_diff)); + + if (uint32 base_att = getAttackTimer(OFF_ATTACK)) + setAttackTimer(OFF_ATTACK, (update_diff >= base_att ? 0 : base_att - update_diff)); + + if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK)) + setAttackTimer(RANGED_ATTACK, (update_diff >= ranged_att ? 0 : ranged_att - update_diff)); + + // update abilities available only for fraction of time + UpdateReactives(update_diff); + + if (isAlive()) + ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth() * 0.20f); + + UpdateSplineMovement(p_time); + GetMotionMaster()->UpdateMotion(p_time); + if (GetMotionMaster()->NeedsAsyncUpdate() && IsInWorld()) + { + if (sWorld.getConfig(CONFIG_UINT32_CONTINENTS_MOTIONUPDATE_THREADS) && GetMap()->IsContinent()) + GetMap()->AddUnitToMovementUpdate(this); + else + GetMotionMaster()->UpdateMotionAsync(p_time); + } + WorldObject::Update(update_diff, p_time); + if (_delayedActions & OBJECT_DELAYED_ADD_TO_RELOCATED_LIST) + { + if (IsInWorld() && !m_needUpdateVisibility) + { + m_needUpdateVisibility = true; + GetMap()->AddRelocatedUnit(this); + } + _delayedActions &= ~OBJECT_DELAYED_ADD_TO_RELOCATED_LIST; + } + + _lastDamageTaken += p_time; + if (_lastDamageTaken > 60000) + _damageTakenHistory.clear(); +} + +bool Unit::UpdateMeleeAttackingState() +{ + Unit* victim = getVictim(); + if (!victim || IsNonMeleeSpellCasted(false)) + return false; + + if (!isAttackReady(BASE_ATTACK) && !(isAttackReady(OFF_ATTACK) && haveOffhandWeapon())) + return false; + + uint8 swingError = 0; + if (!CanReachWithMeleeAttack(victim)) + { + setAttackTimer(BASE_ATTACK, 100); + setAttackTimer(OFF_ATTACK, 100); + swingError = 1; + } + // 120 degrees of radiant range + else if (!HasInArc(2 * M_PI_F / 3, victim)) + { + setAttackTimer(BASE_ATTACK, 100); + setAttackTimer(OFF_ATTACK, 100); + swingError = 2; + } + else + { + if (isAttackReady(BASE_ATTACK)) + { + // prevent base and off attack in same time, delay attack at 0.2 sec + if (haveOffhandWeapon()) + { + if (getAttackTimer(OFF_ATTACK) < ATTACK_DISPLAY_DELAY) + setAttackTimer(OFF_ATTACK, ATTACK_DISPLAY_DELAY); + } + AttackerStateUpdate(victim, BASE_ATTACK); + resetAttackTimer(BASE_ATTACK); + } + if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK)) + { + // prevent base and off attack in same time, delay attack at 0.2 sec + uint32 base_att = getAttackTimer(BASE_ATTACK); + if (base_att < ATTACK_DISPLAY_DELAY) + setAttackTimer(BASE_ATTACK, ATTACK_DISPLAY_DELAY); + // do attack + AttackerStateUpdate(victim, OFF_ATTACK); + resetAttackTimer(OFF_ATTACK); + } + } + + Player* player = (GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL); + if (player && swingError != player->LastSwingErrorMsg()) + { + if (swingError == 1) + player->SendAttackSwingNotInRange(); + else if (swingError == 2) + player->SendAttackSwingBadFacingAttack(); + player->SwingErrorMsg(swingError); + } + + return swingError == 0; +} + +bool Unit::haveOffhandWeapon() const +{ + if (!CanUseEquippedWeapon(OFF_ATTACK)) + return false; + + if (GetTypeId() == TYPEID_PLAYER) + return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK, true, true); + else + { + uint8 itemClass = GetByteValue(UNIT_VIRTUAL_ITEM_INFO + (1 * 2) + 0, VIRTUAL_ITEM_INFO_0_OFFSET_CLASS); + if (itemClass == ITEM_CLASS_WEAPON) + return true; + + return false; + } +} + +void Unit::SendHeartBeat(bool includingSelf) +{ + //m_movementInfo.ChangePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); + m_movementInfo.UpdateTime(WorldTimer::getMSTime()); + WorldPacket data(MSG_MOVE_HEARTBEAT, 31); + data << GetPackGUID(); + data << m_movementInfo; + SendMovementMessageToSet(std::move(data), includingSelf); +} + +void Unit::resetAttackTimer(WeaponAttackType type) +{ + m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]); +} + +void Unit::RemoveSpellsCausingAura(AuraType auraType) +{ + for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) + { + RemoveAurasDueToSpell((*iter)->GetId()); + iter = m_modAuras[auraType].begin(); + } +} + +bool Unit::HasAuraTypeByCaster(AuraType auraType, ObjectGuid casterGuid) const +{ + for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); ++iter) + if ((*iter)->GetCasterGuid() == casterGuid) + return true; + return false; +} + +uint64 Unit::GetAuraApplicationMask() const +{ + if (!IsInWorld()) + return 0; + + uint64 mask = 0x0; + for (uint64 i = MAX_POSITIVE_AURAS; i < MAX_AURAS; ++i) + if (GetUInt32Value(UNIT_FIELD_AURA + i)) + mask |= uint64(1) << i; + return mask; +} + +uint32 Unit::GetFirstAuraBySpellIconAndVisual(uint32 spellIconId, uint32 spellVisual) const +{ + for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) + { + if ((*i).second->GetSpellProto()->SpellIconID == spellIconId && (*i).second->GetSpellProto()->SpellVisual == spellVisual) + return (*i).second->GetId(); + } + return 0; +} + +void Unit::RemoveSpellsCausingAura(AuraType auraType, SpellAuraHolder* except) +{ + for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) + { + // skip `except` aura + if ((*iter)->GetHolder() == except) + { + ++iter; + continue; + } + + RemoveAurasDueToSpell((*iter)->GetId(), except); + iter = m_modAuras[auraType].begin(); + } +} + +/* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */ +void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage) +{ + if (!HasAuraType(auraType)) + return; + if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) + return; + + // The chance to dispel an aura depends on the damage taken with respect to the casters level. + uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50; + float chance = float(damage) / max_dmg * 100.0f; + if (roll_chance_f(chance)) + { + for (AuraList::const_iterator iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end();) + { + if ((*iter)->GetSpellProto()->procFlags) + { + RemoveAurasDueToSpell((*iter)->GetId()); + iter = m_modAuras[auraType].begin(); + } + else + ++iter; + } + } +} + +// Nostalrius +void Unit::RemoveFearEffectsByDamageTaken(uint32 damage, uint32 exceptSpellId, DamageEffectType damagetype) +{ + if (!HasAuraType(SPELL_AURA_MOD_FEAR)) + return; + if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) + return; + + // Formula derived from Youfie's post here: + // https://forum.nostalrius.org/viewtopic.php?f=5&t=17424#p119432 + + // The chance to dispel an aura depends on the damage taken with respect to the caster's level. + uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50; + + // Players are 3x more likely to break fears + if (GetTypeId() == TYPEID_PLAYER) + max_dmg *= 0.333f; + // DOT spells are 3x less likely to break fears + if (damagetype == DOT) + max_dmg *= 3; + + // for players, this means max_dmg = 450 at level 60, or 1350 if the damage source is a dot + // for mobs, this means max_dmg = 1350 at level 60, or 4050 if the damage source is a dot + + float chance = float(damage) / float(max_dmg) * 100.0f; + + if (!roll_chance_f(chance)) + return; + + for (AuraList::const_iterator iter = m_modAuras[SPELL_AURA_MOD_FEAR].begin(); iter != m_modAuras[SPELL_AURA_MOD_FEAR].end();) + { + // skip `except` aura + if ((*iter)->GetId() == exceptSpellId) + { + ++iter; + continue; + } + bool canRemoveAura = false; + switch ((*iter)->GetSpellProto()->Mechanic) + { + case MECHANIC_FEAR: + case MECHANIC_TURN: // [Turn Undead] #2878 + canRemoveAura = true; + break; + } + if (!canRemoveAura) + { + ++iter; + continue; + } + RemoveAurasDueToSpell((*iter)->GetId()); + iter = m_modAuras[SPELL_AURA_MOD_FEAR].begin(); + } +} + +void Unit::DoKillUnit(Unit* victim) +{ + if (!victim) + victim = this; + if (!victim->isAlive()) + return; + DealDamage(victim, victim->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); +} + +void Unit::DealDamageMods(Unit *victim, uint32 &damage, uint32* absorb) +{ + // [Nostalrius] Pas de degats sous esprit de redemption + if (!victim->isAlive() || victim->IsTaxiFlying() || (victim->GetTypeId() == TYPEID_UNIT && ((Creature*)victim)->IsInEvadeMode()) || + (getClass() == CLASS_PRIEST && HasAura(27827))) + { + if (absorb) + *absorb += damage; + damage = 0; + return; + } + + uint32 originalDamage = damage; + + //Script Event damage Deal + if (GetTypeId() == TYPEID_UNIT && ((Creature *)this)->AI()) + ((Creature *)this)->AI()->DamageDeal(victim, damage); + //Script Event damage taken + if (victim->GetTypeId() == TYPEID_UNIT && ((Creature *)victim)->AI()) + ((Creature *)victim)->AI()->DamageTaken(this, damage); + + if (absorb && originalDamage > damage) + *absorb += (originalDamage - damage); +} + +uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss, Spell* spell) +{ + // remove affects from victim (including from 0 damage and DoTs) + if (pVictim != this) + pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); + + // remove affects from attacker at any non-DoT damage (including 0 damage) + if (damagetype != DOT) + { + RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); + RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); + + if (pVictim != this) + RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY); + + if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) + pVictim->SetStandState(UNIT_STAND_STATE_STAND); + } + + if (!damage) + { + if (cleanDamage) + { + //sLog.outString("[ABSORB] Deal Damage sur %s (Dam%u|Absorb%u|Resist%u)", pVictim->GetName(), cleanDamage->damage, cleanDamage->absorb, cleanDamage->resist); + + // Rage on outgoing parry/dodge + if (cleanDamage->hitOutCome == MELEE_HIT_PARRY || cleanDamage->hitOutCome == MELEE_HIT_DODGE) + { + if (cleanDamage->damage && damagetype == DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE)) + ((Player*)this)->RewardRage(cleanDamage->damage*0.75, true); + } + + // Degats recus sous bouclier par exemple. + if (cleanDamage->absorb) + { + if (!spellProto || !spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR)) + { + if (!(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsWorldBoss())) + pVictim->RemoveFearEffectsByDamageTaken(cleanDamage->absorb, spellProto ? spellProto->Id : 0, damagetype); + } + + if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT))) + pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, cleanDamage->absorb); + + pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DAMAGE, spellProto ? spellProto->Id : 0); + + // interrupt spells like trying to mount even through absorb shields + if (pVictim->GetTypeId() == TYPEID_PLAYER && damagetype != DOT) + pVictim->InterruptSpellsWithInterruptFlags(SPELL_INTERRUPT_FLAG_ABORT_ON_DMG, spellProto ? spellProto->Id : 0); + } + if (damagetype != DOT) + { + SetInCombatWith(pVictim); + pVictim->SetInCombatWith(this); + } + + //PMonsterSay("-> Absorb %5u | Resist %5u. AttackType %u", cleanDamage->absorb, cleanDamage->resist, cleanDamage->hitOutCome); + if (Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself()) + SetContestedPvP(attackedPlayer); + } + return 0; + } + //else if (cleanDamage) + // sLog.outString("[NORMAL] Deal Damage sur %s (Dam%u|Absorb%u|Resist%u)", pVictim->GetName(), cleanDamage->damage, cleanDamage->absorb, cleanDamage->resist); + + if (!spellProto || !spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR)) + { + if (!(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsWorldBoss())) + pVictim->RemoveFearEffectsByDamageTaken(damage, spellProto ? spellProto->Id : 0, damagetype); + } + + // root type spells do not dispel the root effect + if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || spellProto->IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT))) + pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage); + + // no xp,health if type 8 /critters/ + uint32 victimEntry = pVictim->GetEntry(); + if (pVictim->GetTypeId() == TYPEID_UNIT && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER && victimEntry != 10441 && victimEntry != 10461 && victimEntry != 10536) + { + // TODO: fix this part + // Critter may not die of damage taken, instead expect it to run away (no fighting back) + // If (this) is TYPEID_PLAYER, (this) will enter combat w/victim, but after some time, automatically leave combat. + // It is unclear how it should work for other cases. + + Creature* creature = pVictim->ToCreature(); + creature->SetLootRecipient(this); + + pVictim->SetDeathState(JUST_DIED); + pVictim->SetHealth(0); + + if (!creature->IsPet()) + { + creature->DeleteThreatList(); + if (CreatureInfo const *cinfo = creature->GetCreatureInfo()) + if (cinfo->lootid || cinfo->maxgold > 0) + creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); + } + // some critters required for quests + if (GetTypeId() == TYPEID_PLAYER) + if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry())) + ((Player*)this)->KilledMonster(normalInfo, pVictim->GetObjectGuid()); + // Nostalrius : ajout de 'JustDied' pour les CRITTER. + if (CreatureAI* pAi = pVictim->AI()) + pAi->JustDied(this); + + if (InstanceData* mapInstance = pVictim->GetInstanceData()) + mapInstance->OnCreatureDeath(((Creature*)pVictim)); + + DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamage critter, critter dies"); + + // Rage from Damage made vs critters (only from direct weapon damage) + if (damage && damagetype == DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE)) + ((Player*)this)->RewardRage(damage, true); + + return damage; + } + + uint32 health = pVictim->GetHealth(); + // duel ends when player has 1 or less hp + bool duel_hasEnded = false; + if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health - 1)) + { + // prevent kill only if killed in duel and killed by opponent or opponent controlled creature + if (((Player*)pVictim)->duel->opponent == this || ((Player*)pVictim)->duel->opponent->GetObjectGuid() == GetOwnerGuid()) + damage = health - 1; + + duel_hasEnded = true; + } + //Get in CombatState + if ((pVictim != this) && (damagetype != DOT) && + (!spellProto || !spellProto->IsAuraAddedBySpell(SPELL_AURA_DAMAGE_SHIELD))) + { + SetInCombatWith(pVictim); + pVictim->SetInCombatWith(this); + if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_UNIT) + pVictim->ToCreature()->ResetLastDamageTakenTime(); + + if (Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself()) + SetContestedPvP(attackedPlayer); + } + if (pVictim->GetTypeId() == TYPEID_UNIT) + pVictim->ToCreature()->CountDamageTaken(damage, GetCharmerOrOwnerOrOwnGuid().IsPlayer() || pVictim == this); + else if (pVictim != this) + { + if (Player* attackerPlayer = GetAffectingPlayer()) + pVictim->UnitDamaged(attackerPlayer->GetObjectGuid(), damage); + else + pVictim->UnitDamaged(ObjectGuid(), damage); + } + + // Rage from Damage made (only from direct weapon damage) + if (damage && damagetype == DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE)) + ((Player*)this)->RewardRage(damage, true); + + if (Creature* creaVictim = pVictim->ToCreature()) + if (!creaVictim->IsPet() && !creaVictim->HasLootRecipient()) + creaVictim->SetLootRecipient(this); + if (health <= damage) + { + // Can't kill gods + if (Player* pPlayer = pVictim->ToPlayer()) + if (pPlayer->IsGod()) + return 0; + + DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamage: victim just died"); + Kill(pVictim, spellProto, durabilityLoss); // Function too long, we cut + // last damage from non duel opponent or opponent controlled creature + if (duel_hasEnded) + { + MANGOS_ASSERT(pVictim->GetTypeId() == TYPEID_PLAYER); + Player *he = (Player*)pVictim; + + MANGOS_ASSERT(he->duel); + + he->duel->opponent->CombatStopWithPets(true); + he->CombatStopWithPets(true); + + he->DuelComplete(DUEL_INTERUPTED); + } + } + else // if (health <= damage) + { + pVictim->ModifyHealth(- (int32)damage); + + if (damagetype != DOT) + { + if (!getVictim()) + { + // if not have main target then attack state with target (including AI call) + //start melee attacks only after melee hit + Attack(pVictim, (damagetype == DIRECT_DAMAGE)); + } + + // if damage pVictim call AI reaction + if (!spell) // AttackedBy already handled at spell cast + pVictim->AttackedBy(this); + } + + // polymorphed, hex and other negative transformed cases + uint32 morphSpell = pVictim->getTransForm(); + if (morphSpell && !IsPositiveSpell(morphSpell)) + { + if (SpellEntry const* morphEntry = sSpellMgr.GetSpellEntry(morphSpell)) + { + if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_CONFUSE)) + pVictim->RemoveAurasDueToSpell(morphSpell); + else if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_PACIFY_SILENCE)) + pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_PACIFY_SILENCE, damage); + } + } + + if (damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE) + { + if (!spellProto || !(spellProto->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DIRECT_DAMAGE)) + pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE); + } + if (pVictim->GetTypeId() != TYPEID_PLAYER) + { + float threat = damage * sSpellMgr.GetSpellThreatMultiplier(spellProto); + pVictim->AddThreat(this, threat, (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto); + } + else // victim is a player + { + // Rage from damage received + if (this != pVictim && pVictim->getPowerType() == POWER_RAGE) + { + ((Player*)pVictim)->RewardRage(damage, false); + } + + // random durability for items (HIT TAKEN) + if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE))) + { + EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END - 1)); + ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot); + } + } + + if (GetTypeId() == TYPEID_PLAYER) + { + // random durability for items (HIT DONE) + if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE))) + { + EquipmentSlots slot = EquipmentSlots(urand(0, EQUIPMENT_SLOT_END - 1)); + ((Player*)this)->DurabilityPointLossForEquipSlot(slot); + } + } + + pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DAMAGE, spellProto ? spellProto->Id : 0); + + if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER) + { + if (damagetype != DOT) + { + for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) + { + // skip channeled spell (processed differently below) + if (i == CURRENT_CHANNELED_SPELL) + continue; + + if (Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i))) + { + if (spell->getState() == SPELL_STATE_PREPARING) + { + if (spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG) + pVictim->InterruptSpell(CurrentSpellTypes(i)); + else + spell->Delayed(); + } + } + } + + if (Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL]) + { + if (spell->getState() == SPELL_STATE_CASTING) + { + uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags; + if (channelInterruptFlags & CHANNEL_FLAG_DELAY) + { + if (pVictim != this) //don't shorten the duration of channeling if you damage yourself + spell->DelayedChannel(); + } + else if ((channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2))) + { + DETAIL_LOG("Spell %u canceled at damage!", spell->m_spellInfo->Id); + pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL); + } + } + else if (spell->getState() == SPELL_STATE_DELAYED) + // break channeled spell in delayed state on damage + { + DETAIL_LOG("Spell %u canceled at damage!", spell->m_spellInfo->Id); + pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL); + } + } + } + } + + // last damage from duel opponent + if (duel_hasEnded) + { + MANGOS_ASSERT(pVictim->GetTypeId() == TYPEID_PLAYER); + Player *he = (Player*)pVictim; + + MANGOS_ASSERT(he->duel); + + he->SetHealth(1); + + he->duel->opponent->CombatStopWithPets(true); + he->CombatStopWithPets(true); + + he->CastSpell(he, 7267, true); // beg + he->DuelComplete(DUEL_WON); + } + } + + return damage; +} + +void Unit::Kill(Unit* pVictim, SpellEntry const *spellProto, bool durabilityLoss) +{ + // find player: owner of controlled `this` or `this` itself maybe + // for loot will be sued only if group_tap==NULL + Player *player_tap = GetCharmerOrOwnerPlayerOrPlayerItself(); + Creature* creature = pVictim->ToCreature(); + Group *group_tap = nullptr; + + // find owner of pVictim, used for creature cases, AI calls + Unit* pOwner = pVictim->GetCharmerOrOwner(); + + // in creature kill case group/player tap stored for creature + if (creature) + { + if (creature->IsLootAllowedDueToDamageOrigin()) + { + group_tap = creature->GetGroupLootRecipient(); + + if (Player* recipient = creature->GetOriginalLootRecipient()) + player_tap = recipient; + // Set correct group_tap if player entered a group + if (player_tap && !group_tap) + group_tap = player_tap->GetGroup(); + } + else if (creature->lootForCreator && creature->GetCreatorGuid()) + { + Unit* creator = GetUnit(*this, creature->GetCreatorGuid()); + if (creator->IsPlayer()) + player_tap = (Player*)creator; + } + else + creature->SetLootRecipient(nullptr); + } + // in player kill case group tap selected by player_tap (killer-player itself, or charmer, or owner, etc) + else + { + if (player_tap) + group_tap = player_tap->GetGroup(); + } + + // Nostalrius: Loots desactives / map (retire ici l'XP et les reputs) + bool allowLoot = !sObjectMgr.IsMapLootDisabled(GetMapId()); + // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop) + if (allowLoot && player_tap && player_tap != pVictim) + { + WorldPacket data(SMSG_PARTYKILLLOG, (8 + 8)); //send event PARTY_KILL + data << player_tap->GetObjectGuid(); //player with killing blow + data << pVictim->GetObjectGuid(); //victim + + Player* looter = player_tap; + if (group_tap) + { + group_tap->BroadcastPacket(&data, false, group_tap->GetMemberGroup(player_tap->GetObjectGuid()), player_tap->GetObjectGuid()); + + if (creature) + { + group_tap->UpdateLooterGuid(creature, true); + if (group_tap->GetLooterGuid()) + { + looter = ObjectAccessor::FindPlayer(group_tap->GetLooterGuid()); + if (looter) + { + creature->SetLootRecipient(looter); // update creature loot recipient to the allowed looter. + group_tap->SendLooter(creature, looter); + } + else + group_tap->SendLooter(creature, nullptr); + } + else + group_tap->SendLooter(creature, nullptr); + + group_tap->UpdateLooterGuid(creature); + } + } + + player_tap->SendDirectMessage(&data); + + if (creature) + { + Loot* loot = &creature->loot; + if (creature->lootForPickPocketed) + creature->lootForPickPocketed = false; + + loot->clear(); + if (creature->AI() || !creature->AI()->FillLoot(loot, looter)) + if (uint32 lootid = creature->GetCreatureInfo()->lootid) + { + loot->SetTeam(group_tap ? group_tap->GetTeam() : looter->GetTeam()); + loot->FillLoot(lootid, LootTemplates_Creature, looter, false, false, creature); + } + + loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold, creature->GetCreatureInfo()->maxgold); + } + + if (group_tap) + group_tap->RewardGroupAtKill(pVictim, player_tap); + else if (player_tap) + player_tap->RewardSinglePlayerAtKill(pVictim); + } + if (Player* playerVictim = pVictim->ToPlayer()) + playerVictim->RewardHonorOnDeath(); + + // To be replaced if possible using ProcDamageAndSpell + if (pVictim != this) // The one who has the fatal blow + ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0); + + DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageAttackStop"); + + // before the stop of combat, the auras of type CM are withdrawn. We must be able to redirect the mobs to the caster. + // You should specify 'AURA_REMOVE_BY_DEATH', but this is not useful for these auras. + pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM); + pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS); + + // stop combat + pVictim->CombatStop(); + pVictim->getHostileRefManager().deleteReferences(); + + bool damageFromSpiritOfRedemtionTalent = (spellProto && spellProto->Id == 27795); + + // if talent known but not triggered (check priest class for speedup check) + bool spiritOfRedemtionTalentImmune = false; + if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST) + { + if (!damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION + pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->getClass() == CLASS_PRIEST) + { + AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY); + for (AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr) + { + if ((*itr)->GetSpellProto()->SpellIconID == 1654) + { + spiritOfRedemtionTalentImmune = true; + break; + } + } + } + + // Already applied spirit of redemption. Fix stuck in ANGEL form. + if (!spiritOfRedemtionTalentImmune && HasAura(27827)) + return; + } + + if (!spiritOfRedemtionTalentImmune) + { + pVictim->SetHealth(0); + DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "SET JUST_DIED"); + pVictim->SetDeathState(JUST_DIED); + // Nostalrius: Instantly send values update for health + if (pVictim->ToPlayer() && pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL)) + pVictim->DirectSendPublicValueUpdate(PLAYER_SELF_RES_SPELL); + pVictim->DirectSendPublicValueUpdate(UNIT_FIELD_HEALTH); + } + + // outdoor pvp things, do these after setting the death state, else the player activity notify won't work... doh... + // handle player kill only if not suicide (spirit of redemption for example) + if (GetTypeId() == TYPEID_PLAYER && this != pVictim) + if (ZoneScript * pZoneScript = ((Player*)this)->GetZoneScript()) + pZoneScript->HandleKill((Player*)this, pVictim); + + DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageHealth1"); + + if (spiritOfRedemtionTalentImmune) + { + // save value before aura remove + uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL); + if (!ressSpellId) + ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId(); + + //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers) + pVictim->RemoveAllAurasOnDeath(); + + // restore for use at real death + pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId); + + // FORM_SPIRITOFREDEMPTION and related auras + pVictim->AddAura(27827, ADD_AURA_NO_OPTION, pVictim); + pVictim->InterruptNonMeleeSpells(false); + } + else + pVictim->SetHealth(0); + + // remember victim PvP death for corpse type and corpse reclaim delay + // at original death (not at SpiritOfRedemtionTalent timeout) + if (pVictim->GetTypeId() == TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent) + ((Player*)pVictim)->SetPvPDeath(player_tap != nullptr); + + // Call KilledUnit for creatures + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI()) + ((Creature*)this)->AI()->KilledUnit(pVictim); + + // Call AI OwnerKilledUnit (for any current summoned minipet/guardian/protector) + PetOwnerKilledUnit(pVictim); + + // 10% durability loss on death + // clean InHateListOf + if (pVictim->GetTypeId() == TYPEID_PLAYER) + { + // only if not player and not controlled by player pet. And not at BG + if (durabilityLoss && !player_tap && !((Player*)pVictim)->InBattleGround()) + { + DEBUG_LOG("We are dead, loosing 10 percents durability"); + ((Player*)pVictim)->DurabilityLossAll(0.10f, false); + // durability lost message + WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0); + ((Player*)pVictim)->GetSession()->SendPacket(&data); + } + } + else // creature died + { + DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE, "DealDamageNotPlayer"); + + if (!creature->IsPet()) + { + creature->LogDeath(this); + creature->UpdateCombatState(false); + + creature->DeleteThreatList(); + if (CreatureInfo const *cinfo = creature->GetCreatureInfo()) + if (cinfo->lootid || cinfo->maxgold > 0) + creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); + } + + // Call creature just died function + if (creature->AI()) + creature->AI()->JustDied(this); + + if (creature->IsTemporarySummon()) + { + TemporarySummon* pSummon = (TemporarySummon*)creature; + if (pSummon->GetSummonerGuid().IsCreature()) + if (Creature* pSummoner = creature->GetMap()->GetCreature(pSummon->GetSummonerGuid())) + if (pSummoner->AI()) + pSummoner->AI()->SummonedCreatureJustDied(creature); + } + else if (pOwner && pOwner->GetTypeId() == TYPEID_UNIT) + { + if (((Creature*)pOwner)->AI()) + ((Creature*)pOwner)->AI()->SummonedCreatureJustDied(creature); + } + + if (ZoneScript* pScript = creature->GetZoneScript()) + pScript->OnCreatureDeath(creature); + + // Dungeon specific stuff, only applies to players killing creatures + if (creature->GetInstanceId() && creature->GetMapId() > 1) + if (Player* playerKiller = GetCharmerOrOwnerPlayerOrPlayerItself()) + creature->GetMap()->BindToInstanceOrRaid(playerKiller, creature->GetRespawnTimeEx(), creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND); + } + + // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill) + if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround()) + { + Player *killed = ((Player*)pVictim); + if (BattleGround *bg = killed->GetBattleGround()) + bg->HandleKillPlayer(killed, player_tap); + } + else if (pVictim->GetTypeId() == TYPEID_UNIT) + { + if (player_tap) + if (BattleGround *bg = player_tap->GetBattleGround()) + bg->HandleKillUnit((Creature*)pVictim, player_tap); + } + // Nostalrius: interrupt non melee spell casted + pVictim->InterruptSpellsCastedOnMe(false, true); + if (player_tap) + ALL_SESSION_SCRIPTS(player_tap->GetSession(), OnUnitKilled(pVictim->GetObjectGuid())); +} + +struct PetOwnerKilledUnitHelper +{ + explicit PetOwnerKilledUnitHelper(Unit* pVictim) : m_victim(pVictim) {} + void operator()(Unit* pTarget) const + { + if (pTarget->GetTypeId() == TYPEID_UNIT) + { + if (((Creature*)pTarget)->AI()) + ((Creature*)pTarget)->AI()->OwnerKilledUnit(m_victim); + } + } + + Unit* m_victim; +}; + +void Unit::PetOwnerKilledUnit(Unit* pVictim) +{ + // for minipet and guardians (including protector) + CallForAllControlledUnits(PetOwnerKilledUnitHelper(pVictim), CONTROLLED_MINIPET | CONTROLLED_GUARDIANS); +} + +void Unit::CastStop(uint32 except_spellid) +{ + for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) + if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) + if (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) + InterruptSpell(CurrentSpellTypes(i), false); +} + +void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) +{ + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); + + if (!spellInfo) + { + if (triggeredByAura) + sLog.outError("CastSpell: unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + else + sLog.outError("CastSpell: unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); + return; + } + + CastSpell(Victim, spellInfo, triggered, castItem, triggeredByAura, originalCaster, triggeredBy); +} + +void Unit::CastSpell(Unit* Victim, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) +{ + if (!spellInfo) + { + if (triggeredByAura) + sLog.outError("CastSpell: unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + else + sLog.outError("CastSpell: unknown spell by caster: %s", GetGuidStr().c_str()); + return; + } + + if (castItem) + DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id); + + if (triggeredByAura) + { + if (!originalCaster) + originalCaster = triggeredByAura->GetCasterGuid(); + + triggeredBy = triggeredByAura->GetSpellProto(); + } + + Spell *spell = new Spell(this, spellInfo, triggered, originalCaster, triggeredBy); + + SpellCastTargets targets; + targets.setUnitTarget(Victim); + + if (spellInfo->Targets & TARGET_FLAG_DEST_LOCATION) + targets.setDestination(Victim->GetPositionX(), Victim->GetPositionY(), Victim->GetPositionZ()); + if (spellInfo->Targets & TARGET_FLAG_SOURCE_LOCATION) + if (WorldObject* caster = spell->GetCastingObject()) + targets.setSource(caster->GetPositionX(), caster->GetPositionY(), caster->GetPositionZ()); + + spell->SetCastItem(castItem); + spell->prepare(&targets, triggeredByAura); +} + +void Unit::CastCustomSpell(Unit* Victim, uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) +{ + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); + + if (!spellInfo) + { + if (triggeredByAura) + sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + else + sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); + return; + } + + CastCustomSpell(Victim, spellInfo, bp0, bp1, bp2, triggered, castItem, triggeredByAura, originalCaster, triggeredBy); +} + +void Unit::CastCustomSpell(Unit* Victim, SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) +{ + if (!spellInfo) + { + if (triggeredByAura) + sLog.outError("CastCustomSpell: unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + else + sLog.outError("CastCustomSpell: unknown spell by caster: %s", GetGuidStr().c_str()); + return; + } + + if (castItem) + DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id); + + if (triggeredByAura) + { + if (!originalCaster) + originalCaster = triggeredByAura->GetCasterGuid(); + + triggeredBy = triggeredByAura->GetSpellProto(); + } + + Spell *spell = new Spell(this, spellInfo, triggered, originalCaster, triggeredBy); + + if (bp0) + spell->m_currentBasePoints[EFFECT_INDEX_0] = *bp0; + + if (bp1) + spell->m_currentBasePoints[EFFECT_INDEX_1] = *bp1; + + if (bp2) + spell->m_currentBasePoints[EFFECT_INDEX_2] = *bp2; + + SpellCastTargets targets; + targets.setUnitTarget(Victim); + spell->SetCastItem(castItem); + spell->prepare(&targets, triggeredByAura); +} + +// used for scripting +void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) +{ + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); + + if (!spellInfo) + { + if (triggeredByAura) + sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s triggered by aura %u (eff %u)", spellId, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + else + sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s", spellId, GetGuidStr().c_str()); + return; + } + + CastSpell(x, y, z, spellInfo, triggered, castItem, triggeredByAura, originalCaster, triggeredBy); +} + +// used for scripting +void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster, SpellEntry const* triggeredBy) +{ + if (!spellInfo) + { + if (triggeredByAura) + sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s triggered by aura %u (eff %u)", GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); + else + sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s", GetGuidStr().c_str()); + return; + } + + if (castItem) + DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id); + + if (triggeredByAura) + { + if (!originalCaster) + originalCaster = triggeredByAura->GetCasterGuid(); + + triggeredBy = triggeredByAura->GetSpellProto(); + } + + Spell *spell = new Spell(this, spellInfo, triggered, originalCaster, triggeredBy); + + SpellCastTargets targets; + targets.setDestination(x, y, z); + spell->SetCastItem(castItem); + spell->prepare(&targets, triggeredByAura); +} + +// Obsolete func need remove, here only for comotability vs another patches +uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage) +{ + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellID); + SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, SpellSchools(spellInfo->School)); + CalculateSpellDamage(&damageInfo, damage, spellInfo); + damageInfo.target->CalculateAbsorbResistBlock(this, &damageInfo, spellInfo); + DealDamageMods(damageInfo.target, damageInfo.damage, &damageInfo.absorb); + SendSpellNonMeleeDamageLog(&damageInfo); + DealSpellDamage(&damageInfo, true); + return damageInfo.damage; +} + +void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType, Spell* spell) +{ + SpellSchoolMask damageSchoolMask = GetSchoolMask(damageInfo->school); + Unit *pVictim = damageInfo->target; + if (!pVictim) + return; + + if (damage < 0) + return; + + if (!pVictim->isAlive()) + return; + + // Check spell crit chance + bool crit = IsSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType, spell); + + // damage bonus (per damage class) + switch (spellInfo->DmgClass) + { + // Melee and Ranged Spells + case SPELL_DAMAGE_CLASS_RANGED: + case SPELL_DAMAGE_CLASS_MELEE: + { + //Calculate damage bonus + damage = MeleeDamageBonusDone(pVictim, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE, 1, spell); + damage = pVictim->MeleeDamageBonusTaken(this, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE, 1, spell); + + // if crit add critical bonus + if (crit) + { + damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; + damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim, spell); + } + } + break; + // Magical Attacks + case SPELL_DAMAGE_CLASS_NONE: + case SPELL_DAMAGE_CLASS_MAGIC: + { + // Calculate damage bonus + damage = SpellDamageBonusDone(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE, 1, spell); + damage = pVictim->SpellDamageBonusTaken(this, spellInfo, damage, SPELL_DIRECT_DAMAGE, 1, spell); + + // If crit add critical bonus + if (crit) + { + damageInfo->HitInfo |= SPELL_HIT_TYPE_CRIT; + damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim, spell); + } + } + break; + } + + // damage mitigation + if (damage > 0) + { + // physical damage => armor + if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL && !(spellInfo->Custom & SPELL_CUSTOM_IGNORE_ARMOR)) + damage = CalcArmorReducedDamage(pVictim, damage); + } + else + damage = 0; + damageInfo->damage = damage; +} + +void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss) +{ + if (!damageInfo) + return; + + Unit *pVictim = damageInfo->target; + + if (!pVictim) + return; + + if (!pVictim->isAlive() || pVictim->IsTaxiFlying() || (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())) + return; + + SpellEntry const *spellProto = sSpellMgr.GetSpellEntry(damageInfo->SpellID); + if (spellProto == nullptr) + { + sLog.outError("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID); + return; + } + + // Call default DealDamage (send critical in hit info for threat calculation) + CleanDamage cleanDamage(0, BASE_ATTACK, damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT ? MELEE_HIT_CRIT : MELEE_HIT_NORMAL, damageInfo->absorb, damageInfo->resist); + DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, GetSchoolMask(damageInfo->school), spellProto, durabilityLoss, damageInfo->spell); +} + +//TODO for melee need create structure as in +void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType) +{ + if (!pVictim) + return; + if (!isAlive() || !pVictim->isAlive()) + return; + + damageInfo->attacker = this; + damageInfo->target = pVictim; + damageInfo->attackType = attackType; + damageInfo->totalDamage = 0; + damageInfo->cleanDamage = 0; + damageInfo->totalAbsorb = 0; + damageInfo->totalResist = 0; + damageInfo->blocked_amount = 0; + + damageInfo->TargetState = VICTIMSTATE_UNAFFECTED; + damageInfo->HitInfo = HITINFO_NORMALSWING; + damageInfo->procAttacker = PROC_FLAG_NONE; + damageInfo->procVictim = PROC_FLAG_NONE; + damageInfo->procEx = PROC_EX_NONE; + damageInfo->hitOutCome = MELEE_HIT_EVADE; + + // Select HitInfo/procAttacker/procVictim flag based on attack type + switch (attackType) + { + case BASE_ATTACK: + damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT; + damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT; + damageInfo->HitInfo = HITINFO_NORMALSWING2; + SetLastAttackType(0); // Nostalrius : Ivina (lastAttackType) + break; + case OFF_ATTACK: + damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT; + damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used + damageInfo->HitInfo = HITINFO_LEFTSWING; + SetLastAttackType(1); + break; + case RANGED_ATTACK: + damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT; + damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT; + damageInfo->HitInfo = HITINFO_UNK3; // test (dev note: test what? HitInfo flag possibly not confirmed.) + SetLastAttackType(2); + break; + default: + break; + } + + bool immune = true; + bool feral = IsInFeralForm(); + + // Only get one damage type for feral druids so they don't receive incorrect benefits + // from weapons with multiple types of damage + uint8 actualDamageCount = feral ? 1 : m_weaponDamageCount[damageInfo->attackType]; + for (uint8 i = 0; i < actualDamageCount; i++) + { + SubDamageInfo *subDamage = &damageInfo->subDamage[i]; + + // feral only allowed melee school + subDamage->damageSchoolMask = GetTypeId() == TYPEID_PLAYER && !feral + ? GetSchoolMask(GetWeaponDamageSchool(damageInfo->attackType, i)) + : GetMeleeDamageSchoolMask(); + + if (damageInfo->target->IsImmuneToDamage(subDamage->damageSchoolMask)) + { + subDamage->damage = 0; + continue; + } + else + immune = false; + + subDamage->damage = CalculateDamage(damageInfo->attackType, false, i); + // Add melee damage bonus + subDamage->damage = MeleeDamageBonusDone(damageInfo->target, subDamage->damage, damageInfo->attackType, nullptr, DIRECT_DAMAGE, 1, nullptr, i == 0); + subDamage->damage = damageInfo->target->MeleeDamageBonusTaken(this, subDamage->damage, damageInfo->attackType, nullptr, DIRECT_DAMAGE, 1, nullptr, i == 0); + + // Calculate armor reduction + if(subDamage->damageSchoolMask == SPELL_SCHOOL_MASK_NORMAL) + { + damageInfo->cleanDamage += subDamage->damage; + subDamage->damage = CalcArmorReducedDamage(damageInfo->target, subDamage->damage); + damageInfo->cleanDamage -= subDamage->damage; + } + + damageInfo->totalDamage += subDamage->damage; + } + + // Physical Immune check + if (immune) + { + damageInfo->HitInfo |= HITINFO_NORMALSWING; + damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE; + + damageInfo->procEx |= PROC_EX_IMMUNE; + damageInfo->totalDamage = 0; + damageInfo->cleanDamage = 0; + return; + } + + damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType); + + // Disable parry or dodge for ranged attack + if (damageInfo->attackType == RANGED_ATTACK) + { + if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL; + if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS; + } + + switch (damageInfo->hitOutCome) + { + case MELEE_HIT_EVADE: + { + damageInfo->HitInfo |= HITINFO_MISS | HITINFO_SWINGNOHITSOUND; + damageInfo->TargetState = VICTIMSTATE_EVADES; + + damageInfo->procEx |= PROC_EX_EVADE; + damageInfo->totalDamage = 0; + damageInfo->cleanDamage = 0; + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage = 0; + + return; + } + case MELEE_HIT_MISS: + { + damageInfo->HitInfo |= HITINFO_MISS; + damageInfo->TargetState = VICTIMSTATE_UNAFFECTED; + + damageInfo->procEx |= PROC_EX_MISS; + damageInfo->totalDamage = 0; + damageInfo->cleanDamage = 0; + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage = 0; + + break; + } + case MELEE_HIT_NORMAL: + { + damageInfo->TargetState = VICTIMSTATE_NORMAL; + damageInfo->procEx |= PROC_EX_NORMAL_HIT; + break; + } + case MELEE_HIT_CRIT: + { + damageInfo->HitInfo |= HITINFO_CRITICALHIT; + damageInfo->TargetState = VICTIMSTATE_NORMAL; + + damageInfo->procEx |= PROC_EX_CRITICAL_HIT; + + uint32 creatureTypeMask = damageInfo->target->GetCreatureTypeMask(); + + int32 mod = GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask); + + damageInfo->totalDamage = uint32((damageInfo->totalDamage) * float((200.0f + mod) / 100.0f)); + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage = uint32((damageInfo->subDamage[i].damage) * float((200.0f + mod) / 100.0f)); + + break; + } + case MELEE_HIT_PARRY: + { + damageInfo->TargetState = VICTIMSTATE_PARRY; + damageInfo->procEx |= PROC_EX_PARRY; + damageInfo->cleanDamage += damageInfo->totalDamage; + damageInfo->totalDamage = 0; + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage = 0; + + break; + } + case MELEE_HIT_DODGE: + { + damageInfo->TargetState = VICTIMSTATE_DODGE; + damageInfo->procEx |= PROC_EX_DODGE; + damageInfo->cleanDamage += damageInfo->totalDamage; + damageInfo->totalDamage = 0; + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage = 0; + + break; + } + case MELEE_HIT_BLOCK: + { + damageInfo->TargetState = VICTIMSTATE_NORMAL; + damageInfo->procEx |= PROC_EX_BLOCK; + damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue(); + if (damageInfo->blocked_amount >= damageInfo->subDamage[0].damage) + { + damageInfo->TargetState = VICTIMSTATE_BLOCKS; + damageInfo->blocked_amount = damageInfo->subDamage[0].damage; + } + else + damageInfo->procEx |= PROC_EX_NORMAL_HIT; // Partial blocks can still cause attacker procs + + damageInfo->totalDamage -= damageInfo->blocked_amount; + damageInfo->subDamage[0].damage -= damageInfo->blocked_amount; + damageInfo->cleanDamage += damageInfo->blocked_amount; + break; + } + case MELEE_HIT_GLANCING: + { + damageInfo->HitInfo |= HITINFO_GLANCING; + damageInfo->TargetState = VICTIMSTATE_NORMAL; + damageInfo->procEx |= PROC_EX_NORMAL_HIT; + // int32 attackerWeaponSkill = GetWeaponSkillValue(damageInfo->attackType,pVictim); + // int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this); + int SkillDiff = 0; + SkillDiff = pVictim->GetDefenseSkillValue(this) - GetWeaponSkillValue(damageInfo->attackType, pVictim); + float reducePercent = 1.0f; + // (Youfie) Formule de calcul de la réduction de dégâts des érafles, influencée en pré-BC par le +skill au delà de [niveau du joueur * 5] + // Formule d'Athan retenue et supposée comme Blizz-like au regard des multiples sources et tests concordants + // float reducePercent = 1 - (5*(pow(2,(victimDefenseSkill/5) - (attackerWeaponSkill/5) - 1))/100); + // Après tentative d'implémentation "propre" de la formule et de nombreux échecs, mise en place de celle-ci après calcul manuel des différentes valeurs + // cf. http://nostalrius.org/forum/viewtopic.php?p=43964#p43964 pour infos et sources + if (SkillDiff >= 15) + reducePercent = 0.6500f; + if (SkillDiff <= 0) + reducePercent = 1; + switch (SkillDiff) + { + case 14 : + reducePercent = 0.7018f; + break; + case 13 : + reducePercent = 0.7469f; + break; + case 12 : + reducePercent = 0.7860f; + break; + case 11 : + reducePercent = 0.8203f; + break; + case 10 : + reducePercent = 0.8500f; + break; + case 9 : + reducePercent = 0.8759f; + break; + case 8 : + reducePercent = 0.8984f; + break; + case 7 : + reducePercent = 0.9180f; + break; + case 6 : + reducePercent = 0.9351f; + break; + case 5 : + reducePercent = 0.9500f; + break; + case 4 : + reducePercent = 0.9629f; + break; + case 3 : + reducePercent = 0.9742f; + break; + case 2 : + reducePercent = 0.9840f; + break; + case 1 : + reducePercent = 0.9926f; + break; + } + + // sLog.outString("SkillDiff = %i, reducePercent = %f", SkillDiff, reducePercent); // Pour tests & débug via la console + + damageInfo->cleanDamage += uint32((1.0f - reducePercent) * damageInfo->totalDamage); + damageInfo->totalDamage = uint32(reducePercent * damageInfo->totalDamage); + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage = uint32(reducePercent * damageInfo->subDamage[i].damage); + + break; + } + case MELEE_HIT_CRUSHING: + { + damageInfo->HitInfo |= HITINFO_CRUSHING; + damageInfo->TargetState = VICTIMSTATE_NORMAL; + damageInfo->procEx |= PROC_EX_NORMAL_HIT; + + // 150% of normal damage + damageInfo->totalDamage += damageInfo->totalDamage / 2; + + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + damageInfo->subDamage[i].damage += damageInfo->subDamage[i].damage / 2; + + break; + } + default: + break; + } + + // Calculate absorb resist + if (int32(damageInfo->totalDamage) > 0) + { + damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE; + + // Calculate absorb & resists + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + { + SubDamageInfo *subDamage = &damageInfo->subDamage[i]; + + damageInfo->target->CalculateDamageAbsorbAndResist(this, subDamage->damageSchoolMask, DIRECT_DAMAGE, subDamage->damage, &subDamage->absorb, &subDamage->resist, nullptr); + damageInfo->totalDamage -= subDamage->absorb + subDamage->resist; + subDamage->damage -= subDamage->absorb + subDamage->resist; + + damageInfo->totalAbsorb += subDamage->absorb; + damageInfo->totalResist += subDamage->resist; + + if (subDamage->absorb) + { + damageInfo->HitInfo |= HITINFO_ABSORB; + damageInfo->procEx |= PROC_EX_ABSORB; + } + + if (subDamage->resist) + damageInfo->HitInfo |= HITINFO_RESIST; + } + } + else + damageInfo->totalDamage = 0; +} + +void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss) +{ + if (damageInfo == nullptr) return; + Unit *pVictim = damageInfo->target; + + if (!pVictim) + return; + + if (!pVictim->isAlive() || pVictim->IsTaxiFlying() || (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())) + return; + + // Hmmmm dont like this emotes client must by self do all animations + if (damageInfo->HitInfo & HITINFO_CRITICALHIT) + pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL); + if (damageInfo->blocked_amount && damageInfo->TargetState != VICTIMSTATE_BLOCKS) + pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD); + + if (damageInfo->TargetState == VICTIMSTATE_PARRY) + { + // Get attack timers + float offtime = float(pVictim->getAttackTimer(OFF_ATTACK)); + float basetime = float(pVictim->getAttackTimer(BASE_ATTACK)); + // Reduce attack time + if (pVictim->haveOffhandWeapon() && offtime < basetime) + { + float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f; + float percent60 = 3.0f * percent20; + if (offtime > percent20 && offtime <= percent60) + pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20)); + else if (offtime > percent60) + { + offtime -= 2.0f * percent20; + pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime)); + } + } + else + { + float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20f; + float percent60 = 3.0f * percent20; + if (basetime > percent20 && basetime <= percent60) + pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20)); + else if (basetime > percent60) + { + basetime -= 2.0f * percent20; + pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime)); + } + } + } + + // Call default DealDamage + CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->attackType, damageInfo->hitOutCome, damageInfo->totalAbsorb, damageInfo->totalResist); + DealDamage(pVictim, damageInfo->totalDamage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->subDamage[0].damageSchoolMask), nullptr, durabilityLoss); + + // If this is a creature and it attacks from behind it has a probability to daze it's victim + if (damageInfo->totalDamage && GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGuid() && !pVictim->HasInArc(M_PI_F, this)) + { + // -probability is between 0% and 40% + // 20% base chance + uint32 VictimDefense = pVictim->GetDefenseSkillValue(); + uint32 AttackerMeleeSkill = GetUnitMeleeSkill(); + + float Probability = 0.0f; + + //there is a newbie protection, at level 10 just 7% base chance; assuming linear function + if (pVictim->getLevel() < 30) + Probability = 0.65f * pVictim->getLevel() + 0.5f + ((float)AttackerMeleeSkill - (float)VictimDefense) * 0.2f; + else + Probability = 20.0f + ((float)AttackerMeleeSkill - (float)VictimDefense) * 0.2f; + + if (Probability > 40.0f) + Probability = 40.0f; + + if (Player* pPlayer = pVictim->ToPlayer()) + if (pPlayer->IsGod()) + Probability = 0.0f; + + if (roll_chance_f(Probability)) + CastSpell(pVictim, 1604, true); + } + + // update at damage Judgement aura duration that applied by attacker at victim + if (damageInfo->totalDamage) + { + SpellAuraHolderMap const& vAuras = pVictim->GetSpellAuraHolderMap(); + for (SpellAuraHolderMap::const_iterator itr = vAuras.begin(); itr != vAuras.end(); ++itr) + { + SpellEntry const *spellInfo = (*itr).second->GetSpellProto(); + if (spellInfo->AttributesEx3 & 0x40000 && spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && ((*itr).second->GetCasterGuid() == GetObjectGuid())) + (*itr).second->RefreshHolder(); + } + } + + // If not miss + if (!(damageInfo->HitInfo & HITINFO_MISS) && damageInfo->TargetState != VICTIMSTATE_PARRY && damageInfo->TargetState != VICTIMSTATE_DODGE) + { + // on weapon hit casts + if (GetTypeId() == TYPEID_PLAYER && pVictim->isAlive()) + ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType); + + // victim's damage shield + std::set alreadyDone; + AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD); + for (AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();) + { + if (alreadyDone.find(*i) == alreadyDone.end()) + { + alreadyDone.insert(*i); + uint32 damage = (*i)->GetModifier()->m_amount; + SpellEntry const *i_spellProto = (*i)->GetSpellProto(); + + // apply SpellBaseDamageBonusTaken for mobs only + // for example, Death Talon Seethers with Aura of Flames reflect 1200 damage to tanks with Mark of Flame + if (pVictim->GetTypeId() == TYPEID_UNIT) + { + int32 spellDmgTakenBonus = this->SpellBaseDamageBonusTaken(GetSpellSchoolMask(i_spellProto)); + // don't allow damage shields to be reduced by Blessing of Sanctuary, etc. + if (spellDmgTakenBonus > 0) damage += spellDmgTakenBonus; + } + + //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist? + //uint32 absorb; + //uint32 resist; + //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist); + //damage-=absorb + resist; + + pVictim->DealDamageMods(this, damage, nullptr); + + WorldPacket data(SMSG_SPELLDAMAGESHIELD, (8 + 8 + 4 + 4)); + data << pVictim->GetObjectGuid(); + data << GetObjectGuid(); + data << uint32(damage); + data << uint32(i_spellProto->School); + pVictim->SendObjectMessageToSet(&data, true); + + pVictim->DealDamage(this, damage, nullptr, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true); + + i = vDamageShields.begin(); + } + else + ++i; + } + } +} + +void Unit::HandleEmoteCommand(uint32 emote_id) +{ + WorldPacket data(SMSG_EMOTE, 4 + 8); + data << uint32(emote_id); + data << GetObjectGuid(); + SendObjectMessageToSet(&data, true); +} + +void Unit::HandleEmoteState(uint32 emote_id) +{ + SetUInt32Value(UNIT_NPC_EMOTESTATE, emote_id); +} + +void Unit::HandleEmote(uint32 emote_id) +{ + if (!emote_id) + HandleEmoteState(0); + else if (EmotesEntry const* emoteEntry = sEmotesStore.LookupEntry(emote_id)) + { + if (emoteEntry->EmoteType) // 1,2 states, 0 command + HandleEmoteState(emote_id); + else + HandleEmoteCommand(emote_id); + } +} + +uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage) +{ + uint32 newdamage = 0; + float armor = (float)pVictim->GetArmor(); + + // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura + armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL); + + if (armor < 0.0f) + armor = 0.0f; + + float levelModifier = (float)getLevel(); + if (levelModifier > 59) + levelModifier = levelModifier + (4.5f * (levelModifier - 59)); + + float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40); + tmpvalue = tmpvalue / (1.0f + tmpvalue); + + if (tmpvalue < 0.0f) + tmpvalue = 0.0f; + if (tmpvalue > 0.75f) + tmpvalue = 0.75f; + + newdamage = uint32(damage - (damage * tmpvalue)); + + return (newdamage > 1) ? newdamage : 1; +} + +// NOSTALRIUS: Provient d'un tableau du forum (http://www.hostingpics.net/viewer.php?id=995056Resistances.jpg) +struct ResistanceValues +{ + int32 resist100; + int32 resist75; + int32 resist50; + int32 resist25; + int32 resist0; + uint32 chanceResist; +}; + +static ResistanceValues resistValues[] = +{ + {0, 0, 0, 0, 100, 0}, // 0 + {0, 0, 2, 6, 92, 3}, // 10 + {0, 1, 4, 12, 84, 5}, // 20 + {0, 1, 5, 18, 76, 8}, // 30 + {0, 1, 7, 23, 69, 10}, // 40 + {0, 2, 9, 28, 61, 13}, // 50 + {0, 2, 11, 33, 54, 15}, // 60 + {0, 2, 13, 37, 37, 18}, // 70 + {0, 3, 15, 41, 41, 20}, // 80 + {1, 3, 17, 46, 36, 23}, // 90 + {1, 4, 19, 47, 29, 25}, // 100 + {1, 5, 21, 48, 24, 28}, // 110 + {1, 6, 24, 49, 20, 30}, // 120 + {1, 8, 28, 47, 17, 33}, // 130 + {1, 9, 33, 43, 14, 35}, // 140 + {1, 11, 37, 39, 12, 38}, // 150 + {1, 13, 41, 35, 10, 40}, // 160 + {1, 16, 45, 30, 8, 43}, // 170 + {1, 18, 48, 26, 7, 45}, // 180 + {2, 20, 48, 24, 6, 43}, // 190 + {4, 23, 48, 21, 4, 50}, // 200 + {5, 25, 47, 19, 3, 53}, // 210 + {7, 28, 45, 17, 2, 55}, // 220 + {9, 31, 43, 16, 2, 58}, // 230 + {11, 34, 40, 14, 1, 60}, // 240 + {13, 37, 37, 12, 1, 62}, // 250 + {15, 41, 33, 10, 1, 65}, // 260 + {18, 44, 29, 8, 1, 68}, // 270 + {20, 48, 25, 7, 1, 70}, // 280 + {23, 51, 20, 5, 1, 73}, // 290 + {25, 55, 16, 3, 1, 75} // 300 +}; + +void Unit::CalculateDamageAbsorbAndResist(Unit *pCaster, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellEntry const* spellProto, Spell* spell) +{ + if (!pCaster || !isAlive() || !damage) + return; + + if (spell) + schoolMask = spell->m_spellSchoolMask; + + // Nostalrius : immune ? + if (IsImmuneToSchoolMask(schoolMask) && !(spellProto && (spellProto->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY))) + { + (*absorb) = damage; + return; + } + /* + if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || + (pCaster->IsPlayer() && pCaster->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) + return; + */ + + // Magic damage, check for resists + bool canResist = (schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0; + + // NOSTALRIUS: Sorts binaires ne sont pas résistés. + if (canResist && spellProto && spellProto->IsBinary()) + canResist = false; + else if (spellProto && spellProto->AttributesEx4 & SPELL_ATTR_EX4_IGNORE_RESISTANCES) + canResist = false; + + DEBUG_UNIT_IF(spellProto, this, DEBUG_SPELL_COMPUTE_RESISTS, "%s : Binary [%s]. Partial resists %s", spellProto->SpellName[2], spellProto->IsBinary() ? "YES" : "NO", canResist ? "possible" : "impossible"); + + if (canResist) + { + float resistanceChance = pCaster->GetSpellResistChance(this, schoolMask, true); + resistanceChance *= 100.0f; + + // DoTs + // The mechanic for this is strange in classic - most dots can be seen exhibiting partial resists in videos, but only very rarely, + // and almost never more than 25% resists. How this should work exactly is somewhat a guess. + // Kalgan post-2.0 dot nerf: "Previously, dots in general were 1/10th as likely to be resisted as normal spells." + // http://web.archive.org/web/20080601184008/http://forums.worldofwarcraft.com/thread.html?topicId=65457765&pageNo=18&sid=1#348 + if (damagetype == DOT && spellProto) + { + switch (spellProto->Id) + { + // NOSTALRIUS: Some DoTs follow normal resist rules. Need to find which ones, why and how. + // We have a video proof for the following ones. + case 23461: // Vaelastrasz's Flame Breath + case 24818: // Nightmare Dragon's Noxious Breath + case 25812: // Lord Kri's Toxic Volley + break; + default: + resistanceChance *= 0.1f; + } + } + + ResistanceValues* prev = nullptr; + ResistanceValues* next = nullptr; + for (int i = 1; i < 31; ++i) + { + // On depasse la valeur cherchee. + if (resistValues[i].chanceResist >= resistanceChance) + { + prev = &resistValues[i - 1]; + next = &resistValues[i]; + break; + } + } + ASSERT(next && prev); + float coeff = float(resistanceChance - prev->chanceResist) / float(next->chanceResist - prev->chanceResist); + float resist0 = prev->resist0 + (next->resist0 - prev->resist0) * coeff; + float resist25 = prev->resist25 + (next->resist25 - prev->resist25) * coeff; + float resist50 = prev->resist50 + (next->resist50 - prev->resist50) * coeff; + float resist75 = prev->resist75 + (next->resist75 - prev->resist75) * coeff; + float resist100 = prev->resist100 + (next->resist100 - prev->resist100) * coeff; + uint32 ran = urand(0, 99); + float resistCnt = 0.0f; + // Players CANNOT resist 100% of damage, it is always rounded down to 75%, despite what Blizzard's table sugests. + // The true magic damage resist cap is therefore actually ~68-70% because of this mechanic. + // http://web.archive.org/web/20110808083353/http://elitistjerks.com/f15/t10712-resisting_magical_damage_its_relation_resistance_levels/p4/ + if (ran < resist100 + resist75) + resistCnt = 0.75f; + else if (ran < resist100 + resist75 + resist50) + resistCnt = 0.5f; + else if (ran < resist100 + resist75 + resist50 + resist25) + resistCnt = 0.25f; + + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "Partial resist : chances %.2f:%.2f:%.2f:%.2f:%.2f. Hit resist chance %f", + resist0, resist25, resist50, resist75, resist100, resistanceChance); + *resist += uint32(damage * resistCnt); + if (*resist > damage) + *resist = damage; + } + else + *resist = 0; + + int32 RemainingDamage = damage - *resist; + + // Need remove expired auras after + bool existExpired = false; + + // absorb without mana cost + AuraList const& vSchoolAbsorb = GetAurasByType(SPELL_AURA_SCHOOL_ABSORB); + for (AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (!(mod->m_miscvalue & schoolMask)) + continue; + + // Max Amount can be absorbed by this aura + int32 currentAbsorb = mod->m_amount; + + // Found empty aura (impossible but..) + if (currentAbsorb <= 0) + { + existExpired = true; + continue; + } + + // currentAbsorb - damage can be absorbed by shield + // If need absorb less damage + if (RemainingDamage < currentAbsorb) + currentAbsorb = RemainingDamage; + + RemainingDamage -= currentAbsorb; + + // Reduce shield amount + mod->m_amount -= currentAbsorb; + if ((*i)->GetHolder()->DropAuraCharge()) + mod->m_amount = 0; + // Need remove it later + if (mod->m_amount <= 0) + existExpired = true; + } + + // Remove all expired absorb auras + if (existExpired) + { + for (AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();) + { + if ((*i)->GetModifier()->m_amount <= 0) + { + RemoveAurasDueToSpell((*i)->GetId(), nullptr, AURA_REMOVE_BY_SHIELD_BREAK); + i = vSchoolAbsorb.begin(); + } + else + ++i; + } + } + + // absorb by mana cost + AuraList const& vManaShield = GetAurasByType(SPELL_AURA_MANA_SHIELD); + for (AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next) + { + next = i; + ++next; + + // check damage school mask + if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) + continue; + + int32 currentAbsorb; + if (RemainingDamage >= (*i)->GetModifier()->m_amount) + currentAbsorb = (*i)->GetModifier()->m_amount; + else + currentAbsorb = RemainingDamage; + + if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()]) + { + if (Player *modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier, spell); + + int32 maxAbsorb = int32(GetPower(POWER_MANA) / manaMultiplier); + if (currentAbsorb > maxAbsorb) + currentAbsorb = maxAbsorb; + + int32 manaReduction = int32(currentAbsorb * manaMultiplier); + ApplyPowerMod(POWER_MANA, manaReduction, false); + } + + (*i)->GetModifier()->m_amount -= currentAbsorb; + if ((*i)->GetModifier()->m_amount <= 0) + { + RemoveAurasDueToSpell((*i)->GetId()); + next = vManaShield.begin(); + } + + RemainingDamage -= currentAbsorb; + } + + // only split damage if not damaging yourself + if (pCaster != this) + { + AuraList const& vSplitDamageFlat = GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT); + for (AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next) + { + next = i; + ++next; + + // check damage school mask + if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) + continue; + + // Damage can be splitted only if aura has an alive caster + Unit* reflectTo = (*i)->GetCaster(); + if (!reflectTo || reflectTo == this || !reflectTo->IsInWorld() || !reflectTo->isAlive()) + continue; + + int32 currentAbsorb; + if (RemainingDamage >= (*i)->GetModifier()->m_amount) + currentAbsorb = (*i)->GetModifier()->m_amount; + else + currentAbsorb = RemainingDamage; + + RemainingDamage -= currentAbsorb; + + uint32 splitted = currentAbsorb; + uint32 splitted_absorb = 0; + // Nostalrius : la reflection (bene de sacrifice par exemple) ne fait pas forcement des degats (si pala sous bouclier divin) + uint32 reflectAbsorb = 0, reflectResist = 0; + // On evite une boucle infinie + if (!reflectTo->HasAuraType(SPELL_AURA_SPLIT_DAMAGE_FLAT)) + reflectTo->CalculateDamageAbsorbAndResist(pCaster, schoolMask, DOT, splitted, &reflectAbsorb, &reflectResist, spellProto); + splitted -= (reflectAbsorb + reflectResist); + pCaster->DealDamageMods(reflectTo, splitted, &splitted_absorb); + pCaster->SendSpellNonMeleeDamageLog(reflectTo, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false); + CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL, reflectAbsorb, reflectResist); + pCaster->DealDamage(reflectTo, splitted, &cleanDamage, DOT, schoolMask, (*i)->GetSpellProto(), false); + } + + AuraList const& vSplitDamagePct = GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT); + for (AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next) + { + next = i; + ++next; + + // check damage school mask + if (((*i)->GetModifier()->m_miscvalue & schoolMask) == 0) + continue; + + // Damage can be splitted only if aura has an alive caster + Unit *caster = (*i)->GetCaster(); + if (!caster || caster == this || !caster->IsInWorld() || !caster->isAlive()) + continue; + + uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f); + + RemainingDamage -= int32(splitted); + + uint32 split_absorb = 0; + pCaster->DealDamageMods(caster, splitted, &split_absorb); + + pCaster->SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false); + + CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL, 0, 0); + pCaster->DealDamage(caster, splitted, &cleanDamage, DOT, schoolMask, (*i)->GetSpellProto(), false); + } + } + + *absorb = damage - RemainingDamage - *resist; +} + +void Unit::CalculateAbsorbResistBlock(Unit *pCaster, SpellNonMeleeDamage *damageInfo, SpellEntry const* spellProto, WeaponAttackType attType, Spell* spell) +{ + bool blocked = false; + // Get blocked status + switch (spellProto->DmgClass) + { + // Melee and Ranged Spells + case SPELL_DAMAGE_CLASS_RANGED: + case SPELL_DAMAGE_CLASS_MELEE: + blocked = IsSpellBlocked(pCaster, spellProto, attType); + break; + default: + break; + } + + if (blocked) + { + damageInfo->blocked = GetShieldBlockValue(); + if (damageInfo->damage < damageInfo->blocked) + damageInfo->blocked = damageInfo->damage; + damageInfo->damage -= damageInfo->blocked; + } + + CalculateDamageAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), SPELL_DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist, spellProto, spell); + damageInfo->damage -= damageInfo->absorb + damageInfo->resist; +} + +void Unit::AttackerStateUpdate(Unit *pVictim, WeaponAttackType attType, bool extra) +{ + if (hasUnitState(UNIT_STAT_CAN_NOT_REACT) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED)) + return; + + if (!pVictim->isAlive() || !isAlive()) + return; + + if (!extra && IsNonMeleeSpellCasted(false)) + return; + + uint32 hitInfo; + if (attType == BASE_ATTACK) + hitInfo = HITINFO_NORMALSWING2; + else if (attType == OFF_ATTACK) + hitInfo = HITINFO_LEFTSWING; + else + return; // ignore ranged case + + // Nostalrius: check ligne de vision + if (!IsWithinLOSInMap(pVictim)) + return; + + if (GetExtraAttacks() && !extra) + AddExtraAttackOnUpdate(); + + // melee attack spell casted at main hand attack only + if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL]) + { + m_currentSpells[CURRENT_MELEE_SPELL]->cast(); + Spell* spell = m_currentSpells[CURRENT_MELEE_SPELL]; + if (!spell || !spell->IsNextMeleeSwingSpell() || spell->isSuccessCast()) + return; + } + + CalcDamageInfo damageInfo; + CalculateMeleeDamage(pVictim, 0, &damageInfo, attType); + // Send log damage message to client + for (uint8 i = 0; i < m_weaponDamageCount[attType]; i++) + { + damageInfo.totalDamage -= damageInfo.subDamage[i].damage; + DealDamageMods(pVictim, damageInfo.subDamage[i].damage, &damageInfo.subDamage[i].absorb); + damageInfo.totalDamage += damageInfo.subDamage[i].damage; + } + + SendAttackStateUpdate(&damageInfo); + ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.totalDamage, damageInfo.attackType); + + DealMeleeDamage(&damageInfo, true); + + if (GetTypeId() == TYPEID_PLAYER) + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", + GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.totalDamage, damageInfo.totalAbsorb, damageInfo.blocked_amount, damageInfo.totalResist); + else + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.", + GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.totalDamage, damageInfo.totalAbsorb, damageInfo.blocked_amount, damageInfo.totalResist); + + // if damage pVictim call AI reaction + pVictim->AttackedBy(this); + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MELEE_ATTACK); +} + +MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const +{ + // This is only wrapper + + // Miss chance based on melee + float miss_chance = MeleeMissChanceCalc(pVictim, attType); + + // Critical hit chance + float crit_chance = GetUnitCriticalChance(attType, pVictim); + + // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case) + float dodge_chance = pVictim->GetUnitDodgeChance(); + float block_chance = pVictim->GetUnitBlockChance(); + float parry_chance = pVictim->GetUnitParryChance(); + + // Useful if want to specify crit & miss chances for melee, else it could be removed + //DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance, crit_chance, dodge_chance, parry_chance, block_chance); + + return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance * 100), int32(miss_chance * 100), int32(dodge_chance * 100), int32(parry_chance * 100), int32(block_chance * 100), false); +} + +MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance, bool SpellCasted) const +{ + // Nostalrius : cheat. + if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_ALWAYS_CRIT)) + return MELEE_HIT_CRIT; + + if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode()) + return MELEE_HIT_EVADE; + + int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim); + int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this); + + int32 attackerWeaponSkill = GetWeaponSkillValue(attType, pVictim); + int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this); + + // bonus from skills is 0.04% + int32 skillBonus = 4 * (attackerWeaponSkill - victimMaxSkillValueForLevel); + int32 sum = 0, tmp = 0; + int32 roll = urand(0, 10000); + + //DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus); + //DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d", roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance); + + tmp = miss_chance; + + if (tmp > 0 && roll < (sum += tmp)) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: MISS"); + return MELEE_HIT_MISS; + } + + // always crit against a sitting target (except 0 crit chance) + if (pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState()) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRIT (sitting victim)"); + return MELEE_HIT_CRIT; + } + + bool from_behind = !pVictim->HasInArc(M_PI_F, this); + + if (from_behind) + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: attack came from behind."); + + // Dodge chance + + // only players can't dodge if attacker is behind + if (pVictim->GetTypeId() != TYPEID_PLAYER || !from_behind) + { + tmp = dodge_chance; + if ((tmp > 0) // check if unit _can_ dodge + && ((tmp -= skillBonus) > 0) + && roll < (sum += tmp)) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum - tmp, sum); + return MELEE_HIT_DODGE; + } + } + + // parry chances + // check if attack comes from behind, nobody can parry or block if attacker is behind + if (!from_behind) + { + if (parry_chance > 0 && (pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY))) + { + parry_chance -= skillBonus; + + if (parry_chance > 0 && // check if unit _can_ parry + (roll < (sum += parry_chance))) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum - parry_chance, sum); + return MELEE_HIT_PARRY; + } + } + } + + // Max 40% chance to score a glancing blow against mobs that are higher level (can do only players and pets and not with ranged weapon) + if (attType != RANGED_ATTACK && !SpellCasted && + (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->IsPet()) && + pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->IsPet() && !((Creature*)pVictim)->IsTotem()) + { + // cap possible value (with bonuses > max skill) + int32 skill = attackerWeaponSkill; + int32 maxskill = attackerMaxSkillValueForLevel; + skill = (skill > maxskill) ? maxskill : skill; + + // (Youfie) Le +skill avant BC ne permet pas de réduire la fréquence des glancing blows une fois qu'il est égal au niveau du joueur*5 + if (attackerWeaponSkill > maxskill) + attackerWeaponSkill = maxskill; + + // (Youfie) Chance de glance en Vanilla (inchangée par le +skill au delà de maxskill, cf. au dessus) : + tmp = (10 + ((victimDefenseSkill - attackerWeaponSkill) * 2)) * 100; + tmp = tmp > 4000 ? 4000 : tmp; + if (tmp < 0) + tmp = 0; + // sLog.outString("tmp = %i, Skill = %i, Max Skill = %i", tmp, attackerWeaponSkill, attackerMaxSkillValueForLevel); //Pour tests & débug via la console + + if (roll < (sum += tmp)) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum - 4000, sum); + return MELEE_HIT_GLANCING; + } + } + + // block chances + // check if attack comes from behind, nobody can parry or block if attacker is behind + if (!from_behind) + { + if ((pVictim->GetTypeId() == TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK)) + && !(GetTypeId() == TYPEID_UNIT && GetMeleeDamageSchoolMask() != SPELL_SCHOOL_MASK_NORMAL)) // can't block elemental melee attacks from mobs + { + tmp = block_chance; + if ((tmp > 0) // check if unit _can_ block + && ((tmp -= skillBonus) > 0) + && (roll < (sum += tmp))) + { + // Critical chance + tmp = crit_chance; + if (GetTypeId() == TYPEID_PLAYER && SpellCasted && tmp > 0) + { + if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || + (pVictim->IsPlayer() && pVictim->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) + tmp = 0; + if (roll_chance_i(tmp / 100)) + { + DEBUG_LOG("RollMeleeOutcomeAgainst: BLOCKED CRIT"); + return MELEE_HIT_BLOCK_CRIT; + } + } + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum - tmp, sum); + return MELEE_HIT_BLOCK; + } + } + } + + // Critical chance + tmp = crit_chance; + + if (tmp > 0 && roll < (sum += tmp)) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum - tmp, sum); + return MELEE_HIT_CRIT; + } + + if ((GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->IsPet()) && + !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) && + !SpellCasted /*Only autoattack can be crashing blow*/) + { + // mobs can score crushing blows if they're 3 or more levels above victim + // or when their weapon skill is 15 or more above victim's defense skill + tmp = victimDefenseSkill; + int32 tmpmax = victimMaxSkillValueForLevel; + // having defense above your maximum (from items, talents etc.) has no effect + tmp = tmp > tmpmax ? tmpmax : tmp; + // tmp = mob's level * 5 - player's current defense skill + tmp = attackerMaxSkillValueForLevel - tmp; + if (tmp >= 15) + { + // add 2% chance per lacking skill point, min. is 15% + tmp = tmp * 200 - 1500; + if (roll < (sum += tmp)) + { + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum - tmp, sum); + return MELEE_HIT_CRUSHING; + } + } + } + + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: NORMAL"); + return MELEE_HIT_NORMAL; +} + +uint32 Unit::CalculateDamage(WeaponAttackType attType, bool normalized, uint8 index) +{ + float min_damage, max_damage; + + if (GetTypeId() != TYPEID_PLAYER && index != 0) + return 0; + + if ((normalized || index != 0) && GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->CalculateMinMaxDamage(attType, normalized, min_damage, max_damage, index); + else + { + switch (attType) + { + case RANGED_ATTACK: + min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE); + max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE); + break; + case BASE_ATTACK: + min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE); + max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE); + break; + case OFF_ATTACK: + min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE); + max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE); + break; + // Just for good manner + default: + min_damage = 0.0f; + max_damage = 0.0f; + break; + } + } + + if (min_damage > max_damage) + std::swap(min_damage, max_damage); + + if (max_damage == 0.0f) + max_damage = 5.0f; + + return urand((uint32)min_damage, (uint32)max_damage); +} + +float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const +{ + // Fix Nostalrius. La formule de MaNGOSZero est BC. + uint32 spellLevel = spellProto->spellLevel; + if (spellLevel <= 0 || spellLevel > 20) + return 1.0f; + return 1 - ((20.0f - spellLevel) * 0.0375f); + + /* + float LvlPenalty = 0.0f; + + if(spellLevel < 20) + LvlPenalty = 20.0f - spellLevel * 3.75f; + float LvlFactor = (float(spellLevel) + 6.0f) / float(getLevel()); + if(LvlFactor > 1.0f) + LvlFactor = 1.0f; + + return (100.0f - LvlPenalty) * LvlFactor / 100.0f; + */ +} + +void Unit::SendMeleeAttackStart(Unit* pVictim) +{ + WorldPacket data(SMSG_ATTACKSTART, 8 + 8); + data << GetObjectGuid(); + data << pVictim->GetObjectGuid(); + + SendObjectMessageToSet(&data, true); + DEBUG_LOG("WORLD: Sent SMSG_ATTACKSTART"); +} + +void Unit::SendMeleeAttackStop(Unit* victim) +{ + if (!victim) + return; + + WorldPacket data(SMSG_ATTACKSTOP, (4 + 16)); // we guess size + data << GetPackGUID(); + data << victim->GetPackGUID(); // can be 0x00... + data << uint32(0); // can be 0x1 + SendObjectMessageToSet(&data, true); + DETAIL_FILTER_LOG(LOG_FILTER_COMBAT, "%s %u stopped attacking %s %u", (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), victim->GetGUIDLow()); + + /*if(victim->GetTypeId() == TYPEID_UNIT) + ((Creature*)victim)->AI().EnterEvadeMode(this);*/ +} + +bool Unit::IsSpellBlocked(Unit *pCaster, SpellEntry const *spellEntry, WeaponAttackType attackType) +{ + if (!HasInArc(M_PI_F, pCaster)) + return false; + + if (spellEntry) + { + // Some spells cannot be blocked + if (spellEntry->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK) + return false; + } + + // Check creatures flags_extra for disable block + if (GetTypeId() == TYPEID_UNIT) + { + if (((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) + return false; + } + + float blockChance = GetUnitBlockChance(); + blockChance += (int32(pCaster->GetWeaponSkillValue(attackType)) - int32(GetMaxSkillValueForLevel())) * 0.04f; + + if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || + (pCaster->IsPlayer() && pCaster->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) + blockChance = 0; + return roll_chance_f(blockChance); +} + +// Melee based spells can be miss, parry or dodge on this step +// Crit or block - determined on damage calculation phase! (and can be both in some time) +float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell, Spell* spellPtr) +{ + // Calculate hit chance (more correct for chance mod) + float hitChance = 0.0f; + + // PvP - PvE melee chances + if (pVictim->GetTypeId() == TYPEID_PLAYER) + hitChance = 95.0f + skillDiff * 0.04f; + else if (skillDiff < -10) + hitChance = 93.0f + (skillDiff + 10) * 0.4f; // 7% base chance to miss for big skill diff (%6 in 3.x) + else + hitChance = 95.0f + skillDiff * 0.1f; + + // Hit chance depends from victim auras + if (attType == RANGED_ATTACK) + hitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); + else + hitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); + + // Spellmod from SPELLMOD_RESIST_MISS_CHANCE + if (Player *modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, hitChance, spellPtr); + + // Miss = 100 - hit + float missChance = 100.0f - hitChance; + + // Bonuses from attacker aura and ratings + if (attType == RANGED_ATTACK) + missChance -= m_modRangedHitChance; + else + missChance -= m_modMeleeHitChance; + + // Limit miss chance from 0 to 60% + if (missChance < 0.0f) + return 0.0f; + if (missChance > 60.0f) + return 60.0f; + return missChance; +} + +// Melee based spells hit result calculations +SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell, Spell* spellPtr) +{ + WeaponAttackType attType = BASE_ATTACK; + + if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED) + attType = RANGED_ATTACK; + + // Warrior spell Execute (5308) should never dodge, miss, resist ... Only the trigger can (20647) + if (spell->IsFitToFamily() && spell->Id != 20647) + return SPELL_MISS_NONE; + + // bonus from skills is 0.04% per skill Diff + int32 attackerWeaponSkill = (spell->EquippedItemClass == ITEM_CLASS_WEAPON) ? int32(GetWeaponSkillValue(attType, pVictim)) : GetMaxSkillValueForLevel(); + int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this)); + int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this)); + + uint32 roll = urand(0, 10000); + + uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell, spellPtr) * 100.0f); + // Roll miss + uint32 tmp = spell->AttributesEx3 & SPELL_ATTR_EX3_CANT_MISS ? 0 : missChance; + if (roll < tmp) + return SPELL_MISS_MISS; + + // Chance resist mechanic (select max value from every mechanic spell effect) + int32 resist_mech = 0; + // Get effects mechanic and chance + if (spell->Mechanic) + resist_mech = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, spell->Mechanic) * 100; + // Roll chance + tmp += resist_mech; + if (roll < tmp) + return SPELL_MISS_RESIST; + + bool canDodge = true; + bool canParry = true; + + // Same spells cannot be parry/dodge + if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK) + return SPELL_MISS_NONE; + + // Ranged attack cannot be parry/dodge + if (attType == RANGED_ATTACK) + return SPELL_MISS_NONE; + + bool from_behind = !pVictim->HasInArc(M_PI_F, this); + + // Check for attack from behind + if (from_behind) + { + // Can`t dodge from behind in PvP (but its possible in PvE) + if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER) + canDodge = false; + // Can`t parry + canParry = false; + } + // Check creatures flags_extra for disable parry + if (pVictim->GetTypeId() == TYPEID_UNIT) + { + uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra; + if (flagEx & CREATURE_FLAG_EXTRA_NO_PARRY) + canParry = false; + } + + // Check if the player can parry + if (pVictim->GetTypeId() == TYPEID_PLAYER) + { + if (!((Player*)pVictim)->CanParry()) + canParry = false; + } + + if (canDodge) + { + // Roll dodge + int32 dodgeChance = int32(pVictim->GetUnitDodgeChance() * 100.0f) - skillDiff * 4; + + if (dodgeChance < 0) + dodgeChance = 0; + + + tmp += dodgeChance; + if (roll < tmp) + return SPELL_MISS_DODGE; + } + + if (canParry) + { + // Roll parry + int32 parryChance = int32(pVictim->GetUnitParryChance() * 100.0f) - skillDiff * 4; + // Can`t parry from behind + if (parryChance < 0) + parryChance = 0; + + tmp += parryChance; + if (roll < tmp) + return SPELL_MISS_PARRY; + } + + return SPELL_MISS_NONE; +} + +SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell, Spell* spellPtr) +{ + // Can`t miss on dead target (on skinning for example) + if (!pVictim->isAlive()) + return SPELL_MISS_NONE; + + // Spell cannot be resisted (not exist on dbc, custom flag) + if (spell->AttributesEx4 & SPELL_ATTR_EX4_IGNORE_RESISTANCES) + return SPELL_MISS_NONE; + + int32 hitChance = MagicSpellHitChance(pVictim, spell, spellPtr); + int32 missChance = 10000 - hitChance; + int32 rand = irand(0, 10000); + + if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || + (pVictim->IsPlayer() && pVictim->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) + missChance = 0; + + if (rand < missChance) + return SPELL_MISS_RESIST; + + return SPELL_MISS_NONE; +} + +float Unit::GetSpellResistChance(Unit* victim, uint32 schoolMask, bool innateResists) const +{ + // Get base victim resistance for school + float resistModHitChance = victim->GetResistance(GetFirstSchoolInMask(SpellSchoolMask(schoolMask))); + // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura + resistModHitChance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask); + // No "negative" resist chance. Applied before innate resists. + if (resistModHitChance < 0) + resistModHitChance = 0.0f; + + // Computing innate resists, resistance bonus when attacking a creature higher level. Not affected by modifiers. + if (innateResists && victim->GetTypeId() == TYPEID_UNIT) + { + int32 leveldiff = int32(victim->GetLevelForTarget(this)) - int32(GetLevelForTarget(victim)); + resistModHitChance += int32((8.0f * leveldiff) * getLevel() / 63.0f); + } + resistModHitChance *= (float)(0.15f / getLevel()); + + if (resistModHitChance < 0.0f) + resistModHitChance = 0.0f; + if (resistModHitChance > 0.75f) + resistModHitChance = 0.75f; + + return resistModHitChance; +} + +int32 Unit::MagicSpellHitChance(Unit *pVictim, SpellEntry const *spell, Spell* spellPtr) +{ + if (spell->AttributesEx3 & SPELL_ATTR_EX3_CANT_MISS) + return 10000; + + SpellSchoolMask schoolMask = GetSpellSchoolMask(spell); + // PvP - PvE spell misschances per leveldif > 2 + int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11; + int32 leveldif = int32(pVictim->GetLevelForTarget(this)) - int32(GetLevelForTarget(pVictim)); + + // Base hit chance from attacker and victim levels + float modHitChance; + if (leveldif < 3) + modHitChance = 96 - leveldif; + else + modHitChance = 94 - (leveldif - 2) * lchance; + + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "%s [%u] : Binary [%s]. Base hit chance %f, level diff: %d", spell->SpellName[2], spell->Id, spell->IsBinary() ? "YES" : "NO", modHitChance, leveldif); + + // Spellmod from SPELLMOD_RESIST_MISS_CHANCE + if (Player *modOwner = GetSpellModOwner()) + { + modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance, spellPtr); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELLMOD_RESIST_MISS_CHANCE : %f", modHitChance); + } + // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras + modHitChance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE (+ %i) : %f", pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask), modHitChance); + + // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura + if (IsAreaOfEffectSpell(spell)) + { + modHitChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_AOE_AVOIDANCE (- %i) : %f", pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE), modHitChance); + } + + // Chance resist mechanic + int32 resist_mech = 0; + // Get effects mechanic and chance + if (spell->Mechanic) + resist_mech = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, spell->Mechanic); + // Apply mod + modHitChance -= resist_mech; + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_MECHANIC_RESISTANCE (- %i) : %f", resist_mech, modHitChance); + + // Chance resist debuff + modHitChance -= pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_DEBUFF_RESISTANCE (- %i) : %f", pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel)), modHitChance); + + // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings + modHitChance += int32(m_modSpellHitChance); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "SPELL_AURA_MOD_SPELL_HIT_CHANCE (+ %i) : %f", int32(m_modSpellHitChance), modHitChance); + + // Nostalrius: sorts binaires. + if (spell->IsBinary()) + { + // Get base victim resistance for school + float resistModHitChance = GetSpellResistChance(pVictim, schoolMask, false); + modHitChance *= (1 - resistModHitChance); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "x %f : HitChance = %f", (1 - resistModHitChance), modHitChance); + } + + int32 HitChance = modHitChance * 100; + if (HitChance < 100) HitChance = 100; + if (HitChance > 9900) HitChance = 9900; + return HitChance; +} +// Calculate spell hit result can be: +// Every spell can: Evade/Immune/Reflect/Sucesful hit +// For melee based spells: +// Miss +// Dodge +// Parry +// For spells +// Resist +SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, SpellEffectIndex effIndex, bool CanReflect, Spell* spellPtr) +{ + // Return evade for units in evade mode + if (pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode()) + return SPELL_MISS_EVADE; + + // Check for immune (use charges) + if (pVictim != this && pVictim->IsImmuneToSpell(spell, pVictim == this)) + return SPELL_MISS_IMMUNE; + + // All positive spells can`t miss + // TODO: client not show miss log for this spells - so need find info for this in dbc and use it! + if (IsPositiveSpell(spell->Id, this, pVictim) || IsPositiveEffect(spell, effIndex)) + return SPELL_MISS_NONE; + + // Check for immune (use charges) + SpellSchoolMask schoolMask; + if (spellPtr) + schoolMask = spellPtr->m_spellSchoolMask; + else + schoolMask = GetSpellSchoolMask(spell); + + if (pVictim != this && pVictim->IsImmuneToDamage(schoolMask)) + return SPELL_MISS_IMMUNE; + + // Try victim reflect spell + if (CanReflect) + { + int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS); + Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL); + for (Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i) + if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell)) + reflectchance += (*i)->GetModifier()->m_amount; + if (reflectchance > 0 && roll_chance_i(reflectchance)) + { + // Start triggers for remove charges if need (trigger only for victim, and mark as active spell) + ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell); + return SPELL_MISS_REFLECT; + } + } + + switch (spell->DmgClass) + { + case SPELL_DAMAGE_CLASS_NONE: + return SPELL_MISS_NONE; + case SPELL_DAMAGE_CLASS_MAGIC: + return MagicSpellHitResult(pVictim, spell, spellPtr); + case SPELL_DAMAGE_CLASS_MELEE: + case SPELL_DAMAGE_CLASS_RANGED: + return MeleeSpellHitResult(pVictim, spell, spellPtr); + } + return SPELL_MISS_NONE; +} + +bool Unit::IsAuraResist(SpellEntry const* spell) +{ + // Chance resist mechanic (select max value from every mechanic spell effect) + int32 resist_mech = 0; + int32 rand = urand(0, 99); + // Get effects mechanic and chance => Aura side (Nostalrius) + for (int eff = 0; eff < MAX_EFFECT_INDEX; ++eff) + { + if (spell->Effect[eff] != SPELL_EFFECT_APPLY_AURA) + continue; + int32 effect_mech = spell->EffectMechanic[eff]; + if (effect_mech && effect_mech != spell->Mechanic) + { + int32 temp = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech); + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "Spell %u Eff %u: MechanicResistChance %i", spell->Id, eff, temp); + if (resist_mech < temp) + resist_mech = temp; + } + } + return (rand < resist_mech); +} + +float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const +{ + if (!pVictim) + return 0.0f; + + // Base misschance 5% + float missChance = 5.0f; + + // DualWield - white damage has additional 19% miss penalty + if (haveOffhandWeapon() && attType != RANGED_ATTACK) + { + bool isNormal = false; + for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) + { + if (m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL)) + { + isNormal = true; + break; + } + } + if (!isNormal && !m_currentSpells[CURRENT_MELEE_SPELL]) + missChance += 19.0f; + } + + int32 skillDiff = int32(GetWeaponSkillValue(attType, pVictim)) - int32(pVictim->GetDefenseSkillValue(this)); + + // PvP - PvE melee chances + if (pVictim->GetTypeId() == TYPEID_PLAYER) + missChance -= skillDiff * 0.04f; + else if (skillDiff < -10) + missChance -= (skillDiff + 10) * 0.4f - 2.0f; // 7% base chance to miss for big skill diff (%6 in 3.x) + else + missChance -= skillDiff * 0.1f; + + // Hit chance bonus from attacker based on ratings and auras + if (attType == RANGED_ATTACK) + missChance -= m_modRangedHitChance; + else + missChance -= m_modMeleeHitChance; + + // Modify miss chance by victim auras + if (attType == RANGED_ATTACK) + missChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE); + else + missChance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE); + + // Limit miss chance from 0 to 60% + if (missChance < 0.0f) + return 0.0f; + if (missChance > 60.0f) + return 60.0f; + + return missChance; +} + +uint32 Unit::GetDefenseSkillValue(Unit const* target) const +{ + if (GetTypeId() == TYPEID_PLAYER) + { + // in PvP use full skill instead current skill value + uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER) + ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE) + : ((Player*)this)->GetSkillValue(SKILL_DEFENSE); + return value; + } + else + return GetUnitMeleeSkill(target); +} + +float Unit::GetUnitDodgeChance() const +{ + if (IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) + return 0.0f; + if (GetTypeId() == TYPEID_PLAYER) + return GetFloatValue(PLAYER_DODGE_PERCENTAGE); + else + { + if (((Creature const*)this)->IsTotem()) + return 0.0f; + else + { + float dodge = 5.0f; + dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT); + return dodge > 0.0f ? dodge : 0.0f; + } + } +} + +float Unit::GetUnitParryChance() const +{ + if (IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) + return 0.0f; + + float chance = 0.0f; + + if (GetTypeId() == TYPEID_PLAYER) + { + Player const* player = (Player const*)this; + if (player->CanParry()) + { + Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK, true, true); + if (!tmpitem) + tmpitem = player->GetWeaponForAttack(OFF_ATTACK, true, true); + + if (tmpitem) + chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE); + } + } + else if (GetTypeId() == TYPEID_UNIT) + { + if (GetCreatureType() == CREATURE_TYPE_HUMANOID) + { + chance = 5.0f; + chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT); + } + } + + return chance > 0.0f ? chance : 0.0f; +} + +float Unit::GetUnitBlockChance() const +{ + if (IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) + return 0.0f; + + if (GetTypeId() == TYPEID_PLAYER) + { + Player const* player = (Player const*)this; + if (player->CanBlock() && player->CanUseEquippedWeapon(OFF_ATTACK)) + { + Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); + if (tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block) + return GetFloatValue(PLAYER_BLOCK_PERCENTAGE); + } + // is player but has no block ability or no not broken shield equipped + return 0.0f; + } + else + { + if (((Creature const*)this)->IsTotem()) + return 0.0f; + else + { + float block = 5.0f; + block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT); + return block > 0.0f ? block : 0.0f; + } + } +} + +float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const +{ + float crit; + + if (GetTypeId() == TYPEID_PLAYER) + { + switch (attackType) + { + case OFF_ATTACK: + case BASE_ATTACK: + crit = GetFloatValue(PLAYER_CRIT_PERCENTAGE); + break; + case RANGED_ATTACK: + crit = GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE); + break; + // Just for good manner + default: + crit = 0.0f; + break; + } + } + else + { + crit = 5.0f; + crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT); + } + + // flat aura mods + if (attackType == RANGED_ATTACK) + crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE); + else + crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE); + + // Apply crit chance from defence skill + crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f; + + if (crit < 0.0f) + crit = 0.0f; + return crit; +} + +uint32 Unit::GetWeaponSkillValue(WeaponAttackType attType, Unit const* target) const +{ + uint32 value = 0; + if (GetTypeId() == TYPEID_PLAYER) + { + Item* item = ((Player*)this)->GetWeaponForAttack(attType, true, true); + + // feral or unarmed skill only for base attack + if (attType != BASE_ATTACK && !item) + return 0; + + if (IsInFeralForm()) + return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact + + // weapon skill or (unarmed for base attack) + uint32 skill = item ? item->GetSkill() : SKILL_UNARMED; + +// Daemon: pas en preBC ! +// // in PvP use full skill instead current skill value +// value = (target && target->GetTypeId() == TYPEID_PLAYER) +// ? ((Player*)this)->GetMaxSkillValue(skill) +// : ((Player*)this)->GetSkillValue(skill); + value = ToPlayer()->GetSkillValue(skill); + } + else + value = GetUnitMeleeSkill(target); + return value; +} + +void Unit::_UpdateSpells(uint32 time) +{ + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) + _UpdateAutoRepeatSpell(); + + // remove finished spells from current pointers + for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i) + { + if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED) + { + m_currentSpells[i]->SetReferencedFromCurrent(false); + m_currentSpells[i] = nullptr; // remove pointer + } + } + + // update auras + // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras + for (m_spellAuraHoldersUpdateIterator = m_spellAuraHolders.begin(); m_spellAuraHoldersUpdateIterator != m_spellAuraHolders.end();) + { + SpellAuraHolder* i_holder = m_spellAuraHoldersUpdateIterator->second; + ++m_spellAuraHoldersUpdateIterator; // need shift to next for allow update if need into aura update + i_holder->UpdateHolder(time); + } + + // remove expired auras + for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) + { + SpellAuraHolder *holder = iter->second; + + if (!(holder->IsPermanent() || holder->IsPassive()) && holder->GetAuraDuration() == 0) + { + RemoveSpellAuraHolder(holder, AURA_REMOVE_BY_EXPIRE); + iter = m_spellAuraHolders.begin(); + } + else + ++iter; + } + + if (!m_gameObj.empty()) + { + GameObjectList::iterator ite1, dnext1; + for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1) + { + dnext1 = ite1; + //(*i)->Update( difftime ); + if (!(*ite1)->isSpawned()) + { + (*ite1)->SetOwnerGuid(ObjectGuid()); + (*ite1)->SetRespawnTime(0); + (*ite1)->Delete(); + dnext1 = m_gameObj.erase(ite1); + } + else + ++dnext1; + } + } +} + +void Unit::_UpdateAutoRepeatSpell() +{ + //check "realtime" interrupts + if ((GetTypeId() == TYPEID_PLAYER && ((Player*)this)->IsMoving()) || IsNonMeleeSpellCasted(false, false, true)) + { + // cancel wand shoot + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Category == 351) + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + m_AutoRepeatFirstCast = true; + return; + } + + //apply delay + if (m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500) + setAttackTimer(RANGED_ATTACK, 500); + m_AutoRepeatFirstCast = false; + + //castroutine + if (isAttackReady(RANGED_ATTACK)) + { + // Check if able to cast + // We need to update pointers before calling CheckCast ! + m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->UpdatePointers(); + SpellCastResult result = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true); + if (result == SPELL_FAILED_MOVING) // Just delay it if moving + return; + + if (result != SPELL_CAST_OK) + { + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + return; + } + + // we want to shoot + Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true); + spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets)); + + // all went good, reset attack + resetAttackTimer(RANGED_ATTACK); + SetStandState(UNIT_STAND_STATE_STAND); + } +} + +void Unit::SetCurrentCastedSpell(Spell * pSpell) +{ + MANGOS_ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells + + CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer(); + + if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self + + // break same type spell if it is not delayed + InterruptSpell(CSpellType, false); + + // special breakage effects: + switch (CSpellType) + { + case CURRENT_GENERIC_SPELL: + { + // generic spells always break channeled not delayed spells + InterruptSpell(CURRENT_CHANNELED_SPELL, false); + + // autorepeat breaking + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) + { + // break autorepeat if not Auto Shot + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Category == 351) + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + m_AutoRepeatFirstCast = true; + } + } + break; + + case CURRENT_CHANNELED_SPELL: + { + // channel spells always break generic non-delayed and any channeled spells + InterruptSpell(CURRENT_GENERIC_SPELL, false); + InterruptSpell(CURRENT_CHANNELED_SPELL); + + // it also does break autorepeat if not Auto Shot + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && + m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Category == 351) + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + } + break; + + case CURRENT_AUTOREPEAT_SPELL: + { + // only Auto Shoot does not break anything + if (pSpell->m_spellInfo->Category == 351) + { + // generic autorepeats break generic non-delayed and channeled non-delayed spells + InterruptSpell(CURRENT_GENERIC_SPELL, false); + InterruptSpell(CURRENT_CHANNELED_SPELL, false); + } + // special action: set first cast flag + m_AutoRepeatFirstCast = true; + } + break; + + default: + { + // other spell types don't break anything now + } break; + } + + // current spell (if it is still here) may be safely deleted now + if (m_currentSpells[CSpellType]) + m_currentSpells[CSpellType]->SetReferencedFromCurrent(false); + + // set new current spell + m_currentSpells[CSpellType] = pSpell; + pSpell->SetReferencedFromCurrent(true); + + pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]); +} + +void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed) +{ + MANGOS_ASSERT(spellType < CURRENT_MAX_SPELL); + + if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED)) + { + // send autorepeat cancel message for autorepeat spells + if (spellType == CURRENT_AUTOREPEAT_SPELL) + { + if (GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->SendAutoRepeatCancel(); + } + + if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED) + m_currentSpells[spellType]->cancel(); + + // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt) + if (m_currentSpells[spellType]) + { + m_currentSpells[spellType]->SetReferencedFromCurrent(false); + m_currentSpells[spellType] = nullptr; + } + } +} + +void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/) +{ + Spell* spell = m_currentSpells[spellType]; + if (!spell) + return; + + spell->finish(ok); + + if (spellType == CURRENT_CHANNELED_SPELL) + spell->SendChannelUpdate(0); +} + + +bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const +{ + // We don't do loop here to explicitly show that melee spell is excluded. + // Maybe later some special spells will be excluded too. + + // generic spells are casted when they are not finished and not delayed + if (m_currentSpells[CURRENT_GENERIC_SPELL] && + (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && + (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED)) + return (true); + + // channeled spells may be delayed, but they are still considered casted + else if (!skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] && + (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED)) + return (true); + + // autorepeat spells may be finished or delayed, but they are still considered casted + else if (!skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL]) + return (true); + + return (false); +} + +bool Unit::IsNoMovementSpellCasted() const +{ + if (m_currentSpells[CURRENT_GENERIC_SPELL] && + (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) && + m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED && + m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) + return (true); + else if (m_currentSpells[CURRENT_CHANNELED_SPELL] && + m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED && + m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) + return (true); + // don't need to check for AUTOREPEAT_SPELL + + return (false); +} + +void Unit::InterruptSpellsWithInterruptFlags(uint32 flags, uint32 except) +{ + for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) + if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) + if (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) + if (!spell->IsNextMeleeSwingSpell() && !spell->IsAutoRepeat() && !spell->IsTriggered() && (spell->m_spellInfo->InterruptFlags & flags) && spell->m_spellInfo->Id != except) + InterruptSpell(CurrentSpellTypes(i)); +} + + +void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id) +{ + // generic spells are interrupted if they are not finished or delayed + if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id == spell_id)) + InterruptSpell(CURRENT_GENERIC_SPELL, withDelayed); + + // autorepeat spells are interrupted if they are not finished or delayed + if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == spell_id)) + InterruptSpell(CURRENT_AUTOREPEAT_SPELL, withDelayed); + + // channeled spells are interrupted if they are not finished, even if they are delayed + if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id == spell_id)) + InterruptSpell(CURRENT_CHANNELED_SPELL, true); +} + + +Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const +{ + 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 nullptr; +} + +void Unit::SetInFront(Unit const* target) +{ + SetOrientation(GetAngle(target)); +} + +void Unit::SetFacingTo(float ori) +{ + m_movementInfo.ChangeOrientation(ori); + + Movement::MoveSplineInit init(*this, "SetFacingTo"); + init.SetFacing(ori); + init.Launch(); +} + +void Unit::SetFacingToObject(WorldObject* pObject) +{ + // never face when already moving + if (!IsStopped()) + return; + + // TODO: figure out under what conditions creature will move towards object instead of facing it where it currently is. + SetFacingTo(GetAngle(pObject)); +} + +bool Unit::isInAccessablePlaceFor(Creature const* c) const +{ + if (IsInWater()) + return c->CanSwim(); + else + return c->CanWalk() || c->CanFly(); +} + +bool Unit::IsInWater() const +{ + return GetTerrain()->IsInWater(GetPositionX(), GetPositionY(), GetPositionZ()); +} + +bool Unit::IsUnderWater() const +{ + return GetTerrain()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ()); +} + +void Unit::DeMorph() +{ + SetDisplayId(GetNativeDisplayId()); +} + +int32 Unit::GetTotalAuraModifier(AuraType auratype) const +{ + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + // Exception for stealth detection, remove hidden trap detection (id:2836) from stealth modifier (should not be taken into account) + // If it was the cast, rogue will see others rogue at 40 meters + if ((*i)->GetId() != 2836) + modifier += (*i)->GetModifier()->m_amount; + } + + + return modifier; +} + +float Unit::GetTotalAuraMultiplier(AuraType auratype) const +{ + float multiplier = 1.0f; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + multiplier *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + + return multiplier; +} + +int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const +{ + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + if ((*i)->GetModifier()->m_amount > modifier) + modifier = (*i)->GetModifier()->m_amount; + + return modifier; +} + +int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const +{ + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + if ((*i)->GetModifier()->m_amount < modifier) + modifier = (*i)->GetModifier()->m_amount; + + return modifier; +} + +int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const +{ + if (!misc_mask) + return 0; + + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue & misc_mask) + modifier += mod->m_amount; + } + return modifier; +} + +float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const +{ + if (!misc_mask) + return 1.0f; + + float multiplier = 1.0f; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue & misc_mask) + multiplier *= (100.0f + mod->m_amount) / 100.0f; + } + return multiplier; +} + +int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const +{ + if (!misc_mask) + return 0; + + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier) + modifier = mod->m_amount; + } + + return modifier; +} + +int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const +{ + if (!misc_mask) + return 0; + + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier) + modifier = mod->m_amount; + } + + return modifier; +} + +int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const +{ + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue == misc_value) + modifier += mod->m_amount; + } + return modifier; +} + +float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const +{ + float multiplier = 1.0f; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue == misc_value) + multiplier *= (100.0f + mod->m_amount) / 100.0f; + } + return multiplier; +} + +int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const +{ + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue == misc_value && mod->m_amount > modifier) + modifier = mod->m_amount; + } + + return modifier; +} + +int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const +{ + int32 modifier = 0; + + AuraList const& mTotalAuraList = GetAurasByType(auratype); + for (AuraList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) + { + Modifier* mod = (*i)->GetModifier(); + if (mod->m_miscvalue == misc_value && mod->m_amount < modifier) + modifier = mod->m_amount; + } + + return modifier; +} + +bool Unit::AddSpellAuraHolder(SpellAuraHolder *holder) +{ + SpellEntry const* aurSpellInfo = holder->GetSpellProto(); + + // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load) + if (!isAlive() && !IsDeathPersistentSpell(aurSpellInfo) && + !IsDeathOnlySpell(aurSpellInfo) && + (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading())) + { + delete holder; + return false; + } + + if (holder->GetTarget() != this) + { + sLog.outError("Holder (spell %u) add to spell aura holder list of %s (lowguid: %u) but spell aura holder target is %s (lowguid: %u)", + holder->GetId(), (GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), + (holder->GetTarget()->GetTypeId() == TYPEID_PLAYER ? "player" : "creature"), holder->GetTarget()->GetGUIDLow()); + delete holder; + return false; + } + + // passive and persistent auras can stack with themselves any number of times + if ((!holder->IsPassive() && !holder->IsPersistent()) || holder->IsAreaAura()) + { + SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(aurSpellInfo->Id); + + // take out same spell + for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second; ++iter) + { + SpellAuraHolder *foundHolder = iter->second; + if ((foundHolder->GetCasterGuid() == holder->GetCasterGuid() && foundHolder->GetCastItemGuid() == holder->GetCastItemGuid()) + || aurSpellInfo->Custom & SPELL_CUSTOM_ALLOW_STACK_BETWEEN_CASTER) + { + if (foundHolder->CanBeRefreshedBy(holder)) + { + Unit* pAuraCaster = foundHolder->GetCaster(); + if (pAuraCaster) + { + foundHolder->Refresh(pAuraCaster, this, holder); + delete holder; + return false; + } + } + + // Aura can stack on self -> Stack it; + if (aurSpellInfo->StackAmount) + { + // can be created with >1 stack by some spell mods + foundHolder->ModStackAmount(holder->GetStackAmount()); + delete holder; + return false; + } + + // Check for coexisting Weapon-proced Auras + if (holder->IsWeaponBuffCoexistableWith(foundHolder)) + continue; + + // can be only single + RemoveSpellAuraHolder(foundHolder, AURA_REMOVE_BY_STACK); + break; + } + + // Skip channeled spells (Arcane missile, ...) so two casters can channel at the same time + if (IsChanneledSpell(aurSpellInfo)) + continue; + bool stop = false; + + for (int32 i = 0; i < MAX_EFFECT_INDEX && !stop; ++i) + { + // no need to check non stacking auras that weren't/won't be applied on this target + if (!foundHolder->m_auras[i] || !holder->m_auras[i]) + continue; + + // Croise + if (aurSpellInfo->Id == 20007) + break; + + // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original + AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[i]); + + switch (aurNameReal) + { + // DoT/HoT/etc + case SPELL_AURA_DUMMY: // allow stack (HoTs checked later) + case SPELL_AURA_PERIODIC_DAMAGE: + case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: + case SPELL_AURA_PERIODIC_LEECH: + case SPELL_AURA_PERIODIC_HEAL: + case SPELL_AURA_OBS_MOD_HEALTH: + case SPELL_AURA_PERIODIC_MANA_LEECH: + case SPELL_AURA_OBS_MOD_MANA: + case SPELL_AURA_POWER_BURN_MANA: + case SPELL_AURA_CHANNEL_DEATH_ITEM: + break; + case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable + default: // not allow + // can be only single (this check done at _each_ aura add + stop = true; + break; + } + } + + if (stop) + { + RemoveSpellAuraHolder(foundHolder, AURA_REMOVE_BY_STACK); + break; + } + } + } + + // passive auras not stackable with other ranks + if (!IsPassiveSpellStackableWithRanks(aurSpellInfo) && !holder->IsPersistent()) + { + if (!RemoveNoStackAurasDueToAuraHolder(holder)) + { + DETAIL_LOG("[STACK] Annulation de l'aura en cours : %u.", holder->GetId()); + delete holder; + return false; // couldn't remove conflicting aura with higher rank + } + } + + // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura) + if (holder->IsSingleTarget()) + { + if (Unit* caster = holder->GetCaster()) // caster not in world + { + SingleCastSpellTargetMap& scTargets = caster->GetSingleCastSpellTargets(); + for (SingleCastSpellTargetMap::iterator itr = scTargets.begin(); itr != scTargets.end();) + { + SpellEntry const* itr_spellEntry = itr->first; + ObjectGuid itr_targetGuid = itr->second; + + if (itr_targetGuid != GetObjectGuid() && + IsSingleTargetSpells(itr_spellEntry, aurSpellInfo)) + { + scTargets.erase(itr); // remove for caster in any case + + // remove from target if target found + if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) + itr_target->RemoveAurasDueToSpell(itr_spellEntry->Id); + + itr = scTargets.begin(); // list can be chnaged at remove aura + continue; + } + + ++itr; + } + + // register spell holder single target + scTargets[aurSpellInfo] = GetObjectGuid(); + } + } + + if (holder->IsDeleted()) + { + sLog.outInfo("[Crash/Auras] Adding aura %u on player %s, but aura marked as deleted !", holder->GetId(), GetName()); + return false; + } + // add aura, register in lists and arrays + m_spellAuraHolders.insert(SpellAuraHolderMap::value_type(holder->GetId(), holder)); + + for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) + if (Aura *aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i))) + AddAuraToModList(aur); + + holder->ApplyAuraModifiers(true, true); + DEBUG_LOG("Holder of spell %u now is in use", holder->GetId()); + + // if aura deleted before boosts apply ignore + // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier + if (holder->IsDeleted()) + { + DETAIL_LOG(">> Aura %u is deleted", holder->GetId()); + return false; + } + holder->HandleSpellSpecificBoosts(true); + + // Check debuff limit + //DEBUG_LOG("AddSpellAuraHolder: Adding spell %d, debuff limit affected: %d", holder->GetId(), holder->IsAffectedByDebuffLimit()); + if (holder->IsAffectedByDebuffLimit()) + { + uint32 negativeAuras = GetNegativeAurasCount(); + if (negativeAuras > sWorld.getConfig(CONFIG_UINT32_DEBUFF_LIMIT)) + { + // We may have removed the aura we just applied ... + if (RemoveAuraDueToDebuffLimit(holder)) + return false; // The holder has been deleted with 'RemoveSpellAuraHolder' + } + } + // When we call _AddSpellAuraHolder, we must have a free aura slot + holder->_AddSpellAuraHolder(); + return true; +} + +// Debuff limit +uint32 Unit::GetNegativeAurasCount() +{ + uint32 count = 0; + for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) + { + if (!i->second || !i->second->IsAffectedByDebuffLimit()) + continue; + + ++count; + } + return count; +} + +bool Unit::RemoveAuraDueToDebuffLimit(SpellAuraHolder* currentAura) +{ + SpellAuraHolderMap::const_iterator i, uselessDebuff; + uselessDebuff = m_spellAuraHolders.end(); + for (i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) + { + if (!i->second || !i->second->IsAffectedByDebuffLimit() || i->second->IsInUse()) + continue; + + if (uselessDebuff == m_spellAuraHolders.end() || uselessDebuff->second->IsMoreImportantDebuffThan(i->second)) + uselessDebuff = i; + } + + SpellAuraHolder* removeAuraHolder = currentAura; + if (uselessDebuff != m_spellAuraHolders.end()) + removeAuraHolder = uselessDebuff->second; + RemoveSpellAuraHolder(removeAuraHolder); + return currentAura == removeAuraHolder; +} + +void Unit::AddAuraToModList(Aura *aura) +{ + if (aura->GetModifier()->m_auraname < TOTAL_AURAS) + m_modAuras[aura->GetModifier()->m_auraname].push_back(aura); +} + +void Unit::RemoveRankAurasDueToSpell(uint32 spellId) +{ + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); + if (!spellInfo) + return; + SpellAuraHolderMap::const_iterator i, next; + for (i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); i = next) + { + next = i; + ++next; + uint32 i_spellId = (*i).second->GetId(); + if ((*i).second && i_spellId && i_spellId != spellId) + { + if (sSpellMgr.IsRankSpellDueToSpell(spellInfo, i_spellId)) + { + RemoveAurasDueToSpell(i_spellId); + + if (m_spellAuraHolders.empty()) + break; + else + next = m_spellAuraHolders.begin(); + } + } + } +} + +bool Unit::RemoveNoStackAurasDueToAuraHolder(SpellAuraHolder *holder) +{ + if (!holder) + return false; + + SpellEntry const* spellProto = holder->GetSpellProto(); + if (!spellProto) + return false; + + uint32 spellId = holder->GetId(); + + // passive spell special case (only non stackable with ranks) + if (spellProto->Attributes & (SPELL_ATTR_PASSIVE | 0x80)) + { + if (IsPassiveSpellStackableWithRanks(spellProto)) + return true; + } + + uint32 firstInChain = 0; + for (int eff = 0; eff < MAX_EFFECT_INDEX; ++eff) + { + if (Aura* aura = holder->GetAuraByEffectIndex(SpellEffectIndex(eff))) + { + switch (aura->GetModifier()->m_auraname) + { + case SPELL_AURA_PERIODIC_HEAL: + case SPELL_AURA_OBS_MOD_HEALTH: + { + firstInChain = sSpellMgr.GetFirstSpellInChain(holder->GetId()); + break; + } + default: + break; + } + } + + if (firstInChain) + break; + } + + SpellSpecific spellId_spec = GetSpellSpecific(spellId); + + bool isAreaAura = IsSpellHaveEffect(spellProto, SPELL_EFFECT_APPLY_AREA_AURA_PARTY); + SpellAuraHolderMap::iterator i, next; + for (i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); i = next) + { + next = i; + ++next; + if (!(*i).second) continue; + + SpellEntry const* i_spellProto = (*i).second->GetSpellProto(); + + if (!i_spellProto) + continue; + + uint32 i_spellId = i_spellProto->Id; + + // early checks that spellId is passive non stackable spell + if (i_spellProto->Attributes & (SPELL_ATTR_PASSIVE | 0x80)) + { + // passive non-stackable spells not stackable only for same caster + // -> Sauf si 2 AreaAuras + if (holder->GetCasterGuid() != i->second->GetCasterGuid() && !isAreaAura && !IsSpellHaveEffect(i_spellProto, SPELL_EFFECT_APPLY_AREA_AURA_PARTY)) + continue; + + // passive non-stackable spells not stackable only with another rank of same spell + if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) + { + if (CompareAuraRanks(spellId, i_spellId) < 0) // Le sort actuel est plus puissant. + { + DETAIL_LOG("[STACK] [%u/%u] Le sort actuel est plus puissant.", spellId, i_spellId); + // On empeche la pose de l'aura. + return false; + } + } + else + continue; + } + + if (i_spellId == spellId) + { + // Nostalrius - fix stack same HoT rank / diff caster + if (firstInChain) + RemoveAurasDueToSpell(i_spellId); + else switch (spellId) + { + // Blessing of Light does not stack between casters. + case 19977: + case 19978: + case 19979: + case 25890: + RemoveAurasDueToSpell(spellId); + break; + } + continue; + } + + SpellGroup spellGroup; + SpellGroupStackRule rule = sSpellMgr.CheckSpellGroupStackRules(i_spellId, spellId, spellGroup); + if (rule != SPELL_GROUP_STACK_RULE_DEFAULT) + { + // Attempt to add apply less powerfull spell + if (rule == SPELL_GROUP_STACK_RULE_POWERFULL_CHAIN && sSpellMgr.IsMorePowerfullSpell(i_spellId, spellId, spellGroup)) + { + DETAIL_LOG("[STACK][DB] Powerfull chain %u > %u (group %u). Aura %u will not be applied.", i_spellId, spellId, spellGroup, spellId); + return false; + } + DETAIL_LOG("[STACK][DB] Unable to stack %u and %u. %u will be removed.", spellId, i_spellId, i_spellId); + RemoveAurasDueToSpell(i_spellId); + continue; + } + + bool is_triggered_by_spell = false; + // prevent triggering aura of removing aura that triggered it + for (int j = 0; j < MAX_EFFECT_INDEX; ++j) + if (i_spellProto->EffectTriggerSpell[j] == spellId) + is_triggered_by_spell = true; + + // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell + for (int j = 0; j < MAX_EFFECT_INDEX; ++j) + if (spellProto->EffectTriggerSpell[j] == i_spellId) + is_triggered_by_spell = true; + + if (is_triggered_by_spell) + continue; + + if (IsSpellHaveAura(i_spellProto, SPELL_AURA_CHANNEL_DEATH_ITEM)) // Plusieurs demo par exemple peuvent mettre un siphon d'ame. + continue; + + SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId); + + // single allowed spell specific from same caster or from any caster at target + bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec, i_spellId_spec); + + bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec, i_spellId_spec); + + // HoTs in 1.x must be per target also + if (!is_spellSpecPerTarget && firstInChain && firstInChain == sSpellMgr.GetFirstSpellInChain(i_spellId)) + is_spellSpecPerTarget = true; + + if (is_spellSpecPerTarget || (is_spellSpecPerTargetPerCaster && holder->GetCasterGuid() == (*i).second->GetCasterGuid())) + { + // cannot remove higher rank + if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) + if (CompareAuraRanks(spellId, i_spellId) < 0) + return false; + + // Its a parent aura (create this aura in ApplyModifier) + if ((*i).second->IsInUse()) + { + sLog.outError("SpellAuraHolder (Spell %u) is in process but attempt removed at SpellAuraHolder (Spell %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAuraHolder", i->second->GetId(), holder->GetId()); + continue; + } + DETAIL_LOG("[STACK][%u/%u] SpellSpecPerTarget ou SpellSpecPerCaster", spellId, i_spellId); + RemoveAurasDueToSpell(i_spellId); + + if (m_spellAuraHolders.empty()) + break; + else + next = m_spellAuraHolders.begin(); + + continue; + } + + // spell with spell specific that allow single ranks for spell from diff caster + // same caster case processed or early or later + bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec, i_spellId_spec); + if (is_spellPerTarget && holder->GetCasterGuid() != (*i).second->GetCasterGuid() && sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId)) + { + // cannot remove higher rank + if (CompareAuraRanks(spellId, i_spellId) < 0) + { + DETAIL_LOG("[STACK] [%u/%u] Rang plus haut.", spellId, i_spellId); + return false; + } + + // Its a parent aura (create this aura in ApplyModifier) + if ((*i).second->IsInUse()) + { + sLog.outError("SpellAuraHolder (Spell %u) is in process but attempt removed at SpellAuraHolder (Spell %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAuraHolder", i->second->GetId(), holder->GetId()); + continue; + } + DETAIL_LOG("[STACK][%u/%u] SpellPerTarget", spellId, i_spellId); + RemoveAurasDueToSpell(i_spellId); + + if (m_spellAuraHolders.empty()) + break; + else + next = m_spellAuraHolders.begin(); + + continue; + } + + // non single (per caster) per target spell specific (possible single spell per target at caster) + if (!is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && sSpellMgr.IsNoStackSpellDueToSpell(spellId, i_spellId)) + { + // Its a parent aura (create this aura in ApplyModifier) + if ((*i).second->IsInUse()) + { + sLog.outError("SpellAuraHolder (Spell %u) is in process but attempt removed at SpellAuraHolder (Spell %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAuraHolder", i->second->GetId(), holder->GetId()); + continue; + } + DETAIL_LOG("[STACK][%u/%u] NoStackSpellDueToSpell", spellId, i_spellId); + RemoveAurasDueToSpell(i_spellId); + + if (m_spellAuraHolders.empty()) + break; + else + next = m_spellAuraHolders.begin(); + + continue; + } + } + // Sorts moins puissants : + std::list lessPowerfullSpells; + if (sSpellMgr.ListLessPowerfullSpells(spellId, lessPowerfullSpells)) + for (std::list::const_iterator it = lessPowerfullSpells.begin(); it != lessPowerfullSpells.end(); ++it) + RemoveAurasDueToSpell(*it); + return true; +} + +void Unit::RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except) +{ + SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) + { + Aura *aur = iter->second->m_auras[effindex]; + if (aur && aur != except) + { + RemoveSingleAuraFromSpellAuraHolder(iter->second, effindex); + // may remove holder + spair = GetSpellAuraHolderBounds(spellId); + iter = spair.first; + } + else + ++iter; + } +} +void Unit::RemoveAurasByCasterSpell(uint32 spellId, ObjectGuid casterGuid) +{ + SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) + { + if (iter->second->GetCasterGuid() == casterGuid) + { + RemoveSpellAuraHolder(iter->second); + spair = GetSpellAuraHolderBounds(spellId); + iter = spair.first; + } + else + ++iter; + } +} + +void Unit::RemoveSingleAuraFromSpellAuraHolder(uint32 spellId, SpellEffectIndex effindex, ObjectGuid casterGuid, AuraRemoveMode mode) +{ + SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) + { + Aura *aur = iter->second->m_auras[effindex]; + if (aur && aur->GetCasterGuid() == casterGuid) + { + RemoveSingleAuraFromSpellAuraHolder(iter->second, effindex, mode); + spair = GetSpellAuraHolderBounds(spellId); + iter = spair.first; + } + else + ++iter; + } +} + +void Unit::RemoveAuraHolderDueToSpellByDispel(uint32 spellId, uint32 stackAmount, ObjectGuid casterGuid, Unit *dispeller) +{ + RemoveAuraHolderFromStack(spellId, stackAmount, casterGuid, AURA_REMOVE_BY_DISPEL); +} + +void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGuid, Unit *stealer) +{ + SpellAuraHolder *holder = GetSpellAuraHolder(spellId, casterGuid); + SpellEntry const* spellProto = sSpellMgr.GetSpellEntry(spellId); + SpellAuraHolder *new_holder = CreateSpellAuraHolder(spellProto, stealer, this); + + // set its duration and maximum duration + // max duration 2 minutes (in msecs) + int32 dur = holder->GetAuraDuration(); + int32 max_dur = 2 * MINUTE * IN_MILLISECONDS; + int32 new_max_dur = max_dur > dur ? dur : max_dur; + new_holder->SetAuraMaxDuration(new_max_dur); + new_holder->SetAuraDuration(new_max_dur); + + for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) + { + Aura *aur = holder->GetAuraByEffectIndex(SpellEffectIndex(i)); + + if (!aur) + continue; + + int32 basePoints = aur->GetBasePoints(); + // construct the new aura for the attacker - will never return NULL, it's just a wrapper for + // some different constructors + Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, new_holder, stealer, this); + + // set periodic to do at least one tick (for case when original aura has been at last tick preparing) + int32 periodic = aur->GetModifier()->periodictime; + new_aur->GetModifier()->periodictime = periodic < new_max_dur ? periodic : new_max_dur; + + // add the new aura to stealer + new_holder->AddAura(new_aur, new_aur->GetEffIndex()); + } + + if (holder->ModStackAmount(-1)) + // Remove aura as dispel + RemoveSpellAuraHolder(holder, AURA_REMOVE_BY_DISPEL); + + // strange but intended behaviour: Stolen single target auras won't be treated as single targeted + new_holder->SetIsSingleTarget(false); + + stealer->AddSpellAuraHolder(new_holder); +} + +void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId) +{ + SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second;) + { + RemoveSpellAuraHolder(iter->second, AURA_REMOVE_BY_CANCEL); + spair = GetSpellAuraHolderBounds(spellId); + iter = spair.first; + } +} + +void Unit::RemoveAurasWithDispelType(DispelType type, ObjectGuid casterGuid) +{ + // Create dispel mask by dispel type + uint32 dispelMask = GetDispellMask(type); + // Dispel all existing auras vs current dispel type + SpellAuraHolderMap& auras = GetSpellAuraHolderMap(); + for (SpellAuraHolderMap::iterator itr = auras.begin(); itr != auras.end();) + { + SpellEntry const* spell = itr->second->GetSpellProto(); + if (((1 << spell->Dispel) & dispelMask) && (!casterGuid || casterGuid == itr->second->GetCasterGuid())) + { + // Dispel aura + RemoveAurasDueToSpell(spell->Id); + itr = auras.begin(); + } + else + ++itr; + } +} + +void Unit::RemoveAuraHolderFromStack(uint32 spellId, uint32 stackAmount, ObjectGuid casterGuid, AuraRemoveMode mode) +{ + SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = spair.first; iter != spair.second; ++iter) + { + if (!casterGuid || iter->second->GetCasterGuid() == casterGuid) + { + if (iter->second->ModStackAmount(-int32(stackAmount))) + { + RemoveSpellAuraHolder(iter->second, mode); + break; + } + } + } +} + +void Unit::RemoveSingleAuraDueToItemSet(uint32 spellId, AuraRemoveMode mode) +{ + SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second;) + { + if (!iter->second->GetCastItemGuid()) + { + RemoveSpellAuraHolder(iter->second, mode); + return; + } + else + ++iter; + } +} + +void Unit::RemoveAurasDueToSpell(uint32 spellId, SpellAuraHolder* except, AuraRemoveMode mode) +{ + SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second;) + { + if (iter->second != except) + { + RemoveSpellAuraHolder(iter->second, mode); + bounds = GetSpellAuraHolderBounds(spellId); + iter = bounds.first; + } + else + ++iter; + } +} + +void Unit::RemoveAurasDueToItemSpell(Item* castItem, uint32 spellId) +{ + SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second;) + { + if (iter->second->GetCastItemGuid() == castItem->GetObjectGuid()) + { + RemoveSpellAuraHolder(iter->second); + bounds = GetSpellAuraHolderBounds(spellId); + iter = bounds.first; + } + else + ++iter; + } +} + +void Unit::RemoveAurasWithInterruptFlags(uint32 flags, uint32 except) +{ + for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) + { + if (iter->second->GetSpellProto()->AuraInterruptFlags & flags && iter->second->GetSpellProto()->Id != except) + { + RemoveSpellAuraHolder(iter->second); + iter = m_spellAuraHolders.begin(); + } + else + ++iter; + } +} + +void Unit::RemoveAurasWithAttribute(uint32 flags) +{ + for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) + { + if (iter->second->GetSpellProto()->Attributes & flags) + { + RemoveSpellAuraHolder(iter->second); + iter = m_spellAuraHolders.begin(); + } + else + ++iter; + } +} + +void Unit::RemoveNotOwnSingleTargetAuras() +{ + // single target auras from other casters + for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) + { + if (iter->second->GetCasterGuid() != GetObjectGuid() && iter->second->IsSingleTarget()) + { + RemoveSpellAuraHolder(iter->second); + iter = m_spellAuraHolders.begin(); + continue; + } + + ++iter; + } + + // single target auras at other targets + SingleCastSpellTargetMap& scTargets = GetSingleCastSpellTargets(); + for (SingleCastSpellTargetMap::iterator itr = scTargets.begin(); itr != scTargets.end();) + { + SpellEntry const* itr_spellEntry = itr->first; + ObjectGuid itr_targetGuid = itr->second; + + if (itr_targetGuid != GetObjectGuid()) + { + scTargets.erase(itr); // remove for caster in any case + + // remove from target if target found + if (Unit* itr_target = GetMap()->GetUnit(itr_targetGuid)) + itr_target->RemoveAurasByCasterSpell(itr_spellEntry->Id, GetObjectGuid()); + + itr = scTargets.begin(); // list can be changed at remove aura + continue; + } + + ++itr; + } + +} + +void Unit::RemoveSpellAuraHolder(SpellAuraHolder *holder, AuraRemoveMode mode) +{ + // Statue unsummoned at holder remove + SpellEntry const* AurSpellInfo = holder->GetSpellProto(); + Totem* statue = nullptr; + Unit* caster = holder->GetCaster(); + if (IsChanneledSpell(AurSpellInfo) && caster) + if (caster->GetTypeId() == TYPEID_UNIT && ((Creature*)caster)->IsTotem() && ((Totem*)caster)->GetTotemType() == TOTEM_STATUE) + statue = ((Totem*)caster); + + if (m_spellAuraHoldersUpdateIterator != m_spellAuraHolders.end() && m_spellAuraHoldersUpdateIterator->second == holder) + ++m_spellAuraHoldersUpdateIterator; + + SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(holder->GetId()); + bool foundInMap = false; + for (SpellAuraHolderMap::iterator itr = bounds.first; itr != bounds.second; ++itr) + { + if (itr->second == holder) + { + m_spellAuraHolders.erase(itr); + foundInMap = true; + break; + } + } + if (!foundInMap) + sLog.outInfo("[Crash/Auras] Removing aura holder *not* in holders map ! Aura %u on %s", holder->GetId(), GetName()); + holder->SetRemoveMode(mode); + holder->UnregisterSingleCastHolder(); + + for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) + { + if (Aura *aura = holder->m_auras[i]) + RemoveAura(aura, mode); + } + + holder->_RemoveSpellAuraHolder(); + + if (mode != AURA_REMOVE_BY_DELETE) + holder->HandleSpellSpecificBoosts(false); + + if (statue) + statue->UnSummon(); + + uint32 auraSpellId = holder->GetId(); + // If holder in use (removed from code that plan access to it data after return) + // store it in holder list with delayed deletion + if (holder->IsInUse()) + { + holder->SetDeleted(); + m_deletedHolders.push_back(holder); + } + else + delete holder; + + uint32 uiTriggeredSpell = 0; + + // Spell that trigger another spell on dispell + if (mode == AURA_REMOVE_BY_DISPEL) + { + switch (auraSpellId) + { + case 26180: // Wyvern Sting (AQ40, Princess Huhuran) + uiTriggeredSpell = 26233; + break; + default: + break; + } + } + + if (IsChanneledSpell(AurSpellInfo) && caster && (mode != AURA_REMOVE_BY_EXPIRE || caster->IsControlledByPlayer())) + { + Spell *channeled = caster->GetCurrentSpell(CURRENT_CHANNELED_SPELL); + if (channeled && channeled->m_spellInfo->Id == auraSpellId && channeled->m_targets.getUnitTarget() == this) + caster->InterruptSpell(CURRENT_CHANNELED_SPELL); + } + + if (uiTriggeredSpell) + { + if (caster) + caster->CastSpell(this, uiTriggeredSpell, true); + else + CastSpell(this, uiTriggeredSpell, true); + } +} + +void Unit::RemoveSingleAuraFromSpellAuraHolder(SpellAuraHolder *holder, SpellEffectIndex index, AuraRemoveMode mode) +{ + Aura *aura = holder->GetAuraByEffectIndex(index); + if (!aura) + return; + + if (aura->IsLastAuraOnHolder()) + RemoveSpellAuraHolder(holder, mode); + else + RemoveAura(aura, mode); +} + +void Unit::RemoveAura(Aura *Aur, AuraRemoveMode mode) +{ + // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order) + if (Aur->GetModifier()->m_auraname < TOTAL_AURAS) + m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur); + + // Set remove mode + Aur->SetRemoveMode(mode); + + // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura + // remove aura from list before to prevent deleting it before + ///m_Auras.erase(i); + + DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura %u [spell%u] now is remove mode %d. Caster %s", Aur->GetModifier()->m_auraname, Aur->GetSpellProto()->Id, mode, GetName()); + + // aura _MUST_ be remove from holder before unapply. + // un-apply code expected that aura not find by diff searches + // in another case it can be double removed for example, if target die/etc in un-apply process. + Aur->GetHolder()->RemoveAura(Aur->GetEffIndex()); + + // some auras also need to apply modifier (on caster) on remove + if (mode == AURA_REMOVE_BY_DELETE) + { + switch (Aur->GetModifier()->m_auraname) + { + // need properly undo any auras with player-caster mover set (or will crash at next caster move packet) + case SPELL_AURA_MOD_POSSESS: + case SPELL_AURA_MOD_POSSESS_PET: + Aur->ApplyModifier(false, true); + break; + default: + break; + } + } + else + Aur->ApplyModifier(false, true); + + // If aura in use (removed from code that plan access to it data after return) + // store it in aura list with delayed deletion + if (Aur->IsInUse()) + m_deletedAuras.push_back(Aur); + else + delete Aur; +} + +void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) +{ + while (!m_spellAuraHolders.empty()) + { + SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); + RemoveSpellAuraHolder(iter->second, mode); + } +} + +void Unit::RemoveAllNegativeAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) +{ + for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) + { + if (!iter->second->IsPositive()) + { + RemoveSpellAuraHolder(iter->second, mode); + iter = m_spellAuraHolders.begin(); + } + else + ++iter; + } +} + +void Unit::RemoveAurasAtReset(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/) +{ + // @TODO: Some buffs should maybe not get removed ? Self casted buffs ? ... + if (Creature* c = ToCreature()) + if (CreatureInfo const* info = c->GetCreatureInfo()) + if (info->flags_extra & CREATURE_FLAG_EXTRA_KEEP_POSITIVE_AURAS_ON_EVADE) + { + RemoveAllNegativeAuras(mode); + return; + } + RemoveAllAuras(mode); +} + +void Unit::RemoveAllAurasOnDeath() +{ + // used just after dieing to remove all visible auras + // and disable the mods for the passive ones + for (SpellAuraHolderMap::iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end();) + { + if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent()) + { + RemoveSpellAuraHolder(iter->second, AURA_REMOVE_BY_DEATH); + iter = m_spellAuraHolders.begin(); + } + else + ++iter; + } +} + +void Unit::DelaySpellAuraHolder(uint32 spellId, int32 delaytime, ObjectGuid casterGuid) +{ + SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::iterator iter = bounds.first; iter != bounds.second; ++iter) + { + SpellAuraHolder* holder = iter->second; + + if (casterGuid != holder->GetCasterGuid()) + continue; + + if (holder->GetAuraDuration() < delaytime) + holder->SetAuraDuration(0); + else + holder->SetAuraDuration(holder->GetAuraDuration() - delaytime); + + holder->UpdateAuraDuration(); + + DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Spell %u partially interrupted on %s, new duration: %u ms", spellId, GetObjectGuid().GetString().c_str(), holder->GetAuraDuration()); + } +} + +void Unit::_RemoveAllAuraMods() +{ + for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) + (*i).second->ApplyAuraModifiers(false); +} + +void Unit::_ApplyAllAuraMods() +{ + for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) + (*i).second->ApplyAuraModifiers(true); +} + +bool Unit::HasAuraType(AuraType auraType) const +{ + return !GetAurasByType(auraType).empty(); +} + +bool Unit::HasAffectedAura(AuraType auraType, SpellEntry const* spellProto) const +{ + Unit::AuraList const& auras = GetAurasByType(auraType); + + for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) + { + if ((*itr)->isAffectedOnSpell(spellProto)) + return true; + } + + return false; +} + +Aura* Unit::GetAura(uint32 spellId, SpellEffectIndex effindex) +{ + SpellAuraHolderBounds bounds = GetSpellAuraHolderBounds(spellId); + if (bounds.first != bounds.second) + return bounds.first->second->GetAuraByEffectIndex(effindex); + return nullptr; +} + +Aura* Unit::GetAura(AuraType type, SpellFamily family, uint64 familyFlag, ObjectGuid casterGuid) +{ + AuraList const& auras = GetAurasByType(type); + for (AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i) + if ((*i)->GetSpellProto()->IsFitToFamily(family, familyFlag) && + (!casterGuid || (*i)->GetCasterGuid() == casterGuid)) + return *i; + + return nullptr; +} + +bool Unit::HasAura(uint32 spellId, SpellEffectIndex effIndex) const +{ + SpellAuraHolderConstBounds spair = GetSpellAuraHolderBounds(spellId); + for (SpellAuraHolderMap::const_iterator i_holder = spair.first; i_holder != spair.second; ++i_holder) + if (i_holder->second->GetAuraByEffectIndex(effIndex)) + return true; + + return false; +} + +void Unit::AddDynObject(DynamicObject* dynObj) +{ + m_dynObjGUIDs.push_back(dynObj->GetObjectGuid()); + dynObj->SetWorldMask(GetWorldMask()); // Nostalrius : phasing +} + +void Unit::RemoveDynObject(uint32 spellid) +{ + if (m_dynObjGUIDs.empty()) + return; + for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();) + { + DynamicObject* dynObj = GetMap()->GetDynamicObject(*i); + if (!dynObj) + i = m_dynObjGUIDs.erase(i); + else if (spellid == 0 || dynObj->GetSpellId() == spellid) + { + dynObj->Delete(); + i = m_dynObjGUIDs.erase(i); + } + else + ++i; + } +} + +void Unit::RemoveAllDynObjects() +{ + while (!m_dynObjGUIDs.empty()) + { + if (DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin())) + dynObj->Delete(); + m_dynObjGUIDs.erase(m_dynObjGUIDs.begin()); + } +} + +DynamicObject * Unit::GetDynObject(uint32 spellId, SpellEffectIndex effIndex) +{ + for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();) + { + DynamicObject* dynObj = GetMap()->GetDynamicObject(*i); + if (!dynObj) + { + i = m_dynObjGUIDs.erase(i); + continue; + } + + if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex) + return dynObj; + ++i; + } + return nullptr; +} + +DynamicObject * Unit::GetDynObject(uint32 spellId) +{ + for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();) + { + DynamicObject* dynObj = GetMap()->GetDynamicObject(*i); + if (!dynObj) + { + i = m_dynObjGUIDs.erase(i); + continue; + } + + if (dynObj->GetSpellId() == spellId) + return dynObj; + ++i; + } + return nullptr; +} + +GameObject* Unit::GetGameObject(uint32 spellId) const +{ + for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i) + if ((*i)->GetSpellId() == spellId) + return *i; + + return nullptr; +} + +void Unit::AddGameObject(GameObject* gameObj) +{ + MANGOS_ASSERT(gameObj && !gameObj->GetOwnerGuid()); + m_gameObj.push_back(gameObj); + gameObj->SetOwnerGuid(GetObjectGuid()); + gameObj->SetWorldMask(GetWorldMask()); + + if (GetTypeId() == TYPEID_PLAYER && gameObj->GetSpellId()) + { + SpellEntry const* createBySpell = sSpellMgr.GetSpellEntry(gameObj->GetSpellId()); + // Need disable spell use for owner + if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) + // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases) + ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell, 0, nullptr, true); + } +} + +void Unit::RemoveGameObject(GameObject* gameObj, bool del) +{ + MANGOS_ASSERT(gameObj && gameObj->GetOwnerGuid() == GetObjectGuid()); + + gameObj->SetOwnerGuid(ObjectGuid()); + + // GO created by some spell + if (uint32 spellid = gameObj->GetSpellId()) + { + RemoveAurasDueToSpell(spellid); + + SpellEntry const* createBySpell = sSpellMgr.GetSpellEntry(spellid); + // Need activate spell use for owner + if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) + // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existing cases) + CooldownEvent(createBySpell); + } + + m_gameObj.remove(gameObj); + + if (del) + { + gameObj->SetRespawnTime(0); + gameObj->Delete(); + } +} + +void Unit::RemoveGameObject(uint32 spellid, bool del) +{ + if (m_gameObj.empty()) + return; + GameObjectList::iterator i, next; + for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next) + { + next = i; + if (spellid == 0 || (*i)->GetSpellId() == spellid) + { + (*i)->SetOwnerGuid(ObjectGuid()); + if (del) + { + (*i)->SetRespawnTime(0); + (*i)->Delete(); + } + + next = m_gameObj.erase(i); + } + else + ++next; + } +} + +void Unit::RemoveAllGameObjects() +{ + // remove references to unit + for (GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();) + { + (*i)->SetOwnerGuid(ObjectGuid()); + (*i)->SetRespawnTime(0); + (*i)->Delete(); + i = m_gameObj.erase(i); + } +} + +void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log) +{ + WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16 + 4 + 4 + 1 + 4 + 4 + 1 + 1 + 4 + 4 + 1)); // we guess size + data << log->target->GetPackGUID(); + data << log->attacker->GetPackGUID(); + data << uint32(log->SpellID); + data << uint32(log->damage); // damage amount + data << uint8(log->school); // damage school + data << uint32(log->absorb); // AbsorbedDamage + data << uint32(log->resist); // resist + data << uint8(log->physicalLog); // if 1, then client show spell name (example: %s's ranged shot hit %s for %u school or %s suffers %u school damage from %s's spell_name + data << uint8(log->unused); // unused + data << uint32(log->blocked); // blocked + data << uint32(log->HitInfo); + data << uint8(0); // flag to use extend data + SendMessageToSet(&data, true); +} + +void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit) +{ + SpellNonMeleeDamage log(this, target, SpellID, GetFirstSchoolInMask(damageSchoolMask)); + log.damage = Damage - AbsorbedDamage - Resist - Blocked; + log.absorb = AbsorbedDamage; + log.resist = Resist; + log.physicalLog = PhysicalDamage; + log.blocked = Blocked; + log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6; + if (CriticalHit) + log.HitInfo |= SPELL_HIT_TYPE_CRIT; + SendSpellNonMeleeDamageLog(&log); +} + +void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo, AuraType auraTypeOverride) +{ + Aura *aura = pInfo->aura; + Modifier *mod = aura->GetModifier(); + AuraType auraType = auraTypeOverride ? auraTypeOverride : mod->m_auraname; + + WorldPacket data(SMSG_PERIODICAURALOG, 30); + data << aura->GetTarget()->GetPackGUID(); + data << aura->GetCasterGuid().WriteAsPacked(); + data << uint32(aura->GetId()); // spellId + data << uint32(1); // count + data << uint32(auraType); // auraId + switch (auraType) + { + case SPELL_AURA_PERIODIC_DAMAGE: + case SPELL_AURA_PERIODIC_DAMAGE_PERCENT: + data << uint32(pInfo->damage); // damage + data << uint32(aura->GetSpellProto()->School); + data << uint32(pInfo->absorb); // absorb + data << uint32(pInfo->resist); // resist + break; + case SPELL_AURA_PERIODIC_HEAL: + case SPELL_AURA_OBS_MOD_HEALTH: + data << uint32(pInfo->damage); // damage + break; + case SPELL_AURA_OBS_MOD_MANA: + case SPELL_AURA_PERIODIC_ENERGIZE: + data << uint32(mod->m_miscvalue); // power type + data << uint32(pInfo->damage); // damage + break; + case SPELL_AURA_PERIODIC_MANA_LEECH: + data << uint32(mod->m_miscvalue); // power type + data << uint32(pInfo->damage); // amount + data << float(pInfo->multiplier); // gain multiplier + break; + default: + sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(auraType)); + return; + } + + aura->GetTarget()->SendObjectMessageToSet(&data, true); +} + +class RemovedSpellData +{ +public: + RemovedSpellData(uint32 spell, Unit* target) : spellId(spell), unit(target) + { + } + bool operator <(const RemovedSpellData& b) const + { + return spellId < b.spellId; + } + bool operator==(const RemovedSpellData& b) const + { + return spellId == b.spellId && unit == b.unit; + } + uint32 spellId; + Unit* unit; +}; + +typedef std::list RemoveSpellList; + +void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell, Spell* spell) +{ + if (!IsInWorld()) + return; + + ProcTriggeredList procTriggered; + + // Not much to do if no flags are set. + if (procAttacker) + ProcDamageAndSpellFor(false, pVictim, procAttacker, procExtra, attType, procSpell, amount, procTriggered, spell); + + // Now go on with a victim's events'n'auras + // Not much to do if no flags are set or there is no victim + if (pVictim && pVictim->isAlive() && procVictim) + pVictim->ProcDamageAndSpellFor(true, this, procVictim, procExtra, attType, procSpell, amount, procTriggered, spell); + + HandleTriggers(pVictim, procExtra, amount, procSpell, procTriggered); +} + +void Unit::HandleTriggers(Unit *pVictim, uint32 procExtra, uint32 amount, SpellEntry const *procSpell, ProcTriggeredList const& procTriggered) +{ + RemoveSpellList removedSpells; + // Nothing found + if (procTriggered.empty()) + return; + + // Handle effects proceed this time + for (ProcTriggeredList::const_iterator itr = procTriggered.begin(); itr != procTriggered.end(); ++itr) + { + // Some auras can be deleted in function called in this loop (except first, ofc) + SpellAuraHolder *triggeredByHolder = itr->triggeredByHolder; + if (triggeredByHolder->IsDeleted()) + { + triggeredByHolder->SetInUse(false); + continue; + } + + SpellProcEventEntry const *spellProcEvent = itr->spellProcEvent; + bool useCharges = triggeredByHolder->GetAuraCharges() > 0; + bool procSuccess = true; + bool anyAuraProc = false; + Unit* caster = itr->target == this ? pVictim : this; + + if (!caster || !caster->IsInWorld()) + { + triggeredByHolder->SetInUse(false); + continue; + } + + // For players set spell cooldown if need + uint32 cooldown = 0; + if (triggeredByHolder->GetTarget()->GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown) + cooldown = spellProcEvent->cooldown; + + for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i) + { + Aura *triggeredByAura = triggeredByHolder->GetAuraByEffectIndex(SpellEffectIndex(i)); + if (!triggeredByAura) + continue; + + Modifier *auraModifier = triggeredByAura->GetModifier(); + + if (procSpell) + { + if (spellProcEvent) + { + if (spellProcEvent->spellFamilyMask[i]) + { + if (!procSpell->IsFitToFamilyMask(spellProcEvent->spellFamilyMask[i])) + continue; + } + // don't check dbc FamilyFlags if schoolMask exists + else if (!triggeredByAura->CanProcFrom(procSpell, spellProcEvent->procEx, procExtra, amount != 0, !spellProcEvent->schoolMask)) + continue; + } + else if (!triggeredByAura->CanProcFrom(procSpell, PROC_EX_NONE, procExtra, amount != 0, true)) + continue; + } + + SpellAuraProcResult procResult = (*caster.*AuraProcHandler[auraModifier->m_auraname])(itr->target, amount, triggeredByAura, procSpell, itr->procFlag, procExtra, cooldown); + switch (procResult) + { + case SPELL_AURA_PROC_CANT_TRIGGER: + continue; + case SPELL_AURA_PROC_FAILED: + procSuccess = false; + break; + case SPELL_AURA_PROC_OK: + break; + } + + anyAuraProc = true; + } + // Remove charge (aura can be removed by triggers) + if (useCharges && procSuccess && anyAuraProc && !triggeredByHolder->IsDeleted()) + { + // If last charge dropped add spell to remove list + if (triggeredByHolder->DropAuraCharge()) + removedSpells.push_back(RemovedSpellData(triggeredByHolder->GetId(), caster)); + } + + triggeredByHolder->SetInUse(false); + } + + if (!removedSpells.empty()) + { + // Sort spells and remove duplicates + removedSpells.sort(); + removedSpells.unique(); + // Remove auras from removedAuras + for (RemoveSpellList::iterator i = removedSpells.begin(); i != removedSpells.end(); ++i) + i->unit->RemoveAurasDueToSpell(i->spellId); + } +} + +void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo) +{ + WorldPacket data(SMSG_SPELLLOGMISS, (4 + 8 + 1 + 4 + 8 + 1)); + data << uint32(spellID); + data << GetObjectGuid(); + data << uint8(0); // unk8 + data << uint32(1); // target count + // for(i = 0; i < target count; ++i) + data << target->GetObjectGuid(); // target GUID + data << uint8(missInfo); + // Nostalrius: + 2 * float if unk8=1 + // end loop + SendObjectMessageToSet(&data, true); +} + +void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo) +{ + DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Sending SMSG_ATTACKERSTATEUPDATE"); + + WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16 + 45)); // we guess size + + data << uint32(damageInfo->HitInfo); + data << GetPackGUID(); + data << damageInfo->target->GetPackGUID(); + data << uint32(damageInfo->totalDamage); // Total damage + + data << uint8(m_weaponDamageCount[damageInfo->attackType]); // Sub damage count + + // Sub damage description + for (uint8 i = 0; i < m_weaponDamageCount[damageInfo->attackType]; i++) + { + SubDamageInfo *subDamage = &damageInfo->subDamage[i]; + + data << uint32(GetFirstSchoolInMask(subDamage->damageSchoolMask)); + data << float(subDamage->damage)/ float(damageInfo->totalDamage); // Float coefficient of sub damage + data << uint32(subDamage->damage); + data << uint32(subDamage->absorb); + data << uint32(subDamage->resist); + } + data << uint32(damageInfo->TargetState); + data << uint32(0); + data << uint32(0); // spell id, seen with heroic strike and disarm as examples. + // HITINFO_NOACTION normally set if spell + data << uint32(damageInfo->blocked_amount); + + SendMessageToSet(&data, true); +} + +void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount) +{ + CalcDamageInfo dmgInfo; + dmgInfo.HitInfo = HitInfo; + dmgInfo.attacker = this; + dmgInfo.target = target; + dmgInfo.attackType = BASE_ATTACK; + dmgInfo.totalDamage = Damage - AbsorbDamage - Resist - BlockedAmount; + dmgInfo.totalAbsorb = AbsorbDamage; + dmgInfo.totalResist = Resist; + dmgInfo.subDamage[0].damage = dmgInfo.totalDamage; + dmgInfo.subDamage[0].damageSchoolMask = damageSchoolMask; + dmgInfo.subDamage[0].absorb = AbsorbDamage; + dmgInfo.subDamage[0].resist = Resist; + dmgInfo.TargetState = TargetState; + dmgInfo.blocked_amount = BlockedAmount; + SendAttackStateUpdate(&dmgInfo); +} + +void Unit::SetInitCreaturePowerType() +{ + if (GetTypeId() == TYPEID_PLAYER) + return; + + auto pCreature = static_cast(this); + auto pPet = pCreature->ToPet(); + + if (pPet && pPet->getPetType() == HUNTER_PET) + return; + + // a bit wrong, but have to follow the dirty database values + if (pCreature->GetCreatureInfo()->minmana > 0) + SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_MANA); + else + { + switch (getClass()) + { + case CLASS_ROGUE: + SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_ENERGY); + SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY)); + SetPower(POWER_ENERGY, 0); + break; + default: + SetByteValue(UNIT_FIELD_BYTES_0, 3, POWER_RAGE); + SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE)); + SetPower(POWER_RAGE, 0); + break; + } + } +} + +void Unit::setPowerType(Powers new_powertype) +{ + SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype); + + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE); + } + } + + switch (new_powertype) + { + default: + case POWER_MANA: + break; + case POWER_RAGE: + SetMaxPower(POWER_RAGE, GetCreatePowers(POWER_RAGE)); + SetPower(POWER_RAGE, 0); + break; + case POWER_FOCUS: + SetMaxPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS)); + SetPower(POWER_FOCUS, GetCreatePowers(POWER_FOCUS)); + break; + case POWER_ENERGY: + SetMaxPower(POWER_ENERGY, GetCreatePowers(POWER_ENERGY)); + SetPower(POWER_ENERGY, 0); + break; + case POWER_HAPPINESS: + SetMaxPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); + SetPower(POWER_HAPPINESS, GetCreatePowers(POWER_HAPPINESS)); + break; + } +} + +FactionTemplateEntry const* Unit::getFactionTemplateEntry() const +{ + FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction()); + if (!entry) + { + static ObjectGuid guid; // prevent repeating spam same faction problem + + if (GetObjectGuid() != guid) + { + sLog.outError("%s have invalid faction (faction template id) #%u", GetGuidStr().c_str(), getFaction()); + guid = GetObjectGuid(); + } + } + return entry; +} + +// function based on function Unit::UnitReaction from 13850 client +ReputationRank Unit::GetReactionTo(Unit const* target) const +{ + // always friendly to self + if (this == target) + return REP_FRIENDLY; + + // always friendly to charmer or owner + if (GetCharmerOrOwnerOrSelf() == target->GetCharmerOrOwnerOrSelf()) + return REP_FRIENDLY; + + Player const* selfPlayerOwner = GetAffectingPlayer(); + Player const* targetPlayerOwner = target->GetAffectingPlayer(); + + // check forced reputation to support SPELL_AURA_FORCE_REACTION + if (selfPlayerOwner) + { + if (selfPlayerOwner->isGameMaster()) + return REP_NEUTRAL; + if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) + if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) + return *repRank; + } + else if (targetPlayerOwner) + { + if (targetPlayerOwner->isGameMaster()) + return REP_NEUTRAL; + if (FactionTemplateEntry const* selfFactionTemplateEntry = getFactionTemplateEntry()) + if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(selfFactionTemplateEntry)) + return *repRank; + } + + // Interaction between pvp flagged units + if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && + target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) + { + if (selfPlayerOwner && targetPlayerOwner) + { + // always friendly to other unit controlled by player, or to the player himself + if (selfPlayerOwner == targetPlayerOwner) + return REP_FRIENDLY; + + // duel - always hostile to opponent + if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0 && !selfPlayerOwner->duel->finished) + return REP_HOSTILE; + + // same group - checks dependant only on our faction - skip FFA_PVP for example + if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner)) + return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work + // however client seems to allow mixed group parties, because in 13850 client it works like: + // return GetFactionReactionTo(getFactionTemplateEntry(), target); + + // Sanctuary + if (selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY) && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY)) + return REP_FRIENDLY; + + // Nostalrius: Hackfix because UNIT_BYTE2_FLAG_FFA_PVP is not implemented yet. + if (selfPlayerOwner->IsFFAPvP() && targetPlayerOwner->IsFFAPvP()) + return REP_HOSTILE; + } + + // check FFA_PVP - not implemented that way on MaNGOS :/ + /* + if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP + && target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) + return REP_HOSTILE; + */ + + if (selfPlayerOwner) + { + if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) + { + if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) + return *repRank; + if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) + { + if (targetFactionEntry->CanHaveReputation()) + { + // check contested flags + if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD + && selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) + return REP_HOSTILE; + + // if faction has reputation, hostile state depends only from AtWar state + if (FactionState const* factionState = selfPlayerOwner->GetReputationMgr().GetState(targetFactionEntry)) + if (factionState->Flags & FACTION_FLAG_AT_WAR) + return REP_HOSTILE; + return REP_FRIENDLY; + } + } + } + } + } + + // Player reaction against Neutral faction Creature + if (selfPlayerOwner && !targetPlayerOwner) + { + if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) + { + if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) + { + if(targetFactionEntry->CanHaveReputation()) + { + return selfPlayerOwner->GetReputationMgr().GetRank(targetFactionEntry); + } + } + } + } + + // do checks dependant only on our faction + return GetFactionReactionTo(getFactionTemplateEntry(), target); +} + +ReputationRank Unit::GetFactionReactionTo(FactionTemplateEntry const* factionTemplateEntry, Unit const* target) +{ + // always neutral when no template entry found + if (!factionTemplateEntry) + return REP_NEUTRAL; + + FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry(); + if (!targetFactionTemplateEntry) + return REP_NEUTRAL; + + if (Player const* targetPlayerOwner = target->GetAffectingPlayer()) + { + // check contested flags + if (factionTemplateEntry->IsContestedGuardFaction() + && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) + return REP_HOSTILE; + if (ReputationRank const* repRank = targetPlayerOwner->GetReputationMgr().GetForcedRankIfAny(factionTemplateEntry)) + return *repRank; + if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction)) + { + if (factionEntry->CanHaveReputation()) + { + // CvP case - check reputation, don't allow state higher than neutral when at war + ReputationRank repRank = targetPlayerOwner->GetReputationMgr().GetRank(factionEntry); + if (FactionState const* factionState = targetPlayerOwner->GetReputationMgr().GetState(factionEntry)) + if (factionState->Flags & FACTION_FLAG_AT_WAR) + repRank = std::min(REP_NEUTRAL, repRank); + return repRank; + } + } + } + + // common faction based check + if (factionTemplateEntry->IsHostileTo(*targetFactionTemplateEntry)) + return REP_HOSTILE; + if (factionTemplateEntry->IsFriendlyTo(*targetFactionTemplateEntry)) + return REP_FRIENDLY; + if (targetFactionTemplateEntry->IsFriendlyTo(*factionTemplateEntry)) + return REP_FRIENDLY; + if (factionTemplateEntry->factionFlags & FACTION_TEMPLATE_HOSTILE_BY_DEFAULT) + return REP_HOSTILE; + // neutral by default + return REP_NEUTRAL; +} + +bool Unit::IsHostileTo(Unit const* unit) const +{ + return GetReactionTo(unit) <= REP_HOSTILE; +} + +bool Unit::IsFriendlyTo(Unit const* unit) const +{ + return GetReactionTo(unit) >= REP_FRIENDLY; +} + +bool Unit::IsHostileToPlayers() const +{ + FactionTemplateEntry const* my_faction = getFactionTemplateEntry(); + if (!my_faction || !my_faction->faction) + return false; + + FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction); + if (raw_faction && raw_faction->reputationListID >= 0) + return false; + + return my_faction->IsHostileToPlayers(); +} + +bool Unit::IsNeutralToAll() const +{ + FactionTemplateEntry const* my_faction = getFactionTemplateEntry(); + if (!my_faction || !my_faction->faction) + return true; + + FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction); + if (raw_faction && raw_faction->reputationListID >= 0) + return false; + + return my_faction->IsNeutralToAll(); +} + +bool Unit::Attack(Unit *victim, bool meleeAttack) +{ + if (!victim || victim == this) + return false; + + // Nostalrius : verifications de bon sens + if (victim->IsDeleted() || IsDeleted()) + return false; + + // dead units can neither attack nor be attacked + if (!isAlive() || !victim->IsInWorld() || !victim->isAlive()) + return false; + + // player cannot attack in mount state + if (GetTypeId() == TYPEID_PLAYER && IsMounted()) + return false; + + // nobody can attack GM in GM-mode + if (victim->GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)victim)->isGameMaster()) + return false; + } + else + { + if (((Creature*)victim)->IsInEvadeMode()) + return false; + } + + // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack) + if (HasAuraType(SPELL_AURA_MOD_UNATTACKABLE)) + RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE); + + // in fighting already + if (m_attacking) + { + if (m_attacking == victim) + { + // switch to melee attack from ranged/magic + if (meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING)) + { + addUnitState(UNIT_STAT_MELEE_ATTACKING); + SendMeleeAttackStart(victim); + return true; + } + return false; + } + + // remove old target data + AttackStop(true); + } + + // Set our target + SetTargetGuid(victim->GetObjectGuid()); + + if (meleeAttack) + addUnitState(UNIT_STAT_MELEE_ATTACKING); + + m_attacking = victim; + m_attacking->_addAttacker(this); + + if (GetTypeId() == TYPEID_UNIT) // && !((Creature*)this)->GetLinkGroup()) + { + ((Creature*)this)->SendAIReaction(AI_REACTION_HOSTILE); + ((Creature*)this)->CallAssistance(); + } + + // delay offhand weapon attack to next attack time + if (haveOffhandWeapon()) + resetAttackTimer(OFF_ATTACK); + + if (meleeAttack) + SendMeleeAttackStart(victim); + + if (Pet* pet = GetPet()) + if (pet->isAlive()) + pet->AI()->OwnerAttacked(victim); + return true; +} + +void Unit::AttackedBy(Unit* attacker) +{ + if (Pet* pet = GetPet()) + if (pet->isAlive()) + pet->AI()->OwnerAttackedBy(attacker); + + if (!IsCreature()) + return; + + // trigger AI reaction + if (((Creature*)this)->AI()) + ((Creature*)this)->AI()->AttackedBy(attacker); + + // trigger owner AI reaction + if(Unit* owner = GetCharmerOrOwner()) + if (owner->IsCreature() && ((Creature*)owner)->AI()){ + ((Creature*)owner)->AI()->AttackedBy(attacker); + } +} + +bool Unit::AttackStop(bool targetSwitch /*=false*/) +{ + if (!m_attacking) + return false; + + Unit* victim = m_attacking; + + m_attacking->_removeAttacker(this); + m_attacking = nullptr; + + // Clear our target + SetTargetGuid(ObjectGuid()); + + clearUnitState(UNIT_STAT_MELEE_ATTACKING); + + InterruptSpell(CURRENT_MELEE_SPELL); + + // reset only at real combat stop + if (!targetSwitch) + if (Creature* me = ToCreature()) + { + me->ResetDamageTakenOrigin(); + me->SetNoCallAssistance(false); + + if (me->HasSearchedAssistance()) + { + me->SetNoSearchAssistance(false); + UpdateSpeed(MOVE_RUN, false); + } + } + + SendMeleeAttackStop(victim); + + return true; +} + +void Unit::CombatStop(bool includingCast) +{ + if (includingCast && IsNonMeleeSpellCasted(false)) + InterruptNonMeleeSpells(false); + + AttackStop(); + RemoveAllAttackers(); + + if (GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel + else if (GetTypeId() == TYPEID_UNIT) + { + ((Creature*)this)->m_TargetNotReachableTimer = 0; + if (((Creature*)this)->GetTemporaryFactionFlags() & TEMPFACTION_RESTORE_COMBAT_STOP) + ((Creature*)this)->ClearTemporaryFaction(); + } + + ClearInCombat(); +} + +struct CombatStopWithPetsHelper +{ + explicit CombatStopWithPetsHelper(bool _includingCast) : includingCast(_includingCast) {} + void operator()(Unit* unit) const + { + unit->CombatStop(includingCast); + } + bool includingCast; +}; + +void Unit::CombatStopWithPets(bool includingCast) +{ + CombatStop(includingCast); + CallForAllControlledUnits(CombatStopWithPetsHelper(includingCast), CONTROLLED_PET | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); +} + +struct IsAttackingPlayerHelper +{ + explicit IsAttackingPlayerHelper() {} + bool operator()(Unit const* unit) const + { + return unit->isAttackingPlayer(); + } +}; + +bool Unit::isAttackingPlayer() const +{ + if (hasUnitState(UNIT_STAT_ATTACK_PLAYER)) + return true; + + return CheckAllControlledUnits(IsAttackingPlayerHelper(), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); +} + +void Unit::RemoveAllAttackers() +{ + while (!m_attackers.empty()) + { + AttackerSet::iterator iter = m_attackers.begin(); + if (!(*iter)->AttackStop()) + { + sLog.outError("WORLD: Unit has an attacker that isn't attacking it!"); + m_attackers.erase(iter); + } + } +} + +void Unit::ModifyAuraState(AuraState flag, bool apply) +{ + if (apply) + { + if (!HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) + { + SetFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); + if (GetTypeId() == TYPEID_PLAYER) + { + const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap(); + for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) + { + if (itr->second.state == PLAYERSPELL_REMOVED) continue; + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(itr->first); + if (!spellInfo || !IsPassiveSpell(spellInfo)) continue; + if (AuraState(spellInfo->CasterAuraState) == flag) + CastSpell(this, itr->first, true, nullptr); + } + } + } + } + else + { + if (HasFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1))) + { + RemoveFlag(UNIT_FIELD_AURASTATE, 1 << (flag - 1)); + + Unit::SpellAuraHolderMap& tAuras = GetSpellAuraHolderMap(); + for (Unit::SpellAuraHolderMap::iterator itr = tAuras.begin(); itr != tAuras.end();) + { + SpellEntry const* spellProto = (*itr).second->GetSpellProto(); + if (spellProto->CasterAuraState == flag) + { + RemoveSpellAuraHolder(itr->second); + itr = tAuras.begin(); + } + else + ++itr; + } + } + } +} + +Unit *Unit::GetOwner() const +{ + if (ObjectGuid ownerid = GetOwnerGuid()) + return ObjectAccessor::GetUnit(*this, ownerid); + return nullptr; +} + +Unit *Unit::GetCharmer() const +{ + if (ObjectGuid charmerid = GetCharmerGuid()) + return ObjectAccessor::GetUnit(*this, charmerid); + return nullptr; +} + +bool Unit::IsCharmerOrOwnerPlayerOrPlayerItself() const +{ + if (GetTypeId() == TYPEID_PLAYER) + return true; + + return GetCharmerOrOwnerGuid().IsPlayer(); +} + +Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself() const +{ + ObjectGuid guid = GetCharmerOrOwnerGuid(); + if (guid.IsPlayer()) + return ObjectAccessor::FindPlayer(guid); + + return GetTypeId() == TYPEID_PLAYER ? (Player*)this : NULL; +} + +Player* Unit::GetAffectingPlayer() const +{ + if (!GetCharmerOrOwnerGuid()) + return const_cast(this)->ToPlayer(); + + if (Unit* owner = GetCharmerOrOwner()) + return owner->GetCharmerOrOwnerPlayerOrPlayerItself(); + + return nullptr; +} + +Pet* Unit::GetPet() const +{ + if (ObjectGuid pet_guid = GetPetGuid()) + { + if (Pet* pet = GetMap()->GetPet(pet_guid)) + return pet; + + sLog.outError("Unit::GetPet: %s not exist.", pet_guid.GetString().c_str()); + const_cast(this)->SetPet(nullptr); + } + + return nullptr; +} + +Pet* Unit::_GetPet(ObjectGuid guid) const +{ + return GetMap()->GetPet(guid); +} + +Unit* Unit::GetCharm() const +{ + if (ObjectGuid charm_guid = GetCharmGuid()) + { + if (Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid)) + return pet; + + sLog.outError("Unit::GetCharm: Charmed %s not exist.", charm_guid.GetString().c_str()); + const_cast(this)->SetCharm(nullptr); + } + + return nullptr; +} + +void Unit::Uncharm() +{ + if (Unit* charm = GetCharm()) + { + charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM); + charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS); + charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS_PET); + } +} + +float Unit::GetCombatDistance(const Unit* target) const +{ + float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH); + float dx = GetPositionX() - target->GetPositionX(); + float dy = GetPositionY() - target->GetPositionY(); + float dz = GetPositionZ() - target->GetPositionZ(); + float dist = sqrt((dx * dx) + (dy * dy) + (dz * dz)) - radius; + return (dist > 0 ? dist : 0); +} + +float Unit::GetDistanceToCenter(const Unit* target) const +{ + float dx = GetPositionX() - target->GetPositionX(); + float dy = GetPositionY() - target->GetPositionY(); + float dz = GetPositionZ() - target->GetPositionZ(); + float dist = sqrt((dx * dx) + (dy * dy) + (dz * dz)); + return (dist > 0 ? dist : 0); +} + +void Unit::SetPet(Pet* pet) +{ + SetPetGuid(pet ? pet->GetObjectGuid() : ObjectGuid()); + if (pet) + pet->SetWorldMask(GetWorldMask()); +} + +void Unit::SetCharm(Unit* pet) +{ + SetCharmGuid(pet ? pet->GetObjectGuid() : ObjectGuid()); +} + + +void Unit::RestoreFaction() +{ + if (GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->setFactionForRace(getRace()); + else + { + if (CreatureInfo const *cinfo = ((Creature*)this)->GetCreatureInfo()) // normal creature + { + FactionTemplateEntry const *faction = getFactionTemplateEntry(); + setFaction((faction && faction->friendlyMask & 0x004) ? cinfo->faction_H : cinfo->faction_A); + } + } +} + +bool Unit::canAttack(Unit const* target, bool force) const +{ + ASSERT(target); + + if (force) + { + if (IsFriendlyTo(target)) + return false; + + if (GetTypeId() != TYPEID_PLAYER) + { + if (((Creature*)this)->IsPet()) + { + if (Unit *owner = GetOwner()) + if (!(owner->canAttack(target))) + return false; + } + else if (!IsHostileTo(target)) + return false; + } + } + else if (!IsHostileTo(target)) + return false; + + if (!target->isAttackableByAOE() || target->hasUnitState(UNIT_STAT_DIED)) + return false; + + // shaman totem quests: spell 8898, shaman can detect elementals but elementals cannot see shaman + if (m_invisibilityMask || target->m_invisibilityMask) + if (!canDetectInvisibilityOf(target) && !target->canDetectInvisibilityOf(this)) + return false; + + return true; +} + +void Unit::AddGuardian(Pet* pet) +{ + m_guardianPets.insert(pet->GetObjectGuid()); + pet->SetWorldMask(GetWorldMask()); // Nostalrius : phasing +} + +void Unit::RemoveGuardian(Pet* pet) +{ + m_guardianPets.erase(pet->GetObjectGuid()); +} + +void Unit::RemoveGuardians() +{ + while (!m_guardianPets.empty()) + { + ObjectGuid guid = *m_guardianPets.begin(); + + if (Pet* pet = GetMap()->GetPet(guid)) + pet->Unsummon(PET_SAVE_AS_DELETED, this); // can remove pet guid from m_guardianPets + + m_guardianPets.erase(guid); + } +} + +Pet* Unit::FindGuardianWithEntry(uint32 entry) +{ + for (GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr) + if (Pet* pet = GetMap()->GetPet(*itr)) + if (pet->GetEntry() == entry) + return pet; + + return nullptr; +} + +Unit* Unit::_GetTotem(TotemSlot slot) const +{ + return GetTotem(slot); +} + +Totem* Unit::GetTotem(TotemSlot slot) const +{ + if (slot >= MAX_TOTEM_SLOT || !IsInWorld() || !m_TotemSlot[slot]) + return nullptr; + + Creature *totem = GetMap()->GetCreature(m_TotemSlot[slot]); + return totem && totem->IsTotem() ? (Totem*)totem : NULL; +} + +bool Unit::IsAllTotemSlotsUsed() const +{ + for (int i = 0; i < MAX_TOTEM_SLOT; ++i) + if (!m_TotemSlot[i]) + return false; + return true; +} + +void Unit::_AddTotem(TotemSlot slot, Totem* totem) +{ + m_TotemSlot[slot] = totem->GetObjectGuid(); + totem->SetWorldMask(GetWorldMask()); +} + +void Unit::_RemoveTotem(Totem* totem) +{ + for (int i = 0; i < MAX_TOTEM_SLOT; ++i) + { + if (m_TotemSlot[i] == totem->GetObjectGuid()) + { + m_TotemSlot[i].Clear(); + break; + } + } +} + +void Unit::UnsummonAllTotems() +{ + for (int i = 0; i < MAX_TOTEM_SLOT; ++i) + if (Totem* totem = GetTotem(TotemSlot(i))) + totem->UnSummon(); +} + +int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical) +{ + int32 gain = pVictim->ModifyHealth(int32(addhealth)); + + Unit* unit = this; + + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) + unit = GetOwner(); + + if (unit->GetTypeId() == TYPEID_PLAYER) + unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, critical); + + // Script Event HealedBy + if (pVictim->AI()) + pVictim->AI()->HealedBy(this, addhealth); + + return gain; +} + +Unit* Unit::SelectMagnetTarget(Unit *victim, Spell* spell, SpellEffectIndex eff) +{ + if (!victim) + return nullptr; + + SpellEntry const* pProto = spell->m_spellInfo; + if (!pProto) return nullptr; + // Example spell: Cause Insanity (Hakkar) + if (pProto->AttributesEx & SPELL_ATTR_EX_CANT_BE_REDIRECTED) + return victim; + // Magic case + + if (pProto->AttributesEx3 & SPELL_ATTR_EX3_NO_INITIAL_AGGRO) + return victim; + + if ((pProto->DmgClass == SPELL_DAMAGE_CLASS_MAGIC || pProto->SpellVisual == 7250) && pProto->Dispel != DISPEL_POISON && !(pProto->Attributes & 0x10)) + { + Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET); + for (Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr) + { + if (Unit* magnet = (*itr)->GetCaster()) + { + if (magnet->isAlive() && magnet->IsWithinLOSInMap(this) && spell->CheckTarget(magnet, eff)) + { + if (SpellAuraHolder *holder = (*itr)->GetHolder()) + if (holder->DropAuraCharge()) + { + magnet->RemoveAurasDueToSpell(holder->GetId()); // Remove from grounding totem also + victim->RemoveSpellAuraHolder(holder); + } + return magnet; + } + } + } + } + + return victim; +} + +void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical) +{ + // we guess size + WorldPacket data(SMSG_SPELLHEALLOG, (8 + 8 + 4 + 4 + 1)); + data << pVictim->GetPackGUID(); + data << GetPackGUID(); + data << uint32(SpellID); + data << uint32(Damage); + data << uint8(critical ? 1 : 0); + data << uint8(0); // unused in client? + SendMessageToSet(&data, true); +} + +void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype) +{ + WorldPacket data(SMSG_SPELLENERGIZELOG, (8 + 8 + 4 + 4 + 4 + 1)); + data << pVictim->GetPackGUID(); + data << GetPackGUID(); + data << uint32(SpellID); + data << uint32(powertype); + data << uint32(Damage); + SendMessageToSet(&data, true); +} + +void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype) +{ + SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype); + // needs to be called after sending spell log + pVictim->ModifyPower(powertype, Damage); +} + +int32 Unit::SpellBonusWithCoeffs(SpellEntry const *spellProto, int32 total, int32 benefit, int32 ap_benefit, DamageEffectType damagetype, bool donePart, Unit *pCaster, Spell* spell) +{ + // Distribute Damage over multiple effects, reduce by AoE + float coeff = 0.0f; + + // Not apply this to creature casted spells + // Daemon: n'importe quoi. Et apres on se demande pourquoi les degats du sceau du croise sont abuses ... + //if (GetTypeId()==TYPEID_UNIT && !((Creature*)this)->IsPet()) + // coeff = 1.0f; + // Check for table values + if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id)) + { + coeff = damagetype == DOT ? bonus->dot_damage : bonus->direct_damage; + + // apply ap bonus at done part calculation only (it flat total mod so common with taken) + if (donePart && (bonus->ap_bonus || bonus->ap_dot_bonus)) + { + float ap_bonus = damagetype == DOT ? bonus->ap_dot_bonus : bonus->ap_bonus; + + total += int32(ap_bonus * (GetTotalAttackPowerValue(IsSpellRequiresRangedAP(spellProto) ? RANGED_ATTACK : BASE_ATTACK) + ap_benefit)); + } + } + // Calculate default coefficient + else if (benefit) + coeff = CalculateDefaultCoefficient(spellProto, damagetype); + + if (benefit) + { + // Calculate level penalty + float LvlPenalty = CalculateLevelPenalty(spellProto); + + // Calculate custom coefficient + coeff = CalculateCustomCoefficient(spellProto, pCaster, damagetype, coeff, spell); + + // Spellmod SpellDamage + if (Player* modOwner = GetSpellModOwner()) + { + coeff *= 100.0f; + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, coeff, spell); + coeff /= 100.0f; + } + // Nostalrius. + bool bUsePenalty = true; + // Eclair lumineux + if (spellProto->Id == 19993) + { + bUsePenalty = false; + // Libram de divinite + if (HasAura(28853)) + total += 53.0f; + } + // Lumiere sacree + //else if (spellProto->Id == 19968) + //bUsePenalty = false; + + if (bUsePenalty) + total += int32(benefit * coeff * LvlPenalty); + else + total += int32(benefit * coeff); + + } + + return total; +}; + +/** + * Calculates caster part of spell damage bonuses, + * also includes different bonuses dependent from target auras + */ +uint32 Unit::SpellDamageBonusDone(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack, Spell* spell) +{ + if (!spellProto || !pVictim || damagetype == DIRECT_DAMAGE) + return pdamage; + + // Ignite damage already includes modifiers + if (spellProto->IsFitToFamily()) + return pdamage; + + // For totems get damage bonus from owner (statue isn't totem in fact) + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) + { + if (Unit* owner = GetOwner()) + return owner->SpellDamageBonusDone(pVictim, spellProto, pdamage, damagetype, stack, spell); + } + + float DoneTotalMod = 1.0f; + int32 DoneTotal = 0; + Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(BASE_ATTACK, true, false) : NULL; + + // Creature damage + if (GetTypeId() == TYPEID_UNIT && !((Creature*)this)->IsPet()) + DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank); + + AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); + for (AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) + { + if (((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) && + (*i)->GetSpellProto()->EquippedItemClass == -1 && + // -1 == any item class (not wand then) + (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) + // 0 == any inventory type (not wand then) + DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + + // Paladin seals benefit from weapon modifiers + else if ((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && + spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && spellProto->IsFitToFamilyMask() && + (((*i)->GetSpellProto()->EquippedItemClass == -1) || + (pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto())))) + DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } + + uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); + + // Add pct bonus from spell damage versus + DoneTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask); + + // Add flat bonus from spell damage creature + DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask); + + // done scripted mod (take it from owner) + Unit *owner = GetOwner(); + if (!owner) owner = this; + AuraList const& mOverrideClassScript = owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) + { + if (!(*i)->isAffectedOnSpell(spellProto)) + continue; + switch ((*i)->GetModifier()->m_miscvalue) + { + case 4418: // Increased Shock Damage + case 4554: // Increased Lightning Damage + case 4555: // Improved Moonfire + { + DoneTotal += (*i)->GetModifier()->m_amount; + break; + } + } + } + + // Pet happiness increases damage of Hunter pet spells (e.g. Lightning Breath) + if (IsPet() && ((Pet*)this)->getPetType() == HUNTER_PET) + { + if (Pet* pet = ((Pet*)this)) + { + switch (pet->GetHappinessState()) + { + case HAPPY: DoneTotalMod *= 1.25; break; + case CONTENT: break; + case UNHAPPY: DoneTotalMod *= 0.75; break; + } + } + } + + // Done fixed damage bonus auras + int32 DoneAdvertisedBenefit = SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto)); + + // Add flat bonus from spell damage versus + DoneAdvertisedBenefit += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask); + + // Pets just add their bonus damage to their spell damage + // note that their spell damage is just gain of their own auras + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage(); + + // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties + DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true, this, spell); + + float tmpDamage = (int32(pdamage) + DoneTotal * int32(stack)) * DoneTotalMod; + // apply spellmod to Done damage (flat and pct) + if (Player* modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage, spell); + + DEBUG_UNIT(this, DEBUG_SPELLS_DAMAGE, "SpellDmgBonus[spell=%u]: (base=%u + %i) * %f. SP=%i", spellProto->Id, pdamage, DoneTotal, DoneTotalMod, DoneAdvertisedBenefit); + return tmpDamage > 0 ? uint32(tmpDamage) : 0; +} + +/** + * Calculates target part of spell damage bonuses, + * will be called on each tick for periodic damage over time auras + */ +uint32 Unit::SpellDamageBonusTaken(Unit *pCaster, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack, Spell* spell) +{ + if (!spellProto || !pCaster || damagetype == DIRECT_DAMAGE) + return pdamage; + + uint32 schoolMask = spell ? spell->m_spellSchoolMask : GetSpellSchoolMask(spellProto); + + // Taken total percent damage auras + float TakenTotalMod = 1.0f; + int32 TakenTotal = 0; + + // ..taken + TakenTotalMod *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask); + + // Taken fixed damage bonus auras + int32 TakenAdvertisedBenefit = SpellBaseDamageBonusTaken(GetSpellSchoolMask(spellProto)); + + // apply benefit affected by spell power implicit coeffs and spell level penalties + TakenTotal = SpellBonusWithCoeffs(spellProto, TakenTotal, TakenAdvertisedBenefit, 0, damagetype, false, pCaster, spell); + + float tmpDamage = (int32(pdamage) + TakenTotal * int32(stack)) * TakenTotalMod; + + return tmpDamage > 0 ? uint32(tmpDamage) : 0; +} + +int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) +{ + int32 DoneAdvertisedBenefit = 0; + + // ..done + AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE); + for (AuraList::const_iterator i = mDamageDone.begin(); i != mDamageDone.end(); ++i) + { + if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 && + (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then) + (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then) + DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount; + } + + if (GetTypeId() == TYPEID_PLAYER) + { + // Damage bonus from stats + AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT); + for (AuraList::const_iterator i = mDamageDoneOfStatPercent.begin(); i != mDamageDoneOfStatPercent.end(); ++i) + { + if ((*i)->GetModifier()->m_miscvalue & schoolMask) + { + // stat used stored in miscValueB for this aura + Stats usedStat = STAT_SPIRIT; + DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f); + } + } + } + return DoneAdvertisedBenefit; +} + +int32 Unit::SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask) +{ + int32 TakenAdvertisedBenefit = 0; + + // ..taken + AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN); + for (AuraList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) + { + if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0) + TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount; + } + + return TakenAdvertisedBenefit; +} + +bool Unit::IsSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType, Spell* spell) +{ + ASSERT(pVictim); + // Les mobs ne peuvent pas critiquer avec les sorts. Mais totems et pets peuvent. + if (GetTypeId() == TYPEID_UNIT && !GetOwnerGuid().IsPlayer()) + return false; + + if (IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_ALWAYS_CRIT)) + return true; + + // not critting spell + if ((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT)) + return false; + + float crit_chance = 0.0f; + // Les potions/pierres de soin peuvent critiquer avec un pourcentage de chance constant + if (spellProto->SpellFamilyName == SPELLFAMILY_POTION || + (spellProto->IsFitToFamily())) + crit_chance = 10.0f; + else + { + switch (spellProto->DmgClass) + { + case SPELL_DAMAGE_CLASS_NONE: + return false; + case SPELL_DAMAGE_CLASS_MAGIC: + { + if (schoolMask & SPELL_SCHOOL_MASK_NORMAL) + crit_chance = 0.0f; + // For other schools + else if (GetTypeId() == TYPEID_PLAYER) + crit_chance = ((Player*)this)->m_SpellCritPercentage[GetFirstSchoolInMask(schoolMask)]; + else + { + crit_chance = float(m_baseSpellCritChance); + crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); + } + // taken + if (!IsPositiveSpell(spellProto->Id)) + { + // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE + crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask); + } + + // scripted (increase crit chance ... against ... target by x% + AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) + { + if (!((*i)->GetSpellProto()->SpellFamilyName == spellProto->SpellFamilyName)) + continue; + switch ((*i)->GetModifier()->m_miscvalue) + { + // Shatter + case 849: + if (pVictim->isFrozen()) crit_chance += 10.0f; + break; + case 910: + if (pVictim->isFrozen()) crit_chance += 20.0f; + break; + case 911: + if (pVictim->isFrozen()) crit_chance += 30.0f; + break; + case 912: + if (pVictim->isFrozen()) crit_chance += 40.0f; + break; + case 913: + if (pVictim->isFrozen()) crit_chance += 50.0f; + break; + default: + break; + } + } + break; + } + case SPELL_DAMAGE_CLASS_MELEE: + case SPELL_DAMAGE_CLASS_RANGED: + { + // Joueurs assis = critique obligatoire. + if (pVictim->GetTypeId() == TYPEID_PLAYER && pVictim->IsSitState()) + return true; + crit_chance = GetUnitCriticalChance(attackType, pVictim); + crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask); + break; + } + default: + return false; + } + } + // percent done + // only players use intelligence for critical chance computations + if (Player* modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance, spell); + + crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f; + + DEBUG_UNIT(this, DEBUG_SPELL_COMPUTE_RESISTS, "%s [ID:%u] Crit chance %f.", spellProto->SpellName[2], spellProto->Id, crit_chance); + + if ((IsPlayer() && ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE)) || + (pVictim->IsPlayer() && pVictim->ToPlayer()->HasOption(PLAYER_CHEAT_UNRANDOMIZE))) + crit_chance = 0; + if (roll_chance_f(crit_chance)) + return true; + return false; +} + +uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim, Spell* spell) +{ + // Calculate critical bonus + int32 crit_bonus; + switch (spellProto->DmgClass) + { + case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100% + case SPELL_DAMAGE_CLASS_RANGED: + crit_bonus = damage; + break; + default: + crit_bonus = damage / 2; // for spells is 50% + break; + } + + // adds additional damage to crit_bonus (from talents) + if (Player* modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus, spell); + + if (!pVictim) + return damage += crit_bonus; + + uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); + + float critPctDamageMod = GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask); + + damage = (damage + crit_bonus) * critPctDamageMod; + + return damage; +} + +uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim) +{ + // Calculate critical bonus + int32 crit_bonus; + switch (spellProto->DmgClass) + { + case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100% + case SPELL_DAMAGE_CLASS_RANGED: + // TODO: write here full calculation for melee/ranged spells + crit_bonus = damage; + break; + default: + crit_bonus = damage / 2; // for spells is 50% + break; + } + + if (pVictim) + { + uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); + crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask)); + } + + if (crit_bonus > 0) + damage += crit_bonus; + + return damage; +} + +/** + * Calculates caster part of healing spell bonuses, + * also includes different bonuses dependent from target auras + */ +uint32 Unit::SpellHealingBonusDone(Unit *pVictim, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack, Spell* spell) +{ + // For totems get healing bonus from owner (statue isn't totem in fact) + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem() && ((Totem*)this)->GetTotemType() != TOTEM_STATUE) + if (Unit* owner = GetOwner()) + return owner->SpellHealingBonusDone(pVictim, spellProto, healamount, damagetype, stack, spell); + + // No heal amount for this class spells + if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellProto->Custom & SPELL_CUSTOM_FIXED_DAMAGE) + { + DEBUG_UNIT(this, DEBUG_SPELLS_DAMAGE, "SpellHealingBonusDone[spell=%u]: has fixed damage (SPELL_DAMAGE_CLASS_NONE)", spellProto->Id); + return healamount < 0 ? 0 : healamount; + } + // Healing Done + // Done total percent damage auras + float DoneTotalMod = 1.0f; + int32 DoneTotal = 0; + + // Healing done percent + AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT); + for (AuraList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i) + DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f; + + // done scripted mod (take it from owner) + Unit *owner = GetOwner(); + if (!owner) + owner = this; + AuraList const& mOverrideClassScript = owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); + for (AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) + { + if (!(*i)->isAffectedOnSpell(spellProto)) + continue; + switch ((*i)->GetModifier()->m_miscvalue) + { + case 4415: // Increased Rejuvenation Healing + DoneTotal += (*i)->GetModifier()->m_amount / 4; // 4 ticks + break; + case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / Savage Totem of the Third Wind + DoneTotal += (*i)->GetModifier()->m_amount; + break; + default: + break; + } + } + + // Done fixed damage bonus auras + int32 DoneAdvertisedBenefit = SpellBaseHealingBonusDone(GetSpellSchoolMask(spellProto)); + + // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties + DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true, this, spell); + + // use float as more appropriate for negative values and percent applying + float heal = (healamount + DoneTotal * int32(stack)) * DoneTotalMod; + // apply spellmod to Done amount + if (Player* modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal, spell); + + DEBUG_UNIT(this, DEBUG_SPELLS_DAMAGE, "SpellHealingBonusDone[spell=%u]: (base=%u + %i) * %f. HealingPwr=%i", spellProto->Id, healamount, DoneTotal, DoneTotalMod, DoneAdvertisedBenefit); + return heal < 0 ? 0 : uint32(heal); +} + +/** + * Calculates target part of healing spell bonuses, + * will be called on each tick for periodic damage over time auras + */ +uint32 Unit::SpellHealingBonusTaken(Unit *pCaster, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack, Spell* spell) +{ + float TakenTotalMod = 1.0f; + + // Healing taken percent + float minval = float(GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT)); + if (minval) + TakenTotalMod *= (100.0f + minval) / 100.0f; + + float maxval = float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT)); + if (maxval) + TakenTotalMod *= (100.0f + maxval) / 100.0f; + + // No heal amount for this class spells + if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE) + { + healamount = int32(healamount * TakenTotalMod); + return healamount < 0 ? 0 : healamount; + } + + // Healing Done + // Done total percent damage auras + int32 TakenTotal = 0; + + // Taken fixed damage bonus auras + int32 TakenAdvertisedBenefit = SpellBaseHealingBonusTaken(GetSpellSchoolMask(spellProto)); + + // Blessing of Light dummy effects healing taken from Holy Light and Flash of Light + if (spellProto->IsFitToFamily()) + { + AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY); + for (AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i) + { + // Libram of Divinity + if ((*i)->GetSpellProto()->Id == 28851 && spellProto->IsFitToFamilyMask()) + TakenTotal += (*i)->GetModifier()->m_amount; + if ((*i)->GetSpellProto()->IsFitToFamilyMask() && (*i)->GetSpellProto()->SpellVisual == 300) + { + // Holy Light + if (spellProto->IsFitToFamilyMask() && (*i)->GetEffIndex() == EFFECT_INDEX_0) + TakenTotal += (*i)->GetModifier()->m_amount; + // Flash of Light + else if (spellProto->IsFitToFamilyMask() && (*i)->GetEffIndex() == EFFECT_INDEX_1) + TakenTotal += (*i)->GetModifier()->m_amount; + } + } + } + // apply benefit affected by spell power implicit coeffs and spell level penalties + TakenTotal = SpellBonusWithCoeffs(spellProto, TakenTotal, TakenAdvertisedBenefit, 0, damagetype, false, pCaster, spell); + + // Taken mods + // Healing Wave cast + if (spellProto->IsFitToFamily()) + { + // Search for Healing Way on Victim + Unit::AuraList const& auraDummy = GetAurasByType(SPELL_AURA_DUMMY); + for (Unit::AuraList::const_iterator itr = auraDummy.begin(); itr != auraDummy.end(); ++itr) + if ((*itr)->GetId() == 29203) + TakenTotalMod *= ((*itr)->GetModifier()->m_amount + 100.0f) / 100.0f; + } + + + // use float as more appropriate for negative values and percent applying + float heal = (healamount + TakenTotal * int32(stack)) * TakenTotalMod; + + return heal < 0 ? 0 : uint32(heal); +} + +int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask) +{ + int32 AdvertisedBenefit = 0; + + AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE); + for (AuraList::const_iterator i = mHealingDone.begin(); i != mHealingDone.end(); ++i) + if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0) + AdvertisedBenefit += (*i)->GetModifier()->m_amount; + + // Healing bonus of spirit, intellect and strength + if (GetTypeId() == TYPEID_PLAYER) + { + // Healing bonus from stats + AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT); + for (AuraList::const_iterator i = mHealingDoneOfStatPercent.begin(); i != mHealingDoneOfStatPercent.end(); ++i) + { + // 1.12.* have only 1 stat type support + Stats usedStat = STAT_SPIRIT; + AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f); + } + } + return AdvertisedBenefit; +} + +int32 Unit::SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask) +{ + int32 AdvertisedBenefit = 0; + AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_HEALING); + for (AuraList::const_iterator i = mDamageTaken.begin(); i != mDamageTaken.end(); ++i) + if ((*i)->GetModifier()->m_miscvalue & schoolMask) + AdvertisedBenefit += (*i)->GetModifier()->m_amount; + + return AdvertisedBenefit; +} + +bool Unit::IsImmuneToDamage(SpellSchoolMask shoolMask) +{ + // If m_immuneToSchool type contain this school type, IMMUNE damage. + SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL]; + for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) + if (itr->type & shoolMask) + return true; + + // If m_immuneToDamage type contain magic, IMMUNE damage. + SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE]; + for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr) + if (itr->type & shoolMask) + return true; + + return false; +} + +bool Unit::IsImmuneToSpell(SpellEntry const *spellInfo, bool /*castOnSelf*/) +{ + if (!spellInfo) + return false; + + //TODO add spellEffect immunity checks!, player with flag in bg is immune to immunity buffs from other friendly players! + //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT]; + + SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL]; + for (SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr) + if (itr->type == spellInfo->Dispel) + return true; + + if ( !(spellInfo->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) // ignore invulnerability + && !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) // unaffected by school immunity + && !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it) + { + SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL]; + for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr) + if (!(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) && + (itr->type & GetSpellSchoolMask(spellInfo))) + return true; + } + + if (uint32 mechanic = spellInfo->Mechanic) + { + SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC]; + for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr) + { + if (itr->type == mechanic) + { + // always remove Fear Ward on fear immunity event, even if the unit has another fear immunity aura like Berserker Rage + if (mechanic == MECHANIC_FEAR) + RemoveAurasDueToSpell(6346); + return true; + } + } + + AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK); + for (AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter) + if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic - 1))) + return true; + } + + return false; +} + +bool Unit::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index, bool /*castOnSelf*/) const +{ + //If m_immuneToEffect type contain this effect type, IMMUNE effect. + uint32 effect = spellInfo->Effect[index]; + SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT]; + for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr) + if (itr->type == effect) + return true; + + if (uint32 mechanic = spellInfo->EffectMechanic[index]) + { + SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC]; + for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr) + if (itr->type == spellInfo->EffectMechanic[index]) + return true; + + AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK); + for (AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter) + if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic - 1))) + return true; + } + + uint32 aura = spellInfo->EffectApplyAuraName[index]; + if (aura) + { + SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE]; + for (SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr) + if (itr->type == aura) + return true; + } + return false; +} + +/** + * Calculates caster part of melee damage bonuses, + * also includes different bonuses dependent from target auras + */ +uint32 Unit::MeleeDamageBonusDone(Unit* pVictim, uint32 pdamage, WeaponAttackType attType, SpellEntry const* spellProto, DamageEffectType damagetype, uint32 stack, Spell* spell, bool flat) +{ + if (!pVictim) + return pdamage; + + if (pdamage == 0) + return pdamage; + + // differentiate for weapon damage based spells + bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE))); + Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(attType, true, false) : NULL; + uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); + uint32 schoolMask = spellProto ? GetSpellSchoolMask(spellProto) : GetMeleeDamageSchoolMask(); + + // FLAT damage bonus auras + // ======================= + int32 DoneFlat = 0; + int32 APbonus = 0; + + // ..done flat, already included in weapon damage based spells + if (!isWeaponDamageBasedSpell) + { + AuraList const& mModDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE); + for (AuraList::const_iterator i = mModDamageDone.begin(); i != mModDamageDone.end(); ++i) + { + if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school + ((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() || // AND schoolmask has to fit with weapon damage school (essential for non-physical spells) + spellProto->DmgClass == SPELL_DAMAGE_CLASS_RANGED) && // Some ranged physical attacks use magic damage, ex. Arcane Shot + (((*i)->GetSpellProto()->EquippedItemClass == -1) || // general, weapon independent + (pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto())))) // OR used weapon fits aura requirements + DoneFlat += (*i)->GetModifier()->m_amount; + } + + // Pets just add their bonus damage to their melee damage + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + DoneFlat += ((Pet*)this)->GetBonusDamage(); + } + + // ..done flat (by creature type mask) + DoneFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask); + + // ..done flat (base at attack power for marked target and base at attack power for creature type) + if (attType == RANGED_ATTACK) + { + APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS); + APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS, creatureTypeMask); + } + else + { + APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS); + APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS, creatureTypeMask); + } + + // PERCENT damage auras + // ==================== + float DonePercent = 1.0f; + + // ..done pct, already included in weapon damage based spells + if (!isWeaponDamageBasedSpell) + { + AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); + for (AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) + { + if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school + (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells) + (((*i)->GetSpellProto()->EquippedItemClass == -1) || // general, weapon independent + (pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto())))) // OR used weapon fits aura requirements + DonePercent *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f; + } + + if (attType == OFF_ATTACK) + DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required + } + + // Pet happiness increases damage of Hunter pet melee spells + if (IsPet() && ((Pet*)this)->getPetType() == HUNTER_PET) + { + if (Pet* pet = ((Pet*)this)) + { + switch (pet->GetHappinessState()) + { + case HAPPY: DonePercent *= 1.25; break; + case CONTENT: break; + case UNHAPPY: DonePercent *= 0.75; break; + } + } + } + + // ..done pct (by creature type mask) + DonePercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask); + + // special dummys/class scripts and other effects + // ============================================= + Unit *owner = GetOwner(); + if (!owner) + owner = this; + + // final calculation + // ================= + + float DoneTotal = 0.0f; + + // scaling of non weapon based spells + if (!isWeaponDamageBasedSpell) + { + // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties + DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneFlat, APbonus, damagetype, true, this, spell); + } + // weapon damage based spells + else if (APbonus || DoneFlat) + { + bool normalized = spellProto ? IsSpellHaveEffect(spellProto, SPELL_EFFECT_NORMALIZED_WEAPON_DMG) : false; + DoneTotal += int32(APbonus / 14.0f * GetAPMultiplier(attType, normalized)); + + // for weapon damage based spells we still have to apply damage done percent mods + // (that are already included into pdamage) to not-yet included DoneFlat + // e.g. from doneVersusCreature, apBonusVs... + UnitMods unitMod; + switch (attType) + { + default: + case BASE_ATTACK: + unitMod = UNIT_MOD_DAMAGE_MAINHAND; + break; + case OFF_ATTACK: + unitMod = UNIT_MOD_DAMAGE_OFFHAND; + break; + case RANGED_ATTACK: + unitMod = UNIT_MOD_DAMAGE_RANGED; + break; + } + + DoneTotal += DoneFlat; + + DoneTotal *= GetModifierValue(unitMod, TOTAL_PCT); + } + + if (!flat) + DoneTotal = 0.0f; + + float tmpDamage = float(int32(pdamage) + DoneTotal * int32(stack)) * DonePercent; + + // apply spellmod to Done damage + if (spellProto) + { + if (Player* modOwner = GetSpellModOwner()) + modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage, spell); + } + + // bonus result can be negative + return tmpDamage > 0 ? uint32(tmpDamage) : 0; +} + +/** + * Calculates target part of melee damage bonuses, + * will be called on each tick for periodic damage over time auras + */ +uint32 Unit::MeleeDamageBonusTaken(Unit* pCaster, uint32 pdamage, WeaponAttackType attType, SpellEntry const* spellProto, DamageEffectType damagetype, uint32 stack, Spell* spell, bool flat) +{ + if (!pCaster) + return pdamage; + + if (pdamage == 0) + return pdamage; + + // Exception for Seal of Command and Seal of Righteousness + // already with coeff! + if (spellProto && (spellProto->Id == 20424 || + (spellProto->SpellFamilyName == SPELLFAMILY_PALADIN && spellProto->DmgClass == SPELL_DAMAGE_CLASS_MELEE))) // SoR is the only pala spell with melee dmg class + return pdamage; + + // differentiate for weapon damage based spells + bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE))); + uint32 schoolMask = spellProto ? GetSpellSchoolMask(spellProto) : uint32(pCaster->GetMeleeDamageSchoolMask()); + + // FLAT damage bonus auras + // ======================= + int32 TakenFlat = 0; + + // ..taken flat (base at attack power for marked target and base at attack power for creature type) + if (attType == RANGED_ATTACK) + TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN); + else + TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN); + + // ..taken flat (by school mask) + TakenFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask); + + // PERCENT damage auras + // ==================== + float TakenPercent = 1.0f; + + // ..taken pct (by school mask) + TakenPercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask); + + // ..taken pct (melee/ranged) + if (attType == RANGED_ATTACK) + TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT); + else + TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT); + + // final calculation + // ================= + + // scaling of non weapon based spells + if (!isWeaponDamageBasedSpell) + { + // apply benefit affected by spell power implicit coeffs and spell level penalties + TakenFlat = SpellBonusWithCoeffs(spellProto, 0, TakenFlat, 0, damagetype, false, pCaster, spell); + } + + if (!flat) + TakenFlat = 0.0f; + + float tmpDamage = float(int32(pdamage) + TakenFlat * int32(stack)) * TakenPercent; + + // bonus result can be negative + return tmpDamage > 0 ? uint32(tmpDamage) : 0; +} + +void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply) +{ + if (apply) + { + for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next) + { + next = itr; + ++next; + if (itr->type == type) + { + m_spellImmune[op].erase(itr); + next = m_spellImmune[op].begin(); + } + } + SpellImmune Immune; + Immune.spellId = spellId; + Immune.type = type; + m_spellImmune[op].push_back(Immune); + } + else + { + for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr) + { + if (itr->spellId == spellId) + { + m_spellImmune[op].erase(itr); + break; + } + } + } +} + +void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply) +{ + ApplySpellImmune(spellProto->Id, IMMUNITY_DISPEL, type, apply); + + if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY) + RemoveAurasWithDispelType(type); +} + +float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const +{ + // proc per minute chance calculation + if (PPM <= 0.0f) + return 0.0f; + return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60)) +} + +void Unit::Mount(uint32 mount, uint32 spellId) +{ + if (!mount) + return; + + if (SpellAuraHolder *holder = GetSpellAuraHolder(29519)) + { + if (((Player*)this)->GetZoneId() == 1377) + { + // OutdoorPVP Silithus : Perte du buff silithyste + if (ZoneScript* pScript = ((Player*)this)->GetZoneScript()) + pScript->HandleDropFlag(((Player*)this), 29519); + } + } + + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING); + SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount); + + if (GetTypeId() == TYPEID_PLAYER) + { + // Called by Taxi system / GM command + if (!spellId) + ((Player*)this)->UnsummonPetTemporaryIfAny(); + // Called by mount aura + else + { + // Normal case (Unsummon only permanent pet) + if (Pet* pet = GetPet()) + { + if (pet->IsPermanentPetFor((Player*)this) && + sWorld.getConfig(CONFIG_BOOL_PET_UNSUMMON_AT_MOUNT)) + ((Player*)this)->UnsummonPetTemporaryIfAny(); + else + pet->SetEnabled(false); + } + } + } +} + +void Unit::Unmount(bool from_aura) +{ + if (!IsMounted()) + return; + + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED); + + SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0); + + // only resummon old pet if the player is already added to a map + // this prevents adding a pet to a not created map which would otherwise cause a crash + // (it could probably happen when logging in after a previous crash) + if (GetTypeId() == TYPEID_PLAYER) + { + if (Pet* pet = GetPet()) + pet->SetEnabled(true); + else + ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny(); + } +} + +void Unit::SetInCombatWith(Unit* enemy) +{ + ASSERT(enemy); + Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf(); + ASSERT(eOwner); + if (eOwner->IsPvP()) + { + SetInCombatState(true, enemy); + return; + } + + //check for duel + if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel) + { + if (Player const* myOwner = GetCharmerOrOwnerPlayerOrPlayerItself()) + { + if (myOwner->IsInDuelWith((Player const*)eOwner)) + { + SetInCombatState(true, enemy); + return; + } + } + } + + SetInCombatState(false, enemy); +} + +void Unit::SetInCombatState(bool PvP, Unit* enemy) +{ + // only alive units can be in combat + if (!isAlive()) + return; + + if (PvP) + m_CombatTimer = 5500; + + bool wasInCombat = isInCombat(); + bool creatureNotInCombat = GetTypeId() == TYPEID_UNIT && !wasInCombat; + + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); + + if (isCharmed() || (GetTypeId() != TYPEID_PLAYER && ((Creature*)this)->IsPet())) + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); + // set pet in combat + if (Pet* pet = GetPet()) + pet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); + + // interrupt all delayed non-combat casts + if (!wasInCombat) + for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) + if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i))) + if (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) + if (IsNonCombatSpell(spell->m_spellInfo)) + InterruptSpell(CurrentSpellTypes(i), false); + + if (creatureNotInCombat) + { + auto pCreature = ToCreature(); + + pCreature->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ()); + // should probably be removed for the attacked (+ it's party/group) only, not global + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); + + OnEnterCombat(enemy, true); + + // Some bosses are set into combat with zone + if (GetMap()->IsDungeon() && (pCreature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_AGGRO_ZONE) && enemy && enemy->IsControlledByPlayer()) + pCreature->SetInCombatWithZone(); + if (Spell* spell = m_currentSpells[CURRENT_CHANNELED_SPELL]) + if (spell->getState() == SPELL_STATE_CASTING) + if (spell->m_spellInfo->ChannelInterruptFlags & CHANNEL_FLAG_ENTER_COMBAT) + InterruptSpell(CURRENT_CHANNELED_SPELL); + } +} + +void Unit::ClearInCombat() +{ + m_CombatTimer = 0; + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT); + + // Player's state will be cleared in Player::UpdateContestedPvP + if (GetTypeId() != TYPEID_PLAYER) + { + if (((Creature*)this)->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE) + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); + + clearUnitState(UNIT_STAT_ATTACK_PLAYER); + } + + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); +} + +bool Unit::isTargetableForAttack(bool inverseAlive /*=false*/) const +{ + if (!CanBeDetected()) + return false; + + if (GetTypeId() == TYPEID_PLAYER && (((Player *)this)->isGameMaster() || ((Player*)this)->watching_cinematic_entry != 0)) + return false; + + if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE)) + return false; + + // to be removed if unit by any reason enter combat + if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE)) + return false; + + // inversealive is needed for some spells which need to be casted at dead targets (aoe) + if (isAlive() == inverseAlive) + return false; + + return IsInWorld() && !hasUnitState(UNIT_STAT_DIED) && !IsTaxiFlying(); +} + +bool Unit::IsValidAttackTarget(Unit const* target) const +{ + return _IsValidAttackTarget(target, nullptr); +} + +// function based on function Unit::CanAttack from 13850 client +bool Unit::_IsValidAttackTarget(Unit const* target, SpellEntry const* bySpell, WorldObject const* obj) const +{ + ASSERT(target); + // can't attack self + if (this == target) + return false; + + if (FindMap() != target->FindMap()) + return false; + + // can't attack unattackable units or GMs + if (target->GetTypeId() == TYPEID_PLAYER && target->ToPlayer()->isGameMaster()) + return false; + + // check flags + if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_TAXI_FLIGHT | UNIT_FLAG_NOT_ATTACKABLE_1 | UNIT_FLAG_UNK_16)) + return false; + + // CvC case - can attack each other only when one of them is hostile + if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && !target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) + return GetReactionTo(target) <= REP_HOSTILE || target->GetReactionTo(this) <= REP_HOSTILE; + + // PvP, PvC, CvP case + // can't attack friendly targets + if (GetReactionTo(target) > REP_NEUTRAL + || target->GetReactionTo(this) > REP_NEUTRAL) + return false; + + Player const* playerAffectingAttacker = HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? GetAffectingPlayer() : NULL; + Player const* playerAffectingTarget = target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) ? target->GetAffectingPlayer() : NULL; + + // Not all neutral creatures can be attacked + if (GetReactionTo(target) == REP_NEUTRAL && + target->GetReactionTo(this) == REP_NEUTRAL) + { + if (!(playerAffectingTarget && playerAffectingAttacker) && + !(!playerAffectingTarget && !playerAffectingAttacker)) + { + Player const* player = playerAffectingTarget ? playerAffectingTarget : playerAffectingAttacker; + Unit const* creature = playerAffectingTarget ? this : target; + + if (FactionTemplateEntry const* factionTemplate = creature->getFactionTemplateEntry()) + { + if (!(player->GetReputationMgr().GetForcedRankIfAny(factionTemplate))) + if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionTemplate->faction)) + if (FactionState const* repState = player->GetReputationMgr().GetState(factionEntry)) + if (!(repState->Flags & FACTION_FLAG_AT_WAR)) + return false; + + } + } + } + + // PvP checks + if (playerAffectingAttacker && playerAffectingTarget) + { + if (playerAffectingAttacker->duel && playerAffectingAttacker->duel->opponent == playerAffectingTarget && playerAffectingAttacker->duel->startTime != 0) + return true; + + if (playerAffectingTarget->IsPvP()) + return true; + + if (playerAffectingAttacker->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP + && playerAffectingTarget->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) + return true; + + return (playerAffectingAttacker->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1) + || (playerAffectingTarget->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_UNK1); + } + return true; +} + +int32 Unit::ModifyHealth(int32 dVal) +{ + int32 gain = 0; + + if (dVal == 0) + return 0; + + int32 curHealth = (int32)GetHealth(); + + int32 val = dVal + curHealth; + if (val <= 0) + { + SetHealth(0); + return -curHealth; + } + + int32 maxHealth = (int32)GetMaxHealth(); + + if (val < maxHealth) + { + SetHealth(val); + gain = val - curHealth; + } + else if (curHealth != maxHealth) + { + SetHealth(maxHealth); + gain = maxHealth - curHealth; + } + + return gain; +} + +int32 Unit::ModifyPower(Powers power, int32 dVal) +{ + int32 gain = 0; + + if (dVal == 0) + return 0; + + int32 curPower = (int32)GetPower(power); + + int32 val = dVal + curPower; + if (val <= 0) + { + SetPower(power, 0); + return -curPower; + } + + int32 maxPower = (int32)GetMaxPower(power); + + if (val < maxPower) + { + SetPower(power, val); + gain = val - curPower; + } + else if (curPower != maxPower) + { + SetPower(power, maxPower); + gain = maxPower - curPower; + } + + return gain; +} + +bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool /*inVisibleList*/, bool* alert) const +{ + if (!u || !IsInMap(u)) + return false; + + // Always can see self + if (u == this) + return true; + + bool at_same_transport = GetTransport() && GetTransport() == u->GetTransport(); + + // not in world + if (!at_same_transport && (!IsInWorld() || !u->IsInWorld())) + return false; + + // forbidden to seen (at GM respawn command) + if (m_Visibility == VISIBILITY_RESPAWN) + return false; + + Map& _map = *u->GetMap(); + bool isTargetPlayer = u->GetTypeId() == TYPEID_PLAYER; + auto pPlayerTarget = isTargetPlayer ? (Player*)u : nullptr; + + // Grid dead/alive checks + if (isTargetPlayer) + { + // non visible at grid for any stealth state + if (!IsVisibleInGridForPlayer(pPlayerTarget)) + return false; + + // if player is dead then he can't detect anyone in any cases + if (!u->isAlive()) + detect = false; + } + else + { + // all dead creatures/players not visible for any creatures + if (!u->isAlive() || !isAlive()) + return false; + } + + // always seen by owner + if (GetCharmerOrOwnerGuid() == u->GetObjectGuid()) + return true; + + // isInvisibleForAlive() those units can only be seen by dead or if other + // unit is also invisible for alive.. if an isinvisibleforalive unit dies we + // should be able to see it too + if (u->isAlive() && isAlive() && isInvisibleForAlive() != u->isInvisibleForAlive()) + if (!isTargetPlayer || !pPlayerTarget->isGameMaster()) + return false; + + // redundant phasing + //if (!u->CanSeeInWorld(this)) + // return false; + + if (Creature* pCreature = (Creature*)ToCreature()) + { + bool bVisible = false; + if (pCreature->AI() && pCreature->AI()->IsVisibleFor(u, bVisible)) + return bVisible; + } + + // Visible units, always are visible for all units, except for units under invisibility + if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask == 0) + return true; + + // GMs see any players, not higher GMs and all units + if (isTargetPlayer && pPlayerTarget->isGameMaster()) + { + if (GetTypeId() == TYPEID_PLAYER) + return ToPlayer()->GetGMInvisibilityLevel() <= uint8(pPlayerTarget->GetSession()->GetSecurity()); + return true; + } + + // non faction visibility non-breakable for non-GMs + if (m_Visibility == VISIBILITY_OFF) + return false; + + // raw invisibility + bool invisible = m_invisibilityMask != 0; + + // detectable invisibility case + if (invisible && ( + // Invisible units, always are visible for units under same invisibility type + m_invisibilityMask & u->m_invisibilityMask || + // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect) + u->canDetectInvisibilityOf(this) || + // Units that can detect invisibility always are visible for units that can be detected + canDetectInvisibilityOf(u))) + invisible = false; + + // special cases for always overwrite invisibility/stealth + if (invisible || m_Visibility == VISIBILITY_GROUP_STEALTH) + { + // non-hostile case + if (!u->IsHostileTo(this)) + { + // player see other player with stealth/invisibility only if he in same group or raid or same team (raid/team case dependent from conf setting) + if (GetTypeId() == TYPEID_PLAYER && isTargetPlayer) + { + if (((Player*)this)->IsGroupVisibleFor(pPlayerTarget)) + return true; + + // else apply same rules as for hostile case (detecting check for stealth) + } + } + + // none other cases for detect invisibility, so invisible + if (invisible) + return false; + + // else apply stealth detecting check + } + + // unit got in stealth in this moment and must ignore old detected state + if (m_Visibility == VISIBILITY_GROUP_NO_DETECT) + return false; + + // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible + if (m_Visibility != VISIBILITY_GROUP_STEALTH) + return true; + + // NOW ONLY STEALTH CASE + //if in non-detect mode then invisible for unit + //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false) + //players detect players only in Player::HandleStealthedUnitsDetection() + // Units detect Units only in Units::HandleStealthedUnitsDetection() + if (!detect) + return isTargetPlayer ? pPlayerTarget->IsInVisibleList(this) : false; + + // Special cases + if (!u->canDetectStealthOf(this, GetDistance(viewPoint), alert)) + return false; + + // Now check if target is visible with LoS + float ox, oy, oz; + viewPoint->GetPosition(ox, oy, oz); + return IsWithinLOS(ox, oy, oz); +} + +void Unit::UpdateVisibilityAndView() +{ + + static const AuraType auratypes[] = {SPELL_AURA_BIND_SIGHT, SPELL_AURA_FAR_SIGHT, SPELL_AURA_NONE}; + for (AuraType const* type = &auratypes[0]; *type != SPELL_AURA_NONE; ++type) + { + AuraList& alist = m_modAuras[*type]; + if (alist.empty()) + continue; + + for (AuraList::iterator it = alist.begin(); it != alist.end();) + { + Aura* aura = (*it); + Unit* owner = aura->GetCaster(); + + if (!owner || !isVisibleForOrDetect(owner, this, false)) + { + alist.erase(it); + RemoveAura(aura); + it = alist.begin(); + } + else + ++it; + } + } + + GetViewPoint().Call_UpdateVisibilityForOwner(); + UpdateObjectVisibility(); + ScheduleAINotify(0); + GetViewPoint().Event_ViewPointVisibilityChanged(); +} + +void Unit::SetVisibility(UnitVisibility x) +{ + m_Visibility = x; + + if (IsInWorld()) + UpdateVisibilityAndView(); +} + +bool Unit::canDetectInvisibilityOf(Unit const* u) const +{ + if (!u->m_invisibilityMask && m_detectInvisibilityMask) + return true; + + if (const Creature* worldBoss = u->ToCreature()) + if (worldBoss->IsWorldBoss()) + return true; + + if (uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask)) + { + for (int32 i = 0; i < 32; ++i) + { + if (((1 << i) & mask) == 0) + continue; + + // find invisibility level + int32 invLevel = 0; + Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY); + for (Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr) + if ((*itr)->GetModifier()->m_miscvalue == i && invLevel < (*itr)->GetModifier()->m_amount) + invLevel = (*itr)->GetModifier()->m_amount; + + // find invisibility detect level + int32 detectLevel = 0; + Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION); + for (Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr) + if ((*itr)->GetModifier()->m_miscvalue == i && detectLevel < (*itr)->GetModifier()->m_amount) + detectLevel = (*itr)->GetModifier()->m_amount; + + if (i == 6 && GetTypeId() == TYPEID_PLAYER) // special drunk detection case + detectLevel = ((Player*)this)->GetDrunkValue(); + + if (invLevel <= detectLevel) + return true; + } + } + + return false; +} + +bool Unit::canDetectStealthOf(Unit const* target, float distance, bool *alert) const +{ + if (hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED)) + return false; + if (distance < 0.388f) //collision + return true; + + // Hunter mark functionality + AuraList const& auras = target->GetAurasByType(SPELL_AURA_MOD_STALKED); + for (AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) + if ((*iter)->GetCasterGuid() == GetObjectGuid()) + return true; + + // set max distance + float MaxStealthDetectRange = sWorld.getConfig(CONFIG_FLOAT_MAX_PLAYERS_STEALTH_DETECT_RANGE); + float visibleDistance = IsPlayer() ? MaxStealthDetectRange : ((Creature*)this)->GetAttackDistance(target); + + //Always invisible from back (when stealth detection is on), also filter max distance cases + bool isInFront = distance < visibleDistance && HasInArc(M_PI_F, target); + if (!isInFront) + return false; + + visibleDistance = 10.5f - target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH) / 100.0f; + + //Visible distance is modified by + //-Level Diff (every level diff = 1.0f in visible distance) + int32 level_diff = int32(GetLevelForTarget(target)) - int32(target->GetLevelForTarget(this)); + if (abs(level_diff) > 3) + visibleDistance += level_diff; + else + visibleDistance += 0.5f * level_diff; + + //This allows to check talent tree and will add addition stealth dependent on used points) + int32 stealthMod = target->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL); + if (stealthMod < 0) + stealthMod = 0; + + //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia) + //based on wowwiki every 5 mod we have 1 more level diff in calculation + visibleDistance += (int32(GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_STEALTH_DETECT, 0)) - stealthMod) / 5.0f; + visibleDistance = visibleDistance > MaxStealthDetectRange ? MaxStealthDetectRange : visibleDistance; + + // recheck new distance + if (visibleDistance <= 0 || distance > visibleDistance) + { + if (alert && distance < 15.0f /*TODO: add MAX ALERT DISTANCE config*/) + { + visibleDistance = visibleDistance * 1.08f + 1.5f; + *alert = distance < visibleDistance; + } + return false; + } + + return true; +} + +void Unit::UpdateSpeed(UnitMoveType mtype, bool forced, float ratio) +{ + // not in combat pet have same speed as owner + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet() && hasUnitState(UNIT_STAT_FOLLOW) && !isInCombat()) + { + if (Unit* owner = GetOwner()) + { + switch(mtype) + { + case MOVE_RUN: + case MOVE_WALK: + case MOVE_SWIM: + SetSpeedRate(mtype, owner->GetSpeedRate(mtype), forced); + return; + default: + break; + } + } + } + + int32 main_speed_mod = 0; + float stack_bonus = 1.0f; + float non_stack_bonus = 1.0f; + + switch (mtype) + { + case MOVE_WALK: + break; + case MOVE_RUN: + { + if (IsMounted()) // Use on mount auras + { + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED); + stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS); + non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK)) / 100.0f; + } + else + { + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED); + stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS); + non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK)) / 100.0f; + } + break; + } + case MOVE_RUN_BACK: + return; + case MOVE_SWIM: + { + main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED); + break; + } + case MOVE_SWIM_BACK: + return; + default: + sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype); + return; + } + + float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus; + // now we ready for speed calculation + float speed = main_speed_mod ? bonus * (100.0f + main_speed_mod) / 100.0f : bonus; + + switch (mtype) + { + case MOVE_RUN: + case MOVE_SWIM: + { + // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need + // TODO: possible affect only on MOVE_RUN + if (int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED)) + { + // Use speed from aura + float max_speed = normalization / baseMoveSpeed[mtype]; + if (speed > max_speed) + speed = max_speed; + } + break; + } + default: + break; + } + + // for creature case, we check explicit if mob searched for assistance + if (GetTypeId() == TYPEID_UNIT) + { + if (((Creature*)this)->HasSearchedAssistance()) + speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk". + } + // for player case, we look for some custom rates + else + { + if (getDeathState() == CORPSE) + speed *= sWorld.getConfig(((Player*)this)->InBattleGround() ? CONFIG_FLOAT_GHOST_RUN_SPEED_BG : CONFIG_FLOAT_GHOST_RUN_SPEED_WORLD); + } + + // Apply strongest slow aura mod to speed + int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED); + if (slow) + speed *= (100.0f + slow) / 100.0f; + + if (GetTypeId() == TYPEID_UNIT) + { + Creature* pCreature = (Creature*)this; + if (!(pCreature->IsPet() && pCreature->GetOwnerGuid().IsPlayer())) // don't use DB values for player controlled pets + { + switch (mtype) + { + case MOVE_RUN: + speed *= ((Creature*)this)->GetCreatureInfo()->speed_run; + break; + case MOVE_WALK: + speed *= ((Creature*)this)->GetCreatureInfo()->speed_walk; + break; + default: + break; + } + } + else + speed *= 1.14286f; // normalized player pet runspeed + } + + SetSpeedRate(mtype, speed * ratio, forced); +} + +float Unit::GetSpeed(UnitMoveType mtype) const +{ + return m_speed_rate[mtype] * baseMoveSpeed[mtype]; +} + +float Unit::GetXZFlagBasedSpeed(const Unit *unit) const +{ + if (!unit->HasUnitMovementFlag(MOVEFLAG_MASK_XZ)) + return 0.0f; + + if (unit->IsSwimming()) + { + if (unit->HasUnitMovementFlag(MOVEFLAG_BACKWARD)) + return unit->GetSpeed(MOVE_SWIM_BACK); + + return unit->GetSpeed(MOVE_SWIM); + } + + if (unit->IsWalking()) + { + // Seems to always be same speed forward and backward when walking + return unit->GetSpeed(MOVE_WALK); + } + + // Presumably only running left when IsMoving is true + if (unit->HasUnitMovementFlag(MOVEFLAG_BACKWARD)) + return unit->GetSpeed(MOVE_RUN_BACK); + + return unit->GetSpeed(MOVE_RUN); +} + +struct SetSpeedRateHelper +{ + explicit SetSpeedRateHelper(UnitMoveType _mtype, bool _forced) : mtype(_mtype), forced(_forced) {} + void operator()(Unit* unit) const + { + unit->UpdateSpeed(mtype, forced); + } + UnitMoveType mtype; + bool forced; +}; + +void Unit::SetSpeedRate(UnitMoveType mtype, float rate, bool forced) +{ + if (rate <= 0) + rate = 1.0f; + + // Update speed only on change + if (m_speed_rate[mtype] != rate) + { + m_speed_rate[mtype] = rate; + + const uint16 SetSpeed2Opc_table[MAX_MOVE_TYPE][2] = + { + {MSG_MOVE_SET_WALK_SPEED, SMSG_FORCE_WALK_SPEED_CHANGE}, + {MSG_MOVE_SET_RUN_SPEED, SMSG_FORCE_RUN_SPEED_CHANGE}, + {MSG_MOVE_SET_RUN_BACK_SPEED, SMSG_FORCE_RUN_BACK_SPEED_CHANGE}, + {MSG_MOVE_SET_SWIM_SPEED, SMSG_FORCE_SWIM_SPEED_CHANGE}, + {MSG_MOVE_SET_SWIM_BACK_SPEED, SMSG_FORCE_SWIM_BACK_SPEED_CHANGE}, + {MSG_MOVE_SET_TURN_RATE, SMSG_FORCE_TURN_RATE_CHANGE}, + }; + + if (forced) + { + if (Player* me = GetAffectingPlayer()) + { + WorldPacket dataForMe(SetSpeed2Opc_table[mtype][1], 18); + dataForMe << GetPackGUID(); + dataForMe << uint32(0); + dataForMe << float(GetSpeed(mtype)); + me->GetSession()->SendPacket(&dataForMe); + me->GetCheatData()->OrderSent(&dataForMe); + //if (this == me) + //if (WardenInterface* warden = me->GetSession()->GetWarden()) + //warden->SendSpeedChange(mtype, GetSpeed(mtype)); + } + } + + + // TODO: Actually such opcodes should (always?) be packed with SMSG_COMPRESSED_MOVES + // Nostalrius: (google translated) + // Unable to send here the package 'MSG_MOVE_SET _ * _ SPEED', because we do not know the flags of movements, and the position dimension client + // (update every 0.5 sec). If one sends a packet, one leads to a desynchro (in the absence of interpolation of the position) + // This package will be sent after receiving a packet type 'CMSG_FORCE _ * _ SPEED_CHANGE_ACK' (MovementHandler.cpp) + //m_updateFlag |= UPDATEFLAG_LIVING; // Mise a jour des mouvements en cours, spline, vitesses, etc ... Inutile ? + + propagateSpeedChange(); + } + + CallForAllControlledUnits(SetSpeedRateHelper(mtype, forced), CONTROLLED_PET | CONTROLLED_GUARDIANS | CONTROLLED_CHARM | CONTROLLED_MINIPET); +} + +void Unit::SetHover(bool on) +{ + if (on) + CastSpell(this, 11010, true); + else + RemoveAurasDueToSpell(11010); +} + +void Unit::SetDeathState(DeathState s) +{ + if (s != ALIVE && s != JUST_ALIVED) + { + CombatStop(); + DeleteThreatList(); + ClearComboPointHolders(); // any combo points pointed to unit lost at it death + + if (IsNonMeleeSpellCasted(false)) + InterruptNonMeleeSpells(false); + } + + m_deathState = s; + if (s == JUST_DIED) + { + RemoveAllAurasOnDeath(); + UnsummonAllTotems(); + + i_motionMaster.Clear(false, true); + i_motionMaster.MoveIdle(); + StopMoving(true); + + ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false); + // remove aurastates allowing special moves + ClearAllReactives(); + ClearDiminishings(); + } + else if (s == JUST_ALIVED || s == ALIVE) + { + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground) + } + + if (m_deathState != ALIVE && s == ALIVE) + { + //_ApplyAllAuraMods(); + } +} + +/*######################################## +######## ######## +######## AGGRO SYSTEM ######## +######## ######## +########################################*/ + +bool Unit::CanHaveThreatList() const +{ + // only creatures can have threat list + if (GetTypeId() != TYPEID_UNIT) + return false; + + // only alive units can have threat list + if (!isAlive()) + return false; + + Creature const* creature = ((Creature const*)this); + + // totems can not have threat list + if (creature->IsTotem()) + return false; + + // pets can not have a threat list, unless they are controlled by a creature + if (creature->IsPet() && creature->GetOwnerGuid().IsPlayer()) + return false; + + // charmed units can not have a threat list if charmed by player + if (creature->GetCharmerGuid().IsPlayer()) + return false; + + if (creature->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_THREAT_LIST) + return false; + + return true; +} + +//====================================================================== + +float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask) +{ + if (!HasAuraType(SPELL_AURA_MOD_THREAT)) + return threat; + + if (schoolMask == SPELL_SCHOOL_MASK_NONE) + return threat; + + SpellSchools school = GetFirstSchoolInMask(schoolMask); + + return threat * m_threatModifier[school]; +} + +//====================================================================== + +void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false*/, SpellSchoolMask schoolMask /*= SPELL_SCHOOL_MASK_NONE*/, SpellEntry const *threatSpell /*= NULL*/) +{ + // Only mobs can manage threat lists + if (CanHaveThreatList()) + m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell, false); +} + +//====================================================================== + +void Unit::DeleteThreatList() +{ + m_ThreatManager.clearReferences(); +} + +//====================================================================== + +void Unit::TauntApply(Unit* taunter) +{ + MANGOS_ASSERT(GetTypeId() == TYPEID_UNIT); + + if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster())) + return; + + if (!CanHaveThreatList()) + return; + + Unit *target = getVictim(); + + if (target && target == taunter) + return; + // Nostalrius : Correction bug sheep/fear + if (!HasAuraType(SPELL_AURA_MOD_FEAR) && !HasAuraType(SPELL_AURA_MOD_CONFUSE)) + { + SetInFront(taunter); + OnEnterCombat(taunter, !isInCombat()); + + if (((Creature*)this)->AI()) + ((Creature*)this)->AI()->AttackStart(taunter); + } + + m_ThreatManager.tauntApply(taunter); +} + +//====================================================================== + +void Unit::TauntFadeOut(Unit *taunter) +{ + MANGOS_ASSERT(GetTypeId() == TYPEID_UNIT); + + if (!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster())) + return; + + if (!CanHaveThreatList()) + return; + + Unit *target = getVictim(); + + if (!target || target != taunter) + return; + + if (m_ThreatManager.isThreatListEmpty()) + { + // Nostalrius - pas d'evade quand on charm quelque chose. + if (!GetCharmGuid()) + OnLeaveCombat(); + return; + } + + m_ThreatManager.tauntFadeOut(taunter); + target = m_ThreatManager.getHostileTarget(); + + // Nostalrius : Correction bug sheep/fear + if (target && target != taunter && !HasAuraType(SPELL_AURA_MOD_FEAR) && !HasAuraType(SPELL_AURA_MOD_CONFUSE)) + { + SetInFront(target); + OnEnterCombat(target, false); + } +} + +//====================================================================== + +bool Unit::SelectHostileTarget() +{ + //function provides main threat functionality + //next-victim-selection algorithm and evade mode are called + //threat list sorting etc. + + MANGOS_ASSERT(GetTypeId() == TYPEID_UNIT); + + if (!this->isAlive()) + return false; + + //This function only useful once AI has been initialized + if (!((Creature*)this)->AI()) + return false; + + // Nostalrius: delai de 5 sec avant attaque apres spawn. + if (ToCreature()->IsTempPacified()) + return false; + + Unit* target = nullptr; + + // First checking if we have some taunt on us + const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT); + if (!tauntAuras.empty()) + { + Unit* caster; + + // The last taunt aura caster is alive an we are happy to attack him + if ((caster = tauntAuras.back()->GetCaster()) && caster->isAlive()) + return true; + else if (tauntAuras.size() > 1) + { + // We do not have last taunt aura caster but we have more taunt auras, + // so find first available target + + // Auras are pushed_back, last caster will be on the end + AuraList::const_iterator aura = --tauntAuras.end(); + do + { + --aura; + if ((caster = (*aura)->GetCaster()) && caster->IsInMap(this) && caster->isTargetableForAttack()) + { + target = caster; + break; + } + } + while (aura != tauntAuras.begin()); + } + } + + // No taunt aura or taunt aura caster is dead, standard target selection + if (!target && !m_ThreatManager.isThreatListEmpty()) + target = m_ThreatManager.getHostileTarget(); + + if (target) + { + // Nostalrius : Correction bug sheep/fear + if (!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED | UNIT_STAT_DIED | UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING) && (!HasAuraType(SPELL_AURA_MOD_FEAR) || HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) && !HasAuraType(SPELL_AURA_MOD_CONFUSE)) + { + SetInFront(target); + ((Creature*)this)->AI()->AttackStart(target); + } + return true; + } + + // no target but something prevent go to evade mode // Nostalrius - fix evade quand CM. + if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) || GetCharmerGuid()) + return false; + + // last case when creature don't must go to evade mode: + // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list + // for example at owner command to pet attack some far away creature + // Note: creature not have targeted movement generator but have attacker in this case + if (GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE) + { + for (AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr) + { + if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack()) + return false; + } + } + + // enter in evade mode in other case + OnLeaveCombat(); + return false; +} + +//====================================================================== +//====================================================================== +//====================================================================== + +int32 Unit::CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, SpellEffectIndex effect_index, int32 const* effBasePoints, Spell* spell) +{ + Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL; + + uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0; + + int32 level = int32(getLevel()); + if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0) + level = (int32)spellProto->maxLevel; + else if (level < (int32)spellProto->baseLevel) + level = (int32)spellProto->baseLevel; + level -= (int32)spellProto->spellLevel; + + int32 baseDice = int32(spellProto->EffectBaseDice[effect_index]); + float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index]; + float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index]; + int32 basePoints = effBasePoints + ? *effBasePoints - baseDice + : spellProto->EffectBasePoints[effect_index]; + + basePoints += int32(level * basePointsPerLevel); + int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel); + float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index]; + + switch (randomPoints) + { + case 0: + case 1: + basePoints += baseDice; + break; // range 1..1 + default: + { + // range can have positive (1..rand) and negative (rand..1) values, so order its for irand + int32 randvalue = baseDice >= randomPoints + ? irand(randomPoints, baseDice) + : irand(baseDice, randomPoints); + + basePoints += randvalue; + break; + } + } + + int32 value = basePoints; + + // random damage + if (comboDamage != 0 && unitPlayer && target && (target->GetObjectGuid() == unitPlayer->GetComboTargetGuid())) + value += (int32)(comboDamage * comboPoints); + + if (Player* modOwner = GetSpellModOwner()) + { + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value, spell); + + switch (effect_index) + { + case EFFECT_INDEX_0: + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value, spell); + break; + case EFFECT_INDEX_1: + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value, spell); + break; + case EFFECT_INDEX_2: + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value, spell); + break; + } + } + + if (spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel && + spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE && + spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK && + (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED)) + value = int32(value * 0.25f * exp(getLevel() * (70 - spellProto->spellLevel) / 1000.0f)); + + return value; +} + +DiminishingLevels Unit::GetDiminishing(DiminishingGroup group) +{ + for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) + { + if (i->DRGroup != group) + continue; + + if (!i->hitCount) + return DIMINISHING_LEVEL_1; + + if (!i->hitTime) + return DIMINISHING_LEVEL_1; + + // If last spell was casted more than 15 seconds ago - reset the count. + if (i->stack == 0 && WorldTimer::getMSTimeDiff(i->hitTime, WorldTimer::getMSTime()) > 15 * IN_MILLISECONDS) + { + i->hitCount = DIMINISHING_LEVEL_1; + return DIMINISHING_LEVEL_1; + } + // or else increase the count. + else + return DiminishingLevels(i->hitCount); + } + return DIMINISHING_LEVEL_1; +} + +void Unit::IncrDiminishing(DiminishingGroup group) +{ + // Checking for existing in the table + for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) + { + if (i->DRGroup != group) + continue; + if (i->hitCount < DIMINISHING_LEVEL_IMMUNE) + i->hitCount += 1; + return; + } + m_Diminishing.push_back(DiminishingReturn(group, WorldTimer::getMSTime(), DIMINISHING_LEVEL_2)); +} + +bool Unit::IsLikePlayer() const +{ + if (IsPlayer()) + return true; + if (!IsPet()) + return false; + // Pet creature. Reste a savoir si ce machin appartient a un joueur. + Pet* pet = ((Pet*)this); + if (!pet->isControlled()) + return false; + return pet->GetOwnerGuid().IsPlayer(); +} + +void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration, Unit* caster, DiminishingLevels Level, bool isReflected) +{ + if (duration == -1 || group == DIMINISHING_NONE || (!isReflected && caster->IsFriendlyTo(this))) + return; + + float mod = 1.0f; + + // Some diminishings applies to mobs too (for example, Stun) + // Nostalrius: fix DR sur les pets. + bool pvp = (IsLikePlayer() && caster->IsLikePlayer()); + if ((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && pvp) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL) + { + DiminishingLevels diminish = Level; + switch (diminish) + { + case DIMINISHING_LEVEL_1: + break; + case DIMINISHING_LEVEL_2: + mod = 0.5f; + break; + case DIMINISHING_LEVEL_3: + mod = 0.25f; + break; + case DIMINISHING_LEVEL_IMMUNE: + mod = 0.0f; + break; + default: + break; + } + } + + duration = int32(duration * mod); +} + +void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) +{ + // Checking for existing in the table + for (Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i) + { + if (i->DRGroup != group) + continue; + + if (apply) + i->stack += 1; + else if (i->stack) + { + i->stack -= 1; + // Remember time after last aura from group removed + if (i->stack == 0) + i->hitTime = WorldTimer::getMSTime(); + } + break; + } +} + +bool Unit::isVisibleForInState(Player const* u, WorldObject const* viewPoint, bool inVisibleList) const +{ + return isVisibleForOrDetect(u, viewPoint, false, inVisibleList); +} + +/// returns true if creature can't be seen by alive units +bool Unit::isInvisibleForAlive() const +{ + if (m_AuraFlags & UNIT_AURAFLAG_ALIVE_INVISIBLE) + return true; + // TODO: maybe spiritservices also have just an aura + return isSpiritService(); +} + +uint32 Unit::GetCreatureType() const +{ + if (GetTypeId() == TYPEID_PLAYER) + { + SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(GetShapeshiftForm()); + if (ssEntry && ssEntry->creatureType > 0) + return ssEntry->creatureType; + else + return CREATURE_TYPE_HUMANOID; + } + else + return ((Creature*)this)->GetCreatureInfo()->type; +} + +/*####################################### +######## ######## +######## STAT SYSTEM ######## +######## ######## +#######################################*/ + +bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply) +{ + if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END) + { + sLog.outError("ERROR in HandleStatModifier(): nonexistent UnitMods or wrong UnitModifierType!"); + return false; + } + + float val = 1.0f; + + switch (modifierType) + { + case BASE_VALUE: + case TOTAL_VALUE: + m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount; + break; + case BASE_PCT: + case TOTAL_PCT: + if (amount <= -100.0f) //small hack-fix for -100% modifiers + amount = -200.0f; + + val = (100.0f + amount) / 100.0f; + m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f / val); + break; + + default: + break; + } + + if (!CanModifyStats()) + return false; + + switch (unitMod) + { + case UNIT_MOD_STAT_STRENGTH: + case UNIT_MOD_STAT_AGILITY: + case UNIT_MOD_STAT_STAMINA: + case UNIT_MOD_STAT_INTELLECT: + case UNIT_MOD_STAT_SPIRIT: + UpdateStats(GetStatByAuraGroup(unitMod)); + break; + + case UNIT_MOD_ARMOR: + UpdateArmor(); + break; + case UNIT_MOD_HEALTH: + UpdateMaxHealth(); + break; + + case UNIT_MOD_MANA: + case UNIT_MOD_RAGE: + case UNIT_MOD_FOCUS: + case UNIT_MOD_ENERGY: + case UNIT_MOD_HAPPINESS: + UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); + break; + + case UNIT_MOD_RESISTANCE_HOLY: + case UNIT_MOD_RESISTANCE_FIRE: + case UNIT_MOD_RESISTANCE_NATURE: + case UNIT_MOD_RESISTANCE_FROST: + case UNIT_MOD_RESISTANCE_SHADOW: + case UNIT_MOD_RESISTANCE_ARCANE: + UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); + break; + + case UNIT_MOD_ATTACK_POWER: + UpdateAttackPowerAndDamage(); + break; + case UNIT_MOD_ATTACK_POWER_RANGED: + UpdateAttackPowerAndDamage(true); + break; + + case UNIT_MOD_DAMAGE_MAINHAND: + UpdateDamagePhysical(BASE_ATTACK); + break; + case UNIT_MOD_DAMAGE_OFFHAND: + UpdateDamagePhysical(OFF_ATTACK); + break; + case UNIT_MOD_DAMAGE_RANGED: + UpdateDamagePhysical(RANGED_ATTACK); + break; + + default: + break; + } + + return true; +} + +float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const +{ + if (unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END) + { + sLog.outError("attempt to access nonexistent modifier value from UnitMods!"); + return 0.0f; + } + + if (modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f) + return 0.0f; + + return m_auraModifiersGroup[unitMod][modifierType]; +} + +float Unit::GetTotalStatValue(Stats stat) const +{ + UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat); + + if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f) + return 0.0f; + + // value = ((base_value * base_pct) + total_value) * total_pct + float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat); + value *= m_auraModifiersGroup[unitMod][BASE_PCT]; + value += m_auraModifiersGroup[unitMod][TOTAL_VALUE]; + value *= m_auraModifiersGroup[unitMod][TOTAL_PCT]; + + return value; +} + +float Unit::GetTotalAuraModValue(UnitMods unitMod) const +{ + if (unitMod >= UNIT_MOD_END) + { + sLog.outError("attempt to access nonexistent UnitMods in GetTotalAuraModValue()!"); + return 0.0f; + } + + if (m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f) + return 0.0f; + + float value = m_auraModifiersGroup[unitMod][BASE_VALUE]; + value *= m_auraModifiersGroup[unitMod][BASE_PCT]; + value += m_auraModifiersGroup[unitMod][TOTAL_VALUE]; + value *= m_auraModifiersGroup[unitMod][TOTAL_PCT]; + + return value; +} + +SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const +{ + SpellSchools school = SPELL_SCHOOL_NORMAL; + + switch (unitMod) + { + case UNIT_MOD_RESISTANCE_HOLY: + school = SPELL_SCHOOL_HOLY; + break; + case UNIT_MOD_RESISTANCE_FIRE: + school = SPELL_SCHOOL_FIRE; + break; + case UNIT_MOD_RESISTANCE_NATURE: + school = SPELL_SCHOOL_NATURE; + break; + case UNIT_MOD_RESISTANCE_FROST: + school = SPELL_SCHOOL_FROST; + break; + case UNIT_MOD_RESISTANCE_SHADOW: + school = SPELL_SCHOOL_SHADOW; + break; + case UNIT_MOD_RESISTANCE_ARCANE: + school = SPELL_SCHOOL_ARCANE; + break; + + default: + break; + } + + return school; +} + +Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const +{ + Stats stat = STAT_STRENGTH; + + switch (unitMod) + { + case UNIT_MOD_STAT_STRENGTH: + stat = STAT_STRENGTH; + break; + case UNIT_MOD_STAT_AGILITY: + stat = STAT_AGILITY; + break; + case UNIT_MOD_STAT_STAMINA: + stat = STAT_STAMINA; + break; + case UNIT_MOD_STAT_INTELLECT: + stat = STAT_INTELLECT; + break; + case UNIT_MOD_STAT_SPIRIT: + stat = STAT_SPIRIT; + break; + + default: + break; + } + + return stat; +} + +Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const +{ + switch (unitMod) + { + case UNIT_MOD_MANA: + return POWER_MANA; + case UNIT_MOD_RAGE: + return POWER_RAGE; + case UNIT_MOD_FOCUS: + return POWER_FOCUS; + case UNIT_MOD_ENERGY: + return POWER_ENERGY; + case UNIT_MOD_HAPPINESS: + return POWER_HAPPINESS; + default: + return POWER_MANA; + } + + return POWER_MANA; +} + +float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const +{ + if (attType == RANGED_ATTACK) + { + int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS); + if (ap < 0) + return 0.0f; + return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER)); + } + else + { + int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS); + if (ap < 0) + return 0.0f; + return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER)); + } +} + +float Unit::GetWeaponDamageRange(WeaponAttackType attType, WeaponDamageRange damageRange, uint8 index) const +{ + if (attType == OFF_ATTACK && !haveOffhandWeapon()) + return 0.0f; + + return m_weaponDamage[attType][index].damage[damageRange]; +} + +void Unit::SetLevel(uint32 lvl) +{ + SetUInt32Value(UNIT_FIELD_LEVEL, lvl); + + // group update + if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL); +} + +void Unit::SetHealth(uint32 val) +{ + uint32 maxHealth = GetMaxHealth(); + if (maxHealth < val) + val = maxHealth; + + SetUInt32Value(UNIT_FIELD_HEALTH, val); + ForceValuesUpdateAtIndex(UNIT_FIELD_MAXHEALTH); // Necessaire pour script qui cache PV aux joueurs. + + // group update + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP); + } + } +} + +void Unit::SetMaxHealth(uint32 val) +{ + uint32 health = GetHealth(); + SetUInt32Value(UNIT_FIELD_MAXHEALTH, val); + ForceValuesUpdateAtIndex(UNIT_FIELD_HEALTH); // Cf plus haut. + + // group update + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP); + } + } + + if (val < health) + SetHealth(val); +} + +void Unit::SetHealthPercent(float percent) +{ + uint32 newHealth = GetMaxHealth() * percent / 100.0f; + SetHealth(newHealth); +} + +void Unit::SetPower(Powers power, uint32 val) +{ + if (GetPower(power) == val) + return; + + uint32 maxPower = GetMaxPower(power); + if (maxPower < val) + val = maxPower; + + SetStatInt32Value(UNIT_FIELD_POWER1 + power, val); + + // group update + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER); + } + + // Update the pet's character sheet with happiness damage bonus + if (pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS) + pet->UpdateDamagePhysical(BASE_ATTACK); + } +} + +void Unit::SetMaxPower(Powers power, uint32 val) +{ + uint32 cur_power = GetPower(power); + SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val); + + // group update + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER); + } + } + + if (val < cur_power) + SetPower(power, val); +} + +void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply) +{ + ApplyModUInt32Value(UNIT_FIELD_POWER1 + power, val, apply); + + // group update + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER); + } + } +} + +void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply) +{ + ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1 + power, val, apply); + + // group update + if (GetTypeId() == TYPEID_PLAYER) + { + if (((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER); + } + else if (((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER); + } + } +} + +void Unit::ApplyAuraProcTriggerDamage(Aura* aura, bool apply) +{ + AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE]; + if (apply) + tAuraProcTriggerDamage.push_back(aura); + else + tAuraProcTriggerDamage.remove(aura); +} + +uint32 Unit::GetCreatePowers(Powers power) const +{ + switch (power) + { + case POWER_HEALTH: + return 0; // is it really should be here? + case POWER_MANA: + return GetCreateMana(); + case POWER_RAGE: + return 1000; + case POWER_FOCUS: + return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 100); + case POWER_ENERGY: + return 100; + case POWER_HAPPINESS: + return (GetTypeId() == TYPEID_PLAYER || !((Creature const*)this)->IsPet() || ((Pet const*)this)->getPetType() != HUNTER_PET ? 0 : 1050000); + } + + return 0; +} + +void Unit::AddToWorld() +{ + Object::AddToWorld(); + ScheduleAINotify(0); +} + +void Unit::RemoveFromWorld() +{ + // cleanup + if (IsInWorld()) + { + Uncharm(); + RemoveNotOwnSingleTargetAuras(); + RemoveGuardians(); + RemoveAllGameObjects(); + RemoveAllDynObjects(); + CleanupDeletedAuras(); + GetViewPoint().Event_RemovedFromWorld(); + } + if (m_needUpdateVisibility && FindMap()) + { + FindMap()->RemoveRelocatedUnit(this); + m_needUpdateVisibility = false; + } + Object::RemoveFromWorld(); +} + +void Unit::CleanupsBeforeDelete() +{ + if (m_uint32Values) // only for fully created object + { + InterruptNonMeleeSpells(true); + m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList + CombatStop(); + ClearComboPointHolders(); + DeleteThreatList(); + if (getHostileRefManager().getOwner() == this) + { + if (GetTypeId() == TYPEID_PLAYER) + getHostileRefManager().setOnlineOfflineState(false); + else + getHostileRefManager().deleteReferences(); + } + RemoveAllAuras(AURA_REMOVE_BY_DELETE); + } + WorldObject::CleanupsBeforeDelete(); +} + +CharmInfo* Unit::InitCharmInfo(Unit *charm) +{ + if (!m_charmInfo) + m_charmInfo = new CharmInfo(charm); + return m_charmInfo; +} + +CharmInfo::CharmInfo(Unit* unit) + : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0), + _isCommandAttack(false), _isAtStay(false), _isFollowing(false), _isReturning(false), + _stayX(0.0f), _stayY(0.0f), _stayZ(0.0f), _isCommandFollow(false) +{ + for (int i = 0; i < CREATURE_MAX_SPELLS; ++i) + m_charmspells[i].SetActionAndType(0, ACT_DISABLED); +} + +void CharmInfo::InitPetActionBar() +{ + // the first 3 SpellOrActions are attack, follow and stay + for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i) + SetActionBar(ACTION_BAR_INDEX_START + i, COMMAND_ATTACK - i, ACT_COMMAND); + + // middle 4 SpellOrActions are spells/special attacks/abilities + for (uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END - ACTION_BAR_INDEX_PET_SPELL_START; ++i) + SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i, 0, ACT_DISABLED); + + // last 3 SpellOrActions are reactions + for (uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i) + SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i, COMMAND_ATTACK - i, ACT_REACTION); +} + +void CharmInfo::InitEmptyActionBar() +{ + SetActionBar(ACTION_BAR_INDEX_START, COMMAND_ATTACK, ACT_COMMAND); + for (uint32 x = ACTION_BAR_INDEX_START + 1; x < ACTION_BAR_INDEX_END; ++x) + SetActionBar(x, 0, ACT_PASSIVE); +} + +void CharmInfo::InitPossessCreateSpells() +{ + InitEmptyActionBar(); //charm action bar + + if (m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty + return; + + for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) + { + if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x])) + m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true); + else + AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE); + } +} + +void CharmInfo::InitCharmCreateSpells() +{ + if (m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells + { + //InitEmptyActionBar(); + InitPetActionBar(); + return; + } + + InitPetActionBar(); + + for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) + { + uint32 spellId = ((Creature*)m_unit)->m_spells[x]; + + if (!spellId) + { + m_charmspells[x].SetActionAndType(spellId, ACT_DISABLED); + continue; + } + + if (IsPassiveSpell(spellId)) + { + m_unit->CastSpell(m_unit, spellId, true); + m_charmspells[x].SetActionAndType(spellId, ACT_PASSIVE); + } + else + { + m_charmspells[x].SetActionAndType(spellId, ACT_DISABLED); + + ActiveStates newstate; + bool onlyselfcast = true; + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); + + if (!spellInfo) onlyselfcast = false; + for (uint32 i = 0; i < 3 && onlyselfcast; ++i) //nonexistent spell will not make any problems as onlyselfcast would be false -> break right away + { + if (spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0) + onlyselfcast = false; + } + + if (onlyselfcast || !IsPositiveSpell(spellId)) // only self cast and spells versus enemies are autocastable + newstate = ACT_DISABLED; + else + newstate = ACT_PASSIVE; + + AddSpellToActionBar(spellId, newstate); + } + } +} + +bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate) +{ + uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id); + + // new spell rank can be already listed + for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) + { + if (uint32 action = PetActionBar[i].GetAction()) + { + if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id) + { + PetActionBar[i].SetAction(spell_id); + return true; + } + } + } + + // or use empty slot in other case + for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) + { + if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell()) + { + SetActionBar(i, spell_id, newstate == ACT_DECIDE ? ACT_DISABLED : newstate); + return true; + } + } + return false; +} + +bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id) +{ + uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id); + + for (uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) + { + if (uint32 action = PetActionBar[i].GetAction()) + { + if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id) + { + SetActionBar(i, 0, ACT_DISABLED); + return true; + } + } + } + + return false; +} + +void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply) +{ + if (IsPassiveSpell(spellid)) + return; + + for (uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x) + if (spellid == m_charmspells[x].GetAction()) + m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED); +} + +void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow) +{ + m_petnumber = petnumber; + if (statwindow) + m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber); + else + m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0); +} + +void CharmInfo::LoadPetActionBar(const std::string& data) +{ + InitPetActionBar(); + + Tokens tokens = StrSplit(data, " "); + + if (tokens.size() != (ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_START) * 2) + return; // non critical, will reset to default + + int index; + Tokens::iterator iter; + for (iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index) + { + // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion + uint8 type = (uint8)atol((*iter).c_str()); + ++iter; + uint32 action = atol((*iter).c_str()); + + PetActionBar[index].SetActionAndType(action, ActiveStates(type)); + + // check correctness + if (PetActionBar[index].IsActionBarForSpell() && !sSpellMgr.GetSpellEntry(PetActionBar[index].GetAction())) + SetActionBar(index, 0, ACT_DISABLED); + } +} + +void CharmInfo::BuildActionBar(WorldPacket* data) +{ + for (uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) + *data << uint32(PetActionBar[i].packedData); +} + +void CharmInfo::SetSpellAutocast(uint32 spell_id, bool state) +{ + for (int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i) + { + if (spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell()) + { + PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED); + break; + } + } +} + +void CharmInfo::SetIsCommandAttack(bool val) +{ + _isCommandAttack = val; +} + +bool CharmInfo::IsCommandAttack() +{ + return _isCommandAttack; +} + +void CharmInfo::SetIsCommandFollow(bool val) +{ + _isCommandFollow = val; +} + +bool CharmInfo::IsCommandFollow() +{ + return _isCommandFollow; +} + +void CharmInfo::SaveStayPosition() +{ + //! At this point a new spline destination is enabled because of Unit::StopMoving() + G3D::Vector3 const stayPos = m_unit->movespline->FinalDestination(); + _stayX = stayPos.x; + _stayY = stayPos.y; + _stayZ = stayPos.z; +} + +void CharmInfo::GetStayPosition(float &x, float &y, float &z) +{ + x = _stayX; + y = _stayY; + z = _stayZ; +} + +void CharmInfo::SetIsAtStay(bool val) +{ + _isAtStay = val; +} + +bool CharmInfo::IsAtStay() +{ + return _isAtStay; +} + +void CharmInfo::SetIsFollowing(bool val) +{ + _isFollowing = val; +} + +bool CharmInfo::IsFollowing() +{ + return _isFollowing; +} + +void CharmInfo::SetIsReturning(bool val) +{ + _isReturning = val; +} + +bool CharmInfo::IsReturning() +{ + return _isReturning; +} + + +bool Unit::isFrozen() const +{ + return HasAuraState(AURA_STATE_FROZEN); +} + +uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition) +{ + uint32 procEx = PROC_EX_NONE; + switch (missCondition) + { + case SPELL_MISS_MISS: + procEx |= PROC_EX_MISS; + break; + case SPELL_MISS_RESIST: + procEx |= PROC_EX_RESIST; + break; + case SPELL_MISS_DODGE: + procEx |= PROC_EX_DODGE; + break; + case SPELL_MISS_PARRY: + procEx |= PROC_EX_PARRY; + break; + case SPELL_MISS_BLOCK: + procEx |= PROC_EX_BLOCK; + break; + case SPELL_MISS_EVADE: + procEx |= PROC_EX_EVADE; + break; + case SPELL_MISS_IMMUNE: + procEx |= PROC_EX_IMMUNE; + break; + case SPELL_MISS_IMMUNE2: + procEx |= PROC_EX_IMMUNE; + break; + case SPELL_MISS_DEFLECT: + procEx |= PROC_EX_DEFLECT; + break; + case SPELL_MISS_ABSORB: + procEx |= PROC_EX_ABSORB; + break; + case SPELL_MISS_REFLECT: + procEx |= PROC_EX_REFLECT; + // no break + case SPELL_MISS_NONE: + // On block + if (damageInfo->blocked) + procEx |= PROC_EX_BLOCK; + // On absorb + if (damageInfo->absorb) + procEx |= PROC_EX_ABSORB; + // On crit + if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT) + procEx |= PROC_EX_CRITICAL_HIT; + else + procEx |= PROC_EX_NORMAL_HIT; + break; + } + return procEx; +} + +void Unit::ProcDamageAndSpellFor(bool isVictim, Unit* pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const* procSpell, uint32 damage, ProcTriggeredList& triggeredList, Spell* spell) +{ + // For melee/ranged based attack need update skills and set some Aura states + if (procFlag & MELEE_BASED_TRIGGER_MASK && pTarget) + { + // Update skills here for players + if (GetTypeId() == TYPEID_PLAYER) + { + // On melee based hit/miss/resist need update skill (for victim and attacker) + if (procExtra & (PROC_EX_NORMAL_HIT | PROC_EX_MISS | PROC_EX_RESIST)) + { + if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER) + ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim); + } + // Update defence if player is victim and parry/dodge/block + if (isVictim && procExtra & (PROC_EX_DODGE | PROC_EX_PARRY | PROC_EX_BLOCK)) + ((Player*)this)->UpdateDefense(); + } + // If exist crit/parry/dodge/block need update aura state (for victim and attacker) + if (procExtra & (PROC_EX_CRITICAL_HIT | PROC_EX_PARRY | PROC_EX_DODGE | PROC_EX_BLOCK)) + { + // for victim + if (isVictim) + { + // if victim and dodge attack + if (procExtra & PROC_EX_DODGE) + { + //Update AURA_STATE on dodge + if (getClass() != CLASS_ROGUE) // skip Rogue Riposte + { + ModifyAuraState(AURA_STATE_DEFENSE, true); + StartReactiveTimer(REACTIVE_DEFENSE, pTarget->GetObjectGuid()); + } + } + // if victim and parry attack + if (procExtra & PROC_EX_PARRY) + { + // For Hunters only Counterattack (skip Mongoose bite) + if (getClass() == CLASS_HUNTER) + { + ModifyAuraState(AURA_STATE_HUNTER_PARRY, true); + StartReactiveTimer(REACTIVE_HUNTER_PARRY, pTarget->GetObjectGuid()); + ((Player*)this)->AddComboPoints(pTarget, 1); + } + else + { + ModifyAuraState(AURA_STATE_DEFENSE, true); + StartReactiveTimer(REACTIVE_DEFENSE, pTarget->GetObjectGuid()); + } + } + // if and victim block attack + if (procExtra & PROC_EX_BLOCK) + { + ModifyAuraState(AURA_STATE_DEFENSE, true); + StartReactiveTimer(REACTIVE_DEFENSE, pTarget->GetObjectGuid()); + } + } + else //For attacker + { + // Overpower on victim dodge + if (procExtra & PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR) + { + ((Player*)this)->AddComboPoints(pTarget, 1); + StartReactiveTimer(REACTIVE_OVERPOWER, pTarget->GetObjectGuid()); + } + } + } + } + DEBUG_UNIT(this, DEBUG_PROCS, "PROC: Flags 0x%.5x Ex 0x%.3x Spell %5u %s", procFlag, procExtra, procSpell ? procSpell->Id : 0, isVictim ? "[victim]" : ""); + + // Fill triggeredList list + for (SpellAuraHolderMap::const_iterator itr = GetSpellAuraHolderMap().begin(); itr != GetSpellAuraHolderMap().end(); ++itr) + { + // Can not proc on self. + if (procSpell && procSpell->Id == itr->first) + continue; + + // skip deleted auras (possible at recursive triggered call + if (itr->second->IsDeleted()) + continue; + + // Aura that applies a modifier with charges. Gere? otherwise. + bool hasmodifier = false; + for (int i = 0; i < 3; ++i) + if (itr->second->GetAuraByEffectIndex(SpellEffectIndex(i))) + if (SpellModifier* auraMod = itr->second->GetAuraByEffectIndex(SpellEffectIndex(i))->GetSpellModifier()) + if (auraMod->charges > 0 || (spell && spell->HasModifierApplied(auraMod))) + { + hasmodifier = true; + break; + } + if (hasmodifier) + continue; + + SpellProcEventEntry const* spellProcEvent = nullptr; + if (!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, spellProcEvent)) + continue; + + itr->second->SetInUse(true); // prevent holder deletion + triggeredList.push_back(ProcTriggeredData(spellProcEvent, itr->second, pTarget, procFlag)); + } +} + +SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const +{ + return SPELL_SCHOOL_MASK_NORMAL; +} + +Player* Unit::GetSpellModOwner() const +{ + if (GetTypeId() == TYPEID_PLAYER) + return (Player*)this; + if (((Creature*)this)->IsPet() || ((Creature*)this)->IsTotem()) + { + Unit* owner = GetOwner(); + if (owner && owner->GetTypeId() == TYPEID_PLAYER) + return (Player*)owner; + } + return nullptr; +} + +///----------Pet responses methods----------------- +void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg) +{ + if (msg == SPELL_CAST_OK) + return; + + Unit *owner = GetCharmerOrOwner(); + if (!owner || owner->GetTypeId() != TYPEID_PLAYER) + return; + + WorldPacket data(SMSG_PET_CAST_FAILED, 4 + 1 + 1); + data << uint32(spellid); + data << uint8(2); // 1.12: comme SMSG_CAST_FAILED je suppose. 2 = echec, 0 = reussi. + data << uint8(msg); + ((Player*)owner)->GetSession()->SendPacket(&data); +} + +void Unit::SendPetActionFeedback(uint8 msg) +{ + Unit* owner = GetOwner(); + if (!owner || owner->GetTypeId() != TYPEID_PLAYER) + return; + + WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1); + data << uint8(msg); + ((Player*)owner)->GetSession()->SendPacket(&data); +} + +void Unit::SendPetTalk(uint32 pettalk) +{ + Unit* owner = GetOwner(); + if (!owner || owner->GetTypeId() != TYPEID_PLAYER) + return; + + WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4); + data << GetObjectGuid(); + data << uint32(pettalk); + ((Player*)owner)->GetSession()->SendPacket(&data); +} + +void Unit::SendPetAIReaction() +{ + Unit* owner = GetOwner(); + if (!owner || owner->GetTypeId() != TYPEID_PLAYER) + return; + + WorldPacket data(SMSG_AI_REACTION, 8 + 4); + data << GetObjectGuid(); + data << uint32(AI_REACTION_HOSTILE); + ((Player*)owner)->GetSession()->SendPacket(&data); +} + +///----------End of Pet responses methods---------- + +void Unit::StopMoving(bool force) +{ + clearUnitState(UNIT_STAT_MOVING); + RemoveUnitMovementFlag(MOVEFLAG_MASK_MOVING); + // not need send any packets if not in world + if (!IsInWorld()) + return; + + Movement::MoveSplineInit init(*this, "StopMoving"); + if (Transport* t = GetTransport()) { + init.SetTransport(t->GetGUIDLow()); + } + + if (!movespline->Finalized() || force) { + init.SetStop(); // Will trigger CMSG_MOVE_SPLINE_DONE from client. + init.Launch(); + } + + DisableSpline(); +} + +void Unit::SetFleeing(bool apply, ObjectGuid casterGuid, uint32 spellID, uint32 time) +{ + if (apply && HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) + return; + + ModConfuseSpell(apply, casterGuid, spellID, MOV_MOD_FLEE_FOR_ASSISTANCE, time); +} + +void Unit::SetFeared(bool apply, ObjectGuid casterGuid, uint32 spellID, uint32 time) +{ + if (apply && HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) + return; + + ModConfuseSpell(apply, casterGuid, spellID, MOV_MOD_FLEE_IN_FEAR, time); +} + +void Unit::SetConfused(bool apply, ObjectGuid casterGuid, uint32 spellID) +{ + ModConfuseSpell(apply, casterGuid, spellID, MOV_MOD_CONFUSED, 0); +} + +void Unit::ModConfuseSpell(bool apply, ObjectGuid casterGuid, uint32 spellID, MovementModType modType, uint32 time) +{ + if (GetTypeId() == TYPEID_UNIT) + if (ToCreature()->IsTotem()) + return; + + bool controlFinished = true; + + if (HasAuraType(SPELL_AURA_MOD_CONFUSE)) + { + controlFinished = false; + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED); + } + else + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED); + + if (HasAuraType(SPELL_AURA_MOD_FEAR) && !HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) + { + controlFinished = false; + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); + } + else + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); + + m_movementInfo.moveFlags &= ~MOVEFLAG_MASK_MOVING_OR_TURN; + + if (apply) + { + CastStop(GetObjectGuid() == casterGuid ? spellID : 0); + + switch (modType) + { + case MOV_MOD_FLEE_FOR_ASSISTANCE: + { + Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : nullptr; + GetMotionMaster()->MoveFleeing(caster, time); + break; + } + case MOV_MOD_FLEE_IN_FEAR: + { + Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : nullptr; + GetMotionMaster()->MoveFeared(caster, time); + break; + } + case MOV_MOD_CONFUSED: + GetMotionMaster()->MoveConfused(); + break; + } + + if (casterGuid != GetObjectGuid()) + InterruptNonMeleeSpells(false); + + if (GetTypeId() == TYPEID_UNIT) + SetTargetGuid(ObjectGuid()); + } + else + { + switch (modType) + { + case MOV_MOD_FLEE_FOR_ASSISTANCE: + case MOV_MOD_FLEE_IN_FEAR: + { + if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING)) + GetMotionMaster()->ClearType(FLEEING_MOTION_TYPE); + break; + } + case MOV_MOD_CONFUSED: + if (!HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED)) + GetMotionMaster()->ClearType(CONFUSED_MOTION_TYPE); + break; + } + + // Si spellID=0, c'est pour interrompre (par exemple male de temerite - 704) + // Donc on retire les effets meme si on a encore un aura de fear. + if (!controlFinished && spellID) + return; + + if (GetTypeId() != TYPEID_PLAYER && isAlive()) + { + Unit* caster = IsInWorld() ? GetMap()->GetUnit(casterGuid) : nullptr; + if (caster) + AttackedBy(caster); + + // restore appropriate movement generator + if (!SelectHostileTarget()) + return; + + if (getVictim()) + SetTargetGuid(getVictim()->GetObjectGuid()); + + RestoreMovement(); + } + } +} + +void Unit::SetFeignDeath(bool apply, ObjectGuid casterGuid, uint32 /*spellID*/) +{ + // [TODO] SMSG_FEIGN_DEATH_RESISTED sert a quoi ? - il affiche 'Resiste' en notify. + if (apply) + { + m_movementInfo.RemoveMovementFlag(MOVEFLAG_MASK_MOVING_OR_TURN); + if (GetTypeId() != TYPEID_PLAYER) + StopMoving(); + + + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); + SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); + + addUnitState(UNIT_STAT_DIED); + CombatStop(); + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION); + + // prevent interrupt message + if (casterGuid == GetObjectGuid()) + FinishSpell(CURRENT_GENERIC_SPELL, false); + InterruptNonMeleeSpells(true); + getHostileRefManager().deleteReferences(); + } + else + { + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29); + // blizz like 2.0.x + //SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); [-ZERO] remove/replace ? + + RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); + + clearUnitState(UNIT_STAT_DIED); + + RestoreMovement(); + } +} + +bool Unit::IsSitState() const +{ + uint8 s = getStandState(); + return + s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR || + s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR || + s == UNIT_STAND_STATE_SIT; +} + +bool Unit::IsStandState() const +{ + uint8 s = getStandState(); + return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL; +} + +void Unit::SetStandState(uint8 state) +{ + if (GetByteValue(UNIT_FIELD_BYTES_1, 0) == state) + return; + + SetByteValue(UNIT_FIELD_BYTES_1, 0, state); + + if (IsStandState()) + RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED); + + if (GetTypeId() == TYPEID_PLAYER) + { + WorldPacket data(SMSG_STANDSTATE_UPDATE, 1); + data << (uint8)state; + ((Player*)this)->GetSession()->SendPacket(&data); + } +} + +bool Unit::IsPolymorphed() const +{ + return GetSpellSpecific(getTransForm()) == SPELL_MAGE_POLYMORPH; +} + +bool Unit::isAttackReady(WeaponAttackType type) const +{ + return m_attackTimer[type] == 0; +} +void Unit::SetDisplayId(uint32 modelId) +{ + if (IsPlayer()) + { + float mod_x = 1; + switch (modelId) + { + case 59: + mod_x *= DEFAULT_TAUREN_MALE_SCALE; + break; + case 60: + mod_x *= DEFAULT_TAUREN_FEMALE_SCALE; + break; + // Orb of Deception Gone + case 10148: + mod_x *= DEFAULT_TAUREN_MALE_SCALE; + break; + case 10149: + mod_x *= DEFAULT_TAUREN_FEMALE_SCALE; + break; + } + switch (GetDisplayId()) + { + case 59: + mod_x /= DEFAULT_TAUREN_MALE_SCALE; + break; + case 60: + mod_x /= DEFAULT_TAUREN_FEMALE_SCALE; + break; + // Orb of Deception Gone + case 10148: + mod_x /= DEFAULT_TAUREN_MALE_SCALE; + break; + case 10149: + mod_x /= DEFAULT_TAUREN_FEMALE_SCALE; + break; + } + ApplyPercentModFloatValue(OBJECT_FIELD_SCALE_X, (mod_x -1)*100, true); + } + + SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId); + + UpdateModelData(); + + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (!pet->isControlled()) + return; + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID); + } +} + +void Unit::UpdateModelData() +{ + CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(GetDisplayId()); + CreatureModelInfo const* modelInfo = sObjectMgr.GetCreatureModelInfo(GetDisplayId()); + if (modelInfo && displayEntry && modelInfo->bounding_radius && modelInfo->combat_reach && displayEntry->scale) + { + // we expect values in database to be relative to scale = 1.0 + SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (GetObjectScale() / displayEntry->scale) * modelInfo->bounding_radius); + + // never actually update combat_reach for player, it's always the same. Below player case is for initialization + if (GetTypeId() == TYPEID_PLAYER) + SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); + else + SetFloatValue(UNIT_FIELD_COMBATREACH, (GetObjectScale() / displayEntry->scale) * modelInfo->combat_reach); + } + else + { + sLog.outError("UpdateModelData : pas / mauvaises infos pour le displayid %u de '%s'", GetDisplayId(), GetGuidStr().c_str()); + SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); + SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 1.5f); + } +} + +void Unit::ClearComboPointHolders() +{ + while (!m_ComboPointHolders.empty()) + { + uint32 lowguid = *m_ComboPointHolders.begin(); + + Player* plr = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, lowguid)); + if (plr && plr->GetComboTargetGuid() == GetObjectGuid())// recheck for safe + plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders; + else + m_ComboPointHolders.erase(lowguid); // or remove manually + } +} + +void Unit::ClearAllReactives() +{ + for (int i = 0; i < MAX_REACTIVE; ++i) + { + m_reactiveTimer[i] = 0; + m_reactiveTarget[i].Clear(); + } + + if (HasAuraState(AURA_STATE_DEFENSE)) + ModifyAuraState(AURA_STATE_DEFENSE, false); + if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) + ModifyAuraState(AURA_STATE_HUNTER_PARRY, false); + + if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->ClearComboPoints(); +} + +void Unit::UpdateReactives(uint32 p_time) +{ + for (int i = 0; i < MAX_REACTIVE; ++i) + { + ReactiveType reactive = ReactiveType(i); + + if (!m_reactiveTimer[reactive]) + continue; + + if (m_reactiveTimer[reactive] <= p_time) + { + m_reactiveTimer[reactive] = 0; + m_reactiveTarget[reactive].Clear(); + + switch (reactive) + { + case REACTIVE_DEFENSE: + if (HasAuraState(AURA_STATE_DEFENSE)) + ModifyAuraState(AURA_STATE_DEFENSE, false); + break; + case REACTIVE_HUNTER_PARRY: + if (getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY)) + ModifyAuraState(AURA_STATE_HUNTER_PARRY, false); + break; + case REACTIVE_OVERPOWER: + if (getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->ClearComboPoints(); + break; + default: + break; + } + } + else + m_reactiveTimer[reactive] -= p_time; + } +} + +Unit* Unit::SelectRandomUnfriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const +{ + std::list targets; + + MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, radius); + MaNGOS::UnitListSearcher searcher(targets, u_check); + Cell::VisitAllObjects(this, searcher, radius); + + // remove current target + if (except) + targets.remove(except); + + // remove not LoS targets + for (std::list::iterator tIter = targets.begin(); tIter != targets.end();) + { + if (!IsWithinLOSInMap(*tIter)) + { + std::list::iterator tIter2 = tIter; + ++tIter; + targets.erase(tIter2); + } + else + ++tIter; + } + + // no appropriate targets + if (targets.empty()) + return nullptr; + + // select random + uint32 rIdx = urand(0, targets.size() - 1); + std::list::const_iterator tcIter = targets.begin(); + for (uint32 i = 0; i < rIdx; ++i) + ++tcIter; + + return *tcIter; +} + +Unit* Unit::SelectRandomFriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const +{ + std::list targets; + + MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(this, radius); + MaNGOS::UnitListSearcher searcher(targets, u_check); + + Cell::VisitAllObjects(this, searcher, radius); + + // remove current target + if (except) + targets.remove(except); + + // remove not LoS targets + for (std::list::iterator tIter = targets.begin(); tIter != targets.end();) + { + if (!IsWithinLOSInMap(*tIter)) + { + std::list::iterator tIter2 = tIter; + ++tIter; + targets.erase(tIter2); + } + else + ++tIter; + } + + // no appropriate targets + if (targets.empty()) + return nullptr; + + // select random + uint32 rIdx = urand(0, targets.size() - 1); + std::list::const_iterator tcIter = targets.begin(); + for (uint32 i = 0; i < rIdx; ++i) + ++tcIter; + + return *tcIter; +} + +bool Unit::IsSecondaryThreatTarget() +{ + // Targets with Fear / Confuse / breakable CC + for (SpellAuraHolderMap::const_iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end(); ++iter) + { + if (iter->second->IsTargetSecondaryThreatFocus()) + return true; + } + // Totems have secondary threat priority + if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsTotem()) + { + if (Totem* totem = ((Totem*)this)) + { + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(totem->GetSpell()); + if (!spellInfo) + return true; + + switch (spellInfo->SpellIconID) + { + // Fire Nova Totem / Magma Totem / Searing Totem / Stoneclaw Totem do have threat + case 33: + case 37: + case 680: + case 689: + break; + default: + return true; + } + } + } + return false; +} + +bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag) +{ + for (SpellAuraHolderMap::const_iterator iter = m_spellAuraHolders.begin(); iter != m_spellAuraHolders.end(); ++iter) + { + if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag) + return true; + } + return false; +} + +void Unit::ApplyAttackTimePercentMod(WeaponAttackType att, float val, bool apply, bool recalcDamage /*= false*/) +{ + if (val > 0) + { + ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply); + ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, val, !apply); + + if (recalcDamage) + ApplyPercentModFloatVar(m_modRecalcDamagePct[att], val, !apply); + } + else + { + ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply); + ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME + att, -val, apply); + + if (recalcDamage) + ApplyPercentModFloatVar(m_modRecalcDamagePct[att], val, apply); + } +} + +void Unit::ApplyCastTimePercentMod(float val, bool apply) +{ + ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED, -val, apply); +} + +void Unit::UpdateAuraForGroup(uint8 slot) +{ + if (GetTypeId() == TYPEID_PLAYER) + { + Player* player = (Player*)this; + if (player->GetGroup()) + { + player->SetGroupUpdateFlag(slot < MAX_POSITIVE_AURAS ? GROUP_UPDATE_FLAG_AURAS : GROUP_UPDATE_FLAG_AURAS_NEGATIVE); + player->SetAuraUpdateSlot(slot); + } + } + else if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->IsPet()) + { + Pet *pet = ((Pet*)this); + if (pet->isControlled()) + { + Unit *owner = GetOwner(); + if (owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup()) + { + ((Player*)owner)->SetGroupUpdateFlag(slot < MAX_POSITIVE_AURAS ? GROUP_UPDATE_FLAG_PET_AURAS : GROUP_UPDATE_FLAG_PET_AURAS_NEGATIVE); + pet->SetAuraUpdateSlot(slot); + } + } + } +} + +float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized) +{ + if (!normalized || GetTypeId() != TYPEID_PLAYER) + return float(GetAttackTime(attType)) / 1000.0f; + + Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType, true, false); + if (!Weapon) + return 2.4f; // fist attack + + switch (Weapon->GetProto()->InventoryType) + { + case INVTYPE_2HWEAPON: + return 3.3f; + case INVTYPE_RANGED: + case INVTYPE_RANGEDRIGHT: + case INVTYPE_THROWN: + return 2.8f; + case INVTYPE_WEAPON: + case INVTYPE_WEAPONMAINHAND: + case INVTYPE_WEAPONOFFHAND: + default: + return Weapon->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f; + } +} + +Aura* Unit::GetDummyAura(uint32 spell_id) const +{ + Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY); + for (Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr) + if ((*itr)->GetId() == spell_id) + return *itr; + + return nullptr; +} + +void Unit::SetContestedPvP(Player *attackedPlayer) +{ + Player* player = GetCharmerOrOwnerPlayerOrPlayerItself(); + + if (!player || (attackedPlayer && (attackedPlayer == player || player->IsInDuelWith(attackedPlayer)))) + return; + + player->SetContestedPvPTimer(30000); + + if (!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER)) + { + player->addUnitState(UNIT_STAT_ATTACK_PLAYER); + player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP); + // call MoveInLineOfSight for nearby contested guards + UpdateVisibilityAndView(); + } + + if (!hasUnitState(UNIT_STAT_ATTACK_PLAYER)) + { + addUnitState(UNIT_STAT_ATTACK_PLAYER); + // call MoveInLineOfSight for nearby contested guards + UpdateVisibilityAndView(); + } +} + +void Unit::AddPetAura(PetAura const* petSpell) +{ + m_petAuras.insert(petSpell); + if (Pet* pet = GetPet()) + pet->CastPetAura(petSpell); +} + +void Unit::RemovePetAura(PetAura const* petSpell) +{ + m_petAuras.erase(petSpell); + if (Pet* pet = GetPet()) + pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry())); +} + +void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/) +{ + Unit::SpellAuraHolderMap& auras = GetSpellAuraHolderMap(); + for (Unit::SpellAuraHolderMap::iterator iter = auras.begin(); iter != auras.end();) + { + SpellEntry const *spell = iter->second->GetSpellProto(); + if (spell->Id == exceptSpellId) + ++iter; + else if (non_positive && iter->second->IsPositive()) + ++iter; + else if (spell->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) + ++iter; + else if (iter->second->HasMechanicMask(mechMask)) + { + RemoveAurasDueToSpell(spell->Id); + + if (auras.empty()) + break; + else + iter = auras.begin(); + } + else + ++iter; + } +} + +void Unit::NearTeleportTo(float x, float y, float z, float orientation, uint32 teleportOptions) +{ + DisableSpline(); + + if (GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->TeleportTo(GetMapId(), x, y, z, orientation, teleportOptions); + else + { + Creature* c = (Creature*)this; + // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly + if (!c->GetMotionMaster()->empty()) + if (MovementGenerator *movgen = c->GetMotionMaster()->top()) + movgen->Interrupt(*c); + + GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation); + SendHeartBeat(); + + // finished relocation, movegen can different from top before creature relocation, + // but apply Reset expected to be safe in any case + if (!c->GetMotionMaster()->empty()) + if (MovementGenerator *movgen = c->GetMotionMaster()->top()) + movgen->Reset(*c); + } +} + +void Unit::NearLandTo(float x, float y, float z, float orientation) +{ + m_movementInfo.RemoveMovementFlag(MOVEFLAG_JUMPING | MOVEFLAG_FALLINGFAR); + m_movementInfo.ChangePosition(x, y, z, orientation); + m_movementInfo.UpdateTime(WorldTimer::getMSTime()); + m_movementInfo.ctime = 0; // Not a client packet. Pauses interpolation. + + WorldPacket data(MSG_MOVE_FALL_LAND, 41); + data << GetPackGUID(); + data << m_movementInfo; + SendMovementMessageToSet(std::move(data), true); + TeleportPositionRelocation(x, y, z, orientation); + DisableSpline(); +} + +void Unit::TeleportPositionRelocation(float x, float y, float z, float orientation) +{ + Player* player = ToPlayer(); + Creature* crea = ToCreature(); + uint32 old_zone = 0; + if (player) + { + player->SetPosition(x, y, z, orientation, true); + player->m_movementInfo.ChangePosition(x, y, z, orientation); + player->m_movementInfo.UpdateTime(WorldTimer::getMSTime()); + } + else if (crea) + { + if (!crea->GetMotionMaster()->empty()) + if (MovementGenerator *movgen = crea->GetMotionMaster()->top()) + movgen->Interrupt(*crea); + GetMap()->CreatureRelocation(crea, x, y, z, orientation); + } + + // new zone + if (player) + { + uint32 newzone, newarea; + GetZoneAndAreaId(newzone, newarea); + if (old_zone != newzone) + player->UpdateZone(newzone, newarea); + // honorless target + if (!player->pvpInfo.inHostileArea) + player->RemoveDelayedOperation(DELAYED_CAST_HONORLESS_TARGET); + } + else if (crea) + { + if (!crea->GetMotionMaster()->empty()) + if (MovementGenerator *movgen = crea->GetMotionMaster()->top()) + movgen->Reset(*crea); + } +} + +void Unit::MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath, bool forceDestination) +{ + uint32 options = 0; + if (generatePath) + options |= MOVE_PATHFINDING; + if (forceDestination) + options |= MOVE_FORCE_DESTINATION; + Movement::MoveSplineInit init(*this, "MonsterMoveWithSpeed"); + init.MoveTo(x, y, z, options); + init.SetVelocity(speed); + init.Launch(); +} + +struct SetPvPHelper +{ + explicit SetPvPHelper(bool _state) : state(_state) {} + void operator()(Unit* unit) const + { + unit->SetPvP(state); + } + bool state; +}; + +void Unit::SetPvP(bool state) +{ + if (state) + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP); + else + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP); + + if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->GetGroup()) + ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_STATUS); + + CallForAllControlledUnits(SetPvPHelper(state), CONTROLLED_PET | CONTROLLED_TOTEMS | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); +} + +void Unit::KnockBackFrom(WorldObject* target, float horizontalSpeed, float verticalSpeed) +{ + float angle = this == target ? GetOrientation() + M_PI_F : target->GetAngle(this); + + // set immune anticheat and calculate speed + if (Player* plr = ToPlayer()) + { + plr->SetLaunched(true); + plr->SetXYSpeed(horizontalSpeed); + } + + KnockBack(angle, horizontalSpeed, verticalSpeed); +} + +void Unit::KnockBack(float angle, float horizontalSpeed, float verticalSpeed) +{ + InterruptNonMeleeSpells(false); + + // Effect properly implemented only for players + if (GetTypeId() == TYPEID_PLAYER) + { + float vsin = sin(angle); + float vcos = cos(angle); + 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 << float(horizontalSpeed); // Horizontal speed + data << float(-verticalSpeed); // Z Movement speed (vertical) + SendMovementMessageToSet(std::move(data), true); + + ToPlayer()->GetCheatData()->KnockBack(horizontalSpeed, verticalSpeed, vcos, vsin); + } +} + +struct StopAttackFactionHelper +{ + explicit StopAttackFactionHelper(uint32 _faction_id) : faction_id(_faction_id) {} + void operator()(Unit* unit) const + { + unit->StopAttackFaction(faction_id); + } + uint32 faction_id; +}; + +void Unit::StopAttackFaction(uint32 faction_id) +{ + if (Unit* victim = getVictim()) + { + if (victim->getFactionTemplateEntry()->faction == faction_id) + { + AttackStop(); + if (IsNonMeleeSpellCasted(false)) + InterruptNonMeleeSpells(false); + + // melee and ranged forced attack cancel + if (GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->SendAttackSwingCancelAttack(); + } + } + + AttackerSet const& attackers = getAttackers(); + for (AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();) + { + if ((*itr)->getFactionTemplateEntry()->faction == faction_id) + { + (*itr)->AttackStop(); + itr = attackers.begin(); + } + else + ++itr; + } + + getHostileRefManager().deleteReferencesForFaction(faction_id); + + CallForAllControlledUnits(StopAttackFactionHelper(faction_id), CONTROLLED_PET | CONTROLLED_GUARDIANS | CONTROLLED_CHARM); +} + +void Unit::CleanupDeletedAuras() +{ + for (SpellAuraHolderList::const_iterator iter = m_deletedHolders.begin(); iter != m_deletedHolders.end(); ++iter) + { + if ((*iter)->IsInUse()) + { + // Use case: + // - Spell damage + // - Player::SetDeathState + // - Pet::AddObjectToRemoveList + // Seen happening with spells like [Health Funnel], [Tainted Blood] + ACE_Stack_Trace st; + sLog.outInfo("[Crash/Auras] Deleting aura holder %u in use (%s)", (*iter)->GetId(), GetObjectGuid().GetString().c_str()); + sLog.outInfo("%s", st.c_str()); + } + else + delete *iter; + } + m_deletedHolders.clear(); + + // really delete auras "deleted" while processing its ApplyModify code + for (AuraList::const_iterator iter = m_deletedAuras.begin(); iter != m_deletedAuras.end(); ++iter) + { + if ((*iter)->IsInUse()) + { + ACE_Stack_Trace st; + sLog.outInfo("[Crash/Auras] Deleting aura %u in use (%s)", (*iter)->GetId(), GetObjectGuid().GetString().c_str()); + sLog.outInfo("%s", st.c_str()); + } + else + delete *iter; + } + m_deletedAuras.clear(); +} + +bool Unit::CheckAndIncreaseCastCounter() +{ + uint32 maxCasts = sWorld.getConfig(CONFIG_UINT32_MAX_SPELL_CASTS_IN_CHAIN); + + if (maxCasts && m_castCounter >= maxCasts) + return false; + + ++m_castCounter; + return true; +} + +SpellAuraHolder* Unit::GetSpellAuraHolder(uint32 spellid) const +{ + SpellAuraHolderMap::const_iterator itr = m_spellAuraHolders.find(spellid); + return itr != m_spellAuraHolders.end() ? itr->second : NULL; +} + +SpellAuraHolder* Unit::GetSpellAuraHolder(uint32 spellid, ObjectGuid casterGuid) const +{ + SpellAuraHolderConstBounds bounds = GetSpellAuraHolderBounds(spellid); + for (SpellAuraHolderMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter) + if (iter->second->GetCasterGuid() == casterGuid) + return iter->second; + + return nullptr; +} + + +class RelocationNotifyEvent : public BasicEvent +{ +public: + RelocationNotifyEvent(Unit& owner) : BasicEvent(), m_owner(owner) + { + m_owner._SetAINotifyScheduled(true); + } + + bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) + { + float radius = sWorld.getConfig(CONFIG_FLOAT_MAX_CREATURE_ATTACK_RADIUS) * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO); + if (m_owner.GetTypeId() == TYPEID_PLAYER) + { + MaNGOS::PlayerRelocationNotifier notify((Player&)m_owner); + Cell::VisitAllObjects(&m_owner, notify, radius); + } + else //if(m_owner.GetTypeId() == TYPEID_UNIT) + { + MaNGOS::CreatureRelocationNotifier notify((Creature&)m_owner); + Cell::VisitAllObjects(&m_owner, notify, radius); + } + m_owner._SetAINotifyScheduled(false); + return true; + } + + void Abort(uint64) + { + m_owner._SetAINotifyScheduled(false); + } + +private: + Unit& m_owner; +}; + +void Unit::ScheduleAINotify(uint32 delay) +{ + if (!delay) + { + // Instant + RelocationNotifyEvent event(*this); + event.Execute(0, 0); + return; + } + if (!IsAINotifyScheduled()) + m_Events.AddEvent(new RelocationNotifyEvent(*this), m_Events.CalculateTime(delay)); +} + +void Unit::OnRelocated() +{ + // switch to use G3D::Vector3 is good idea, maybe + float dx = m_last_notified_position.x - GetPositionX(); + float dy = m_last_notified_position.y - GetPositionY(); + float dz = m_last_notified_position.z - GetPositionZ(); + float distsq = dx * dx + dy * dy + dz * dz; + if (distsq > World::GetRelocationLowerLimitSq()) + { + m_last_notified_position.x = GetPositionX(); + m_last_notified_position.y = GetPositionY(); + m_last_notified_position.z = GetPositionZ(); + + if (IsInWorld() && !m_needUpdateVisibility) + AddDelayedAction(OBJECT_DELAYED_ADD_TO_RELOCATED_LIST); + } + ScheduleAINotify(World::GetRelocationAINotifyDelay()); +} + +void Unit::ProcessRelocationVisibilityUpdates() +{ + m_needUpdateVisibility = false; + if (!IsInWorld()) + return; + + GetViewPoint().Call_UpdateVisibilityForOwner(); // HEAVY LOAD + UpdateObjectVisibility(); +} + +// BEGIN Nostalrius specific functions +void Unit::InterruptSpellsCastedOnMe(bool killDelayed, bool interruptPositiveSpells) +{ + std::list targets; + // Maximum spell range=100m ? + MaNGOS::AnyUnitInObjectRangeCheck u_check(this, 100.0f); + MaNGOS::UnitListSearcher searcher(targets, u_check); + Cell::VisitAllObjects(this, searcher, GetMap()->GetVisibilityDistance()); + for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) + { + if (!interruptPositiveSpells && IsFriendlyTo(*iter)) + continue; + for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++) + if (Spell *spell = (*iter)->GetCurrentSpell(CurrentSpellTypes(i))) + if (spell->m_targets.getUnitTargetGuid() == GetObjectGuid()) + if (killDelayed || (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastedTime()) || i == CURRENT_CHANNELED_SPELL) + (*iter)->InterruptSpell(CurrentSpellTypes(i), true); + if (!killDelayed) + continue; + // 2/ Interruption des sorts qui ne sont plus reference, mais dont il reste un event (ceux en parcours par exemple) + auto i_Events = (*iter)->m_Events.GetEvents().begin(); + for (; i_Events != (*iter)->m_Events.GetEvents().end(); ++i_Events) + if (SpellEvent* event = dynamic_cast(i_Events->second)) + if (event && event->GetSpell()->m_targets.getUnitTargetGuid() == GetObjectGuid()) + if (event->GetSpell()->getState() != SPELL_STATE_FINISHED) + event->GetSpell()->cancel(); + } +} + +void Unit::InterruptAttacksOnMe(float dist) +{ + if (dist == 0.0f) + dist = GetMap()->GetVisibilityDistance(); + std::list targets; + MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist); + MaNGOS::UnitListSearcher searcher(targets, u_check); + Cell::VisitAllObjects(this, searcher, dist); + for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) + { + if ((*iter)->getVictim() != this) + continue; + (*iter)->AttackStop(); + if (Player* pAttacker = (*iter)->ToPlayer()) + pAttacker->SendAttackSwingCancelAttack(); + } +} + +void Unit::CombatStopInRange(float dist) +{ + if (dist == 0.0f) + dist = GetMap()->GetVisibilityDistance(); + std::list targets; + MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, dist); + MaNGOS::UnitListSearcher searcher(targets, u_check); + Cell::VisitAllObjects(this, searcher, dist); + for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) + (*iter)->CombatStopWithPets(true); +} + +uint32 Unit::DespawnNearCreaturesByEntry(uint32 entry, float range) +{ + std::list creatures; + GetCreatureListWithEntryInGrid(creatures, entry, range); + uint32 count = 0; + for (std::list::iterator it = creatures.begin(); it != creatures.end(); ++it) + { + if ((*it)->IsInWorld()) + { + ++count; + (*it)->DisappearAndDie(); + } + } + return count; +} + +uint32 Unit::RespawnNearCreaturesByEntry(uint32 entry, float range) +{ + if (range == 0.0f) + range = GetMap()->GetVisibilityDistance(); + uint32 count = 0; + std::list lList; + GetCreatureListWithEntryInGrid(lList, entry, range); + for (std::list::iterator it = lList.begin(); it != lList.end(); ++it) + { + if (!(*it)->isAlive()) + { + (*it)->Respawn(); + ++count; + } + } + return count; +} + + +uint32 Unit::DespawnHostileCreaturesInRange(float range) +{ + if (range == 0.0f) + range = GetMap()->GetVisibilityDistance(); + uint32 count = 0; + std::list targets; + MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, range); + MaNGOS::UnitListSearcher searcher(targets, u_check); + Cell::VisitAllObjects(this, searcher, range); + for (std::list::iterator iter = targets.begin(); iter != targets.end(); ++iter) + { + if ((*iter)->GetTypeId() == TYPEID_UNIT) + { + ++count; + (*iter)->AddObjectToRemoveList(); + } + } + return count; +} + +bool Unit::IsWithinMeleeRange(const Unit *obj, float dist) const +{ + if (!obj || !IsInMap(obj)) + return false; + + float dx = GetPositionX() - obj->GetPositionX(); + float dy = GetPositionY() - obj->GetPositionY(); + float dz = GetPositionZ() - obj->GetPositionZ(); + float distsq = dx * dx + dy * dy + dz * dz; + + float maxdist = dist + BASE_MELEERANGE_OFFSET + GetMeleeReach() + obj->GetObjectBoundingRadius(); + + if (maxdist < ATTACK_DISTANCE) + maxdist = ATTACK_DISTANCE; + + return distsq < maxdist * maxdist; +} + +// TriniyCore +void Unit::GetRandomAttackPoint(const Unit* attacker, float &x, float &y, float &z) const +{ + // Compute random angle + float angle = GetAngle(attacker); + float sizeFactor = GetObjectBoundingRadius() + attacker->GetObjectBoundingRadius(); + if (sizeFactor < 0.1f) + sizeFactor = DEFAULT_COMBAT_REACH; + + uint32 attacker_number = getAttackers().size(); + if (attacker_number > 0) + --attacker_number; + // Don't compute a random position for a moving player + if (GetTypeId() == TYPEID_PLAYER && IsMoving()) + attacker_number = 0; + angle += (attacker_number ? ((float(M_PI / 2) - float(M_PI) * rand_norm_f()) * attacker_number / sizeFactor) * 0.3f : 0); + + float dist = attacker->GetObjectBoundingRadius() + GetObjectBoundingRadius() + rand_norm_f() * (attacker->GetMeleeReach() - attacker->GetObjectBoundingRadius()); + float initialPosX, initialPosY, initialPosZ, o; + GetPosition(initialPosX, initialPosY, initialPosZ); + + // Moving player: try to interpolate movement a bit + if (GetTypeId() == TYPEID_PLAYER && IsMoving()) + if (!ToPlayer()->GetCheatData()->InterpolateMovement(m_movementInfo, 200, initialPosX, initialPosY, initialPosZ, o)) + GetPosition(initialPosX, initialPosY, initialPosZ); + + float attackerTargetDistance = sqrt(pow(initialPosX - attacker->GetPositionX(), 2) + + pow(initialPosY - attacker->GetPositionY(), 2) + + pow(initialPosZ - attacker->GetPositionZ(), 2)); + if (dist > attackerTargetDistance) + { + // On ne bouge pas, on est deja a portee. + attacker->GetPosition(x, y, z); + return; + } + float normalizedVectZ = (attacker->GetPositionZ() - initialPosZ) / attackerTargetDistance; + float normalizedVectXY = sqrt(1 - normalizedVectZ * normalizedVectZ); + x = initialPosX + dist * cos(angle) * normalizedVectXY; + y = initialPosY + dist * sin(angle) * normalizedVectXY; + z = initialPosZ + dist * normalizedVectZ; + + if ((attacker->CanFly() || (attacker->CanSwim() && IsInWater()))) + { + GetMap()->GetLosHitPosition(initialPosX, initialPosY, initialPosZ, x, y, z, -0.2f); + if (attacker->CanFly()) + return; + float ground = 0.0f; + float waterSurface = GetTerrain()->GetWaterLevel(x, y, z, &ground); + if (waterSurface == VMAP_INVALID_HEIGHT_VALUE) + waterSurface = GetPositionZ(); + if (z > waterSurface) + z = waterSurface; + if (z < ground) + z = ground; + } + else + { + uint32 nav = NAV_GROUND | NAV_WATER; + if (attacker->GetTypeId() != TYPEID_PLAYER) + nav |= NAV_MAGMA | NAV_SLIME; + // Try mmaps. On fail, use target position (but should not fail) + if (!GetMap()->GetWalkHitPosition(GetTransport(), initialPosX, initialPosY, initialPosZ, x, y, z, nav)) + GetPosition(x, y, z); + } +} + +float Unit::GetMeleeReach() const +{ + return GetCombatReach(true); +} + +float Unit::GetCombatReach(bool forMeleeRange /*=true*/) const +{ + float reach = GetFloatValue(UNIT_FIELD_COMBATREACH); + return (forMeleeRange && reach < 1.5f) ? 1.5f : reach; +} + +float Unit::GetCombatReach(Unit const* pVictim, bool forMeleeRange /*=true*/, float flat_mod /*=0.0f*/) const +{ + float victimReach = (pVictim && pVictim->IsInWorld()) + ? pVictim->GetCombatReach(forMeleeRange) + : 0.0f; + + float reach = GetCombatReach(forMeleeRange) + victimReach + flat_mod; + + if (forMeleeRange) + { + reach += BASE_MELEERANGE_OFFSET; + if (reach < ATTACK_DISTANCE) + reach = ATTACK_DISTANCE; + } + + // Melee leeway mechanic. + // When both player and target has > 70% of normal runspeed, and are moving, + // the player gains an additional 2.5yd of melee range. + if (IsPlayer()) + { + static const float leewayMinSpeed = 4.97f; + if (GetXZFlagBasedSpeed(this) > leewayMinSpeed && GetXZFlagBasedSpeed(pVictim) > leewayMinSpeed) + reach += 2.5f; + } + + return reach; +} + +bool Unit::CanReachWithMeleeAttack(Unit const* pVictim, float flat_mod /*= 0.0f*/) const +{ + if (!pVictim || !pVictim->IsInWorld()) + return false; + + float reach = GetCombatReach(pVictim, true, flat_mod); + + // This check is not related to bounding radius + float dx = GetPositionX() - pVictim->GetPositionX(); + float dy = GetPositionY() - pVictim->GetPositionY(); + float dz = GetPositionZ() - pVictim->GetPositionZ(); + + return (dx * dx + dy * dy < reach * reach) && ((dz * dz) < MELEE_Z_LIMIT); +} + +bool Unit::CanReachWithMeleeSpellAttack(Unit const* pVictim, float flat_mod /*= 0.0f*/) const +{ + if (!pVictim || !pVictim->IsInWorld()) + return false; + + float reach = GetCombatReach(pVictim, true, flat_mod); + + // This check is not related to bounding radius + float dx = GetPositionX() - pVictim->GetPositionX(); + float dy = GetPositionY() - pVictim->GetPositionY(); + + // melee spells ignore Z-axis checks + return dx * dx + dy * dy < reach * reach; +} + +Unit* Unit::GetUnit(WorldObject &obj, uint64 const &Guid) +{ + if (obj.IsInWorld()) + return obj.GetMap()->GetUnit(ObjectGuid(Guid)); + return nullptr; +} + +Unit* Unit::SummonCreatureAndAttack(uint32 creatureEntry, Unit* pVictim) +{ + float summonX, summonY, summonZ, summonAng; + summonX = GetPositionX(); + summonY = GetPositionY(); + summonZ = GetPositionZ(); + summonAng = GetOrientation(); + + if (!pVictim) + if (!(pVictim = getVictim())) + return nullptr; + + if (Creature *pCreature = SummonCreature(creatureEntry, summonX, summonY, summonZ, summonAng, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 25000)) + { + if (pCreature->AI()) + pCreature->AI()->AttackStart(pVictim); + return pCreature; + } + return nullptr; +} + +bool Unit::IsCaster() +{ + // Cast en cours : on est casteur. + if (IsNonMeleeSpellCasted(true, false, true)) + return true; + + switch (getClass()) + { + case CLASS_WARRIOR: + case CLASS_ROGUE: + return false; + case CLASS_MAGE: + case CLASS_PRIEST: + case CLASS_SHAMAN: + case CLASS_HUNTER: + case CLASS_WARLOCK: + return true; + // Pala heal si faveur divine. Sinon CaC. + case CLASS_PALADIN: + return HasSpell(20216); + // Druide caster ? + case CLASS_DRUID: + if (HasAura(14858)) // Forme de Selenien + return true; + if (HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) // Dans une forme (donc CaC, ou voyage ou aquatique) + return false; + return true; // Pas en changeforme, on suppose qu'il est casteur. + default: + return false; + } +} + +void Unit::EnterVanish() +{ + SetVisibility(VISIBILITY_OFF); + SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); + InterruptSpellsCastedOnMe(true); + InterruptAttacksOnMe(); + AttackStop(); + InterruptSpell(CURRENT_AUTOREPEAT_SPELL); + // DoResetThreat : + if (Creature* pCrea = ToCreature()) + { + if (!pCrea->CanHaveThreatList() || pCrea->getThreatManager().isThreatListEmpty()) + return; + + ThreatList const& tList = pCrea->getThreatManager().getThreatList(); + for (ThreatList::const_iterator itr = tList.begin(); itr != tList.end(); ++itr) + { + Unit* pUnit = pCrea->GetMap()->GetUnit((*itr)->getUnitGuid()); + + if (pUnit && pCrea->getThreatManager().getThreat(pUnit)) + pCrea->getThreatManager().modifyThreatPercent(pUnit, -100); + } + } +} + +void Unit::LeaveVanish() +{ + SetVisibility(VISIBILITY_ON); + RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FIELD_FLAGS); +} + +void Unit::Ambush(Unit* pNewVictim, uint32 embushSpellId) +{ + if (!pNewVictim) + return; + if (Creature* pCrea = ToCreature()) + { + // Se position derriere + float x, y, z; + pNewVictim->GetRelativePositions(-4.0f, 0.0f, 0.0f, x, y, z); + pCrea->NearTeleportTo(x, y, z, 0.0f); + pCrea->SetFacingToObject(pNewVictim); + // Embush + if (embushSpellId) + pCrea->CastSpell(pNewVictim, embushSpellId, true); + if (pCrea->AI()) + pCrea->AI()->AttackStart(pNewVictim); + } +} + +bool Unit::isAttackableByAOE(bool requireDeadTarget) const +{ + if (isAlive() == requireDeadTarget) + return false; + + if (HasFlag(UNIT_FIELD_FLAGS, + UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE)) + return false; + + if (GetTypeId() == TYPEID_PLAYER && ToPlayer()->isGameMaster()) + return false; + + return true; +} + +bool Unit::IsImmuneToSchoolMask(uint32 schoolMask) const +{ + AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY); + + uint32 immuneMask = 0; + for (AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr) + { + immuneMask |= (*itr)->GetModifier()->m_miscvalue; + if (immuneMask & schoolMask) // Immunise + return true; + } + return false; +} + +void Unit::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) +{ + // Still needed ... ? + ProhibitSpellInfo inf; + inf.SchoolMask = idSchoolMask; + inf.RestingMsTime = unTimeMs; + m_prohibitSpell.push_back(inf); +} + +bool Unit::IsSpellProhibited(SpellEntry const* pSpell) +{ + uint32 spellSchoolMask = GetSpellSchoolMask(pSpell); + for (ProhibitSpellList::const_iterator it = m_prohibitSpell.begin(); it != m_prohibitSpell.end(); ++it) + { + if (it->SchoolMask & spellSchoolMask) + return true; + } + return false; +} + +bool Unit::HasProhibitedSpell() +{ + return (m_prohibitSpell.size() > 0); +} + +CreatureAI* Unit::AI() const +{ + return GetTypeId() == TYPEID_UNIT ? ((Creature*)this)->AI() : NULL; +} + +SpellAuraHolder* Unit::AddAura(uint32 spellId, uint32 addAuraFlags, Unit* pCaster) +{ + if (IsDeleted() || (pCaster && pCaster->IsDeleted())) + return nullptr; + + SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(spellId); + if (!spellInfo) + return nullptr; + + if (!IsSpellAppliesAura(spellInfo, (1 << EFFECT_INDEX_0) | (1 << EFFECT_INDEX_1) | (1 << EFFECT_INDEX_2)) && + !IsSpellHaveEffect(spellInfo, SPELL_EFFECT_PERSISTENT_AREA_AURA)) + { + sLog.outError("Impossible d'appliquer le sort %u : il n'a pas d'aura !", spellInfo->Id); + return nullptr; + } + + if (!pCaster) + pCaster = this; + + SpellAuraHolder *holder = CreateSpellAuraHolder(spellInfo, this, pCaster); + if (!holder) + return nullptr; + + if (addAuraFlags & ADD_AURA_PASSIVE) + holder->SetPassive(true); + if (addAuraFlags & ADD_AURA_PERMANENT) + holder->SetPermanent(true); + + for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i) + { + uint8 eff = spellInfo->Effect[i]; + if (eff >= TOTAL_SPELL_EFFECTS) + continue; + + if (IsAreaAuraEffect(eff) || + eff == SPELL_EFFECT_APPLY_AURA || + eff == SPELL_EFFECT_PERSISTENT_AREA_AURA) + { + Aura *aur = CreateAura(spellInfo, SpellEffectIndex(i), nullptr, holder, this, pCaster); + if (addAuraFlags & ADD_AURA_POSITIVE) + aur->SetPositive(true); + else if (addAuraFlags & ADD_AURA_NEGATIVE) + aur->SetPositive(true); + + holder->AddAura(aur, SpellEffectIndex(i)); + } + } + if (!AddSpellAuraHolder(holder)) + holder = nullptr; + return holder; +} + +SpellAuraHolder* Unit::RefreshAura(uint32 spellId, int32 duration) +{ + if (SpellAuraHolder *holder = GetSpellAuraHolder(spellId)) + { + holder->SetAuraDuration(duration); + holder->UpdateAuraDuration(); + return holder; + } + return nullptr; +} + +bool Unit::HasMorePowerfullSpellActive(SpellEntry const* spell) +{ + std::list morePowerfullSpells; + if (!sSpellMgr.ListMorePowerfullSpells(spell->Id, morePowerfullSpells)) + return false; + for (SpellAuraHolderMap::const_iterator i = m_spellAuraHolders.begin(); i != m_spellAuraHolders.end(); ++i) + for (std::list::const_iterator it = morePowerfullSpells.begin(); it != morePowerfullSpells.end(); ++it) + if ((*it) == i->first) + return true; + return false; +} + +Aura* Unit::GetMostImportantAuraAfter(Aura const* like, Aura const* except) +{ + ASSERT(like); + AuraType auraName = like->GetModifier()->m_auraname; + + // Certains area aura (Cf AreaAura::AreaAura), exemple 8836, 10626 + if (auraName == SPELL_AURA_NONE) + return nullptr; + + if (auraName >= TOTAL_AURAS) + { + sLog.outInfo("[AURASTACK][%u] auraName %u invalide.", like->GetId(), auraName); + return nullptr; + } + + Aura* currMostImportant = nullptr; + for (AuraList::iterator iter = m_modAuras[auraName].begin(); iter != m_modAuras[auraName].end(); ++iter) + { + if (!(*iter)->IsExclusive() || (*iter) == except) + continue; + if (!currMostImportant) + { + int checkResult = (*iter)->CheckExclusiveWith(like); + // On veut un aura de meme type que 'like'. Osef qu'il soit mieux ou moins bien ici. + if (checkResult > 0) + currMostImportant = (*iter); + } + else + { + int checkResult = (*iter)->CheckExclusiveWith(currMostImportant); + // '*iter' doit etre mieux que 'currMostImportant' + if (checkResult == 1) + currMostImportant = (*iter); + } + } + if (currMostImportant) + { + // A-t-on trouve ce qu'il faut ? + // Different de 'except' + ASSERT(currMostImportant != except); + // Et de meme type que 'like'. + ASSERT(currMostImportant->CheckExclusiveWith(like) > 0); + } + return currMostImportant; +} + +// Nostalrius : Ivina +void Unit::SetLastCastedSpell(uint32 spell_id, bool byclient) +{ + if (spell_id != 23303 && spell_id != 836) + m_lastCastedSpellID = spell_id; +} + +uint32 Unit::GetLastCastedSpell(bool byclientonly) +{ + if (byclientonly) + return 0; + else + return m_lastCastedSpellID; +} + +uint32 Unit::GetLastAttackType() +{ + return m_lastAttackType; +} + +void Unit::SetLastAttackType(uint32 attackType) +{ + m_lastAttackType = attackType; +} + +void Unit::UpdateSplineMovement(uint32 t_diff) +{ + if (movespline->Finalized()) + return; + + movespline->updateState(t_diff); + bool arrived = movespline->Finalized(); + + if (arrived) + DisableSpline(); + else if (!movespline->isCyclic() && movespline->getLastPointSent() >= 0 && movespline->getLastPointSent() < (movespline->currentPathIdx() + 3)) + { + WorldPacket data(SMSG_MONSTER_MOVE, 64); + data << GetPackGUID(); + movespline->setLastPointSent(Movement::PacketBuilder::WriteMonsterMove(*movespline, data, movespline->getLastPointSent() + 1)); + SendMovementMessageToSet(std::move(data), true); + } + + Movement::Location loc = movespline->ComputePosition(); + if (Transport* t = GetTransport()) + { + m_movementInfo.GetTransportPos()->x = loc.x; + m_movementInfo.GetTransportPos()->y = loc.y; + m_movementInfo.GetTransportPos()->z = loc.z; + m_movementInfo.GetTransportPos()->o = loc.orientation; + t->CalculatePassengerPosition(loc.x, loc.y, loc.z, &loc.orientation); + } + if (!MaNGOS::IsValidMapCoord(loc.x, loc.y, loc.z)) + return; + + if (GetTypeId() == TYPEID_PLAYER) + ((Player*)this)->SetPosition(loc.x, loc.y, loc.z, loc.orientation); + else + GetMap()->CreatureRelocation((Creature*)this, loc.x, loc.y, loc.z, loc.orientation); +} + +void Unit::MonsterMove(float x, float y, float z) +{ + MonsterMoveWithSpeed(x, y, z, GetSpeed(MOVE_RUN)); +} + + +void Unit::SetWalk(bool enable, bool asDefault) +{ + if (asDefault) + { + if (enable) + clearUnitState(UNIT_STAT_RUNNING); + else + addUnitState(UNIT_STAT_RUNNING); + } + + if (enable == m_movementInfo.HasMovementFlag(MOVEFLAG_WALK_MODE)) + return; + + if (enable) + m_movementInfo.AddMovementFlag(MOVEFLAG_WALK_MODE); + else + m_movementInfo.RemoveMovementFlag(MOVEFLAG_WALK_MODE); + + WorldPacket data(enable ? SMSG_SPLINE_MOVE_SET_WALK_MODE : SMSG_SPLINE_MOVE_SET_RUN_MODE, 9); + data << GetPackGUID(); + if (Player* me = ToPlayer()) + me->GetSession()->SendPacket(&data); + else + SendObjectMessageToSet(&data, false); +} + +void Unit::SetLevitate(bool enable) +{ + if (enable) + m_movementInfo.AddMovementFlag(MOVEFLAG_LEVITATING); + else + m_movementInfo.RemoveMovementFlag(MOVEFLAG_LEVITATING); +} + +void Unit::SetFly(bool enable) +{ + if (enable) + m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING | MOVEFLAG_CAN_FLY); + else + m_movementInfo.RemoveMovementFlag(MOVEFLAG_FLYING | MOVEFLAG_CAN_FLY); +} + +void Unit::DisableSpline() +{ + if (Player* me = ToPlayer()) + me->SetFallInformation(0, me->GetPositionZ()); + m_movementInfo.RemoveMovementFlag(MovementFlags(MOVEFLAG_SPLINE_ENABLED | MOVEFLAG_FORWARD)); + movespline->_Interrupt(); +} + + +void Unit::SendSpellGo(Unit* target, uint32 spellId) +{ + SpellCastTargets targets; + targets.setUnitTarget(target); + + WorldPacket data(SMSG_SPELL_GO, 53); + data << GetPackGUID(); + + data << GetPackGUID(); + data << uint32(spellId); + data << uint16(CAST_FLAG_UNKNOWN9); + + //WriteSpellGoTargets(&data); + data << uint8(1); + data << target->GetObjectGuid(); + data << uint8(0); + + data << targets; + SendMessageToSet(&data, true); +} + +#define PRELOAD if (this == unit) return true; \ +const Unit* u1 = GetCharmerOrOwnerOrSelf(); \ +const Unit* u2 = unit->GetCharmerOrOwnerOrSelf(); \ +if (u1 == u2) return true; + + +bool Unit::IsInPartyWith(Unit const* unit) const +{ + PRELOAD + if (u1->IsPlayer() && u2->IsPlayer()) + return u1->ToPlayer()->IsInSameGroupWith(u2->ToPlayer()); + return false; +} + +bool Unit::IsInRaidWith(Unit const* unit) const +{ + PRELOAD + if (u1->IsPlayer() && u2->IsPlayer()) + return u1->ToPlayer()->IsInSameRaidWith(u2->ToPlayer()); + return false; +} + +void Unit::Debug(uint32 flags, const char* format, ...) const +{ + if (!format) + return; + if (!(flags & _debugFlags)) + return; + if (_debuggerGuid.IsEmpty()) + return; + if (!IsInWorld() || !FindMap()) + return; + Player* player = FindMap()->GetPlayer(_debuggerGuid); + if (!player) + { + Unit* me = (Unit*)this; + me->_debuggerGuid.Clear(); + me->_debugFlags = 0; + return; + } + va_list ap; + va_start(ap, format); + char str[2048]; + vsnprintf(str, 2048, format, ap); + va_end(ap); + ChatHandler(player).SendSysMessage(str); +} + +class ThreatTransferDo +{ +public: + ThreatTransferDo(Unit* from, Unit* to) : _from(from), _to(to) {} + void operator()(Unit* unit) + { + if (unit == _from || unit == _to) + return; + if (!unit->IsValidAttackTarget(_to)) + return; + + if (unit->getThreatManager().getThreat(_from) > 0.1f) + unit->AddThreat(_to, unit->getThreatManager().getThreat(_from)); + else if (unit->getVictim() == _from) // Si on aggro sans faire de degat + unit->AI()->AttackStart(_to); + else + return; + unit->getThreatManager().modifyThreatPercent(_from, -100); + } +protected: + Unit* _from; + Unit* _to; +}; + +void Unit::TransferAttackersThreatTo(Unit* unit) +{ + ThreatTransferDo u_do(this, unit); + MaNGOS::CreatureWorker worker(this, u_do); + Cell::VisitGridObjects(this, worker, 50.0f); +} + +void Unit::SetMovement(UnitMovementType pType) +{ + switch (pType) + { + case MOVE_ROOT: + m_movementInfo.ChangePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); + m_movementInfo.UpdateTime(WorldTimer::getMSTime()); + m_movementInfo.moveFlags = MOVEFLAG_ROOT | (m_movementInfo.moveFlags & ~MOVEFLAG_MASK_MOVING_OR_TURN); + break; + case MOVE_UNROOT: + m_movementInfo.ChangePosition(GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); + m_movementInfo.UpdateTime(WorldTimer::getMSTime()); + m_movementInfo.moveFlags = (m_movementInfo.moveFlags & ~(MOVEFLAG_MASK_MOVING_OR_TURN | MOVEFLAG_ROOT)); + break; + } + WorldPacket data; + if (!movespline->Finalized()) + { + // Spline roots are sent here. + MovementData mvtData(this); + switch (pType) + { + case MOVE_ROOT: + mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_ROOT, GetObjectGuid()); + return; + case MOVE_UNROOT: + mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_UNROOT, GetObjectGuid()); + break; + case MOVE_WATER_WALK: + mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_WATER_WALK, GetObjectGuid()); + break; + case MOVE_LAND_WALK: + mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_LAND_WALK, GetObjectGuid()); + break; + } + return; + } + // Inform controller + Player* mePlayer = ToPlayer(); + Player* controller = nullptr; + if (Unit* charmer = GetCharmer()) + if (Player* charmerPlayer = charmer->ToPlayer()) + if (charmerPlayer->GetCharmGuid() == GetObjectGuid()) + controller = charmerPlayer; + if (!mePlayer && !controller) + return; + + switch (pType) + { + case MOVE_ROOT: + data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size() + 4); + break; + case MOVE_UNROOT: + data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size() + 4); + break; + case MOVE_WATER_WALK: + data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size() + 4); + break; + case MOVE_LAND_WALK: + data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size() + 4); + break; + default: + sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.", pType); + return; + } + data << GetPackGUID(); + data << uint32(WorldTimer::getMSTime()); // Peut etre msTime : WorldTimer::getMSTime() ? + if (mePlayer) + { + mePlayer->GetCheatData()->OrderSent(&data); + mePlayer->GetSession()->SendPacket(&data); + + // Send root messages now rather than on acks from the force messages + // so our state is consistent + if (pType == MOVE_ROOT || pType == MOVE_UNROOT) { + WorldPacket rootData(pType == MOVE_ROOT ? MSG_MOVE_ROOT : MSG_MOVE_UNROOT, 31); + rootData << GetPackGUID(); + rootData << m_movementInfo; + + mePlayer->SendMovementMessageToSet(std::move(rootData), false); + } + } + if (controller) + controller->GetSession()->SendPacket(&data); +} + +bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const +{ + AuraList const& auras = GetAurasByType(type); + for (AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) + if ((!excludeAura || excludeAura != (*itr)->GetSpellProto()->Id) && //Avoid self interrupt of channeled Crowd Control spells like Seduction + ((*itr)->GetSpellProto()->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE)) + return true; + return false; +} + +bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) const +{ + uint32 excludeAura = 0; + if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : NULL) + excludeAura = currentChanneledSpell->m_spellInfo->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction + + return (HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura) + //|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_FEAR, excludeAura) // no breakable fears in vanilla + || HasBreakableByDamageAuraType(SPELL_AURA_MOD_STUN, excludeAura) + //|| HasBreakableByDamageAuraType(SPELL_AURA_MOD_ROOT, excludeAura) // no breakable roots in vanilla + || HasBreakableByDamageAuraType(SPELL_AURA_TRANSFORM, excludeAura)); +} + +void Unit::UpdateControl() +{ + Player* mePlayer = ToPlayer(); + + // Inform controller + if (Unit* charmer = GetCharmer()) + if (Player* charmerPlayer = charmer->ToPlayer()) + if (charmerPlayer->GetCharmGuid() == GetObjectGuid()) + charmerPlayer->SetClientControl(this, !hasUnitState(UNIT_STAT_FLEEING | UNIT_STAT_CONFUSED)); + // Inform myself + if (mePlayer) + { + // Possessing someone ? + if (Unit* possessed = GetCharm()) + if (possessed->GetCharmerGuid() == GetObjectGuid()) + { + mePlayer->SetClientControl(possessed, !possessed->hasUnitState(UNIT_STAT_FLEEING | UNIT_STAT_CONFUSED)); + return; + } + mePlayer->SetClientControl(mePlayer, !hasUnitState(UNIT_STAT_CONTROLLED | UNIT_STAT_FLEEING | UNIT_STAT_CONFUSED) && !GetCharmerGuid()); + } +} + +// select nearest hostile unit within the given distance (regardless of threat list). +Unit* Unit::SelectNearestTarget(float dist) const +{ + CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY())); + Cell cell(p); + cell.SetNoCreate(); + + Unit *target = nullptr; + + if (dist == 0.0f || dist > MAX_VISIBILITY_DISTANCE) + dist = MAX_VISIBILITY_DISTANCE; + + MaNGOS::NearestHostileUnitCheck u_check(this, dist); + MaNGOS::UnitLastSearcher searcher(target, u_check); + + TypeContainerVisitor, WorldTypeMapContainer > world_unit_searcher(searcher); + TypeContainerVisitor, GridTypeMapContainer > grid_unit_searcher(searcher); + + cell.Visit(p, world_unit_searcher, *GetMap(), *this, dist); + cell.Visit(p, grid_unit_searcher, *GetMap(), *this, dist); + + return target; +} + +float Unit::GetMinChaseDistance(Unit* victim) const +{ + if (_casterChaseDistance > 1.0f) + return _casterChaseDistance; + return GetObjectBoundingRadius(); +} + +float Unit::GetMaxChaseDistance(Unit* victim) const +{ + if (_casterChaseDistance > 1.0f) + return _casterChaseDistance + GetObjectBoundingRadius() + victim->GetObjectBoundingRadius(); + return GetMeleeReach() + BASE_MELEERANGE_OFFSET; +} + +void Unit::RestoreMovement() +{ + if (GetTypeId() != TYPEID_UNIT) + return; + // Need restore previous movement since we have no proper states system + if (isAlive() && !hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING)) + { + if (Unit * victim = getVictim()) + GetMotionMaster()->MoveChase(victim); + else + GetMotionMaster()->Initialize(); + } +} + +/** Spell cooldown management system. Shared by Players, Creatures, Pets, ... */ +void Unit::RemoveSpellCooldown(uint32 spell_id, bool update /* = false */) +{ + m_spellCooldowns.erase(spell_id); + + if (update) + if (Player* player = GetAffectingPlayer()) + player->SendClearCooldown(spell_id, this); +} + +bool Unit::HasSpellCategoryCooldown(uint32 cat) const +{ + if (!cat) + return false; + for (SpellCooldowns::const_iterator it = m_spellCooldowns.begin(); it != m_spellCooldowns.end(); ++it) + if (it->second.cat == cat && it->second.categoryEnd > time(nullptr)) + return true; + return false; +} + +void Unit::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */) +{ + SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat); + if (ct == sSpellCategoryStore.end()) + return; + + const SpellCategorySet& ct_set = ct->second; + for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();) + { + if (ct_set.find(i->first) != ct_set.end()) + RemoveSpellCooldown((i++)->first, update); + else + ++i; + } +} + +void Unit::RemoveAllSpellCooldown() +{ + if (!m_spellCooldowns.empty()) + { + if (Player* player = GetAffectingPlayer()) + for (SpellCooldowns::const_iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end(); ++itr) + player->SendClearCooldown(itr->first, this); + + m_spellCooldowns.clear(); + } +} + +void Unit::CooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell) +{ + // start cooldowns at server side, if any + AddSpellAndCategoryCooldowns(spellInfo, itemId, spell); + + // Send activate cooldown timer (possible 0) at client side + if (Player* player = GetAffectingPlayer()) + { + WorldPacket data(SMSG_COOLDOWN_EVENT, (4 + 8)); + data << uint32(spellInfo->Id); + data << GetObjectGuid(); + player->SendDirectMessage(&data); + } +} + +void Unit::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown) +{ + // init cooldown values + uint32 cat = 0; + int32 rec = -1; + int32 catrec = -1; + + // some special item spells without correct cooldown in SpellInfo + // cooldown information stored in item prototype + // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client. + + if (itemId) + { + if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId)) + { + for (int idx = 0; idx < MAX_ITEM_PROTO_SPELLS; ++idx) + { + if (proto->Spells[idx].SpellId == spellInfo->Id) + { + cat = proto->Spells[idx].SpellCategory; + rec = proto->Spells[idx].SpellCooldown; + catrec = proto->Spells[idx].SpellCategoryCooldown; + break; + } + } + } + } + + // if no cooldown found above then base at DBC data + if (rec < 0 && catrec < 0) + { + cat = spellInfo->Category; + rec = spellInfo->RecoveryTime; + catrec = spellInfo->CategoryRecoveryTime; + } + + time_t curTime = time(nullptr); + + time_t catrecTime; + time_t recTime; + + // overwrite time for selected category + if (infinityCooldown) + { + // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped) + // but not allow ignore until reset or re-login + catrecTime = catrec > 0 ? curTime + infinityCooldownDelay : 0; + recTime = rec > 0 ? curTime + infinityCooldownDelay : catrecTime; + } + else + { + // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK) + // prevent 0 cooldowns set by another way + if (rec <= 0 && catrec <= 0 && (cat == 76 || cat == 351)) + rec = GetAttackTime(RANGED_ATTACK); + + if (rec > 0 || catrec > 0) + { + if (Player* modOwner = GetSpellModOwner()) + { + // Now we have cooldown data (if found any), time to apply mods + if (rec > 0) + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell); + + if (catrec > 0) + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell); + } + if (Player* player = GetAffectingPlayer()) + if (player != this) + player->SendSpellCooldown(spellInfo->Id, rec > catrec ? rec : catrec, GetObjectGuid()); + } + + // replace negative cooldowns by 0 + if (rec < 0) rec = 0; + if (catrec < 0) catrec = 0; + + // Hackfix: minimum cooldown for controlled creatures + if (!rec && !catrec && GetTypeId() == TYPEID_UNIT && GetCharmerGuid().IsPlayer()) + rec = 1500; // Global cooldown + + // no cooldown after applying spell mods + if (rec == 0 && catrec == 0) + return; + + catrecTime = catrec ? curTime + catrec / IN_MILLISECONDS : 0; + recTime = rec ? curTime + rec / IN_MILLISECONDS : catrecTime; + } + + // self spell cooldown + if (recTime > 0) + AddSpellCooldown(spellInfo->Id, itemId, recTime, catrecTime, cat); +} + +void Unit::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t endTime, time_t categoryEndTime, uint32 cat) +{ + // Do not replace longer cooldown + SpellCooldowns::iterator it = m_spellCooldowns.find(spellid); + if (it != m_spellCooldowns.end()) + { + it->second.end = endTime; + it->second.categoryEnd = categoryEndTime; + return; + } + SpellCooldown sc; + sc.end = endTime; + sc.categoryEnd = categoryEndTime; + sc.itemid = itemid; + sc.cat = cat; + m_spellCooldowns[spellid] = sc; +} + + +void Unit::WritePetSpellsCooldown(WorldPacket& data) +{ + uint8 cooldownsCount = GetSpellCooldownMap().size(); + data << uint8(cooldownsCount); + + time_t curTime = time(nullptr); + + for (SpellCooldowns::const_iterator itr = GetSpellCooldownMap().begin(); itr != GetSpellCooldownMap().end(); ++itr) + { + //time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0; + + data << uint16(itr->first); // spellid + data << uint16(0); // spell category? + data << uint32(IN_MILLISECONDS * (itr->second.end - curTime)); // cooldown + data << uint32(0); // category cooldown + } +} + + +void Unit::InitPlayerDisplayIds() +{ + PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass()); + if (!info) + return; + + uint8 gender = getGender(); + + switch (gender) + { + case GENDER_FEMALE: + SetDisplayId(info->displayId_f); + SetNativeDisplayId(info->displayId_f); + break; + case GENDER_MALE: + SetDisplayId(info->displayId_m); + SetNativeDisplayId(info->displayId_m); + break; + default: + return; + } +} diff --git a/src/game/ScriptMgr.cpp b/src/game/ScriptMgr.cpp index 36ae82b92..409dddd9f 100644 --- a/src/game/ScriptMgr.cpp +++ b/src/game/ScriptMgr.cpp @@ -1,8 +1,6 @@ /* * Copyright (C) 2005-2011 MaNGOS * Copyright (C) 2009-2011 MaNGOSZero - * Copyright (C) 2011-2016 Nostalrius - * Copyright (C) 2016-2017 Elysium Project * * 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 @@ -682,7 +680,7 @@ void ScriptMgr::LoadCreatureMovementScripts() void ScriptMgr::LoadDbScriptStrings() { - sObjectMgr.LoadMangosStrings(WorldDatabase, "db_script_string", MIN_DB_SCRIPT_STRING_ID, MAX_DB_SCRIPT_STRING_ID); + sObjectMgr.LoadMangosStrings(WorldDatabase, "db_script_string", MIN_DB_SCRIPT_STRING_ID, MAX_DB_SCRIPT_STRING_ID, false); std::set ids; @@ -790,7 +788,7 @@ void ScriptMgr::LoadEventIdScripts() BarGoLink bar(result->GetRowCount()); std::set eventIds; // Store possible event ids - + CollectPossibleEventIds(eventIds); do @@ -1241,7 +1239,7 @@ void ScriptMgr::LoadDatabase() void ScriptMgr::LoadScriptTexts() { sLog.outString("Loading Script Texts..."); - LoadMangosStrings(WorldDatabase, "script_texts", TEXT_SOURCE_TEXT_START, TEXT_SOURCE_TEXT_END); + LoadMangosStrings(WorldDatabase, "script_texts", TEXT_SOURCE_TEXT_START, TEXT_SOURCE_TEXT_END, true); QueryResult* result = WorldDatabase.PQuery("SELECT entry, sound, type, language, emote FROM script_texts WHERE entry BETWEEN %i AND %i", TEXT_SOURCE_GOSSIP_END, TEXT_SOURCE_TEXT_START); @@ -1303,7 +1301,7 @@ void ScriptMgr::LoadScriptTexts() void ScriptMgr::LoadScriptTextsCustom() { sLog.outString("Loading Custom Texts..."); - LoadMangosStrings(WorldDatabase, "custom_texts", TEXT_SOURCE_CUSTOM_START, TEXT_SOURCE_CUSTOM_END); + LoadMangosStrings(WorldDatabase, "custom_texts", TEXT_SOURCE_CUSTOM_START, TEXT_SOURCE_CUSTOM_END, true); QueryResult* result = WorldDatabase.PQuery("SELECT entry, sound, type, language, emote FROM custom_texts WHERE entry BETWEEN %i AND %i", TEXT_SOURCE_CUSTOM_END, TEXT_SOURCE_CUSTOM_START); @@ -1632,6 +1630,62 @@ void DoScriptText(int32 iTextEntry, WorldObject* pSource, Unit* pTarget) } } + +/** + * Function that either simulates or does script text for a map + * + * @param iTextEntry Entry of the text, stored in SD2-database, only type CHAT_TYPE_ZONE_YELL supported + * @param uiCreatureEntry Id of the creature of whom saying will be simulated + * @param pMap Given Map on which the map-wide text is displayed + * @param pCreatureSource Can be nullptr. If pointer to Creature is given, then the creature does the map-wide text + * @param pTarget Can be nullptr. Possible target for the text + */ +void DoOrSimulateScriptTextForMap(int32 iTextEntry, uint32 uiCreatureEntry, Map* pMap, Creature* pCreatureSource /*=nullptr*/, Unit* pTarget /*=nullptr*/) +{ + if (!pMap) + { + sLog.outError("DoOrSimulateScriptTextForMap entry %i, invalid Map pointer.", iTextEntry); + return; + } + + if (iTextEntry >= 0) + { + sLog.outError("DoOrSimulateScriptTextForMap with source entry %u for map %u attempts to process text entry %i, but text entry must be negative.", uiCreatureEntry, pMap->GetId(), iTextEntry); + return; + } + + CreatureInfo const* pInfo = GetCreatureTemplateStore(uiCreatureEntry); + if (!pInfo) + { + sLog.outError("DoOrSimulateScriptTextForMap has invalid source entry %u for map %u.", uiCreatureEntry, pMap->GetId()); + return; + } + + MangosStringLocale const* pData = sObjectMgr.GetMangosStringLocale(iTextEntry); + if (!pData) + { + sLog.outError("DoOrSimulateScriptTextForMap with source entry %u for map %u could not find text entry %i.", uiCreatureEntry, pMap->GetId(), iTextEntry); + return; + } + + sLog.outDebug("SD2: DoOrSimulateScriptTextForMap: text entry=%i, Sound=%u, Type=%u, Language=%u, Emote=%u", + iTextEntry, pData->SoundId, pData->Type, pData->LanguageId, pData->Emote); + + if (pData->Type != CHAT_TYPE_ZONE_YELL) + { + sLog.outError("DoSimulateScriptTextForMap entry %i has not supported chat type %u.", iTextEntry, pData->Type); + return; + } + + if (pData->SoundId) + pMap->PlayDirectSoundToMap(pData->SoundId); + + if (pCreatureSource) // If provided pointer for sayer, use direct version + pMap->MonsterYellToMap(pCreatureSource->GetObjectGuid(), iTextEntry, pData->LanguageId, pTarget); + else // Simulate yell + pMap->MonsterYellToMap(pInfo, iTextEntry, pData->LanguageId, pTarget); +} + void Script::RegisterSelf(bool bReportError) { if (uint32 id = sScriptMgr.GetScriptId(Name.c_str())) @@ -1732,4 +1786,3 @@ void ScriptMgr::FillSpellSummary() } } } - diff --git a/src/game/ScriptMgr.h b/src/game/ScriptMgr.h index 8f560a960..590d818ea 100644 --- a/src/game/ScriptMgr.h +++ b/src/game/ScriptMgr.h @@ -1,8 +1,6 @@ /* * Copyright (C) 2005-2011 MaNGOS * Copyright (C) 2009-2011 MaNGOSZero - * Copyright (C) 2011-2016 Nostalrius - * Copyright (C) 2016-2017 Elysium Project * * 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 @@ -640,6 +638,7 @@ class ScriptMgr //Generic scripting text function void DoScriptText(int32 textEntry, WorldObject* pSource, Unit* target = nullptr); +void DoOrSimulateScriptTextForMap(int32 iTextEntry, uint32 uiCreatureEntry, Map* pMap, Creature* pCreatureSource = nullptr, Unit* pTarget = nullptr); #define sScriptMgr MaNGOS::Singleton::Instance() diff --git a/src/game/Spells/Spell.cpp b/src/game/Spells/Spell.cpp index d52386f8b..e7f005cfc 100644 --- a/src/game/Spells/Spell.cpp +++ b/src/game/Spells/Spell.cpp @@ -1800,9 +1800,6 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& case 28796: // Poison Bolt Volley (Naxx, Faerlina) unMaxTargets = 10; break; - case 25991: // Poison Bolt Volley (AQ40, Pincess Huhuran) - unMaxTargets = 15; - break; } break; } @@ -1832,6 +1829,35 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& break; } + bool SelectClosestTargets = false; + + // custom selection cases + switch (m_spellInfo->SpellFamilyName) + { + case SPELLFAMILY_GENERIC: + { + switch (m_spellInfo->Id) + { + case 26052: // Poison Bolt Volley (AQ40, Princess Huhuran) + SelectClosestTargets = true; + break; + } + break; + } + case SPELLFAMILY_HUNTER: + { + switch (m_spellInfo->Id) + { + case 26180: // Wyvern Sting (AQ40, Princess Huhuran) + SelectClosestTargets = true; + break; + } + break; + } + default: + break; + } + switch (targetMode) { case TARGET_TOTEM_EARTH: @@ -2067,7 +2093,14 @@ void Spell::SetTargetMap(SpellEffectIndex effIndex, uint32 targetMode, UnitList& if ((*itr)->IsWithinDist(m_caster, minDist)) targetUnitMap.erase(itr); } - } + } + if (SelectClosestTargets && unMaxTargets && targetUnitMap.size() > unMaxTargets) + { + targetUnitMap.sort(TargetDistanceOrderNear(m_caster)); + UnitList::iterator itr = targetUnitMap.begin(); + advance(itr, unMaxTargets); + targetUnitMap.erase(itr, targetUnitMap.end()); + } break; } case TARGET_AREAEFFECT_INSTANT: @@ -2981,7 +3014,9 @@ void Spell::prepare(SpellCastTargets const* targets, Aura* triggeredByAura) SendChannelUpdate(0); triggeredByAura->GetHolder()->SetAuraDuration(0); } + SendCastResult(result); + //SendInterrupted(0); finish(false); return; } @@ -4661,8 +4696,8 @@ SpellCastResult Spell::CheckCast(bool strict) } } - if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR_PASSIVE) && - (m_caster->HasSpellCooldown(m_spellInfo->Id) || m_caster->HasSpellCategoryCooldown(spellCat))) + if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR_PASSIVE) + && !m_IsTriggeredSpell && (m_caster->HasSpellCooldown(m_spellInfo->Id) || m_caster->HasSpellCategoryCooldown(spellCat))) { if (m_triggeredByAuraSpell) return SPELL_FAILED_DONT_REPORT; @@ -4711,11 +4746,11 @@ SpellCastResult Spell::CheckCast(bool strict) { if (m_spellInfo->Attributes & SPELL_ATTR_OUTDOORS_ONLY && !m_caster->GetTerrain()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) - return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_ONLY_OUTDOORS; + return SPELL_FAILED_ONLY_OUTDOORS; if (m_spellInfo->Attributes & SPELL_ATTR_INDOORS_ONLY && m_caster->GetTerrain()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) - return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_ONLY_INDOORS; + return SPELL_FAILED_ONLY_INDOORS; } // caster state requirements @@ -5870,13 +5905,7 @@ SpellCastResult Spell::CheckCast(bool strict) switch (m_spellInfo->Id) { - case 25863: // spell used by ingame item for Black Qiraji mount (legendary reward) - case 26655: // spells also related to Black Qiraji mount but use/trigger unknown - case 26656: - case 31700: - if (m_caster->GetMapId() == 531) - isAQ40Mount = true; - break; + case 25863: // spell used by the Black Qiraji Crystal script when mounting inside AQ40 case 25953: // spells of the 4 regular AQ40 mounts case 26054: case 26055: @@ -5889,6 +5918,8 @@ SpellCastResult Spell::CheckCast(bool strict) else return SPELL_FAILED_NOT_HERE; default: + if ((m_caster->GetMapId() == 531 && m_caster->GetTerrain()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ()))) + isAQ40Mount = true; break; } diff --git a/src/game/Spells/SpellEffects.cpp b/src/game/Spells/SpellEffects.cpp index 4e8725c44..6d8ade48d 100644 --- a/src/game/Spells/SpellEffects.cpp +++ b/src/game/Spells/SpellEffects.cpp @@ -4032,20 +4032,24 @@ void Spell::EffectSummonObjectWild(SpellEffectIndex eff_idx) if (!target) target = m_caster; - float x, y, z; + float x, y, z, o; if (m_targets.m_targetMask & TARGET_FLAG_DEST_LOCATION) { x = m_targets.m_destX; y = m_targets.m_destY; z = m_targets.m_destZ; + o = target->GetOrientation(); } else - m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); + { + m_caster->GetPosition(x, y, z); + o = m_caster->GetOrientation(); + } Map *map = target->GetMap(); if (!pGameObj->Create(map->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), gameobject_id, map, - x, y, z, target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, GO_ANIMPROGRESS_DEFAULT, GO_STATE_READY)) + x, y, z, o, 0.0f, 0.0f, 0.0f, 0.0f, GO_ANIMPROGRESS_DEFAULT, GO_STATE_READY)) { delete pGameObj; return; @@ -4374,9 +4378,9 @@ void Spell::EffectScriptEffect(SpellEffectIndex eff_idx) // Two separate mounts depending on area id (allows use both in and out of specific instance) if (unitTarget->GetAreaId() == 3428) - unitTarget->CastSpell(unitTarget, 25863, false); + unitTarget->CastSpell(unitTarget, 25863, true, m_CastItem); else - unitTarget->CastSpell(unitTarget, 26655, false); + unitTarget->CastSpell(unitTarget, 26655, true, m_CastItem); return; } diff --git a/src/game/Spells/SpellEntry.cpp b/src/game/Spells/SpellEntry.cpp index 745238c29..63c980b84 100644 --- a/src/game/Spells/SpellEntry.cpp +++ b/src/game/Spells/SpellEntry.cpp @@ -176,6 +176,12 @@ void SpellEntry::ComputeBinary() } } _isBinary = foundNoDamageAura; + if (Id == 26143) { // SPELL_MIND_FLAY (C'Thuns Eye Tentacles) + _isBinary = true; + } + else if (Id == 26478) { + _isBinary = true; // SPELL_GROUND_RUPTURE_NATURE (C'thuns Giant tentacles ground rupture) + } } void SpellEntry::ComputeDispel() diff --git a/src/game/UnitAuraProcHandler.cpp b/src/game/UnitAuraProcHandler.cpp index 06be470c0..aef413aa9 100644 --- a/src/game/UnitAuraProcHandler.cpp +++ b/src/game/UnitAuraProcHandler.cpp @@ -516,6 +516,8 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura return SPELL_AURA_PROC_OK; } // Viscidus Frost Weakness + // Disabled for now, handled on Viscidus script + /* case 25926: { if (!procSpell) @@ -536,25 +538,25 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura break; } + */ // Viscidus Freeze case 25937: { if (procSpell) { - if (GetSchoolMask(procSpell->School) != SPELL_SCHOOL_MASK_NORMAL) + // Wand spell entry marked as physical, we need to add an exception here + if (GetSchoolMask(procSpell->School) != SPELL_SCHOOL_MASK_NORMAL || procSpell->Id == 5019) return SPELL_AURA_PROC_FAILED; } - else - return SPELL_AURA_PROC_FAILED; ++triggeredByAura->GetModifier()->m_amount; triggerAmount = triggeredByAura->GetModifier()->m_amount; - if (triggerAmount == 25) + if (triggerAmount == 50) MonsterTextEmote(-1531044, NULL); // Cracks - else if (triggerAmount == 50) + else if (triggerAmount == 100) MonsterTextEmote(-1531045, NULL); // Shatter - else if (triggerAmount == 75) + else if (triggerAmount == 150) { RemoveAurasDueToSpell(25937); triggered_spell_id = 25938; // Explode diff --git a/src/scripts/eastern_kingdoms/burning_steppes/blackrock_depths/boss_emperor_dagran_thaurissan.cpp b/src/scripts/eastern_kingdoms/burning_steppes/blackrock_depths/boss_emperor_dagran_thaurissan.cpp index 675cf8829..af5e92149 100644 --- a/src/scripts/eastern_kingdoms/burning_steppes/blackrock_depths/boss_emperor_dagran_thaurissan.cpp +++ b/src/scripts/eastern_kingdoms/burning_steppes/blackrock_depths/boss_emperor_dagran_thaurissan.cpp @@ -211,7 +211,7 @@ struct boss_moira_bronzebeardAI : public ScriptedAI else m_uiSmite_Timer -= uiDiff; - //Heal_Timer + //healTimer if (m_uiHeal_Timer < uiDiff) { if (Creature* pEmperor = m_pInstance->instance->GetCreature(m_pInstance->GetData64(DATA_EMPEROR))) diff --git a/src/scripts/eastern_kingdoms/stranglethorn_vale/zulgurub/boss_jindo.cpp b/src/scripts/eastern_kingdoms/stranglethorn_vale/zulgurub/boss_jindo.cpp index faaa1d33e..acc6addc3 100644 --- a/src/scripts/eastern_kingdoms/stranglethorn_vale/zulgurub/boss_jindo.cpp +++ b/src/scripts/eastern_kingdoms/stranglethorn_vale/zulgurub/boss_jindo.cpp @@ -307,7 +307,7 @@ struct mob_healing_wardAI : public ScriptedAI void UpdateAI(const uint32 diff) { - //Heal_Timer + //healTimer if (Heal_Timer < diff) { if (m_pInstance) diff --git a/src/scripts/kalimdor/silithus/ruins_of_ahnqiraj/boss_rajaxx.cpp b/src/scripts/kalimdor/silithus/ruins_of_ahnqiraj/boss_rajaxx.cpp index 9886015b2..a23a966cd 100644 --- a/src/scripts/kalimdor/silithus/ruins_of_ahnqiraj/boss_rajaxx.cpp +++ b/src/scripts/kalimdor/silithus/ruins_of_ahnqiraj/boss_rajaxx.cpp @@ -238,6 +238,12 @@ struct boss_rajaxxAI : public ScriptedAI DoScriptText(SAY_DEATH, m_creature); if (m_pInstance) m_pInstance->SetData(TYPE_RAJAXX, DONE); + + // According to http://wowwiki.wikia.com/wiki/Cenarion_Circle_reputation_guide + // and http://wowwiki.wikia.com/wiki/General_Rajaxx, + // When Rajaxx dies, players should gain 90 (post-"nerf" 150) reputation for each + // of the NPCs that are still alive. + OnKillReputationReward(); } void KilledUnit(Unit *pKilled) @@ -271,6 +277,41 @@ struct boss_rajaxxAI : public ScriptedAI return false; } + void OnKillReputationReward() + { + FactionEntry const *factionEntry = sFactionStore.LookupEntry(609); // Cenarion Circle + if (!factionEntry) { + sLog.outError("Rajaxx justDied, unable to find Cenarion Circle faction"); + return; + } + std::list helpers; + GetCreatureListWithEntryInGrid(helpers, m_creature, { 15473, 15478, 15471, 987001 }, 400.0f); + + if (!helpers.size()) + return; + int alive = 0; + for (auto it : helpers) + if (it->isAlive()) ++alive; + + if (Player* pLootRecepient = m_creature->GetLootRecipient()) { + if (Group* pGroup = pLootRecepient->GetGroup()) { + for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) + { + Player* pGroupGuy = itr->getSource(); + if (!pGroupGuy || !pGroupGuy->IsInWorld()) + continue; + + uint32 current_reputation_rank1 = pGroupGuy->GetReputationMgr().GetRank(factionEntry); + if (factionEntry && current_reputation_rank1 <= 7) { + for(int i = 0; i < alive; i++) + pGroupGuy->GetReputationMgr().ModifyReputation(factionEntry, 90); + + } + } + } + } + } + void UpdateAI(const uint32 uiDiff) { // Waves launcher diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_bug_trio.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_bug_trio.cpp index 469897499..ec90add9a 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_bug_trio.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_bug_trio.cpp @@ -14,176 +14,176 @@ the script is using Magmadar's panic spell which has the exact same range and du enum { - // emote - EMOTE_DEVOUR = -1388004, + // emote + EMOTE_DEVOUR = -1388004, - // kri - SPELL_THRASH = 3391, - SPELL_CLEAVE = 19983, - SPELL_TOXIC_VOLLEY = 25812, - SPELL_SUMMON_CLOUD = 25786, // should be 26590 -> summons 15933 -> casts 25786 ("Toxic Vapors") in EventAI - // the trigger that spawns was meleeing players and keeping them in combat, some better way to make it non-aggro? - // yauj - SPELL_RAVAGE = 24213, - SPELL_HEAL = 25807, - SPELL_FEAR = 19408, // should be spell 25807, but will need to fix that spell fearing 1 person max first + // kri + SPELL_THRASH = 3391, + SPELL_CLEAVE = 19983, + SPELL_TOXIC_VOLLEY = 25812, + SPELL_SUMMON_CLOUD = 25786, // should be 26590 -> summons 15933 -> casts 25786 ("Toxic Vapors") in EventAI + // the trigger that spawns was meleeing players and keeping them in combat, some better way to make it non-aggro? + // yauj + SPELL_RAVAGE = 24213, + SPELL_HEAL = 25807, + SPELL_FEAR = 19408, // should be spell 25807, but will need to fix that spell fearing 1 person max first - // vem - SPELL_CHARGE = 26561, - SPELL_KNOCKBACK = 18813, - SPELL_KNOCKDOWN = 19128, - SPELL_VENGEANCE = 25790, + // vem + SPELL_CHARGE = 26561, + SPELL_KNOCKBACK = 18813, + SPELL_KNOCKDOWN = 19128, + SPELL_VENGEANCE = 25790, }; // Base class for handling shared mechanics struct boss_bug_trioAI : public ScriptedAI { - boss_bug_trioAI(Creature* pCreature) : ScriptedAI(pCreature) - { - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); - Reset(); - } + boss_bug_trioAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + Reset(); + } - ScriptedInstance* m_pInstance; - uint32 m_uiDevourTimer; - uint32 m_uiEvadeCheckTimer; - bool m_bIsEating; + ScriptedInstance* m_pInstance; + uint32 m_uiDevourTimer; + uint32 m_uiEvadeCheckTimer; + bool m_bIsEating; - void Reset() override - { - m_bIsEating = false; - m_uiEvadeCheckTimer = 2500; - } + void Reset() override + { + m_bIsEating = false; + m_uiEvadeCheckTimer = 2500; + } - void EnterEvadeMode() override - { - // If somehow a raid wipes during devour phase, restore normal speed/behavior - m_creature->UpdateSpeed(MOVE_RUN, false); - ScriptedAI::EnterEvadeMode(); - } + void EnterEvadeMode() override + { + // If somehow a raid wipes during devour phase, restore normal speed/behavior + m_creature->UpdateSpeed(MOVE_RUN, false); + ScriptedAI::EnterEvadeMode(); + } - void Aggro(Unit* /*pWho*/) override - { - // Reset the slain bug count on pull - if (m_pInstance) - m_pInstance->SetData(TYPE_BUG_TRIO, FAIL); - } + void Aggro(Unit* /*pWho*/) override + { + // Reset the slain bug count on pull + if (m_pInstance) + m_pInstance->SetData(TYPE_BUG_TRIO, FAIL); + } - void MoveInLineOfSight(Unit* pWho) override - { - // The bug trio have a larger than normal aggro radius - if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 65.0f) && m_creature->IsWithinLOSInMap(pWho) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) - { - AttackStart(pWho); - } - ScriptedAI::MoveInLineOfSight(pWho); - } + void MoveInLineOfSight(Unit* pWho) override + { + // The bug trio have a larger than normal aggro radius + if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 60.0f) && m_creature->IsWithinLOSInMap(pWho) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) + { + AttackStart(pWho); + } + ScriptedAI::MoveInLineOfSight(pWho); + } - void JustDied(Unit* /*pKiller*/) override - { - // If another bug is still alive, prevent looting and trigger corpse despawn - if (m_pInstance->GetData(TYPE_BUG_TRIO) != DONE) - { - m_creature->SetLootRecipient(NULL); - m_creature->ForcedDespawn(4000); + void JustDied(Unit* /*pKiller*/) override + { + // If another bug is still alive, prevent looting and trigger corpse despawn + if (m_pInstance->GetData(TYPE_BUG_TRIO) != DONE) + { + m_creature->SetLootRecipient(NULL); + m_creature->ForcedDespawn(4000); - if (Creature* pKri = m_pInstance->GetSingleCreatureFromStorage(NPC_KRI)) - if (boss_bug_trioAI* pFakerAI = dynamic_cast(pKri->AI())) - pFakerAI->TriggerDevour(m_creature); - if (Creature* pYauj = m_pInstance->GetSingleCreatureFromStorage(NPC_PRINCESS_YAUJ)) - if (boss_bug_trioAI* pFakerAI = dynamic_cast(pYauj->AI())) - pFakerAI->TriggerDevour(m_creature); - if (Creature* pVem = m_pInstance->GetSingleCreatureFromStorage(NPC_VEM)) - if (boss_bug_trioAI* pFakerAI = dynamic_cast(pVem->AI())) - pFakerAI->TriggerDevour(m_creature); + if (Creature* pKri = m_pInstance->GetSingleCreatureFromStorage(NPC_KRI)) + if (boss_bug_trioAI* pFakerAI = dynamic_cast(pKri->AI())) + pFakerAI->TriggerDevour(m_creature); + if (Creature* pYauj = m_pInstance->GetSingleCreatureFromStorage(NPC_PRINCESS_YAUJ)) + if (boss_bug_trioAI* pFakerAI = dynamic_cast(pYauj->AI())) + pFakerAI->TriggerDevour(m_creature); + if (Creature* pVem = m_pInstance->GetSingleCreatureFromStorage(NPC_VEM)) + if (boss_bug_trioAI* pFakerAI = dynamic_cast(pVem->AI())) + pFakerAI->TriggerDevour(m_creature); - m_pInstance->SetData(TYPE_BUG_TRIO, SPECIAL); - } - } + m_pInstance->SetData(TYPE_BUG_TRIO, SPECIAL); + } + } - void CorpseRemoved(uint32& /*uiRespawnDelay*/) override - { - // Emote on devoured - DoScriptText(EMOTE_DEVOUR, m_creature); - } + void CorpseRemoved(uint32& /*uiRespawnDelay*/) override + { + // Emote on devoured + DoScriptText(EMOTE_DEVOUR, m_creature); + } - void MovementInform(uint32 uiMotionType, uint32 /*uiPointId*/) override - { - if (uiMotionType != POINT_MOTION_TYPE) - return; + void MovementInform(uint32 uiMotionType, uint32 /*uiPointId*/) override + { + if (uiMotionType != POINT_MOTION_TYPE) + return; - // Stop movement after reaching corpse - m_creature->GetMotionMaster()->MoveIdle(); - } + // Stop movement after reaching corpse + m_creature->GetMotionMaster()->MoveIdle(); + } - void TriggerDevour(Unit* pWho) - { - if (m_creature->isAlive()) - { - m_uiDevourTimer = 4000; - m_bIsEating = true; + void TriggerDevour(Unit* pWho) + { + if (m_creature->isAlive()) + { + m_uiDevourTimer = 4000; + m_bIsEating = true; - // Sprint to dead bug and clear target - m_creature->UpdateSpeed(MOVE_RUN, true, 2.7f); - m_creature->GetMotionMaster()->MovePoint(1, pWho->GetPositionX(), pWho->GetPositionY(), pWho->GetPositionZ()); - m_creature->SetTargetGuid(ObjectGuid()); - } - } + // Sprint to dead bug and clear target + m_creature->UpdateSpeed(MOVE_RUN, true, 2.7f); + m_creature->GetMotionMaster()->MovePoint(1, pWho->GetPositionX(), pWho->GetPositionY(), pWho->GetPositionZ()); + m_creature->SetTargetGuid(ObjectGuid()); + } + } - void LeashEncounter() - { - // Force evade all 3 bugs and respawn any that are already dead. We have to do this manually or linked bugs don't evade/respawn on region triggered EnterEvadeMode. - if (Creature* pKri = m_pInstance->GetSingleCreatureFromStorage(NPC_KRI)) - if (pKri->isDead()) pKri->Respawn(); else pKri->AI()->EnterEvadeMode(); - if (Creature* pYauj = m_pInstance->GetSingleCreatureFromStorage(NPC_PRINCESS_YAUJ)) - if (pYauj->isDead()) pYauj->Respawn(); else pYauj->AI()->EnterEvadeMode(); - if (Creature* pVem = m_pInstance->GetSingleCreatureFromStorage(NPC_VEM)) - if (pVem->isDead()) pVem->Respawn(); else pVem->AI()->EnterEvadeMode(); - } + void LeashEncounter() + { + // Force evade all 3 bugs and respawn any that are already dead. We have to do this manually or linked bugs don't evade/respawn on region triggered EnterEvadeMode. + if (Creature* pKri = m_pInstance->GetSingleCreatureFromStorage(NPC_KRI)) + if (pKri->isDead()) pKri->Respawn(); else pKri->AI()->EnterEvadeMode(); + if (Creature* pYauj = m_pInstance->GetSingleCreatureFromStorage(NPC_PRINCESS_YAUJ)) + if (pYauj->isDead()) pYauj->Respawn(); else pYauj->AI()->EnterEvadeMode(); + if (Creature* pVem = m_pInstance->GetSingleCreatureFromStorage(NPC_VEM)) + if (pVem->isDead()) pVem->Respawn(); else pVem->AI()->EnterEvadeMode(); + } - virtual bool UpdateBugAI(const uint32 /*uiDiff*/) { return true; } + virtual bool UpdateBugAI(const uint32 /*uiDiff*/) { return true; } - void UpdateAI(const uint32 uiDiff) override - { - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; + void UpdateAI(const uint32 uiDiff) override + { + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; - if (m_bIsEating) - { - if (m_uiDevourTimer < uiDiff) - { - // Reset threat, heal to full, restore target, and remove temporary speed buff - DoResetThreat(); - m_bIsEating = false; - m_creature->SetHealth(m_creature->GetMaxHealth()); - m_creature->SetTargetGuid(m_creature->getVictim()->GetObjectGuid()); - m_creature->UpdateSpeed(MOVE_RUN, false); - DoStartMovement(m_creature->getVictim()); - } - else - { - m_uiDevourTimer -= uiDiff; - return; - } - } + if (m_bIsEating) + { + if (m_uiDevourTimer < uiDiff) + { + // Reset threat, heal to full, restore target, and remove temporary speed buff + DoResetThreat(); + m_bIsEating = false; + m_creature->SetHealth(m_creature->GetMaxHealth()); + m_creature->SetTargetGuid(m_creature->getVictim()->GetObjectGuid()); + m_creature->UpdateSpeed(MOVE_RUN, false); + DoStartMovement(m_creature->getVictim()); + } + else + { + m_uiDevourTimer -= uiDiff; + return; + } + } - // Call bug specific virtual function - if (!UpdateBugAI(uiDiff)) - return; + // Call bug specific virtual function + if (!UpdateBugAI(uiDiff)) + return; - DoMeleeAttackIfReady(); + DoMeleeAttackIfReady(); - // Evade if any bug leaves the room - if (m_uiEvadeCheckTimer < uiDiff) - { - m_uiEvadeCheckTimer = 2500; - if (m_creature->GetPositionY() < 2060 && m_creature->GetPositionX() > -8600) - LeashEncounter(); - } - else - m_uiEvadeCheckTimer -= uiDiff; - } + // Evade if any bug leaves the room + if (m_uiEvadeCheckTimer < uiDiff) + { + m_uiEvadeCheckTimer = 2500; + if (m_creature->GetPositionY() < 2060 && m_creature->GetPositionX() > -8600) + LeashEncounter(); + } + else + m_uiEvadeCheckTimer -= uiDiff; + } }; //########## @@ -192,57 +192,57 @@ struct boss_bug_trioAI : public ScriptedAI struct boss_kriAI : public boss_bug_trioAI { - boss_kriAI(Creature* pCreature) : boss_bug_trioAI(pCreature) { Reset(); } + boss_kriAI(Creature* pCreature) : boss_bug_trioAI(pCreature) { Reset(); } - uint32 m_uiThrashTimer; - uint32 m_uiCleaveTimer; - uint32 m_uiToxicVolleyTimer; + uint32 m_uiThrashTimer; + uint32 m_uiCleaveTimer; + uint32 m_uiToxicVolleyTimer; - void Reset() override - { - m_uiCleaveTimer = urand(4000, 8000); - m_uiThrashTimer = urand(4000, 7000); - m_uiToxicVolleyTimer = urand(8000, 10000); - } + void Reset() override + { + m_uiCleaveTimer = urand(4000, 8000); + m_uiThrashTimer = urand(4000, 7000); + m_uiToxicVolleyTimer = urand(8000, 10000); + } - void JustDied(Unit* pKiller) override - { - // Spawn Poison Cloud on death - DoCastSpellIfCan(m_creature, SPELL_SUMMON_CLOUD, CAST_TRIGGERED); - boss_bug_trioAI::JustDied(pKiller); - } + void JustDied(Unit* pKiller) override + { + // Spawn Poison Cloud on death + DoCastSpellIfCan(m_creature, SPELL_SUMMON_CLOUD, CAST_TRIGGERED); + boss_bug_trioAI::JustDied(pKiller); + } - bool UpdateBugAI(const uint32 uiDiff) - { - // Cleave - if (m_uiCleaveTimer < uiDiff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_CLEAVE) == CAST_OK) - m_uiCleaveTimer = urand(5000, 12000); - } - else - m_uiCleaveTimer -= uiDiff; + bool UpdateBugAI(const uint32 uiDiff) + { + // Cleave + if (m_uiCleaveTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_CLEAVE) == CAST_OK) + m_uiCleaveTimer = urand(5000, 12000); + } + else + m_uiCleaveTimer -= uiDiff; - // Toxic Volley - if (m_uiToxicVolleyTimer < uiDiff) - { - if (DoCastSpellIfCan(m_creature, SPELL_TOXIC_VOLLEY) == CAST_OK) - m_uiToxicVolleyTimer = urand(8000, 14000); - } - else - m_uiToxicVolleyTimer -= uiDiff; + // Toxic Volley + if (m_uiToxicVolleyTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_TOXIC_VOLLEY) == CAST_OK) + m_uiToxicVolleyTimer = urand(8000, 14000); + } + else + m_uiToxicVolleyTimer -= uiDiff; - // Thrash - if (m_uiThrashTimer < uiDiff) - { - if (DoCastSpellIfCan(m_creature, SPELL_THRASH) == CAST_OK) - m_uiThrashTimer = urand(2000, 8000); - } - else - m_uiThrashTimer -= uiDiff; + // Thrash + if (m_uiThrashTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_THRASH) == CAST_OK) + m_uiThrashTimer = urand(2000, 8000); + } + else + m_uiThrashTimer -= uiDiff; - return true; - } + return true; + } }; //############### @@ -251,95 +251,95 @@ struct boss_kriAI : public boss_bug_trioAI struct boss_yaujAI : public boss_bug_trioAI { - boss_yaujAI(Creature* pCreature) : boss_bug_trioAI(pCreature) { Reset(); } + boss_yaujAI(Creature* pCreature) : boss_bug_trioAI(pCreature) { Reset(); } - uint32 m_uiHealTimer; - uint32 m_uiFearTimer; - uint32 m_uiRavageTimer; + uint32 m_uiHealTimer; + uint32 m_uiFearTimer; + uint32 m_uiRavageTimer; - void Reset() override - { - m_uiHealTimer = urand(10000, 20000); - m_uiFearTimer = urand(10000, 20000); - m_uiRavageTimer = urand(4000, 9000); - } + void Reset() override + { + m_uiHealTimer = urand(10000, 20000); + m_uiFearTimer = urand(10000, 20000); + m_uiRavageTimer = urand(4000, 9000); + } - void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpellEntry) override - { - // Yauj is immune to Curse of Tongues and Mind-Numbing Poison. These spells don't have a mechanic type to set an immunity mask to in vanilla so we simply remove them. - if (m_creature->HasAuraType(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK)) - m_creature->RemoveSpellsCausingAura(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK); - } + void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpellEntry) override + { + // Yauj is immune to Curse of Tongues and Mind-Numbing Poison. These spells don't have a mechanic type to set an immunity mask to in vanilla so we simply remove them. + if (m_creature->HasAuraType(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK)) + m_creature->RemoveSpellsCausingAura(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK); + } - void JustDied(Unit* pKiller) override - { - // Spawn 10 Yauj Brood on death - float fX, fY, fZ; - const float aCenterLoc[3] = { -8590.0f, 2138.0f, 0.0f }; // define a central point in the room to use for LOS check + void JustDied(Unit* pKiller) override + { + // Spawn 10 Yauj Brood on death + float fX, fY, fZ; + const float aCenterLoc[3] = { -8590.0f, 2138.0f, 0.0f }; // define a central point in the room to use for LOS check - for (int i = 0; i < 10; ++i) - { - m_creature->GetRandomPoint(m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), 40.0f, fX, fY, fZ); - // prevent Yauj Brood from spawning under the world or in walls -- re-roll if random point is not in LOS - if (m_creature->GetMap()->isInLineOfSight(aCenterLoc[0], aCenterLoc[1], aCenterLoc[2], fX, fY, fZ)) - m_creature->SummonCreature(NPC_YAUJ_BROOD, fX, fY, fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 10000); - else - --i; - } - boss_bug_trioAI::JustDied(pKiller); - } + for (int i = 0; i < 10; ++i) + { + m_creature->GetRandomPoint(m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), 40.0f, fX, fY, fZ); + // prevent Yauj Brood from spawning under the world or in walls -- re-roll if random point is not in LOS + if (m_creature->GetMap()->isInLineOfSight(aCenterLoc[0], aCenterLoc[1], aCenterLoc[2], fX, fY, fZ)) + m_creature->SummonCreature(NPC_YAUJ_BROOD, fX, fY, fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 10000); + else + --i; + } + boss_bug_trioAI::JustDied(pKiller); + } - void JustSummoned(Creature* pSummoned) override - { - if (pSummoned->GetEntry() != NPC_YAUJ_BROOD) - return; + void JustSummoned(Creature* pSummoned) override + { + if (pSummoned->GetEntry() != NPC_YAUJ_BROOD) + return; - pSummoned->SetInCombatWithZone(); - } + pSummoned->SetInCombatWithZone(); + } - bool UpdateBugAI(const uint32 uiDiff) - { - // Fear - if (m_uiFearTimer < uiDiff) - { - if (DoCastSpellIfCan(m_creature, SPELL_FEAR) == CAST_OK) - { - DoResetThreat(); - m_uiFearTimer = 20000; - } - } - else - m_uiFearTimer -= uiDiff; + bool UpdateBugAI(const uint32 uiDiff) + { + // Fear + if (m_uiFearTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_FEAR) == CAST_OK) + { + DoResetThreat(); + m_uiFearTimer = 20000; + } + } + else + m_uiFearTimer -= uiDiff; - // Heal - if (m_uiHealTimer < uiDiff) - { - // Yauj prioritizes herself with heal when under 93% - if (m_creature->GetHealthPercent() <= 93.0f) - { - if (DoCastSpellIfCan(m_creature, SPELL_HEAL) == CAST_OK) - m_uiHealTimer = 12000; - } - else if (Unit* pTarget = DoSelectLowestHpFriendly(100.0f)) - { - if (DoCastSpellIfCan(pTarget, SPELL_HEAL) == CAST_OK) - m_uiHealTimer = 12000; - } - } - else - m_uiHealTimer -= uiDiff; + // Heal + if (m_uiHealTimer < uiDiff) + { + // Yauj prioritizes herself with heal when under 93% + if (m_creature->GetHealthPercent() <= 93.0f) + { + if (DoCastSpellIfCan(m_creature, SPELL_HEAL) == CAST_OK) + m_uiHealTimer = 12000; + } + else if (Unit* pTarget = DoSelectLowestHpFriendly(100.0f)) + { + if (DoCastSpellIfCan(pTarget, SPELL_HEAL) == CAST_OK) + m_uiHealTimer = 12000; + } + } + else + m_uiHealTimer -= uiDiff; - // Ravage - if (m_uiRavageTimer < uiDiff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_RAVAGE) == CAST_OK) - m_uiRavageTimer = urand(12000, 20000); - } - else - m_uiRavageTimer -= uiDiff; + // Ravage + if (m_uiRavageTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_RAVAGE) == CAST_OK) + m_uiRavageTimer = urand(12000, 20000); + } + else + m_uiRavageTimer -= uiDiff; - return true; - } + return true; + } }; //##### @@ -348,110 +348,110 @@ struct boss_yaujAI : public boss_bug_trioAI struct boss_vemAI : public boss_bug_trioAI { - boss_vemAI(Creature* pCreature) : boss_bug_trioAI(pCreature) { Reset(); } + boss_vemAI(Creature* pCreature) : boss_bug_trioAI(pCreature) { Reset(); } - uint32 m_uiChargeTimer; - uint32 m_uiKnockBackTimer; - uint32 m_uiKnockdownTimer; + uint32 m_uiChargeTimer; + uint32 m_uiKnockBackTimer; + uint32 m_uiKnockdownTimer; - void Reset() override - { - m_uiChargeTimer = urand(10000, 15000); - m_uiKnockBackTimer = urand(15000, 20000); - m_uiKnockdownTimer = urand(5000, 8000); - } + void Reset() override + { + m_uiChargeTimer = urand(10000, 15000); + m_uiKnockBackTimer = urand(15000, 20000); + m_uiKnockdownTimer = urand(5000, 8000); + } - void JustDied(Unit* pKiller) override - { - // Enrage the other bugs on death - DoCastSpellIfCan(m_creature, SPELL_VENGEANCE, CAST_TRIGGERED); - boss_bug_trioAI::JustDied(pKiller); - } + void JustDied(Unit* pKiller) override + { + // Enrage the other bugs on death + DoCastSpellIfCan(m_creature, SPELL_VENGEANCE, CAST_TRIGGERED); + boss_bug_trioAI::JustDied(pKiller); + } - void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) override - { - if ((pSpell->Id == SPELL_KNOCKBACK) && pTarget->GetTypeId() == TYPEID_PLAYER) - { - if (m_creature->getThreatManager().getThreat(m_creature->getVictim())) - m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(), -80); - } - } + void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) override + { + if ((pSpell->Id == SPELL_KNOCKBACK) && pTarget->GetTypeId() == TYPEID_PLAYER) + { + if (m_creature->getThreatManager().getThreat(m_creature->getVictim())) + m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(), -80); + } + } - bool UpdateBugAI(const uint32 uiDiff) - { - // Charge - if (m_uiChargeTimer < uiDiff) - { - // Only charge targets outside of melee range - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, SPELL_CHARGE, SELECT_FLAG_NOT_IN_MELEE_RANGE)) - { - if (DoCastSpellIfCan(pTarget, SPELL_CHARGE) == CAST_OK) - m_uiChargeTimer = urand(15000, 20000); - } - } - else - m_uiChargeTimer -= uiDiff; + bool UpdateBugAI(const uint32 uiDiff) + { + // Charge + if (m_uiChargeTimer < uiDiff) + { + // Only charge targets outside of melee range + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, SPELL_CHARGE, SELECT_FLAG_NOT_IN_MELEE_RANGE)) + { + if (DoCastSpellIfCan(pTarget, SPELL_CHARGE) == CAST_OK) + m_uiChargeTimer = urand(15000, 20000); + } + } + else + m_uiChargeTimer -= uiDiff; - // Knock Away - if (m_uiKnockBackTimer < uiDiff) - { - if (m_creature->IsWithinMeleeRange(m_creature->getVictim()) && !m_creature->getVictim()->hasUnitState(UNIT_STAT_STUNNED)) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_KNOCKBACK) == CAST_OK) - m_uiKnockBackTimer = urand(10000, 14000); - } - } - else - m_uiKnockBackTimer -= uiDiff; + // Knock Away + if (m_uiKnockBackTimer < uiDiff) + { + if (m_creature->IsWithinMeleeRange(m_creature->getVictim()) && !m_creature->getVictim()->hasUnitState(UNIT_STAT_STUNNED)) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_KNOCKBACK) == CAST_OK) + m_uiKnockBackTimer = urand(10000, 14000); + } + } + else + m_uiKnockBackTimer -= uiDiff; - // Knockdown - if (m_uiKnockdownTimer < uiDiff) - { - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, SPELL_KNOCKDOWN, SELECT_FLAG_IN_MELEE_RANGE)) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_KNOCKDOWN) == CAST_OK) - m_uiKnockdownTimer = urand(15000, 20000); - } - } - else - m_uiKnockdownTimer -= uiDiff; + // Knockdown + if (m_uiKnockdownTimer < uiDiff) + { + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, SPELL_KNOCKDOWN, SELECT_FLAG_IN_MELEE_RANGE)) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_KNOCKDOWN) == CAST_OK) + m_uiKnockdownTimer = urand(15000, 20000); + } + } + else + m_uiKnockdownTimer -= uiDiff; - return true; - } + return true; + } }; CreatureAI* GetAI_boss_kri(Creature* pCreature) { - return new boss_kriAI(pCreature); + return new boss_kriAI(pCreature); } CreatureAI* GetAI_boss_yauj(Creature* pCreature) { - return new boss_yaujAI(pCreature); + return new boss_yaujAI(pCreature); } CreatureAI* GetAI_boss_vem(Creature* pCreature) { - return new boss_vemAI(pCreature); + return new boss_vemAI(pCreature); } void AddSC_bug_trio() { - Script* pNewScript; + Script* pNewScript; - pNewScript = new Script; - pNewScript->Name = "boss_kri"; - pNewScript->GetAI = &GetAI_boss_kri; - pNewScript->RegisterSelf(); + pNewScript = new Script; + pNewScript->Name = "boss_kri"; + pNewScript->GetAI = &GetAI_boss_kri; + pNewScript->RegisterSelf(); - pNewScript = new Script; - pNewScript->Name = "boss_yauj"; - pNewScript->GetAI = &GetAI_boss_yauj; - pNewScript->RegisterSelf(); + pNewScript = new Script; + pNewScript->Name = "boss_yauj"; + pNewScript->GetAI = &GetAI_boss_yauj; + pNewScript->RegisterSelf(); - pNewScript = new Script; - pNewScript->Name = "boss_vem"; - pNewScript->GetAI = &GetAI_boss_vem; - pNewScript->RegisterSelf(); + pNewScript = new Script; + pNewScript->Name = "boss_vem"; + pNewScript->GetAI = &GetAI_boss_vem; + pNewScript->RegisterSelf(); } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_cthun.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_cthun.cpp index 8c17ea109..4a85e9f5e 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_cthun.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_cthun.cpp @@ -19,872 +19,1560 @@ /* Nostalrius (inital version Scriptcraft) ** Name: Boss_Cthun -** Complete: 95% -** Comment: Aggro mechanism +** Complete: who knows +** Comment: so many things ** Category: Temple of Ahn'Qiraj +** Rewrtten by Gemt */ #include "scriptPCH.h" #include "temple_of_ahnqiraj.h" +#include -#define EMOTE_WEAKENED -1531011 -#define PI 3.14 -#define RANDOM_SOUND_WHISPER 8663 +enum eCreatures { + EMOTE_WEAKENED = -1531011, + MOB_EYE_TENTACLE = 15726, + MOB_CLAW_TENTACLE = 15725, + MOB_GIANT_CLAW_TENTACLE = 15728, + MOB_GIANT_EYE_TENTACLE = 15334, + MOB_FLESH_TENTACLE = 15802, -#define BOSS_EYE_OF_CTHUN 15589 + MOB_CTHUN_PORTAL = 15896, + MOB_SMALL_PORTAL = 15904, + MOB_GIANT_PORTAL = 15910, -#define MOB_CLAW_TENTACLE 15725 -#define MOB_EYE_TENTACLE 15726 -#define MOB_SMALL_PORTAL 15904 -#define MOB_BODY_OF_CTHUN 15809 -#define MOB_GIANT_CLAW_TENTACLE 15728 -#define MOB_GIANT_EYE_TENTACLE 15334 -#define MOB_FLESH_TENTACLE 15802 -#define MOB_GIANT_PORTAL 15910 + PUNT_CREATURE = 15922, //invisible viscidus trigger, used in stomach +}; -#define SPELL_GREEN_BEAM 26134 -#define SPELL_DARK_GLARE 26029 -#define SPELL_RED_COLORATION 23537 //Probably not the right spell but looks similar -#define SPELL_PURPLE_COLORATION 22581 //Probably not the right spell but looks similar -#define SPELL_MIND_FLAY 26143 -#define SPELL_GROUND_RUPTURE 26139 -#define SPELL_HAMSTRING 26141 -#define SPELL_GIANT_GROUND_RUPTURE 26478 -#define SPELL_GROUND_STUN 6524 -#define SPELL_TRANSFORM 26232 -#define SPELL_MASSIVE_GROUND_RUPTURE 26100 -#define SPELL_THRASH 3391 -#define SPELL_PUNT_UPWARD 16716 -#define SPELL_MOUTH_TENTACLE 26332 -#define SPELL_EXIT_STOMACH_KNOCKBACK 25383 -#define SPELL_DIGESTIVE_ACID 26476 +enum eSpells { + // Phase 1 spells + SPELL_FREEZE_ANIMATION = 16245, // Dummy spell to avoid the eye gazing around during dark glare + SPELL_ROTATE_TRIGGER = 26137, + SPELL_ROTATE_NEGATIVE_360 = 26136, + SPELL_ROTATE_POSITIVE_360 = 26009, + SPELL_DARK_GLARE = 26029, + + // Shared spells + SPELL_GREEN_EYE_BEAM = 26134, -#define STOMACH_X -8562.0f -#define STOMACH_Y 2037.0f -#define STOMACH_Z -70.0f -#define STOMACH_O 5.05f + // Mob spells + SPELL_THRASH = 3391, + SPELL_GROUND_TREMOR = 6524, + SPELL_TENTACLE_BIRTH = 26262, + SPELL_SUBMERGE_VISUAL = 26234, + SPELL_SUBMERGE_EFFECT = 21859, // Must be removed after re-emerge after a submerge to remove immunity -#define TENTACLE_POS1_X -8571.0f -#define TENTACLE_POS1_Y 1990.0f -#define TENTACLE_POS1_Z -98.0f -#define TENTACLE_POS1_O 1.22f -#define TENTACLE_POS2_X -8525.0f -#define TENTACLE_POS2_Y 1994.0f -#define TENTACLE_POS2_Z -98.0f -#define TENTACLE_POS2_O 2.12f + // spellid 26100 has a more correct knockback effect for giant tentacles, but wrong dmg values -#define KICK_X -8546.9f -#define KICK_Y 1989.3f -#define KICK_Z -96.0f + //SPELL_PUNT_UPWARD = 16716, // Used to knock people up from stomach. Remove manually after port as it's the wrong spell and applies slowfall + SPELL_MASSIVE_GROUND_RUPTURE = 26100, // currently unused, ~1k physical huge knockback, not sure who should do it, if any + SPELL_GROUND_RUPTURE_PHYSICAL = 26139, // used by small tentacles + SPELL_HAMSTRING = 26141, //26211 is in DBC with more correct ID? + SPELL_MIND_FLAY = 26143, + SPELL_GROUND_RUPTURE_NATURE = 26478, //used by giant tentacles + + //C'thun spells + + SPELL_CARAPACE_OF_CTHUN = 26156, // Makes C'thun invulnerable + SPELL_DIGESTIVE_ACID_TELEPORT = 26220, // Not yet used, seems to port C'thun instead of player no matter what. + SPELL_TRANSFORM = 26232, // Initiates the p1->p2 transform + SPELL_CTHUN_VULNERABLE = 26235, // Adds the red color. Does not actually him vulnerable, need to remove carapace for that. + SPELL_MOUTH_TENTACLE = 26332, // Spawns the tentacle that "eats" you to stomach and mounts the player on it. +}; -struct cthunAI : public ScriptedAI +static const std::vector allTentacleTypes +({ MOB_EYE_TENTACLE, MOB_CLAW_TENTACLE, MOB_GIANT_CLAW_TENTACLE, MOB_GIANT_EYE_TENTACLE, MOB_FLESH_TENTACLE, + MOB_SMALL_PORTAL, MOB_GIANT_PORTAL}); + +static constexpr uint32 CANNOT_CAST_SPELL_MASK = (UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED | UNIT_FLAG_STUNNED + | UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING); + +static constexpr float stomachPortPosition[4] = { - cthunAI(Creature* pCreature) : ScriptedAI(pCreature) - { - SetCombatMovement(false); + -8562.0f, 2037.0f, -96.0f, 5.05f +}; - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); +static constexpr float fleshTentaclePositions[2][4] = +{ + { -8571.0f, 1990.0f, -98.0f, 1.22f }, + { -8525.0f, 1994.0f, -98.0f, 2.12f } +}; - if (!m_pInstance) - sLog.outError("SD0: No Instance eye_of_cthunAI"); - Reset(); +static constexpr float eyeTentaclePositions[8][3] = +{ + { -8547.269531f, 1986.939941f, 100.490351f }, + { -8556.047852f, 2008.144653f, 100.598129f }, + { -8577.246094f, 2016.939941f, 100.320351f }, + { -8598.457031f, 2008.178467f, 100.320351f }, + { -8607.269531f, 1986.987671f, 100.490351f }, + { -8598.525391f, 1965.769043f, 100.490351f }, + { -8577.340820f, 1956.940063f, 100.536636f }, + { -8556.115234f, 1965.667725f, 100.598129f } +}; + +using SpellTarSelectFunction = std::function; + +class SpellTimer { +public: + SpellTimer(Creature* creature, + uint32 spellID, + uint32 initialCD, + std::function resetCD, + bool triggeredSpell, + SpellTarSelectFunction targetSelectFunc, + bool retryOnFail = false) : + m_creature(creature), + spellID(spellID), + cooldown(initialCD), + resetCD(resetCD), + triggered(triggeredSpell), + targetSelectFunc(targetSelectFunc), + timeSinceLast(std::numeric_limits::max()), + retryOnFail(retryOnFail) + {} + + virtual void Reset(int custom = -1) { + if (custom >= 0) { + cooldown = static_cast(custom); + } + else { + if (!resetCD) + cooldown = 0; + else + cooldown = resetCD(); + } } - ScriptedInstance* m_pInstance; + // Returns true when the cooldown reaches < diff, a cast is attempted, and cooldown is reset + virtual bool Update(uint32 diff) { + if (cooldown < diff) { + Unit* target = targetSelectFunc(m_creature); + bool didCast = false; + if (target) { + if(m_creature->AI()->DoCastSpellIfCan(target, spellID, triggered ? CAST_TRIGGERED : 0) == CAST_OK) { + didCast = true; + } + } + if (retryOnFail && !didCast) { + return false; + } + else { + if (!resetCD) + cooldown = 0; + else + cooldown = resetCD(); + timeSinceLast = 0; + return true; + } + } + else { + cooldown -= diff; + timeSinceLast += diff; + } + return false; + } - uint8 FleshTentaclesKilled; + uint32 TimeSinceLast() { + return timeSinceLast; + } - uint32 WisperTimer; - uint32 EyeTentacleTimer; - uint32 GiantClawTentacleTimer; - uint32 GiantEyeTentacleTimer; - uint32 StomachAcidTimer; - uint32 StomachEnterTimer; - uint32 StomachEnterVisTimer; - uint32 WeaknessTimer; +protected: + Creature* m_creature; + uint32 spellID; + uint32 cooldown; + std::function resetCD; + bool triggered; + bool onlyOnce; + bool retryOnFail; + uint32 timeSinceLast; + SpellTarSelectFunction targetSelectFunc; - uint64 StomachEnterTarget; - uint64 HoldPlayer; +}; - int32 AnimTimer; - int32 EjectorTimer; - int32 EjectorCast; - int32 PhaseTimer; +class OnlyOnceSpellTimer : public SpellTimer { +public: + OnlyOnceSpellTimer(Creature* creature, uint32 spellID, uint32 initialCD, std::function resetCD, + bool triggeredSpell, SpellTarSelectFunction targetSelectFunc, bool retryOnFail=false) : + SpellTimer(creature, spellID, initialCD, resetCD, triggeredSpell, targetSelectFunc, retryOnFail), + didOnce(false) + {} - std::vector m_FleshTentGUIDs; + void Reset(int custom = -1) override { + SpellTimer::Reset(custom); + didOnce = false; + } + + bool Update(uint32 diff) override { + if (!didOnce) { + if (SpellTimer::Update(diff)) { + didOnce = true; + } + } + else { + timeSinceLast += diff; + } + return didOnce; + } + + bool DidCast() { + return didOnce; + } +private: + bool didOnce; + +}; + +static Player* SelectRandomAliveNotStomach(instance_temple_of_ahnqiraj* instance) +{ + if (!instance) return nullptr; + std::list temp; + std::list::iterator j; + const Map::PlayerList& PlayerList = instance->GetMap()->GetPlayers(); + + if (!PlayerList.isEmpty()) + { + for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) + { + if (Player* player = itr->getSource()) + { + if (!player->isDead() && !player->isGameMaster() && player->isInCombat() && !instance->PlayerInStomach(player)) { + temp.push_back(player); + } + } + } + } + + if (temp.empty()) + return NULL; + + j = temp.begin(); + + if (temp.size() > 1) { + advance(j, urand(0, temp.size() - 1)); + } + + return (*j); +} + +// Helper functions for SpellTimer users +static Unit* selectRandNotStomachFunc(Creature* c) { + instance_temple_of_ahnqiraj* inst = dynamic_cast(c->GetInstanceData()); + if (inst) { + return SelectRandomAliveNotStomach(inst); + } + return nullptr; +} +static Unit* selectSelfFunc(Creature* c) { + return c; +} +static Unit* selectTargetFunc(Creature* c) { + return c->getVictim(); +} + +// ================== PHASE 1 CONSTANTS ================== +static constexpr uint32 P1_EYE_TENTACLE_RESPAWN_TIMER = 45000; +static constexpr uint32 SPELL_ROTATE_TRIGGER_CASTTIME = 3000; +static constexpr uint32 GREEN_BEAM_PHASE_DURATION = 45000; +static constexpr uint32 DARK_GLARE_PHASE_DURATION = 38000; +static constexpr uint32 DARK_GLARE_COOLING_DOWN = 1000; +static constexpr int32 MAX_INITIAL_PULLER_HITS = 3; // How many times will c'thun target the initial + // puller with green beam before random target. +static constexpr int32 P1_GREEN_BEAM_COOLDOWN = 3000; // Green beam has a 2 sec cast time. If this number is > 2000, + // the cooldown will be P1_GREEN_BEAM_COOLDOWN - 2000 +static const uint32 P1_CLAW_TENTACLE_RESPAWN_TIMER = 5000; // checked against old footage & current fight +// ======================================================= + +// ================= TRANSITION CONSTANTS ================ +static constexpr uint32 EYE_DEAD_TO_BODY_EMERGE_DELAY = 4000; +static constexpr uint32 CTHUN_EMERGE_ANIM_DURATION = 8000; +// ======================================================= + +// ================== PHASE 2 CONSTANTS ================== +static constexpr uint32 P2_EYE_TENTACLE_RESPAWN_TIMER = 30000; +static constexpr uint32 GIANT_CLAW_RESPAWN_TIMER = 60000; +static constexpr uint32 STOMACH_GRAB_COOLDOWN = 10000; +static constexpr uint32 GIANT_EYE_RESPAWN_TIMER = 60000; +static constexpr uint32 STOMACH_GRAB_DURATION = 3250; +static constexpr uint32 WEAKNESS_DURATION = 45000; +static constexpr uint32 P2_FIRST_GIANT_CLAW_SPAWN = 8000; +static constexpr uint32 P2_FIRST_EYE_TENTACLE_SPAWN = 38000; +static constexpr uint32 P2_FIRST_GIANT_EYE_SPAWN = 38000; +static constexpr uint32 P2_FIRST_STOMACH_GRAB = 18000 - STOMACH_GRAB_DURATION; +// ======================================================= + +// ======================= MISC ========================== +static constexpr uint32 GROUND_RUPTURE_DELAY = 0; // ms after spawn that the ground rupture will be cast +static constexpr uint32 HAMSTRING_INITIAL_COOLDOWN = 2000; // Claw tentacle hamstring cooldown after spawn/tp +static const uint32 hamstringResetCooldownFunc() { return 5000; } // Claw tentacle hamstring cooldown after use +static const uint32 trashResetCooldownFunc() { return urand(6000, 12000); } +static const uint32 groundTremorResetCooldownFunc() { return urand(6000, 12000); } +static constexpr uint32 CLAW_TENTACLE_FIRST_MELEE_DELAY = 1000; // Earliest possible point for a claw tentacle to melee after spawn/tp +static constexpr uint32 CLAW_TENTACLE_EVADE_PORT_COOLDOWN = 5000; // How long does a claw tentacle evade before TPing to new target + +static constexpr uint32 TENTACLE_BIRTH_DURATION = 3000; // Duration of birth animation and /afk before tentacles start doing stuff + +static constexpr uint32 GIANT_EYE_BEAM_COOLDOWN = 2500; // How often will giant eye tentacles cast green beam +static constexpr uint32 GIANT_EYE_INITIAL_GREEN_BEAM_COOLDOWN = 0; // How long will giant eye wait after spawn before casting UPDATE: use TENTACLE_BIRTH_DURATION +static constexpr uint32 MIND_FLAY_COOLDOWN_ON_RESIST = 1500; // How long do we wait if Eye Tentacle MF resists before retrying cast +static constexpr uint32 MIND_FLAY_INITIAL_WAIT_DURATION = 0; // How long do we wait after Eye tentacle has spawned until first MF UPDATE: use TENTACLE_BIRTH_DURATION +static constexpr uint32 TELEPORT_BURIED_DURATION = 1000; // How long will a claw tentacle say underground before re-emerging on teleport. +// ======================================================= + +// ================== THE PULL =========================== +/* if defined, the encounter does not pull all players in combat on aggro, but +* rather aggros the initial puller and then places everyone else in combat +* 12 seconds later. Sources: https://pastebin.com/BiC33bU5 +* +* If not defined, the current logic is to target the intial puller 3 times with the +* beam before going on a random target. More research should be done to better understand +* how the pull worked *after* the later nerfs, and also when it was implemented. +* +* The one thing that is certain is that in all kills with videos around the time it first became +* "killable" (april 24th 2006), the 12seconds delayed combat was how it worked. +* In later kills, towards the end of 2006, people were put in combat as soon as the first beam *hit* +* the initial puller, but how many times it would hit the initial puller is currently unknown. +* +* A suggested way to make the pull slightly more challenging is tuning DELAYED_COMBAT_DURATION to +* somewhere between 6 and 9 seconds. +*/ +#define USE_POSTFIX_PRENERF_PULL_LOGIC +#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC +static constexpr uint32 DELAYED_COMBAT_DURATION = 9000; +#endif +// ======================================================= + +static constexpr TempSummonType TENTACLE_DESPAWN_FLAG = TEMPSUMMON_CORPSE_TIMED_DESPAWN; + +struct cthunTentacle : public ScriptedAI +{ + instance_temple_of_ahnqiraj* m_pInstance; + float defaultOrientation; + + cthunTentacle(Creature* pCreature) : + ScriptedAI(pCreature) + { + m_pInstance = dynamic_cast(pCreature->GetInstanceData()); + if (!m_pInstance) + sLog.outError("C'thun tentacle could not find it's instance"); + + SetCombatMovement(false); + defaultOrientation = m_creature->GetOrientation(); + } + + virtual void Reset() override + { + m_creature->addUnitState(UNIT_STAT_ROOT); + m_creature->StopMoving(); + m_creature->SetMovement(MOVE_ROOT); + m_creature->SetInCombatWithZone(); + } + + void Aggro(Unit* pWho) override + { + ScriptedAI::Aggro(pWho); + m_creature->SetInCombatWithZone(); + } + + bool UpdateCthunTentacle(uint32 diff) + { + if (!m_pInstance) return false; + + if (!m_pInstance->GetPlayerInMap(true, false)) { + if (TemporarySummon* tmpS = dynamic_cast(m_creature)) { + tmpS->UnSummon(); + } + else { + sLog.outError("CThunTentacle could not cast creature to TemporarySummon*"); + } + //EnterEvadeMode(); + //m_creature->OnLeaveCombat(); + //Reset(); + return false; + } + + // This makes the mob behave like frostnovaed mobs etc, that is, + // retargetting another top-threat target if current leaves melee range + m_creature->addUnitState(UNIT_STAT_ROOT); + m_creature->StopMoving(); + m_creature->SetMovement(MOVE_ROOT); + return true; + } + + bool UpdateMelee(bool resetOrientation) + { + if (!SelectHostileTargetMelee()) { + DoStopAttack(); + if(resetOrientation) + m_creature->SetOrientation(defaultOrientation); + return false; + } + else { + DoMeleeAttackIfReady(); + return true; + } + } + + // Custom targetting function. + // Will only target hostile players/pets that are in melee range. + // If current target leaves melee range, his threat is reset. + // IF there are no targets in melee range, the creature will + // not target anyone. + // Returns true when the creature has a target. + bool SelectHostileTargetMelee() + { + if (!m_creature->isAlive()) + return false; + + // If we're casting something its sort-of counter intuitive to return true, + // but it also means we do have a valid target already, even if it's not melee. + // DoMeleeAttack, which is typically called on true return, will check + // m_creature->IsNonMeleeSpellCasted(false) internally anyway. + if (m_creature->IsNonMeleeSpellCasted(false)) { + return true; + } + + Unit* oldTarget = m_creature->getVictim(); + Unit* target = nullptr; + + // First checking if we have some taunt on us + const Unit::AuraList& tauntAuras = m_creature->GetAurasByType(SPELL_AURA_MOD_TAUNT); + for (auto it = tauntAuras.crbegin(); it != tauntAuras.crend(); it++) { + Unit* caster = (*it)->GetCaster(); + if (!caster) continue; + + if (caster->IsInMap(m_creature) && caster->isTargetableForAttack() && m_creature->CanReachWithMeleeAttack(caster)) + { + target = caster; + break; + } + else { + // Target is not in melee and reset his threat + m_creature->getThreatManager().modifyThreatPercent(caster, -100); + } + } + // So far so good. If we have a target after this loop it means we have a valid target in melee range. + + // If we dont have a target we need to keep searching through the threatlist + if (!target) + { + Unit* tmpTarget = nullptr; + if (m_creature->CanHaveThreatList()) { + ThreatList const& threatlist = m_creature->getThreatManager().getThreatList(); + ThreatList::const_iterator itr = threatlist.begin(); + ThreatList::const_reverse_iterator ritr = threatlist.rbegin(); + + // Implementing this loop manually instead of using Creature::SelectAttackingTarget + // to use target->CanReachWithMeleeAttack(creature) instead of creature->isWithinMeleeRange(target), + // because melee ranges are fucked up. todo: fix melee ranges.... + for (; itr != threatlist.end(); ++itr) { + if (Unit* pTarget = m_creature->GetMap()->GetUnit((*itr)->getUnitGuid())) { + if (pTarget->isTargetableForAttack() + && pTarget->CanReachWithMeleeAttack(m_creature) + && pTarget->IsWithinLOSInMap(m_creature)) { + tmpTarget = pTarget; + break; + } + } + } + } + + // Resetting threat of old target if it has left melee range + if (oldTarget && tmpTarget != oldTarget && !oldTarget->CanReachWithMeleeAttack(m_creature)) { + //if (oldTarget && tmpTarget != oldTarget && !m_creature->IsWithinMeleeRange(oldTarget)) { + m_creature->getThreatManager().modifyThreatPercent(oldTarget, -100); + } + + if (tmpTarget) { + // Need to call getHostileTarget to force an update of the threatlist, bleh + target = m_creature->getThreatManager().getHostileTarget(); + } + } + + + if (target) + { + // Nostalrius : Correction bug sheep/fear + if (!m_creature->hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED | UNIT_STAT_DIED | UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING) + && (!m_creature->HasAuraType(SPELL_AURA_MOD_FEAR) || m_creature->HasAuraType(SPELL_AURA_PREVENTS_FLEEING)) && !m_creature->HasAuraType(SPELL_AURA_MOD_CONFUSE)) + { + m_creature->SetInFront(target); + AttackStart(target); + } + return true; + } + return false; + } +}; + +struct cthunPortalTentacle : public cthunTentacle +{ +private: + uint32 birthTimer; +public: + ObjectGuid portalGuid; + OnlyOnceSpellTimer groundRuptureTimer; + + cthunPortalTentacle(Creature* pCreature, uint32 groundRuptSpellId, uint32 portalId) : + cthunTentacle(pCreature), + groundRuptureTimer(pCreature, groundRuptSpellId, GROUND_RUPTURE_DELAY, 0, true, selectSelfFunc) + { + Creature* pPortal = DoSpawnCreature(portalId, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 500); //TEMPSUMMON_DEAD_DESPAWN, 120000 + if (pPortal) { + pPortal->SetInCombatWithZone(); + portalGuid = pPortal->GetGUID(); + FixPortalPosition(); + } + else { + sLog.outError("cthunPortalTentacle failed to spawn portal with entry %d", portalId); + } + } + + void DespawnPortal() { + if (Creature* pCreature = m_creature->GetMap()->GetCreature(portalGuid)) { + if (TemporarySummon* ts = dynamic_cast(pCreature)) { + ts->UnSummon(); + portalGuid = 0; + } + else { + sLog.outError("Unable to despawn cthunPortalTentacle portal, could not cast to temporarySummon*"); + } + } + } + + virtual void Reset() override + { + cthunTentacle::Reset(); + groundRuptureTimer.Reset(); + birthTimer = TENTACLE_BIRTH_DURATION; + m_creature->AttackStop(true); + //DoStopAttack(true); + } + + void JustDied(Unit*) override + { + DespawnPortal(); + } + + bool UpdatePortalTentacle(uint32 diff) + { + if (!cthunTentacle::UpdateCthunTentacle(diff)) { + DespawnPortal(); + //m_creature->ForcedDespawn(500); + return false; + } + + if (groundRuptureTimer.Update(diff)) { + if (birthTimer > diff) { + // Only want to cast it once, and it cant be done in ctor because groundRupture interrupts the animation. + if (birthTimer == TENTACLE_BIRTH_DURATION) { + DoCastSpellIfCan(m_creature, SPELL_TENTACLE_BIRTH, CAST_FORCE_TARGET_SELF); + } + birthTimer -= diff; + } + } + if (birthTimer <= diff) { + return true; + } + return false; + } + + void FixPortalPosition() { + Unit* pPortal = nullptr; + if (portalGuid && m_pInstance) + pPortal = m_pInstance->GetCreature(portalGuid); + if (!pPortal) + return; + uint32 portalEntry = pPortal->GetEntry(); + float radius; + switch (portalEntry) { + case MOB_SMALL_PORTAL: radius = 3.0f; break; + case MOB_GIANT_PORTAL: radius = 8.0f; break; + default: + radius = 3.0f; + sLog.outError("C'thun FixPortalPosition unknown portalID %d", portalEntry); + } + //Searching for best z-coordinate to place the portal + float centerX = m_creature->GetPositionX(); + float centerY = m_creature->GetPositionY(); + float useZ = m_creature->GetPositionZ(); + float angle = 360.0f / 8.0f; + float highZ = useZ; + float avg_height = 0.0f; + uint8 inliers = 0; + for (uint8 i = 0; i < 8; i++) + { + float x = centerX + cos(((float)i * angle) * (3.14f / 180.0f)) * radius; + float y = centerY + sin(((float)i * angle) * (3.14f / 180.0f)) * radius; + float z = m_creature->GetMap()->GetHeight(x, y, useZ); + float deviation = abs(useZ - z); + // Any deviation >= 0.5 we consider outliers as we dont want to handle sloped terrain + if (deviation < 0.5f) { + if (z > highZ) + highZ = z; + avg_height += z; + inliers++; + } + } + avg_height /= inliers; + // Only move portal up if the average height is higher than the creatures height + if (avg_height > useZ) { + useZ = highZ; + } + pPortal->NearLandTo(m_creature->GetPositionX(), m_creature->GetPositionY(), useZ, 0); + } + +}; + +struct clawTentacle : public cthunPortalTentacle +{ + uint32 EvadeTimer; + SpellTimer hamstringTimer; + uint32 teleportBuriedTimer; + uint32 feignDeathTimer; + + enum eClawState { + NORMAL, + FEIGN_IN_PROCES, + BURRIED, + }; + eClawState clawState; + + clawTentacle(Creature* pCreature, uint32 groundRuptSpellId, uint32 portalId) : + cthunPortalTentacle(pCreature, groundRuptSpellId, portalId), + EvadeTimer(0), + hamstringTimer(pCreature, SPELL_HAMSTRING, HAMSTRING_INITIAL_COOLDOWN, hamstringResetCooldownFunc, false, selectTargetFunc, true) + { + } + + virtual void Reset() override + { + cthunPortalTentacle::Reset(); + hamstringTimer.Reset(HAMSTRING_INITIAL_COOLDOWN); + EvadeTimer = CLAW_TENTACLE_EVADE_PORT_COOLDOWN; + teleportBuriedTimer = 0; + + // If reset is called after a teleport, it regains full HP. + // Todo: Should we also clear any debuffs? + m_creature->SetFullHealth(); + + clawState = eClawState::NORMAL; + feignDeathTimer = 0; + } + + bool UpdateClawTentacle(uint32 diff) + { + if (!cthunPortalTentacle::UpdatePortalTentacle(diff)) + return false; + + switch (clawState) { + case NORMAL: + updateNormal(diff); + return true; + break; + case FEIGN_IN_PROCES: + updateFeign(diff); + return false; + break; + case BURRIED: + updateBurried(diff); + return false; + break; + default: + sLog.outError("Unknown UpdateClawTentacle state."); + return false; + } + } + +private: + void updateNormal(uint32 diff) { + + if (UpdateMelee(false)) { + EvadeTimer = CLAW_TENTACLE_EVADE_PORT_COOLDOWN; + hamstringTimer.Update(diff); + } + else { + if (EvadeTimer < diff) { + clawState = eClawState::FEIGN_IN_PROCES; + feignDeathTimer = 1000; + m_creature->CastSpell(m_creature, SPELL_SUBMERGE_VISUAL, false); + } + else { + EvadeTimer -= diff; + } + } + /* + if (Unit* uP = CheckForMelee()) { + EvadeTimer = CLAW_TENTACLE_EVADE_PORT_COOLDOWN; + } + else { + // Initiate submerge->teleport->birth sequence if it's time + if (EvadeTimer < diff) { + DoStopAttack(); // Added after testing + clawState = eClawState::FEIGN_IN_PROCES; + feignDeathTimer = 1000; + m_creature->CastSpell(m_creature, SPELL_SUBMERGE_VISUAL, false); + } + else { + EvadeTimer -= diff; + } + } + */ + } + + void updateFeign(uint32 diff) { + if (feignDeathTimer < diff) { + clawState = eClawState::BURRIED; + teleportBuriedTimer = TELEPORT_BURIED_DURATION; + setVisibility(false); + } + else { + feignDeathTimer -= diff; + } + } + + void updateBurried(uint32 diff) { + if (teleportBuriedTimer < diff) { + // Done being burried, time to teleport on a new target. + // If we're successfull in selecting a new target, reset will reset + // all necessary cooldowns, including setting the correct clawState (NORMAL) + if (TeleportOnNewRandomTarget()) { + DoResetThreat(); + m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_VISUAL); + setVisibility(true); + m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_EFFECT); + Reset(); + } + } + else { + teleportBuriedTimer -= diff; + } + } + + bool TeleportOnNewRandomTarget() + { + if (Player* target = SelectRandomAliveNotStomach(m_pInstance)) + { + float x; + float y; + float z; + m_creature->GetRandomPoint(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.5f, x, y, z); + m_creature->NearTeleportTo(x, y, z, 0); + + if (Creature* pCreature = m_creature->GetMap()->GetCreature(portalGuid)) { + FixPortalPosition(); + } + return true; + } + return false; + } + + void setVisibility(bool visiblityOn) { + Creature* pCreature = m_creature->GetMap()->GetCreature(portalGuid); + if (visiblityOn) { + m_creature->SetVisibility(VISIBILITY_ON); + if (pCreature) + pCreature->SetVisibility(VISIBILITY_ON); + } + else { + m_creature->SetVisibility(VISIBILITY_OFF); + if (pCreature) + pCreature->SetVisibility(VISIBILITY_OFF); + } + } +}; + +struct eye_tentacleAI : public cthunPortalTentacle +{ + uint32 nextMFAttempt; + ObjectGuid currentMFTarget; + + eye_tentacleAI(Creature* pCreature) : + cthunPortalTentacle(pCreature, SPELL_GROUND_RUPTURE_PHYSICAL, MOB_SMALL_PORTAL) + { + eye_tentacleAI::Reset(); + } void Reset() { - WisperTimer = 90000; // One random wisper every 90 - 300 seconds + cthunPortalTentacle::Reset(); + nextMFAttempt = MIND_FLAY_INITIAL_WAIT_DURATION; + currentMFTarget = 0; + } - AnimTimer = 0; - PhaseTimer = 0; - HoldPlayer = 0; - EjectorTimer = 5000; - EjectorCast = 3000; - EyeTentacleTimer = 20000; - FleshTentaclesKilled = 0; - GiantClawTentacleTimer = 0; - GiantEyeTentacleTimer = 30000; - StomachAcidTimer = 4000; - StomachEnterTimer = 5000; - StomachEnterVisTimer = 0; - StomachEnterTarget = 0; - - // Reset visibility - m_creature->SetVisibility(VISIBILITY_OFF); - m_creature->SetVisibility(VISIBILITY_ON); - - if (m_pInstance) - { - m_pInstance->SetData(TYPE_CTHUN_PHASE, 0); - Creature* b_Eye = m_pInstance->GetSingleCreatureFromStorage(NPC_EYE_OF_C_THUN); - if (b_Eye) - b_Eye->Respawn(); + void AttackStart(Unit* who) override + { + // Prevents AttacStart from stopping the cast animation + if (!m_creature->IsNonMeleeSpellCasted(false)) { + ScriptedAI::AttackStart(who); } } void UpdateAI(const uint32 diff) { - if (!m_pInstance) + if (!cthunPortalTentacle::UpdatePortalTentacle(diff)) return; - if (m_pInstance->GetData(TYPE_CTHUN_PHASE) < 2) - return; - - if (TransitionLogic(diff)) - return; - - StomachEjector(diff); - - // Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - { - WhisperIfShould(diff); - return; + if (nextMFAttempt > diff) { + nextMFAttempt -= diff; + } + else { + nextMFAttempt = 0; } - if (m_creature->GetTargetGuid() != m_creature->GetObjectGuid()) - m_creature->SetTargetGuid(m_creature->GetObjectGuid()); - - // Body phase or weakend - if (!m_creature->HasAura(SPELL_PURPLE_COLORATION)) - DoSpells(diff); - else + // If we are not already casting, try to start casting + if (!m_creature->GetCurrentSpell(CurrentSpellTypes::CURRENT_CHANNELED_SPELL)) { - if (WeaknessTimer < diff) // If weakend runs out - { - EndWeaknessPhase(); - WeaknessTimer = 0; - } - else - WeaknessTimer -= diff; - } - } - - void JustSummoned(Creature *pCreature) - { - if (pCreature->GetEntry() == MOB_FLESH_TENTACLE) - m_FleshTentGUIDs.push_back(pCreature->GetObjectGuid()); - - int numFleshTents = 0; - for (int i = 0; i < m_FleshTentGUIDs.size(); i++) - { - if (Creature *m_Tent = m_creature->GetMap()->GetCreature(m_FleshTentGUIDs[i])) - { - if (m_Tent->isAlive()) - { - if (numFleshTents >= 2) - m_Tent->ForcedDespawn(); - else - numFleshTents++; - } - } - } - } - - void EndWeaknessPhase() - { - // Reset these cooldowns - GiantClawTentacleTimer = 10000; //10 seconds into body phase (1 min repeat) - GiantEyeTentacleTimer = 40000; //40 seconds into body phase (1 min repeat) - StomachEnterTimer = 10000; //Every 10 seconds - - // Clear eaten guys - StomachEnterTarget = 0; - StomachEnterVisTimer = 0; - - //Remove red coloration - m_creature->SetVisibility(VISIBILITY_OFF); - m_creature->RemoveAurasDueToSpell(SPELL_PURPLE_COLORATION); - m_creature->SetVisibility(VISIBILITY_ON); - - //Spawn 2 flesh tentacles - FleshTentaclesKilled = 0; - - //Spawn flesh tentacle - Creature* pSpawned = m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS1_X, TENTACLE_POS1_Y, TENTACLE_POS1_Z, TENTACLE_POS1_O, TEMPSUMMON_CORPSE_DESPAWN, 0); - - if (!pSpawned) - ++FleshTentaclesKilled; - - //Spawn flesh tentacle - pSpawned = m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS2_X, TENTACLE_POS2_Y, TENTACLE_POS2_Z, TENTACLE_POS2_O, TEMPSUMMON_CORPSE_DESPAWN, 0); - - if (!pSpawned) - ++FleshTentaclesKilled; - } - - void BeginEmergePhase() - { - AnimTimer = 5000; - } - - void DoSpells(uint32 diff) - { - TentacleTimers(diff); - - // Weaken - if (FleshTentaclesKilled > 1) - { - WeaknessTimer = 45000; - DoScriptText(EMOTE_WEAKENED, m_creature); - m_creature->CastSpell(m_creature, SPELL_PURPLE_COLORATION, true); - } - - //Stomach Enter Timer - if (StomachEnterTimer < diff) - { - if (Unit* target = SelectRandomNotStomach()) - { - // Set target in stomach - target->InterruptNonMeleeSpells(false); - target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, NULL, NULL, m_creature->GetObjectGuid()); - StomachEnterTarget = target->GetObjectGuid(); - StomachEnterVisTimer = 3500; - } - - StomachEnterTimer = 10000 + StomachEnterVisTimer; - } - else - StomachEnterTimer -= diff; - - if (StomachEnterVisTimer && StomachEnterTarget) - { - if (StomachEnterVisTimer <= diff) - { - if (Unit* pUnit = m_creature->GetMap()->GetUnit(StomachEnterTarget)) - { - DoTeleportPlayer(pUnit, STOMACH_X, STOMACH_Y, STOMACH_Z, STOMACH_O); - pUnit->RemoveAurasDueToSpell(SPELL_MOUTH_TENTACLE); - } - - StomachEnterTarget = 0; - StomachEnterVisTimer = 0; - } - else - StomachEnterVisTimer -= diff; - } - } - - void TentacleTimers(uint32 diff) - { - // Stomach acid - if (StomachAcidTimer < diff) - { - DebuffStomachPlayers(); - StomachAcidTimer = 4000; - } - else - StomachAcidTimer -= diff; - - // GientClawTentacleTimer - if (GiantClawTentacleTimer < diff) - { - if (Unit* target = SelectRandomNotStomach()) - { - if (Creature* Spawned = m_creature->SummonCreature(MOB_GIANT_CLAW_TENTACLE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 500)) - Spawned->AI()->AttackStart(target); - - // One giant claw tentacle every minute - GiantClawTentacleTimer = 60000; - } - } - else - GiantClawTentacleTimer -= diff; - - // GiantEyeTentacleTimer - if (GiantEyeTentacleTimer < diff) - { - if (Unit* target = SelectRandomNotStomach()) - { - if (Creature *Spawned = m_creature->SummonCreature(MOB_GIANT_EYE_TENTACLE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 500)) - Spawned->AI()->AttackStart(target); - - // One giant eye tentacle every minute - GiantEyeTentacleTimer = 60000; - } - } - else - GiantEyeTentacleTimer -= diff; - - // EyeTentacleTimer - if (EyeTentacleTimer < diff) - { - // Spawn the 8 Eye Tentacles in the corret spots - float centerX = m_creature->GetPositionX(); - float centerY = m_creature->GetPositionY(); - float radius = 30.0f; - float angle = 360.0f / 8.0f; - - // Summon 8 of them them in a circle centered around centerX and centerY - for (uint8 i = 0; i < 8; i++) - { - float x = centerX + cos(((float)i * angle) * (3.14f / 180.0f)) * radius; - float y = centerY + sin(((float)i * angle) * (3.14f / 180.0f)) * radius; - - SpawnEyeTentacle(x, y); - } - - //These spawn at every 30 seconds - EyeTentacleTimer = 30000; - } - else - EyeTentacleTimer -= diff; - } - - void StomachEjector(uint32 diff) - { - int SignedDiff = static_cast (diff); - if (EjectorTimer < SignedDiff) - { - BeginEjectorAnimation(); - EjectorTimer = 999999; // Don't start this until the punt happens - } - else - EjectorTimer -= SignedDiff; - - if (EjectorCast > SignedDiff) - { - EjectorCast -= SignedDiff; - if (EjectorCast <= SignedDiff) - { - TriggerStomachEjector(); - EjectorTimer = 3000; // Started - } - } - - EjectStomachIfShould(); - } - - void BeginEjectorAnimation() - { - EjectorCast = 5000; - // Start cast visual - if (Creature *pCreature = m_creature->SummonCreature(7444, KICK_X, KICK_Y, - KICK_Z, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 4450)) - { - pCreature->SetFactionTemporary(35); - pCreature->SetDisplayId(11686); - pCreature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - pCreature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - pCreature->CastSpell(pCreature, 26092, false); - } - } - - void TriggerStomachEjector() - { - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - if (!PlayerList.isEmpty()) - { - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - if (Player* player = itr->getSource()) - { - if (UnitInStomach(player)) + currentMFTarget = 0; + bool didCast = false; + // Rough check against common auras that prevent the creature from casting, + // before getting a random target etc + if (!m_creature->HasFlag(UNIT_FIELD_FLAGS, CANNOT_CAST_SPELL_MASK)) { + // nextMFAttempt acts as a fake gcd in case of resist + if (nextMFAttempt == 0) { + if (Player* target = SelectRandomAliveNotStomach(m_pInstance)) { - if (player->GetDistance(KICK_X, KICK_Y, KICK_Z) < 5.0f) - { - player->CastSpell(player, SPELL_PUNT_UPWARD, true); - player->RemoveAurasDueToSpell(SPELL_PUNT_UPWARD); + if (DoCastSpellIfCan(target, SPELL_MIND_FLAY) == CAST_OK) { + currentMFTarget = target->GetGUID(); + m_creature->SetFacingToObject(target); + m_creature->SetTargetGuid(currentMFTarget); + didCast = true; + nextMFAttempt = MIND_FLAY_COOLDOWN_ON_RESIST; } } + + } + } + if (!didCast) { + UpdateMelee(false); + } + + } + else { + // Stop casting on current target if it's been ported to stomach + if (Unit* currentCastTarget = m_creature->GetMap()->GetPlayer(currentMFTarget)) { + if (m_pInstance->PlayerInStomach(currentCastTarget)) { + m_creature->InterruptSpell(CurrentSpellTypes::CURRENT_CHANNELED_SPELL); } } } } +}; - void EjectStomachIfShould() +struct claw_tentacleAI : public clawTentacle +{ + claw_tentacleAI(Creature* pCreature) : + clawTentacle(pCreature, SPELL_GROUND_RUPTURE_PHYSICAL, MOB_SMALL_PORTAL) { - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - if (!PlayerList.isEmpty()) + claw_tentacleAI::Reset(); + } + + void Reset() override + { + clawTentacle::Reset(); + } + + void UpdateAI(const uint32 diff) + { + clawTentacle::UpdateClawTentacle(diff); + } +}; + +struct giant_claw_tentacleAI : public clawTentacle +{ + SpellTimer groundTremorTimer; + SpellTimer trashTimer; + + giant_claw_tentacleAI(Creature* pCreature) : + clawTentacle(pCreature, SPELL_GROUND_RUPTURE_NATURE, MOB_GIANT_PORTAL), + groundTremorTimer(pCreature, SPELL_GROUND_TREMOR, groundTremorResetCooldownFunc(), groundTremorResetCooldownFunc, true, selectTargetFunc, true), + trashTimer(pCreature, eSpells::SPELL_THRASH, trashResetCooldownFunc(), trashResetCooldownFunc, false, selectTargetFunc, true) + { + giant_claw_tentacleAI::Reset(); + } + + void Reset() override + { + clawTentacle::Reset(); + groundTremorTimer.Reset(); + trashTimer.Reset(); + } + + void UpdateAI(const uint32 diff) + { + if (!clawTentacle::UpdateClawTentacle(diff)) + return; + + groundTremorTimer.Update(diff); + trashTimer.Update(diff); + } +}; + +struct giant_eye_tentacleAI : public cthunPortalTentacle +{ + uint32 BeamTimer; + ObjectGuid beamTargetGuid; + bool isCasting; + giant_eye_tentacleAI(Creature* pCreature) : + cthunPortalTentacle(pCreature, SPELL_GROUND_RUPTURE_NATURE, MOB_GIANT_PORTAL) + { + giant_eye_tentacleAI::Reset(); + } + void Reset() + { + cthunPortalTentacle::Reset(); + BeamTimer = GIANT_EYE_INITIAL_GREEN_BEAM_COOLDOWN; + isCasting = false; + } + + void UpdateAI(const uint32 diff) + { + if (!isCasting) { - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - if (Player* player = itr->getSource()) - { - if (player->GetPositionZ() < -35.0f) - { - // If we're at the top of the stomach and have falling state - if (player->GetPositionZ() > -40.0f && player->HasMovementFlag(MOVEFLAG_JUMPING)) - { - //Teleport player out - DoTeleportPlayer(player, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ() + 5, player->GetOrientation()); + if (!cthunPortalTentacle::UpdatePortalTentacle(diff)) + return; + } - //Cast knockback on them - player->CastSpell(player, SPELL_EXIT_STOMACH_KNOCKBACK, true); + if (!m_creature->GetCurrentSpell(CurrentSpellTypes::CURRENT_GENERIC_SPELL)) { + beamTargetGuid = 0; + isCasting = false; + } - //Remove the acid debuff - player->RemoveAurasDueToSpell(SPELL_DIGESTIVE_ACID); - } + if (BeamTimer < diff) { + // Rough check against common auras that prevent the creature from casting, + // before getting a random target etc + if (!m_creature->HasFlag(UNIT_FIELD_FLAGS, CANNOT_CAST_SPELL_MASK)) { + if (Player* target = SelectRandomAliveNotStomach(m_pInstance)) { + // need to check if we can cast before doing so, because if we update target + // after initiating the cast, the cast animation dissapear for some reason + if (CanCastSpell(target, sSpellMgr.GetSpellEntry(SPELL_GREEN_EYE_BEAM), false) == CanCastResult::CAST_OK) { + beamTargetGuid = target->GetObjectGuid(); + m_creature->SetTargetGuid(target->GetObjectGuid()); + m_creature->SetFacingToObject(target); + m_creature->CastSpell(target, SPELL_GREEN_EYE_BEAM, false); + isCasting = true; + BeamTimer = GIANT_EYE_BEAM_COOLDOWN; } } } } - } - - void DebuffStomachPlayers() - { - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - if (!PlayerList.isEmpty()) - { - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - if (Player* player = itr->getSource()) - { - if (UnitInStomach(player)) - player->CastSpell(player, SPELL_DIGESTIVE_ACID, true); - } - } - } - } - - void SpawnEyeTentacle(float x, float y) - { - if (Creature* Spawned = m_creature->SummonCreature(MOB_EYE_TENTACLE, x, y, m_creature->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 500)) - { - Spawned->SetInCombatWithZone(); - Spawned->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.75f); - } - } - - bool UnitInStomach(Unit *unit) - { - if (unit->GetPositionZ() < -30.0f) - return true; - - return false; - } - - Unit* SelectRandomNotStomach() - { - std::list temp; - std::list::iterator j; - - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - if (!PlayerList.isEmpty()) - { - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - if (Player* player = itr->getSource()) - { - if (!UnitInStomach(player) && !player->isGameMaster() && !player->HasMovementFlag(MOVEFLAG_JUMPING)) - temp.push_back(player); - } - } - } - - if (temp.empty()) - return NULL; - - j = temp.begin(); - - //Get random but only if we have more than one unit on threat list - if (temp.size() > 1) - advance(j , rand() % (temp.size() - 1)); - - return (*j); - } - - - void WhisperIfShould(uint32 diff) - { - //No target so we'll use this section to do our random wispers instance wide - if (!m_creature->isInCombat()) - { - //WisperTimer - if (WisperTimer < diff) - { - Map *map = m_creature->GetMap(); - if (!map->IsDungeon()) - return; - - //Play random sound to the zone - Map::PlayerList const &PlayerList = map->GetPlayers(); - - if (!PlayerList.isEmpty()) - { - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - if (Player* pPlr = itr->getSource()) - pPlr->PlayDirectSound(RANDOM_SOUND_WHISPER, pPlr); + else { + BeamTimer -= diff; + if (m_creature->GetCurrentSpell(CurrentSpellTypes::CURRENT_GENERIC_SPELL)) { + // Stop casting on current target if it's been ported to stomach + // and immediately start casting on a new target + if (Unit* currentCastTarget = m_creature->GetMap()->GetPlayer(beamTargetGuid)) { + if (m_pInstance->PlayerInStomach(currentCastTarget)) { + m_creature->InterruptNonMeleeSpells(false); + BeamTimer = 0; } } - - //One random wisper every 90 - 300 seconds - WisperTimer = urand(90000, 300000); } - else WisperTimer -= diff; } - } - - bool TransitionLogic(uint32 diff) - { - int32 SignedDiff = diff; - if (AnimTimer > SignedDiff) + if (!isCasting) { - AnimTimer -= SignedDiff; - - if (AnimTimer <= SignedDiff) - PhaseTimer = 10000; - - if (AnimTimer < 1000) - { - m_creature->RemoveAurasDueToSpell(SPELL_TRANSFORM); - m_creature->CastSpell(m_creature, SPELL_TRANSFORM, true); - } - - return true; + UpdateMelee(false); } + } +}; - if (PhaseTimer > SignedDiff) - { - PhaseTimer -= SignedDiff; - if (PhaseTimer <= SignedDiff) - Emerge(); +struct flesh_tentacleAI : public cthunTentacle +{ + ScriptedInstance* m_pInstance; - return true; - } - - return false; + flesh_tentacleAI(Creature* pCreature) : cthunTentacle(pCreature) + { + flesh_tentacleAI::Reset(); + } + + void Reset() override + { + cthunTentacle::Reset(); } - void Emerge() + void UpdateAI(const uint32 diff) override { - m_creature->SetInCombatWithZone(); - m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); - - //Emerging phase - m_creature->SetInCombatWithZone(); - - FleshTentaclesKilled = 0; - - //Spawn flesh tentacle - Creature* pSpawned = m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS1_X, TENTACLE_POS1_Y, TENTACLE_POS1_Z, TENTACLE_POS1_O, TEMPSUMMON_CORPSE_DESPAWN, 0); - - if (!pSpawned) - ++FleshTentaclesKilled; - - // Spawn flesh tentacle - pSpawned = m_creature->SummonCreature(MOB_FLESH_TENTACLE, TENTACLE_POS2_X, TENTACLE_POS2_Y, TENTACLE_POS2_Z, TENTACLE_POS2_O, TEMPSUMMON_CORPSE_DESPAWN, 0); - - if (!pSpawned) - ++FleshTentaclesKilled; - } - - void JustDied(Unit* pKiller) - { - //Switch - if (m_pInstance) - m_pInstance->SetData(TYPE_CTHUN_PHASE, DONE); - } - - void DamageTaken(Unit *done_by, uint32 &damage) - { - if (!m_creature->HasAura(SPELL_PURPLE_COLORATION)) - { - //Not weakened so reduce damage by 99% - if (damage / 99 > 0) damage /= 99; - else damage = 1; - - //Prevent death in non-weakened state - if (damage >= m_creature->GetHealth()) - damage = 0; - } - else - DoCastSpellIfCan(m_creature, 27880, CAST_AURA_NOT_PRESENT); - } - - void FleshTentcleKilled() - { - ++FleshTentaclesKilled; + UpdateMelee(true); } }; struct eye_of_cthunAI : public ScriptedAI { - eye_of_cthunAI(Creature* pCreature) : ScriptedAI(pCreature) + // The eye phases can be a bit difficult to decode due to cast time and "cooling down" duration + // of red beam. + // There should be 45 seconds of "green beam phase" + // cast time of dark glare is 3 seconds + // once dark glare is up, boss rotates and keeps dark glare up for 38 seconds + // after 38 seconds he stops rotating and removes dark glare from himself, this is a 1 second period where nothing happens + // he then starts a new 45 seconds of green beam + // Dark glare should start casting every 86 seconds + // 45 sec green beam + // 3 sec cast dark glare + // 38 sec dark glare + // 1 sec "cooling down" + // = 86 seconds + instance_temple_of_ahnqiraj* m_pInstance; + + bool IsAlreadyPulled; + + uint32 eyeBeamCooldown; + uint32 eyeBeamCastCount; + //uint32 eyeBeamPhaseDuration; + //uint32 darkGlarePhaseDuration; + + ObjectGuid initialPullerGuid; + enum CthunEyePhase { + GREEN_BEAM, + DARK_GLARE_CAST, + DARK_GLARE, + DARK_GLARE_COOLING + }; + CthunEyePhase currentPhase; + + uint32 greenBeamPhaseTimer; + uint32 darkGlareCastTimer; + uint32 darkGlareTimer; + uint32 darkGlareCoolingTimer; + + eye_of_cthunAI(Creature* pCreature) : + ScriptedAI(pCreature) { SetCombatMovement(false); - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + m_pInstance = dynamic_cast(pCreature->GetInstanceData()); if (!m_pInstance) sLog.outError("SD0: No Instance eye_of_cthunAI"); Reset(); } - ScriptedInstance* m_pInstance; + void Pull(Unit* puller) { - //Global variables - uint32 PhaseTimer; + m_creature->SetFactionTemporary(14); - //Eye beam phase - uint32 BeamTimer; - uint32 EyeTentacleTimer; - uint32 ClawTentacleTimer; + initialPullerGuid = puller->GetObjectGuid(); + CastGreenBeam(puller); + + IsAlreadyPulled = true; + } - //Dark Glare phase - uint32 DarkGlareTick; - uint32 DarkGlareTickTimer; - float DarkGlareAngle; - bool ClockWise; + void Aggro(Unit* puller) + { + // Just in case someone manages to get through the AggroRadius logic in C'thuns AI + // we make sure the proper pull-sequence is initiated by calling C'thuns attackstart. + if (!m_creature->isInCombat()) { + if (Creature* pCthun = m_pInstance->GetSingleCreatureFromStorage(NPC_CTHUN)) { + pCthun->AI()->AttackStart(puller); + } + } + } void Reset() { - //Phase information - PhaseTimer = 50000; + currentPhase = GREEN_BEAM; + initialPullerGuid = 0; + eyeBeamCastCount = 0; + eyeBeamCooldown = P1_GREEN_BEAM_COOLDOWN; + greenBeamPhaseTimer = GREEN_BEAM_PHASE_DURATION; - //Eye beam phase 50 seconds - BeamTimer = 3000; - EyeTentacleTimer = 45000; - ClawTentacleTimer = urand(6000, 12000); + IsAlreadyPulled = false; - //Dark Beam phase 35 seconds (each tick = 1 second, 35 ticks) - DarkGlareTick = 0; - DarkGlareTickTimer = 1000; - DarkGlareAngle = 0; - ClockWise = false; - - //Reset flags - m_creature->RemoveAurasDueToSpell(SPELL_RED_COLORATION); - - //Reset Phase - if (m_pInstance) - m_pInstance->SetData(TYPE_CTHUN_PHASE, 0); - - m_creature->SetVisibility(VISIBILITY_OFF); - m_creature->SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f); - m_creature->SetVisibility(VISIBILITY_ON); + if (m_creature) { + m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + // need to reset the orientation in case of wipe during glare phase + m_creature->SetOrientation(3.44f); + RemoveGlarePhaseSpells(); + } + else { + sLog.outError("eye_of_cthunAI: Reset called, but m_creature does not exist."); + } } void UpdateAI(const uint32 diff) { - //No instance if (!m_pInstance) return; - //Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - { - AggroRadius(); + if (!IsAlreadyPulled) { + m_creature->SetTargetGuid(0); return; } - TentacleTimers(diff); - - if (m_pInstance->GetData(TYPE_CTHUN_PHASE) == 0) - FightPhase(diff); - else - GlarePhase(diff); - } - - void FightPhase(uint32 diff) - { - // Green lazer - if (BeamTimer < diff) - { - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { - m_creature->InterruptNonMeleeSpells(false); - DoCastSpellIfCan(target, SPELL_GREEN_BEAM); - - //Correctly update our target - m_creature->SetTargetGuid(target->GetObjectGuid()); - - if (m_creature->HasAura(16245)) - m_creature->RemoveAurasDueToSpell(16245); - } - - //Beam every 3 seconds - BeamTimer = 3000; - } - else - BeamTimer -= diff; - - // PhaseTimer - if (PhaseTimer < diff) - StartBeamPhase(); - else - PhaseTimer -= diff; - } - - void TentacleTimers(uint32 diff) - { - // ClawTentacleTimer - if (ClawTentacleTimer < diff) - { - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { - if (Creature* Spawned = m_creature->SummonCreature(MOB_CLAW_TENTACLE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 500)) - Spawned->AI()->AttackStart(target); - } - - //One claw tentacle every 10 seconds - ClawTentacleTimer = urand(6000, 12000); - } - else - ClawTentacleTimer -= diff; - - // EyeTentacleTimer - if (EyeTentacleTimer < diff) - { - float centerX = m_creature->GetPositionX(); - float centerY = m_creature->GetPositionY(); - float radius = 30.0f; - float angle = 360.0f / 8.0f; - - // Summon 8 of them them in a circle centered around centerX and centerY - for (uint8 i = 0; i < 8; i++) - { - float x = centerX + cos(((float)i * angle) * (3.14f / 180.0f)) * radius; - float y = centerY + sin(((float)i * angle) * (3.14f / 180.0f)) * radius; - - SpawnEyeTentacle(x + frand(-2, 2), y + frand(-2, 2)); - } - - EyeTentacleTimer = 45000; - } - else - EyeTentacleTimer -= diff; - } - - void GlarePhase(uint32 diff) - { - // 35 ticks relative to a 180 - if (DarkGlareTick < 36) // Allow 1 extra for compleition visual - { - UpdateGlareVisual(); - - if (DarkGlareTickTimer < diff) // tick every 1 second - { - if (DarkGlareTick >= 35) // extra for compleition visual - { - EndBeamPhase(); - return; + // No combat reset managment. C'thuns body will reset this creature when needed. + + // Yes, could easily make all these different timers into just two, but + // this approach is much easier to understand, debug and tune. + switch (currentPhase) { + case GREEN_BEAM: + if (greenBeamPhaseTimer < diff) { + if (EnterDarkGlarePhase()) { + darkGlareCastTimer = SPELL_ROTATE_TRIGGER_CASTTIME; + currentPhase = DARK_GLARE_CAST; } - - m_creature->CastSpell(NULL, SPELL_DARK_GLARE, true); - - // Increase tick - DarkGlareTick++; - - if (DarkGlareTick >= 35) - DarkGlareTickTimer = 2000; - else - DarkGlareTickTimer = 1000; } - else - DarkGlareTickTimer -= diff; + else { + greenBeamPhaseTimer -= diff; + UpdateGreenBeamPhase(diff); + } + break; + case DARK_GLARE_CAST: + if (darkGlareCastTimer < diff) { + currentPhase = DARK_GLARE; + darkGlareTimer = DARK_GLARE_PHASE_DURATION; + } + else { + darkGlareCastTimer -= diff; + } + break; + case DARK_GLARE: + if (darkGlareTimer < diff) { + RemoveGlarePhaseSpells(); + currentPhase = DARK_GLARE_COOLING; + darkGlareCoolingTimer = DARK_GLARE_COOLING_DOWN; + } + else { + darkGlareTimer -= diff; + } + break; + case DARK_GLARE_COOLING: + if (darkGlareCoolingTimer < diff) { + currentPhase = GREEN_BEAM; + greenBeamPhaseTimer = GREEN_BEAM_PHASE_DURATION; + eyeBeamCooldown = 0; + } + else { + darkGlareCoolingTimer -= diff; + } + break; + default: + sLog.outError("CThun eye update called with incorrect state: %d", currentPhase); + } + } + + void UpdateGreenBeamPhase(uint32 diff) + { + if (m_creature->HasAura(SPELL_FREEZE_ANIMATION)) + m_creature->RemoveAurasDueToSpell(SPELL_FREEZE_ANIMATION); + + if (eyeBeamCooldown < diff) { + Unit* target = nullptr; + +#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC + target = SelectRandomAliveNotStomach(m_pInstance); +#else + // We force the initial puller as the target for MAX_INITIAL_PULLER_HITS + if (eyeBeamCastCount < MAX_INITIAL_PULLER_HITS) { + target = m_pInstance->GetMap()->GetPlayer(initialPullerGuid); + } + else { + target = SelectRandomAliveNotStomach(m_pInstance); + } +#endif + if (target) { + CastGreenBeam(target); + } + } + else { + eyeBeamCooldown -= diff; } } - void StartBeamPhase() + void AttackStart(Unit* pUnit) override + { + // dont do nothin' + } + + bool EnterDarkGlarePhase() { m_creature->InterruptNonMeleeSpells(false); - - //Select random target for dark beam to start on - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { - // Correctly update our target - m_creature->SetTargetGuid(target->GetObjectGuid()); - - //Face our target - DarkGlareAngle = m_creature->GetAngle(target); - DarkGlareTickTimer = 2000; - DarkGlareTick = 0; - ClockWise = urand(0, 1); - - //Set angle and cast - if (ClockWise) - m_creature->SetOrientation(DarkGlareAngle + ((float)DarkGlareTick * PI / 35)); - else - m_creature->SetOrientation(DarkGlareAngle - ((float)DarkGlareTick * PI / 35)); - - m_creature->CastSpell(m_creature, 16245, true); - m_creature->CastSpell(m_creature, 30138, true); - m_creature->CastSpell(m_creature, SPELL_RED_COLORATION, true); - - //Remove any target - m_creature->SetTargetGuid(ObjectGuid()); + //Select random target for dark beam to start on and start the trigger + if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { + // Remove the target focus but allow the boss to face the current victim + DoStopAttack(); + m_creature->SetFacingToObject(target); + if (DoCastSpellIfCan(m_creature, SPELL_ROTATE_TRIGGER) == CAST_OK) { + if (!m_creature->HasAura(SPELL_FREEZE_ANIMATION)) { + m_creature->CastSpell(m_creature, SPELL_FREEZE_ANIMATION, true); + } + m_creature->SetTargetGuid(ObjectGuid()); + return true; + } + } + return false; + } + + void RemoveGlarePhaseSpells() { + if (m_creature->HasAura(SPELL_ROTATE_NEGATIVE_360)) { + m_creature->RemoveAurasDueToSpell(SPELL_ROTATE_NEGATIVE_360); + } + else if (m_creature->HasAura(SPELL_ROTATE_POSITIVE_360)) { + m_creature->RemoveAurasDueToSpell(SPELL_ROTATE_POSITIVE_360); } - - // Switch to Dark Beam - m_pInstance->SetData(TYPE_CTHUN_PHASE, 1); } - void EndBeamPhase() + bool CastGreenBeam(Unit* target) { - BeamTimer = 3000; - - // Remove Red coloration from c'thun - m_creature->RemoveAurasDueToSpell(SPELL_RED_COLORATION); - - // Next eye beam in 50 seconds - PhaseTimer = 50000; - - // Switch to fight phase - m_pInstance->SetData(TYPE_CTHUN_PHASE, 0); - - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { + if (DoCastSpellIfCan(target, SPELL_GREEN_EYE_BEAM) == CAST_OK) { m_creature->SetTargetGuid(target->GetObjectGuid()); + ++eyeBeamCastCount; + eyeBeamCooldown = P1_GREEN_BEAM_COOLDOWN; + return true; + } + return false; + } +}; + +struct cthunAI : public ScriptedAI +{ + enum CThunPhase + { + PHASE_EYE_NORMAL = 0, + PHASE_EYE_DARK_GLARE = 1, + PHASE_PRE_TRANSITION = 2, + PHASE_TRANSITION = 3, + PHASE_CTHUN_INVULNERABLE = 4, + PHASE_CTHUN_WEAKENED = 5, + PHASE_CTHUN_DONE = 6, + }; + + instance_temple_of_ahnqiraj* m_pInstance; + + bool inProgress; + CThunPhase currentPhase; + + // P1 timers + uint32 eyeTentacleTimer_p1; + uint32 clawTentacleTimer_p1; + + // P2 timers + uint32 weaknessTimer; + uint32 eyeTentacleTimer; + uint32 cthunEmergeTimer; + uint32 giantEyeTentacleTimer; + uint32 stomachEnterPortTimer; + uint32 giantClawTentacleTimer; + uint32 nextStomachEnterGrabTimer; + +#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC + uint32 delayedCombatEntryTimer; + bool isInCombatWithZone; +#endif + + ObjectGuid eyeGuid; + ObjectGuid puntCreatureGuid; + ObjectGuid StomachEnterTargetGUID; + + std::vector fleshTentacles; + + uint32 wipeRespawnEyeTimer; + + cthunAI(Creature* pCreature) : + ScriptedAI(pCreature), + wipeRespawnEyeTimer(0) + { + SetCombatMovement(false); + m_creature->SetLootAndXPModDist(800.0f); // Players in stomach should get rep too, poor bastards + + m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData(); + if (!m_pInstance) + sLog.outError("SD0: No Instance for cthunAI"); + + if (Creature* pPortal = DoSpawnCreature(MOB_CTHUN_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0)) { + pPortal->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); + } + + Reset(); + } + + void AttackStart(Unit* who) override + { + if (!m_creature->isInCombat()) { + Creature* pEye = m_pInstance->GetCreature(eyeGuid); + if (!pEye) { + sLog.outError("cthunAI::AggroRadius could not find pEye"); + return; + } + eye_of_cthunAI* eyeAI = (eye_of_cthunAI*)pEye->AI(); + eyeAI->Pull(who); +#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC + m_creature->SetInCombatWith(who); + pEye->SetInCombatWith(who); +#else m_creature->SetInCombatWithZone(); - m_creature->CastSpell(target, SPELL_GREEN_BEAM, true); + pEye->SetInCombatWithZone(); +#endif + if (m_pInstance) { + m_pInstance->SetData(TYPE_CTHUN, IN_PROGRESS); + } + } + else { + ScriptedAI::AttackStart(who); + } + } + + void JustReachedHome() override + { + if(m_pInstance) + m_pInstance->SetData(TYPE_CTHUN, FAIL); + } + + void Reset() override + { +#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC + delayedCombatEntryTimer = DELAYED_COMBAT_DURATION; + isInCombatWithZone = false; +#endif + inProgress = false; + currentPhase = PHASE_EYE_NORMAL; + if (!m_pInstance) + return; + + cthunEmergeTimer = CTHUN_EMERGE_ANIM_DURATION; + clawTentacleTimer_p1 = P1_CLAW_TENTACLE_RESPAWN_TIMER; + eyeTentacleTimer_p1 = P1_EYE_TENTACLE_RESPAWN_TIMER; + + ResetartUnvulnerablePhase(false); + + // Reset visibility + m_creature->SetVisibility(VISIBILITY_OFF); + m_creature->InterruptNonMeleeSpells(false); + if (m_creature->HasAura(SPELL_CTHUN_VULNERABLE)) { + m_creature->RemoveAurasDueToSpell(SPELL_CTHUN_VULNERABLE); + } + // Demorph should set C'thuns modelId back to burrowed. + // Also removing SPELL_TRANSFORM in case of reset just as he was casting that. + m_creature->RemoveAurasDueToSpell(SPELL_TRANSFORM); + m_creature->DeMorph(); + + m_creature->SetVisibility(VISIBILITY_ON); + m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); + + + // Hack to allow eye-respawning with .respawn chat-command. + // On regular wipe in p2 it's respawned from UpdateAI() + if (!wipeRespawnEyeTimer) { + CheckRespawnEye(); + } + + // Force despawn any tentacles or portals alive. + std::list creaturesToDespawn; + GetCreatureListWithEntryInGrid(creaturesToDespawn, m_creature, allTentacleTypes, 2000.0f); + for (auto it = creaturesToDespawn.cbegin(); it != creaturesToDespawn.cend(); it++) { + if (cthunPortalTentacle* cpt = dynamic_cast((*it)->AI())) { + cpt->DespawnPortal(); + } + if (TemporarySummon* ts = dynamic_cast(*it)) { + ts->UnSummon(); + } + } + + //if (m_pInstance && m_creature->isAlive()) + // m_pInstance->SetData(TYPE_CTHUN, NOT_STARTED); + } + + void CheckRespawnEye() + { + Creature* pEye = nullptr; + if (m_creature->isDead()) { + // Despawning the eye if something weird has happened and C'thun is dead. + if (pEye = m_pInstance->GetCreature(eyeGuid)) { + pEye->ForcedDespawn(); + } + } + else { + // Respawning eye if it exists, but is dead. + // Otherwise attempting to spawn a new eye + if (pEye = m_pInstance->GetCreature(eyeGuid)) { + eye_of_cthunAI* eyeAI = (eye_of_cthunAI*)pEye->AI(); + if (!pEye->isAlive()) { + pEye->Respawn(); + eyeAI->Reset(); // todo: remove if we KNOW that creature::respawn() calls Reset() + } + else { + eyeAI->EnterEvadeMode(); + } + } + else if (pEye = DoSpawnCreature(NPC_EYE_OF_C_THUN, 0, 0, 0, 3.44f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, EYE_DEAD_TO_BODY_EMERGE_DELAY)) { + eyeGuid = pEye->GetGUID(); + } + else { + sLog.outError("C'thun was unable to summon it's eye"); + } } } - void UpdateGlareVisual() + void SummonedCreatureJustDied(Creature* pCreature) override { - // Set angle and cast - if (ClockWise) - m_creature->SetOrientation(DarkGlareAngle + ((float)DarkGlareTick * PI / 35)); - else - m_creature->SetOrientation(DarkGlareAngle - ((float)DarkGlareTick * PI / 35)); + if (pCreature->GetEntry() == MOB_FLESH_TENTACLE) { + auto it = std::find(fleshTentacles.begin(), fleshTentacles.end(), pCreature->GetObjectGuid()); + if (it != fleshTentacles.end()) + fleshTentacles.erase(it); - // Visual corrections - m_creature->SetTargetGuid(ObjectGuid()); - m_creature->StopMoving(); - - if (!m_creature->HasAura(16245)) // Freeze animation - m_creature->CastSpell(m_creature, 16245, true); + } + else if (pCreature->GetEntry() == NPC_EYE_OF_C_THUN) { + currentPhase = PHASE_PRE_TRANSITION; + } } - void SpawnEyeTentacle(float x, float y) + void JustSummoned(Creature* pCreature) override { - if (Creature* Spawned = m_creature->SummonCreature(MOB_EYE_TENTACLE, x, y, m_creature->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 500)) + if (pCreature->GetEntry() == MOB_FLESH_TENTACLE) { + if (fleshTentacles.size() > 1) { + sLog.outError("Flesh tentacle summoned, but there are already %i tentacles up.", fleshTentacles.size()); + } + fleshTentacles.push_back(pCreature->GetGUID()); + } + } + + void UpdateAI(const uint32 diff) override + { + if (!m_pInstance) + return; + + // Delaying respawn of eye if it was a wipe so we get the re-emerge animation before spawn + if (wipeRespawnEyeTimer > 0) { + wipeRespawnEyeTimer -= std::min(diff, wipeRespawnEyeTimer); + if (wipeRespawnEyeTimer < diff) { + CheckRespawnEye(); + wipeRespawnEyeTimer = 0; + } + } + + if (!inProgress) { + // Wait with calling aggroRadius until eye has respawned + if (!wipeRespawnEyeTimer && AggroRadius()) { + inProgress = true; + } + else { + return; + } + } + // Not resetting during transition phase, just wait until it's over, then we reset. + else if (!m_pInstance->GetPlayerInMap(true, false) && currentPhase != PHASE_TRANSITION && currentPhase != PHASE_PRE_TRANSITION) { + inProgress = false; + wipeRespawnEyeTimer = 5000; + EnterEvadeMode(); + // C'thuns eye will enter evade mode through C'thuns Reset() call + } + +#ifdef USE_POSTFIX_PRENERF_PULL_LOGIC + if (!isInCombatWithZone) { + if (delayedCombatEntryTimer < diff) { + isInCombatWithZone = true; + m_creature->SetInCombatWithZone(); + if (Creature* pEye = m_pInstance->GetCreature(eyeGuid)) { + pEye->SetInCombatWithZone(); + } + } + else { + delayedCombatEntryTimer -= diff; + } + } +#endif + + m_creature->SetTargetGuid(0); + + switch (currentPhase) { + case PHASE_EYE_NORMAL: + UpdateTentaclesP1(diff); + break; + case PHASE_EYE_DARK_GLARE: + UpdateTentaclesP1(diff); + break; + case PHASE_PRE_TRANSITION: + // We just wait for eye to death animation before it's despawwn will trigger PHASE_TRANSITION + break; + case PHASE_TRANSITION: + UpdateTransitionPhase(diff); + + break; + case PHASE_CTHUN_INVULNERABLE: + UpdateInvulnerablePhase(diff); + CheckIfAllDead(); + + break; + case PHASE_CTHUN_WEAKENED: + UpdateWeakenedPhase(diff); + CheckIfAllDead(); + + break; + case PHASE_CTHUN_DONE: + + break; + default: + sLog.outError("C'Thun in bugged state: %i", currentPhase); + } + } + + void SummonedCreatureDespawn(Creature* pCreature) override + { + // Despawn will happen EYE_DEAD_TO_BODY_EMERGE_DELAY time after eye death + if (pCreature->GetEntry() == NPC_EYE_OF_C_THUN) { + currentPhase = PHASE_TRANSITION; + + ResetartUnvulnerablePhase(); + + m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + m_creature->SetVisibility(VISIBILITY_OFF); + m_creature->CastSpell(m_creature, SPELL_TRANSFORM, true); + m_creature->SetVisibility(VISIBILITY_ON); + m_creature->CastSpell(m_creature, SPELL_TRANSFORM, true); + } + else if (pCreature->GetEntry() == MOB_FLESH_TENTACLE) { + auto it = std::find(fleshTentacles.begin(), fleshTentacles.end(), pCreature->GetObjectGuid()); + if (it != fleshTentacles.end()) + fleshTentacles.erase(it); + } + } + + void JustDied(Unit* pKiller) override + { + if (m_pInstance) { + currentPhase = PHASE_CTHUN_DONE; + m_pInstance->SetData(TYPE_CTHUN, DONE); + std::list creaturesToDespawn; + GetCreatureListWithEntryInGrid(creaturesToDespawn, m_creature, MOB_FLESH_TENTACLE, 2000.0f); + for (auto it = creaturesToDespawn.cbegin(); it != creaturesToDespawn.cend(); it++) { + if (TemporarySummon* ts = dynamic_cast(*it)) { + ts->UnSummon(); + } + } + + } + } + + void ResetartUnvulnerablePhase(bool spawnFleshTentacles = true) { + giantClawTentacleTimer = P2_FIRST_GIANT_CLAW_SPAWN; + eyeTentacleTimer = P2_FIRST_EYE_TENTACLE_SPAWN; + giantEyeTentacleTimer = P2_FIRST_GIANT_EYE_SPAWN; + + StomachEnterTargetGUID = 0; + stomachEnterPortTimer = 0; + nextStomachEnterGrabTimer = P2_FIRST_STOMACH_GRAB; + + weaknessTimer = 0; + if (spawnFleshTentacles) + SpawnFleshTentacles(); + m_creature->CastSpell(m_creature, SPELL_CARAPACE_OF_CTHUN, true); + } + + bool UnitShouldPull(Unit* unit) + { + float distToCthun = unit->GetDistanceToCenter(m_creature); + //float distToCthun = pPlayer->GetDistance(m_creature); + float zDist = abs(unit->GetPositionZ() - 100.0f); + // If we're at the same Z axis of cthun, or within the maximum possible pull distance + if (zDist < 10.0f && distToCthun < 95.0f && unit->IsWithinLOSInMap(m_creature)) { - Spawned->SetInCombatWithZone(); - Spawned->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.75f); + //xxx: it will still be possible to hide behind one of the pillars in the room to avoid pulling, + //but I don't think it's really something to take advantage of anyway + return true; } + return false; } - void AggroRadius() + bool AggroRadius() { - if (m_creature->getFaction() != 7 && !m_creature->isInCombat()) - m_creature->setFaction(7); // This prevents strange, uncontrolled aggro's through the walls - // Large aggro radius Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) @@ -892,504 +1580,224 @@ struct eye_of_cthunAI : public ScriptedAI Player* pPlayer = itr->getSource(); if (pPlayer && pPlayer->isAlive() && !pPlayer->isGameMaster()) { - if (abs(pPlayer->GetPositionZ() - 100.0f) < 10.0f) // If we're at the same Z axis of cthun + if (UnitShouldPull(pPlayer)) { + AttackStart(pPlayer); + return true; + } + else if (Pet* pPet = pPlayer->GetPet()) { - if (pPlayer->GetDistance(-8653.6f, 1960.3f, 106.5f) < 12.5f || // Anyone is near my door - pPlayer->GetDistance(m_creature) < 50.0f) // If anyone is within 50 units of me - { - m_creature->SetFactionTemporary(14); - m_creature->SetInCombatWithZone(); - m_creature->CastSpell(pPlayer, SPELL_GREEN_BEAM, true); - BeamTimer = 3000; - - Creature* b_Cthun = m_pInstance->GetSingleCreatureFromStorage(NPC_CTHUN); - if (b_Cthun) - { - b_Cthun->SetInCombatWithZone(); - b_Cthun->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - b_Cthun->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - } - - Creature* b_Portal = m_pInstance->GetSingleCreatureFromStorage(NPC_CTHUN_PORTAL); - if (b_Portal) - { - b_Portal->SetInCombatWithZone(); - b_Portal->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - b_Portal->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); - } - return; + if (UnitShouldPull(pPet)) { + AttackStart(pPlayer); //screw the pet, go straight for the head! + return true; } } } } + return false; } - void JustDied(Unit *pKiller) - { - //Death animation/respawning; - Creature* b_Cthun = m_pInstance->GetSingleCreatureFromStorage(NPC_CTHUN); - if (b_Cthun) - { - ((cthunAI*)(b_Cthun->AI()))->BeginEmergePhase(); - m_pInstance->SetData(TYPE_CTHUN_PHASE, 2); - } - } -}; - - -struct eye_tentacleAI : public ScriptedAI -{ - eye_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature) - { - SetCombatMovement(false); - Reset(); - - if (Unit* pPortal = DoSpawnCreature(MOB_SMALL_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 120000)) - { - Portal = pPortal->GetObjectGuid(); - pPortal->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.075f); - } - } - - uint32 MindflayTimer; - uint64 Portal; - - void JustDied(Unit*) - { - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); - } - - void Reset() - { - MindflayTimer = urand(1000, 2000); - - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); - - m_creature->SetInCombatWithZone(); - m_creature->CastSpell(m_creature, SPELL_GROUND_RUPTURE, true); - } - - void Aggro(Unit* pWho) - { - m_creature->SetInCombatWithZone(); - } - - void UpdateAI(const uint32 diff) - { - //Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; - - //MindflayTimer - if (MindflayTimer < diff) - { - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { - if (target->GetPositionZ() >= 100.0f) - { - DoCastSpellIfCan(target, SPELL_MIND_FLAY); - MindflayTimer = 5000; - } + bool CheckIfAllDead() { + if (!SelectRandomAliveNotStomach(m_pInstance)) { + if (m_pInstance->KillPlayersInStomach()) { + m_creature->OnLeaveCombat(); + return true; } } - else - MindflayTimer -= diff; + return false; } -}; -struct claw_tentacleAI : public ScriptedAI -{ - claw_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature) - { - SetCombatMovement(false); - Reset(); + void UpdateTentaclesP1(uint32 diff) { + if (SpawnTentacleIfReady(diff, clawTentacleTimer_p1, 0, MOB_CLAW_TENTACLE)) { + clawTentacleTimer_p1 = P1_CLAW_TENTACLE_RESPAWN_TIMER; + } - if (Unit* pPortal = DoSpawnCreature(MOB_SMALL_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 120000)) - { - Portal = pPortal->GetObjectGuid(); - pPortal->SetFloatValue(OBJECT_FIELD_SCALE_X, 0.075f); + if (eyeTentacleTimer_p1 < diff) { + SpawnEyeTentacles(); + eyeTentacleTimer_p1 = P1_EYE_TENTACLE_RESPAWN_TIMER; + } + else { + eyeTentacleTimer_p1 -= diff; } } - uint32 GroundRuptureTimer; - uint32 HamstringTimer; - uint32 EvadeTimer; - uint64 Portal; - - void JustDied(Unit*) + void UpdateTransitionPhase(uint32 diff) { - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); + UpdateTentaclesP2(diff); + UpdateStomachGrab(diff); + + if (cthunEmergeTimer < diff) { + m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + m_creature->SetInCombatWithZone(); + + currentPhase = PHASE_CTHUN_INVULNERABLE; + } + else { + cthunEmergeTimer -= diff; + } } - void Reset() + void UpdateInvulnerablePhase(uint32 diff) { - //First rupture should happen half a second after we spawn - GroundRuptureTimer = 500; - HamstringTimer = 1000; - EvadeTimer = 5000; + // Weaken if both Flesh Tentacles are killed + if (fleshTentacles.size() == 0) { + weaknessTimer = WEAKNESS_DURATION; - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); - - m_creature->SetInCombatWithZone(); - } - - void Aggro(Unit* pWho) - { - m_creature->SetInCombatWithZone(); - } - - void AttackClosestTarget() - { - DoResetThreat(); - // Large aggro radius - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - Player* pPlayer = itr->getSource(); - if (pPlayer && pPlayer->isAlive() && !pPlayer->isGameMaster()) - { - if (m_creature->IsWithinMeleeRange(pPlayer)) - { - m_creature->getThreatManager().addThreatDirectly(pPlayer, 500.0f); - m_creature->AI()->AttackStart(pPlayer); - return; + DoScriptText(EMOTE_WEAKENED, m_creature); + // If there is a grabbed player, release him. + if (!StomachEnterTargetGUID.IsEmpty()) { + if (Player* pPlayer = m_creature->GetMap()->GetPlayer(StomachEnterTargetGUID)) { + pPlayer->RemoveAurasDueToSpell(SPELL_MOUTH_TENTACLE); } } + + //Remove the damage reduction aura + m_creature->CastSpell(m_creature, SPELL_CTHUN_VULNERABLE, true); + //Make him glow all red and nice + m_creature->RemoveAurasDueToSpell(SPELL_CARAPACE_OF_CTHUN); + + currentPhase = PHASE_CTHUN_WEAKENED; + } + else { + UpdateTentaclesP2(diff); + + UpdateStomachGrab(diff); } } - - void UpdateAI(const uint32 diff) + void UpdateWeakenedPhase(uint32 diff) { - //Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; + // If weakend runs out + if (weaknessTimer < diff) { + ResetartUnvulnerablePhase(); + //note: can set visibility off and on again after removing vulnerable spell, + // if it does not visually dissapear + m_creature->RemoveAurasDueToSpell(SPELL_CTHUN_VULNERABLE); + + currentPhase = PHASE_CTHUN_INVULNERABLE; + } + else { + weaknessTimer -= diff; + } + } + + void SpawnFleshTentacles() { - //EvadeTimer - if (!m_creature->IsWithinMeleeRange(m_creature->getVictim())) - { - AttackClosestTarget(); - if (EvadeTimer < diff) - { - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { - if (target->GetPositionZ() >= 100.0f && target->GetTypeId() == TYPEID_PLAYER && !((Player*)target)->HasMovementFlag(MOVEFLAG_JUMPING)) // If the target is on same level as C'thun - { - //Dissapear and reappear at new position - m_creature->SetVisibility(VISIBILITY_OFF); + if (fleshTentacles.size() != 0) { + sLog.outError("SpawnFleshTentacles() called, but there are already %i tentacles up.", fleshTentacles.size()); + } + //Spawn 2 flesh tentacles in C'thun stomach + for (uint32 i = 0; i < 2; i++) { + Creature* pSpawned = m_creature->SummonCreature(MOB_FLESH_TENTACLE, + fleshTentaclePositions[i][0], + fleshTentaclePositions[i][1], + fleshTentaclePositions[i][2], + fleshTentaclePositions[i][3], + TENTACLE_DESPAWN_FLAG, 1500); + } + + } + + void UpdateStomachGrab(uint32 diff) { + if (!StomachEnterTargetGUID.IsEmpty()) { + if (stomachEnterPortTimer < diff) { + if (Player* pPlayer = m_creature->GetMap()->GetPlayer(StomachEnterTargetGUID)) { - m_creature->NearTeleportTo(target->GetPositionX() + frand(-5, 5), target->GetPositionY() + frand(-5, 5), target->GetPositionZ(), 0); - - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - { - pCreature->SetVisibility(VISIBILITY_OFF); - pCreature->NearTeleportTo(m_creature->GetPositionX(), m_creature->GetPositionY(), target->GetPositionZ(), 0); - pCreature->SetVisibility(VISIBILITY_ON); - } - - GroundRuptureTimer = 500; - HamstringTimer = 2000; - EvadeTimer = 5000; - AttackStart(target); - - m_creature->SetVisibility(VISIBILITY_ON); + DoTeleportPlayer(pPlayer, stomachPortPosition[0], stomachPortPosition[1], stomachPortPosition[2], stomachPortPosition[3]); + pPlayer->RemoveAurasDueToSpell(SPELL_MOUTH_TENTACLE); + if (m_pInstance) { + m_pInstance->AddPlayerToStomach(pPlayer); } } + + StomachEnterTargetGUID = 0; + stomachEnterPortTimer = 0; + } + else { + stomachEnterPortTimer -= diff; } - else - EvadeTimer -= diff; } - else - EvadeTimer = 5000; - //GroundRuptureTimer - if (GroundRuptureTimer < diff) - { - m_creature->CastSpell(m_creature->getVictim(), SPELL_GROUND_RUPTURE, true); - GroundRuptureTimer = 3000000; + if (nextStomachEnterGrabTimer < diff) { + if (Player* target = SelectRandomAliveNotStomach(m_pInstance)) { + target->InterruptNonMeleeSpells(false); + target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, NULL, NULL, m_creature->GetObjectGuid()); + stomachEnterPortTimer = STOMACH_GRAB_DURATION; + StomachEnterTargetGUID = target->GetObjectGuid(); + } + nextStomachEnterGrabTimer = STOMACH_GRAB_COOLDOWN; } - else - GroundRuptureTimer -= diff; - - //HamstringTimer - if (HamstringTimer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_HAMSTRING) == CAST_OK) - HamstringTimer = 5000; + else { + nextStomachEnterGrabTimer -= diff; } - else - HamstringTimer -= diff; - if (GroundRuptureTimer > 500 && GroundRuptureTimer < 3000000 - 1000) - DoMeleeAttackIfReady(); - } -}; - -struct giant_claw_tentacleAI : public ScriptedAI -{ - giant_claw_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature) - { - SetCombatMovement(false); - Reset(); - - if (Unit* pPortal = DoSpawnCreature(MOB_GIANT_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 120000)) - Portal = pPortal->GetObjectGuid(); } - uint32 ThrashTimer; - uint32 GroundRuptureTimer; - uint32 HamstringTimer; - uint32 EvadeTimer; - uint64 Portal; - uint32 GroundStunTimer; - - void JustDied(Unit*) + void UpdateTentaclesP2(uint32 diff) { - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); + SpawnTentacleIfReady(diff, giantClawTentacleTimer, GIANT_CLAW_RESPAWN_TIMER, MOB_GIANT_CLAW_TENTACLE); + SpawnTentacleIfReady(diff, giantEyeTentacleTimer, GIANT_EYE_RESPAWN_TIMER, MOB_GIANT_EYE_TENTACLE); + + if (eyeTentacleTimer < diff) { + SpawnEyeTentacles(); + eyeTentacleTimer = P2_EYE_TENTACLE_RESPAWN_TIMER; + } + else { + eyeTentacleTimer -= diff; + } } - void Reset() + void SpawnEyeTentacles() { - //First rupture should happen half a second after we spawn - GroundRuptureTimer = 500; - HamstringTimer = 1000; - EvadeTimer = 5000; - GroundStunTimer = urand(6000, 12000); - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); + //float centerX = relToThisCreature->GetPositionX(); + //float centerY = relToThisCreature->GetPositionY(); + //float radius = 30.0f; + //float angle = 360.0f / 8.0f; - m_creature->SetInCombatWithZone(); - } - - void Aggro(Unit* pWho) - { - m_creature->SetInCombatWithZone(); - } - - void AttackClosestTarget() - { - DoResetThreat(); - // Large aggro radius - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) + for (uint8 i = 0; i < 8; i++) { - Player* pPlayer = itr->getSource(); - if (pPlayer && pPlayer->isAlive() && !pPlayer->isGameMaster()) + //float x = centerX + cos(((float)i * angle) * (3.14f / 180.0f)) * radius; + //float y = centerY + sin(((float)i * angle) * (3.14f / 180.0f)) * radius; + //float z = relToThisCreature->GetMap()->GetHeight(x, y, relToThisCreature->GetPositionZ()) + 0.1f; + //sLog.outBasic("{%.6f, %.6f, %.6f},", x, y, z); + + float x = eyeTentaclePositions[i][0]; + float y = eyeTentaclePositions[i][1]; + float z = eyeTentaclePositions[i][2]; + if (Creature* Spawned = m_creature->SummonCreature(MOB_EYE_TENTACLE, x, y, z, 0, + TENTACLE_DESPAWN_FLAG, 1500)) + //TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1500)) { - if (m_creature->IsWithinMeleeRange(pPlayer)) - { - m_creature->getThreatManager().addThreatDirectly(pPlayer, 500.0f); - m_creature->AI()->AttackStart(pPlayer); - return; + Spawned->SetInCombatWithZone(); + } + } + } + + bool SpawnTentacleIfReady(uint32 diff, uint32& timer, uint32 resetTo, uint32 id) + { + if (timer < diff) { + if (Unit* target = SelectRandomAliveNotStomach(m_pInstance)) + { + if (target->GetPositionZ() < -30.0f) { + sLog.outError("Cthun trying to spawn %i <-30.0f", id); } - } - } - } - - void UpdateAI(const uint32 diff) - { - //Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; - - //EvadeTimer - if (!m_creature->IsWithinMeleeRange(m_creature->getVictim())) - { - AttackClosestTarget(); - if (EvadeTimer < diff) - { - if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) + float x; + float y; + float z; + m_creature->GetRandomPoint(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.5f, x, y, z); + if (Creature* Spawned = m_creature->SummonCreature(id, x, y, z, 0, + TENTACLE_DESPAWN_FLAG, 1500)) { - if (target->GetPositionZ() >= 100.0f && target->GetTypeId() == TYPEID_PLAYER && !((Player*)target)->HasMovementFlag(MOVEFLAG_JUMPING)) // If the target is on same level as C'thun - { - //Dissapear and reappear at new position - m_creature->SetVisibility(VISIBILITY_OFF); - - m_creature->NearTeleportTo(target->GetPositionX() + frand(-5, 5), target->GetPositionY() + frand(-5, 5), target->GetPositionZ(), 0); - - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - { - pCreature->SetVisibility(VISIBILITY_OFF); - pCreature->NearTeleportTo(m_creature->GetPositionX(), m_creature->GetPositionY(), target->GetPositionZ(), 0); - pCreature->SetVisibility(VISIBILITY_ON); - } - - GroundRuptureTimer = 500; - HamstringTimer = 2000; - EvadeTimer = 5000; - AttackStart(target); - - m_creature->SetVisibility(VISIBILITY_ON); - } + Spawned->AI()->AttackStart(target); } - } - else - EvadeTimer -= diff; - } - else - EvadeTimer = 5000; - - if (GroundStunTimer < diff) - { - m_creature->CastSpell(m_creature->getVictim(), SPELL_GROUND_STUN, true); - GroundStunTimer = urand(6000, 12000); - } - else - GroundStunTimer -= diff; - - //GroundRuptureTimer - if (GroundRuptureTimer < diff) - { - m_creature->CastSpell(m_creature->getVictim(), SPELL_GIANT_GROUND_RUPTURE, true); - GroundRuptureTimer = 3000000; - } - else - GroundRuptureTimer -= diff; - - //HamstringTimer - if (HamstringTimer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_HAMSTRING) == CAST_OK) - HamstringTimer = 5000; - } - else - HamstringTimer -= diff; - - if (ThrashTimer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_THRASH) == CAST_OK) - HamstringTimer = urand(6000, 12000); - } - else - ThrashTimer -= diff; - - if (GroundRuptureTimer > 500 && GroundRuptureTimer < 3000000 - 1000) - DoMeleeAttackIfReady(); - } -}; - -struct giant_eye_tentacleAI : public ScriptedAI -{ - giant_eye_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature) - { - SetCombatMovement(false); - Reset(); - - if (Unit* pPortal = DoSpawnCreature(MOB_GIANT_PORTAL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0)) - Portal = pPortal->GetObjectGuid(); - } - - uint32 BeamTimer; - uint64 Portal; - - void JustDied(Unit*) - { - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); - } - - void Reset() - { - //Green Beam half a second after we spawn - BeamTimer = 500; - - if (Creature* pCreature = m_creature->GetMap()->GetCreature(Portal)) - pCreature->ForcedDespawn(); - } - - void Aggro(Unit* pWho) - { - m_creature->SetInCombatWithZone(); - } - - void UpdateAI(const uint32 diff) - { - //Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; - - //BeamTimer - if (BeamTimer < diff) - { - Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0); - - if (target && !target->HasAura(SPELL_DIGESTIVE_ACID, EFFECT_INDEX_0)) - { - if (DoCastSpellIfCan(target, SPELL_GREEN_BEAM) != CAST_OK) - DoResetThreat(); - else - BeamTimer = 2100; + timer = resetTo; + return true; } } - else - BeamTimer -= diff; - } -}; - -struct flesh_tentacleAI : public ScriptedAI -{ - flesh_tentacleAI(Creature* pCreature) : ScriptedAI(pCreature) - { - SetCombatMovement(false); - Reset(); - - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); - } - - ScriptedInstance* m_pInstance; - - void Reset() - { - - } - - void AttackClosestTarget() - { - DoResetThreat(); - // Large aggro radius - Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) - { - Player* pPlayer = itr->getSource(); - if (pPlayer && pPlayer->isAlive() && !pPlayer->isGameMaster()) - { - if (m_creature->IsWithinMeleeRange(pPlayer)) - { - m_creature->getThreatManager().addThreatDirectly(pPlayer, 500.0f); - m_creature->AI()->AttackStart(pPlayer); - return; - } - } - } - } - - void UpdateAI(const uint32 diff) - { - //Check if we have a target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; - - //EvadeTimer - if (!m_creature->IsWithinMeleeRange(m_creature->getVictim())) - AttackClosestTarget(); - - DoMeleeAttackIfReady(); - } - - void JustDied(Unit* killer) - { - if (m_pInstance) - { - Creature* b_Cthun = m_pInstance->GetSingleCreatureFromStorage(NPC_CTHUN); - if (b_Cthun) - ((cthunAI*)(b_Cthun->AI()))->FleshTentcleKilled(); + else { + timer -= diff; } + return false; } }; @@ -1469,4 +1877,3 @@ void AddSC_boss_cthun() newscript->GetAI = &GetAI_flesh_tentacle; newscript->RegisterSelf(); } - diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_fankriss.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_fankriss.cpp index abd396704..4de80851e 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_fankriss.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_fankriss.cpp @@ -9,6 +9,10 @@ Stryg comments: #include "scriptPCH.h" #include "temple_of_ahnqiraj.h" +#include +#include +#include + enum { SPELL_MORTAL_WOUND = 25646, @@ -18,10 +22,8 @@ enum //SPELL_SUMMON_WORM_1 = 518, //SPELL_SUMMON_WORM_2 = 25831, //SPELL_SUMMON_WORM_3 = 25832, - + SPELL_SPAWN_ENRAGE = 26662, NPC_SPAWN_FANKRISS = 15630, - - MAX_HATCHLINGS = 20, }; struct SpawnLocation @@ -29,21 +31,171 @@ struct SpawnLocation float m_fX, m_fY, m_fZ; }; -static const SpawnLocation aSummonWormLocs[3] = +static constexpr SpawnLocation aSummonWormLocs[3] = { { -8076.53f, 1120.37f, -88.50f }, { -8150.18f, 1146.97f, -87.45f }, { -8023.31f, 1242.42f, -83.47f }, }; +static constexpr SpawnLocation hatchlingLocations[3] = +{ + {-8043.01f, 1254.20f, -84.19f}, + {-8003.00f, 1222.90f, -82.10f}, + {-8022.68f, 1150.08f, -89.33f} +}; +static constexpr float PULL_DISTANCE = 80.0f; +static constexpr SpawnLocation pullCenter = {-8074.88f, 1193.64f, -92.11f}; +static constexpr uint32 aIndex[3] = { 0, 1, 2 }; +static constexpr uint32 aEntangleSpells[3] = { SPELL_ENTANGLE_1, SPELL_ENTANGLE_2, SPELL_ENTANGLE_3 }; +static constexpr size_t MAX_HATCHLINGS = 20; // Max hatchlings alive at any one time +static constexpr size_t MAX_HATCHLINGS_PER_WEB = 4; // Max amount of hatchlings that can spawn at the same time, on one web. Its at least 4, might be 5. +static constexpr uint32 HATCHLINGS_ATTACK_DELAY = 2500; // ~2.5sec in curse killvideo. +static constexpr uint32 WORM_ENRAGE_BASE_TIMER = 15000; +static constexpr uint32 WORM_ENRAGE_ADDITION = 5000; -static const uint32 aIndex[3] = { 0, 1, 2 }; -static const uint32 aEntangleSpells[3] = { SPELL_ENTANGLE_1, SPELL_ENTANGLE_2, SPELL_ENTANGLE_3 }; +// if defined, 2-MAX_HATCHLINGS_PER_WEB hatchlings are spawned in all 3 locations each time a player is ported, +// otherwise 2-MAX_HATCHLINGS_PER_WEB hatchlings will only spawn on the single location the player was ported to. +#define ALWAYS_HATCHLINGS_IN_3_LOCATIONS + +/* + +ALWAYS_HATCHLINGS_IN_3_LOCATIONS when defined will spawn 2-MAX_HATCHLINGS_PER_WEB hatchlings in all 3 locations whenever one player is teleported. + If its not defined 2-MAX_HATCHLINGS_PER_WEB hatchlings only spawn in the location of the teleported player. + In curse video it clearly looks like hatchlings spawn in all 3 locations, while in later videos they only spawn + in the location of a teleported player. + +MAX_HATCHLINGS defines how many hatchlings can be alive at the same time. I'm sure it was capped on retail, but not on the amount. + +MAX_HATCHLINGS_PER_WEB defines how many hatchlings can spawn spawn in one web location. Currently 4, possible it should be 5, but I have not seen it. + +HATCHLINGS_ATTACK_DELAY defines how long after hatchlings spawn until they go in combat with zone and attack the closest target. + If the hatchling is already in combat when HATCHLINGS_ATTACK_DELAY runs out, they will not force themself on the closest target. + + If we want to force players periodically aoe down hatchlings instead of just offtanking them we can set this MAX_HATCHLINGS + to a high value so it's not tankable. This will however require us to adjust down the frequency of players being teleported, + OR not define ALWAYS_HATCHLINGS_IN_3_LOCATIONS. If we increase MAX_HATCHLINGS to an amount that is not offtankable, + the current configuration will most likely overrun the raid. +*/ std::vector vIndex(aIndex, aIndex + 3); -std::vector vEntangleSpells(aEntangleSpells, aEntangleSpells + 3); + +struct creature_spawn_fankrissAI : public ScriptedAI +{ + ScriptedInstance* m_pInstance; + uint32 enrageTimer; + creature_spawn_fankrissAI(Creature* pCreature) : ScriptedAI(pCreature) + { + + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + Reset(); + } + + void Reset() override + { + enrageTimer = 10000; + } + + void UpdateAI(const uint32 diff) override + { + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) { + return; + } + + if (enrageTimer < diff) + { + DoCastSpellIfCan(m_creature, SPELL_SPAWN_ENRAGE, CAST_TRIGGERED); + enrageTimer = std::numeric_limits::max(); + } + else + { + enrageTimer -= diff; + } + DoMeleeAttackIfReady(); + } +}; + +struct creature_vekniss_hatchlingAI : public ScriptedAI +{ + ScriptedInstance* m_pInstance; + uint32 engageTimer; + bool hasEngaged; + bool wasAttacked; + creature_vekniss_hatchlingAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + Reset(); + } + + void Reset() override + { + engageTimer = HATCHLINGS_ATTACK_DELAY; + hasEngaged = false; + wasAttacked = false; + } + + void AttackedBy(Unit* attacker) override + { + engageTimer = 0; + wasAttacked = true; + ScriptedAI::AttackedBy(attacker); + } + void AttackStart(Unit* u) override + { + if (hasEngaged) + ScriptedAI::AttackStart(u); + } + void EnterCombat(Unit* u) override + { + if (hasEngaged) + ScriptedAI::EnterCombat(u); + } + void MoveInLineOfSight(Unit* u) override + { + if (hasEngaged) + ScriptedAI::MoveInLineOfSight(u); + } + void Aggro(Unit* u) override + { + if (hasEngaged) + ScriptedAI::Aggro(u); + } + + void UpdateAI(const uint32 diff) override + { + if (engageTimer <= diff && !hasEngaged) + { + hasEngaged = true; + m_creature->SetInCombatWithZone(); + if (!wasAttacked) + { + if (Unit* pTarget = m_creature->SelectAttackingTarget(AttackingTarget::ATTACKING_TARGET_NEAREST, 0)) + { + if (m_creature->GetDistance(pTarget) > 200) { + return; //avoid running after people far off in the instance somewhere + } + m_creature->getThreatManager().addThreat(pTarget, 1); + AttackStart(pTarget); + + } + } + } + else if(!hasEngaged) { + engageTimer -= diff; + return; + } + + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) { + return; + } + DoMeleeAttackIfReady(); + } + +}; struct boss_fankrissAI : public ScriptedAI { - boss_fankrissAI(Creature* pCreature) : ScriptedAI(pCreature) + boss_fankrissAI(Creature* pCreature) : + ScriptedAI(pCreature), + worms(3) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); @@ -52,32 +204,58 @@ struct boss_fankrissAI : public ScriptedAI ScriptedInstance* m_pInstance; uint32 m_uiMortalWoundTimer; - uint32 m_uiSummonWorm1Timer; - uint32 m_uiSummonWorm2Timer; - uint32 m_uiSummonWorm3Timer; - uint32 m_uiEntangle1Timer; - uint32 m_uiEntangle2Timer; - uint32 m_uiEntangle3Timer; - uint32 m_uiEntangleSummonTimer; - uint32 m_uiEvadeCheckTimer; - uint32 m_uiEntangleAttackTimer; + uint32 m_uiEvadeCheckTimer; + uint32 entangleRotationTimer; - ObjectGuid m_EntangleTargetGUID; - GuidList m_lHatchlingsGUIDs; + struct Worm { + bool shouldSpawn; + bool haveSpawned; + uint32 enrageTimer; + uint32 spawnTimer; + }; + std::vector worms; + uint32 numWormsLastWave; + + struct HatchlingBatch + { + HatchlingBatch(GuidList& list) : + hatchlings(std::move(list)) + {} + uint32 attackTimer; + bool hasAttacked; + GuidList hatchlings; + }; + std::vector hatchlingVec; + uint32 aliveHatchlings; + std::vector < std::pair> entangleSpells = + { + std::make_pair(SPELL_ENTANGLE_1, hatchlingLocations[0]), + std::make_pair(SPELL_ENTANGLE_2, hatchlingLocations[1]), + std::make_pair(SPELL_ENTANGLE_3, hatchlingLocations[2]), + }; + + std::pair entangleTimers[3]; // timer and bool==true meaning the timer is ready for re-initialization void Reset() override { m_uiMortalWoundTimer = urand(4000, 8000); - m_uiSummonWorm1Timer = urand(22500, 30000); - m_uiSummonWorm2Timer = 0; - m_uiSummonWorm3Timer = 0; - m_uiEntangle1Timer = urand(10000, 15000); - m_uiEntangle2Timer = 0; - m_uiEntangle3Timer = 0; - m_uiEntangleSummonTimer = 0; - m_uiEntangleAttackTimer = 0; - m_uiEvadeCheckTimer = 2500; - m_lHatchlingsGUIDs.clear(); + + worms[0].shouldSpawn = true; + worms[0].haveSpawned = false; + worms[0].spawnTimer = urand(20000, 30000); + worms[0].enrageTimer = WORM_ENRAGE_BASE_TIMER; + worms[1].shouldSpawn = false; + worms[2].shouldSpawn = false; + numWormsLastWave = 1; + + m_uiEvadeCheckTimer = 2500; + + // Delaying first webs by 8 seconds, such that they cannot happen + // until, at the earliest, 10 seconds after the pull. + ReinitializeWebTimers(8000); + aliveHatchlings = 0; + hatchlingVec.clear(); + std::random_shuffle(vIndex.begin(), vIndex.end()); } void MoveInLineOfSight(Unit* pWho) override @@ -112,15 +290,11 @@ struct boss_fankrissAI : public ScriptedAI { if (pSummoned->GetEntry() == NPC_VEKNISS_HATCHLING) { - m_lHatchlingsGUIDs.push_back(pSummoned->GetObjectGuid()); - if (Player* pTarget = m_creature->GetMap()->GetPlayer(m_EntangleTargetGUID)) - { - pSummoned->AI()->AttackStart(pTarget); - pSummoned->SetInCombatWithZone(); - } + ++aliveHatchlings; } else if (pSummoned->GetEntry() == NPC_SPAWN_FANKRISS) { + pSummoned->SetInCombatWithZone(); if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { pSummoned->AI()->AttackStart(pTarget); @@ -131,13 +305,143 @@ struct boss_fankrissAI : public ScriptedAI void SummonedCreatureJustDied(Creature* pSummoned) override { if (pSummoned->GetEntry() == NPC_VEKNISS_HATCHLING) - m_lHatchlingsGUIDs.remove(pSummoned->GetObjectGuid()); + { + for (auto it = hatchlingVec.begin(); it != hatchlingVec.end(); it++) + { + it->hatchlings.remove(pSummoned->GetObjectGuid()); + } + --aliveHatchlings; + } + } + + void ReinitializeWebTimers(uint32 add = 0) + { + std::random_shuffle(entangleSpells.begin(), entangleSpells.end()); + // it's possible the longest cooldown should be able to reach more than the + // 45 seconds max that it is here. Old nost code was 45sec. Cmangos use 75sec. + // Should it also be possible that two players are webbed at the same time? + // If not, we need shorter rand intervals and no overlap between the 3 webs. + entangleTimers[0] = std::make_pair(urand(2000 + add, 18000 + add), false); + entangleTimers[1] = std::make_pair(urand(15000 + add, 28000 + add), false); + entangleTimers[2] = std::make_pair(urand(25000 + add, 45000 + add), false); + entangleRotationTimer = 45000 + add; + } + + size_t GetHatchlingSpawnAmount() + { + size_t spawnAmount = std::min(MAX_HATCHLINGS_PER_WEB, MAX_HATCHLINGS - aliveHatchlings); + if (spawnAmount > 2) + spawnAmount = (size_t)urand((uint32)2, (uint32)spawnAmount); + return spawnAmount; + } + + void SummonHatchling(GuidList& batch, SpawnLocation loc) + { + if (Creature* hatchling = m_creature->SummonCreature(NPC_VEKNISS_HATCHLING, loc.m_fX, loc.m_fY, loc.m_fZ, 0.0f, + TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 65000)) + { + batch.push_back(hatchling->GetObjectGuid()); + } + } + + void HandleHatchlings(const uint32 uiDiff) + { + bool reInitWebTimers = true; + for (size_t i = 0; i < 3; i++) + { + bool& webCast = entangleTimers[i].second; + if (webCast) continue; + + uint32& t = entangleTimers[i].first; + if (t < uiDiff) { + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER)) + { + if (DoCastSpellIfCan(pTarget, entangleSpells[i].first) == CAST_OK) + { + webCast = true; + } + } + } + else { + t -= uiDiff; + } + + if (webCast) + { + GuidList batch; +#ifdef ALWAYS_HATCHLINGS_IN_3_LOCATIONS + for (size_t x = 0; x < 3; x++) + { + const SpawnLocation& sLoc = entangleSpells[x].second; + size_t spawnAmount = GetHatchlingSpawnAmount(); + for (size_t s = 0; s < spawnAmount; s++) + { + SummonHatchling(batch, sLoc); + } + } +#else + const SpawnLocation& sLoc = entangleSpells[i].second; + size_t spawnAmount = GetHatchlingSpawnAmount(); + for (size_t s = 0; s < spawnAmount; s++) + { + SummonHatchling(batch, sLoc); + } +#endif + hatchlingVec.push_back(HatchlingBatch(batch)); + } + else { + reInitWebTimers = entangleTimers[i].second ? reInitWebTimers : false; + } + } + + if (reInitWebTimers && entangleRotationTimer < uiDiff) + { + ReinitializeWebTimers(); + } + else { + entangleRotationTimer -= uiDiff; + } + } + + void SummonWorm(const SpawnLocation& loc, uint32 enrageTimer) + { + if (Creature* pC = m_creature->SummonCreature(NPC_SPAWN_FANKRISS, loc.m_fX, loc.m_fY, loc.m_fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 50000)) + { + creature_spawn_fankrissAI* ai = dynamic_cast(pC->AI()); + if (!ai) { + sLog.outError("unable to cast spawn of fankriss AI to creature_spawn_fankrissAI"); + return; + } + ai->enrageTimer = enrageTimer; + } } void UpdateAI(const uint32 uiDiff) override { - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + if (!m_creature->isInCombat()) { + Map::PlayerList const &PlayerList = m_creature->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) + { + Player* pPlayer = itr->getSource(); + if (pPlayer && pPlayer->isAlive() && !pPlayer->isGameMaster()) + { + // cheap way of quickly disgarding the check most of the time. No point + // where he can be pulled should be higher than this point (he is at roughly -100) + if (pPlayer->GetPositionZ() > -70.0f) + continue; + + float distToPull = pPlayer->GetDistance(pullCenter.m_fX, pullCenter.m_fY, pullCenter.m_fZ); + if (distToPull < PULL_DISTANCE && pPlayer->IsWithinLOSInMap(m_creature)) + { + AttackStart(pPlayer); + } + } + } + } + + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) { return; + } // // Mortal Wound @@ -149,150 +453,60 @@ struct boss_fankrissAI : public ScriptedAI else m_uiMortalWoundTimer -= uiDiff; - // - // Summon Worm (1-3) - if (m_uiSummonWorm1Timer < uiDiff) + bool allWormsSpawned = true; + for(size_t i = 0; i < worms.size(); i++) + { + Worm& w = worms[i]; + if (w.shouldSpawn && !w.haveSpawned) { + if (w.spawnTimer < uiDiff) { + w.haveSpawned = true; + SummonWorm(aSummonWormLocs[vIndex[i]], w.enrageTimer); + } + else { + allWormsSpawned = false; + w.spawnTimer -= uiDiff; + } + } + } + + if (allWormsSpawned) { - // randomize order of Summon Worm pattern std::random_shuffle(vIndex.begin(), vIndex.end()); - m_creature->SummonCreature(NPC_SPAWN_FANKRISS, aSummonWormLocs[vIndex[0]].m_fX, aSummonWormLocs[vIndex[0]].m_fY, aSummonWormLocs[vIndex[0]].m_fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 50000); - m_uiSummonWorm1Timer = urand(50000, 70000); - m_uiSummonWorm2Timer = urand(1000, 30000); - m_uiSummonWorm3Timer = urand(2000, 30000); - } - else - m_uiSummonWorm1Timer -= uiDiff; - - if (m_uiSummonWorm2Timer) - { - if (m_uiSummonWorm2Timer <= uiDiff) + uint32 spawnCount = urand(1, 3); + for (size_t i = 0; i < 3; i++) { - m_creature->SummonCreature(NPC_SPAWN_FANKRISS, aSummonWormLocs[vIndex[1]].m_fX, aSummonWormLocs[vIndex[1]].m_fY, aSummonWormLocs[vIndex[1]].m_fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 50000); - m_uiSummonWorm2Timer = 0; - } - else - m_uiSummonWorm2Timer -= uiDiff; - } - - if (m_uiSummonWorm3Timer) - { - if (m_uiSummonWorm3Timer <= uiDiff) - { - m_creature->SummonCreature(NPC_SPAWN_FANKRISS, aSummonWormLocs[vIndex[2]].m_fX, aSummonWormLocs[vIndex[2]].m_fY, aSummonWormLocs[vIndex[2]].m_fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 50000); - m_uiSummonWorm3Timer = 0; - } - else - m_uiSummonWorm3Timer -= uiDiff; - } - - // - // Entangle (1-3) - if (m_uiEntangle1Timer < uiDiff) - { - // randomize order of Entangle pattern - std::random_shuffle(vEntangleSpells.begin(), vEntangleSpells.end()); - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER)) - { - if (DoCastSpellIfCan(pTarget, vEntangleSpells[0]) == CAST_OK) - { - m_uiEntangle1Timer = urand(35000, 45000); - m_uiEntangle2Timer = urand(2000, 20000); - m_uiEntangle3Timer = urand(2000, 20000); - m_EntangleTargetGUID = pTarget->GetObjectGuid(); - m_uiEntangleSummonTimer = 1000; + Worm& w = worms[i]; + w.haveSpawned = false; + w.shouldSpawn = i < spawnCount; + if (w.shouldSpawn) { + w.enrageTimer = WORM_ENRAGE_BASE_TIMER + WORM_ENRAGE_ADDITION*i; // 15sec for first, 20 for second and 25 sec for last. + /* How long after each wave has fully spawned will next wave start spawning. (minTime,maxTime) + 1x snake in prev wave = (18, 23) + 2x snake in prev wave = (25 30) + 3x snake in prev wave = (32 37) + */ + if (i == 0) + w.spawnTimer = 18000 + ((numWormsLastWave-1)*7000) + urand(0, 5000); + else + w.spawnTimer = worms[i-1].spawnTimer + urand(4000, 8000); // Each snake in a wave comes 4-8s after the previous one } } + numWormsLastWave = spawnCount; } - else - m_uiEntangle1Timer -= uiDiff; - - if (m_uiEntangle2Timer && !m_uiEntangleSummonTimer) - { - if (m_uiEntangle2Timer < uiDiff) - { - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER)) - { - if (DoCastSpellIfCan(pTarget, vEntangleSpells[1]) == CAST_OK) - { - m_uiEntangle2Timer = 0; - m_EntangleTargetGUID = pTarget->GetObjectGuid(); - m_uiEntangleSummonTimer = 1000; - } - } - } - else - m_uiEntangle2Timer -= uiDiff; - } - - if (m_uiEntangle3Timer && !m_uiEntangleSummonTimer) - { - if (m_uiEntangle3Timer < uiDiff) - { - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0, nullptr, SELECT_FLAG_PLAYER)) - { - if (DoCastSpellIfCan(pTarget, vEntangleSpells[2]) == CAST_OK) - { - m_uiEntangle3Timer = 0; - m_EntangleTargetGUID = pTarget->GetObjectGuid(); - m_uiEntangleSummonTimer = 1000; - } - } - } - else - m_uiEntangle3Timer -= uiDiff; - } - - // - // Spawn 4 Hatchlings on top of players who have been entangled - if (m_uiEntangleSummonTimer) - { - if (m_uiEntangleSummonTimer < uiDiff) - { - if (m_lHatchlingsGUIDs.size() < (MAX_HATCHLINGS + 4)) // If there are already more than MAX_HATCHLINGS - 4 up, prevent spawn - { - if (Player* pTarget = m_creature->GetMap()->GetPlayer(m_EntangleTargetGUID)) - { - float fX, fY, fZ; - for (uint8 i = 0; i < 4; ++i) - { - m_creature->GetRandomPoint(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), 3.0f, fX, fY, fZ); - m_creature->SummonCreature(NPC_VEKNISS_HATCHLING, fX, fY, fZ, 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 65000); - } - } - } - m_uiEntangleAttackTimer = 1500; - m_uiEntangleSummonTimer = 0; - } - else - m_uiEntangleSummonTimer -= uiDiff; - } - - // Summoned Hatchlings should be set in combat with Zone after meleeing the person they've spawned next to once (if not picked up by a tank) - if (m_uiEntangleAttackTimer) - { - if (m_uiEntangleAttackTimer < uiDiff) - { - for (GuidList::const_iterator itr = m_lHatchlingsGUIDs.begin(); itr != m_lHatchlingsGUIDs.end(); itr++) - { - if (Creature* pSummoned = m_creature->GetMap()->GetCreature(*itr)) - pSummoned->SetInCombatWithZone(); - } - } - else - m_uiEntangleAttackTimer -= uiDiff; - } + + HandleHatchlings(uiDiff); DoMeleeAttackIfReady(); - // Evade in case Fankriss starts running after someone at zone in - if (m_uiEvadeCheckTimer < uiDiff) - { - m_uiEvadeCheckTimer = 2500; - if (m_creature->GetPositionY() > 1400) - EnterEvadeMode(); - } - else - m_uiEvadeCheckTimer -= uiDiff; + // Evade in case Fankriss starts running after someone at zone in + if (m_uiEvadeCheckTimer < uiDiff) + { + m_uiEvadeCheckTimer = 2500; + if (m_creature->GetPositionY() > 1400) + EnterEvadeMode(); + } + else + m_uiEvadeCheckTimer -= uiDiff; } }; @@ -301,6 +515,16 @@ CreatureAI* GetAI_boss_fankriss(Creature* pCreature) return new boss_fankrissAI(pCreature); } +CreatureAI* GetAI_creature_spawn_fankriss(Creature* pCreature) +{ + return new creature_spawn_fankrissAI(pCreature); +} + +CreatureAI* GetAI_creature_vekniss_hatchling(Creature* pCreature) +{ + return new creature_vekniss_hatchlingAI(pCreature); +} + void AddSC_boss_fankriss() { Script* pNewScript; @@ -309,4 +533,17 @@ void AddSC_boss_fankriss() pNewScript->Name = "boss_fankriss"; pNewScript->GetAI = &GetAI_boss_fankriss; pNewScript->RegisterSelf(); + + + pNewScript = new Script; + pNewScript->Name = "creature_spawn_fankriss"; + pNewScript->GetAI = &GetAI_creature_spawn_fankriss; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "creature_vekniss_hatchling"; + pNewScript->GetAI = &GetAI_creature_vekniss_hatchling; + pNewScript->RegisterSelf(); + + } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_huhuran.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_huhuran.cpp index 05099edd5..3abc0f1fe 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_huhuran.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_huhuran.cpp @@ -25,121 +25,122 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "scriptPCH.h" +#include "temple_of_ahnqiraj.h" -#define EMOTE_GENERIC_FRENZY_KILL -1000001 -#define EMOTE_GENERIC_BERSERK -1000004 +enum +{ + EMOTE_GENERIC_FRENZY_KILL = -1000001, + EMOTE_GENERIC_BERSERK = -1000004, -#define SPELL_FRENZY 26051 -#define SPELL_BERSERK 26068 -#define SPELL_POISONBOLT 26052 -#define SPELL_NOXIOUSPOISON 26053 -#define SPELL_WYVERNSTING 26180 -#define SPELL_ACIDSPIT 26050 + SPELL_ACIDSPIT = 26050, + SPELL_FRENZY = 26051, + SPELL_NOXIOUSPOISON = 26053, + SPELL_BERSERK = 26068, + SPELL_WYVERNSTING = 26180 +}; struct boss_huhuranAI : public ScriptedAI { boss_huhuranAI(Creature* pCreature) : ScriptedAI(pCreature) { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } - uint32 Frenzy_Timer; - uint32 Wyvern_Timer; - uint32 Spit_Timer; - uint32 PoisonBolt_Timer; - uint32 NoxiousPoison_Timer; - uint32 FrenzyBack_Timer; + ScriptedInstance* m_pInstance; - bool Frenzy; - bool Berserk; + uint32 m_uiFrenzyTimer; + uint32 m_uiWyvernTimer; + uint32 m_uiSpitTimer; + uint32 m_uiNoxiousPoisonTimer; + uint32 m_uiBerserkTimer; + + bool m_bBerserk; + + void MoveInLineOfSight(Unit* pWho) override + { + + if (m_creature->canAttack(pWho) + && !m_creature->isInCombat() + && m_creature->IsWithinDistInMap(pWho, 80.0f) + && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) + { + AttackStart(pWho); + } + ScriptedAI::MoveInLineOfSight(pWho); + } + + void JustDied(Unit*) override + { + if (m_pInstance) + m_pInstance->SetData(TYPE_HUHURAN, DONE); + } void Reset() { - Frenzy_Timer = urand(25000, 35000); - Wyvern_Timer = urand(18000, 28000); - Spit_Timer = 8000; - PoisonBolt_Timer = 4000; - NoxiousPoison_Timer = urand(10000, 20000); - FrenzyBack_Timer = 15000; + m_uiFrenzyTimer = urand(25000, 35000); + m_uiWyvernTimer = urand(18000, 28000); + m_uiSpitTimer = 8000; + m_uiNoxiousPoisonTimer = urand(10000, 20000); + m_uiBerserkTimer = 5 * MINUTE * IN_MILLISECONDS; - Frenzy = false; - Berserk = false; + m_bBerserk = false; } - void UpdateAI(const uint32 diff) + void UpdateAI(const uint32 uiDiff) { //Return since we have no target if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; - //Frenzy_Timer - if (!Frenzy && Frenzy_Timer < diff) + //m_uiFrenzyTimer + if (m_uiFrenzyTimer < uiDiff) { - DoCastSpellIfCan(m_creature, SPELL_FRENZY); - DoScriptText(EMOTE_GENERIC_FRENZY_KILL, m_creature); - Frenzy = true; - PoisonBolt_Timer = 3000; - Frenzy_Timer = urand(25000, 35000); + if (DoCastSpellIfCan(m_creature, SPELL_FRENZY) == CAST_OK) + { + DoScriptText(EMOTE_GENERIC_FRENZY_KILL, m_creature); + m_uiFrenzyTimer = urand(25000, 35000); + } } - else Frenzy_Timer -= diff; + else + m_uiFrenzyTimer -= uiDiff; // Wyvern Timer - if (Wyvern_Timer < diff) + if (m_uiWyvernTimer < uiDiff) { - if (Unit *target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) - { - if (DoCastSpellIfCan(target, SPELL_WYVERNSTING) == CAST_OK) - Wyvern_Timer = urand(15000, 32000); - } + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_WYVERNSTING) == CAST_OK) + m_uiWyvernTimer = urand(15000, 32000); } - else Wyvern_Timer -= diff; + else + m_uiWyvernTimer -= uiDiff; //Spit Timer - if (Spit_Timer < diff) + if (m_uiSpitTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ACIDSPIT) == CAST_OK) - Spit_Timer = urand(5000, 10000); + m_uiSpitTimer = urand(5000, 10000); } - else Spit_Timer -= diff; + else + m_uiSpitTimer -= uiDiff; - //NoxiousPoison_Timer - if (NoxiousPoison_Timer < diff) + //m_uiNoxiousPoisonTimer + if (m_uiNoxiousPoisonTimer < uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_NOXIOUSPOISON) == CAST_OK) - NoxiousPoison_Timer = urand(12000, 24000); + m_uiNoxiousPoisonTimer = urand(12000, 24000); } - else NoxiousPoison_Timer -= diff; + else + m_uiNoxiousPoisonTimer -= uiDiff; - //PoisonBolt only if frenzy or berserk - if (Frenzy || Berserk) - { - if (PoisonBolt_Timer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_POISONBOLT) == CAST_OK) - PoisonBolt_Timer = 3000; - } - else PoisonBolt_Timer -= diff; - } - - //FrenzyBack_Timer - if (Frenzy && FrenzyBack_Timer < diff) - { - m_creature->InterruptNonMeleeSpells(false); - Frenzy = false; - FrenzyBack_Timer = 15000; - } - else FrenzyBack_Timer -= diff; - - if (!Berserk && m_creature->GetHealthPercent() < 31.0f) + if (m_bBerserk) + DoCastSpellIfCan(m_creature, SPELL_BERSERK, CAST_AURA_NOT_PRESENT); + else if (m_creature->GetHealthPercent() < 31.0f || m_uiBerserkTimer < uiDiff) { DoScriptText(EMOTE_GENERIC_BERSERK, m_creature); - Berserk = true; + m_bBerserk = true; } - else if (Berserk) - DoCastSpellIfCan(m_creature, SPELL_BERSERK, CAST_AURA_NOT_PRESENT); - - if (m_creature->isAttackReady() && m_creature->getVictim()->HasAura(SPELL_WYVERNSTING)) - m_creature->getVictim()->RemoveAurasDueToSpell(SPELL_WYVERNSTING); + else + m_uiBerserkTimer -= uiDiff; DoMeleeAttackIfReady(); } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_ouro.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_ouro.cpp index b2062c7e1..1d0f430c7 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_ouro.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_ouro.cpp @@ -19,8 +19,8 @@ /* ScriptData SDName: Boss_Ouro -SD%Complete: 50 -SDComment: script needs to be reworked +SD%Complete: 90 +SDComment: Some minor adjustments may be required SDCategory: Temple of Ahn'Qiraj EndScriptData */ @@ -29,58 +29,244 @@ EndScriptData */ enum { - SPELL_SWEEP = 26103, - SPELL_SANDBLAST = 26102, - SPELL_GROUND_RUPTURE = 26100, - SPELL_BIRTH = 26262, //The Birth Animation - SPELL_BOULDER = 26616, - SPELL_BERSERK = 26615, + // ground spells + SPELL_SWEEP = 26103, + SPELL_SANDBLAST = 26102, + SPELL_BOULDER = 26616, + SPELL_BERSERK = 26615, - SPELL_SUMMON_SCARABS = 26060, - SPELL_SUMMON_OURO_MOUND = 26058, - SPELL_SUMMON_OURO = 26642, + // emerge spells + SPELL_BIRTH = 26262, // The Birth Animation + SPELL_GROUND_RUPTURE = 26100, // spell not confirmed + SPELL_SUMMON_BASE = 26133, // summons gameobject 180795 + SPELL_DESPAWN_BASE = 26594, - SPELL_DIRTMOUND_PASSIVE = 26092, - SPELL_SUBMERGE_VISUAL = 26063, + // submerge spells + SPELL_SUBMERGE_VISUAL = 26063, + SPELL_SUMMON_OURO_MOUNDS = 26058, // summons 5 dirt mounds + SPELL_SUMMON_TRIGGER = 26284, - NPC_OURO_SPAWNER = 15957, - NPC_OURO_TRIGGER = 15717 + // SPELL_SUMMON_OURO_TRIGG = 26642, + SPELL_SUMMON_OURO = 26061, // used by the script to summon the boss directly + //SPELL_QUAKE = 26093, + + // other spells - not used + SPELL_SUMMON_SCARABS = 26060, // triggered after 30 secs - cast by the Dirt Mounds + SPELL_DIRTMOUND_PASSIVE = 26092, // casts 26093 every 1 sec + // SPELL_SET_OURO_HEALTH = 26075, // removed from DBC + // SPELL_SAVE_OURO_HEALTH = 26076, // removed from DBC + // SPELL_TELEPORT_TRIGGER = 26285, // removed from DBC + // SPELL_SUBMERGE_TRIGGER = 26104, // removed from DBC + SPELL_SUMMON_OURO_MOUND = 26617, + // SPELL_SCARABS_PERIODIC = 26619, // cast by the Dirt Mounds in order to spawn the scarabs - removed from DBC + + // summoned npcs + // NPC_OURO_SCARAB = 15718, // summoned by Dirt Mounds + NPC_OURO_TRIGGER = 15717, + NPC_DIRT_MOUND = 15712, }; -struct boss_ouroAI : public ScriptedAI +/* + * Sand Blast timers are based on June 2006 values (15-20s) as shown in + * https://www.youtube.com/watch?v=REmX3uRTFkQ and further reduced to account + * for April 2006 nerfs (http://blue.cardplace.com/cache/wow-dungeons/481724.htm & + * http://blue.cardplace.com/cache/wow-general/7950998.htm + * Sweep timers based on the same video. No known nerfs. + */ +const uint32_t SANDBLAST_TIMER_INITIAL_MIN = 30000; +const uint32_t SANDBLAST_TIMER_INITIAL_MAX = 45000; +const uint32_t SANDBLAST_TIMER_MIN = 10000; +const uint32_t SANDBLAST_TIMER_MAX = 15000; +const uint32_t SUBMERGE_TIMER = 60000; +const uint32_t SUBMERGE_ANIMATION_INVIS = 2000; +const uint32_t SWEEP_TIMER = 15000; + +struct boss_ouroAI : public Scripted_NoMovementAI { - boss_ouroAI(Creature* pCreature) : ScriptedAI(pCreature) + boss_ouroAI(Creature* pCreature) : Scripted_NoMovementAI(pCreature) { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); - SetCombatMovement(false); } + ScriptedInstance* m_pInstance; + uint32 m_uiSweepTimer; uint32 m_uiSandBlastTimer; uint32 m_uiSubmergeTimer; - uint32 m_uiBackTimer; - uint32 m_uiChangeTargetTimer; - uint32 m_uiSpawnTimer; + bool m_SummonBase; + uint32 m_uiNoMeleeTimer; + uint32 m_uiSubmergeInvisTimer; + uint32 m_justEmergedGraceTimer; + uint32 m_uiSummonMoundTimer; bool m_bEnraged; bool m_bSubmerged; + ObjectGuid m_ouroTriggerGuid; + + WorldLocation m_StartingLoc; + void Reset() { - m_uiSweepTimer = urand(5000, 10000); - m_uiSandBlastTimer = urand(20000, 35000); - m_uiSubmergeTimer = urand(90000, 150000); - m_uiBackTimer = urand(30000, 45000); - m_uiChangeTargetTimer = urand(5000, 8000); - m_uiSpawnTimer = urand(10000, 20000); + m_uiSweepTimer = urand(30000, 40000); + m_uiSandBlastTimer = urand(SANDBLAST_TIMER_INITIAL_MIN, SANDBLAST_TIMER_INITIAL_MAX); + m_uiSubmergeTimer = SUBMERGE_TIMER; + m_SummonBase = true; + m_uiSubmergeInvisTimer = SUBMERGE_ANIMATION_INVIS; + + m_uiNoMeleeTimer = 3000; + // Source : http://wowwiki.wikia.com/wiki/Ouro + // "Ouro seems to give you about 10 seconds to get a MT in there when he pops up" + m_justEmergedGraceTimer = 10000; - m_bEnraged = false; - m_bSubmerged = false; + m_uiSummonMoundTimer = 10000; + m_bEnraged = false; + m_bSubmerged = false; + + + m_ouroTriggerGuid.Clear(); } - void Aggro(Unit* pWho) + void Aggro(Unit* /*pWho*/) { - DoCastSpellIfCan(m_creature, SPELL_BIRTH); + if (m_pInstance) + m_pInstance->SetData(TYPE_OURO, IN_PROGRESS); + + m_creature->GetPosition(m_StartingLoc); + } + + void DespawnCreatures(bool ShouldDespawnScarabs) + { + std::list lCreature; + m_creature->GetCreatureListWithEntryInGrid(lCreature, NPC_DIRT_MOUND, 250.0f); + if (ShouldDespawnScarabs) + m_creature->GetCreatureListWithEntryInGrid(lCreature, NPC_OURO_SCARAB, 250.0f); + for (std::list::iterator itr = lCreature.begin(); itr != lCreature.end(); ++itr) + (*itr)->ForcedDespawn(); + } + + void JustReachedHome() + { + if (m_pInstance) + m_pInstance->SetData(TYPE_OURO, FAIL); + + DespawnCreatures(true); + m_creature->CastSpell(m_creature, SPELL_DESPAWN_BASE, true); + + Submerge(true); + m_creature->ForcedDespawn(2000); + } + + void JustDied(Unit* /*pKiller*/) + { + if (m_pInstance) + m_pInstance->SetData(TYPE_OURO, DONE); + + m_creature->CastSpell(m_creature, SPELL_DESPAWN_BASE, true); + } + + void JustSummoned(Creature* pSummoned) + { + switch (pSummoned->GetEntry()) + { + case NPC_OURO_TRIGGER: + m_ouroTriggerGuid = pSummoned->GetGUID(); + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) + pSummoned->GetMotionMaster()->MoveFollow(pTarget, 0.0f, 0.0f); + break; + } + } + + void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) override + { + if (pSpell->Id == SPELL_SANDBLAST && pTarget) + { + if (m_creature->getThreatManager().getThreat(pTarget)) + m_creature->getThreatManager().modifyThreatPercent(pTarget, -100); + } + } + + void Submerge(bool isReset = false) + { + // Source : http://wowwiki.wikia.com/wiki/Ouro + // "Ouro has a chance to submerge every 1.5minutes. + // He will not submerge if he is busy casting a Sand Blast or Sweep, else he will submerge + // (ie. the chance of submerging is totally random)" + m_uiSubmergeTimer = SUBMERGE_TIMER; + + if (DoCastSpellIfCan(m_creature, SPELL_SUBMERGE_VISUAL, false) == CAST_OK) + { + if (!isReset) + { + DoCastSpellIfCan(m_creature, SPELL_SUMMON_OURO_MOUNDS, CAST_TRIGGERED); + DoCastSpellIfCan(m_creature, SPELL_SUMMON_TRIGGER, CAST_TRIGGERED); + } + + m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); + ClearTargetIcon(); + + m_bSubmerged = true; + m_uiSubmergeTimer = 30000; + + m_justEmergedGraceTimer = 10000; + m_uiNoMeleeTimer = 3000; + m_uiSubmergeInvisTimer = SUBMERGE_ANIMATION_INVIS; + DoResetThreat(); + } + else + { + m_uiSubmergeTimer = 2000; // try again in a moment + } + } + + void SetNewTarget(Unit &pNewTarget) + { + const uint32 uiMaxThreat = m_creature->getThreatManager().getThreat(m_creature->getVictim()); + + // erase current target's threat as soon as we switch the target now + m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(), -100); + + // give the new target aggro + m_creature->getThreatManager().addThreat(&pNewTarget, uiMaxThreat); + } + + + bool CheckForMelee() + { + // at first we check for the current player-type target + Unit* pMainTarget = m_creature->getVictim(); + if (pMainTarget->GetTypeId() == TYPEID_PLAYER && !pMainTarget->ToPlayer()->isGameMaster() && + m_creature->IsWithinMeleeRange(pMainTarget) && m_creature->IsWithinLOSInMap(pMainTarget)) + { + return true; + } + + // at second we look for any melee player-type target (if current target is not reachable) + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, nullptr, + SELECT_FLAG_PLAYER_NOT_GM | SELECT_FLAG_IN_LOS | SELECT_FLAG_IN_MELEE_RANGE)) + { + SetNewTarget(*pTarget); + return true; + } + + // reaching this point means there are no more reachable player-type targets in melee range + + // at third we take any melee pet target just to punch in the face + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, nullptr, + SELECT_FLAG_PET | SELECT_FLAG_IN_LOS | SELECT_FLAG_IN_MELEE_RANGE)) + { + SetNewTarget(*pTarget); + return false; + } + + // at fourth we take anything to wipe it out and log (whatever, just in case) + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_TOPAGGRO, 0, nullptr, + SELECT_FLAG_NOT_PLAYER | SELECT_FLAG_IN_LOS | SELECT_FLAG_IN_MELEE_RANGE)) + { + SetNewTarget(*pTarget); + } + return false; } void UpdateAI(const uint32 uiDiff) @@ -91,11 +277,21 @@ struct boss_ouroAI : public ScriptedAI if (!m_bSubmerged) { + // Summon sandworm base + if (m_SummonBase) + { + // Note: server side spells should be cast directly + m_creature->CastSpell(m_creature, SPELL_SUMMON_BASE, true); + // Cast Despawn base to trigger spawn anim + m_creature->CastSpell(m_creature, SPELL_DESPAWN_BASE, true); + m_SummonBase = false; + } + // Sweep if (m_uiSweepTimer < uiDiff) { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SWEEP) == CAST_OK) - m_uiSweepTimer = urand(15000, 30000); + if (DoCastSpellIfCan(m_creature, SPELL_SWEEP) == CAST_OK) + m_uiSweepTimer = SWEEP_TIMER; } else m_uiSweepTimer -= uiDiff; @@ -103,71 +299,141 @@ struct boss_ouroAI : public ScriptedAI // Sand Blast if (m_uiSandBlastTimer < uiDiff) { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SANDBLAST) == CAST_OK) - m_uiSandBlastTimer = urand(20000, 35000); + // one post claims Sand Blast has melee priority when enraged, another post claims otherwise :( + // note: need testing + auto target = m_creature->getThreatManager().getHostileTarget(); + + if (target && DoCastSpellIfCan(target, SPELL_SANDBLAST) == CAST_OK) + { + m_uiSandBlastTimer = urand(SANDBLAST_TIMER_MIN, SANDBLAST_TIMER_MAX); + } } else m_uiSandBlastTimer -= uiDiff; if (!m_bEnraged) { + // Enrage at 20% HP if (m_creature->GetHealthPercent() < 20.0f) { - m_bEnraged = true; - return; + if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK) + { + m_bEnraged = true; + return; + } } // Submerge if (m_uiSubmergeTimer < uiDiff) { - //Cast - m_creature->HandleEmote(EMOTE_ONESHOT_SUBMERGE); - m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - m_creature->setFaction(35); - if (DoCastSpellIfCan(m_creature, SPELL_DIRTMOUND_PASSIVE) == CAST_OK) - { - m_bSubmerged = true; - m_uiBackTimer = urand(30000, 45000); - } + Submerge(); } else m_uiSubmergeTimer -= uiDiff; } else - DoCastSpellIfCan(m_creature, SPELL_BERSERK, CAST_AURA_NOT_PRESENT); + { + // Summon 1 mound every 10 secs when enraged + if (m_uiSummonMoundTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_OURO_MOUND) == CAST_OK) + m_uiSummonMoundTimer = 10000; + } + else + m_uiSummonMoundTimer -= uiDiff; + } - DoMeleeAttackIfReady(); + // every tick we check for melee targets to attack + if (CheckForMelee()) + { + m_uiNoMeleeTimer = std::max((uint32)3000, m_justEmergedGraceTimer); + } + + // If we are within range melee the target + if (m_creature->CanReachWithMeleeAttack(m_creature->getVictim())) + { + DoMeleeAttackIfReady(); + } + // Spam Boulder spell when enraged and not tanked + else if (m_bEnraged) + { + if (!m_creature->IsNonMeleeSpellCasted(false)) + { + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) + DoCastSpellIfCan(pTarget, SPELL_BOULDER); + } + } + // Submerge if no melee and not enraged + else if (m_uiNoMeleeTimer < uiDiff) + { + Submerge(); + } + else + m_uiNoMeleeTimer -= uiDiff; + + m_justEmergedGraceTimer -= std::min(uiDiff, m_justEmergedGraceTimer); } else { - // Change Target - if (m_uiChangeTargetTimer < uiDiff) + // Resume combat + if (m_uiSubmergeTimer < uiDiff) { - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) + m_creature->SetVisibility(VISIBILITY_ON); + m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); + + // Teleport to the trigger in order to get a new location + if (Creature* pTrigger = m_creature->GetMap()->GetCreature(m_ouroTriggerGuid)) + m_creature->NearTeleportTo(pTrigger->GetPositionX(), pTrigger->GetPositionY(), pTrigger->GetPositionZ(), 0); + + if (DoCastSpellIfCan(m_creature, SPELL_BIRTH) == CAST_OK) { - m_creature->GetMap()->CreatureRelocation(m_creature, pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), 0.0f); - m_creature->MonsterMove(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ()); - } + //DoCastSpellIfCan(m_creature, SPELL_SUMMON_SCARABS, CAST_TRIGGERED); - m_uiChangeTargetTimer = urand(10000, 20000); - } - else - m_uiChangeTargetTimer -= uiDiff; + m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_VISUAL); + m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - // Back - if (m_uiBackTimer < uiDiff) - { - m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - m_creature->setFaction(14); + std::list lGroundRuptureTargets; + ThreatList const& lThreat = m_creature->getThreatManager().getThreatList(); + for (ThreatList::const_iterator i = lThreat.begin(); i != lThreat.end(); ++i) + { + Unit* pUnit = m_creature->GetMap()->GetUnit((*i)->getUnitGuid()); + if (pUnit && pUnit->GetDistance2d(m_creature) < 20.0f) + lGroundRuptureTargets.push_back(pUnit); + } + for (auto &target : lGroundRuptureTargets) + m_creature->CastSpell(target, SPELL_GROUND_RUPTURE, true); - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_GROUND_RUPTURE) == CAST_OK) - { - m_bSubmerged = false; - m_uiSubmergeTimer = urand(60000, 120000); + m_bSubmerged = false; + m_SummonBase = true; + m_uiSubmergeTimer = SUBMERGE_TIMER; + m_uiSubmergeInvisTimer = SUBMERGE_ANIMATION_INVIS; + + DespawnCreatures(false); + + // Ouro should despawn instant on reset, not after going to his spawn point + m_creature->SetHomePosition( + m_creature->GetPositionX(), + m_creature->GetPositionY(), + m_creature->GetPositionZ(), + m_creature->GetOrientation()); } } else - m_uiBackTimer -= uiDiff; + { + if (m_creature->GetVisibility() == VISIBILITY_ON) + { + if (m_uiSubmergeInvisTimer < uiDiff) + { + m_creature->SetVisibility(VISIBILITY_OFF); + } + else + { + m_uiSubmergeInvisTimer -= uiDiff; + } + } + + m_uiSubmergeTimer -= uiDiff; + } } } }; @@ -177,11 +443,219 @@ CreatureAI* GetAI_boss_ouro(Creature* pCreature) return new boss_ouroAI(pCreature); } +struct npc_ouro_spawnerAI : public Scripted_NoMovementAI +{ + npc_ouro_spawnerAI(Creature* pCreature) : Scripted_NoMovementAI(pCreature) {Reset();} + + bool m_bHasSummoned; + + void Reset() + { + m_bHasSummoned = false; + + DoCastSpellIfCan(m_creature, SPELL_DIRTMOUND_PASSIVE); + } + + void MoveInLineOfSight(Unit* pWho) override + { + // Spawn Ouro on LoS check + if (!m_bHasSummoned && pWho->GetTypeId() == TYPEID_PLAYER && !((Player*)pWho)->isGameMaster() && m_creature->IsWithinDistInMap(pWho, 25.0f)) + { + if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_OURO) == CAST_OK) + { + m_bHasSummoned = true; + } + } + + ScriptedAI::MoveInLineOfSight(pWho); + } + + void JustSummoned(Creature* pSummoned) + { + // Despawn when Ouro is spawned + if (pSummoned->GetEntry() == NPC_OURO) + { + pSummoned->CastSpell(pSummoned, SPELL_BIRTH, false); + pSummoned->SetInCombatWithZone(); + m_creature->ForcedDespawn(); + } + } + + void UpdateAI(const uint32 /*uiDiff*/) { } +}; + +CreatureAI* GetAI_npc_ouro_spawner(Creature* pCreature) +{ + return new npc_ouro_spawnerAI(pCreature); +} + +struct npc_dirt_moundAI : public ScriptedAI +{ + npc_dirt_moundAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();} + + uint32 m_uiChangeTargetTimer; + uint32 m_uiDespawnTimer; + ObjectGuid m_TargetGUID; + ObjectGuid m_CurrentTargetGUID; + + void JustRespawned() override + { + m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE); + ScriptedAI::JustRespawned(); + } + + void Reset() + { + m_uiDespawnTimer = 30000; + m_TargetGUID.Clear(); + m_CurrentTargetGUID.Clear(); + + DoCastSpellIfCan(m_creature, SPELL_DIRTMOUND_PASSIVE); + } + + void MoveInLineOfSight(Unit *who) + { + if (!m_TargetGUID && who->GetTypeId() == TYPEID_PLAYER) + { + m_TargetGUID = who->GetGUID(); + } + } + + void UpdateAI(const uint32 uiDiff) + { + Unit *pTarget = m_creature->GetMap()->GetUnit(m_CurrentTargetGUID); + const bool bForceChangeTarget = !pTarget || pTarget->isDead() + || pTarget->IsImmuneToDamage(SPELL_SCHOOL_MASK_NATURE); + + if (bForceChangeTarget || m_uiChangeTargetTimer < uiDiff) + { + m_CurrentTargetGUID.Clear(); + + if (Unit* pTarget = m_creature->GetMap()->GetUnit(m_TargetGUID)) + { + m_creature->GetMotionMaster()->MoveFollow(pTarget, 0.0f, 0.0f); + m_CurrentTargetGUID = m_TargetGUID; + m_TargetGUID.Clear(); + } + else + { + m_creature->GetMotionMaster()->MoveRandom(); + } + m_uiChangeTargetTimer = urand(0, 10000); + } + else + m_uiChangeTargetTimer -= uiDiff; + + if (m_uiDespawnTimer < uiDiff) + { + m_creature->CastSpell(m_creature, SPELL_SUMMON_SCARABS, true); + m_creature->ForcedDespawn(); + } + else + { + m_uiDespawnTimer -= uiDiff; + } + } +}; + +CreatureAI* GetAI_npc_dirt_mound(Creature* pCreature) +{ + return new npc_dirt_moundAI(pCreature); +} + +struct npc_ouro_scarabAI : public ScriptedAI +{ + npc_ouro_scarabAI(Creature* pCreature) : ScriptedAI(pCreature) { Reset(); } + + uint32 m_uiDespawnTimer; + + void Reset() + { + m_uiDespawnTimer = 45000; + } + + void MoveInLineOfSight(Unit *who) + { + if (who->GetTypeId() == TYPEID_PLAYER && !m_creature->getVictim() && !urand(0, 5)) + { + AttackStart(who); + } + } + + void UpdateAI(const uint32 uiDiff) + { + if (m_creature->getVictim()) + DoMeleeAttackIfReady(); + + if (m_uiDespawnTimer < uiDiff) + m_creature->ForcedDespawn(); + else + m_uiDespawnTimer -= uiDiff; + } +}; + +CreatureAI* GetAI_npc_ouro_scarab(Creature* pCreature) +{ + return new npc_ouro_scarabAI(pCreature); +} + +struct go_sandworm_baseAI: public GameObjectAI +{ + go_sandworm_baseAI(GameObject* pGo) : GameObjectAI(pGo), m_bActive(true) {} + + bool m_bActive; + + bool OnUse(Unit* pUser) + { + WorldLocation loc; + pUser->GetObjectScale(); + pUser->GetPosition(loc); + + if (m_bActive) + { + m_bActive = false; + me->SendGameObjectCustomAnim(me->GetObjectGuid()); + } + else + { + me->SetRespawnTime(0); + me->Delete(); + } + return false; + } +}; + +GameObjectAI* GetAIgo_sandworm_base(GameObject *pGo) +{ + return new go_sandworm_baseAI(pGo); +} + void AddSC_boss_ouro() { - Script* newscript; - newscript = new Script; - newscript->Name = "boss_ouro"; - newscript->GetAI = &GetAI_boss_ouro; - newscript->RegisterSelf(); + Script* pNewScript; + + pNewScript = new Script; + pNewScript->Name = "boss_ouro"; + pNewScript->GetAI = &GetAI_boss_ouro; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "npc_ouro_spawner"; + pNewScript->GetAI = &GetAI_npc_ouro_spawner; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "npc_dirt_mound"; + pNewScript->GetAI = &GetAI_npc_dirt_mound; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "npc_ouro_scarab"; + pNewScript->GetAI = &GetAI_npc_ouro_scarab; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "go_sandworm_base"; + pNewScript->GOGetAI = &GetAIgo_sandworm_base; + pNewScript->RegisterSelf(); } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_sartura.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_sartura.cpp index 7fc187eff..22a0c86ab 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_sartura.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_sartura.cpp @@ -21,6 +21,12 @@ SDComment: SDCategory: Temple of Ahn'Qiraj EndScriptData */ +/* + * Notes: + * Whirlwind - Sartura does a physical AoE that does 3k+ damage to everyone within 10 yards of her. + * During this time she is immune to stuns and taunt. She tends to use this ability after a stun fades. + */ + #include "scriptPCH.h" #include "temple_of_ahnqiraj.h" @@ -37,12 +43,15 @@ enum SPELL_ENRAGE = 26527, SPELL_ENRAGEHARD = 27680, + TAUNT_IMMUNE = 26602, + EMOTE_ENRAGE = -1000003, EMOTE_ENRAGEHARD = -1000004, // Royal Guard SPELL_KNOCKBACK = 19813, - SPELL_GUARD_WHIRLWIND = 26038, + SPELL_GUARD_WHIRLWIND = 26038, + }; // ******************** @@ -53,11 +62,11 @@ struct boss_sarturaAI : public ScriptedAI { boss_sarturaAI(Creature* pCreature) : ScriptedAI(pCreature) { - m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData(); + m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData(); Reset(); } - instance_temple_of_ahnqiraj* m_pInstance; + instance_temple_of_ahnqiraj* m_pInstance; uint32 m_uiCleaveTimer; uint32 m_uiWhirlWindTimer; @@ -72,7 +81,7 @@ struct boss_sarturaAI : public ScriptedAI void Reset() override { m_uiCleaveTimer = 4000; - m_uiWhirlWindTimer = urand(18000, 20000);; + m_uiWhirlWindTimer = urand(8000, 12000);; m_uiWhirlWindEndTimer = 0; m_uiAggroResetTimer = urand(5000, 7500); @@ -93,11 +102,11 @@ struct boss_sarturaAI : public ScriptedAI ScriptedAI::MoveInLineOfSight(pWho); } - void EnterEvadeMode() override - { - LeashEncounter(); - ScriptedAI::EnterEvadeMode(); - } + void EnterEvadeMode() override + { + LeashEncounter(); + ScriptedAI::EnterEvadeMode(); + } void Aggro(Unit* /*pWho*/) override { @@ -131,25 +140,25 @@ struct boss_sarturaAI : public ScriptedAI { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { - if (m_creature->IsWithinDist(pTarget, VISIBLE_RANGE)) - { - DoResetThreat(); - m_creature->getThreatManager().addThreatDirectly(pTarget, urand(1000, 2000)); - } + if (m_creature->IsWithinDist(pTarget, VISIBLE_RANGE)) + { + DoResetThreat(); + m_creature->getThreatManager().addThreatDirectly(pTarget, urand(1000, 2000)); + } } } void LeashEncounter() { - GuidList m_lRoyalGuardsGuid; - m_pInstance->GetRoyalGuardGUIDList(m_lRoyalGuardsGuid); - for (GuidList::const_iterator itr = m_lRoyalGuardsGuid.begin(); itr != m_lRoyalGuardsGuid.end(); ++itr) - { - if (Creature* pRoyalGuard = m_creature->GetMap()->GetCreature(*itr)) - { - if (pRoyalGuard->isDead()) pRoyalGuard->Respawn(); else pRoyalGuard->AI()->EnterEvadeMode(); - } - } + GuidList m_lRoyalGuardsGuid; + m_pInstance->GetRoyalGuardGUIDList(m_lRoyalGuardsGuid); + for (GuidList::const_iterator itr = m_lRoyalGuardsGuid.begin(); itr != m_lRoyalGuardsGuid.end(); ++itr) + { + if (Creature* pRoyalGuard = m_creature->GetMap()->GetCreature(*itr)) + { + if (pRoyalGuard->isDead()) pRoyalGuard->Respawn(); else pRoyalGuard->AI()->EnterEvadeMode(); + } + } } void UpdateAI(const uint32 uiDiff) override @@ -172,11 +181,12 @@ struct boss_sarturaAI : public ScriptedAI if (m_uiWhirlWindEndTimer <= uiDiff) { m_uiWhirlWindEndTimer = 0; - m_uiWhirlWindTimer = urand(8000, 10000); + m_uiWhirlWindTimer = urand(5000, 10000); m_uiAggroResetTimer = urand(3000, 7000); - // Remove the negative haste modifier from Whirlwind to restore Sartura's auto attack - m_creature->ApplyAttackTimePercentMod(BASE_ATTACK, 0, true); - m_creature->setAttackTimer(BASE_ATTACK, 100); + // Remove the negative haste modifier from Whirlwind to restore Sartura's auto attack + m_creature->ApplyAttackTimePercentMod(BASE_ATTACK, 0, true); + m_creature->setAttackTimer(BASE_ATTACK, 100); + m_creature->RemoveAurasByCasterSpell(TAUNT_IMMUNE, m_creature->GetObjectGuid()); } else m_uiWhirlWindEndTimer -= uiDiff; @@ -189,6 +199,7 @@ struct boss_sarturaAI : public ScriptedAI { if (DoCastSpellIfCan(m_creature, SPELL_WHIRLWIND) == CAST_OK) { + m_creature->CastSpell(m_creature, TAUNT_IMMUNE, true); AssignRandomThreat(); m_uiWhirlWindEndTimer = 15000; m_uiAggroResetTimer = urand(1000, 2000); @@ -217,9 +228,8 @@ struct boss_sarturaAI : public ScriptedAI } - // If she is <25% enrage - if (!m_bIsEnraged && m_creature->GetHealthPercent() <= 25.0f) + if (!m_bIsEnraged && m_creature->GetHealthPercent() <= 20.0f) { if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE, m_uiWhirlWindEndTimer ? CAST_TRIGGERED : 0) == CAST_OK) { @@ -250,11 +260,11 @@ struct boss_sarturaAI : public ScriptedAI if (m_uiEvadeCheckTimer < uiDiff) { m_uiEvadeCheckTimer = 2500; - if (m_creature->GetPositionY() > 1780) - { - EnterEvadeMode(); - LeashEncounter(); - } + if (m_creature->GetPositionY() > 1780) + { + EnterEvadeMode(); + LeashEncounter(); + } } else m_uiEvadeCheckTimer -= uiDiff; @@ -268,12 +278,12 @@ struct boss_sarturaAI : public ScriptedAI struct mob_sartura_royal_guardAI : public ScriptedAI { mob_sartura_royal_guardAI(Creature* pCreature) : ScriptedAI(pCreature) - { - m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData(); - Reset(); - } + { + m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData(); + Reset(); + } - instance_temple_of_ahnqiraj* m_pInstance; + instance_temple_of_ahnqiraj* m_pInstance; uint32 m_uiKnockbackTimer; uint32 m_uiWhirlWindTimer; @@ -306,23 +316,23 @@ struct mob_sartura_royal_guardAI : public ScriptedAI void LeashEncounter() { - if (Creature* pSartura = m_pInstance->GetSingleCreatureFromStorage(NPC_BATTLEGUARD_SARTURA)) - { - if (pSartura->isAlive()) - { - pSartura->AI()->EnterEvadeMode(); + if (Creature* pSartura = m_pInstance->GetSingleCreatureFromStorage(NPC_BATTLEGUARD_SARTURA)) + { + if (pSartura->isAlive()) + { + pSartura->AI()->EnterEvadeMode(); - GuidList m_lRoyalGuardsGuid; - m_pInstance->GetRoyalGuardGUIDList(m_lRoyalGuardsGuid); - for (GuidList::const_iterator itr = m_lRoyalGuardsGuid.begin(); itr != m_lRoyalGuardsGuid.end(); ++itr) - { - if (Creature* pRoyalGuard = m_creature->GetMap()->GetCreature(*itr)) - { - if (pRoyalGuard->isDead()) pRoyalGuard->Respawn(); else pRoyalGuard->AI()->EnterEvadeMode(); - } - } - } - } + GuidList m_lRoyalGuardsGuid; + m_pInstance->GetRoyalGuardGUIDList(m_lRoyalGuardsGuid); + for (GuidList::const_iterator itr = m_lRoyalGuardsGuid.begin(); itr != m_lRoyalGuardsGuid.end(); ++itr) + { + if (Creature* pRoyalGuard = m_creature->GetMap()->GetCreature(*itr)) + { + if (pRoyalGuard->isDead()) pRoyalGuard->Respawn(); else pRoyalGuard->AI()->EnterEvadeMode(); + } + } + } + } } void UpdateAI(const uint32 uiDiff) override @@ -357,10 +367,10 @@ struct mob_sartura_royal_guardAI : public ScriptedAI // Enter Whirlwind Phase if (m_uiWhirlWindTimer < uiDiff) { - if (DoCastSpellIfCan(m_creature, SPELL_GUARD_WHIRLWIND) == CAST_OK) + if (DoCastSpellIfCan(m_creature, SPELL_GUARD_WHIRLWIND) == CAST_OK) { AssignRandomThreat(); - m_uiWhirlWindEndTimer = 8000; + m_uiWhirlWindEndTimer = 8000; m_uiAggroResetTimer = urand(1000, 2000); } } @@ -391,14 +401,14 @@ struct mob_sartura_royal_guardAI : public ScriptedAI DoMeleeAttackIfReady(); // Leash check - if (m_uiEvadeCheckTimer < uiDiff) - { - m_uiEvadeCheckTimer = 2500; - if (m_creature->GetPositionY() > 1780) - LeashEncounter(); - } - else - m_uiEvadeCheckTimer -= uiDiff; + if (m_uiEvadeCheckTimer < uiDiff) + { + m_uiEvadeCheckTimer = 2500; + if (m_creature->GetPositionY() > 1780) + LeashEncounter(); + } + else + m_uiEvadeCheckTimer -= uiDiff; } }; @@ -408,12 +418,12 @@ struct mob_sartura_royal_guardAI : public ScriptedAI enum { - SPELL_IMPALE = 26025, - SPELL_FRENZY = 8599, + SPELL_IMPALE = 26025, + SPELL_FRENZY = 8599, - EMOTE_EMIT = -1531100, - EMOTE_FRENZY = -1000002, - SOUND_CHARGE = 3330, + EMOTE_EMIT = -1531100, + EMOTE_FRENZY = -1000002, + SOUND_CHARGE = 3330, }; // array of GUIDs permitted to emote on aggro @@ -421,153 +431,153 @@ static const uint32 aEmoteGUIDs[8] = { 87595, 87671, 87610, 87611, 87618, 87627, struct mob_vekniss_guardianAI : public ScriptedAI { - mob_vekniss_guardianAI(Creature* pCreature) : ScriptedAI(pCreature) - { - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); - m_uiImpaleTimer = 0; - Reset(); - } + mob_vekniss_guardianAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + m_uiImpaleTimer = 0; + Reset(); + } - ScriptedInstance* m_pInstance; + ScriptedInstance* m_pInstance; - uint32 m_uiImpaleTimer; - uint32 m_uiEmoteTimer; - uint32 m_uiEvadeCheckTimer; + uint32 m_uiImpaleTimer; + uint32 m_uiEmoteTimer; + uint32 m_uiEvadeCheckTimer; - bool m_bCalledForHelp; - bool m_bFrenzied; - bool m_bIsAlone; + bool m_bCalledForHelp; + bool m_bFrenzied; + bool m_bIsAlone; - void Reset() override - { - m_bCalledForHelp = false; - m_bFrenzied = false; - m_uiEmoteTimer = 0; - m_uiEvadeCheckTimer = 2500; - } + void Reset() override + { + m_bCalledForHelp = false; + m_bFrenzied = false; + m_uiEmoteTimer = 0; + m_uiEvadeCheckTimer = 2500; + } - void Aggro(Unit* /*pWho*/) override - { - for (uint8 i = 0; i < 8; ++i) - { - if (m_creature->GetGUIDLow() == aEmoteGUIDs[i]) - { - m_uiEmoteTimer = 2500; - break; - } - } - } + void Aggro(Unit* /*pWho*/) override + { + for (uint8 i = 0; i < 8; ++i) + { + if (m_creature->GetGUIDLow() == aEmoteGUIDs[i]) + { + m_uiEmoteTimer = 2500; + break; + } + } + } - void MoveInLineOfSight(Unit* pWho) override - { - // Increased aggro radius - if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 50.0f) && m_creature->IsWithinLOSInMap(pWho) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) - { - AttackStart(pWho); - } - ScriptedAI::MoveInLineOfSight(pWho); - } + void MoveInLineOfSight(Unit* pWho) override + { + // Increased aggro radius + if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 50.0f) && m_creature->IsWithinLOSInMap(pWho) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) + { + AttackStart(pWho); + } + ScriptedAI::MoveInLineOfSight(pWho); + } - void EnterEvadeMode() override - { - m_creature->UpdateSpeed(MOVE_RUN, false); - ScriptedAI::EnterEvadeMode(); - } + void EnterEvadeMode() override + { + m_creature->UpdateSpeed(MOVE_RUN, false); + ScriptedAI::EnterEvadeMode(); + } - void ImpaleAssist(Unit* pWho) - { - m_creature->UpdateSpeed(MOVE_RUN, true, 2.5); - m_creature->GetMotionMaster()->MovePoint(1, pWho->GetPositionX(), pWho->GetPositionY(), pWho->GetPositionZ()); - m_creature->PlayDistanceSound(SOUND_CHARGE); - } + void ImpaleAssist(Unit* pWho) + { + m_creature->UpdateSpeed(MOVE_RUN, true, 2.5); + m_creature->GetMotionMaster()->MovePoint(1, pWho->GetPositionX(), pWho->GetPositionY(), pWho->GetPositionZ()); + m_creature->PlayDistanceSound(SOUND_CHARGE); + } - void MovementInform(uint32 uiMotionType, uint32 /*uiPointId*/) override - { - if (uiMotionType != POINT_MOTION_TYPE) - return; + void MovementInform(uint32 uiMotionType, uint32 /*uiPointId*/) override + { + if (uiMotionType != POINT_MOTION_TYPE) + return; - DoCastSpellIfCan(m_creature, SPELL_IMPALE); - m_creature->UpdateSpeed(MOVE_RUN, false); - DoStartMovement(m_creature->getVictim()); - } + DoCastSpellIfCan(m_creature, SPELL_IMPALE); + m_creature->UpdateSpeed(MOVE_RUN, false); + DoStartMovement(m_creature->getVictim()); + } - void DamageTaken(Unit* /*pDoneBy*/, uint32& uiDamage) override - { - if (m_creature->GetHealthPercent() < 25.0f && !m_bCalledForHelp) - { - m_bCalledForHelp = true; - m_bIsAlone = true; - std::list lAssistList; - GetCreatureListWithEntryInGrid(lAssistList, m_creature, 15233, 45.0f); + void DamageTaken(Unit* /*pDoneBy*/, uint32& uiDamage) override + { + if (m_creature->GetHealthPercent() < 25.0f && !m_bCalledForHelp) + { + m_bCalledForHelp = true; + m_bIsAlone = true; + std::list lAssistList; + GetCreatureListWithEntryInGrid(lAssistList, m_creature, 15233, 45.0f); - for (std::list::iterator itr = lAssistList.begin(); itr != lAssistList.end(); ++itr) - { - if ((*itr)->GetObjectGuid() == m_creature->GetObjectGuid()) - continue; + for (std::list::iterator itr = lAssistList.begin(); itr != lAssistList.end(); ++itr) + { + if ((*itr)->GetObjectGuid() == m_creature->GetObjectGuid()) + continue; - if ((*itr)->isAlive() && m_creature->IsWithinLOSInMap((*itr))) - { - if (m_bIsAlone) - m_bIsAlone = false; - if (mob_vekniss_guardianAI* pVeknissAI = dynamic_cast((*itr)->AI())) - pVeknissAI->ImpaleAssist(m_creature); - } - } - if (m_bIsAlone) - DoCastSpellIfCan(m_creature, SPELL_IMPALE); - } - } + if ((*itr)->isAlive() && m_creature->IsWithinLOSInMap((*itr))) + { + if (m_bIsAlone) + m_bIsAlone = false; + if (mob_vekniss_guardianAI* pVeknissAI = dynamic_cast((*itr)->AI())) + pVeknissAI->ImpaleAssist(m_creature); + } + } + if (m_bIsAlone) + DoCastSpellIfCan(m_creature, SPELL_IMPALE); + } + } - void UpdateAI(const uint32 uiDiff) override - { - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; + void UpdateAI(const uint32 uiDiff) override + { + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; - if (m_uiEvadeCheckTimer < uiDiff) - { - m_uiEvadeCheckTimer = 2500; - if (m_creature->IsInEvadeMode()) - { - if (Unit* pTarget = m_creature->getVictim()) - m_creature->Relocate(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ()); - } - } - else - m_uiEvadeCheckTimer -= uiDiff; + if (m_uiEvadeCheckTimer < uiDiff) + { + m_uiEvadeCheckTimer = 2500; + if (m_creature->IsInEvadeMode()) + { + if (Unit* pTarget = m_creature->getVictim()) + m_creature->Relocate(pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ()); + } + } + else + m_uiEvadeCheckTimer -= uiDiff; - if (m_uiEmoteTimer) - { - if (m_uiEmoteTimer < uiDiff) - { - DoScriptText(EMOTE_EMIT, m_creature); - m_uiEmoteTimer = 0; - } - else - m_uiEmoteTimer -= uiDiff; - } + if (m_uiEmoteTimer) + { + if (m_uiEmoteTimer < uiDiff) + { + DoScriptText(EMOTE_EMIT, m_creature); + m_uiEmoteTimer = 0; + } + else + m_uiEmoteTimer -= uiDiff; + } - if (m_creature->GetHealthPercent() < 30.0f && !m_bFrenzied) - { - if (DoCastSpellIfCan(m_creature, SPELL_FRENZY) == CAST_OK) - { - DoScriptText(EMOTE_FRENZY, m_creature); - m_bFrenzied = true; - } - } + if (m_creature->GetHealthPercent() < 30.0f && !m_bFrenzied) + { + if (DoCastSpellIfCan(m_creature, SPELL_FRENZY) == CAST_OK) + { + DoScriptText(EMOTE_FRENZY, m_creature); + m_bFrenzied = true; + } + } - if (m_uiImpaleTimer) // stop chasing momentarily after casting impale to prevent z-axis problems - { - if (m_uiImpaleTimer < uiDiff) - { - - m_uiImpaleTimer = 0; - } - else - m_uiImpaleTimer -= uiDiff; - } + if (m_uiImpaleTimer) // stop chasing momentarily after casting impale to prevent z-axis problems + { + if (m_uiImpaleTimer < uiDiff) + { + + m_uiImpaleTimer = 0; + } + else + m_uiImpaleTimer -= uiDiff; + } - DoMeleeAttackIfReady(); - } + DoMeleeAttackIfReady(); + } }; @@ -583,7 +593,7 @@ CreatureAI* GetAI_mob_sartura_royal_guard(Creature* pCreature) CreatureAI* GetAI_mob_vekniss_guardian(Creature* pCreature) { - return new mob_vekniss_guardianAI(pCreature); + return new mob_vekniss_guardianAI(pCreature); } void AddSC_boss_sartura() @@ -598,10 +608,10 @@ void AddSC_boss_sartura() pNewScript = new Script; pNewScript->Name = "mob_sartura_royal_guard"; pNewScript->GetAI = &GetAI_mob_sartura_royal_guard; - pNewScript->RegisterSelf(); + pNewScript->RegisterSelf(); - pNewScript = new Script; - pNewScript->Name = "mob_vekniss_guardian"; - pNewScript->GetAI = &GetAI_mob_vekniss_guardian; - pNewScript->RegisterSelf(); + pNewScript = new Script; + pNewScript->Name = "mob_vekniss_guardian"; + pNewScript->GetAI = &GetAI_mob_vekniss_guardian; + pNewScript->RegisterSelf(); } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp index 863b5c9b3..bfbb12ce8 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp @@ -1,297 +1,310 @@ -/* ScriptData -SDName: Boss_Skeram -SDCategory: Temple of Ahn'Qiraj -EndScriptData */ - -#include "scriptPCH.h" -#include "temple_of_ahnqiraj.h" - -#define SAY_AGGRO_0 -1531000 -#define SAY_AGGRO_1 -1531001 -#define SAY_AGGRO_2 -1531002 -#define SAY_SLAY_0 -1531003 -#define SAY_SLAY_1 -1531004 -#define SAY_SLAY_2 -1531005 -#define SAY_SPLIT -1531006 -#define SAY_DEATH -1531007 - -#define SPELL_ARCANE_EXPLOSION 26192 -#define SPELL_EARTH_SHOCK 26194 - -#define SPELL_TRUE_FULFILLMENT 785 -#define FULFILLMENT_RANGE 90.0f -#define SPELL_TF_HASTE 2313 -#define SPELL_TF_MOD_HEAL 26525 -#define SPELL_TF_IMMUNITY 26526 -#define SPELL_TF_CANCEL 26589 - -#define SPELL_BLINK_0 4801 -#define SPELL_BLINK_1 8195 -#define SPELL_BLINK_2 20449 - -#define SPELL_SUMMON_IMAGES 747 - -struct boss_skeramAI : public ScriptedAI -{ - boss_skeramAI(Creature* pCreature) : ScriptedAI(pCreature) - { - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); - IsImage = false; - Reset(); - } - - ScriptedInstance* m_pInstance; - - uint32 ArcaneExplosion_Timer; - uint32 EarthShock_Timer; - uint32 FullFillment_Timer; - uint32 Blink_Timer; - - float NextSplitPercent; - - Creature *ImageA, *ImageB; - ObjectGuid ControlledPlayerGUID; - - bool IsImage; - - void Reset() - { - ArcaneExplosion_Timer = urand(6000, 8000); - EarthShock_Timer = 100; - FullFillment_Timer = urand(10000, 15000); - Blink_Timer = urand(15000, 20000); - - NextSplitPercent = 75.0f; - - m_creature->SetVisibility(VISIBILITY_ON); - - ImageA = nullptr; - ImageA = nullptr; - ControlledPlayerGUID.Clear(); - } - - void CancelFulfillment() - { - if (Player* FulfilledPlayer = m_creature->GetMap()->GetPlayer(ControlledPlayerGUID)) - { - FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TRUE_FULFILLMENT); - FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_HASTE); - FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_MOD_HEAL); - FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_IMMUNITY); - } - } - - void KilledUnit(Unit* victim) - { - switch (urand(0,8)) - { - case 0: DoScriptText(SAY_SLAY_0, m_creature); break; - case 1: DoScriptText(SAY_SLAY_1, m_creature); break; - case 2: DoScriptText(SAY_SLAY_2, m_creature); break; - } - } - - void JustDied(Unit* Killer) - { - if (IsImage) - { - CancelFulfillment(); - m_creature->ForcedDespawn(); - return; - } - // Leave up to 20s of instant casts as reward for vaniquishing the True Prophet - DoScriptText(SAY_DEATH, m_creature); - m_creature->SetRespawnDelay(7 * DAY); - - if (m_pInstance) - m_pInstance->SetData(TYPE_SKERAM, DONE); - } - - void Aggro(Unit *who) - { - if (m_pInstance && m_pInstance->GetData(TYPE_SKERAM) == IN_PROGRESS) - return; - - switch (urand(0,2)) - { - case 0: DoScriptText(SAY_AGGRO_0, m_creature); break; - case 1: DoScriptText(SAY_AGGRO_1, m_creature); break; - case 2: DoScriptText(SAY_AGGRO_2, m_creature); break; - } - - if (m_pInstance) - m_pInstance->SetData(TYPE_SKERAM, IN_PROGRESS); - } - - void JustReachedHome() - { - CancelFulfillment(); - - if (IsImage) - m_creature->DoKillUnit(); - - if (m_pInstance) - m_pInstance->SetData(TYPE_SKERAM, FAIL); - } - - void UpdateAI(const uint32 diff) - { - // Despawn Images instantly if the True Prophet died - if (IsImage && m_pInstance && m_pInstance->GetData(TYPE_SKERAM) == DONE) - m_creature->DoKillUnit(); - - //Return since we have no target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; - - if (ArcaneExplosion_Timer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ARCANE_EXPLOSION) == CAST_OK) - ArcaneExplosion_Timer = urand(6000, 14000); - } - else ArcaneExplosion_Timer -= diff; - - //If we are within range, melee the target - if (m_creature->IsWithinMeleeRange(m_creature->getVictim())) - DoMeleeAttackIfReady(); - else - // Target not in melee range. Spam Earthshock - { - if (EarthShock_Timer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_EARTH_SHOCK) == CAST_OK) - EarthShock_Timer = 1000; - } - else - EarthShock_Timer -= diff; - } - - if (FullFillment_Timer < diff) - { - // Get random target excluding highest threat who is not MCed - if (Unit* MCTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) - { - if (DoCastSpellIfCan(MCTarget, SPELL_TRUE_FULFILLMENT, CAST_AURA_NOT_PRESENT) == CAST_OK) - { - // Cancel buffs on previous victim - CancelFulfillment(); - - m_creature->CastSpell(MCTarget, SPELL_TF_HASTE, true); - m_creature->CastSpell(MCTarget, SPELL_TF_MOD_HEAL, true); - m_creature->CastSpell(MCTarget, SPELL_TF_IMMUNITY, true); - - FullFillment_Timer = urand(20500, 25000); - ControlledPlayerGUID = MCTarget->GetObjectGuid(); - } - } - } - else FullFillment_Timer -= diff; - - if (Blink_Timer < diff) - { - CastBlink(m_creature); - Blink_Timer = urand(10000, 18000); - } - else - Blink_Timer -= diff; - - // Summon 2 Images and teleport for every 25% hp lost - if (!IsImage && m_creature->GetHealthPercent() < NextSplitPercent) - if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_IMAGES) == CAST_OK) - { - if (NextSplitPercent < 26.0f) - DoScriptText(SAY_SPLIT, m_creature); - - NextSplitPercent -= 25.0f; - } - - } - - void JustSummoned(Creature* skeramImage) - { - if (m_creature->GetEntry() != skeramImage->GetEntry()) - return; - - if (boss_skeramAI* imageAI = dynamic_cast(skeramImage->AI())) - imageAI->IsImage = true; - - float skeramPercent = m_creature->GetHealthPercent(); - - // Set health to look like the True Prophet. Will have 12.5%, 25%, finally 50% of max Skeram HP. - skeramImage->SetMaxHealth(m_creature->GetMaxHealth() * (12.5f / skeramPercent) * (100 / (int)skeramPercent)); - skeramImage->SetHealthPercent(skeramPercent); - skeramImage->SetInCombatWithZone(); - skeramImage->SetVisibility(VISIBILITY_OFF); - - if (!ImageA) - ImageA = skeramImage; - else - { - ImageB = skeramImage; - UnisonBlink(); - } - - } - - void UnisonBlink() - // At least two images present. Blink self and newest two images - { - uint32 mask = 0x7; - - // Get Skeram ready for blink - m_creature->RemoveAllAuras(); - ClearTargetIcon(); - m_creature->SetVisibility(VISIBILITY_OFF); - - CastBlink(ImageA, mask); - CastBlink(ImageB, mask); - CastBlink(m_creature, mask); - - ImageA = nullptr; - ImageB = nullptr; - } - - void CastBlink(Creature* caster) - // Teleport to any of three positions - { - uint32 mask = 0x7; - CastBlink(caster, mask); - } - - void CastBlink(Creature* caster, uint32& choiceMask) - // Teleport to a random position in mask - // Can teleport to any position if mask = 0x7 - { - uint32 position = urand(0,2); - - while (!(1 << position & choiceMask)) // Bogo select - position = urand(0, 2); - - choiceMask &= ~(1 << position); // Remove used position from mask - - DoStopAttack(); - - // Blink to one of the three platforms - switch (position) - { - case 0: caster->CastSpell(caster, SPELL_BLINK_0, true); break; - case 1: caster->CastSpell(caster, SPELL_BLINK_1, true); break; - case 2: caster->CastSpell(caster, SPELL_BLINK_2, true); break; - } - - DoResetThreat(); - caster->SetVisibility(VISIBILITY_ON); - } - -}; - -CreatureAI* GetAI_boss_skeram(Creature* pCreature) { return new boss_skeramAI(pCreature); } - -void AddSC_boss_skeram() -{ - Script *newscript; - newscript = new Script; - newscript->Name = "boss_skeram"; - newscript->GetAI = &GetAI_boss_skeram; - newscript->RegisterSelf(); -} +/* ScriptData +SDName: Boss_Skeram +SDCategory: Temple of Ahn'Qiraj +EndScriptData */ + +#include "scriptPCH.h" +#include "temple_of_ahnqiraj.h" + +#define SAY_AGGRO_1 -1531000 +#define SAY_AGGRO_2 -1531001 +#define SAY_AGGRO_3 -1531002 +#define SAY_SLAY_1 -1531003 +#define SAY_SLAY_2 -1531004 +#define SAY_SLAY_3 -1531005 +#define SAY_SPLIT -1531006 +#define SAY_DEATH -1531007 + +#define SPELL_ARCANE_EXPLOSION 26192 +#define SPELL_EARTH_SHOCK 26194 + +#define SPELL_TRUE_FULFILLMENT 785 +#define FULFILLMENT_RANGE 90.0f +#define SPELL_TF_HASTE 2313 +#define SPELL_TF_MOD_HEAL 26525 +#define SPELL_TF_IMMUNITY 26526 +#define SPELL_TF_CANCEL 26589 + +#define SPELL_BLINK_1 4801 +#define SPELL_BLINK_2 8195 +#define SPELL_BLINK_3 20449 + +#define SPELL_SUMMON_IMAGES 747 + +struct boss_skeramAI : public ScriptedAI +{ + boss_skeramAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + IsImage = false; + Reset(); + } + + ScriptedInstance* m_pInstance; + + uint32 ArcaneExplosion_Timer; + uint32 EarthShock_Timer; + uint32 FullFillment_Timer; + uint32 Blink_Timer; + + float NextSplitPercent; + + Creature *ImageA, *ImageB; + ObjectGuid ControlledPlayerGUID; + + bool IsImage; + + void Reset() + { + ArcaneExplosion_Timer = urand(6000, 8000); + EarthShock_Timer = 100; + FullFillment_Timer = urand(10000, 15000); + Blink_Timer = urand(15000, 20000); + + NextSplitPercent = 75.0f; + + m_creature->SetVisibility(VISIBILITY_ON); + + ImageA = nullptr; + ImageA = nullptr; + ControlledPlayerGUID.Clear(); + } + + void CancelFulfillment() + { + if (Player* FulfilledPlayer = m_creature->GetMap()->GetPlayer(ControlledPlayerGUID)) + { + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TRUE_FULFILLMENT); + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_HASTE); + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_MOD_HEAL); + FulfilledPlayer->RemoveAurasDueToSpellByCancel(SPELL_TF_IMMUNITY); + } + } + + void MoveInLineOfSight(Unit* pWho) override + { + // The bug trio have a larger than normal aggro radius + if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 28.0f, true) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) + { + AttackStart(pWho); + } + ScriptedAI::MoveInLineOfSight(pWho); + } + + void KilledUnit(Unit* victim) + { + switch (urand(0,8)) + { + case 0: DoScriptText(SAY_SLAY_1, m_creature); break; + case 1: DoScriptText(SAY_SLAY_2, m_creature); break; + case 2: DoScriptText(SAY_SLAY_3, m_creature); break; + } + } + + void JustDied(Unit* Killer) + { + if (IsImage) + { + CancelFulfillment(); + m_creature->ForcedDespawn(); + return; + } + // Leave up to 20s of instant casts as reward for vaniquishing the True Prophet + DoScriptText(SAY_DEATH, m_creature); + m_creature->SetRespawnDelay(7 * DAY); + + if (m_pInstance) + m_pInstance->SetData(TYPE_SKERAM, DONE); + } + + void Aggro(Unit *who) + { + if (IsImage) + return; + + if (m_pInstance && m_pInstance->GetData(TYPE_SKERAM) == IN_PROGRESS) + return; + + switch (urand(0,2)) + { + case 0: DoScriptText(SAY_AGGRO_1, m_creature); break; + case 1: DoScriptText(SAY_AGGRO_2, m_creature); break; + case 2: DoScriptText(SAY_AGGRO_3, m_creature); break; + } + + if (m_pInstance) + m_pInstance->SetData(TYPE_SKERAM, IN_PROGRESS); + } + + void JustReachedHome() + { + CancelFulfillment(); + + if (IsImage) + m_creature->DoKillUnit(); + + if (m_pInstance) + m_pInstance->SetData(TYPE_SKERAM, FAIL); + } + + void UpdateAI(const uint32 diff) + { + // Despawn Images instantly if the True Prophet died + if (IsImage && m_pInstance && m_pInstance->GetData(TYPE_SKERAM) == DONE) + m_creature->DoKillUnit(); + + //Return since we have no target + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; + + if (ArcaneExplosion_Timer < diff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ARCANE_EXPLOSION) == CAST_OK) + ArcaneExplosion_Timer = urand(6000, 14000); + } + else ArcaneExplosion_Timer -= diff; + + //If we are within range, melee the target + if (m_creature->IsWithinMeleeRange(m_creature->getVictim())) + DoMeleeAttackIfReady(); + else + // Target not in melee range. Spam Earthshock + { + if (EarthShock_Timer < diff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_EARTH_SHOCK) == CAST_OK) + EarthShock_Timer = 1000; + } + else + EarthShock_Timer -= diff; + } + + if (FullFillment_Timer < diff) + { + // Get random target excluding highest threat who is not MCed + if (Unit* MCTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) + { + if (DoCastSpellIfCan(MCTarget, SPELL_TRUE_FULFILLMENT, CAST_AURA_NOT_PRESENT) == CAST_OK) + { + // Cancel buffs on previous victim + CancelFulfillment(); + + m_creature->CastSpell(MCTarget, SPELL_TF_HASTE, true); + m_creature->CastSpell(MCTarget, SPELL_TF_MOD_HEAL, true); + m_creature->CastSpell(MCTarget, SPELL_TF_IMMUNITY, true); + + FullFillment_Timer = urand(20500, 25000); + ControlledPlayerGUID = MCTarget->GetObjectGuid(); + } + } + } + else FullFillment_Timer -= diff; + + if (Blink_Timer < diff) + { + CastBlink(m_creature); + Blink_Timer = urand(10000, 18000); + } + else + Blink_Timer -= diff; + + // Summon 2 Images and teleport for every 25% hp lost + if (!IsImage && m_creature->GetHealthPercent() < NextSplitPercent) + if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_IMAGES) == CAST_OK) + { + if (NextSplitPercent < 26.0f) + DoScriptText(SAY_SPLIT, m_creature); + + NextSplitPercent -= 25.0f; + } + + } + + void JustSummoned(Creature* skeramImage) + { + if (m_creature->GetEntry() != skeramImage->GetEntry()) + return; + + if (boss_skeramAI* imageAI = dynamic_cast(skeramImage->AI())) + imageAI->IsImage = true; + + float skeramPercent = m_creature->GetHealthPercent(); + + // Set health to look like the True Prophet. Will have 12.5%, 25%, finally 50% of max Skeram HP. + skeramImage->SetMaxHealth(m_creature->GetMaxHealth() * (12.5f / skeramPercent) * (100 / (int)skeramPercent)); + skeramImage->SetHealthPercent(skeramPercent); + skeramImage->SetInCombatWithZone(); + skeramImage->SetVisibility(VISIBILITY_OFF); + + if (!ImageA) + ImageA = skeramImage; + else + { + ImageB = skeramImage; + UnisonBlink(); + } + + } + + void UnisonBlink() + // At least two images present. Blink self and newest two images + { + uint32 mask = 0x7; + + // Get Skeram ready for blink + m_creature->RemoveAllAuras(); + ClearTargetIcon(); + m_creature->SetVisibility(VISIBILITY_OFF); + + CastBlink(ImageA, mask); + CastBlink(ImageB, mask); + CastBlink(m_creature, mask); + + ImageA = nullptr; + ImageB = nullptr; + } + + void CastBlink(Creature* caster) + // Teleport to any of three positions + { + uint32 mask = 0x7; + CastBlink(caster, mask); + } + + void CastBlink(Creature* caster, uint32& choiceMask) + // Teleport to a random position in mask + // Can teleport to any position if mask = 0x7 + { + uint32 position = urand(0,2); + + while (!(1 << position & choiceMask)) // Bogo select + position = urand(0, 2); + + choiceMask &= ~(1 << position); // Remove used position from mask + + DoStopAttack(); + + // Blink to one of the three platforms + switch (position) + { + case 0: caster->CastSpell(caster, SPELL_BLINK_1, true); break; + case 1: caster->CastSpell(caster, SPELL_BLINK_2, true); break; + case 2: caster->CastSpell(caster, SPELL_BLINK_3, true); break; + } + + DoResetThreat(); + caster->SetVisibility(VISIBILITY_ON); + } + +}; + +CreatureAI* GetAI_boss_skeram(Creature* pCreature) { return new boss_skeramAI(pCreature); } + +void AddSC_boss_skeram() +{ + Script *newscript; + newscript = new Script; + newscript->Name = "boss_skeram"; + newscript->GetAI = &GetAI_boss_skeram; + newscript->RegisterSelf(); +} diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_twinemperors.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_twinemperors.cpp index a6a6f6360..19051d55a 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_twinemperors.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_twinemperors.cpp @@ -19,338 +19,206 @@ /* ScriptData SDName: Boss_Twinemperors -SD%Complete: 95 -SDComment: +SD%Complete: +SDComment: uncertain which dialogue should be used on enrage SDCategory: Temple of Ahn'Qiraj +Rewrtten by Gemt EndScriptData */ #include "scriptPCH.h" #include "temple_of_ahnqiraj.h" -#define SPELL_HEAL_BROTHER 7393 -#define SPELL_TWIN_TELEPORT 800 // CTRA watches for this spell to start its teleport timer -#define SPELL_TWIN_TELEPORT_VISUAL 26638 // visual -#define SPELL_EXPLODEBUG 804 -#define SPELL_MUTATE_BUG 802 -#define SOUND_VN_DEATH 8660 //8660 - Death - Feel -#define SOUND_VN_AGGRO 8661 //8661 - Aggro - Let none -#define SOUND_VN_KILL 8662 //8661 - Kill - your fate -#define SOUND_VL_AGGRO 8657 //8657 - Aggro - To Late -#define SOUND_VL_KILL 8658 //8658 - Kill - You will not -#define SOUND_VL_DEATH 8659 //8659 - Death +enum eSpells { + SPELL_BERSERK = 26662, + + SPELL_TWIN_TELEPORT_SCRIPT = 799, // should have a script effect, dosent seem to have one. + SPELL_TWIN_TELEPORT_MSG = 800, // CTRA watches for this spell to start its teleport timer + SPELL_TWIN_TELEPORT_VISUAL = 26638, -#define PULL_RANGE 50 -#define ABUSE_BUG_RANGE 20 -#define SPELL_BERSERK 26662 -#define TELEPORTTIME 30000 + SPELL_HEAL_BROTHER = 7393, -#define SPELL_UPPERCUT 26007 -#define SPELL_UNBALANCING_STRIKE 26613 -#define VEKLOR_DIST 20 // VL will not come to melee when attacking + // Vek'nilash + SPELL_UPPERCUT = 26007, + SPELL_UNBALANCING_STRIKE = 26613, + SPELL_MUTATE_BUG = 802, + + // Vek'lor + SPELL_SHADOWBOLT = 26006, + SPELL_BLIZZARD = 26607, + SPELL_ARCANEBURST = 568, + SPELL_EXPLODEBUG = 804, -#define SPELL_SHADOWBOLT 26006 -#define SPELL_BLIZZARD 26607 -#define SPELL_ARCANEBURST 568 + BUG_TYPE_1 = 15316, + BUG_TYPE_2 = 15317, + + // bugs, seems to be defined in db? + // Virulet Posion + // Explode Bug + // Mute Bugs +}; + +enum eScriptTexts { + SAY_VEKLOR_AGGRO_1 = -1531019, // its too late to turn away + SAY_VEKLOR_AGGRO_2 = -1531020, // prepare to embrace oblivion + SAY_VEKLOR_AGGRO_3 = -1531021, // like a fly in a web + SAY_VEKLOR_AGGRO_4 = -1531022, // your brash arrogance + SAY_VEKLOR_SLAY = -1531023, // you will not escape death + SAY_VEKLOR_SPECIAL = -1531025, // to decorate our halls + + SAY_VEKNILASH_AGGRO_1 = -1531026, // ah, lambs to the slaughter + SAY_VEKNILASH_AGGRO_2 = -1531027, // let none survive + SAY_VEKNILASH_AGGRO_3 = -1531028, // join me brother, there is blood to be shed + SAY_VEKNILASH_AGGRO_4 = -1531029, // look brother, fresh bloood + SAY_VEKNILASH_SLAY = -1531030, // your fate is sealed + SAY_VEKNILASH_SPECIAL = -1531032, // Shall be your undoing (wipe?) + + //death is handled by instance_temple_of_ahnqiraj.cpp + //NOTE: according to wowwiki, the *_SLAY emotes are used during enrage, + // while "Oblivion will engulf you", "Like a fly in a web" and "your brash arrogance" + // is used on killing player. Not been able to confirm this. +}; + +// Shared constants +static constexpr uint32 PULL_RANGE = 50; +static constexpr uint32 ENRAGE_TIMER = 60 * 60000; + +static constexpr uint32 JUST_TELEPORTED_FREEZE = 2000; // Emperor is "frozen", aka not doing anything, for this long after TP +static constexpr uint32 AFTER_TELEPORT_THREAT = 3000; // Threat added to nearest player after TP. TODO: correct amount? + +static constexpr uint32 TELEPORTTIME_MIN_CD = 30000; // Shortest possible cooldown on teleport +static constexpr uint32 TELEPORTTIME_MAX_CD = 40000; // Longest possible cooldown on teleport + +static constexpr uint32 TRY_HEAL_FREQUENCY = 0; // How ofthen will the emperors TRY to heal eachother, 0 for every update +static constexpr uint32 SUCCESS_HEAL_FREQUENCY = 1500; // How ofthen will the emperors actually heal, when in range of each other +static constexpr float HEAL_BROTHER_AMOUNT = 30000.0f; // How much do they heal when in heal-range +static constexpr float HEAL_BROTHER_RANGE = 60.0f; + +static constexpr uint32 RESPAWN_BUG_FREQUENCY = 10000; // How often do we try to respawn a dead bug +static constexpr float RESPAWN_BUG_DISTANCE = 50.0f; // How far away do we look for dead bugs for respawning +static constexpr float BUG_SPELL_MAX_DIST = 20.0f; // Max distance a bug can be for the twin to choose it + +// Vek'nilash constants +static constexpr uint32 UPPERCUT_MIN_CD = 14000; +static constexpr uint32 UPPERCUT_MAX_CD = 29000; +static constexpr uint32 UNBALANCING_STRIKE_MIN_CD = 8000; +static constexpr uint32 UNBALANCING_STRIKE_MAX_CD = 18000; +static constexpr uint32 MUTATE_BUG_MIN_CD = 10000; +static constexpr uint32 MUTATE_BUG_MAX_CD = 15000; + +// Vek'lor constants +static constexpr float ARCANE_BURST_RANGE = 10.0f; // How close must a player be if VL should cast AB +static constexpr uint32 ARCANE_BURST_MIN_CD = 5000; +static constexpr uint32 ARCANE_BURST_MAX_CD = 10000; +static constexpr uint32 BLIZZARD_MIN_CD = 15000; // todo: no source on blizzard cooldown. Duration is 10s +static constexpr uint32 BLIZZARD_MAX_CD = 20000; +static constexpr uint32 VEKLOR_DIST = 20; // Vek'lor chase to this distance +static constexpr uint32 SHADOWBOLT_RANGED_MIN_CD = 1800; +static constexpr uint32 SHADOWBOLT_RANGED_MAX_CD = 2500; +static constexpr uint32 SHADOWBOLT_MELEE_MIN_CD = 2000; +static constexpr uint32 SHADOWBOLT_MELEE_MAX_CD = 10000; +static constexpr uint32 VEKLOR_PULL_YELL_DELAY = 3000; // Vek'lors pull yell happens after Vek'nilash +static constexpr uint32 EXPLODE_BUG_MIN_CD = 7000; +static constexpr uint32 EXPLODE_BUG_MAX_CD = 10000; + + +struct mob_TwinsBug : public ScriptedAI { + mob_TwinsBug(Creature* pCreature) : ScriptedAI(pCreature) + { + Reset(); + } + + void GoBeBadBug(uint32 whatKindOfbad) + { + m_creature->AddAura(whatKindOfbad); + m_creature->setFaction(14); + m_creature->SetInCombatWithZone(); + if (whatKindOfbad == SPELL_MUTATE_BUG) { + m_creature->SetFullHealth(); + } + } + + void JustDied(Unit* Killer) override + { + m_creature->setFaction(7); + m_creature->RemoveAllAuras(); + } + + virtual void Reset() override + { + m_creature->setFaction(7); + m_creature->RemoveAllAuras(); + } + + virtual void UpdateAI(const uint32 diff) override + { + ScriptedAI::UpdateAI(diff); + } +}; struct boss_twinemperorsAI : public ScriptedAI { - ScriptedInstance* m_pInstance; - uint32 Heal_Timer; - uint32 Teleport_Timer; - bool AfterTeleport; - uint32 AfterTeleportTimer; - bool DontYellWhenDead; - uint32 Abuse_Bug_Timer, BugsTimer; - bool tspellcasted; + instance_temple_of_ahnqiraj* m_pInstance; uint32 EnrageTimer; + + uint32 justTeleportedTimer; + bool justTeleported; + bool didPullDialogue; + + uint32 bugMutationTimer; + uint32 respawnBugTimer; - virtual bool IAmVeklor() = 0; - virtual void Reset() = 0; - virtual void CastSpellOnBug(Creature *target) = 0; + uint32 killSayCooldown; - boss_twinemperorsAI(Creature* pCreature) : ScriptedAI(pCreature) + virtual uint32 GetBugSpellCooldown() = 0; + virtual uint32 GetBugSpell() = 0; + virtual void OnEndTeleportVirtual() = 0; + virtual void UpdateEmperor(uint32) = 0; + + // Only one of the twins should implement these functions + virtual void UpdateTeleportToMyBrother(uint32) {} + virtual void TryHealBrother(uint32 diff) {} + + ObjectGuid closestTargetAfterTP; + + boss_twinemperorsAI(Creature* pCreature) : + ScriptedAI(pCreature) { - m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); - TwinReset(); + pCreature->SetLootAndXPModDist(150.0f); + + instance_temple_of_ahnqiraj* tmpPTr = dynamic_cast(pCreature->GetInstanceData()); + if (!tmpPTr) { + sLog.outError("boss_twinemperorsAI attempted to cast instance to type instance_temple_of_ahnqiraj, but failed."); + m_pInstance = nullptr; + } + else { + m_pInstance = (instance_temple_of_ahnqiraj*)pCreature->GetInstanceData(); + + //If the encounter has not been started yet this ID they should be kneeling to the eye. + if (!m_pInstance->TwinsDialogueStartedOrDone()) { + m_creature->SetStandState(UNIT_STAND_STATE_KNEEL); + } + } + //Reset(); reset is called by child class } - void TwinReset() + void SharedReset() { - Heal_Timer = 0; // first heal immediately when they get close together - Teleport_Timer = TELEPORTTIME; - AfterTeleport = false; - tspellcasted = false; - AfterTeleportTimer = 0; - Abuse_Bug_Timer = urand(10000, 17000); - BugsTimer = 2000; + respawnBugTimer = RESPAWN_BUG_FREQUENCY; + EnrageTimer = ENRAGE_TIMER; + justTeleported = false; + didPullDialogue = false; + killSayCooldown = 0; m_creature->clearUnitState(UNIT_STAT_STUNNED); - DontYellWhenDead = false; - EnrageTimer = 15 * 60000; } - Creature* GetOtherBoss() + void MoveInLineOfSight(Unit *who) override { - if (m_pInstance) - return m_pInstance->GetSingleCreatureFromStorage(IAmVeklor() ? NPC_VEKNILASH : NPC_VEKLOR); - else - return NULL; - } - - void DamageTaken(Unit *done_by, uint32 &damage) - { - Creature *pOtherBoss = GetOtherBoss(); - if (pOtherBoss) - { - float dPercent = ((float)damage) / ((float)m_creature->GetMaxHealth()); - int odmg = (int)(dPercent * ((float)pOtherBoss->GetMaxHealth())); - int ohealth = pOtherBoss->GetHealth() - odmg; - pOtherBoss->SetHealth(ohealth > 0 ? ohealth : 0); - if (ohealth <= 0) - { - pOtherBoss->SetDeathState(JUST_DIED); - pOtherBoss->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); - } - } - } - - void JustDied(Unit* Killer) - { - if (Creature* pOtherBoss = GetOtherBoss()) - { - pOtherBoss->SetHealth(0); - pOtherBoss->SetDeathState(JUST_DIED); - pOtherBoss->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); - - if (boss_twinemperorsAI* pOtherAI = dynamic_cast(pOtherBoss->AI())) - pOtherAI->DontYellWhenDead = true; - } - - if (!DontYellWhenDead) // I hope AI is not threaded - DoPlaySoundToSet(m_creature, IAmVeklor() ? SOUND_VL_DEATH : SOUND_VN_DEATH); - - if (m_pInstance) - m_pInstance->SetData(TYPE_TWINS, DONE); - } - - void KilledUnit(Unit* victim) - { - DoPlaySoundToSet(m_creature, IAmVeklor() ? SOUND_VL_KILL : SOUND_VN_KILL); - } - - void Aggro(Unit* pWho) - { - Creature *pOtherBoss = GetOtherBoss(); - if (pOtherBoss) - { - // TODO: we should activate the other boss location so he can start attackning even if nobody - // is near I dont know how to do that - if (!pOtherBoss->isInCombat()) - { - DoPlaySoundToSet(m_creature, IAmVeklor() ? SOUND_VL_AGGRO : SOUND_VN_AGGRO); - pOtherBoss->AI()->AttackStart(pWho); - } - } - - if (m_pInstance) - m_pInstance->SetData(TYPE_TWINS, IN_PROGRESS); - } - - void JustReachedHome() - { - if (m_pInstance) - m_pInstance->SetData(TYPE_TWINS, DONE); - } - - void SpellHit(Unit *caster, const SpellEntry *entry) - { - if (caster == m_creature) - return; - - Creature *pOtherBoss = GetOtherBoss(); - if (entry->Id != SPELL_HEAL_BROTHER || !pOtherBoss) - return; - - // add health so we keep same percentage for both brothers - uint32 mytotal = m_creature->GetMaxHealth(), histotal = pOtherBoss->GetMaxHealth(); - float mult = ((float)mytotal) / ((float)histotal); - if (mult < 1) - mult = 1.0f / mult; -#define HEAL_BROTHER_AMOUNT 30000.0f - uint32 largerAmount = (uint32)((HEAL_BROTHER_AMOUNT * mult) - HEAL_BROTHER_AMOUNT); - - uint32 myh = m_creature->GetHealth(); - uint32 hish = pOtherBoss->GetHealth(); - if (mytotal > histotal) - { - uint32 h = m_creature->GetHealth() + largerAmount; - m_creature->SetHealth(std::min(mytotal, h)); - } - else - { - uint32 h = pOtherBoss->GetHealth() + largerAmount; - pOtherBoss->SetHealth(std::min(histotal, h)); - } - } - - void TryHealBrother(uint32 diff) - { - if (IAmVeklor()) // this spell heals caster and the other brother so let VN cast it - return; - - if (Heal_Timer < diff) - { - Unit *pOtherBoss = GetOtherBoss(); - if (pOtherBoss && pOtherBoss->IsWithinDist(m_creature, 60.0f)) - { - if (DoCastSpellIfCan(pOtherBoss, SPELL_HEAL_BROTHER) == CAST_OK) - Heal_Timer = 1000; - } - } - else Heal_Timer -= diff; - } - - Unit *GetAnyoneCloseEnough(bool totallyRandom) - { - int cnt = 0; - std::list candidates; - - ThreatList const& tList = m_creature->getThreatManager().getThreatList(); - for (ThreatList::const_iterator i = tList.begin(); i != tList.end(); ++i) - { - Unit* pUnit = m_creature->GetMap()->GetUnit((*i)->getUnitGuid()); - - if (m_creature->IsWithinMeleeRange(pUnit)) - { - if (!totallyRandom) - return pUnit; - candidates.push_back((*i)); - ++cnt; - } - } - if (!cnt) - return NULL; - for (int randomi = rand() % cnt; randomi > 0; randomi --) - candidates.pop_front(); - - Unit *ret = m_creature->GetMap()->GetUnit(candidates.front()->getUnitGuid()); - candidates.clear(); - return ret; - } - - Unit *PickNearestPlayer() - { - Unit *nearp = NULL; - float neardist = 0.0f; - ThreatList const& tList = m_creature->getThreatManager().getThreatList(); - for (ThreatList::const_iterator i = tList.begin(); i != tList.end(); ++i) - { - Unit* pUnit = m_creature->GetMap()->GetUnit((*i)->getUnitGuid()); - - if (!pUnit) - continue; - - float pudist = pUnit->GetDistance((const Creature *)m_creature); - if (!nearp || (neardist > pudist)) - { - nearp = pUnit; - neardist = pudist; - } - } - return nearp; - } - - void TeleportToMyBrother() - { - if (!m_pInstance) - return; - - Teleport_Timer = TELEPORTTIME; - - if (IAmVeklor()) - return; // mechanics handled by veknilash so they teleport exactly at the same time and to correct coordinates - - Creature *pOtherBoss = GetOtherBoss(); - if (pOtherBoss) - { - //m_creature->MonsterYell("Teleporting ...", LANG_UNIVERSAL); - float other_x = pOtherBoss->GetPositionX(); - float other_y = pOtherBoss->GetPositionY(); - float other_z = pOtherBoss->GetPositionZ(); - float other_o = pOtherBoss->GetOrientation(); - - Map *thismap = m_creature->GetMap(); - thismap->CreatureRelocation(pOtherBoss, m_creature->GetPositionX(), - m_creature->GetPositionY(), m_creature->GetPositionZ(), m_creature->GetOrientation()); - thismap->CreatureRelocation(m_creature, other_x, other_y, other_z, other_o); - - SetAfterTeleport(); - - if (boss_twinemperorsAI* pOtherAI = dynamic_cast(pOtherBoss->AI())) - pOtherAI->SetAfterTeleport(); - } - } - - void SetAfterTeleport() - { - m_creature->InterruptNonMeleeSpells(false); - DoStopAttack(); - DoResetThreat(); - DoCastSpellIfCan(m_creature, SPELL_TWIN_TELEPORT_VISUAL); - m_creature->addUnitState(UNIT_STAT_STUNNED); - AfterTeleport = true; - AfterTeleportTimer = 2000; - tspellcasted = false; - } - - bool TryActivateAfterTTelep(uint32 diff) - { - if (AfterTeleport) - { - if (!tspellcasted) - { - m_creature->clearUnitState(UNIT_STAT_STUNNED); - DoCastSpellIfCan(m_creature, SPELL_TWIN_TELEPORT); - m_creature->addUnitState(UNIT_STAT_STUNNED); - } - - tspellcasted = true; - - if (AfterTeleportTimer < diff) - { - AfterTeleport = false; - m_creature->clearUnitState(UNIT_STAT_STUNNED); - Unit *nearu = PickNearestPlayer(); - //DoYell(nearu->GetName(), LANG_UNIVERSAL, 0); - AttackStart(nearu); - m_creature->getThreatManager().addThreat(nearu, 10000); - return true; - } - else - { - AfterTeleportTimer -= diff; - // update important timers which would otherwise get skipped - if (EnrageTimer > diff) - EnrageTimer -= diff; - else - EnrageTimer = 0; - if (Teleport_Timer > diff) - Teleport_Timer -= diff; - else - Teleport_Timer = 0; - return false; - } - } - else - return true; - } - - void MoveInLineOfSight(Unit *who) - { - if (!who || m_creature->getVictim()) + // Only want to run this if we are not in combat + if (!who || m_creature->getVictim() || m_creature->isInCombat()) return; if (who->isTargetableForAttack() && who->isInAccessablePlaceFor(m_creature) && m_creature->IsHostileTo(who)) @@ -358,87 +226,561 @@ struct boss_twinemperorsAI : public ScriptedAI float attackRadius = m_creature->GetAttackDistance(who); if (attackRadius < PULL_RANGE) attackRadius = PULL_RANGE; - if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->GetDistanceZ(who) <= /*CREATURE_Z_ATTACK_RANGE*/7 /*there are stairs*/) + + // CREATURE_Z_ATTACK_RANGE there are stairs + if (m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->GetDistanceZ(who) <= 7) AttackStart(who); } } - Creature *RespawnNearbyBugsAndGetOne() + void AttackedBy(Unit* attacker) override { - std::list lUnitList; - GetCreatureListWithEntryInGrid(lUnitList, m_creature, 15316, 150.0f); - GetCreatureListWithEntryInGrid(lUnitList, m_creature, 15317, 150.0f); - - if (lUnitList.empty()) - return NULL; - - Creature *nearb = NULL; - - for (std::list::iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) + // Preventing the emperors to start attacking target + // during the teleport-idle period + if (!justTeleported) { - Creature *c = (Creature *)(*iter); - if (c->isDead()) - { - c->Respawn(); - c->setFaction(7); - c->RemoveAllAuras(); - } - if (c->IsWithinDistInMap(m_creature, ABUSE_BUG_RANGE)) - { - if (!nearb || !urand(0, 3)) - nearb = c; - } + ScriptedAI::AttackedBy(attacker); } - return nearb; } - void HandleBugs(uint32 diff) + void DamageTaken(Unit *done_by, uint32 &damage) override { - if (BugsTimer < diff || Abuse_Bug_Timer < diff) + if (!m_pInstance) + return; + + if (Creature* pTwin = GetOtherBoss()) { - Creature *c = RespawnNearbyBugsAndGetOne(); - if (Abuse_Bug_Timer < diff) - { - if (c) - { - CastSpellOnBug(c); - Abuse_Bug_Timer = urand(10000, 17000); + float fDamPercent = ((float)damage) / ((float)m_creature->GetMaxHealth()); + uint32 uiTwinDamage = (uint32)(fDamPercent * ((float)pTwin->GetMaxHealth())); + uint32 uiTwinHealth = pTwin->GetHealth() - std::min(uiTwinDamage, pTwin->GetHealth()); + pTwin->SetHealth(std::max((uint32)0, uiTwinHealth)); + + // Possibly needed to make sure the damage dealth through setHealth is counted + pTwin->CountDamageTaken(uiTwinDamage, true); + } + } + + void JustDied(Unit* Killer) override + { + // Only need one of them to kill the other and update instance data + if (m_pInstance) { + if (m_pInstance->GetData(TYPE_TWINS) == DONE) { + return; + } + else { + m_pInstance->SetData(TYPE_TWINS, DONE); + } + } + + if (Creature* pOtherBoss = GetOtherBoss()) + { + Killer->Kill(pOtherBoss, nullptr, false); + } + + // Death text script-text is handled by instance upon receiving DONE data + } + + void Aggro(Unit* pWho) override + { + if (m_pInstance) { + if (m_pInstance->GetData(TYPE_TWINS) == IN_PROGRESS) { + return; + } + m_pInstance->SetData(TYPE_TWINS, IN_PROGRESS); + } + std::list lst; + GetCreatureListWithEntryInGrid(lst, m_creature, NPC_ANUBISATH_DEFENDER, 800); + for (auto it = lst.begin(); it != lst.end(); it++) + { + Creature* pC = *it; + if (pC->isDead()) continue; + pC->SetInCombatWithZone(); + pC->AI()->AttackStart(pWho); + } + + m_creature->SetInCombatWithZone(); + + Creature *pOtherBoss = GetOtherBoss(); + if (pOtherBoss) + { + // The "other boss" will start running to the same initial puller. + pOtherBoss->AI()->AttackStart(pWho); + pOtherBoss->SetInCombatWithZone(); + } + } + + void JustReachedHome() override + { + if (m_pInstance) + m_pInstance->SetData(TYPE_TWINS, FAIL); + } + + // Workaround for the shared health pool + void HealedBy(Unit* pHealer, uint32 uiHealedAmount) override + { + if (!m_pInstance) + return; + + if (Creature* pTwin = GetOtherBoss()) + { + float fHealPercent = ((float)uiHealedAmount) / ((float)m_creature->GetMaxHealth()); + uint32 uiTwinHeal = (uint32)(fHealPercent * ((float)pTwin->GetMaxHealth())); + uint32 uiTwinHealth = pTwin->GetHealth() + uiTwinHeal; + pTwin->SetHealth(uiTwinHealth < pTwin->GetMaxHealth() ? uiTwinHealth : pTwin->GetMaxHealth()); + } + } + + void UpdateAI(const uint32 diff) override + { + // The rest of this script requires an instance, less managment and code duplication, and a bit of lazyness + if (!m_pInstance) + return; + + if (justTeleported) { + + // Delaying selection of new closest player until first update after TP + // to be sure we will actually select a target on the new location. + // (in other words, do it here instead of in OnStartTeleport()) + if (closestTargetAfterTP.IsEmpty()) { + //Making sure everyone is contained in threatlist + m_creature->SetInCombatWithZone(); + //todo: any potential issues with using GetNearestVictimInRange and 300 maxrange? + if (Unit* closestPlayer = m_creature->GetNearestVictimInRange(0, 300.0f)) { + closestTargetAfterTP = closestPlayer->GetGUID(); + m_creature->getThreatManager().addThreat(closestPlayer, AFTER_TELEPORT_THREAT); + } + else { + sLog.outBasic("Twins unable to select closest target during TP stun"); } - else - Abuse_Bug_Timer = 1000; } - else - Abuse_Bug_Timer -= diff; - BugsTimer = 2000; + + if (justTeleportedTimer <= diff) { + OnEndTeleport(); + } + else { + justTeleportedTimer -= diff; + } } - else - { - BugsTimer -= diff; - Abuse_Bug_Timer -= diff; + else { + // Not attempting to get a hostile target during teleport-idle + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) { + return; + } + } + + if (killSayCooldown > 0) { + killSayCooldown -= diff; + } + + // We keep calling all of these updates also when TP-stunned, + // but the functions themself will delay the actual spells until + // they are no longer TP-stunned + CheckEnrage(diff); + UpdateTeleportToMyBrother(diff); + HandleBugSpell(diff); + TryHealBrother(diff); + //HandleDeadBugs(diff); // they respawn by themself... + + // We skip updating emperor-specific spells during teleport stun + if (!justTeleported) { + UpdateEmperor(diff); + } + + // Evade in case starts running after someone outside their room + if (m_creature->GetPositionZ() > -95.0f) { + if(Creature* pOther = GetOtherBoss()) + pOther->AI()->EnterEvadeMode(); + EnterEvadeMode(); } } + Creature* GetOtherBoss() + { + if (m_pInstance) + return m_pInstance->GetSingleCreatureFromStorage(m_creature->GetEntry() == NPC_VEKLOR ? NPC_VEKNILASH : NPC_VEKLOR); + return nullptr; + } + + // Called as teleport happens + void OnStartTeleport(float x, float y, float z, float o) + { + justTeleported = true; + justTeleportedTimer = JUST_TELEPORTED_FREEZE; + m_creature->InterruptNonMeleeSpells(true); + DoStopAttack(); + DoResetThreat(); + m_creature->StopMoving(); + m_creature->NearTeleportTo(x, y, z, o); + closestTargetAfterTP = 0; + m_creature->CastSpell(m_creature, SPELL_TWIN_TELEPORT_MSG, true); + m_creature->CastSpell(m_creature, SPELL_TWIN_TELEPORT_VISUAL, true); + } + + // Called JUST_TELEPORTED_FREEZE after teleport happened + void OnEndTeleport() + { + justTeleported = false; + + if (Player* closestPlayer = m_pInstance->GetMap()->GetPlayer(closestTargetAfterTP)) { + closestTargetAfterTP = closestPlayer->GetGUID(); + AttackStart(closestPlayer); + } + else { + sLog.outBasic("Twins unable to select closest target after TP stun end"); + } + + + OnEndTeleportVirtual(); + } + + void HandleBugSpell(uint32 diff) + { + if (bugMutationTimer < diff) { + + // Wait with doing stuff until after idle + if (justTeleported) return; + + std::list lUnitList; + GetCreatureListWithEntryInGrid(lUnitList, m_creature, { BUG_TYPE_1 , BUG_TYPE_2 }, BUG_SPELL_MAX_DIST); + + std::list::iterator iter; + for (iter = lUnitList.begin(); iter != lUnitList.end();) { + if ((*iter)->isDead()) { + iter = lUnitList.erase(iter); + } + // Ignoring bugs that has already been affected by a spell + else if ((*iter)->HasAura(SPELL_MUTATE_BUG) || (*iter)->HasAura(SPELL_EXPLODEBUG)) { + iter = lUnitList.erase(iter); + } + else { + ++iter; + } + } + + if (lUnitList.size() == 0) + return; + + iter = lUnitList.begin(); + + std::advance(iter, urand(0, lUnitList.size() - 1)); + Creature* c = *iter; + mob_TwinsBug* bugAI = dynamic_cast(c->AI()); + if (bugAI) { + bugAI->GoBeBadBug(GetBugSpell()); + } + bugMutationTimer = GetBugSpellCooldown(); + } + else { + bugMutationTimer -= diff; + } + } + void CheckEnrage(uint32 diff) { - if (EnrageTimer < diff) + if (EnrageTimer < diff && !m_creature->HasAura(SPELL_BERSERK)) { - if (!m_creature->IsNonMeleeSpellCasted(true)) - { - if (DoCastSpellIfCan(m_creature, SPELL_BERSERK, CAST_AURA_NOT_PRESENT) == CAST_OK) - EnrageTimer = 60 * 60000; - } - else EnrageTimer = 0; + // Wait with casting enrage until after TP idle + if (justTeleported) return; + + // just force-apply berserk if it's time. No dilly-dally. + m_creature->CastSpell(m_creature, SPELL_BERSERK, true); + EnrageTimer = 60000 * 5; // resetting to duration of enrage } - else EnrageTimer -= diff; + else + { + EnrageTimer -= diff; + } + } + + // Get players in given range, optionally skip topaggro. Used where + // we dont want to compare distance + bounding radius etc, but rather + // simply center-to-center + Player* GetPlayerInP2PRange(float min, float max, bool skipTopAggro) + { + ThreatList const& tList = m_creature->getThreatManager().getThreatList(); + + if (tList.size() == 0) + return nullptr; + + std::list candidates; + ThreatList::const_iterator i = tList.begin(); + + // skipping top-aggro if there are more than 1 person on threat list + if (tList.size() > 1 && skipTopAggro) + ++i; + + for (i; i != tList.end(); ++i) { + Player* pPlayer = m_creature->GetMap()->GetPlayer((*i)->getUnitGuid()); + if (!pPlayer) continue; + + if (m_creature->IsInRange(pPlayer, min, max)) { + candidates.push_back(pPlayer); + } + } + + if (candidates.size() == 0) + return nullptr; + + auto candIt = candidates.begin(); + std::advance(candIt, candidates.size() - 1); + return *candIt; + } +}; + +struct boss_veklorAI : public boss_twinemperorsAI +{ + boss_veklorAI(Creature* pCreature) : boss_twinemperorsAI(pCreature) + { + Reset(); + + // Making sure we have the correct range values + shadowboltRange = 45.0f; + if (const SpellRangeEntry* sre = sSpellRangeStore.LookupEntry(SPELL_SHADOWBOLT)) + shadowboltRange = sre->maxRange; + blizzardRange = 45.0f; + if (const SpellRangeEntry* sre = sSpellRangeStore.LookupEntry(SPELL_BLIZZARD)) + blizzardRange = sre->maxRange; + } + + float shadowboltRange; + float blizzardRange; + + uint32 shadowBoltTimer; + uint32 blizzardTimer; + uint32 arcaneBurstTimer; + + uint32 pullDialogueTimer; + + uint32 teleportTimer; + uint32 healTimer; + uint32 timeSinceLastSB; + + void Reset() override + { + SharedReset(); + shadowBoltTimer = 0; // No cooldown on pull + arcaneBurstTimer = 0; // No cooldown on pull + bugMutationTimer = boss_veklorAI::GetBugSpellCooldown(); + blizzardTimer = urand(BLIZZARD_MIN_CD, BLIZZARD_MAX_CD); + teleportTimer = urand(TELEPORTTIME_MIN_CD, TELEPORTTIME_MAX_CD); + healTimer = TRY_HEAL_FREQUENCY; + pullDialogueTimer = VEKLOR_PULL_YELL_DELAY; + timeSinceLastSB = SHADOWBOLT_RANGED_MIN_CD; + + // Can be removed if its included in DB. + m_creature->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, true); + } + + void AttackStart(Unit* who) override + { + float dist = m_creature->GetDistanceToCenter(who); + if (dist <= VEKLOR_DIST) { + // if he is <= VEKLOR_DIST he should not start chasing again until + // target is further away than shadowboltRange + m_creature->SetCasterChaseDistance(shadowboltRange); + } + else if (dist > shadowboltRange) { + // if he is further away than shadowboltRange we set + // chase distance to VEKLOR_DIST + m_creature->SetCasterChaseDistance(VEKLOR_DIST); + } + ScriptedAI::AttackStart(who); + } + + void KilledUnit(Unit*) override + { + if (killSayCooldown == 0) { + DoScriptText(SAY_VEKLOR_SLAY, m_creature); + killSayCooldown = urand(5000, 10000); + } + } + + uint32 GetBugSpellCooldown() override + { + return urand(EXPLODE_BUG_MIN_CD, EXPLODE_BUG_MAX_CD); + } + + uint32 GetBugSpell() + { + return SPELL_EXPLODEBUG; + } + + virtual void UpdateTeleportToMyBrother(uint32 diff) override + { + // Updating time and returning if it's not yet time to teleport + if (teleportTimer >= diff) { + teleportTimer -= diff; + return; + } + teleportTimer = urand(TELEPORTTIME_MIN_CD, TELEPORTTIME_MAX_CD); + + // If he is attacked during this periode he will instantly engage + // If noone attacked during that periode, he start attacking after the period. + + Creature *pOtherBoss = GetOtherBoss(); + if (!pOtherBoss) return; // Well, that was too bad... + + float other_x = pOtherBoss->GetPositionX(); + float other_y = pOtherBoss->GetPositionY(); + float other_z = pOtherBoss->GetPositionZ(); + float other_o = pOtherBoss->GetOrientation(); + float me_x = m_creature->GetPositionX(); + float me_y = m_creature->GetPositionY(); + float me_z = m_creature->GetPositionZ(); + float me_o = m_creature->GetOrientation(); + + OnStartTeleport(other_x, other_y, other_z, me_o); + if (boss_twinemperorsAI* pOtherAI = dynamic_cast(pOtherBoss->AI())) { + pOtherAI->OnStartTeleport(me_x, me_y, me_z, other_o); + } + } + + void TryHealBrother(uint32 diff) override + { + // Cant heal while tp-idle, but since the "stun" effect isent really working properly we return manually + // https://www.youtube.com/watch?v=8mGchbCF1Lw + if (justTeleported) { + healTimer -= std::min(diff, healTimer); + return; + } + + if (healTimer < diff) { + Unit *pOtherBoss = GetOtherBoss(); + if (pOtherBoss && pOtherBoss->IsWithinDist(m_creature, HEAL_BROTHER_RANGE)) + { + if (DoCastSpellIfCan(pOtherBoss, SPELL_HEAL_BROTHER) == CAST_OK) { + // triggered-cast from brother on me if we successfully healed the other way + pOtherBoss->CastSpell(m_creature, SPELL_HEAL_BROTHER, true); + healTimer = SUCCESS_HEAL_FREQUENCY; + } + } + else { + healTimer = TRY_HEAL_FREQUENCY; + } + } + else { + healTimer -= diff; + } + } + + void OnEndTeleportVirtual() override + { + // Seems rather random if he starts with an AB instantly or delays it + // when looking at vanilla videos, so possibly because the timer is not reset? + //arcaneBurstTimer = ARCANE_BURST_TP_CD; + + shadowBoltTimer = 0; + } + + void UpdateBlizzard(uint32 diff) + { + if (blizzardTimer < diff) { + if (Player* p = GetPlayerInP2PRange(0, blizzardRange, true)) { + if (DoCastSpellIfCan(p, SPELL_BLIZZARD) == CAST_OK) { + blizzardTimer = urand(BLIZZARD_MIN_CD, BLIZZARD_MAX_CD); + } + } + } + else { + blizzardTimer -= diff; + } + } + + void updateArcaneBurst(uint32 diff) + { + if (arcaneBurstTimer < diff) { + if (Unit* mvic = GetPlayerInP2PRange(0, ARCANE_BURST_RANGE, false)) { + if (DoCastSpellIfCan(mvic, SPELL_ARCANEBURST) == CAST_OK) + arcaneBurstTimer = urand(ARCANE_BURST_MIN_CD, ARCANE_BURST_MAX_CD); + } + } + else { + arcaneBurstTimer -= diff; + } + } + + void UpdateEmperor(uint32 diff) override + { + // Vek'lor does his yell second, so we wait out pullDialogueTimer before yelling + if (!didPullDialogue) + { + if (pullDialogueTimer < diff) + { + didPullDialogue = true; + DoScriptText(irand(SAY_VEKLOR_AGGRO_4, SAY_VEKLOR_AGGRO_1), m_creature); + } + else + { + pullDialogueTimer -= diff; + } + } + + // Always update blizzard and arcane burst, regardless of melee or not + UpdateBlizzard(diff); + updateArcaneBurst(diff); + + Unit* victim = m_creature->getVictim(); + if (!victim) + return; + + bool isMelee = m_creature->IsWithinMeleeRange(victim); + bool isInLos = m_creature->IsWithinLOSInMap(victim); + + // Overriding shadowboltTimer if we're not in melee and we have not casted + // shadowbolt in at least SHADOWBOLT_RANGED_CD time. This will mostly be the + // case if target was in melee, but then moved out, in which case we should + // instantly re-cast a new shadowbolt unless it was just casted. + if (!isMelee && timeSinceLastSB > SHADOWBOLT_RANGED_MAX_CD) + { + shadowBoltTimer = 0; + } + + // If we're in los and melee range and melee attack succeeded we wait one update before + // doing the shadowbolt. + if (isMelee && isInLos && !m_creature->IsNonMeleeSpellCasted() && DoMeleeAttackIfReady()) + { + shadowBoltTimer -= std::min(diff, shadowBoltTimer); + } + else if (!m_creature->IsMoving()) + { + if(m_creature->getStandState() != UNIT_STAND_STATE_STAND) + m_creature->SetStandState(UNIT_STAND_STATE_STAND); + if (shadowBoltTimer < diff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SHADOWBOLT) == CAST_OK) + { + timeSinceLastSB = 0; + if (isMelee) + { + // Looks like VL should prioritize shadowbolt differently if + // target is in melee range. He seems to get a random cooldown on it, and meleeing when he can. + // https://www.youtube.com/watch?v=SNOmg7kE68U&t=53s + // https://www.youtube.com/watch?v=dCrDisOWOjU + // This may just be some bugged/different behaviour in blizzards spell-priority system, + // but I believe the effect should be the same by adding a random cooldown. + shadowBoltTimer = urand(SHADOWBOLT_MELEE_MIN_CD, SHADOWBOLT_MELEE_MAX_CD); + } + else + { + // When not in melee range, there is only a ~2 sec cooldown on shadowbolt, even though + // the cast-time is only 1.5 seconds. + // https://www.youtube.com/watch?v=nHXfSDVX_ZA + shadowBoltTimer = urand(SHADOWBOLT_RANGED_MIN_CD, SHADOWBOLT_RANGED_MAX_CD); + } + } + } + else + { + shadowBoltTimer -= diff; + } + } + + timeSinceLastSB += diff; } }; struct boss_veknilashAI : public boss_twinemperorsAI { - bool IAmVeklor() - { - return false; - } boss_veknilashAI(Creature* pCreature) : boss_twinemperorsAI(pCreature) { Reset(); @@ -447,196 +789,139 @@ struct boss_veknilashAI : public boss_twinemperorsAI uint32 UpperCut_Timer; uint32 UnbalancingStrike_Timer; uint32 Scarabs_Timer; - int Rand; - int RandX; - int RandY; - - Creature* Summoned; - - void Reset() + + void Reset() override { - TwinReset(); - UpperCut_Timer = urand(14000, 29000); - UnbalancingStrike_Timer = urand(8000, 18000); - Scarabs_Timer = urand(7000, 14000); + SharedReset(); + bugMutationTimer = boss_veknilashAI::GetBugSpellCooldown(); + UpperCut_Timer = urand(UPPERCUT_MIN_CD, UPPERCUT_MAX_CD); + UnbalancingStrike_Timer = urand(UNBALANCING_STRIKE_MIN_CD, UNBALANCING_STRIKE_MAX_CD); //Added. Can be removed if its included in DB. - m_creature->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, true); + m_creature->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_SPELL, true); } - void CastSpellOnBug(Creature *target) + void OnEndTeleportVirtual() { - target->setFaction(14); - - DoCastSpellIfCan(target, SPELL_MUTATE_BUG, CAST_TRIGGERED); + //todo: anything that needs doing? } - void UpdateAI(const uint32 diff) + uint32 GetBugSpellCooldown() override { - //Return since we have no target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; + return urand(MUTATE_BUG_MIN_CD, MUTATE_BUG_MAX_CD); + } - if (!TryActivateAfterTTelep(diff)) - return; + uint32 GetBugSpell() + { + return SPELL_MUTATE_BUG; + } - //UnbalancingStrike_Timer - if (UnbalancingStrike_Timer < diff) - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_UNBALANCING_STRIKE) == CAST_OK) - UnbalancingStrike_Timer = urand(8000, 20000); - } - else UnbalancingStrike_Timer -= diff; + Unit *GetPlayerInMeleeRange() + { + std::list candidates; - if (UpperCut_Timer < diff) - { - Unit* randomMelee = GetAnyoneCloseEnough(true); - if (randomMelee) - { - if (DoCastSpellIfCan(randomMelee, SPELL_UPPERCUT) == CAST_OK) - UpperCut_Timer = urand(15000, 30000); + ThreatList const& tList = m_creature->getThreatManager().getThreatList(); + if (tList.size() < 1) + return nullptr; + + for (ThreatList::const_iterator i = tList.begin(); i != tList.end(); ++i) { + Unit* pUnit = m_creature->GetMap()->GetUnit((*i)->getUnitGuid()); + if (!pUnit) continue; + + if (m_creature->IsWithinMeleeRange(pUnit)) { + candidates.push_back((*i)); } } - else UpperCut_Timer -= diff; - HandleBugs(diff); + if (!candidates.size()) + return nullptr; - //Heal brother when 60yrds close - TryHealBrother(diff); + auto it = candidates.begin(); + std::advance(it, candidates.size() - 1); + return m_creature->GetMap()->GetUnit((*it)->getUnitGuid()); + } + + void UpdateEmperor(uint32 diff) + { + // Vek'nilash goes first, instantly does his yell when we are in combat. + if (!didPullDialogue) { + didPullDialogue = true; + DoScriptText(irand(SAY_VEKNILASH_AGGRO_4, SAY_VEKNILASH_AGGRO_1), m_creature); + } - //Teleporting to brother - if (Teleport_Timer < diff) - TeleportToMyBrother(); - else Teleport_Timer -= diff; - CheckEnrage(diff); + //UnbalancingStrike_Timer + if (UnbalancingStrike_Timer < diff) { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_UNBALANCING_STRIKE) == CAST_OK) { + UnbalancingStrike_Timer = urand(UNBALANCING_STRIKE_MIN_CD, UNBALANCING_STRIKE_MAX_CD); + } + } + else { + UnbalancingStrike_Timer -= diff; + } + + if (UpperCut_Timer < diff) { + if (Unit* randomMelee = GetPlayerInMeleeRange()) { + if (DoCastSpellIfCan(randomMelee, SPELL_UPPERCUT) == CAST_OK) { + UpperCut_Timer = urand(UPPERCUT_MIN_CD, UPPERCUT_MAX_CD); + } + } + } + else { + UpperCut_Timer -= diff; + } DoMeleeAttackIfReady(); } -}; -struct boss_veklorAI : public boss_twinemperorsAI -{ - bool IAmVeklor() + void KilledUnit(Unit*) override { - return true; - } - boss_veklorAI(Creature* pCreature) : boss_twinemperorsAI(pCreature) - { - Reset(); - } - - uint32 ShadowBolt_Timer; - uint32 Blizzard_Timer; - uint32 ArcaneBurst_Timer; - uint32 Scorpions_Timer; - int Rand; - int RandX; - int RandY; - - Creature* Summoned; - - void Reset() - { - TwinReset(); - ShadowBolt_Timer = 0; - Blizzard_Timer = urand(15000, 20000); - ArcaneBurst_Timer = 1000; - Scorpions_Timer = urand(7000, 14000); - - //Added. Can be removed if its included in DB. - m_creature->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, true); - m_creature->SetBaseWeaponDamage(BASE_ATTACK, MINDAMAGE, 0); - m_creature->SetBaseWeaponDamage(BASE_ATTACK, MAXDAMAGE, 0); - } - - void CastSpellOnBug(Creature *target) - { - target->setFaction(14); - - DoCastSpellIfCan(target, SPELL_EXPLODEBUG, CAST_TRIGGERED); - } - - void UpdateAI(const uint32 diff) - { - //Return since we have no target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; - - // reset arcane burst after teleport - we need to do this because - // when VL jumps to VN's location there will be a warrior who will get only 2s to run away - // which is almost impossible - if (AfterTeleport) - ArcaneBurst_Timer = 5000; - if (!TryActivateAfterTTelep(diff)) - return; - - //ShadowBolt_Timer - if (ShadowBolt_Timer < diff) - { - if (!m_creature->IsWithinDist(m_creature->getVictim(), 45.0f)) - m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim(), VEKLOR_DIST, 0); - else - { - if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_SHADOWBOLT) == CAST_OK) - ShadowBolt_Timer = 2000; - } + if (killSayCooldown == 0) { + DoScriptText(SAY_VEKNILASH_SLAY, m_creature); + killSayCooldown = urand(5000, 10000); } - else ShadowBolt_Timer -= diff; - - //Blizzard_Timer - if (Blizzard_Timer < diff) - { - Unit* target = NULL; - target = GetAnyoneCloseEnough(true); - if (target) - { - if (DoCastSpellIfCan(target, SPELL_BLIZZARD) == CAST_OK) - Blizzard_Timer = urand(15000, 30000); - } - } - else Blizzard_Timer -= diff; - - if (ArcaneBurst_Timer < diff) - { - Unit *mvic; - if ((mvic = GetAnyoneCloseEnough(false)) != NULL) - { - if (DoCastSpellIfCan(mvic, SPELL_ARCANEBURST) == CAST_OK) - ArcaneBurst_Timer = 5000; - } - } - else ArcaneBurst_Timer -= diff; - - HandleBugs(diff); - - //Heal brother when 60yrds close - TryHealBrother(diff); - - //Teleporting to brother - if (Teleport_Timer < diff) - TeleportToMyBrother(); - else Teleport_Timer -= diff; - - CheckEnrage(diff); - - //VL doesn't melee - //DoMeleeAttackIfReady(); } void AttackStart(Unit* who) { - if (!who) + ScriptedAI::AttackStart(who); + } +}; + +struct mob_mastersEye : public ScriptedAI { + mob_mastersEye(Creature* pCreature) : ScriptedAI(pCreature) + { + sLog.outBasic("Masters Eye ctor!"); + Reset(); + } + + instance_temple_of_ahnqiraj* m_pInstance; + uint32 flightUpdate; + + void Reset() override + { + instance_temple_of_ahnqiraj* tmpPTr = dynamic_cast(m_creature->GetInstanceData()); + if (!tmpPTr) { + sLog.outError("boss_twinemperorsAI attempted to cast instance to type instance_temple_of_ahnqiraj, but failed."); + m_pInstance = nullptr; + } + else { + m_pInstance = (instance_temple_of_ahnqiraj*)m_creature->GetInstanceData(); + } + flightUpdate = 0; + } + + void UpdateAI(const uint32 diff) override + { + if (m_creature->IsDespawned() || m_pInstance->TwinsDialogueStartedOrDone()) return; - - // VL doesn't melee - if (m_creature->Attack(who, false)) - { - m_creature->AddThreat(who); - m_creature->SetInCombatWith(who); - who->SetInCombatWith(m_creature); - - m_creature->GetMotionMaster()->MoveChase(who, VEKLOR_DIST, 0); + if (flightUpdate < diff) { + m_creature->CastSpell(m_creature, 17131, true); // Start flying + m_creature->GetMotionMaster()->MovePoint(0, -8952.7f, 1235.39f, -102.0f, MOVE_FLY_MODE, 0.0f, 4.896f); + flightUpdate = 5000; + } + else { + flightUpdate -= diff; } } }; @@ -651,6 +936,16 @@ CreatureAI* GetAI_boss_veklor(Creature* pCreature) return new boss_veklorAI(pCreature); } +CreatureAI* GetAI_masters_eye(Creature* pCreature) +{ + return new mob_mastersEye(pCreature); +} + +CreatureAI* GetAI_twinsBug(Creature* pCreature) +{ + return new mob_TwinsBug(pCreature); +} + void AddSC_boss_twinemperors() { Script *newscript; @@ -664,4 +959,14 @@ void AddSC_boss_twinemperors() newscript->Name = "boss_veklor"; newscript->GetAI = &GetAI_boss_veklor; newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "mob_masters_eye"; + newscript->GetAI = &GetAI_masters_eye; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "mob_twins_bug"; + newscript->GetAI = &GetAI_twinsBug; + newscript->RegisterSelf(); } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_viscidus.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_viscidus.cpp index c0e2bae9b..961c72a90 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_viscidus.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_viscidus.cpp @@ -19,21 +19,30 @@ /* ScriptData SDName: Boss_Viscidus -SD%Complete: 0 -SDComment: place holder +SD%Complete: 90 +SDComment: ToDo: Use aura proc to handle freeze event instead of direct function SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "scriptPCH.h" +#include "temple_of_ahnqiraj.h" +#include enum { + // emotes + EMOTE_SLOW = -1531041, + EMOTE_FREEZE = -1531042, + EMOTE_FROZEN = -1531043, + EMOTE_CRACK = -1531044, + EMOTE_SHATTER = -1531045, + EMOTE_EXPLODE = -1531046, + // Timer spells SPELL_POISON_SHOCK = 25993, SPELL_POISONBOLT_VOLLEY = 25991, - SPELL_TOXIN = 26575, // Triggers toxin cloud + SPELL_TOXIN = 26575, // Triggers toxin cloud - 25989 SPELL_TOXIN_CLOUD = 25989, - SPELL_TOXIN_SUMMON = 26577, // Debuffs gained by the boss on frost damage SPELL_VISCIDUS_SLOWED = 26034, @@ -42,198 +51,396 @@ enum // When frost damage exceeds a certain limit, then boss explodes SPELL_REJOIN_VISCIDUS = 25896, - SPELL_VISCIDUS_EXPLODE = 25938, // Casts a lot of spells in the same time: 25865 to 25884; All spells have target coords - SPELL_VISCIDUS_SUICIDE = 26003, + SPELL_VISCIDUS_EXPLODE = 25938, + SPELL_VISCIDUS_SUICIDE = 26003, // cast when boss explodes and is below 5% Hp - should trigger 26002 + SPELL_DESPAWN_GLOBS = 26608, + SPELL_MEMBRANE_VISCIDUS = 25994, // damage reduction spell + SPELL_VISCIDUS_WEAKNESS = 25926, // aura which procs at damage - should trigger the slow spells SPELL_VISCIDUS_SHRINKS = 25893, + SPELL_VISCIDUS_SHRINKS_HP = 27934, // should be scripted properly + SPELL_VISCIDUS_GROWS = 25897, + SPELL_SUMMON_GLOBS = 25885, // summons npc 15667 using spells from 25865 to 25884; All spells have target coords + SPELL_VISCIDUS_TELEPORT = 25904, // teleport to room center + SPELL_SUMMONT_TRIGGER = 26564, // summons 15992 - NPC_GLOB_OF_VISCIDUS = 15667 + SPELL_GLOB_SPEED = 26633, // apply aura 26634 each second + + NPC_GLOB_OF_VISCIDUS = 15667, + NPC_VISCIDUS_TRIGGER = 15922, // handles aura 26575 + + MAX_VISCIDUS_GLOBS = 20, // there are 20 summoned globs; each glob = 5% hp + + // hitcounts + HITCOUNT_SLOW = 100, + HITCOUNT_SLOW_MORE = 150, + HITCOUNT_FREEZE = 200, + + // phases + PHASE_NORMAL = 1, + PHASE_FROZEN = 2, + PHASE_EXPLODED = 3, + + SPELL_WAND_SHOOT = 5019, }; +static const uint32 auiGlobSummonSpells[MAX_VISCIDUS_GLOBS] = { 25865, 25866, 25867, 25868, 25869, 25870, 25871, 25872, 25873, 25874, 25875, 25876, 25877, 25878, 25879, 25880, 25881, 25882, 25883, 25884 }; + struct boss_viscidusAI : public ScriptedAI { boss_viscidusAI(Creature* pCreature) : ScriptedAI(pCreature) { + m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); + m_initialScale = pCreature->GetObjectScale(); Reset(); } - uint32 SalveToxiqueTimer; - uint32 HorionEmpoisonneTimer; - uint32 FlaqueTimer; - uint32 InvisibleTimer; + ScriptedInstance* m_pInstance; - int Vie; - int Froid; - bool Gele; - bool Visible; + uint32 m_uiHitCount; + uint32 m_uiToxinTimer; + uint32 m_uiExplodeDelayTimer; + uint32 m_uiPoisonShockTimer; + uint32 m_uiPoisonBoltVolleyTimer; + + uint32 m_uiPhaseTimer; + uint16 m_uiGrowTimer; + uint8 m_uiPhase; + + float m_initialScale; + uint8 m_uiGrowCount; + + GuidList m_lGlobesGuidList; + std::bitset<20> track; void Reset() { - SalveToxiqueTimer = 8000; - HorionEmpoisonneTimer = 1000; - FlaqueTimer = 20000; - InvisibleTimer = 0; - Vie = 20; - Froid = 0; - Gele = false; - Visible = true; + m_uiGrowTimer = 0; + m_uiPhase = PHASE_NORMAL; + m_uiPhaseTimer = 0; + + m_uiHitCount = 0; + m_uiExplodeDelayTimer = 0; + m_uiToxinTimer = 30000; + m_uiPoisonShockTimer = urand(7000, 12000); + m_uiPoisonBoltVolleyTimer = urand(10000, 15000); + m_uiGrowCount = 0; + m_creature->SetObjectScale(m_initialScale); + track.reset(); + + DoCastSpellIfCan(m_creature, SPELL_MEMBRANE_VISCIDUS, CAST_TRIGGERED); + DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_WEAKNESS, CAST_TRIGGERED); + + ResetViscidusState(false); } - void DamageTaken(Unit *done_by, uint32 &damage) + void MoveInLineOfSight(Unit* who) override { - if (damage >= m_creature->GetHealth() && Vie > 0) - damage = 0; - - if (Gele == true && done_by->GetDistance(m_creature) < 5.0f) + if (who->GetTypeId() == TYPEID_PLAYER && !m_creature->getVictim() && m_creature->IsWithinDistInMap(who, 95.0f, true)) { - Froid++; - if (Froid == 50) - SpawnGele(); + AttackStart(who); + } + + ScriptedAI::MoveInLineOfSight(who); + } + + void Aggro(Unit* /*pWho*/) + { + if (m_pInstance) + m_pInstance->SetData(TYPE_VISCIDUS, IN_PROGRESS); + } + + void JustReachedHome() + { + if (m_pInstance) + m_pInstance->SetData(TYPE_VISCIDUS, FAIL); + + DoCastSpellIfCan(m_creature, SPELL_DESPAWN_GLOBS, CAST_TRIGGERED); + } + + void JustDied(Unit* /*pKiller*/) + { + if (m_pInstance) + m_pInstance->SetData(TYPE_VISCIDUS, DONE); + } + + void DamageTaken(Unit* pDealer, uint32 &damage) + { + if (pDealer->IsCreature() && ((Creature*)pDealer)->GetEntry() == NPC_VISCIDUS) + return; + + const uint32 uiViscidusHealth = m_creature->GetHealth(); + + if (damage >= uiViscidusHealth) + damage = uiViscidusHealth - 1; + } + + void JustSummoned(Creature* pSummoned) + { + if (pSummoned->GetEntry() == NPC_GLOB_OF_VISCIDUS) + { + float fX, fY, fZ; + m_creature->GetRespawnCoord(fX, fY, fZ); + pSummoned->GetMotionMaster()->MovePoint(1, fX, fY, fZ); + m_lGlobesGuidList.push_back(pSummoned->GetObjectGuid()); + //pSummoned->CastSpell(pSummoned, SPELL_GLOB_SPEED, true); + } + else if (pSummoned->GetEntry() == NPC_VISCIDUS_TRIGGER) + { + pSummoned->CastSpell(pSummoned, SPELL_TOXIN_CLOUD, true); + pSummoned->CastSpell(pSummoned, SPELL_TOXIN, true); } } - void SummonedCreatureJustDied(Creature* unit) + void ResetViscidusState(bool bApplyToxin) { - Vie--; - m_creature->CastSpell(m_creature, SPELL_VISCIDUS_SHRINKS, true); - CheckGele(); + if (m_creature->GetVisibility() == VISIBILITY_OFF) + { + DoCast(m_creature, SPELL_VISCIDUS_TELEPORT, CAST_TRIGGERED); + } + + DoResetThreat(); + m_creature->SetVisibility(VISIBILITY_ON); + m_creature->clearUnitState(UNIT_STAT_DIED); + m_creature->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); + m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); + m_uiPhase = PHASE_NORMAL; + m_uiHitCount = 0; + + SetCombatMovement(true); + + if (bApplyToxin) + { + DoCastSpellIfCan(m_creature, SPELL_TOXIN); + } } - void JustSummoned(Creature* unit) + void SummonedCreatureJustDied(Creature* pSummoned) { - //unit->SetInCombatWithZone(); - unit->GetMotionMaster()->MovePoint(0, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ()); + if (pSummoned->GetEntry() == NPC_GLOB_OF_VISCIDUS) + { + // should be a spell script! + if (DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_SHRINKS_HP, CAST_TRIGGERED) == CAST_OK) + { + auto health = m_creature->GetHealth() - static_cast((m_creature->GetMaxHealth() * 0.05f)); + + if (health && health <= m_creature->GetMaxHealth()) + { + m_creature->SetHealth(health); + } + else + { + m_creature->SetHealthPercent(1.0f); + } + } + + m_lGlobesGuidList.remove(pSummoned->GetObjectGuid()); + + if (m_lGlobesGuidList.empty()) + { + ResetViscidusState(true); + } + } } - void SummonedMovementInform(Creature* summoned, uint32 motion_type, uint32 point_id) + void SummonedMovementInform(Creature* pSummoned, uint32 uiType, uint32 uiPointId) { - summoned->ForcedDespawn(); - m_creature->SetHealth(m_creature->GetHealth() + m_creature->GetMaxHealth() / 20); - CheckGele(); - } - - void CheckGele() - { - if (m_creature->FindNearestCreature(NPC_GLOB_OF_VISCIDUS, 150.0f)) + if (pSummoned->GetEntry() != NPC_GLOB_OF_VISCIDUS || uiType != POINT_MOTION_TYPE || !uiPointId) return; - Froid = 0; - Gele = false; - Visible = true; - m_creature->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, false); + m_lGlobesGuidList.remove(pSummoned->GetObjectGuid()); + pSummoned->CastSpell(m_creature, SPELL_REJOIN_VISCIDUS, true); + pSummoned->ForcedDespawn(1000); + ++m_uiGrowCount; // should be done in spell script + + if (m_lGlobesGuidList.empty()) + { + ResetViscidusState(true); + } } void SpellHit(Unit* pCaster, const SpellEntry* pSpell) { - if (pSpell->School == SPELL_SCHOOL_FROST && Gele == false) + if (pSpell->Id == SPELL_VISCIDUS_EXPLODE) { - Froid++; - if (Froid >= 200) + // suicide if required + if (m_creature->GetHealthPercent() < 5.0f) { - if (DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_FREEZE, CAST_AURA_NOT_PRESENT) == CAST_OK) - { - m_creature->RemoveAurasDueToSpell(SPELL_VISCIDUS_SLOWED_MORE); - Gele = true; - Froid = 0; - m_creature->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, true); - } + m_creature->SetVisibility(VISIBILITY_ON); + + if (DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_SUICIDE, CAST_TRIGGERED) == CAST_OK) + m_creature->DealDamage(m_creature, m_creature->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NONE, nullptr, false); + + return; } - else if (Froid >= 140) + + DoScriptText(EMOTE_EXPLODE, m_creature); + m_uiPhase = PHASE_EXPLODED; + m_lGlobesGuidList.clear(); + uint32 uiGlobeCount = m_creature->GetHealthPercent() / 5.0f; + + for (uint8 i = 0; i < uiGlobeCount; ++i) + DoCastSpellIfCan(m_creature, auiGlobSummonSpells[i], CAST_TRIGGERED); + + m_creature->RemoveAurasDueToSpell(SPELL_TOXIN); + m_creature->RemoveAurasDueToSpell(SPELL_VISCIDUS_FREEZE); + m_uiExplodeDelayTimer = 1000; + return; + } + + if (m_uiPhase != PHASE_NORMAL) + return; + + bool bIsFrostSpell = pSpell->School == SPELL_SCHOOL_FROST; + + // wand special case: + // shoot's school is physical, as long we get a SpellEntry, + // we need to check the caster currently equiped wand + // if it's frost damage, use a trigger spell + if (pSpell->Id == SPELL_WAND_SHOOT) + { + const Player* pPlayer = dynamic_cast(pCaster); + if (!pPlayer) + return; + + const Item* pItem = pPlayer->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); + if (!pItem) + return; + + const ItemPrototype* pProto = pItem->GetProto(); + + // Wand always have 1 damage type on vanilla + bIsFrostSpell = pProto->Damage[0].DamageType == SPELL_SCHOOL_FROST; + } + + if (bIsFrostSpell) + { + ++m_uiHitCount; + + if (m_uiHitCount >= HITCOUNT_FREEZE) { - if (DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_SLOWED_MORE, CAST_AURA_NOT_PRESENT) == CAST_OK) - m_creature->RemoveAurasDueToSpell(SPELL_VISCIDUS_SLOWED); + m_uiPhase = PHASE_FROZEN; + m_uiHitCount = 0; + + DoScriptText(EMOTE_FROZEN, m_creature); + m_creature->RemoveAurasDueToSpell(SPELL_VISCIDUS_SLOWED_MORE); + DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_FREEZE, CAST_TRIGGERED); + } + else if (m_uiHitCount >= HITCOUNT_SLOW_MORE) + { + if (m_uiHitCount == HITCOUNT_SLOW_MORE) + { + DoScriptText(EMOTE_FREEZE, m_creature); + m_creature->RemoveAurasDueToSpell(SPELL_VISCIDUS_SLOWED); + } + DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_SLOWED_MORE, CAST_TRIGGERED); + } + else if (m_uiHitCount >= HITCOUNT_SLOW) + { + if (m_uiHitCount == HITCOUNT_SLOW) + { + DoScriptText(EMOTE_SLOW, m_creature); + } + DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_SLOWED, CAST_TRIGGERED); } - else if (Froid >= 70) - DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_SLOWED, CAST_AURA_NOT_PRESENT); } } - void SpawnGele() + void ResetFrozenPhase() { - m_creature->CastSpell(m_creature, SPELL_VISCIDUS_EXPLODE, true); - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; - float o = 0.0f; - m_creature->GetRespawnCoord(x, y, z); - for (int i = 0; i < Vie; i++) + if (m_uiPhase == PHASE_EXPLODED) + return; + + DoCastSpellIfCan(m_creature, SPELL_TOXIN); + + // reset phase if not already exploded + m_uiPhase = PHASE_NORMAL; + m_uiHitCount = 0; + } + + void HackyScaleUpdate() + { + auto hp = static_cast(m_creature->GetHealthPercent() / 5); + + if (hp != track.size() && !track.test(hp)) { - float ang = M_PI_F * 2 * i / 20; - float X = x + 70 * cos(ang); - float Y = y + 70 * sin(ang); - float Z = z + 5.0f; - m_creature->CastSpell(X, Y, Z, 25865 + i, true); + track.set(hp); + m_creature->CastSpell(m_creature, SPELL_VISCIDUS_SHRINKS, true); } - InvisibleTimer = 5000; - Froid = 0; - Gele = false; - } - - void KilledUnit(Unit* pVictim) - { - } - - void JustDied(Unit* pKiller) - { - } - - bool IsVisibleFor(Unit const* pOther, bool &isVisible) const - { - isVisible = Visible; - return true; } void UpdateAI(const uint32 uiDiff) { - if (InvisibleTimer > 0) - { - if (InvisibleTimer <= uiDiff) - { - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; - float o = 0.0f; - m_creature->GetRespawnCoord(x, y, z); - m_creature->Relocate(x, y, z, o); - m_creature->SetHealth(1); - Visible = false; - InvisibleTimer = 0; - } - else InvisibleTimer -= uiDiff; - return; - } - - if (Visible == false || Gele == true) - return; - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; - if (SalveToxiqueTimer < uiDiff) - { - if (DoCastSpellIfCan(m_creature, SPELL_POISONBOLT_VOLLEY) == CAST_OK) - SalveToxiqueTimer = 11000; - } - else SalveToxiqueTimer -= uiDiff; + HackyScaleUpdate(); - if (HorionEmpoisonneTimer < uiDiff) + // should be spell scripted properly + if (m_uiGrowTimer <= uiDiff) + { + + if (m_uiGrowCount) + { + DoCastSpellIfCan(m_creature, SPELL_VISCIDUS_GROWS, CAST_TRIGGERED); + m_creature->SetObjectScale(m_creature->GetObjectScale() + 0.04f); + --m_uiGrowCount; + } + m_uiGrowTimer = 150; + } + else + m_uiGrowTimer -= uiDiff; + + if (m_uiExplodeDelayTimer) + { + if (m_uiExplodeDelayTimer <= uiDiff) + { + // Make invisible + m_creature->SetVisibility(VISIBILITY_OFF); + m_uiExplodeDelayTimer = 0; + + // should be part of SPELL_VISCIDUS_SHRINKS_HP script! + auto scale = m_creature->GetObjectScale(); + scale -= 0.04 * m_lGlobesGuidList.size(); + m_creature->SetObjectScale(scale); + } + else + m_uiExplodeDelayTimer -= uiDiff; + } + + if (m_uiPhase != PHASE_NORMAL) + return; + + if (m_uiPoisonShockTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_POISON_SHOCK) == CAST_OK) - HorionEmpoisonneTimer = 7000; + m_uiPoisonShockTimer = urand(7000, 12000); } - else HorionEmpoisonneTimer -= uiDiff; + else + m_uiPoisonShockTimer -= uiDiff; - if (FlaqueTimer < uiDiff) + if (m_uiPoisonBoltVolleyTimer < uiDiff) { - if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) + if (DoCastSpellIfCan(m_creature, SPELL_POISONBOLT_VOLLEY) == CAST_OK) + m_uiPoisonBoltVolleyTimer = urand(10000, 15000); + } + else + m_uiPoisonBoltVolleyTimer -= uiDiff; + + if (m_uiToxinTimer < uiDiff) + { + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) { - if (DoCastSpellIfCan(pTarget, SPELL_TOXIN_SUMMON) == CAST_OK) - FlaqueTimer = 9000; + m_creature->SummonCreature(NPC_VISCIDUS_TRIGGER, pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), pTarget->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 180000); + m_uiToxinTimer = 30000; } } - else FlaqueTimer -= uiDiff; + else + m_uiToxinTimer -= uiDiff; DoMeleeAttackIfReady(); + + EnterEvadeIfOutOfCombatArea(uiDiff); } }; @@ -242,23 +449,58 @@ CreatureAI* GetAI_boss_viscidus(Creature* pCreature) return new boss_viscidusAI(pCreature); } -struct boss_glob_of_viscidusAI : public ScriptedAI +bool EffectAuraDummy_spell_aura_dummy_viscidus_freeze(const Aura* pAura, bool bApply) { - boss_glob_of_viscidusAI(Creature* pCreature) : ScriptedAI(pCreature) + // On Aura removal inform the boss + if (pAura->GetId() == SPELL_VISCIDUS_FREEZE && pAura->GetEffIndex() == EFFECT_INDEX_1 && !bApply) { + if (Creature* pTarget = (Creature*)pAura->GetTarget()) + { + if (boss_viscidusAI* pViscidusAI = dynamic_cast(pTarget->AI())) + pViscidusAI->ResetFrozenPhase(); + } } + return true; +} - void AttackStart(Unit *) {} - void AttackedBy(Unit *) {} +// TODO Remove these 'script' when combat can be proper prevented from core-side +struct ViscidusNullAI : public ScriptedAI +{ + // Hacky timer to work around a core issue + const uint16_t GLOB_SPEED_INTERVAL = 1000; - void Reset() + uint16 m_uiGlobSpeedTimer = 0; + float speed = 1.0f; + + ViscidusNullAI(Creature* pCreature) : ScriptedAI(pCreature) { } + + void Reset() { } + + void AttackStart(Unit* /*pWho*/) { } + void MoveInLineOfSight(Unit* /*pWho*/) { } + void UpdateAI(const uint32 uiDiff) { + if (m_uiGlobSpeedTimer <= uiDiff) + { + speed += 1.50f; + m_creature->UpdateSpeed(MOVE_WALK, true, speed); + m_uiGlobSpeedTimer = GLOB_SPEED_INTERVAL; + } + else + { + m_uiGlobSpeedTimer -= uiDiff; + } } }; CreatureAI* GetAI_boss_glob_of_viscidus(Creature* pCreature) { - return new boss_glob_of_viscidusAI(pCreature); + return new ViscidusNullAI(pCreature); +} + +CreatureAI* GetAI_boss_viscidus_trigger(Creature* pCreature) +{ + return new ViscidusNullAI(pCreature); } void AddSC_boss_viscidus() @@ -268,10 +510,16 @@ void AddSC_boss_viscidus() pNewScript = new Script; pNewScript->Name = "boss_viscidus"; pNewScript->GetAI = &GetAI_boss_viscidus; + pNewScript->pEffectAuraDummy = &EffectAuraDummy_spell_aura_dummy_viscidus_freeze; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "boss_glob_of_viscidus"; pNewScript->GetAI = &GetAI_boss_glob_of_viscidus; pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "boss_viscidus_trigger"; + pNewScript->GetAI = &GetAI_boss_glob_of_viscidus; + pNewScript->RegisterSelf(); } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/instance_temple_of_ahnqiraj.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/instance_temple_of_ahnqiraj.cpp index 0e40da48a..4543d5eaf 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/instance_temple_of_ahnqiraj.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/instance_temple_of_ahnqiraj.cpp @@ -27,8 +27,126 @@ EndScriptData */ #include "scriptPCH.h" #include "temple_of_ahnqiraj.h" -instance_temple_of_ahnqiraj::instance_temple_of_ahnqiraj(Map* pMap) : ScriptedInstance_PTR(pMap), - m_uiBugTrioDeathCount(0) +static constexpr uint32 CTHUN_WHISPER_MUTE_DURATION = 60000 * 10; +static constexpr uint32 CTHUN_FIRST_WHISPER = 90000; +static constexpr uint32 CTHUN_WHISPER_FREQ_MIN = 30000; +static constexpr uint32 CTHUN_WHISPER_FREQ_MAX = 60000; + +enum eTwinsDeathTexts { + SAY_VEKLOR_DEATH = -1531024, //my brother...nO! + SAY_VEKNILASH_DEATH = -1531031 // Vek'loor, i feel your pain! +}; +static const SIDialogueEntry twinsDeathDialogue[] = +{ + { SAY_VEKNILASH_DEATH, NPC_VEKNILASH, 3000 }, //todo: 3000 is just a guess + { SAY_VEKLOR_DEATH, NPC_VEKLOR, 0 }, + { 0, 0, 0 } +}; + +enum eTwinsDialogueEntries +{ + EMOTE_EYE_INTRO = -1531012, + EVENT_EYE_TURN_AROUND = 1, + EVENT_EMPERORS_RISE = 2, + SAY_EMPERORS_INTRO_1 = -1531013, // Only flesh and bone. .. + SAY_EMPERORS_INTRO_2 = -1531014, // Where are your manners... + SAY_EMPERORS_INTRO_3 = -1531015, // There will be pain... + SAY_EMPERORS_INTRO_4 = -1531016, // Oh so much pain... + SAY_EMPERORS_INTRO_5 = -1531017, // Come, little ones... + SAY_EMPERORS_INTRO_6 = -1531018, // The feast of souls... +}; + +// Sources: +// https://www.youtube.com/watch?v=anDqSl-_y9Y +// https://www.youtube.com/watch?v=drIsWEJkkHs +// Before start: The eye should be turned away from the trigger, and emperors should be kneeling. +// +0: Trigger reached - emote happens +// +2: The eye turns around and the emperors rise up to standing state. +// +7: The eye despawns and emperors begins the dialogue +static const SIDialogueEntry aIntroDialogue[] = +{ + { EMOTE_EYE_INTRO, NPC_MASTERS_EYE, 2000 }, // Trigger reached, emote happens. last 2 seconds + { EVENT_EYE_TURN_AROUND, NPC_MASTERS_EYE, 1000 }, // Eye turns around, + { EVENT_EMPERORS_RISE, NPC_MASTERS_EYE, 5000 }, // emperors rise up one second later + { SAY_EMPERORS_INTRO_1, NPC_VEKLOR, 7000 }, // Eye despawns, first line of dialogue 5 seconds later + { SAY_EMPERORS_INTRO_2, NPC_VEKNILASH, 8000 }, + { SAY_EMPERORS_INTRO_3, NPC_VEKLOR, 3000 }, + { SAY_EMPERORS_INTRO_4, NPC_VEKNILASH, 3000 }, + { SAY_EMPERORS_INTRO_5, NPC_VEKLOR, 3000 }, + { SAY_EMPERORS_INTRO_6, NPC_VEKNILASH, 0 }, + { 0, 0, 0 } +}; +TwinsIntroDialogue::TwinsIntroDialogue() : + DialogueHelper(aIntroDialogue), + m_StartedOrDone(false) +{ + +} + +void TwinsIntroDialogue::Start() +{ + m_StartedOrDone = true; + if (!m_pInstance) { + sLog.outError("TwinsIntroDialogue missing instance. Cannot start."); + return; + } + Creature* pEye = m_pInstance->GetSingleCreatureFromStorage(NPC_MASTERS_EYE); + Creature* pVL = m_pInstance->GetSingleCreatureFromStorage(NPC_VEKLOR); + Creature* pVN = m_pInstance->GetSingleCreatureFromStorage(NPC_VEKNILASH); + + // If we're missing one of the creatures needed in this little event, we just skip it. + if (!pEye || !pVL || !pVN) { + sLog.outError("Missing one or more of the required creatures to start TwinsIntroDialogue. Not starting."); + if (pEye) + pEye->ForcedDespawn(1000); + return; + } + StartNextDialogueText(EMOTE_EYE_INTRO); +} + +bool TwinsIntroDialogue::StartedOrDone() +{ + return m_StartedOrDone; +} + +void TwinsIntroDialogue::SetDone() +{ + m_StartedOrDone = true; +} + +void TwinsIntroDialogue::JustDidDialogueStep(int32 iEntry) +{ + Creature* pEye = m_pInstance->GetSingleCreatureFromStorage(NPC_MASTERS_EYE); + Creature* pVL = m_pInstance->GetSingleCreatureFromStorage(NPC_VEKLOR); + Creature* pVN = m_pInstance->GetSingleCreatureFromStorage(NPC_VEKNILASH); + // If we at any point are missing one of the creatures we skip to the end and stop. + if (!pEye || !pVL || !pVN) { + sLog.outError("Missing one or more of the required creatures in TwinsIntroDialogue::JustDidDialogueStep()"); + return; + } + switch (iEntry) { + case EMOTE_EYE_INTRO: + + break; + case EVENT_EYE_TURN_AROUND: + pEye->SetFacingTo(1.57f); + break; + case EVENT_EMPERORS_RISE: + pVL->SetStandState(UNIT_STAND_STATE_STAND); + pVN->SetStandState(UNIT_STAND_STATE_STAND); + break; + case SAY_EMPERORS_INTRO_1: + pEye->ForcedDespawn(1); // Will look like a death to gm, but fade out for players + break; + } +} + +instance_temple_of_ahnqiraj::instance_temple_of_ahnqiraj(Map* pMap) : + ScriptedInstance(pMap), + m_uiBugTrioDeathCount(0), + m_uiCthunWhisperTimer(CTHUN_FIRST_WHISPER), + m_uiCthunPrevWhisperTimer(CTHUN_FIRST_WHISPER), + m_twinsDeadDialogue(twinsDeathDialogue) { Initialize(); }; @@ -36,6 +154,9 @@ instance_temple_of_ahnqiraj::instance_temple_of_ahnqiraj(Map* pMap) : ScriptedIn void instance_temple_of_ahnqiraj::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); + + m_twinsIntroDialogue.InitializeDialogueHelper(this); + m_twinsDeadDialogue.InitializeDialogueHelper(this); } bool instance_temple_of_ahnqiraj::IsEncounterInProgress() const @@ -49,72 +170,105 @@ bool instance_temple_of_ahnqiraj::IsEncounterInProgress() const return false; } +void instance_temple_of_ahnqiraj::DoHandleTempleAreaTrigger(uint32 uiTriggerId) +{ + if (uiTriggerId == AREATRIGGER_TWIN_EMPERORS && !TwinsDialogueStartedOrDone()) + { + // Current assumption is the event only start once every soft reset. + // May need to tweak if-statement to make sure this is the case. + m_twinsIntroDialogue.Start(); + } + else if (uiTriggerId == AREATRIGGER_SARTURA) + { + if (GetData(TYPE_SARTURA) == NOT_STARTED || GetData(TYPE_SARTURA) == FAIL) + { + if (Creature* pSartura = GetSingleCreatureFromStorage(NPC_BATTLEGUARD_SARTURA)) + pSartura->SetInCombatWithZone(); + } + } +} + void instance_temple_of_ahnqiraj::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { - case GO_SKERAM_GATE: - if (m_auiEncounter[TYPE_SKERAM] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); - break; - case GO_TWINS_ENTER_DOOR: - if (m_auiEncounter[TYPE_HUHURAN] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); - break; - case GO_TWINS_EXIT_DOOR: - if (m_auiEncounter[TYPE_TWINS] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); - break; - - default: - return; + case GO_SKERAM_GATE: + if (m_auiEncounter[TYPE_SKERAM] == DONE) + pGo->UseDoorOrButton(0, false); + break; + case GO_TWINS_ENTER_DOOR: + if (m_auiEncounter[TYPE_HUHURAN] == DONE) + pGo->UseDoorOrButton(0, false); + break; + case GO_TWINS_EXIT_DOOR: + if (m_auiEncounter[TYPE_TWINS] == DONE) + pGo->UseDoorOrButton(0, false); + break; + case GO_GRASP_OF_CTHUN: + graspsOfCthun.push_back(pGo->GetObjectGuid()); + if (m_auiEncounter[TYPE_CTHUN] == DONE) { + pGo->SetVisible(false); + } + break; + default: + return; } - - m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); + m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_temple_of_ahnqiraj::OnCreatureRespawn(Creature* pCreature) { switch (pCreature->GetEntry()) { - case NPC_ANUBISATH_SENTINEL: - case NPC_OBSIDIAN_ERADICATOR: - if (m_auiEncounter[TYPE_SKERAM] == DONE) - pCreature->AddObjectToRemoveList(); - break; - case NPC_QIRAJI_BRAINWASHER: - case NPC_VEKNISS_GUARDIAN: - case NPC_VEKNISS_WARRIOR: - case NPC_SARTURA_S_ROYAL_GUARD: - if (m_auiEncounter[TYPE_SARTURA] == DONE) - pCreature->AddObjectToRemoveList(); - break; - case NPC_VEKNISS_DRONE: - case NPC_VEKNISS_SOLDIER: - if (m_auiEncounter[TYPE_FANKRISS] == DONE) - pCreature->AddObjectToRemoveList(); - break; - case NPC_VEKNISS_HIVE_CRAWLER: - case NPC_VEKNISS_WASP: - case NPC_QIRAJI_LASHER: - case NPC_VEKNISS_STINGER: - if (m_auiEncounter[TYPE_HUHURAN] == DONE) - pCreature->AddObjectToRemoveList(); - break; - case NPC_ANUBISATH_DEFENDER: - case NPC_QIRAJI_SCARAB: - case NPC_QIRAJI_SCORPION: - if (m_auiEncounter[TYPE_TWINS] == DONE) - pCreature->AddObjectToRemoveList(); - break; - case NPC_QIRAJI_MINDSLAYER: - case NPC_QIRAJI_SLAYER: - case NPC_QIRAJI_CHAMPION: - case NPC_ANUBISATH_WARDER: - case NPC_OBSIDIAN_NULLIFIER: - if (m_auiEncounter[TYPE_C_THUN] == DONE) - pCreature->AddObjectToRemoveList(); - break; + case NPC_ANUBISATH_SENTINEL: + case NPC_OBSIDIAN_ERADICATOR: + if (m_auiEncounter[TYPE_SKERAM] == DONE) + pCreature->AddObjectToRemoveList(); + break; + case NPC_QIRAJI_BRAINWASHER: + case NPC_VEKNISS_GUARDIAN: + case NPC_VEKNISS_WARRIOR: + case NPC_SARTURA_S_ROYAL_GUARD: + if (m_auiEncounter[TYPE_SARTURA] == DONE) + pCreature->AddObjectToRemoveList(); + break; + case NPC_VEKNISS_DRONE: + case NPC_VEKNISS_SOLDIER: + if (m_auiEncounter[TYPE_FANKRISS] == DONE) + pCreature->AddObjectToRemoveList(); + break; + case NPC_VEKNISS_HIVE_CRAWLER: + case NPC_VEKNISS_WASP: + case NPC_QIRAJI_LASHER: + case NPC_VEKNISS_STINGER: + if (m_auiEncounter[TYPE_HUHURAN] == DONE) + pCreature->AddObjectToRemoveList(); + break; + case NPC_ANUBISATH_DEFENDER: + case NPC_QIRAJI_SCARAB: + case NPC_QIRAJI_SCORPION: + if (m_auiEncounter[TYPE_TWINS] == DONE) + pCreature->AddObjectToRemoveList(); + break; + case NPC_OURO_SCARAB: + if (m_auiEncounter[TYPE_OURO] != IN_PROGRESS) + pCreature->AddObjectToRemoveList(); + break; + case NPC_QIRAJI_MINDSLAYER: + case NPC_QIRAJI_SLAYER: + case NPC_QIRAJI_CHAMPION: + case NPC_ANUBISATH_WARDER: + case NPC_OBSIDIAN_NULLIFIER: + if (m_auiEncounter[TYPE_CTHUN] == DONE) + pCreature->AddObjectToRemoveList(); + break; + case NPC_MASTERS_EYE: + // Despawn C'thun eye at twins if twins are already dead + if (TwinsDialogueStartedOrDone()) { + pCreature->AddObjectToRemoveList(); + //pCreature->ForcedDespawn(1); + } + break; } } @@ -122,35 +276,42 @@ void instance_temple_of_ahnqiraj::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { - case NPC_PRINCESS_YAUJ: - case NPC_VEM: - case NPC_KRI: - case NPC_BATTLEGUARD_SARTURA: - case NPC_VEKLOR: - case NPC_VEKNILASH: - case NPC_EYE_OF_C_THUN: - case NPC_CTHUN: - case NPC_CTHUN_PORTAL: - m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid(); - break; - // Randomize C'thun trash packs - case NPC_QIRAJI_SLAYER: - if (urand(0, 1)) - { - pCreature->SetEntry(15246); - pCreature->UpdateEntry(15246); - pCreature->AIM_Initialize(); - } - break; - case NPC_QIRAJI_MINDSLAYER: - if (urand(0, 1)) - { - pCreature->SetEntry(15250); - pCreature->UpdateEntry(15250); - pCreature->AIM_Initialize(); - } - break; - case NPC_SARTURA_S_ROYAL_GUARD: m_lRoyalGuardGUIDList.push_back(pCreature->GetObjectGuid()); break; + case NPC_PRINCESS_YAUJ: + case NPC_VEM: + case NPC_KRI: + case NPC_BATTLEGUARD_SARTURA: + case NPC_VEKLOR: + case NPC_VEKNILASH: + case NPC_EYE_OF_C_THUN: + case NPC_CTHUN: + case NPC_MASTERS_EYE: + case NPC_OURO_SPAWNER: + case NPC_CTHUN_PORTAL: + m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid(); + break; + case NPC_QIRAJI_SLAYER: // Randomize C'thun trash packs + + if (urand(0, 1)) + { + pCreature->SetEntry(15246); + pCreature->UpdateEntry(15246); + pCreature->AIM_Initialize(); + } + break; + case NPC_QIRAJI_MINDSLAYER: + if (urand(0, 1)) + { + pCreature->SetEntry(15250); + pCreature->UpdateEntry(15250); + pCreature->AIM_Initialize(); + } + break; + case NPC_SARTURA_S_ROYAL_GUARD: + m_lRoyalGuardGUIDList.push_back(pCreature->GetObjectGuid()); + break; + case NPC_CAELESTRASZ: + pCreature->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP); + break; } // Delete some creatures OnCreatureRespawn(pCreature); @@ -160,46 +321,77 @@ void instance_temple_of_ahnqiraj::SetData(uint32 uiType, uint32 uiData) { switch (uiType) { - case TYPE_SKERAM: - m_auiEncounter[uiType] = uiData; - if (uiData == DONE) - DoUseDoorOrButton(GO_SKERAM_GATE); - break; - case TYPE_BUG_TRIO: - if (uiData == SPECIAL) - { - ++m_uiBugTrioDeathCount; - if (m_uiBugTrioDeathCount == 2) - SetData(TYPE_BUG_TRIO, DONE); - // don't store any special data - break; - } - if (uiData == FAIL) - m_uiBugTrioDeathCount = 0; - m_auiEncounter[uiType] = uiData; - break; - case TYPE_HUHURAN: - m_auiEncounter[uiType] = uiData; - if (uiData == DONE) - DoUseDoorOrButton(GO_TWINS_ENTER_DOOR); - break; - case TYPE_SARTURA: - case TYPE_FANKRISS: - case TYPE_VISCIDUS: - case TYPE_CTHUN_PHASE: - m_auiEncounter[uiType] = uiData; + case TYPE_SKERAM: + m_auiEncounter[uiType] = uiData; + if (uiData == DONE) { + if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_SKERAM_GATE)) + DoOpenDoor(pGo->GetGUID()); + } + break; + case TYPE_BUG_TRIO: + if (uiData == SPECIAL) + { + ++m_uiBugTrioDeathCount; + if (m_uiBugTrioDeathCount == 2) + SetData(TYPE_BUG_TRIO, DONE); + // don't store any special data break; - case TYPE_TWINS: - // Either of the twins can set data, so return to avoid double changing - if (m_auiEncounter[uiType] == uiData) - return; - - m_auiEncounter[uiType] = uiData; - DoUseDoorOrButton(GO_TWINS_ENTER_DOOR); - if (uiData == DONE) - DoUseDoorOrButton(GO_TWINS_EXIT_DOOR); + } + if (uiData == FAIL) + m_uiBugTrioDeathCount = 0; + m_auiEncounter[uiType] = uiData; + break; + case TYPE_SARTURA: + case TYPE_FANKRISS: + case TYPE_VISCIDUS: + m_auiEncounter[uiType] = uiData; + break; + case TYPE_HUHURAN: + m_auiEncounter[uiType] = uiData; + if (uiData == DONE) { + if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_TWINS_ENTER_DOOR)) + DoOpenDoor(pGo->GetGUID()); + } + break; + case TYPE_TWINS: + // Either of the twins can set data, so return to avoid double changing + if (m_auiEncounter[uiType] == uiData) + return; + m_auiEncounter[uiType] = uiData; + if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_TWINS_ENTER_DOOR)) { + if (uiData == IN_PROGRESS) { + DoResetDoor(pGo->GetGUID()); + } + else { + DoOpenDoor(pGo->GetGUID()); + } + } + if (uiData == DONE) { + if (GameObject* pGo = GetSingleGameObjectFromStorage(GO_TWINS_EXIT_DOOR)) { + DoOpenDoor(pGo->GetGUID()); + } + m_twinsDeadDialogue.StartNextDialogueText(SAY_VEKNILASH_DEATH); + } + break; + case TYPE_OURO: + switch (uiData) + { + case FAIL: + // Respawn the Ouro spawner on fail + if (Creature* pSpawner = GetSingleCreatureFromStorage(NPC_OURO_SPAWNER)) + pSpawner->Respawn(); break; - + } + m_auiEncounter[uiType] = uiData; + break; + case TYPE_CTHUN: + m_auiEncounter[uiType] = uiData; + for (auto it = graspsOfCthun.begin(); it != graspsOfCthun.end(); it++) { + if (GameObject* pGo = GetGameObject(*it)) { + pGo->SetVisible(uiData != DONE); + } + } + break; } if (uiData == DONE) @@ -207,7 +399,7 @@ void instance_temple_of_ahnqiraj::SetData(uint32 uiType, uint32 uiData) OUT_SAVE_INST_DATA; std::ostringstream saveStream; - for (int i = 0; i < MAX_ENCOUNTER; ++i) + for (int i = 0; i < MAX_ENCOUNTER; ++i) saveStream << m_auiEncounter[i] << " "; m_strInstData = saveStream.str(); @@ -228,53 +420,458 @@ void instance_temple_of_ahnqiraj::Load(const char* chrIn) OUT_LOAD_INST_DATA(chrIn); std::istringstream loadStream(chrIn); - for (int i = 0; i < MAX_ENCOUNTER; ++i) + for (int i = 0; i < MAX_ENCOUNTER; ++i) { loadStream >> m_auiEncounter[i]; if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } - m_auiEncounter[TYPE_CTHUN_PHASE] = 0; - + + if (m_auiEncounter[TYPE_TWINS] == DONE) { + m_twinsIntroDialogue.SetDone(); + } + OUT_LOAD_INST_DATA_COMPLETE; } +void instance_temple_of_ahnqiraj::UpdateCThunWhisper(uint32 diff) +{ + uint32 cthunStatus = GetData(TYPE_CTHUN); + if (cthunStatus == DONE) { + return; + } + if (m_uiCthunWhisperTimer >= diff) { + m_uiCthunWhisperTimer -= diff; + return; + } + m_uiCthunWhisperTimer = urand(CTHUN_WHISPER_FREQ_MIN, CTHUN_WHISPER_FREQ_MAX); + + // Updating muted players + for (auto it = cthunWhisperMutes.begin(); it != cthunWhisperMutes.end(); ) { + it->second -= std::min(m_uiCthunPrevWhisperTimer, it->second); + + if (it->second < CTHUN_WHISPER_FREQ_MAX) + it = cthunWhisperMutes.erase(it); + else + ++it; + } + m_uiCthunPrevWhisperTimer = m_uiCthunWhisperTimer; + + if (cthunStatus == IN_PROGRESS) { + return; + } + + Creature* pCthun = GetSingleCreatureFromStorage(NPC_CTHUN); + if (!pCthun) + return; + + std::list candidates; + std::list::iterator j; + const Map::PlayerList& PlayerList = GetMap()->GetPlayers(); + if (PlayerList.isEmpty()) + return; + + for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) + { + if (Player* player = itr->getSource()) + { + if (!player->isDead()) { + auto find_it = std::find_if(cthunWhisperMutes.begin(), cthunWhisperMutes.end(), + [player](const std::pair& e) {return e.first == player->GetObjectGuid(); }); + if (find_it == cthunWhisperMutes.end()) { + candidates.push_back(player); + } + } + } + } + + if (!candidates.size()) + return; + + j = candidates.begin(); + std::advance(j, urand(0, candidates.size() - 1)); + Player* targetPlayer = *j; + // ToDo: also cast the C'thun Whispering charm spell - requires additional research + DoScriptText(irand(SAY_CTHUN_WHISPER_8, SAY_CTHUN_WHISPER_1), pCthun, targetPlayer); + + cthunWhisperMutes.push_back(std::make_pair(targetPlayer->GetGUID(), CTHUN_WHISPER_MUTE_DURATION)); +} + +void instance_temple_of_ahnqiraj::Update(uint32 uiDiff) +{ + m_twinsIntroDialogue.DialogueUpdate(uiDiff); + m_twinsDeadDialogue.DialogueUpdate(uiDiff); + + UpdateCThunWhisper(uiDiff); + + UpdateStomachOfCthun(uiDiff); +} + +bool instance_temple_of_ahnqiraj::TwinsDialogueStartedOrDone() +{ + return m_twinsIntroDialogue.StartedOrDone(); +} + uint32 instance_temple_of_ahnqiraj::GetData(uint32 uiType) { return m_auiEncounter[uiType]; } +bool AreaTrigger_at_temple_ahnqiraj(Player* pPlayer, const AreaTriggerEntry* pAt) +{ + if (pAt->id == AREATRIGGER_TWIN_EMPERORS || pAt->id == AREATRIGGER_SARTURA) + { + if (pPlayer->isGameMaster() || !pPlayer->isAlive()) + return false; + + if (instance_temple_of_ahnqiraj* pInstance = (instance_temple_of_ahnqiraj*)pPlayer->GetInstanceData()) + pInstance->DoHandleTempleAreaTrigger(pAt->id); + } + if (instance_temple_of_ahnqiraj* pInstance = (instance_temple_of_ahnqiraj*)pPlayer->GetInstanceData()) + pInstance->HandleStomachTriggers(pPlayer, pAt); + + return false; +} + +void instance_temple_of_ahnqiraj::AddPlayerToStomach(Unit * p) +{ + p->CastSpell(p, SPELL_DIGESTIVE_ACID, true); + playersInStomach.push_back(std::make_pair(p->GetGUID(), StomachTimers())); +} + +instance_temple_of_ahnqiraj::CThunStomachList::iterator instance_temple_of_ahnqiraj::PlayerInStomachIter(Unit * unit) +{ + if (!unit) return playersInStomach.end(); + + return std::find_if(playersInStomach.begin(), playersInStomach.end(), + [unit](const std::pair& e) { + if (unit->GetObjectGuid() == e.first) { + return true; + } + return false; + }); +} + +void instance_temple_of_ahnqiraj::TeleportPlayerToCThun(Player* pPlayer) +{ + // Player is ported to center of c'thun with a small, random, offset to knock the player in a random direction. + const AreaTriggerEntry* cthunAreaTrigger = sAreaTriggerStore.LookupEntry(AREATRIGGER_CTHUN_KNOCKBACK); + if (cthunAreaTrigger) { + float x = cthunAreaTrigger->x + cos((frand(0.0f, 360.0f)) * (3.14f / 180.0f)) * 0.1f; + float y = cthunAreaTrigger->y + sin((frand(0.0f, 360.0f)) * (3.14f / 180.0f)) * 0.1f; + pPlayer->NearTeleportTo(x, y, cthunAreaTrigger->z, pPlayer->GetOrientation()); + } + else { + float x = -8578.0f + cos((frand(0.0f, 360.0f)) * (3.14f / 180.0f)) * 0.1f; + float y = 1986.8f + sin((frand(0.0f, 360.0f)) * (3.14f / 180.0f)) * 0.1f; + pPlayer->NearTeleportTo(x, y, 100.4f, pPlayer->GetOrientation()); + sLog.outError("instance_temple_of_ahnqiraj::HandleStomachTriggers attempted to lookup area trigger %d, but it was not found.", + AREATRIGGER_CTHUN_KNOCKBACK); + } +} + +void instance_temple_of_ahnqiraj::PerformCthunKnockback() +{ + const AreaTriggerEntry* pAt = sAreaTriggerStore.LookupEntry(AREATRIGGER_CTHUN_KNOCKBACK); + float x, y, z; + if (pAt) { + x = pAt->x; + y = pAt->y; + z = pAt->z; + } + else { + x = -8578.0f; + y = 1986.8f; + z = 100.22f; + } + if (Creature* kbCreature = GetMap()->SummonCreature(EXIT_KNOCKBACK_CREATURE, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN, 1000)) { + kbCreature->CastSpell(kbCreature, SPELL_EXIT_STOMACH_KNOCKBACK, false); + } +} + +bool instance_temple_of_ahnqiraj::PlayerInStomach(Unit * unit) +{ + if (!unit) return false; + + return PlayerInStomachIter(unit) != playersInStomach.end(); +} + +void instance_temple_of_ahnqiraj::HandleStomachTriggers(Player * pPlayer, const AreaTriggerEntry * pAt) +{ + if (!pPlayer) return; + if (pPlayer->isGameMaster() || !pPlayer->isAlive()) + return; + + if (pAt->id == AREATRIGGER_STOMACH_GROUND) { + if (!puntCreatureGuid) { + if (Creature* pc = GetMap()->SummonCreature(PUNT_CREATURE, pAt->x, pAt->y, pAt->z, 0, + TEMPSUMMON_TIMED_DESPAWN, 4000)) { + puntCreatureGuid = pc->GetGUID(); + quakeTimer = 1000; + puntCountdown = StomachTimers::PUNT_CAST_TIME; + // Since this is the wrong spell, and it deals damage, we send the visual only, instead of casting it. + pc->SendSpellGo(pc, SPELL_QUAKE); + + } + } + } + else if (pAt->id == AREATRIGGER_STOMACH_AIR) { + TeleportPlayerToCThun(pPlayer); + } + else if (pAt->id == AREATRIGGER_CTHUN_KNOCKBACK) { + // "Disable" the knockback if c'thun is killed + if (GetData(TYPE_CTHUN) != DONE) { + PerformCthunKnockback(); + // If the areatrigger was triggered by a player who was ported from stomach + // we find his timer object and set didKnockback to true, to avoid double-knockback + // in the UpdateStomachOfCthun function + auto it = PlayerInStomachIter(pPlayer); + if (it != playersInStomach.end() && !it->second.didKnockback) { + it->second.didKnockback = true; + } + } + } +} + +bool instance_temple_of_ahnqiraj::KillPlayersInStomach() +{ + for (auto iter = playersInStomach.begin(); iter != playersInStomach.end();) { + if (Player* p = GetMap()->GetPlayer(iter->first)) { + // Not killing people with god on, makes debugging easier + if (p->IsGod()) { + ++iter; + continue; + } + + if (p->isAlive()) { + p->KillPlayer(); + } + if (p->HasAura(SPELL_DIGESTIVE_ACID)) { + p->RemoveAurasDueToSpell(SPELL_DIGESTIVE_ACID); + } + } + iter = playersInStomach.erase(iter); + } + + return playersInStomach.size() == 0; +} + +void instance_temple_of_ahnqiraj::UpdateStomachOfCthun(uint32 diff) +{ + // Update the punt creature + if (Creature* pc = GetMap()->GetCreature(puntCreatureGuid)) { + // Updating animation + if (quakeTimer < diff) { + pc->SendSpellGo(pc, SPELL_QUAKE); + quakeTimer = 1000; + } + else { + quakeTimer -= diff; + } + //Checking if it's time to punt + if (puntCountdown < diff) { + pc->CastSpell(pc, SPELL_PUNT_UPWARD, true); + puntCountdown = std::numeric_limits::max(); + puntCreatureGuid = 0; + } + else { + puntCountdown -= diff; + } + } + else { + puntCreatureGuid = 0; + } + + // Update the players in the stomach + if (playersInStomach.empty()) return; + + const AreaTriggerEntry* pot = sAreaTriggerStore.LookupEntry(AREATRIGGER_STOMACH_AIR); + for (auto it = playersInStomach.begin(); it != playersInStomach.end();) { + Player* player = GetMap()->GetPlayer(it->first); + //Player has left instance or something and we remove him from the list. + if (!player) { + it = playersInStomach.erase(it); + continue; + } + + StomachTimers& timers = it->second; + timers.timeSincePortedToStomach += diff; + + // playerPositionZ > 0.0 (stomach teleport-out trigger is at ~-30.0f, c'thun is at ~100.f) + // means the player is outside the stomach as far as the server is concerned. + if (player->GetPositionZ() > 0.0f) + { + // timeSincePortedToStomach prevents the player from being removed from stomach on first + // update after being TPed to the stomach, as the server might not realize the player + // has been teleported during the same update that TeleportPlayerToCThun is called + if (timers.timeSincePortedToStomach > 4000) + { + if (player->HasAura(SPELL_DIGESTIVE_ACID)) + { + player->RemoveAurasDueToSpell(SPELL_DIGESTIVE_ACID); + } + + // HandleStomachTriggers() might be first to the party and perform the knockback, + // in which case we skip it here. We also use timeSincePortedFromStomach > 0 to delay + // the knockback one server-update, as it seems the knockback might not always hit + // if it's cast on the same update as the player is ported. + if (!timers.didKnockback && timers.timeSincePortedFromStomach > 0) + { + PerformCthunKnockback(); + timers.didKnockback = true; + } + else + { + timers.timeSincePortedFromStomach += diff; + } + + // ~1.5 sec after being registered as outside the stomach, we remove the player from the list. + // The delay will prevent tentacles to spawn in the center of c'thun through extremely bad luck, should + // c'thun attempt to spawn a tentacle on the player just as he is TPed out, before the knockback. + if (it->second.timeSincePortedFromStomach > 1500) { + it = playersInStomach.erase(it); + continue; + } + } + } + else + { + if (timers.acidDebuff < diff) { + player->CastSpell(player, SPELL_DIGESTIVE_ACID, true); + timers.acidDebuff += StomachTimers::ACID_REFRESH_RATE; + } + else { + timers.acidDebuff -= diff; + } + + // Crude hack for teleporting players from the stomach if the areatrigger + // in the air above knockback area in stomach of c'thun did not trigger. + if (pot) { + if (player->IsLaunched() && player->IsFalling()) { + if (player->GetDistance(pot->x, pot->y, pot->z) <= pot->radius) { + TeleportPlayerToCThun(player); + } + } + } + } + + ++it; + } +} + +struct AI_QirajiMindslayer : public ScriptedAI { + uint32 insanityTimer; + uint32 mindBlastTimer; + uint32 mindFlayTimer; + + AI_QirajiMindslayer(Creature* pCreature) : + ScriptedAI(pCreature) + { + Reset(); + } + + + void Reset() override + { + insanityTimer = 10000; + mindBlastTimer = 5000; + mindFlayTimer = urand(12000, 15000); + } + + void JustDied(Unit* pWho) override + { + if (!m_creature->GetInstanceData()) + return; + + // finding closest player and casting manaburn on that target. + // todo: should we add a player->getPowerType() == POWER_MANA check too when choosing valid target? + Player* closestPlayer = nullptr; + float closestDist = std::numeric_limits::max(); + MapRefManager const &list = m_creature->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator i = list.begin(); i != list.end(); ++i) + { + if (Player* player = i->getSource()) { + if (player->isAlive()) { + float dist = m_creature->GetDistance(player); + if (dist < closestDist) { + closestPlayer = player; + closestDist = dist; + } + } + } + } + if (closestPlayer) { + DoCastSpellIfCan(closestPlayer, 26049, CAST_TRIGGERED | CAST_INTERRUPT_PREVIOUS); + } + } + + void UpdateAI(const uint32 diff) override + { + if (!m_creature->IsNonMeleeSpellCasted()) { // prevents re-targetting of topaggro from happening while channeling mindflay + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; + } + + if (mindFlayTimer < diff) { + if (Unit* pU = m_creature->SelectAttackingTarget(AttackingTarget::ATTACKING_TARGET_RANDOM, 0, 26044, SELECT_FLAG_PLAYER | SELECT_FLAG_IN_LOS)) { + if (DoCastSpellIfCan(pU, 26044) == CAST_OK) { + mindFlayTimer = urand(12000, 15000); + } + } + } + else { + mindFlayTimer -= diff; + } + + if (mindBlastTimer < diff) { + if (Unit* pU = m_creature->SelectAttackingTarget(AttackingTarget::ATTACKING_TARGET_TOPAGGRO, 0, 26048, SELECT_FLAG_PLAYER | SELECT_FLAG_IN_LOS)) { + if (DoCastSpellIfCan(pU, 26048) == CAST_OK) { + mindBlastTimer = urand(9000, 12000); + } + } + } + else { + mindBlastTimer -= diff; + } + + if (insanityTimer < diff) { + if (Unit* pU = m_creature->SelectAttackingTarget(AttackingTarget::ATTACKING_TARGET_RANDOM, 0, 26079, SELECT_FLAG_PLAYER | SELECT_FLAG_IN_LOS)) { + if (DoCastSpellIfCan(pU, 26079) == CAST_OK) { + insanityTimer = 10000; + } + } + } + else { + insanityTimer -= diff; + } + + DoMeleeAttackIfReady(); + } + +}; InstanceData* GetInstanceData_instance_temple_of_ahnqiraj(Map* pMap) { return new instance_temple_of_ahnqiraj(pMap); } -bool AreaTrigger_at_temple_ahnqiraj(Player* pPlayer, const AreaTriggerEntry* pAt) +bool GossipHello_npc_Caelestrasz(Player* pPlayer, Creature* pCreature) { - if (!pPlayer->isAlive() || pPlayer->isGameMaster()) - return false; + pPlayer->PrepareQuestMenu(pCreature->GetGUID()); + if (InstanceData* instData = pCreature->GetInstanceData()) { + if (instData->GetData(TYPE_CTHUN) == DONE) { + pPlayer->SEND_GOSSIP_MENU(40101, pCreature->GetGUID()); + } + else { + pPlayer->SEND_GOSSIP_MENU(40100, pCreature->GetGUID()); + } + return true; + } + return false; +} - switch (pAt->id) - { - case AREATRIGGER_SARTURA: - if (instance_temple_of_ahnqiraj* pInstance = (instance_temple_of_ahnqiraj*)pPlayer->GetInstanceData()) - { - if (pInstance->GetData(TYPE_SARTURA) == NOT_STARTED || pInstance->GetData(TYPE_SARTURA) == FAIL) - { - if (Creature* pSartura = pInstance->GetSingleCreatureFromStorage(NPC_BATTLEGUARD_SARTURA)) - pSartura->SetInCombatWithZone(); - } - } - break; - case AREATRIGGER_TWIN_EMPERORS: - if (instance_temple_of_ahnqiraj* pInstance = (instance_temple_of_ahnqiraj*)pPlayer->GetInstanceData()) - { - if (Creature* pEye = pInstance->GetSingleCreatureFromStorage(NPC_THE_MASTERS_EYE)) - pEye->ForcedDespawn(1000); - } - break; - } - return false; +CreatureAI* GetAI_qirajiMindslayer(Creature* pCreature) +{ + return new AI_QirajiMindslayer(pCreature); } void AddSC_instance_temple_of_ahnqiraj() @@ -286,8 +883,19 @@ void AddSC_instance_temple_of_ahnqiraj() pNewScript->GetInstanceData = &GetInstanceData_instance_temple_of_ahnqiraj; pNewScript->RegisterSelf(); - pNewScript = new Script; - pNewScript->Name = "at_temple_ahnqiraj"; - pNewScript->pAreaTrigger = &AreaTrigger_at_temple_ahnqiraj; - pNewScript->RegisterSelf(); -} \ No newline at end of file + pNewScript = new Script; + pNewScript->Name = "at_temple_ahnqiraj"; + pNewScript->pAreaTrigger = &AreaTrigger_at_temple_ahnqiraj; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "aq_caelestrasz_ai"; + pNewScript->pGossipHello = &GossipHello_npc_Caelestrasz; + pNewScript->RegisterSelf(); + + pNewScript = new Script; + pNewScript->Name = "mob_qiraji_mindslayer"; + pNewScript->GetAI = &GetAI_qirajiMindslayer; + pNewScript->RegisterSelf(); + +} diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/mob_anubisath_sentinel.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/mob_anubisath_sentinel.cpp index 9b834bac6..3e793f636 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/mob_anubisath_sentinel.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/mob_anubisath_sentinel.cpp @@ -43,11 +43,11 @@ EndScriptData */ #define SPELL_STORM_BUFF 2148 #define SPELL_STORM 26546 -#define SPELL_ENRAGE 24318 -#define EMOTE_ENRAGE -1000003 +#define SPELL_ENRAGE 24318 +#define EMOTE_ENRAGE -1000003 -#define SPELL_TRANSFER 2400 -#define EMOTE_TRANSFER -1388101 +#define SPELL_TRANSFER 2400 +#define EMOTE_TRANSFER -1388101 struct aqsentinelAI; class SentinelAbilityAura : public Aura @@ -70,40 +70,42 @@ struct aqsentinelAI : public ScriptedAI uint32 m_uiDrainMana_Timer; uint8 m_uiDrainCount; std::vector _playerList; - bool m_bEnraged; - bool m_bAlone; + bool m_bEnraged; + bool m_bAlone; + bool gatherOthersWhenAggro; + Creature *nearby[3]; void selectAbility(int asel) { switch (asel) { - case 0: - ability = SPELL_MENDING_BUFF; - break; - case 1: - ability = SPELL_MSTRIKE_BUFF; - break; - case 2: - ability = SPELL_STORM_BUFF; - break; - case 3: - ability = SPELL_REFLECTAF_BUFF; - break; - case 4: - ability = SPELL_REFLECTSFr_BUFF; - break; - case 5: - ability = SPELL_THORNS_BUFF; - break; - case 6: - ability = SPELL_THUNDER_BUFF; - break; - case 7: - ability = SPELL_KNOCK_BUFF; - break; - case 8: - ability = SPELL_MANAB_BUFF; - break; + case 0: + ability = SPELL_MENDING_BUFF; + break; + case 1: + ability = SPELL_MSTRIKE_BUFF; + break; + case 2: + ability = SPELL_STORM_BUFF; + break; + case 3: + ability = SPELL_REFLECTAF_BUFF; + break; + case 4: + ability = SPELL_REFLECTSFr_BUFF; + break; + case 5: + ability = SPELL_THORNS_BUFF; + break; + case 6: + ability = SPELL_THUNDER_BUFF; + break; + case 7: + ability = SPELL_KNOCK_BUFF; + break; + case 8: + ability = SPELL_MANAB_BUFF; + break; } } @@ -111,21 +113,19 @@ struct aqsentinelAI : public ScriptedAI { ClearBudyList(); abselected = 0; // just initialization of variable - m_bEnraged = false; + m_bEnraged = false; Reset(); } - Creature *nearby[3]; - - void MoveInLineOfSight(Unit* pWho) override - { - // Increase aggro radius - if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 45.0f) && m_creature->IsWithinLOSInMap(pWho) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) - { - AttackStart(pWho); - } - ScriptedAI::MoveInLineOfSight(pWho); - } + void MoveInLineOfSight(Unit* pWho) override + { + // Increase aggro radius + if (pWho->GetTypeId() == TYPEID_PLAYER && !m_creature->isInCombat() && m_creature->IsWithinDistInMap(pWho, 45.0f) && m_creature->IsWithinLOSInMap(pWho) && !pWho->HasAuraType(SPELL_AURA_FEIGN_DEATH)) + { + AttackStart(pWho); + } + ScriptedAI::MoveInLineOfSight(pWho); + } void ClearBudyList() { @@ -197,7 +197,9 @@ struct aqsentinelAI : public ScriptedAI { for (int t = 0; t < 2; ++t) { - for (int i = !t ? (rand() % 8) : 0; i < 8; ++i) // should be (rand() % 9) : 0; i < 9; // temporarily precluding sentinels from rolling semi-broken mana burn + // should be (rand() % 9) : 0; i < 9; + // temporarily precluding sentinels from rolling semi-broken mana burn + for (int i = !t ? (rand() % 8) : 0; i < 8; ++i) { if (!chosenAbilities[i]) { @@ -234,8 +236,6 @@ struct aqsentinelAI : public ScriptedAI delete[] chosenAbilities; } - bool gatherOthersWhenAggro; - void Reset() { if (!m_creature->isDead()) @@ -252,7 +252,7 @@ struct aqsentinelAI : public ScriptedAI gatherOthersWhenAggro = true; m_uiKnock_Timer = 13000; m_uiDrainMana_Timer = 11000; - m_bEnraged = 0; + m_bEnraged = 0; m_uiDrainCount = 0; } @@ -264,18 +264,18 @@ struct aqsentinelAI : public ScriptedAI void cast_knock() { if (Unit* victim = m_creature->getVictim()) - m_creature->CastSpell(victim, SPELL_KNOCK, false); - } + m_creature->CastSpell(victim, SPELL_KNOCK, false); + } - // Threat reduction for Knock Away - void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) override - { - if ((pSpell->Id == SPELL_KNOCK) && pTarget->GetTypeId() == TYPEID_PLAYER) - { - if (m_creature->getThreatManager().getThreat(m_creature->getVictim())) - m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(), -20); - } - } + // Threat reduction for Knock Away + void SpellHitTarget(Unit* pTarget, const SpellEntry* pSpell) override + { + if ((pSpell->Id == SPELL_KNOCK) && pTarget->GetTypeId() == TYPEID_PLAYER) + { + if (m_creature->getThreatManager().getThreat(m_creature->getVictim())) + m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(), -20); + } + } void Aggro(Unit* pWho) { @@ -298,10 +298,10 @@ struct aqsentinelAI : public ScriptedAI } } - // Transfer powers on death + // Transfer powers on death void JustDied(Unit*) { - m_bAlone = true; + m_bAlone = true; for (int ni = 0; ni < 3; ++ni) { Creature *sent = nearby[ni]; @@ -309,16 +309,16 @@ struct aqsentinelAI : public ScriptedAI continue; if (sent->isDead()) continue; - m_bAlone = false; - DoCastSpellIfCan(sent, SPELL_TRANSFER, CAST_TRIGGERED); + m_bAlone = false; + DoCastSpellIfCan(sent, SPELL_TRANSFER, CAST_TRIGGERED); uint32 h = sent->GetHealth() + (sent->GetMaxHealth() / 2); if (h > sent->GetMaxHealth()) h = sent->GetMaxHealth(); sent->SetHealth(h); ((aqsentinelAI *)sent->AI())->GainSentinelAbility(ability); } - if (!m_bAlone) - DoScriptText(EMOTE_TRANSFER, m_creature); + if (!m_bAlone) + DoScriptText(EMOTE_TRANSFER, m_creature); } Unit *GetHatedManaUser() @@ -334,16 +334,16 @@ struct aqsentinelAI : public ScriptedAI } void UpdateAI(const uint32 uiDiff) { - //Return since we have no target - if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) - return; + //Return since we have no target + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; if (ability == SPELL_KNOCK_BUFF) { if (m_uiKnock_Timer < uiDiff) { //cast_knock(); - DoCastSpellIfCan(m_creature->getVictim(), SPELL_KNOCK); + DoCastSpellIfCan(m_creature->getVictim(), SPELL_KNOCK); m_uiKnock_Timer = 13000; } else @@ -394,14 +394,14 @@ struct aqsentinelAI : public ScriptedAI m_uiDrainMana_Timer -= uiDiff; } - if (!m_bEnraged && m_creature->GetHealthPercent() < 30.0f) - { - if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK) - { - DoScriptText(EMOTE_ENRAGE, m_creature); - m_bEnraged = true; - } - } + if (!m_bEnraged && m_creature->GetHealthPercent() < 30.0f) + { + if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK) + { + DoScriptText(EMOTE_ENRAGE, m_creature); + m_bEnraged = true; + } + } DoMeleeAttackIfReady(); } @@ -425,20 +425,20 @@ Unit* SentinelAbilityAura::GetTriggerTarget() const { switch (abilityId) { - case SPELL_KNOCK_BUFF: - case SPELL_THUNDER_BUFF: - case SPELL_MSTRIKE_BUFF: - case SPELL_STORM_BUFF: - return aOwner->m_creature->getVictim(); + case SPELL_KNOCK_BUFF: + case SPELL_THUNDER_BUFF: + case SPELL_MSTRIKE_BUFF: + case SPELL_STORM_BUFF: + return aOwner->m_creature->getVictim(); - case SPELL_MANAB_BUFF: - return aOwner->GetHatedManaUser(); - case SPELL_MENDING_BUFF: - case SPELL_REFLECTAF_BUFF: - case SPELL_REFLECTSFr_BUFF: - case SPELL_THORNS_BUFF: - default: - return aOwner->m_creature; + case SPELL_MANAB_BUFF: + return aOwner->GetHatedManaUser(); + case SPELL_MENDING_BUFF: + case SPELL_REFLECTAF_BUFF: + case SPELL_REFLECTSFr_BUFF: + case SPELL_THORNS_BUFF: + default: + return aOwner->m_creature; } } diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/temple_of_ahnqiraj.h b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/temple_of_ahnqiraj.h index f7ddf9ad9..53cf9d880 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/temple_of_ahnqiraj.h +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/temple_of_ahnqiraj.h @@ -7,18 +7,17 @@ enum { - MAX_ENCOUNTER = 10, - TYPE_SKERAM = 0, TYPE_SARTURA = 1, TYPE_FANKRISS = 2, TYPE_HUHURAN = 3, TYPE_TWINS = 4, - TYPE_C_THUN = 5, + TYPE_CTHUN = 5, TYPE_BUG_TRIO = 6, TYPE_VISCIDUS = 7, TYPE_OURO = 8, - TYPE_CTHUN_PHASE = 9, + + MAX_ENCOUNTER = 10, }; enum @@ -66,53 +65,150 @@ enum NPC_VEKNISS_BORER = 15622, NPC_SPAWN_OF_FANKRISS = 15630, NPC_OURO_SCARAB = 15718, + NPC_OURO_SPAWNER = 15957, NPC_CTHUN = 15727, NPC_CTHUN_PORTAL = 15896, NPC_VEKNISS_HATCHLING = 15962, - NPC_THE_MASTERS_EYE = 15963, + NPC_MASTERS_EYE = 15963, NPC_SARTURA_S_ROYAL_GUARD = 15984, - //GO_SKERAM_GATE = 180636, - //GO_TWINS_ENTER_DOOR = 180634, - //GO_TWINS_EXIT_DOOR = 180635, + GO_SKERAM_GATE = 180636, + GO_TWINS_ENTER_DOOR = 180634, + GO_TWINS_EXIT_DOOR = 180635, + GO_SANDWORM_BASE = 180795, + GO_GRASP_OF_CTHUN = 180745, - GO_SKERAM_GATE = 21785, - GO_TWINS_ENTER_DOOR = 21783, - GO_TWINS_EXIT_DOOR = 21784, + AREATRIGGER_TWIN_EMPERORS = 4047, + AREATRIGGER_SARTURA = 4052, + AREATRIGGER_STOMACH_GROUND = 4033, + AREATRIGGER_STOMACH_AIR = 4034, + AREATRIGGER_CTHUN_KNOCKBACK = 4036, - AREATRIGGER_TWIN_EMPERORS = 4047, - AREATRIGGER_SARTURA = 4052, + // Whispered on players around the map + SAY_CTHUN_WHISPER_1 = -1531033, + SAY_CTHUN_WHISPER_2 = -1531034, + SAY_CTHUN_WHISPER_3 = -1531035, + SAY_CTHUN_WHISPER_4 = -1531036, + SAY_CTHUN_WHISPER_5 = -1531037, + SAY_CTHUN_WHISPER_6 = -1531038, + SAY_CTHUN_WHISPER_7 = -1531039, + SAY_CTHUN_WHISPER_8 = -1531040, + + + + SPELL_SUMMON_PLAYER = 20477, + + // Cast periodically on players around the instance + SPELL_WHISPERINGS_CTHUN_1 = 26195, + SPELL_WHISPERINGS_CTHUN_2 = 26197, + SPELL_WHISPERINGS_CTHUN_3 = 26198, + SPELL_WHISPERINGS_CTHUN_4 = 26258, + SPELL_WHISPERINGS_CTHUN_5 = 26259, }; -class instance_temple_of_ahnqiraj : public ScriptedInstance_PTR +class TwinsIntroDialogue : public DialogueHelper { - public: - instance_temple_of_ahnqiraj(Map* pMap); +public: + TwinsIntroDialogue(); + void Start(); + bool StartedOrDone(); + void SetDone(); - void Initialize(); - - bool IsEncounterInProgress() const override; - - void OnCreatureRespawn(Creature* pCreature); - void OnCreatureCreate(Creature* pCreature); - void OnObjectCreate(GameObject* pGo); - - void SetData(uint32 uiType, uint32 uiData); - uint32 GetData(uint32 uiType); - - void GetRoyalGuardGUIDList(GuidList& lList) { lList = m_lRoyalGuardGUIDList; } - - const char* Save() { return m_strInstData.c_str(); } - void Load(const char* chrIn); - - private: - uint32 m_auiEncounter[MAX_ENCOUNTER]; - std::string m_strInstData; - - uint32 m_uiBugTrioDeathCount; - uint32 m_uiCthunPhase; - - GuidList m_lRoyalGuardGUIDList; +protected: + void JustDidDialogueStep(int32 iEntry) override; +private: + bool m_StartedOrDone; }; -#endif \ No newline at end of file +class instance_temple_of_ahnqiraj : public ScriptedInstance +{ +public: + instance_temple_of_ahnqiraj(Map* pMap); + + void Initialize(); + + bool IsEncounterInProgress() const override; + + void OnCreatureRespawn(Creature* pCreature); + void OnCreatureCreate(Creature* pCreature); + void OnObjectCreate(GameObject* pGo); + + void SetData(uint32 uiType, uint32 uiData) override; + uint32 GetData(uint32 uiType) override; + + void GetRoyalGuardGUIDList(GuidList& lList) { lList = m_lRoyalGuardGUIDList; } + + const char* Save() { return m_strInstData.c_str(); } + void Load(const char* chrIn); + + void Update(uint32 uiDiff); + + bool TwinsDialogueStartedOrDone(); + +private: + uint32 m_auiEncounter[MAX_ENCOUNTER]; + std::string m_strInstData; + + uint32 m_uiBugTrioDeathCount; + uint32 m_uiCthunPhase; + + GuidList m_lRoyalGuardGUIDList; + + TwinsIntroDialogue m_twinsIntroDialogue; + DialogueHelper m_twinsDeadDialogue; + std::vector graspsOfCthun; + + void UpdateCThunWhisper(uint32 diff); + std::vector> cthunWhisperMutes; + uint32 m_uiCthunWhisperTimer; + uint32 m_uiCthunPrevWhisperTimer; + + // The following functions, variables etc, are used to handle the C'thun stomach. + // One might argue if they should be in boss_cthun.cpp instead, but it makes it a whole + // lot easier to handle this logic if it's handled by the instance script. +public: + void DoHandleTempleAreaTrigger(uint32 uiTriggerId); + void HandleStomachTriggers(Player* pPlayer, const AreaTriggerEntry* pAt); + void AddPlayerToStomach(Unit* p); + bool PlayerInStomach(Unit* p); + bool KillPlayersInStomach(); + +private: + enum eStomachSpells { + SPELL_PUNT_UPWARD = 26224, //knocks up like craaayy everyone in range, maybe too big radius. Only works if thing is targeting player? + SPELL_EXIT_STOMACH_KNOCKBACK = 26230, //knocks well back, but must be cast probably an invisible trigger, if not by cthun outside + + SPELL_DIGESTIVE_ACID = 26476, // Must be stacked and removed manually. + EXIT_KNOCKBACK_CREATURE = 15800, // Exit trigger creature used for stomach and cthun knockups/knockbacks + PUNT_CREATURE = 15922, // Trigger for cthuns belly knockup spell + SPELL_QUAKE = 26093, //used for its visual only with SendSpellGo. It deals damage if cast normally + SPELL_PORT_OUT_STOMACH = 26648, // Not yet used, was killing c'thun too. Maybe that's intended => a respawn? + }; + struct StomachTimers { + uint32 acidDebuff; + uint32 timeSincePortedFromStomach; + uint32 timeSincePortedToStomach; + bool didKnockback; + StomachTimers() : + acidDebuff(StomachTimers::ACID_REFRESH_RATE), + timeSincePortedFromStomach(0), + timeSincePortedToStomach(0), + didKnockback(false) + {} + static const uint32 PUNT_CAST_TIME = 3000; + static const uint32 ACID_REFRESH_RATE = 5000; + }; + using CThunStomachList = std::vector>; + void UpdateStomachOfCthun(uint32 diff); + CThunStomachList::iterator PlayerInStomachIter(Unit* unit); + void TeleportPlayerToCThun(Player* pPlayer); + void PerformCthunKnockback(); + + ObjectGuid puntCreatureGuid; + uint32 quakeTimer; + uint32 puntCountdown; + + std::vector> playersInStomach; +}; + +#endif diff --git a/src/shared/Log.h b/src/shared/Log.h index f126718c9..4e30840f5 100644 --- a/src/shared/Log.h +++ b/src/shared/Log.h @@ -289,4 +289,13 @@ class Log : public MaNGOS::Singleton Date: Tue, 23 May 2017 23:04:43 +0100 Subject: [PATCH 06/16] Prevent stacking multiple shadow vulns (#830) --- sql/migrations/20170523212555_world.sql | 20 ++++++++++++++++++++ src/game/Spells/SpellMgr.cpp | 5 ----- src/game/Spells/SpellMgr.h | 1 - 3 files changed, 20 insertions(+), 6 deletions(-) create mode 100644 sql/migrations/20170523212555_world.sql diff --git a/sql/migrations/20170523212555_world.sql b/sql/migrations/20170523212555_world.sql new file mode 100644 index 000000000..fe40309fe --- /dev/null +++ b/sql/migrations/20170523212555_world.sql @@ -0,0 +1,20 @@ +INSERT INTO migrations VALUES ('20170523212555'); + +DELETE FROM spell_chain WHERE first_spell = 17794; +INSERT INTO spell_chain (spell_id, prev_spell, first_spell, rank) VALUES +(17794, 0, 17794, 1), +(17798, 17794, 17794, 2), +(17797, 17798, 17794, 3), +(17799, 17797, 17794, 4), +(17800, 17799, 17794, 5); + +DELETE FROM spell_group WHERE group_id = 1073; +INSERT INTO spell_group (group_id, group_spell_id, spell_id) VALUES +(1073, 0, 17794), +(1073, 1, 17798), +(1073, 2, 17797), +(1073, 3, 17799), +(1073, 4, 17800); + +DELETE FROM spell_group_stack_rules WHERE group_id = 1073; +INSERT INTO spell_group_stack_rules (group_id,stack_rule) VALUES (1073,3); diff --git a/src/game/Spells/SpellMgr.cpp b/src/game/Spells/SpellMgr.cpp index ce39725ce..5bea9b131 100644 --- a/src/game/Spells/SpellMgr.cpp +++ b/src/game/Spells/SpellMgr.cpp @@ -434,10 +434,6 @@ SpellSpecific GetSpellSpecific(uint32 spellId) if (spellInfo->Id == 13161) return SPELL_ASPECT; - // Shadow Vulnerability - if (spellInfo->SpellIconID == 213 && spellInfo->EffectApplyAuraName[0] == SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN) - return SPELL_SHADOW_VULN; - // Food / Drinks (mostly) if (spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) { @@ -600,7 +596,6 @@ bool IsSingleFromSpellSpecificSpellRanksPerTarget(SpellSpecific spellSpec1, Spel case SPELL_AURA: case SPELL_CURSE: case SPELL_ASPECT: - case SPELL_SHADOW_VULN: return spellSpec1 == spellSpec2; default: return false; diff --git a/src/game/Spells/SpellMgr.h b/src/game/Spells/SpellMgr.h index 848b12303..1c4d0a4f5 100644 --- a/src/game/Spells/SpellMgr.h +++ b/src/game/Spells/SpellMgr.h @@ -90,7 +90,6 @@ enum SpellSpecific SPELL_FOOD = 20, SPELL_DRINK = 21, SPELL_FOOD_AND_DRINK = 22, - SPELL_SHADOW_VULN = 23, }; SpellSpecific GetSpellSpecific(uint32 spellId); From 16f8ab237542362ce9265eef8d2528ce5c403d06 Mon Sep 17 00:00:00 2001 From: GuybrushGit Date: Mon, 22 May 2017 23:20:15 +0100 Subject: [PATCH 07/16] Fix to Combustion not being removed on dispel (#825) --- sql/migrations/20170522021253_world.sql | 3 +++ src/game/UnitAuraProcHandler.cpp | 7 +++++++ 2 files changed, 10 insertions(+) create mode 100644 sql/migrations/20170522021253_world.sql diff --git a/sql/migrations/20170522021253_world.sql b/sql/migrations/20170522021253_world.sql new file mode 100644 index 000000000..ee5110c71 --- /dev/null +++ b/sql/migrations/20170522021253_world.sql @@ -0,0 +1,3 @@ +INSERT INTO migrations VALUES ('20170522021253'); + +INSERT INTO spell_mod (Id, Dispel, Comment) VALUES (11129, 0, 'Combustion: Hidden buff not dispellable'); diff --git a/src/game/UnitAuraProcHandler.cpp b/src/game/UnitAuraProcHandler.cpp index aef413aa9..39ba1790b 100644 --- a/src/game/UnitAuraProcHandler.cpp +++ b/src/game/UnitAuraProcHandler.cpp @@ -765,6 +765,13 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura // Combustion case 11129: { + // combustion counter was dispelled or clicked off + if (!HasAura(28682)) + { + RemoveAurasDueToSpell(11129); + return SPELL_AURA_PROC_FAILED; + } + //last charge and crit if (triggeredByAura->GetHolder()->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT)) { From e6a2a83b18cedac8898828b2a670e7ab5bf1a884 Mon Sep 17 00:00:00 2001 From: GuybrushGit Date: Mon, 22 May 2017 21:16:07 +0100 Subject: [PATCH 08/16] Readded spell_proc_event for Aura of the Blue Dragon (#823) --- sql/migrations/20170522204702_world.sql | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 sql/migrations/20170522204702_world.sql diff --git a/sql/migrations/20170522204702_world.sql b/sql/migrations/20170522204702_world.sql new file mode 100644 index 000000000..2a0ef84dd --- /dev/null +++ b/sql/migrations/20170522204702_world.sql @@ -0,0 +1,5 @@ +INSERT INTO migrations VALUES ('20170522204702'); + +DELETE FROM spell_proc_event WHERE entry=23688; +INSERT INTO spell_proc_event (entry, SchoolMask, SpellFamilyName, SpellFamilyMask0, SpellFamilyMask1, SpellFamilyMask2, procFlags, procEx, ppmRate, CustomChance, Cooldown) VALUES +(23688, 0, 0, 0, 0, 0, 67108864, 65536, 0, 0, 0); From a3ed2a4033f52a8e2800372ccdbf6bfc9b8b6ee7 Mon Sep 17 00:00:00 2001 From: GuybrushGit Date: Sat, 20 May 2017 09:54:25 +0100 Subject: [PATCH 09/16] Removed Ignite halving mechanic. (#792) --- src/game/UnitAuraProcHandler.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/game/UnitAuraProcHandler.cpp b/src/game/UnitAuraProcHandler.cpp index 39ba1790b..f2206efc9 100644 --- a/src/game/UnitAuraProcHandler.cpp +++ b/src/game/UnitAuraProcHandler.cpp @@ -726,11 +726,6 @@ SpellAuraProcResult Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura bool notAtMaxStack = igniteAura->GetStackAmount() < 5; - // If 1 of 2 ticks of ignite have been applied (2s), - // Halve damage to apply correct remaining damage on 4s refresh - if (1 == igniteAura->GetAuraTicks() && notAtMaxStack) - tickDamage = tickDamage / 2 + 1; - bool reapplyIgnite = igniteAura->GetAuraTicks() >= igniteAura->GetAuraMaxTicks(); if (!reapplyIgnite) From 52b0d7081a528c74e03f149f2f75a27904771808 Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 01:25:04 +0100 Subject: [PATCH 10/16] Small fix - merge weirdness --- .../kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp index e975de9dd..76a31bf34 100644 --- a/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp +++ b/src/scripts/kalimdor/silithus/temple_of_ahnqiraj/boss_skeram.cpp @@ -95,9 +95,9 @@ struct boss_skeramAI : public ScriptedAI { switch (urand(0,8)) { - case 0: DoScriptText(SAY_SLAY_0, m_creature); break; - case 1: DoScriptText(SAY_SLAY_1, m_creature); break; - case 2: DoScriptText(SAY_SLAY_2, m_creature); break; + case 0: DoScriptText(SAY_SLAY_1, m_creature); break; + case 1: DoScriptText(SAY_SLAY_2, m_creature); break; + case 2: DoScriptText(SAY_SLAY_3, m_creature); break; } } From 6a1014f05a58e2e0f6b18a53ee384d452fce0f16 Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 16:00:39 +0100 Subject: [PATCH 11/16] Revert "add playervsneutral case to Unit::GetReactionTo (#337)" This reverts commit 530ae7b933d29de6e1a26f34ef6d7910098a1fd6. --- src/game/Objects/Unit.cpp | 119 +++++++++++++++++--------------------- 1 file changed, 52 insertions(+), 67 deletions(-) diff --git a/src/game/Objects/Unit.cpp b/src/game/Objects/Unit.cpp index b623414de..8e365aeb0 100644 --- a/src/game/Objects/Unit.cpp +++ b/src/game/Objects/Unit.cpp @@ -5384,83 +5384,68 @@ ReputationRank Unit::GetReactionTo(Unit const* target) const return *repRank; } - // Interaction between pvp flagged units - if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE) && - target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) + if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) { - if (selfPlayerOwner && targetPlayerOwner) + if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE)) { - // always friendly to other unit controlled by player, or to the player himself - if (selfPlayerOwner == targetPlayerOwner) - return REP_FRIENDLY; - - // duel - always hostile to opponent - if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0 && !selfPlayerOwner->duel->finished) - return REP_HOSTILE; - - // same group - checks dependant only on our faction - skip FFA_PVP for example - if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner)) - return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work - // however client seems to allow mixed group parties, because in 13850 client it works like: - // return GetFactionReactionTo(getFactionTemplateEntry(), target); - - // Sanctuary - if (selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY) && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY)) - return REP_FRIENDLY; - - // Nostalrius: Hackfix because UNIT_BYTE2_FLAG_FFA_PVP is not implemented yet. - if (selfPlayerOwner->IsFFAPvP() && targetPlayerOwner->IsFFAPvP()) - return REP_HOSTILE; - } - - // check FFA_PVP - not implemented that way on MaNGOS :/ - /* - if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP - && target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) - return REP_HOSTILE; - */ - - if (selfPlayerOwner) - { - if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) + if (selfPlayerOwner && targetPlayerOwner) { - if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) - return *repRank; - if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) - { - if (targetFactionEntry->CanHaveReputation()) - { - // check contested flags - if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD - && selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) - return REP_HOSTILE; + // always friendly to other unit controlled by player, or to the player himself + if (selfPlayerOwner == targetPlayerOwner) + return REP_FRIENDLY; - // if faction has reputation, hostile state depends only from AtWar state - if (FactionState const* factionState = selfPlayerOwner->GetReputationMgr().GetState(targetFactionEntry)) - if (factionState->Flags & FACTION_FLAG_AT_WAR) + // duel - always hostile to opponent + if (selfPlayerOwner->duel && selfPlayerOwner->duel->opponent == targetPlayerOwner && selfPlayerOwner->duel->startTime != 0 && !selfPlayerOwner->duel->finished) + return REP_HOSTILE; + + // same group - checks dependant only on our faction - skip FFA_PVP for example + if (selfPlayerOwner->IsInRaidWith(targetPlayerOwner)) + return REP_FRIENDLY; // return true to allow config option AllowTwoSide.Interaction.Group to work + // however client seems to allow mixed group parties, because in 13850 client it works like: + // return GetFactionReactionTo(getFactionTemplateEntry(), target); + + // Sanctuary + if (selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY) && targetPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY)) + return REP_FRIENDLY; + + // Nostalrius: Hackfix because UNIT_BYTE2_FLAG_FFA_PVP is not implemented yet. + if (selfPlayerOwner->IsFFAPvP() && targetPlayerOwner->IsFFAPvP()) + return REP_HOSTILE; + } + + // check FFA_PVP - not implemented that way on MaNGOS :/ + /* + if (GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP + && target->GetByteValue(UNIT_FIELD_BYTES_2, 1) & UNIT_BYTE2_FLAG_FFA_PVP) + return REP_HOSTILE; + */ + + if (selfPlayerOwner) + { + if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) + { + if (ReputationRank const* repRank = selfPlayerOwner->GetReputationMgr().GetForcedRankIfAny(targetFactionTemplateEntry)) + return *repRank; + if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) + { + if (targetFactionEntry->CanHaveReputation()) + { + // check contested flags + if (targetFactionTemplateEntry->factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD + && selfPlayerOwner->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP)) return REP_HOSTILE; - return REP_FRIENDLY; + + // if faction has reputation, hostile state depends only from AtWar state + if (FactionState const* factionState = selfPlayerOwner->GetReputationMgr().GetState(targetFactionEntry)) + if (factionState->Flags & FACTION_FLAG_AT_WAR) + return REP_HOSTILE; + return REP_FRIENDLY; + } } } } } } - - // Player reaction against Neutral faction Creature - if (selfPlayerOwner && !targetPlayerOwner) - { - if (FactionTemplateEntry const* targetFactionTemplateEntry = target->getFactionTemplateEntry()) - { - if (FactionEntry const* targetFactionEntry = sFactionStore.LookupEntry(targetFactionTemplateEntry->faction)) - { - if(targetFactionEntry->CanHaveReputation()) - { - return selfPlayerOwner->GetReputationMgr().GetRank(targetFactionEntry); - } - } - } - } - // do checks dependant only on our faction return GetFactionReactionTo(getFactionTemplateEntry(), target); } From 7c6e444ef3682f7fac048159a5f9b6a7c77083c9 Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 16:03:28 +0100 Subject: [PATCH 12/16] Revert "Fixes to the PvP flag mechanics (#588)" This reverts commit 22a9511d0fb12e0c24285d954700345f30b6ae97. --- src/game/AI/PetAI.cpp | 13 ------------- src/game/Maps/GridNotifiersImpl.h | 5 ----- src/game/Movement/WaypointMovementGenerator.cpp | 6 +----- src/game/Objects/Player.cpp | 11 +++-------- src/game/Spells/Spell.cpp | 10 ++-------- 5 files changed, 6 insertions(+), 39 deletions(-) diff --git a/src/game/AI/PetAI.cpp b/src/game/AI/PetAI.cpp index b1a1ee955..535e65083 100644 --- a/src/game/AI/PetAI.cpp +++ b/src/game/AI/PetAI.cpp @@ -563,19 +563,6 @@ void PetAI::DoAttack(Unit* target, bool chase) m_creature->GetMotionMaster()->Clear(); m_creature->GetMotionMaster()->MoveIdle(); } - - // Flag owner for PvP if owner is player and target is flagged - Unit* owner = m_creature->GetCharmerOrOwner(); - if (owner && owner->IsPlayer() && !owner->IsPvP()) - { - Player* pOwner = owner->ToPlayer(); - if ((target->IsPlayer() && target->IsPvP() && !pOwner->IsInDuelWith((Player*)target)) || // PvP flagged players - (target->IsCreature() && target->IsPvP())) // PvP flagged creatures - { - pOwner->UpdatePvP(true); - pOwner->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); - } - } } } diff --git a/src/game/Maps/GridNotifiersImpl.h b/src/game/Maps/GridNotifiersImpl.h index ef9ae10f9..d14460346 100644 --- a/src/game/Maps/GridNotifiersImpl.h +++ b/src/game/Maps/GridNotifiersImpl.h @@ -155,11 +155,6 @@ inline void MaNGOS::DynamicObjectUpdater::VisitHelper(Unit* target) if (!i_dynobject.NeedsRefresh(target)) return; - // Negative AoE from non flagged players cannot target other players - if (Player *attackedPlayer = target->GetCharmerOrOwnerPlayerOrPlayerItself()) - if (!i_positive && i_check->IsPlayer() && !i_check->IsPvP() && !((Player*)i_check)->IsInDuelWith(attackedPlayer)) - return; - SpellEntry const *spellInfo = sSpellMgr.GetSpellEntry(i_dynobject.GetSpellId()); SpellEffectIndex eff_index = i_dynobject.GetEffIndex(); diff --git a/src/game/Movement/WaypointMovementGenerator.cpp b/src/game/Movement/WaypointMovementGenerator.cpp index 27a56b08f..6ec7aac7a 100644 --- a/src/game/Movement/WaypointMovementGenerator.cpp +++ b/src/game/Movement/WaypointMovementGenerator.cpp @@ -277,12 +277,8 @@ void FlightPathMovementGenerator::Finalize(Player & player) if (player.m_taxi.empty()) { player.getHostileRefManager().setOnlineOfflineState(true); - if (player.pvpInfo.inHostileArea) - { + if (player.pvpInfo.inHostileArea) player.CastSpell(&player, 2479, true); - if (!player.IsPvP()) - player.UpdatePvP(true, true); - } // update z position to ground and orientation for landing point // this prevent cheating with landing point at lags diff --git a/src/game/Objects/Player.cpp b/src/game/Objects/Player.cpp index 395e5ca51..f31170817 100644 --- a/src/game/Objects/Player.cpp +++ b/src/game/Objects/Player.cpp @@ -1202,11 +1202,10 @@ void Player::Update(uint32 update_diff, uint32 p_time) UpdateMeleeAttackingState(); Unit *pVictim = getVictim(); - if (pVictim && !IsNonMeleeSpellCasted(false) && CanReachWithMeleeAttack(pVictim)) + if (pVictim && !IsNonMeleeSpellCasted(false)) { Player *vOwner = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself(); - if ((vOwner && vOwner->IsPvP() && !IsInDuelWith(vOwner)) || // PvP flagged players - (pVictim->IsCreature() && pVictim->IsPvP())) // PvP flagged creatures + if (vOwner && vOwner->IsPvP() && !IsInDuelWith(vOwner)) { UpdatePvP(true); RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); @@ -6262,7 +6261,7 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) if (pvpInfo.inHostileArea) // in hostile area { - if ((!IsPvP() && !IsTaxiFlying()) || pvpInfo.endTimer != 0) + if (!IsPvP() || pvpInfo.endTimer != 0) UpdatePvP(true, true); } else // in friendly area @@ -12310,10 +12309,6 @@ void Player::AddQuest(Quest const *pQuest, Object *questGiver) else questStatusData.m_timer = 0; - // Set PvP flag for PvP quests - if (pQuest->GetType() == QUEST_TYPE_PVP) - UpdatePvP(true, true); - SetQuestSlot(log_slot, quest_id, qtime); if (questStatusData.uState != QUEST_NEW) diff --git a/src/game/Spells/Spell.cpp b/src/game/Spells/Spell.cpp index e7f005cfc..2888c549c 100644 --- a/src/game/Spells/Spell.cpp +++ b/src/game/Spells/Spell.cpp @@ -592,14 +592,13 @@ void Spell::FillTargetMap() break; } - if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->AttributesEx & SPELL_ATTR_EX_NO_THREAT)) + if (m_caster->GetTypeId() == TYPEID_PLAYER) { Player *me = (Player*)m_caster; for (UnitList::const_iterator itr = tmpUnitMap.begin(); itr != tmpUnitMap.end(); ++itr) { Player *targetOwner = (*itr)->GetCharmerOrOwnerPlayerOrPlayerItself(); - if ((targetOwner && targetOwner != me && targetOwner->IsPvP() && !me->IsInDuelWith(targetOwner)) || // PvP flagged players - ((*itr)->IsCreature() && (*itr)->IsPvP())) // PvP flagged creatures + if (targetOwner && targetOwner != me && targetOwner->IsPvP() && !me->IsInDuelWith(targetOwner)) { me->UpdatePvP(true); me->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT); @@ -7442,11 +7441,6 @@ public: { if (!casterUnit->IsValidAttackTarget(sourceUnit)) continue; - - // Negative AoE from non flagged players cannot target other players - if (Player *attackedPlayer = sourceUnit->GetCharmerOrOwnerPlayerOrPlayerItself()) - if (casterUnit->IsPlayer() && !casterUnit->IsPvP() && !((Player*)casterUnit)->IsInDuelWith(attackedPlayer)) - continue; } else if (GameObject* gobj = i_originalCaster->ToGameObject()) { From 9cf0bb891aeac0fe5b0c7c0269302f903c127945 Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 16:04:50 +0100 Subject: [PATCH 13/16] Revert "fix iterator increment (#595)" This reverts commit 9eb0068781f87b45aa222712abb97f96dfda63c4. --- src/game/Maps/Map.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/game/Maps/Map.cpp b/src/game/Maps/Map.cpp index 202e1578c..3540180e8 100644 --- a/src/game/Maps/Map.cpp +++ b/src/game/Maps/Map.cpp @@ -1031,14 +1031,13 @@ void Map::Remove(Player *player, bool remove) player->m_needUpdateVisibility = false; player->m_visibleGUIDs_lock.acquire_write(); - for (ObjectGuidSet::const_iterator it = player->m_visibleGUIDs.begin(); it != player->m_visibleGUIDs.end();) + for (ObjectGuidSet::const_iterator it = player->m_visibleGUIDs.begin(); it != player->m_visibleGUIDs.end(); ++it) if (Player* other = GetPlayer(*it)) { other->DestroyForPlayer(player); other->m_broadcaster->RemoveListener(player); - it = player->m_visibleGUIDs.erase(it); + player->m_visibleGUIDs.erase(*it); } - else ++it; player->m_visibleGUIDs_lock.release(); player->ResetMap(); From cd85724ae8e73989a3adb1ab003dcf07f80b8fad Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 16:05:02 +0100 Subject: [PATCH 14/16] Revert "remove players from visibility list (#500)" This reverts commit 28aec0e4f32a9bbcf1d7c40244c28193ee8f7d0e. --- src/game/Maps/Map.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/game/Maps/Map.cpp b/src/game/Maps/Map.cpp index 3540180e8..32a762981 100644 --- a/src/game/Maps/Map.cpp +++ b/src/game/Maps/Map.cpp @@ -1030,15 +1030,9 @@ void Map::Remove(Player *player, bool remove) RemoveUnitFromMovementUpdate(player); player->m_needUpdateVisibility = false; - player->m_visibleGUIDs_lock.acquire_write(); for (ObjectGuidSet::const_iterator it = player->m_visibleGUIDs.begin(); it != player->m_visibleGUIDs.end(); ++it) if (Player* other = GetPlayer(*it)) - { - other->DestroyForPlayer(player); other->m_broadcaster->RemoveListener(player); - player->m_visibleGUIDs.erase(*it); - } - player->m_visibleGUIDs_lock.release(); player->ResetMap(); if (remove) From bb8cfdd333fbc53c67f6dd628e5d1407df04bb6e Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 20:53:03 +0100 Subject: [PATCH 15/16] Revert "Fix being able to cast spells whilst under CC effects (#418)" This reverts commit c829cfd59a4c40ad661054b199c441fb8968e586. --- src/game/Spells/Spell.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/game/Spells/Spell.cpp b/src/game/Spells/Spell.cpp index 2888c549c..479103fff 100644 --- a/src/game/Spells/Spell.cpp +++ b/src/game/Spells/Spell.cpp @@ -5023,7 +5023,7 @@ SpellCastResult Spell::CheckCast(bool strict) // Nostalrius: impossible to cast spells while banned / feared / confused ... // Except divine shields, pvp trinkets for example // TODO: This condition allows an antifear item to be used while stuned for example. - if (!m_IsTriggeredSpell && !IsSpellHaveAura(m_spellInfo, SPELL_AURA_SCHOOL_IMMUNITY) && !IsSpellHaveAura(m_spellInfo, SPELL_AURA_MECHANIC_IMMUNITY) && + if (!m_IsTriggeredSpell && !IsSpellAppliesAura(m_spellInfo, SPELL_AURA_SCHOOL_IMMUNITY) && !IsSpellAppliesAura(m_spellInfo, SPELL_AURA_MECHANIC_IMMUNITY) && m_caster->hasUnitState(UNIT_STAT_ISOLATED | UNIT_STAT_STUNNED | UNIT_STAT_PENDING_STUNNED | UNIT_STAT_CONFUSED | UNIT_STAT_FLEEING)) return SPELL_FAILED_DONT_REPORT; From 7910236ab6184db0c9d512e12acf62df395245b5 Mon Sep 17 00:00:00 2001 From: Staden Date: Wed, 24 May 2017 20:59:09 +0100 Subject: [PATCH 16/16] Revert "fix object pools respawn after restart (#424)" This reverts commit 8f6aa9cc2b55f0cd05416b37a500b4d4d5381f0e. --- src/game/Maps/Map.cpp | 2 -- src/game/Maps/MapPersistentStateMgr.cpp | 6 ++-- src/game/Maps/Pool/PoolManager.cpp | 47 ------------------------- src/game/Maps/Pool/PoolManager.h | 2 -- 4 files changed, 2 insertions(+), 55 deletions(-) diff --git a/src/game/Maps/Map.cpp b/src/game/Maps/Map.cpp index 32a762981..4040cff22 100644 --- a/src/game/Maps/Map.cpp +++ b/src/game/Maps/Map.cpp @@ -153,8 +153,6 @@ public: void Map::SpawnActiveObjects() { - if (MapPersistentState* state = GetPersistentState()) - state->InitPools(); ActiveObjectsGridLoader loader(this); sObjectMgr.DoGOData(loader); sObjectMgr.DoCreatureData(loader); diff --git a/src/game/Maps/MapPersistentStateMgr.cpp b/src/game/Maps/MapPersistentStateMgr.cpp index 492dc060b..03adb0b02 100644 --- a/src/game/Maps/MapPersistentStateMgr.cpp +++ b/src/game/Maps/MapPersistentStateMgr.cpp @@ -970,8 +970,7 @@ void MapPersistentStateManager::LoadCreatureRespawnTimes() for (int instance = beginInstance; instance < endInstance; ++instance) { - MapPersistentState* state = AddPersistentState(mapEntry, instance, - resetTime, mapEntry->IsDungeon(), true, false /*= initPools*/); + MapPersistentState* state = AddPersistentState(mapEntry, instance, resetTime, mapEntry->IsDungeon(), true); if (!state) continue; @@ -1050,8 +1049,7 @@ void MapPersistentStateManager::LoadGameobjectRespawnTimes() for (int instance = beginInstance; instance < endInstance; ++instance) { - MapPersistentState* state = AddPersistentState(mapEntry, instance, - resetTime, mapEntry->IsDungeon(), true, false /*= initPools*/); + MapPersistentState* state = AddPersistentState(mapEntry, instance, resetTime, mapEntry->IsDungeon(), true); if (!state) continue; diff --git a/src/game/Maps/Pool/PoolManager.cpp b/src/game/Maps/Pool/PoolManager.cpp index b3c363cc8..a6e6c9c60 100644 --- a/src/game/Maps/Pool/PoolManager.cpp +++ b/src/game/Maps/Pool/PoolManager.cpp @@ -360,35 +360,6 @@ void PoolGroup::SpawnObject(MapPersistentState& mapState, uint32 limit, uint3 // spawned by 1 if (triggerFrom && spawns.IsSpawnedObject(triggerFrom)) ++count; - // Instance loading : no object spawned, check if any timers have been loaded - // from the database and spawn the object at the right location - else if (count && count == limit) - { - if (!ExplicitlyChanced.empty()) - { - for (uint32 i = 0; i < ExplicitlyChanced.size(); ++i) - { - if (count && GetPoolObjectRespawnTime(mapState, ExplicitlyChanced[i].guid)) - { - spawns.AddSpawn(ExplicitlyChanced[i].guid, poolId); - Spawn1Object(mapState, &ExplicitlyChanced[i], instantly); - --count; - } - } - } - else if (!EqualChanced.empty()) - { - for (int i = 0; i < EqualChanced.size(); ++i) - { - if (count && GetPoolObjectRespawnTime(mapState, EqualChanced[i].guid)) - { - spawns.AddSpawn(EqualChanced[i].guid, poolId); - Spawn1Object(mapState, &EqualChanced[i], instantly); - --count; - } - } - } - } // This will try to spawn the rest of pool, not guaranteed for (int i = 0; i < count; ++i) @@ -421,24 +392,6 @@ void PoolGroup::SpawnObject(MapPersistentState& mapState, uint32 limit, uint3 } } -template <> -time_t PoolGroup::GetPoolObjectRespawnTime(MapPersistentState& mapState, uint32 guid) -{ - return mapState.GetCreatureRespawnTime(guid); -} - -template <> -time_t PoolGroup::GetPoolObjectRespawnTime(MapPersistentState& mapState, uint32 guid) -{ - return mapState.GetGORespawnTime(guid); -} - -template <> -time_t PoolGroup::GetPoolObjectRespawnTime(MapPersistentState& mapState, uint32 guid) -{ - return 0; -} - // Method that is actualy doing the spawn job on 1 creature template <> void PoolGroup::Spawn1Object(MapPersistentState& mapState, PoolObject* obj, bool instantly) diff --git a/src/game/Maps/Pool/PoolManager.h b/src/game/Maps/Pool/PoolManager.h index 1bd3e9195..d17269422 100644 --- a/src/game/Maps/Pool/PoolManager.h +++ b/src/game/Maps/Pool/PoolManager.h @@ -137,8 +137,6 @@ class PoolGroup void ReSpawn1Object(MapPersistentState& mapState, PoolObject* obj); void RemoveOneRelation(uint16 child_pool_id); - time_t GetPoolObjectRespawnTime(MapPersistentState& mapState, uint32 guid); - PoolObjectList const& GetExplicitlyChanced() const { return ExplicitlyChanced; } PoolObjectList const& GetEqualChanced() const { return EqualChanced; }