[8867] Implement expected combat stop with friendly faction
[getmangos.git] / src / game / Unit.cpp
blob83e839cc5e9b97b3c44df8c5f100446d16616653
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Log.h"
21 #include "Opcodes.h"
22 #include "WorldPacket.h"
23 #include "WorldSession.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "ObjectDefines.h"
27 #include "SpellMgr.h"
28 #include "Unit.h"
29 #include "QuestDef.h"
30 #include "Player.h"
31 #include "Creature.h"
32 #include "Spell.h"
33 #include "Group.h"
34 #include "SpellAuras.h"
35 #include "MapManager.h"
36 #include "ObjectAccessor.h"
37 #include "CreatureAI.h"
38 #include "Formulas.h"
39 #include "Pet.h"
40 #include "Util.h"
41 #include "Totem.h"
42 #include "BattleGround.h"
43 #include "InstanceSaveMgr.h"
44 #include "GridNotifiersImpl.h"
45 #include "CellImpl.h"
46 #include "Path.h"
47 #include "Traveller.h"
48 #include "VMapFactory.h"
50 #include <math.h>
52 float baseMoveSpeed[MAX_MOVE_TYPE] =
54 2.5f, // MOVE_WALK
55 7.0f, // MOVE_RUN
56 1.25f, // MOVE_RUN_BACK
57 4.722222f, // MOVE_SWIM
58 4.5f, // MOVE_SWIM_BACK
59 3.141594f, // MOVE_TURN_RATE
60 7.0f, // MOVE_FLIGHT
61 4.5f, // MOVE_FLIGHT_BACK
62 3.14f // MOVE_PITCH_RATE
65 // Used for prepare can/can`t triggr aura
66 static bool InitTriggerAuraData();
67 // Define can trigger auras
68 static bool isTriggerAura[TOTAL_AURAS];
69 // Define can`t trigger auras (need for disable second trigger)
70 static bool isNonTriggerAura[TOTAL_AURAS];
71 // Prepare lists
72 static bool procPrepared = InitTriggerAuraData();
74 Unit::Unit()
75 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostileRefManager(this)
77 m_objectType |= TYPEMASK_UNIT;
78 m_objectTypeId = TYPEID_UNIT;
80 m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
82 m_attackTimer[BASE_ATTACK] = 0;
83 m_attackTimer[OFF_ATTACK] = 0;
84 m_attackTimer[RANGED_ATTACK] = 0;
85 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
86 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
87 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
89 m_extraAttacks = 0;
91 m_state = 0;
92 m_form = FORM_NONE;
93 m_deathState = ALIVE;
95 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
96 m_currentSpells[i] = NULL;
98 m_addDmgOnce = 0;
100 for(int i = 0; i < MAX_TOTEM; ++i)
101 m_TotemSlot[i] = 0;
103 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
104 //m_Aura = NULL;
105 //m_AurasCheck = 2000;
106 //m_removeAuraTimer = 4;
107 m_AurasUpdateIterator = m_Auras.end();
108 m_AuraFlags = 0;
110 m_Visibility = VISIBILITY_ON;
112 m_detectInvisibilityMask = 0;
113 m_invisibilityMask = 0;
114 m_transform = 0;
115 m_ShapeShiftFormSpellId = 0;
116 m_canModifyStats = false;
118 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
119 m_spellImmune[i].clear();
120 for (int i = 0; i < UNIT_MOD_END; ++i)
122 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
123 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
124 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
125 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
127 // implement 50% base damage from offhand
128 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
130 for (int i = 0; i < MAX_ATTACK; ++i)
132 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
133 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
135 for (int i = 0; i < MAX_STATS; ++i)
136 m_createStats[i] = 0.0f;
138 m_attacking = NULL;
139 m_modMeleeHitChance = 0.0f;
140 m_modRangedHitChance = 0.0f;
141 m_modSpellHitChance = 0.0f;
142 m_baseSpellCritChance = 5;
144 m_CombatTimer = 0;
145 m_lastManaUseTimer = 0;
147 //m_victimThreat = 0.0f;
148 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
149 m_threatModifier[i] = 1.0f;
150 m_isSorted = true;
151 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
152 m_speed_rate[i] = 1.0f;
154 m_charmInfo = NULL;
156 // remove aurastates allowing special moves
157 for(int i=0; i < MAX_REACTIVE; ++i)
158 m_reactiveTimer[i] = 0;
161 Unit::~Unit()
163 // set current spells as deletable
164 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
166 if (m_currentSpells[i])
168 m_currentSpells[i]->SetReferencedFromCurrent(false);
169 m_currentSpells[i] = NULL;
173 if (m_charmInfo)
174 delete m_charmInfo;
176 // those should be already removed at "RemoveFromWorld()" call
177 assert(m_gameObj.size() == 0);
178 assert(m_dynObjGUIDs.size() == 0);
181 void Unit::Update( uint32 p_time )
183 if(!IsInWorld())
184 return;
186 /*if(p_time > m_AurasCheck)
188 m_AurasCheck = 2000;
189 _UpdateAura();
190 }else
191 m_AurasCheck -= p_time;*/
193 // WARNING! Order of execution here is important, do not change.
194 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
195 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
196 m_Events.Update( p_time );
197 _UpdateSpells( p_time );
199 if (m_lastManaUseTimer)
201 if (p_time >= m_lastManaUseTimer)
202 m_lastManaUseTimer = 0;
203 else
204 m_lastManaUseTimer -= p_time;
207 // really delete auras "deleted" while processing its ApplyModify code
208 for(AuraList::const_iterator itr = m_deletedAuras.begin(); itr != m_deletedAuras.begin(); ++itr)
209 delete *itr;
210 m_deletedAuras.clear();
212 if (CanHaveThreatList())
213 getThreatManager().UpdateForClient(p_time);
215 // update combat timer only for players and pets
216 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
218 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
219 // targets without stopping half way there and running off.
220 // These flags are reset after target dies or another command is given.
221 if( m_HostileRefManager.isEmpty() )
223 // m_CombatTimer set at aura start and it will be freeze until aura removing
224 if ( m_CombatTimer <= p_time )
225 ClearInCombat();
226 else
227 m_CombatTimer -= p_time;
231 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
233 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
236 // update abilities available only for fraction of time
237 UpdateReactives( p_time );
239 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
240 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
241 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
243 i_motionMaster.UpdateMotion(p_time);
246 bool Unit::haveOffhandWeapon() const
248 if(GetTypeId() == TYPEID_PLAYER)
249 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
250 else
251 return false;
254 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, MonsterMovementFlags flags, uint32 Time, Player* player)
256 float moveTime = Time;
258 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
259 data.append(GetPackGUID());
260 data << uint8(0); // new in 3.1
261 data << GetPositionX() << GetPositionY() << GetPositionZ();
262 data << uint32(getMSTime());
264 data << uint8(type); // unknown
265 switch(type)
267 case 0: // normal packet
268 break;
269 case 1: // stop packet (raw pos?)
270 SendMessageToSet( &data, true );
271 return;
272 case 2: // facing spot, not used currently
273 data << float(0);
274 data << float(0);
275 data << float(0);
276 break;
277 case 3: // not used currently
278 data << uint64(0); // probably target guid (facing target?)
279 break;
280 case 4: // not used currently
281 data << float(0); // facing angle
282 break;
285 data << uint32(flags);
287 if(flags & MONSTER_MOVE_WALK)
288 moveTime *= 1.05f;
290 data << uint32(moveTime); // Time in between points
291 data << uint32(1); // 1 single waypoint
292 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
294 if(player)
295 player->GetSession()->SendPacket(&data);
296 else
297 SendMessageToSet( &data, true );
300 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, MonsterMovementFlags flags)
302 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
304 uint32 pathSize = end - start;
306 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+1+4+4+4+4+1+4+4+4+pathSize*4*3) );
307 data.append(GetPackGUID());
308 data << uint8(0);
309 data << GetPositionX();
310 data << GetPositionY();
311 data << GetPositionZ();
312 data << uint32(getMSTime());
313 data << uint8(0);
314 data << uint32(flags);
315 data << uint32(traveltime);
316 data << uint32(pathSize);
317 data.append((char*)path.GetNodes(start), pathSize * 4 * 3);
318 SendMessageToSet(&data, true);
321 void Unit::BuildHeartBeatMsg(WorldPacket *data) const
323 MovementFlags move_flags = GetTypeId()==TYPEID_PLAYER
324 ? ((Player const*)this)->m_movementInfo.GetMovementFlags()
325 : MOVEMENTFLAG_NONE;
327 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
328 data->append(GetPackGUID());
329 *data << uint32(move_flags); // movement flags
330 *data << uint16(0); // 2.3.0
331 *data << uint32(getMSTime()); // time
332 *data << float(GetPositionX());
333 *data << float(GetPositionY());
334 *data << float(GetPositionZ());
335 *data << float(GetOrientation());
336 *data << uint32(0);
339 void Unit::resetAttackTimer(WeaponAttackType type)
341 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
344 bool Unit::canReachWithAttack(Unit *pVictim) const
346 assert(pVictim);
347 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
348 if( reach <= 0.0f )
349 reach = 1.0f;
350 return IsWithinDistInMap(pVictim, reach);
353 void Unit::RemoveSpellsCausingAura(AuraType auraType)
355 if (auraType >= TOTAL_AURAS) return;
356 AuraList::const_iterator iter, next;
357 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
359 next = iter;
360 ++next;
362 if (*iter)
364 RemoveAurasDueToSpell((*iter)->GetId());
365 if (!m_modAuras[auraType].empty())
366 next = m_modAuras[auraType].begin();
367 else
368 return;
373 bool Unit::HasAuraType(AuraType auraType) const
375 return (!m_modAuras[auraType].empty());
378 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
379 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
381 if(!HasAuraType(auraType))
382 return;
384 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
385 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
386 float chance = float(damage) / max_dmg * 100.0f;
387 if (roll_chance_f(chance))
388 RemoveSpellsCausingAura(auraType);
391 void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
393 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
395 if(absorb)
396 absorb += damage;
397 damage = 0;
398 return;
401 //You don't lose health from damage taken from another player while in a sanctuary
402 //You still see it in the combat log though
403 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
405 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
406 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
408 if(absorb)
409 absorb += damage;
410 damage = 0;
414 uint32 originalDamage = damage;
416 //Script Event damage Deal
417 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
418 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
419 //Script Event damage taken
420 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
421 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
423 if(absorb && originalDamage > damage)
424 absorb += (originalDamage - damage);
427 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
429 // remove affects from victim (including from 0 damage and DoTs)
430 if(pVictim != this)
431 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
433 // remove affects from attacker at any non-DoT damage (including 0 damage)
434 if( damagetype != DOT)
436 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
437 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
439 if(pVictim != this)
440 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
442 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
443 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
446 if(!damage)
448 // Rage from physical damage received .
449 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
450 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
452 return 0;
454 if (!spellProto || !IsSpellHaveAura(spellProto,SPELL_AURA_MOD_FEAR))
455 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
456 // root type spells do not dispel the root effect
457 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsSpellHaveAura(spellProto,SPELL_AURA_MOD_ROOT)))
458 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
460 // no xp,health if type 8 /critters/
461 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
463 pVictim->setDeathState(JUST_DIED);
464 pVictim->SetHealth(0);
466 // allow loot only if has loot_id in creature_template
467 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
468 if(cInfo && cInfo->lootid)
469 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
471 // some critters required for quests (need normal entry instead possible heroic in any cases)
472 if(GetTypeId() == TYPEID_PLAYER)
473 if(CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
474 ((Player*)this)->KilledMonster(normalInfo,pVictim->GetGUID());
476 return damage;
479 DEBUG_LOG("DealDamageStart");
481 uint32 health = pVictim->GetHealth();
482 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
484 // duel ends when player has 1 or less hp
485 bool duel_hasEnded = false;
486 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
488 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
489 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
490 damage = health-1;
492 duel_hasEnded = true;
494 //Get in CombatState
495 if(pVictim != this && damagetype != DOT)
497 SetInCombatWith(pVictim);
498 pVictim->SetInCombatWith(this);
500 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
501 SetContestedPvP(attackedPlayer);
504 // Rage from Damage made (only from direct weapon damage)
505 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
507 uint32 weaponSpeedHitFactor;
509 switch(cleanDamage->attackType)
511 case BASE_ATTACK:
513 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
514 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
515 else
516 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
518 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
520 break;
522 case OFF_ATTACK:
524 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
525 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
526 else
527 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
529 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
531 break;
533 case RANGED_ATTACK:
534 break;
538 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
540 Player *killer = ((Player*)this);
542 // in bg, count dmg if victim is also a player
543 if (pVictim->GetTypeId()==TYPEID_PLAYER)
545 if (BattleGround *bg = killer->GetBattleGround())
547 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
548 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
552 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
553 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
556 if (pVictim->GetTypeId() == TYPEID_PLAYER)
557 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
559 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
560 ((Creature*)pVictim)->SetLootRecipient(this);
562 if (health <= damage)
564 DEBUG_LOG("DealDamage: victim just died");
566 if (pVictim->GetTypeId() == TYPEID_PLAYER)
567 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
569 // find player: owner of controlled `this` or `this` itself maybe
570 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
572 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
573 player = ((Creature*)pVictim)->GetLootRecipient();
574 // Reward player, his pets, and group/raid members
575 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
576 if(player && player!=pVictim)
578 player->RewardPlayerAndGroupAtKill(pVictim);
579 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
581 WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); //send event PARTY_KILL
582 data << uint64(player->GetGUID()); //player with killing blow
583 data << uint64(pVictim->GetGUID()); //victim
584 if (Group *group = player->GetGroup())
585 group->BroadcastPacket(&data, group->GetMemberGroup(player->GetGUID()));
586 else
587 player->SendDirectMessage(&data);
590 DEBUG_LOG("DealDamageAttackStop");
592 // stop combat
593 pVictim->CombatStop();
594 pVictim->getHostileRefManager().deleteReferences();
596 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
598 // if talent known but not triggered (check priest class for speedup check)
599 Aura* spiritOfRedemtionTalentReady = NULL;
600 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
601 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
603 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
604 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
606 if((*itr)->GetSpellProto()->SpellIconID==1654)
608 spiritOfRedemtionTalentReady = *itr;
609 break;
614 DEBUG_LOG("SET JUST_DIED");
615 if(!spiritOfRedemtionTalentReady)
616 pVictim->setDeathState(JUST_DIED);
618 DEBUG_LOG("DealDamageHealth1");
620 if(spiritOfRedemtionTalentReady)
622 // save value before aura remove
623 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
624 if(!ressSpellId)
625 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
627 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
628 pVictim->RemoveAllAurasOnDeath();
630 // restore for use at real death
631 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
633 // FORM_SPIRITOFREDEMPTION and related auras
634 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
636 else
637 pVictim->SetHealth(0);
639 // remember victim PvP death for corpse type and corpse reclaim delay
640 // at original death (not at SpiritOfRedemtionTalent timeout)
641 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
642 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
644 // Call KilledUnit for creatures
645 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
646 ((Creature*)this)->AI()->KilledUnit(pVictim);
648 // achievement stuff
649 if (pVictim->GetTypeId() == TYPEID_PLAYER)
651 if (GetTypeId() == TYPEID_UNIT)
652 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
653 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
654 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
657 // 10% durability loss on death
658 // clean InHateListOf
659 if (pVictim->GetTypeId() == TYPEID_PLAYER)
661 // only if not player and not controlled by player pet. And not at BG
662 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
664 DEBUG_LOG("We are dead, loosing 10 percents durability");
665 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
666 // durability lost message
667 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
668 ((Player*)pVictim)->GetSession()->SendPacket(&data);
671 else // creature died
673 DEBUG_LOG("DealDamageNotPlayer");
674 Creature *cVictim = (Creature*)pVictim;
676 if(!cVictim->isPet())
678 cVictim->DeleteThreatList();
679 // only lootable if it has loot or can drop gold
680 if(cVictim->GetCreatureInfo()->lootid || cVictim->GetCreatureInfo()->maxgold > 0)
681 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
682 else
683 cVictim->lootForBody = true; // needed for skinning
685 // Call creature just died function
686 if (cVictim->AI())
687 cVictim->AI()->JustDied(this);
689 // Dungeon specific stuff, only applies to players killing creatures
690 if(cVictim->GetInstanceId())
692 Map *m = cVictim->GetMap();
693 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
694 // TODO: do instance binding anyway if the charmer/owner is offline
696 if(m->IsDungeon() && creditedPlayer)
698 if (m->IsRaidOrHeroicDungeon())
700 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
701 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
703 else
705 // the reset time is set but not added to the scheduler
706 // until the players leave the instance
707 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
708 if(InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(cVictim->GetInstanceId()))
709 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
715 // last damage from non duel opponent or opponent controlled creature
716 if(duel_hasEnded)
718 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
719 Player *he = (Player*)pVictim;
721 assert(he->duel);
723 he->duel->opponent->CombatStopWithPets(true);
724 he->CombatStopWithPets(true);
726 he->DuelComplete(DUEL_INTERUPTED);
729 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
730 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
732 Player *killed = ((Player*)pVictim);
733 if(BattleGround *bg = killed->GetBattleGround())
734 if(player)
735 bg->HandleKillPlayer(killed, player);
737 else if(pVictim->GetTypeId() == TYPEID_UNIT)
739 if (player)
740 if (BattleGround *bg = player->GetBattleGround())
741 bg->HandleKillUnit((Creature*)pVictim, player);
744 else // if (health <= damage)
746 DEBUG_LOG("DealDamageAlive");
748 if (pVictim->GetTypeId() == TYPEID_PLAYER)
749 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
751 pVictim->ModifyHealth(- (int32)damage);
753 if(damagetype != DOT)
755 if(!getVictim())
757 // if not have main target then attack state with target (including AI call)
758 //start melee attacks only after melee hit
759 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
762 // if damage pVictim call AI reaction
763 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
764 ((Creature*)pVictim)->AI()->AttackedBy(this);
767 // polymorphed and other negative transformed cases
768 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
769 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
771 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
773 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
774 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
776 if (pVictim->GetTypeId() != TYPEID_PLAYER)
778 if(spellProto && IsDamageToThreatSpell(spellProto))
779 pVictim->AddThreat(this, damage*2, (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
780 else
781 pVictim->AddThreat(this, damage, (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
783 else // victim is a player
785 // Rage from damage received
786 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
788 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
789 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
792 // random durability for items (HIT TAKEN)
793 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
795 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
796 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
800 if(GetTypeId()==TYPEID_PLAYER)
802 // random durability for items (HIT DONE)
803 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
805 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
806 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
810 // TODO: Store auras by interrupt flag to speed this up.
811 AuraMap& vAuras = pVictim->GetAuras();
812 for (AuraMap::const_iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
814 const SpellEntry *se = i->second->GetSpellProto();
815 next = i; ++next;
816 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
817 continue;
818 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
820 bool remove = true;
821 if (se->procFlags & (1<<3))
823 if (!roll_chance_i(se->procChance))
824 remove = false;
826 if (remove)
828 pVictim->RemoveAurasDueToSpell(i->second->GetId());
829 // FIXME: this may cause the auras with proc chance to be rerolled several times
830 next = vAuras.begin();
835 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
837 if( damagetype != DOT )
839 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
841 // skip channeled spell (processed differently below)
842 if (i == CURRENT_CHANNELED_SPELL)
843 continue;
845 if(Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i)))
847 if(spell->getState() == SPELL_STATE_PREPARING)
849 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
850 pVictim->InterruptSpell(CurrentSpellTypes(i));
851 else
852 spell->Delayed();
858 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
860 if (spell->getState() == SPELL_STATE_CASTING)
862 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
863 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
865 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
866 spell->DelayedChannel();
868 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
870 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
871 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
874 else if (spell->getState() == SPELL_STATE_DELAYED)
875 // break channeled spell in delayed state on damage
877 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
878 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
883 // last damage from duel opponent
884 if(duel_hasEnded)
886 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
887 Player *he = (Player*)pVictim;
889 assert(he->duel);
891 he->SetHealth(1);
893 he->duel->opponent->CombatStopWithPets(true);
894 he->CombatStopWithPets(true);
896 he->CastSpell(he, 7267, true); // beg
897 he->DuelComplete(DUEL_WON);
901 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
903 return damage;
906 void Unit::CastStop(uint32 except_spellid)
908 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
909 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
910 InterruptSpell(CurrentSpellTypes(i),false);
913 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
915 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
917 if(!spellInfo)
919 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
920 return;
923 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
926 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
928 if(!spellInfo)
930 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
931 return;
934 if (castItem)
935 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
937 if(!originalCaster && triggeredByAura)
938 originalCaster = triggeredByAura->GetCasterGUID();
940 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
942 SpellCastTargets targets;
943 targets.setUnitTarget( Victim );
944 spell->m_CastItem = castItem;
945 spell->prepare(&targets, triggeredByAura);
948 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
950 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
952 if(!spellInfo)
954 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
955 return;
958 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
961 void Unit::CastCustomSpell(Unit* Victim,SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
963 if(!spellInfo)
965 sLog.outError("CastCustomSpell: unknown spell");
966 return;
969 if (castItem)
970 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
972 if(!originalCaster && triggeredByAura)
973 originalCaster = triggeredByAura->GetCasterGUID();
975 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
977 if(bp0)
978 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
980 if(bp1)
981 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
983 if(bp2)
984 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
986 SpellCastTargets targets;
987 targets.setUnitTarget( Victim );
988 spell->m_CastItem = castItem;
989 spell->prepare(&targets, triggeredByAura);
992 // used for scripting
993 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
995 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
997 if(!spellInfo)
999 sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
1000 return;
1003 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
1006 // used for scripting
1007 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
1009 if(!spellInfo)
1011 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
1012 return;
1015 if (castItem)
1016 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
1018 if(!originalCaster && triggeredByAura)
1019 originalCaster = triggeredByAura->GetCasterGUID();
1021 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
1023 SpellCastTargets targets;
1024 targets.setDestination(x, y, z);
1025 spell->m_CastItem = castItem;
1026 spell->prepare(&targets, triggeredByAura);
1029 // Obsolete func need remove, here only for comotability vs another patches
1030 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
1032 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
1033 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
1034 CalculateSpellDamage(&damageInfo, damage, spellInfo);
1035 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
1036 SendSpellNonMeleeDamageLog(&damageInfo);
1037 DealSpellDamage(&damageInfo, true);
1038 return damageInfo.damage;
1041 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
1043 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
1044 Unit *pVictim = damageInfo->target;
1046 if (damage < 0)
1047 return;
1049 if(!this || !pVictim)
1050 return;
1051 if(!this->isAlive() || !pVictim->isAlive())
1052 return;
1054 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1055 // Check spell crit chance
1056 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1057 bool blocked = false;
1059 // damage bonus (per damage class)
1060 switch (spellInfo->DmgClass)
1062 // Melee and Ranged Spells
1063 case SPELL_DAMAGE_CLASS_RANGED:
1064 case SPELL_DAMAGE_CLASS_MELEE:
1066 //Calculate damage bonus
1067 damage = MeleeDamageBonus(pVictim, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE);
1068 // Get blocked status
1069 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1071 // if crit add critical bonus
1072 if (crit)
1074 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1075 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1076 // Resilience - reduce crit damage
1077 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1078 if (attackType != RANGED_ATTACK)
1079 damage -= pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1080 else
1081 damage -= pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1084 break;
1085 // Magical Attacks
1086 case SPELL_DAMAGE_CLASS_NONE:
1087 case SPELL_DAMAGE_CLASS_MAGIC:
1089 // Calculate damage bonus
1090 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1091 // If crit add critical bonus
1092 if (crit)
1094 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1095 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1096 // Resilience - reduce crit damage
1097 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1098 damage -= pVictim->GetSpellCritDamageReduction(redunction_affected_damage);
1101 break;
1104 // only from players
1105 if (GetTypeId() == TYPEID_PLAYER)
1107 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1108 damage -= pVictim->GetSpellDamageReduction(redunction_affected_damage);
1111 // damage mitigation
1112 if (damage > 0)
1114 // physical damage => armor
1115 if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
1117 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1118 damage = damage - armor_affected_damage + CalcArmorReducedDamage(pVictim, armor_affected_damage);
1121 // block (only for damage class ranged and -melee, also non-physical damage possible)
1122 if (blocked)
1124 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1125 if (damage < damageInfo->blocked)
1126 damageInfo->blocked = damage;
1127 damage-=damageInfo->blocked;
1130 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damage,damageSchoolMask,spellInfo);
1131 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, !(spellInfo->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED));
1132 damage-= damageInfo->absorb + damageInfo->resist;
1134 else
1135 damage = 0;
1136 damageInfo->damage = damage;
1139 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1141 if (!damageInfo)
1142 return;
1144 Unit *pVictim = damageInfo->target;
1146 if(!this || !pVictim)
1147 return;
1149 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1150 return;
1152 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1153 if (spellProto == NULL)
1155 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1156 return;
1159 //You don't lose health from damage taken from another player while in a sanctuary
1160 //You still see it in the combat log though
1161 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1163 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1164 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1165 return;
1168 // Call default DealDamage (send critical in hit info for threat calculation)
1169 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT ? MELEE_HIT_CRIT : MELEE_HIT_NORMAL);
1170 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1173 //TODO for melee need create structure as in
1174 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1176 damageInfo->attacker = this;
1177 damageInfo->target = pVictim;
1178 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1179 damageInfo->attackType = attackType;
1180 damageInfo->damage = 0;
1181 damageInfo->cleanDamage = 0;
1182 damageInfo->absorb = 0;
1183 damageInfo->resist = 0;
1184 damageInfo->blocked_amount = 0;
1186 damageInfo->TargetState = 0;
1187 damageInfo->HitInfo = 0;
1188 damageInfo->procAttacker = PROC_FLAG_NONE;
1189 damageInfo->procVictim = PROC_FLAG_NONE;
1190 damageInfo->procEx = PROC_EX_NONE;
1191 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1193 if(!this || !pVictim)
1194 return;
1195 if(!this->isAlive() || !pVictim->isAlive())
1196 return;
1198 // Select HitInfo/procAttacker/procVictim flag based on attack type
1199 switch (attackType)
1201 case BASE_ATTACK:
1202 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
1203 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1204 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1205 break;
1206 case OFF_ATTACK:
1207 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1208 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1209 damageInfo->HitInfo = HITINFO_LEFTSWING;
1210 break;
1211 case RANGED_ATTACK:
1212 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1213 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1214 damageInfo->HitInfo = 0x08;// test
1215 break;
1216 default:
1217 break;
1220 // Physical Immune check
1221 if (damageInfo->target->IsImmunedToDamage(damageInfo->damageSchoolMask))
1223 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1224 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1226 damageInfo->procEx |=PROC_EX_IMMUNE;
1227 damageInfo->damage = 0;
1228 damageInfo->cleanDamage = 0;
1229 return;
1231 damage += CalculateDamage (damageInfo->attackType, false);
1232 // Add melee damage bonus
1233 damage = MeleeDamageBonus(damageInfo->target, damage, damageInfo->attackType);
1234 // Calculate armor reduction
1236 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageInfo->damageSchoolMask);
1237 damageInfo->damage = damage - armor_affected_damage + CalcArmorReducedDamage(damageInfo->target, armor_affected_damage);
1238 damageInfo->cleanDamage += damage - damageInfo->damage;
1240 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1242 // Disable parry or dodge for ranged attack
1243 if (damageInfo->attackType == RANGED_ATTACK)
1245 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1246 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1249 switch(damageInfo->hitOutCome)
1251 case MELEE_HIT_EVADE:
1253 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1254 damageInfo->TargetState = VICTIMSTATE_EVADES;
1256 damageInfo->procEx|=PROC_EX_EVADE;
1257 damageInfo->damage = 0;
1258 damageInfo->cleanDamage = 0;
1259 return;
1261 case MELEE_HIT_MISS:
1263 damageInfo->HitInfo |= HITINFO_MISS;
1264 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1266 damageInfo->procEx|=PROC_EX_MISS;
1267 damageInfo->damage = 0;
1268 damageInfo->cleanDamage = 0;
1269 break;
1271 case MELEE_HIT_NORMAL:
1272 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1273 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1274 break;
1275 case MELEE_HIT_CRIT:
1277 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1278 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1280 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1281 // Crit bonus calc
1282 damageInfo->damage += damageInfo->damage;
1283 int32 mod=0;
1284 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1285 if(damageInfo->attackType == RANGED_ATTACK)
1286 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1287 else
1289 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1290 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1293 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1295 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1296 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1297 if (mod!=0)
1298 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1300 // Resilience - reduce crit damage
1301 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damageInfo->damage,damageInfo->damageSchoolMask);
1302 uint32 resilienceReduction;
1303 if (attackType != RANGED_ATTACK)
1304 resilienceReduction = pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1305 else
1306 resilienceReduction = pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1308 damageInfo->damage -= resilienceReduction;
1309 damageInfo->cleanDamage += resilienceReduction;
1310 break;
1312 case MELEE_HIT_PARRY:
1313 damageInfo->TargetState = VICTIMSTATE_PARRY;
1314 damageInfo->procEx|=PROC_EX_PARRY;
1315 damageInfo->cleanDamage += damageInfo->damage;
1316 damageInfo->damage = 0;
1317 break;
1319 case MELEE_HIT_DODGE:
1320 damageInfo->TargetState = VICTIMSTATE_DODGE;
1321 damageInfo->procEx|=PROC_EX_DODGE;
1322 damageInfo->cleanDamage += damageInfo->damage;
1323 damageInfo->damage = 0;
1324 break;
1325 case MELEE_HIT_BLOCK:
1327 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1328 damageInfo->HitInfo |= HITINFO_BLOCK;
1329 damageInfo->procEx|=PROC_EX_BLOCK;
1330 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1331 if (damageInfo->blocked_amount >= damageInfo->damage)
1333 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1334 damageInfo->blocked_amount = damageInfo->damage;
1336 damageInfo->damage -= damageInfo->blocked_amount;
1337 damageInfo->cleanDamage += damageInfo->blocked_amount;
1338 break;
1340 case MELEE_HIT_GLANCING:
1342 damageInfo->HitInfo |= HITINFO_GLANCING;
1343 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1344 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1345 float reducePercent = 1.0f; //damage factor
1346 // calculate base values and mods
1347 float baseLowEnd = 1.3f;
1348 float baseHighEnd = 1.2f;
1349 switch(getClass()) // lowering base values for casters
1351 case CLASS_SHAMAN:
1352 case CLASS_PRIEST:
1353 case CLASS_MAGE:
1354 case CLASS_WARLOCK:
1355 case CLASS_DRUID:
1356 baseLowEnd -= 0.7f;
1357 baseHighEnd -= 0.3f;
1358 break;
1361 float maxLowEnd = 0.6f;
1362 switch(getClass()) // upper for melee classes
1364 case CLASS_WARRIOR:
1365 case CLASS_ROGUE:
1366 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1369 // calculate values
1370 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1371 float lowEnd = baseLowEnd - ( 0.05f * diff );
1372 float highEnd = baseHighEnd - ( 0.03f * diff );
1374 // apply max/min bounds
1375 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1376 lowEnd = 0.01f;
1377 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1378 lowEnd = maxLowEnd;
1380 if ( highEnd < 0.2f ) //high end limits
1381 highEnd = 0.2f;
1382 if ( highEnd > 0.99f )
1383 highEnd = 0.99f;
1385 if(lowEnd > highEnd) // prevent negative range size
1386 lowEnd = highEnd;
1388 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1390 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1391 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1392 break;
1394 case MELEE_HIT_CRUSHING:
1396 damageInfo->HitInfo |= HITINFO_CRUSHING;
1397 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1398 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1399 // 150% normal damage
1400 damageInfo->damage += (damageInfo->damage / 2);
1401 break;
1403 default:
1405 break;
1408 // only from players
1409 if (GetTypeId() == TYPEID_PLAYER)
1411 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageInfo->damageSchoolMask);
1412 if (attackType != RANGED_ATTACK)
1413 damage -= pVictim->GetMeleeDamageReduction(redunction_affected_damage);
1414 else
1415 damage -= pVictim->GetRangedDamageReduction(redunction_affected_damage);
1418 // Calculate absorb resist
1419 if(int32(damageInfo->damage) > 0)
1421 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1423 // Calculate absorb & resists
1424 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damageInfo->damage,damageInfo->damageSchoolMask);
1425 CalcAbsorbResist(damageInfo->target, damageInfo->damageSchoolMask, DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, true);
1426 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1427 if (damageInfo->absorb)
1429 damageInfo->HitInfo|=HITINFO_ABSORB;
1430 damageInfo->procEx|=PROC_EX_ABSORB;
1432 if (damageInfo->resist)
1433 damageInfo->HitInfo|=HITINFO_RESIST;
1436 else // Umpossible get negative result but....
1437 damageInfo->damage = 0;
1440 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1442 if (damageInfo==0) return;
1443 Unit *pVictim = damageInfo->target;
1445 if(!this || !pVictim)
1446 return;
1448 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1449 return;
1451 //You don't lose health from damage taken from another player while in a sanctuary
1452 //You still see it in the combat log though
1453 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1455 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1456 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1457 return;
1460 // Hmmmm dont like this emotes client must by self do all animations
1461 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1462 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1463 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1464 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1466 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1468 // Get attack timers
1469 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1470 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1471 // Reduce attack time
1472 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1474 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1475 float percent60 = 3.0f * percent20;
1476 if(offtime > percent20 && offtime <= percent60)
1478 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1480 else if(offtime > percent60)
1482 offtime -= 2.0f * percent20;
1483 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1486 else
1488 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1489 float percent60 = 3.0f * percent20;
1490 if(basetime > percent20 && basetime <= percent60)
1492 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1494 else if(basetime > percent60)
1496 basetime -= 2.0f * percent20;
1497 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1502 // Call default DealDamage
1503 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1504 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, damageInfo->damageSchoolMask, NULL, durabilityLoss);
1506 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1507 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1508 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1510 // -probability is between 0% and 40%
1511 // 20% base chance
1512 float Probability = 20.0f;
1514 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1515 if( pVictim->getLevel() < 30 )
1516 Probability = 0.65f*pVictim->getLevel()+0.5f;
1518 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1519 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1521 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1523 if(Probability > 40.0f)
1524 Probability = 40.0f;
1526 if(roll_chance_f(Probability))
1527 CastSpell(pVictim, 1604, true);
1530 // If not miss
1531 if (!(damageInfo->HitInfo & HITINFO_MISS))
1533 // on weapon hit casts
1534 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1535 ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType);
1537 // victim's damage shield
1538 std::set<Aura*> alreadyDone;
1539 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1540 for(AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();)
1542 if (alreadyDone.find(*i) == alreadyDone.end())
1544 alreadyDone.insert(*i);
1545 uint32 damage=(*i)->GetModifier()->m_amount;
1546 SpellEntry const *i_spellProto = (*i)->GetSpellProto();
1547 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1548 //uint32 absorb;
1549 //uint32 resist;
1550 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1551 //damage-=absorb + resist;
1553 pVictim->DealDamageMods(this,damage,NULL);
1555 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1556 data << uint64(pVictim->GetGUID());
1557 data << uint64(GetGUID());
1558 data << uint32(i_spellProto->Id);
1559 data << uint32(damage); // Damage
1560 data << uint32(0); // Overkill
1561 data << uint32(i_spellProto->SchoolMask);
1562 pVictim->SendMessageToSet(&data, true );
1564 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
1566 i = vDamageShields.begin();
1568 else
1569 ++i;
1575 void Unit::HandleEmoteCommand(uint32 anim_id)
1577 WorldPacket data( SMSG_EMOTE, 4 + 8 );
1578 data << uint32(anim_id);
1579 data << uint64(GetGUID());
1580 SendMessageToSet(&data, true);
1583 uint32 Unit::CalcNotIgnoreAbsorbDamage( uint32 damage, SpellSchoolMask damageSchoolMask, SpellEntry const* spellInfo /*= NULL*/)
1585 float absorb_affected_rate = 1.0f;
1586 Unit::AuraList const& ignoreAbsorbSchool = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL);
1587 for(Unit::AuraList::const_iterator i = ignoreAbsorbSchool.begin(); i != ignoreAbsorbSchool.end(); ++i)
1588 if ((*i)->GetMiscValue() & damageSchoolMask)
1589 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1591 if(spellInfo)
1593 Unit::AuraList const& ignoreAbsorbForSpell = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1594 for(Unit::AuraList::const_iterator citr = ignoreAbsorbForSpell.begin(); citr != ignoreAbsorbForSpell.end(); ++citr)
1595 if ((*citr)->isAffectedOnSpell(spellInfo))
1596 absorb_affected_rate *= (100.0f - (*citr)->GetModifier()->m_amount)/100.0f;
1599 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1602 uint32 Unit::CalcNotIgnoreDamageRedunction( uint32 damage, SpellSchoolMask damageSchoolMask)
1604 float absorb_affected_rate = 1.0f;
1605 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL);
1606 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1607 if ((*i)->GetMiscValue() & damageSchoolMask)
1608 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1610 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1613 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1615 uint32 newdamage = 0;
1616 float armor = pVictim->GetArmor();
1618 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1619 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1621 // Apply Player CR_ARMOR_PENETRATION rating and percent talents
1622 if (GetTypeId()==TYPEID_PLAYER)
1623 armor *= 1.0f - ((Player*)this)->GetArmorPenetrationPct() / 100.0f;
1625 if (armor < 0.0f)
1626 armor = 0.0f;
1628 float levelModifier = getLevel();
1629 if (levelModifier > 59)
1630 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1632 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1633 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1635 if (tmpvalue < 0.0f)
1636 tmpvalue = 0.0f;
1637 if (tmpvalue > 0.75f)
1638 tmpvalue = 0.75f;
1640 newdamage = uint32(damage - (damage * tmpvalue));
1642 return (newdamage > 1) ? newdamage : 1;
1645 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, bool canReflect)
1647 if(!pVictim || !pVictim->isAlive() || !damage)
1648 return;
1650 // Magic damage, check for resists
1651 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1653 // Get base victim resistance for school
1654 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1655 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1656 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1658 tmpvalue2 *= (float)(0.15f / getLevel());
1659 if (tmpvalue2 < 0.0f)
1660 tmpvalue2 = 0.0f;
1661 if (tmpvalue2 > 0.75f)
1662 tmpvalue2 = 0.75f;
1663 uint32 ran = urand(0, 100);
1664 uint32 faq[4] = {24,6,4,6};
1665 uint8 m = 0;
1666 float Binom = 0.0f;
1667 for (uint8 i = 0; i < 4; ++i)
1669 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1670 if (ran > Binom )
1671 ++m;
1672 else
1673 break;
1675 if (damagetype == DOT && m == 4)
1676 *resist += uint32(damage - 1);
1677 else
1678 *resist += uint32(damage * m / 4);
1679 if(*resist > damage)
1680 *resist = damage;
1682 else
1683 *resist = 0;
1685 int32 RemainingDamage = damage - *resist;
1687 // Get unit state (need for some absorb check)
1688 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1689 // Reflect damage spells (not cast any damage spell in aura lookup)
1690 uint32 reflectSpell = 0;
1691 int32 reflectDamage = 0;
1692 Aura* reflectTriggeredBy = NULL; // expected as not expired at reflect as in current cases
1693 // Death Prevention Aura
1694 SpellEntry const* preventDeathSpell = NULL;
1695 int32 preventDeathAmount = 0;
1696 // Need remove expired auras after
1697 bool existExpired = false;
1698 // absorb without mana cost
1699 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1700 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1702 Modifier* mod = (*i)->GetModifier();
1703 if (!(mod->m_miscvalue & schoolMask))
1704 continue;
1706 SpellEntry const* spellProto = (*i)->GetSpellProto();
1708 // Max Amount can be absorbed by this aura
1709 int32 currentAbsorb = mod->m_amount;
1711 // Found empty aura (impossible but..)
1712 if (currentAbsorb <=0)
1714 existExpired = true;
1715 continue;
1717 // Handle custom absorb auras
1718 // TODO: try find better way
1719 switch(spellProto->SpellFamilyName)
1721 case SPELLFAMILY_GENERIC:
1723 // Astral Shift
1724 if (spellProto->SpellIconID == 3066)
1726 //reduces all damage taken while stun, fear or silence
1727 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1728 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1729 continue;
1731 // Nerves of Steel
1732 if (spellProto->SpellIconID == 2115)
1734 // while affected by Stun and Fear
1735 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1736 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1737 continue;
1739 // Spell Deflection
1740 if (spellProto->SpellIconID == 3006)
1742 // You have a chance equal to your Parry chance
1743 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1744 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1745 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1746 continue;
1748 // Reflective Shield (Lady Malande boss)
1749 if (spellProto->Id == 41475 && canReflect)
1751 if(RemainingDamage < currentAbsorb)
1752 reflectDamage = RemainingDamage / 2;
1753 else
1754 reflectDamage = currentAbsorb / 2;
1755 reflectSpell = 33619;
1756 reflectTriggeredBy = *i;
1757 break;
1759 if (spellProto->Id == 39228 || // Argussian Compass
1760 spellProto->Id == 60218) // Essence of Gossamer
1762 // Max absorb stored in 1 dummy effect
1763 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1764 currentAbsorb = spellProto->EffectBasePoints[1];
1765 break;
1767 break;
1769 case SPELLFAMILY_DRUID:
1771 // Primal Tenacity
1772 if (spellProto->SpellIconID == 2253)
1774 //reduces all damage taken while Stunned
1775 if (unitflag & UNIT_FLAG_STUNNED)
1776 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1777 continue;
1779 break;
1781 case SPELLFAMILY_ROGUE:
1783 // Cheat Death (make less prio with Guardian Spirit case)
1784 if (!preventDeathSpell && spellProto->SpellIconID == 2109 &&
1785 pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1786 !((Player*)pVictim)->HasSpellCooldown(31231) &&
1787 // Only if no cooldown
1788 roll_chance_i((*i)->GetModifier()->m_amount))
1789 // Only if roll
1791 preventDeathSpell = (*i)->GetSpellProto();
1792 continue;
1794 break;
1796 case SPELLFAMILY_PRIEST:
1798 // Guardian Spirit
1799 if (spellProto->SpellIconID == 2873)
1801 preventDeathSpell = (*i)->GetSpellProto();
1802 preventDeathAmount = (*i)->GetModifier()->m_amount;
1803 continue;
1806 // Reflective Shield
1807 if (spellProto->SpellFamilyFlags == 0x1 && canReflect)
1809 if (pVictim == this)
1810 break;
1811 Unit* caster = (*i)->GetCaster();
1812 if (!caster)
1813 break;
1814 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1815 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1817 switch((*k)->GetModifier()->m_miscvalue)
1819 case 5065: // Rank 1
1820 case 5064: // Rank 2
1822 if(RemainingDamage >= currentAbsorb)
1823 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1824 else
1825 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1826 reflectSpell = 33619;
1827 reflectTriggeredBy = *i;
1828 } break;
1829 default: break;
1832 break;
1834 break;
1836 case SPELLFAMILY_SHAMAN:
1838 // Astral Shift
1839 if (spellProto->SpellIconID == 3066)
1841 //reduces all damage taken while stun, fear or silence
1842 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1843 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1844 continue;
1846 break;
1848 case SPELLFAMILY_DEATHKNIGHT:
1850 // Shadow of Death
1851 if (spellProto->SpellIconID == 1958)
1853 // TODO: absorb only while transform
1854 continue;
1856 // Anti-Magic Shell (on self)
1857 if (spellProto->Id == 48707)
1859 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1860 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1861 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1862 int32 regen = absorbed * 2 / 10;
1863 pVictim->CastCustomSpell(pVictim, 49088, &regen, NULL, NULL, true, NULL, *i);
1864 RemainingDamage -= absorbed;
1865 continue;
1867 // Anti-Magic Shell (on single party/raid member)
1868 if (spellProto->Id == 50462)
1870 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1871 continue;
1873 // Anti-Magic Zone
1874 if (spellProto->Id == 50461)
1876 Unit* caster = (*i)->GetCaster();
1877 if (!caster)
1878 continue;
1879 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1880 int32 canabsorb = caster->GetHealth();
1881 if (canabsorb < absorbed)
1882 absorbed = canabsorb;
1884 RemainingDamage -= absorbed;
1886 uint32 ab_damage = absorbed;
1887 DealDamageMods(caster,ab_damage,NULL);
1888 DealDamage(caster, ab_damage, NULL, damagetype, schoolMask, 0, false);
1889 continue;
1891 break;
1893 default:
1894 break;
1897 // currentAbsorb - damage can be absorbed by shield
1898 // If need absorb less damage
1899 if (RemainingDamage < currentAbsorb)
1900 currentAbsorb = RemainingDamage;
1902 RemainingDamage -= currentAbsorb;
1904 // Reduce shield amount
1905 mod->m_amount-=currentAbsorb;
1906 if((*i)->DropAuraCharge())
1907 mod->m_amount = 0;
1908 // Need remove it later
1909 if (mod->m_amount<=0)
1910 existExpired = true;
1913 // Remove all expired absorb auras
1914 if (existExpired)
1916 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1918 if ((*i)->GetModifier()->m_amount<=0)
1920 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1921 i = vSchoolAbsorb.begin();
1923 else
1924 ++i;
1928 // Cast back reflect damage spell
1929 if (canReflect && reflectSpell)
1930 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true, NULL, reflectTriggeredBy);
1932 // absorb by mana cost
1933 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1934 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1936 next = i; ++next;
1938 // check damage school mask
1939 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1940 continue;
1942 int32 currentAbsorb;
1943 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1944 currentAbsorb = (*i)->GetModifier()->m_amount;
1945 else
1946 currentAbsorb = RemainingDamage;
1948 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1949 if(Player *modOwner = pVictim->GetSpellModOwner())
1950 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1952 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1953 if (currentAbsorb > maxAbsorb)
1954 currentAbsorb = maxAbsorb;
1956 (*i)->GetModifier()->m_amount -= currentAbsorb;
1957 if((*i)->GetModifier()->m_amount <= 0)
1959 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1960 next = vManaShield.begin();
1963 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1964 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1966 RemainingDamage -= currentAbsorb;
1969 // only split damage if not damaging yourself
1970 if(pVictim != this)
1972 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1973 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1975 next = i; ++next;
1977 // check damage school mask
1978 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1979 continue;
1981 // Damage can be splitted only if aura has an alive caster
1982 Unit *caster = (*i)->GetCaster();
1983 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1984 continue;
1986 int32 currentAbsorb;
1987 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1988 currentAbsorb = (*i)->GetModifier()->m_amount;
1989 else
1990 currentAbsorb = RemainingDamage;
1992 RemainingDamage -= currentAbsorb;
1995 uint32 splitted = currentAbsorb;
1996 uint32 splitted_absorb = 0;
1997 DealDamageMods(caster,splitted,&splitted_absorb);
1999 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
2001 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2002 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2005 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
2006 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
2008 next = i; ++next;
2010 // check damage school mask
2011 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2012 continue;
2014 // Damage can be splitted only if aura has an alive caster
2015 Unit *caster = (*i)->GetCaster();
2016 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
2017 continue;
2019 uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
2021 RemainingDamage -= int32(splitted);
2023 uint32 split_absorb = 0;
2024 DealDamageMods(caster,splitted,&split_absorb);
2026 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
2028 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2029 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2033 // Apply death prevention spells effects
2034 if (preventDeathSpell && RemainingDamage >= pVictim->GetHealth())
2036 switch(preventDeathSpell->SpellFamilyName)
2038 // Cheat Death
2039 case SPELLFAMILY_ROGUE:
2041 // Cheat Death
2042 if (preventDeathSpell->SpellIconID == 2109)
2044 pVictim->CastSpell(pVictim,31231,true);
2045 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
2046 // with health > 10% lost health until health==10%, in other case no losses
2047 uint32 health10 = pVictim->GetMaxHealth()/10;
2048 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
2050 break;
2052 // Guardian Spirit
2053 case SPELLFAMILY_PRIEST:
2055 // Guardian Spirit
2056 if (preventDeathSpell->SpellIconID == 2873)
2058 int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
2059 pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
2060 pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
2061 RemainingDamage = 0;
2063 break;
2068 *absorb = damage - RemainingDamage - *resist;
2071 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
2073 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING | UNIT_STAT_DIED) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
2074 return;
2076 if (!pVictim->isAlive())
2077 return;
2079 if(IsNonMeleeSpellCasted(false))
2080 return;
2082 uint32 hitInfo;
2083 if (attType == BASE_ATTACK)
2084 hitInfo = HITINFO_NORMALSWING2;
2085 else if (attType == OFF_ATTACK)
2086 hitInfo = HITINFO_LEFTSWING;
2087 else
2088 return; // ignore ranged case
2090 uint32 extraAttacks = m_extraAttacks;
2092 // melee attack spell casted at main hand attack only
2093 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
2095 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
2097 // not recent extra attack only at any non extra attack (melee spell case)
2098 if(!extra && extraAttacks)
2100 while(m_extraAttacks)
2102 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2103 if(m_extraAttacks > 0)
2104 --m_extraAttacks;
2107 return;
2110 // attack can be redirected to another target
2111 pVictim = SelectMagnetTarget(pVictim);
2113 CalcDamageInfo damageInfo;
2114 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
2115 // Send log damage message to client
2116 DealDamageMods(pVictim,damageInfo.damage,&damageInfo.absorb);
2117 SendAttackStateUpdate(&damageInfo);
2118 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
2119 DealMeleeDamage(&damageInfo,true);
2121 if (GetTypeId() == TYPEID_PLAYER)
2122 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2123 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2124 else
2125 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2126 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2128 // if damage pVictim call AI reaction
2129 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2130 ((Creature*)pVictim)->AI()->AttackedBy(this);
2132 // extra attack only at any non extra attack (normal case)
2133 if(!extra && extraAttacks)
2135 while(m_extraAttacks)
2137 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2138 if(m_extraAttacks > 0)
2139 --m_extraAttacks;
2144 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2146 // This is only wrapper
2148 // Miss chance based on melee
2149 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2151 // Critical hit chance
2152 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2154 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2155 float dodge_chance = pVictim->GetUnitDodgeChance();
2156 float block_chance = pVictim->GetUnitBlockChance();
2157 float parry_chance = pVictim->GetUnitParryChance();
2159 // Useful if want to specify crit & miss chances for melee, else it could be removed
2160 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2162 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2165 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2167 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2168 return MELEE_HIT_EVADE;
2170 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2171 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2173 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2174 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2176 // bonus from skills is 0.04%
2177 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2178 int32 sum = 0, tmp = 0;
2179 int32 roll = urand (0, 10000);
2181 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2182 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2183 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2185 tmp = miss_chance;
2187 if (tmp > 0 && roll < (sum += tmp ))
2189 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2190 return MELEE_HIT_MISS;
2193 // always crit against a sitting target (except 0 crit chance)
2194 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2196 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2197 return MELEE_HIT_CRIT;
2200 // Dodge chance
2202 // only players can't dodge if attacker is behind
2203 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2205 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2207 else
2209 // Reduce dodge chance by attacker expertise rating
2210 if (GetTypeId() == TYPEID_PLAYER)
2211 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2212 else
2213 dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2215 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2216 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2218 tmp = dodge_chance;
2219 if ( (tmp > 0) // check if unit _can_ dodge
2220 && ((tmp -= skillBonus) > 0)
2221 && roll < (sum += tmp))
2223 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2224 return MELEE_HIT_DODGE;
2228 // parry & block chances
2230 // check if attack comes from behind, nobody can parry or block if attacker is behind
2231 if (!pVictim->HasInArc(M_PI,this))
2233 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2235 else
2237 // Reduce parry chance by attacker expertise rating
2238 if (GetTypeId() == TYPEID_PLAYER)
2239 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2240 else
2241 parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2243 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2245 int32 tmp2 = int32(parry_chance);
2246 if ( (tmp2 > 0) // check if unit _can_ parry
2247 && ((tmp2 -= skillBonus) > 0)
2248 && (roll < (sum += tmp2)))
2250 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
2251 return MELEE_HIT_PARRY;
2255 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2257 tmp = block_chance;
2258 if ( (tmp > 0) // check if unit _can_ block
2259 && ((tmp -= skillBonus) > 0)
2260 && (roll < (sum += tmp)))
2262 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2263 return MELEE_HIT_BLOCK;
2268 // Critical chance
2269 tmp = crit_chance;
2271 if (tmp > 0 && roll < (sum += tmp))
2273 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2274 return MELEE_HIT_CRIT;
2277 // 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)
2278 if( attType != RANGED_ATTACK &&
2279 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2280 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2281 getLevel() < pVictim->getLevelForTarget(this) )
2283 // cap possible value (with bonuses > max skill)
2284 int32 skill = attackerWeaponSkill;
2285 int32 maxskill = attackerMaxSkillValueForLevel;
2286 skill = (skill > maxskill) ? maxskill : skill;
2288 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2289 tmp = tmp > 4000 ? 4000 : tmp;
2290 if (roll < (sum += tmp))
2292 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2293 return MELEE_HIT_GLANCING;
2297 // mobs can score crushing blows if they're 4 or more levels above victim
2298 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2299 // can be from by creature (if can) or from controlled player that considered as creature
2300 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2301 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2302 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2304 // when their weapon skill is 15 or more above victim's defense skill
2305 tmp = victimDefenseSkill;
2306 int32 tmpmax = victimMaxSkillValueForLevel;
2307 // having defense above your maximum (from items, talents etc.) has no effect
2308 tmp = tmp > tmpmax ? tmpmax : tmp;
2309 // tmp = mob's level * 5 - player's current defense skill
2310 tmp = attackerMaxSkillValueForLevel - tmp;
2311 if(tmp >= 15)
2313 // add 2% chance per lacking skill point, min. is 15%
2314 tmp = tmp * 200 - 1500;
2315 if (roll < (sum += tmp))
2317 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2318 return MELEE_HIT_CRUSHING;
2323 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2324 return MELEE_HIT_NORMAL;
2327 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2329 float min_damage, max_damage;
2331 if (normalized && GetTypeId()==TYPEID_PLAYER)
2332 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2333 else
2335 switch (attType)
2337 case RANGED_ATTACK:
2338 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2339 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2340 break;
2341 case BASE_ATTACK:
2342 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2343 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2344 break;
2345 case OFF_ATTACK:
2346 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2347 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2348 break;
2349 // Just for good manner
2350 default:
2351 min_damage = 0.0f;
2352 max_damage = 0.0f;
2353 break;
2357 if (min_damage > max_damage)
2359 std::swap(min_damage,max_damage);
2362 if(max_damage == 0.0f)
2363 max_damage = 5.0f;
2365 return urand((uint32)min_damage, (uint32)max_damage);
2368 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2370 if(spellProto->spellLevel <= 0)
2371 return 1.0f;
2373 float LvlPenalty = 0.0f;
2375 if(spellProto->spellLevel < 20)
2376 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2377 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2378 if(LvlFactor > 1.0f)
2379 LvlFactor = 1.0f;
2381 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2384 void Unit::SendMeleeAttackStart(Unit* pVictim)
2386 WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
2387 data << uint64(GetGUID());
2388 data << uint64(pVictim->GetGUID());
2390 SendMessageToSet(&data, true);
2391 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2394 void Unit::SendMeleeAttackStop(Unit* victim)
2396 if(!victim)
2397 return;
2399 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2400 data.append(GetPackGUID());
2401 data.append(victim->GetPackGUID()); // can be 0x00...
2402 data << uint32(0); // can be 0x1
2403 SendMessageToSet(&data, true);
2404 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2406 /*if(victim->GetTypeId() == TYPEID_UNIT)
2407 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2410 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
2412 if (pVictim->HasInArc(M_PI,this))
2414 /* Currently not exist spells with ignore block
2415 // Ignore combat result aura (parry/dodge check on prepare)
2416 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2417 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2419 if (!(*i)->isAffectedOnSpell(spellProto))
2420 continue;
2421 if ((*i)->GetModifier()->m_miscvalue == )
2422 return false;
2426 // Check creatures flags_extra for disable block
2427 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2428 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2429 return false;
2431 float blockChance = pVictim->GetUnitBlockChance();
2432 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2433 if (roll_chance_f(blockChance))
2434 return true;
2436 return false;
2439 // Melee based spells can be miss, parry or dodge on this step
2440 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2441 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2443 // Calculate hit chance (more correct for chance mod)
2444 int32 HitChance;
2446 // PvP - PvE melee chances
2447 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2448 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2449 if(leveldif < 3)
2450 HitChance = 95 - leveldif;
2451 else
2452 HitChance = 93 - (leveldif - 2) * lchance;
2454 // Hit chance depends from victim auras
2455 if(attType == RANGED_ATTACK)
2456 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2457 else
2458 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2460 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2461 if(Player *modOwner = GetSpellModOwner())
2462 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2464 // Miss = 100 - hit
2465 float miss_chance= 100.0f - HitChance;
2467 // Bonuses from attacker aura and ratings
2468 if (attType == RANGED_ATTACK)
2469 miss_chance -= m_modRangedHitChance;
2470 else
2471 miss_chance -= m_modMeleeHitChance;
2473 // bonus from skills is 0.04%
2474 miss_chance -= skillDiff * 0.04f;
2476 // Limit miss chance from 0 to 60%
2477 if (miss_chance < 0.0f)
2478 return 0.0f;
2479 if (miss_chance > 60.0f)
2480 return 60.0f;
2481 return miss_chance;
2484 // Melee based spells hit result calculations
2485 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2487 WeaponAttackType attType = BASE_ATTACK;
2489 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2490 attType = RANGED_ATTACK;
2492 // bonus from skills is 0.04% per skill Diff
2493 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2494 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2495 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2497 uint32 roll = urand (0, 10000);
2499 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2500 // Roll miss
2501 uint32 tmp = missChance;
2502 if (roll < tmp)
2503 return SPELL_MISS_MISS;
2505 // Chance resist mechanic (select max value from every mechanic spell effect)
2506 int32 resist_mech = 0;
2507 // Get effects mechanic and chance
2508 for(int eff = 0; eff < 3; ++eff)
2510 int32 effect_mech = GetEffectMechanic(spell, eff);
2511 if (effect_mech)
2513 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2514 if (resist_mech < temp*100)
2515 resist_mech = temp*100;
2518 // Roll chance
2519 tmp += resist_mech;
2520 if (roll < tmp)
2521 return SPELL_MISS_RESIST;
2523 bool canDodge = true;
2524 bool canParry = true;
2526 // Same spells cannot be parry/dodge
2527 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2528 return SPELL_MISS_NONE;
2530 // Ranged attack cannot be parry/dodge only deflect
2531 if (attType == RANGED_ATTACK)
2533 // only if in front
2534 if (pVictim->HasInArc(M_PI,this))
2536 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2537 tmp+=deflect_chance;
2538 if (roll < tmp)
2539 return SPELL_MISS_DEFLECT;
2541 return SPELL_MISS_NONE;
2544 // Check for attack from behind
2545 if (!pVictim->HasInArc(M_PI,this))
2547 // Can`t dodge from behind in PvP (but its possible in PvE)
2548 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2549 canDodge = false;
2550 // Can`t parry
2551 canParry = false;
2553 // Check creatures flags_extra for disable parry
2554 if(pVictim->GetTypeId()==TYPEID_UNIT)
2556 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2557 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2558 canParry = false;
2560 // Ignore combat result aura
2561 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2562 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2564 if (!(*i)->isAffectedOnSpell(spell))
2565 continue;
2566 switch((*i)->GetModifier()->m_miscvalue)
2568 case MELEE_HIT_DODGE: canDodge = false; break;
2569 case MELEE_HIT_BLOCK: break; // Block check in hit step
2570 case MELEE_HIT_PARRY: canParry = false; break;
2571 default:
2572 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2573 break;
2577 if (canDodge)
2579 // Roll dodge
2580 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2581 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2582 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2583 // Reduce dodge chance by attacker expertise rating
2584 if (GetTypeId() == TYPEID_PLAYER)
2585 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2586 else
2587 dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2588 if (dodgeChance < 0)
2589 dodgeChance = 0;
2591 tmp += dodgeChance;
2592 if (roll < tmp)
2593 return SPELL_MISS_DODGE;
2596 if (canParry)
2598 // Roll parry
2599 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2600 // Reduce parry chance by attacker expertise rating
2601 if (GetTypeId() == TYPEID_PLAYER)
2602 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2603 else
2604 parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2605 if (parryChance < 0)
2606 parryChance = 0;
2608 tmp += parryChance;
2609 if (roll < tmp)
2610 return SPELL_MISS_PARRY;
2613 return SPELL_MISS_NONE;
2616 // TODO need use unit spell resistances in calculations
2617 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2619 // Can`t miss on dead target (on skinning for example)
2620 if (!pVictim->isAlive())
2621 return SPELL_MISS_NONE;
2623 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2624 // PvP - PvE spell misschances per leveldif > 2
2625 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2626 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2628 // Base hit chance from attacker and victim levels
2629 int32 modHitChance;
2630 if(leveldif < 3)
2631 modHitChance = 96 - leveldif;
2632 else
2633 modHitChance = 94 - (leveldif - 2) * lchance;
2635 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2636 if(Player *modOwner = GetSpellModOwner())
2637 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2638 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2639 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2640 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2641 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2642 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2643 if (IsAreaOfEffectSpell(spell))
2644 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2645 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2646 if (IsDispelSpell(spell))
2647 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2648 // Chance resist mechanic (select max value from every mechanic spell effect)
2649 int32 resist_mech = 0;
2650 // Get effects mechanic and chance
2651 for(int eff = 0; eff < 3; ++eff)
2653 int32 effect_mech = GetEffectMechanic(spell, eff);
2654 if (effect_mech)
2656 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2657 if (resist_mech < temp)
2658 resist_mech = temp;
2661 // Apply mod
2662 modHitChance-=resist_mech;
2664 // Chance resist debuff
2665 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2667 int32 HitChance = modHitChance * 100;
2668 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2669 HitChance += int32(m_modSpellHitChance*100.0f);
2671 // Decrease hit chance from victim rating bonus
2672 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2673 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2675 if (HitChance < 100) HitChance = 100;
2676 if (HitChance > 10000) HitChance = 10000;
2678 int32 tmp = 10000 - HitChance;
2680 uint32 rand = urand(0,10000);
2682 if (rand < tmp)
2683 return SPELL_MISS_MISS;
2685 // cast by caster in front of victim
2686 if (pVictim->HasInArc(M_PI,this))
2688 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2689 tmp+=deflect_chance;
2690 if (rand < tmp)
2691 return SPELL_MISS_DEFLECT;
2694 return SPELL_MISS_NONE;
2697 // Calculate spell hit result can be:
2698 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2699 // For melee based spells:
2700 // Miss
2701 // Dodge
2702 // Parry
2703 // For spells
2704 // Resist
2705 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2707 // Return evade for units in evade mode
2708 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2709 return SPELL_MISS_EVADE;
2711 // Check for immune
2712 if (pVictim->IsImmunedToSpell(spell))
2713 return SPELL_MISS_IMMUNE;
2715 // All positive spells can`t miss
2716 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2717 if (IsPositiveSpell(spell->Id))
2718 return SPELL_MISS_NONE;
2720 // Check for immune
2721 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2722 return SPELL_MISS_IMMUNE;
2724 // Try victim reflect spell
2725 if (CanReflect)
2727 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2728 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2729 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2730 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2731 reflectchance += (*i)->GetModifier()->m_amount;
2732 if (reflectchance > 0 && roll_chance_i(reflectchance))
2734 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2735 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2736 return SPELL_MISS_REFLECT;
2740 switch (spell->DmgClass)
2742 case SPELL_DAMAGE_CLASS_RANGED:
2743 case SPELL_DAMAGE_CLASS_MELEE:
2744 return MeleeSpellHitResult(pVictim, spell);
2745 case SPELL_DAMAGE_CLASS_NONE:
2746 case SPELL_DAMAGE_CLASS_MAGIC:
2747 return MagicSpellHitResult(pVictim, spell);
2749 return SPELL_MISS_NONE;
2752 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2754 if(!pVictim)
2755 return 0.0f;
2757 // Base misschance 5%
2758 float misschance = 5.0f;
2760 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2761 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2763 bool isNormal = false;
2764 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
2766 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2768 isNormal = true;
2769 break;
2772 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2773 misschance = 5.0f;
2774 else
2775 misschance = 24.0f;
2778 // PvP : PvE melee misschances per leveldif > 2
2779 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2781 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2782 if(leveldif < 0)
2783 leveldif = 0;
2785 // Hit chance from attacker based on ratings and auras
2786 float m_modHitChance;
2787 if (attType == RANGED_ATTACK)
2788 m_modHitChance = m_modRangedHitChance;
2789 else
2790 m_modHitChance = m_modMeleeHitChance;
2792 if(leveldif < 3)
2793 misschance += (leveldif - m_modHitChance);
2794 else
2795 misschance += ((leveldif - 2) * chance - m_modHitChance);
2797 // Hit chance for victim based on ratings
2798 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2800 if (attType == RANGED_ATTACK)
2801 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2802 else
2803 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2806 // Modify miss chance by victim auras
2807 if(attType == RANGED_ATTACK)
2808 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2809 else
2810 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2812 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2813 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2814 misschance -= skillBonus * 0.04f;
2816 // Limit miss chance from 0 to 60%
2817 if ( misschance < 0.0f)
2818 return 0.0f;
2819 if ( misschance > 60.0f)
2820 return 60.0f;
2822 return misschance;
2825 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2827 if(GetTypeId() == TYPEID_PLAYER)
2829 // in PvP use full skill instead current skill value
2830 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2831 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2832 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2833 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2834 return value;
2836 else
2837 return GetUnitMeleeSkill(target);
2840 float Unit::GetUnitDodgeChance() const
2842 if(hasUnitState(UNIT_STAT_STUNNED))
2843 return 0.0f;
2844 if( GetTypeId() == TYPEID_PLAYER )
2845 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2846 else
2848 if(((Creature const*)this)->isTotem())
2849 return 0.0f;
2850 else
2852 float dodge = 5.0f;
2853 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2854 return dodge > 0.0f ? dodge : 0.0f;
2859 float Unit::GetUnitParryChance() const
2861 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2862 return 0.0f;
2864 float chance = 0.0f;
2866 if(GetTypeId() == TYPEID_PLAYER)
2868 Player const* player = (Player const*)this;
2869 if(player->CanParry() )
2871 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2872 if(!tmpitem)
2873 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2875 if(tmpitem)
2876 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2879 else if(GetTypeId() == TYPEID_UNIT)
2881 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2883 chance = 5.0f;
2884 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2888 return chance > 0.0f ? chance : 0.0f;
2891 float Unit::GetUnitBlockChance() const
2893 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2894 return 0.0f;
2896 if(GetTypeId() == TYPEID_PLAYER)
2898 Player const* player = (Player const*)this;
2899 if(player->CanBlock() )
2901 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2902 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2903 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2905 // is player but has no block ability or no not broken shield equipped
2906 return 0.0f;
2908 else
2910 if(((Creature const*)this)->isTotem())
2911 return 0.0f;
2912 else
2914 float block = 5.0f;
2915 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2916 return block > 0.0f ? block : 0.0f;
2921 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2923 float crit;
2925 if(GetTypeId() == TYPEID_PLAYER)
2927 switch(attackType)
2929 case BASE_ATTACK:
2930 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2931 break;
2932 case OFF_ATTACK:
2933 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2934 break;
2935 case RANGED_ATTACK:
2936 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2937 break;
2938 // Just for good manner
2939 default:
2940 crit = 0.0f;
2941 break;
2944 else
2946 crit = 5.0f;
2947 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2950 // flat aura mods
2951 if(attackType == RANGED_ATTACK)
2952 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2953 else
2954 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2956 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2958 // reduce crit chance from Rating for players
2959 if (attackType != RANGED_ATTACK)
2960 crit -= pVictim->GetMeleeCritChanceReduction();
2961 else
2962 crit -= pVictim->GetRangedCritChanceReduction();
2964 // Apply crit chance from defence skill
2965 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2967 if (crit < 0.0f)
2968 crit = 0.0f;
2969 return crit;
2972 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2974 uint32 value = 0;
2975 if(GetTypeId() == TYPEID_PLAYER)
2977 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2979 // feral or unarmed skill only for base attack
2980 if(attType != BASE_ATTACK && !item )
2981 return 0;
2983 if(IsInFeralForm())
2984 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2986 // weapon skill or (unarmed for base attack)
2987 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2989 // in PvP use full skill instead current skill value
2990 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2991 ? ((Player*)this)->GetMaxSkillValue(skill)
2992 : ((Player*)this)->GetSkillValue(skill);
2993 // Modify value from ratings
2994 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2995 switch (attType)
2997 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2998 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2999 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
3002 else
3003 value = GetUnitMeleeSkill(target);
3004 return value;
3007 void Unit::_UpdateSpells( uint32 time )
3009 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
3010 _UpdateAutoRepeatSpell();
3012 // remove finished spells from current pointers
3013 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3015 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
3017 m_currentSpells[i]->SetReferencedFromCurrent(false);
3018 m_currentSpells[i] = NULL; // remove pointer
3022 // update auras
3023 // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras
3024 for (m_AurasUpdateIterator = m_Auras.begin(); m_AurasUpdateIterator != m_Auras.end();)
3026 Aura* i_aura = m_AurasUpdateIterator->second;
3027 ++m_AurasUpdateIterator; // need shift to next for allow update if need into aura update
3028 i_aura->UpdateAura(time);
3031 // remove expired auras
3032 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
3034 if ((*i).second)
3036 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
3037 RemoveAura(i);
3038 else
3039 ++i;
3041 else
3042 ++i;
3045 if(!m_gameObj.empty())
3047 GameObjectList::iterator ite1, dnext1;
3048 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
3050 dnext1 = ite1;
3051 //(*i)->Update( difftime );
3052 if( !(*ite1)->isSpawned() )
3054 (*ite1)->SetOwnerGUID(0);
3055 (*ite1)->SetRespawnTime(0);
3056 (*ite1)->Delete();
3057 dnext1 = m_gameObj.erase(ite1);
3059 else
3060 ++dnext1;
3065 void Unit::_UpdateAutoRepeatSpell()
3067 //check "realtime" interrupts
3068 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
3070 // cancel wand shoot
3071 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3072 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3073 m_AutoRepeatFirstCast = true;
3074 return;
3077 //apply delay
3078 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
3079 setAttackTimer(RANGED_ATTACK,500);
3080 m_AutoRepeatFirstCast = false;
3082 //castroutine
3083 if (isAttackReady(RANGED_ATTACK))
3085 // Check if able to cast
3086 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
3088 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3089 return;
3092 // we want to shoot
3093 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
3094 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
3096 // all went good, reset attack
3097 resetAttackTimer(RANGED_ATTACK);
3101 void Unit::SetCurrentCastedSpell( Spell * pSpell )
3103 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
3105 CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
3107 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3109 // break same type spell if it is not delayed
3110 InterruptSpell(CSpellType,false);
3112 // special breakage effects:
3113 switch (CSpellType)
3115 case CURRENT_GENERIC_SPELL:
3117 // generic spells always break channeled not delayed spells
3118 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3120 // autorepeat breaking
3121 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3123 // break autorepeat if not Auto Shot
3124 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3125 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3126 m_AutoRepeatFirstCast = true;
3128 } break;
3130 case CURRENT_CHANNELED_SPELL:
3132 // channel spells always break generic non-delayed and any channeled spells
3133 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3134 InterruptSpell(CURRENT_CHANNELED_SPELL);
3136 // it also does break autorepeat if not Auto Shot
3137 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3138 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3139 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3140 } break;
3142 case CURRENT_AUTOREPEAT_SPELL:
3144 // only Auto Shoot does not break anything
3145 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3147 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3148 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3149 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3151 // special action: set first cast flag
3152 m_AutoRepeatFirstCast = true;
3153 } break;
3155 default:
3157 // other spell types don't break anything now
3158 } break;
3161 // current spell (if it is still here) may be safely deleted now
3162 if (m_currentSpells[CSpellType])
3163 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3165 // set new current spell
3166 m_currentSpells[CSpellType] = pSpell;
3167 pSpell->SetReferencedFromCurrent(true);
3169 pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
3172 void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed)
3174 assert(spellType < CURRENT_MAX_SPELL);
3176 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3178 // send autorepeat cancel message for autorepeat spells
3179 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3181 if(GetTypeId() == TYPEID_PLAYER)
3182 ((Player*)this)->SendAutoRepeatCancel(this);
3185 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3186 m_currentSpells[spellType]->cancel();
3188 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3189 if (m_currentSpells[spellType])
3191 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3192 m_currentSpells[spellType] = NULL;
3197 void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
3199 Spell* spell = m_currentSpells[spellType];
3200 if (!spell)
3201 return;
3203 if (spellType == CURRENT_CHANNELED_SPELL)
3204 spell->SendChannelUpdate(0);
3206 spell->finish(ok);
3210 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3212 // We don't do loop here to explicitly show that melee spell is excluded.
3213 // Maybe later some special spells will be excluded too.
3215 // generic spells are casted when they are not finished and not delayed
3216 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3217 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3218 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3219 return(true);
3221 // channeled spells may be delayed, but they are still considered casted
3222 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3223 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3224 return(true);
3226 // autorepeat spells may be finished or delayed, but they are still considered casted
3227 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3228 return(true);
3230 return(false);
3233 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3235 // generic spells are interrupted if they are not finished or delayed
3236 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3237 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3239 // autorepeat spells are interrupted if they are not finished or delayed
3240 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3241 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3243 // channeled spells are interrupted if they are not finished, even if they are delayed
3244 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3245 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3248 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3250 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3251 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3252 return m_currentSpells[i];
3253 return NULL;
3256 void Unit::SetInFront(Unit const* target)
3258 SetOrientation(GetAngle(target));
3261 void Unit::SetFacingToObject(WorldObject* pObject)
3263 // update orientation at server
3264 SetOrientation(GetAngle(pObject));
3266 // and client
3267 WorldPacket data;
3268 BuildHeartBeatMsg(&data);
3269 SendMessageToSet(&data, false);
3272 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3274 if(IsInWater())
3275 return c->canSwim();
3276 else
3277 return c->canWalk() || c->canFly();
3280 bool Unit::IsInWater() const
3282 return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3285 bool Unit::IsUnderWater() const
3287 return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3290 void Unit::DeMorph()
3292 SetDisplayId(GetNativeDisplayId());
3295 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3297 int32 modifier = 0;
3299 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3300 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3301 modifier += (*i)->GetModifier()->m_amount;
3303 return modifier;
3306 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3308 float multiplier = 1.0f;
3310 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3311 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3312 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3314 return multiplier;
3317 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3319 int32 modifier = 0;
3321 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3322 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3323 if ((*i)->GetModifier()->m_amount > modifier)
3324 modifier = (*i)->GetModifier()->m_amount;
3326 return modifier;
3329 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3331 int32 modifier = 0;
3333 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3334 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3335 if ((*i)->GetModifier()->m_amount < modifier)
3336 modifier = (*i)->GetModifier()->m_amount;
3338 return modifier;
3341 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3343 if(!misc_mask)
3344 return 0;
3346 int32 modifier = 0;
3348 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3349 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3351 Modifier* mod = (*i)->GetModifier();
3352 if (mod->m_miscvalue & misc_mask)
3353 modifier += mod->m_amount;
3355 return modifier;
3358 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3360 if(!misc_mask)
3361 return 1.0f;
3363 float multiplier = 1.0f;
3365 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3366 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3368 Modifier* mod = (*i)->GetModifier();
3369 if (mod->m_miscvalue & misc_mask)
3370 multiplier *= (100.0f + mod->m_amount)/100.0f;
3372 return multiplier;
3375 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3377 if(!misc_mask)
3378 return 0;
3380 int32 modifier = 0;
3382 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3383 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3385 Modifier* mod = (*i)->GetModifier();
3386 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3387 modifier = mod->m_amount;
3390 return modifier;
3393 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3395 if(!misc_mask)
3396 return 0;
3398 int32 modifier = 0;
3400 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3401 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3403 Modifier* mod = (*i)->GetModifier();
3404 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3405 modifier = mod->m_amount;
3408 return modifier;
3411 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3413 int32 modifier = 0;
3415 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3416 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3418 Modifier* mod = (*i)->GetModifier();
3419 if (mod->m_miscvalue == misc_value)
3420 modifier += mod->m_amount;
3422 return modifier;
3425 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3427 float multiplier = 1.0f;
3429 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3430 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3432 Modifier* mod = (*i)->GetModifier();
3433 if (mod->m_miscvalue == misc_value)
3434 multiplier *= (100.0f + mod->m_amount)/100.0f;
3436 return multiplier;
3439 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3441 int32 modifier = 0;
3443 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3444 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3446 Modifier* mod = (*i)->GetModifier();
3447 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3448 modifier = mod->m_amount;
3451 return modifier;
3454 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3456 int32 modifier = 0;
3458 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3459 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3461 Modifier* mod = (*i)->GetModifier();
3462 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3463 modifier = mod->m_amount;
3466 return modifier;
3469 bool Unit::AddAura(Aura *Aur)
3471 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3473 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3474 if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
3475 !IsDeathOnlySpell(aurSpellInfo) &&
3476 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3478 delete Aur;
3479 return false;
3482 if(Aur->GetTarget() != this)
3484 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3485 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3486 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3487 delete Aur;
3488 return false;
3491 // m_auraname can be modified to SPELL_AURA_NONE for area auras, this expected for this value
3492 AuraType aurName = Aur->GetModifier()->m_auraname;
3494 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3495 AuraMap::iterator i = m_Auras.find( spair );
3497 // take out same spell
3498 if (i != m_Auras.end())
3500 // passive and persistent auras can stack with themselves any number of times
3501 if (!Aur->IsPassive() && !Aur->IsPersistent())
3503 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3505 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3507 // Aura can stack on self -> Stack it;
3508 if(aurSpellInfo->StackAmount)
3510 // can be created with >1 stack by some spell mods
3511 i2->second->modStackAmount(Aur->GetStackAmount());
3512 delete Aur;
3513 return false;
3515 // can be only single (this check done at _each_ aura add
3516 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3517 break;
3520 bool stop = false;
3522 // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original
3523 AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()]);
3525 switch(aurNameReal)
3527 // DoT/HoT/etc
3528 case SPELL_AURA_DUMMY: // allow stack
3529 case SPELL_AURA_PERIODIC_DAMAGE:
3530 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3531 case SPELL_AURA_PERIODIC_LEECH:
3532 case SPELL_AURA_PERIODIC_HEAL:
3533 case SPELL_AURA_OBS_MOD_HEALTH:
3534 case SPELL_AURA_PERIODIC_MANA_LEECH:
3535 case SPELL_AURA_OBS_MOD_MANA:
3536 case SPELL_AURA_POWER_BURN_MANA:
3537 break;
3538 case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable
3539 default: // not allow
3540 // can be only single (this check done at _each_ aura add
3541 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3542 stop = true;
3543 break;
3546 if(stop)
3547 break;
3552 // passive auras not stacable with other ranks
3553 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3555 if (!RemoveNoStackAurasDueToAura(Aur))
3557 delete Aur;
3558 return false; // couldn't remove conflicting aura with higher rank
3562 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3563 if (Aur->IsSingleTarget() && Aur->GetTarget())
3565 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3566 for(;;)
3568 Unit* caster = Aur->GetCaster();
3569 if(!caster) // caster deleted and not required adding scAura
3570 break;
3572 bool restart = false;
3573 AuraList& scAuras = caster->GetSingleCastAuras();
3574 for(AuraList::const_iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3576 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3577 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3579 if ((*itr)->IsInUse())
3581 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for IsSingleTargetSpell", (*itr)->GetId(), (*itr)->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3582 continue;
3584 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3585 restart = true;
3586 break;
3590 if(!restart)
3592 // done
3593 scAuras.push_back(Aur);
3594 break;
3599 // add aura, register in lists and arrays
3600 Aur->_AddAura();
3601 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3602 if (aurName < TOTAL_AURAS)
3604 m_modAuras[aurName].push_back(Aur);
3607 Aur->ApplyModifier(true,true);
3608 sLog.outDebug("Aura %u now is in use", aurName);
3610 // if aura deleted before boosts apply ignore
3611 // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier
3612 if (Aur->IsDeleted())
3613 return false;
3615 if(IsSpellLastAuraEffect(aurSpellInfo,Aur->GetEffIndex()))
3616 Aur->HandleSpellSpecificBoosts(true);
3618 return true;
3621 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3623 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3624 if(!spellInfo)
3625 return;
3626 AuraMap::const_iterator i,next;
3627 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3629 next = i;
3630 ++next;
3631 uint32 i_spellId = (*i).second->GetId();
3632 if((*i).second && i_spellId && i_spellId != spellId)
3634 if(sSpellMgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3636 RemoveAurasDueToSpell(i_spellId);
3638 if( m_Auras.empty() )
3639 break;
3640 else
3641 next = m_Auras.begin();
3647 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3649 if (!Aur)
3650 return false;
3652 SpellEntry const* spellProto = Aur->GetSpellProto();
3653 if (!spellProto)
3654 return false;
3656 uint32 spellId = Aur->GetId();
3657 uint32 effIndex = Aur->GetEffIndex();
3659 // passive spell special case (only non stackable with ranks)
3660 if(IsPassiveSpell(spellId))
3662 if(IsPassiveSpellStackableWithRanks(spellProto))
3663 return true;
3666 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3668 AuraMap::iterator i,next;
3669 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3671 next = i;
3672 ++next;
3673 if (!(*i).second) continue;
3675 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3677 if (!i_spellProto)
3678 continue;
3680 uint32 i_spellId = i_spellProto->Id;
3682 // early checks that spellId is passive non stackable spell
3683 if(IsPassiveSpell(i_spellId))
3685 // passive non-stackable spells not stackable only for same caster
3686 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3687 continue;
3689 // passive non-stackable spells not stackable only with another rank of same spell
3690 if (!sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3691 continue;
3694 uint32 i_effIndex = (*i).second->GetEffIndex();
3696 if(i_spellId == spellId) continue;
3698 bool is_triggered_by_spell = false;
3699 // prevent triggering aura of removing aura that triggered it
3700 for(int j = 0; j < 3; ++j)
3701 if (i_spellProto->EffectTriggerSpell[j] == spellId)
3702 is_triggered_by_spell = true;
3704 // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
3705 for(int j = 0; j < 3; ++j)
3706 if (spellProto->EffectTriggerSpell[j] == i_spellId)
3707 is_triggered_by_spell = true;
3709 if (is_triggered_by_spell)
3710 continue;
3712 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3714 // single allowed spell specific from same caster or from any caster at target
3715 bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec,i_spellId_spec);
3716 bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec,i_spellId_spec);
3717 if( is_spellSpecPerTarget || is_spellSpecPerTargetPerCaster && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3719 // cannot remove higher rank
3720 if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3721 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3722 return false;
3724 // Its a parent aura (create this aura in ApplyModifier)
3725 if ((*i).second->IsInUse())
3727 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3728 continue;
3730 RemoveAurasDueToSpell(i_spellId);
3732 if( m_Auras.empty() )
3733 break;
3734 else
3735 next = m_Auras.begin();
3737 continue;
3740 // spell with spell specific that allow single ranks for spell from diff caster
3741 // same caster case processed or early or later
3742 bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec,i_spellId_spec);
3743 if ( is_spellPerTarget && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3745 // cannot remove higher rank
3746 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3747 return false;
3749 // Its a parent aura (create this aura in ApplyModifier)
3750 if ((*i).second->IsInUse())
3752 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3753 continue;
3755 RemoveAurasDueToSpell(i_spellId);
3757 if( m_Auras.empty() )
3758 break;
3759 else
3760 next = m_Auras.begin();
3762 continue;
3765 // non single (per caster) per target spell specific (possible single spell per target at caster)
3766 if( !is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && sSpellMgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3768 // Its a parent aura (create this aura in ApplyModifier)
3769 if ((*i).second->IsInUse())
3771 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3772 continue;
3774 RemoveAurasDueToSpell(i_spellId);
3776 if( m_Auras.empty() )
3777 break;
3778 else
3779 next = m_Auras.begin();
3781 continue;
3784 // Potions stack aura by aura (elixirs/flask already checked)
3785 if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3787 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3789 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3790 return false; // cannot remove higher rank
3792 // Its a parent aura (create this aura in ApplyModifier)
3793 if ((*i).second->IsInUse())
3795 sLog.outError("Aura (Spell %u Effect %u) is in process but attempt removed at aura (Spell %u Effect %u) adding, need add stack rule for Unit::RemoveNoStackAurasDueToAura", i->second->GetId(), i->second->GetEffIndex(),Aur->GetId(), Aur->GetEffIndex());
3796 continue;
3798 RemoveAura(i);
3799 next = i;
3803 return true;
3806 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3808 spellEffectPair spair = spellEffectPair(spellId, effindex);
3809 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3811 if(iter->second!=except)
3813 RemoveAura(iter);
3814 iter = m_Auras.lower_bound(spair);
3816 else
3817 ++iter;
3821 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3823 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3825 Aura *aur = iter->second;
3826 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3827 RemoveAura(iter);
3828 else
3829 ++iter;
3833 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint32 effindex, uint64 casterGUID)
3835 spellEffectPair spair = spellEffectPair(spellId, effindex);
3836 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3838 Aura *aur = iter->second;
3839 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3841 RemoveAura(iter);
3842 iter = m_Auras.lower_bound(spair);
3844 else
3845 ++iter;
3849 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3851 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3853 Aura *aur = iter->second;
3854 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3856 // Custom dispel case
3857 // Unstable Affliction
3858 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x010000000000)))
3860 int32 damage = aur->GetModifier()->m_amount*9;
3861 uint64 caster_guid = aur->GetCasterGUID();
3863 // Remove aura
3864 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3866 // backfire damage and silence
3867 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3869 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3871 else
3872 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3874 else
3875 ++iter;
3879 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3881 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3883 Aura *aur = iter->second;
3884 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3886 int32 basePoints = aur->GetBasePoints();
3887 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3888 // some different constructors
3889 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3891 // set its duration and maximum duration
3892 // max duration 2 minutes (in msecs)
3893 int32 dur = aur->GetAuraDuration();
3894 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3895 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3896 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3898 // Unregister _before_ adding to stealer
3899 aur->UnregisterSingleCastAura();
3901 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3902 new_aur->SetIsSingleTarget(false);
3904 // add the new aura to stealer
3905 stealer->AddAura(new_aur);
3907 // Remove aura as dispel
3908 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3910 else
3911 ++iter;
3915 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3917 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3919 if (iter->second->GetId() == spellId)
3920 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3921 else
3922 ++iter;
3926 void Unit::RemoveAurasWithDispelType( DispelType type )
3928 // Create dispel mask by dispel type
3929 uint32 dispelMask = GetDispellMask(type);
3930 // Dispel all existing auras vs current dispel type
3931 AuraMap& auras = GetAuras();
3932 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3934 SpellEntry const* spell = itr->second->GetSpellProto();
3935 if( (1<<spell->Dispel) & dispelMask )
3937 // Dispel aura
3938 RemoveAurasDueToSpell(spell->Id);
3939 itr = auras.begin();
3941 else
3942 ++itr;
3946 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3948 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3949 if(iter != m_Auras.end())
3951 if (iter->second->modStackAmount(-1))
3952 RemoveAura(iter);
3956 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3958 for (int i=0; i<3; ++i)
3959 RemoveSingleAuraFromStack(spellId, i);
3962 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3964 for (int i = 0; i < 3; ++i)
3965 RemoveAura(spellId,i,except);
3968 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3970 for (int k=0; k < 3; ++k)
3972 spellEffectPair spair = spellEffectPair(spellId, k);
3973 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3975 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3977 RemoveAura(iter);
3978 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3980 else
3981 ++iter;
3986 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3988 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3990 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3991 RemoveAura(iter);
3992 else
3993 ++iter;
3997 void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
3999 // single target auras from other casters
4000 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4002 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
4004 if(!newPhase)
4005 RemoveAura(iter);
4006 else
4008 Unit* caster = iter->second->GetCaster();
4009 if(!caster || !caster->InSamePhase(newPhase))
4010 RemoveAura(iter);
4011 else
4012 ++iter;
4015 else
4016 ++iter;
4019 // single target auras at other targets
4020 AuraList& scAuras = GetSingleCastAuras();
4021 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
4023 Aura* aura = *iter;
4024 if (aura->GetTarget() != this && !aura->GetTarget()->InSamePhase(newPhase))
4026 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
4027 aura->GetTarget()->RemoveAura(aura);
4028 iter = scAuras.begin();
4030 else
4031 ++iter;
4036 void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4038 AuraMap::iterator i = m_Auras.lower_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4039 AuraMap::iterator upperBound = m_Auras.upper_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4040 for (; i != upperBound; ++i)
4042 if (i->second == aura)
4044 RemoveAura(i,mode);
4045 return;
4048 sLog.outDebug("Trying to remove aura id %u effect %u by pointer but aura not found on target", aura->GetId(), aura->GetEffIndex());
4051 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
4053 Aura* Aur = i->second;
4054 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
4056 Aur->UnregisterSingleCastAura();
4058 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
4059 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
4061 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
4064 // Set remove mode
4065 Aur->SetRemoveMode(mode);
4067 // if unit currently update aura list then make safe update iterator shift to next
4068 if (m_AurasUpdateIterator == i)
4069 ++m_AurasUpdateIterator;
4071 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
4072 // remove aura from list before to prevent deleting it before
4073 m_Auras.erase(i);
4075 // now aura removed from from list and can't be deleted by indirect call but can be referenced from callers
4077 // Statue unsummoned at aura remove
4078 Totem* statue = NULL;
4079 bool caster_channeled = false;
4080 if(IsChanneledSpell(AurSpellInfo))
4082 Unit* caster = Aur->GetCaster();
4084 if(caster)
4086 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
4087 statue = ((Totem*)caster);
4088 else
4089 caster_channeled = caster==this;
4093 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
4094 if (mode != AURA_REMOVE_BY_DELETE) // not unapply if target will deleted
4095 Aur->ApplyModifier(false,true);
4097 if (Aur->_RemoveAura())
4099 // last aura in stack removed
4100 if (mode != AURA_REMOVE_BY_DELETE && IsSpellLastAuraEffect(Aur->GetSpellProto(),Aur->GetEffIndex()))
4101 Aur->HandleSpellSpecificBoosts(false);
4104 // If aura in use (removed from code that plan access to it data after return)
4105 // store it in aura list with delayed deletion
4106 if (Aur->IsInUse())
4107 m_deletedAuras.push_back(Aur);
4108 else
4109 delete Aur;
4111 if(caster_channeled)
4112 RemoveAurasAtChanneledTarget (AurSpellInfo);
4114 if(statue)
4115 statue->UnSummon();
4117 // only way correctly remove all auras from list
4118 if( m_Auras.empty() )
4119 i = m_Auras.end();
4120 else
4121 i = m_Auras.begin();
4124 void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4126 while (!m_Auras.empty())
4128 AuraMap::iterator iter = m_Auras.begin();
4129 RemoveAura(iter,mode);
4133 void Unit::RemoveArenaAuras(bool onleave)
4135 // in join, remove positive buffs, on end, remove negative
4136 // used to remove positive visible auras in arenas
4137 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4139 if (!(iter->second->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_UNK21) &&
4140 // don't remove stances, shadowform, pally/hunter auras
4141 !iter->second->IsPassive() && // don't remove passive auras
4142 (!(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) ||
4143 !(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) &&
4144 // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
4145 (iter->second->IsPositive() != onleave)) // remove positive buffs on enter, negative buffs on leave
4146 RemoveAura(iter);
4147 else
4148 ++iter;
4152 void Unit::RemoveAllAurasOnDeath()
4154 // used just after dieing to remove all visible auras
4155 // and disable the mods for the passive ones
4156 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4158 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
4159 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
4160 else
4161 ++iter;
4165 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
4167 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4168 if (iter != m_Auras.end())
4170 if (iter->second->GetAuraDuration() < delaytime)
4171 iter->second->SetAuraDuration(0);
4172 else
4173 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
4174 iter->second->SendAuraUpdate(false);
4175 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
4179 void Unit::_RemoveAllAuraMods()
4181 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4183 (*i).second->ApplyModifier(false);
4187 void Unit::_ApplyAllAuraMods()
4189 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4191 (*i).second->ApplyModifier(true);
4195 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
4197 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4198 if (iter != m_Auras.end())
4199 return iter->second;
4200 return NULL;
4203 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
4205 AuraList const& auras = GetAurasByType(type);
4206 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
4208 SpellEntry const *spell = (*i)->GetSpellProto();
4209 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
4211 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
4212 continue;
4213 return (*i);
4216 return NULL;
4219 bool Unit::HasAura(uint32 spellId) const
4221 for (int i = 0; i < 3 ; ++i)
4223 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
4224 if (iter != m_Auras.end())
4225 return true;
4227 return false;
4230 void Unit::AddDynObject(DynamicObject* dynObj)
4232 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4235 void Unit::RemoveDynObject(uint32 spellid)
4237 if(m_dynObjGUIDs.empty())
4238 return;
4239 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4241 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4242 if(!dynObj)
4244 i = m_dynObjGUIDs.erase(i);
4246 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4248 dynObj->Delete();
4249 i = m_dynObjGUIDs.erase(i);
4251 else
4252 ++i;
4256 void Unit::RemoveAllDynObjects()
4258 while(!m_dynObjGUIDs.empty())
4260 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4261 if(dynObj)
4262 dynObj->Delete();
4263 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4267 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4269 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4271 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4272 if(!dynObj)
4274 i = m_dynObjGUIDs.erase(i);
4275 continue;
4278 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4279 return dynObj;
4280 ++i;
4282 return NULL;
4285 DynamicObject * Unit::GetDynObject(uint32 spellId)
4287 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4289 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4290 if(!dynObj)
4292 i = m_dynObjGUIDs.erase(i);
4293 continue;
4296 if (dynObj->GetSpellId() == spellId)
4297 return dynObj;
4298 ++i;
4300 return NULL;
4303 GameObject* Unit::GetGameObject(uint32 spellId) const
4305 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
4306 if ((*i)->GetSpellId() == spellId)
4307 return *i;
4309 return NULL;
4312 void Unit::AddGameObject(GameObject* gameObj)
4314 assert(gameObj && gameObj->GetOwnerGUID()==0);
4315 m_gameObj.push_back(gameObj);
4316 gameObj->SetOwnerGUID(GetGUID());
4318 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4320 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4321 // Need disable spell use for owner
4322 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4323 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4324 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4328 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4330 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4332 gameObj->SetOwnerGUID(0);
4334 // GO created by some spell
4335 if (uint32 spellid = gameObj->GetSpellId())
4337 RemoveAurasDueToSpell(spellid);
4339 if (GetTypeId()==TYPEID_PLAYER)
4341 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4342 // Need activate spell use for owner
4343 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4344 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4345 ((Player*)this)->SendCooldownEvent(createBySpell);
4349 m_gameObj.remove(gameObj);
4351 if(del)
4353 gameObj->SetRespawnTime(0);
4354 gameObj->Delete();
4358 void Unit::RemoveGameObject(uint32 spellid, bool del)
4360 if(m_gameObj.empty())
4361 return;
4362 GameObjectList::iterator i, next;
4363 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4365 next = i;
4366 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4368 (*i)->SetOwnerGUID(0);
4369 if(del)
4371 (*i)->SetRespawnTime(0);
4372 (*i)->Delete();
4375 next = m_gameObj.erase(i);
4377 else
4378 ++next;
4382 void Unit::RemoveAllGameObjects()
4384 // remove references to unit
4385 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4387 (*i)->SetOwnerGUID(0);
4388 (*i)->SetRespawnTime(0);
4389 (*i)->Delete();
4390 i = m_gameObj.erase(i);
4394 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4396 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
4397 data.append(log->target->GetPackGUID());
4398 data.append(log->attacker->GetPackGUID());
4399 data << uint32(log->SpellID);
4400 data << uint32(log->damage); // damage amount
4401 data << uint32(log->overkill); // overkill
4402 data << uint8 (log->schoolMask); // damage school
4403 data << uint32(log->absorb); // AbsorbedDamage
4404 data << uint32(log->resist); // resist
4405 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
4406 data << uint8 (log->unused); // unused
4407 data << uint32(log->blocked); // blocked
4408 data << uint32(log->HitInfo);
4409 data << uint8 (0); // flag to use extend data
4410 SendMessageToSet( &data, true );
4413 void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4415 SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
4416 log.damage = Damage - AbsorbedDamage - Resist - Blocked;
4417 log.absorb = AbsorbedDamage;
4418 log.resist = Resist;
4419 log.physicalLog = PhysicalDamage;
4420 log.blocked = Blocked;
4421 log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
4422 if(CriticalHit)
4423 log.HitInfo |= SPELL_HIT_TYPE_CRIT;
4424 SendSpellNonMeleeDamageLog(&log);
4427 void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
4429 Aura *aura = pInfo->aura;
4430 Modifier *mod = aura->GetModifier();
4432 WorldPacket data(SMSG_PERIODICAURALOG, 30);
4433 data.append(aura->GetTarget()->GetPackGUID());
4434 data.appendPackGUID(aura->GetCasterGUID());
4435 data << uint32(aura->GetId()); // spellId
4436 data << uint32(1); // count
4437 data << uint32(mod->m_auraname); // auraId
4438 switch(mod->m_auraname)
4440 case SPELL_AURA_PERIODIC_DAMAGE:
4441 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
4442 data << uint32(pInfo->damage); // damage
4443 data << uint32(pInfo->overDamage); // overkill?
4444 data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
4445 data << uint32(pInfo->absorb); // absorb
4446 data << uint32(pInfo->resist); // resist
4447 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4448 break;
4449 case SPELL_AURA_PERIODIC_HEAL:
4450 case SPELL_AURA_OBS_MOD_HEALTH:
4451 data << uint32(pInfo->damage); // damage
4452 data << uint32(pInfo->overDamage); // overheal?
4453 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4454 break;
4455 case SPELL_AURA_OBS_MOD_MANA:
4456 case SPELL_AURA_PERIODIC_ENERGIZE:
4457 data << uint32(mod->m_miscvalue); // power type
4458 data << uint32(pInfo->damage); // damage
4459 break;
4460 case SPELL_AURA_PERIODIC_MANA_LEECH:
4461 data << uint32(mod->m_miscvalue); // power type
4462 data << uint32(pInfo->damage); // amount
4463 data << float(pInfo->multiplier); // gain multiplier
4464 break;
4465 default:
4466 sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(mod->m_auraname));
4467 return;
4470 aura->GetTarget()->SendMessageToSet(&data, true);
4473 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4475 // Not much to do if no flags are set.
4476 if (procAttacker)
4477 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4478 // Now go on with a victim's events'n'auras
4479 // Not much to do if no flags are set or there is no victim
4480 if(pVictim && pVictim->isAlive() && procVictim)
4481 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4484 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4486 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4487 data << uint32(spellID);
4488 data << uint64(GetGUID());
4489 data << uint8(0); // can be 0 or 1
4490 data << uint32(1); // target count
4491 // for(i = 0; i < target count; ++i)
4492 data << uint64(target->GetGUID()); // target GUID
4493 data << uint8(missInfo);
4494 // end loop
4495 SendMessageToSet(&data, true);
4498 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4500 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4502 uint32 count = 1;
4503 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
4504 data << uint32(damageInfo->HitInfo);
4505 data.append(damageInfo->attacker->GetPackGUID());
4506 data.append(damageInfo->target->GetPackGUID());
4507 data << uint32(damageInfo->damage); // Full damage
4508 data << uint32(0); // overkill value
4509 data << uint8(count); // Sub damage count
4511 for(int i = 0; i < count; ++i)
4513 data << uint32(damageInfo->damageSchoolMask); // School of sub damage
4514 data << float(damageInfo->damage); // sub damage
4515 data << uint32(damageInfo->damage); // Sub Damage
4518 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4520 for(int i = 0; i < count; ++i)
4521 data << uint32(damageInfo->absorb); // Absorb
4524 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4526 for(int i = 0; i < count; ++i)
4527 data << uint32(damageInfo->resist); // Resist
4530 data << uint8(damageInfo->TargetState);
4531 data << uint32(0);
4532 data << uint32(0);
4534 if(damageInfo->HitInfo & HITINFO_BLOCK)
4535 data << uint32(damageInfo->blocked_amount);
4537 if(damageInfo->HitInfo & HITINFO_UNK3)
4538 data << uint32(0);
4540 if(damageInfo->HitInfo & HITINFO_UNK1)
4542 data << uint32(0);
4543 data << float(0);
4544 data << float(0);
4545 data << float(0);
4546 data << float(0);
4547 data << float(0);
4548 data << float(0);
4549 data << float(0);
4550 data << float(0);
4551 for(uint8 i = 0; i < 5; ++i)
4553 data << float(0);
4554 data << float(0);
4556 data << uint32(0);
4559 SendMessageToSet( &data, true );
4562 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4564 CalcDamageInfo dmgInfo;
4565 dmgInfo.HitInfo = HitInfo;
4566 dmgInfo.attacker = this;
4567 dmgInfo.target = target;
4568 dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
4569 dmgInfo.damageSchoolMask = damageSchoolMask;
4570 dmgInfo.absorb = AbsorbDamage;
4571 dmgInfo.resist = Resist;
4572 dmgInfo.TargetState = TargetState;
4573 dmgInfo.blocked_amount = BlockedAmount;
4574 SendAttackStateUpdate(&dmgInfo);
4577 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4579 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4581 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4582 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4584 uint32 triggered_spell_id = 0;
4585 Unit* target = pVictim;
4586 int32 basepoints0 = 0;
4588 switch(hasteSpell->SpellFamilyName)
4590 case SPELLFAMILY_ROGUE:
4592 switch(hasteSpell->Id)
4594 // Blade Flurry
4595 case 13877:
4596 case 33735:
4598 target = SelectNearbyTarget(pVictim);
4599 if(!target)
4600 return false;
4601 basepoints0 = damage;
4602 triggered_spell_id = 22482;
4603 break;
4606 break;
4610 // processed charge only counting case
4611 if(!triggered_spell_id)
4612 return true;
4614 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4616 if(!triggerEntry)
4618 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4619 return false;
4622 // default case
4623 if(!target || target!=this && !target->isAlive())
4624 return false;
4626 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4627 return false;
4629 if(basepoints0)
4630 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4631 else
4632 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4634 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4635 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4637 return true;
4640 bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4642 SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
4644 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4645 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4647 uint32 triggered_spell_id = 0;
4648 Unit* target = pVictim;
4649 int32 basepoints0 = 0;
4651 switch(triggeredByAuraSpell->SpellFamilyName)
4653 case SPELLFAMILY_MAGE:
4655 switch(triggeredByAuraSpell->Id)
4657 // Focus Magic
4658 case 54646:
4660 Unit* caster = triggeredByAura->GetCaster();
4661 if(!caster)
4662 return false;
4664 triggered_spell_id = 54648;
4665 target = caster;
4666 break;
4672 // processed charge only counting case
4673 if(!triggered_spell_id)
4674 return true;
4676 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4678 if(!triggerEntry)
4680 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
4681 return false;
4684 // default case
4685 if(!target || target!=this && !target->isAlive())
4686 return false;
4688 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4689 return false;
4691 if(basepoints0)
4692 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4693 else
4694 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4696 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4697 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4699 return true;
4702 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4704 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4705 uint32 effIndex = triggeredByAura->GetEffIndex();
4706 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4708 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4709 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4711 uint32 triggered_spell_id = 0;
4712 Unit* target = pVictim;
4713 int32 basepoints0 = 0;
4715 switch(dummySpell->SpellFamilyName)
4717 case SPELLFAMILY_GENERIC:
4719 switch (dummySpell->Id)
4721 // Eye for an Eye
4722 case 9799:
4723 case 25988:
4725 // return damage % to attacker but < 50% own total health
4726 basepoints0 = triggerAmount*int32(damage)/100;
4727 if(basepoints0 > GetMaxHealth()/2)
4728 basepoints0 = GetMaxHealth()/2;
4730 triggered_spell_id = 25997;
4731 break;
4733 // Sweeping Strikes (NPC spells may be)
4734 case 18765:
4735 case 35429:
4737 // prevent chain of triggered spell from same triggered spell
4738 if(procSpell && procSpell->Id == 26654)
4739 return false;
4741 target = SelectNearbyTarget(pVictim);
4742 if(!target)
4743 return false;
4745 triggered_spell_id = 26654;
4746 break;
4748 // Unstable Power
4749 case 24658:
4751 if (!procSpell || procSpell->Id == 24659)
4752 return false;
4753 // Need remove one 24659 aura
4754 RemoveSingleSpellAurasFromStack(24659);
4755 return true;
4757 // Restless Strength
4758 case 24661:
4760 // Need remove one 24662 aura
4761 RemoveSingleSpellAurasFromStack(24662);
4762 return true;
4764 // Adaptive Warding (Frostfire Regalia set)
4765 case 28764:
4767 if(!procSpell)
4768 return false;
4770 // find Mage Armor
4771 bool found = false;
4772 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4773 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4775 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4777 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000)))
4779 found=true;
4780 break;
4784 if(!found)
4785 return false;
4787 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4789 case SPELL_SCHOOL_NORMAL:
4790 case SPELL_SCHOOL_HOLY:
4791 return false; // ignored
4792 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4793 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4794 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4795 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4796 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4797 default:
4798 return false;
4801 target = this;
4802 break;
4804 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4805 case 27539:
4807 if(!procSpell)
4808 return false;
4810 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4812 case SPELL_SCHOOL_NORMAL:
4813 return false; // ignore
4814 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4815 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4816 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4817 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4818 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4819 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4820 default:
4821 return false;
4824 target = this;
4825 break;
4827 // Mana Leech (Passive) (Priest Pet Aura)
4828 case 28305:
4830 // Cast on owner
4831 target = GetOwner();
4832 if(!target)
4833 return false;
4835 triggered_spell_id = 34650;
4836 break;
4838 // Mark of Malice
4839 case 33493:
4841 // Cast finish spell at last charge
4842 if (triggeredByAura->GetAuraCharges() > 1)
4843 return false;
4845 target = this;
4846 triggered_spell_id = 33494;
4847 break;
4849 // Twisted Reflection (boss spell)
4850 case 21063:
4851 triggered_spell_id = 21064;
4852 break;
4853 // Vampiric Aura (boss spell)
4854 case 38196:
4856 basepoints0 = 3 * damage; // 300%
4857 if (basepoints0 < 0)
4858 return false;
4860 triggered_spell_id = 31285;
4861 target = this;
4862 break;
4864 // Aura of Madness (Darkmoon Card: Madness trinket)
4865 //=====================================================
4866 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4867 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4868 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4869 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4870 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4871 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4872 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4873 // 41011 Martyr Complex: +35 stamina (All classes)
4874 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4875 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4876 case 39446:
4878 if(GetTypeId() != TYPEID_PLAYER)
4879 return false;
4881 // Select class defined buff
4882 switch (getClass())
4884 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4885 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4887 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4888 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4889 break;
4891 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4892 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4894 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4895 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4896 break;
4898 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4899 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4900 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4901 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4903 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4904 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4905 break;
4907 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4909 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4910 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4911 break;
4913 default:
4914 return false;
4917 target = this;
4918 if (roll_chance_i(10))
4919 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4920 break;
4923 // Sunwell Exalted Caster Neck (??? neck)
4924 // cast ??? Light's Wrath if Exalted by Aldor
4925 // cast ??? Arcane Bolt if Exalted by Scryers*/
4926 case 46569:
4927 return false; // old unused version
4928 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4929 // cast 45479 Light's Wrath if Exalted by Aldor
4930 // cast 45429 Arcane Bolt if Exalted by Scryers
4931 case 45481:
4933 if(GetTypeId() != TYPEID_PLAYER)
4934 return false;
4936 // Get Aldor reputation rank
4937 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4939 target = this;
4940 triggered_spell_id = 45479;
4941 break;
4943 // Get Scryers reputation rank
4944 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4946 // triggered at positive/self casts also, current attack target used then
4947 if(IsFriendlyTo(target))
4949 target = getVictim();
4950 if(!target)
4952 uint64 selected_guid = ((Player *)this)->GetSelection();
4953 target = ObjectAccessor::GetUnit(*this,selected_guid);
4954 if(!target)
4955 return false;
4957 if(IsFriendlyTo(target))
4958 return false;
4961 triggered_spell_id = 45429;
4962 break;
4964 return false;
4966 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4967 // cast 45480 Light's Strength if Exalted by Aldor
4968 // cast 45428 Arcane Strike if Exalted by Scryers
4969 case 45482:
4971 if(GetTypeId() != TYPEID_PLAYER)
4972 return false;
4974 // Get Aldor reputation rank
4975 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4977 target = this;
4978 triggered_spell_id = 45480;
4979 break;
4981 // Get Scryers reputation rank
4982 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4984 triggered_spell_id = 45428;
4985 break;
4987 return false;
4989 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4990 // cast 45431 Arcane Insight if Exalted by Aldor
4991 // cast 45432 Light's Ward if Exalted by Scryers
4992 case 45483:
4994 if(GetTypeId() != TYPEID_PLAYER)
4995 return false;
4997 // Get Aldor reputation rank
4998 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5000 target = this;
5001 triggered_spell_id = 45432;
5002 break;
5004 // Get Scryers reputation rank
5005 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5007 target = this;
5008 triggered_spell_id = 45431;
5009 break;
5011 return false;
5013 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
5014 // cast 45478 Light's Salvation if Exalted by Aldor
5015 // cast 45430 Arcane Surge if Exalted by Scryers
5016 case 45484:
5018 if(GetTypeId() != TYPEID_PLAYER)
5019 return false;
5021 // Get Aldor reputation rank
5022 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5024 target = this;
5025 triggered_spell_id = 45478;
5026 break;
5028 // Get Scryers reputation rank
5029 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5031 triggered_spell_id = 45430;
5032 break;
5034 return false;
5036 // Living Seed
5037 case 48504:
5039 triggered_spell_id = 48503;
5040 basepoints0 = triggerAmount;
5041 target = this;
5042 break;
5044 // Vampiric Touch (generic, used by some boss)
5045 case 52723:
5046 case 60501:
5048 triggered_spell_id = 52724;
5049 basepoints0 = damage / 2;
5050 target = this;
5051 break;
5053 // Divine purpose
5054 case 31871:
5055 case 31872:
5057 // Roll chane
5058 if (!roll_chance_i(triggerAmount))
5059 return false;
5061 // Remove any stun effect on target
5062 AuraMap& Auras = pVictim->GetAuras();
5063 for(AuraMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
5065 SpellEntry const *spell = iter->second->GetSpellProto();
5066 if( spell->Mechanic == MECHANIC_STUN ||
5067 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
5069 pVictim->RemoveAurasDueToSpell(spell->Id);
5070 iter = Auras.begin();
5072 else
5073 ++iter;
5075 return true;
5078 break;
5080 case SPELLFAMILY_MAGE:
5082 // Magic Absorption
5083 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
5085 if (getPowerType() != POWER_MANA)
5086 return false;
5088 // mana reward
5089 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
5090 target = this;
5091 triggered_spell_id = 29442;
5092 break;
5094 // Master of Elements
5095 if (dummySpell->SpellIconID == 1920)
5097 if(!procSpell)
5098 return false;
5100 // mana cost save
5101 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5102 basepoints0 = cost * triggerAmount/100;
5103 if( basepoints0 <=0 )
5104 return false;
5106 target = this;
5107 triggered_spell_id = 29077;
5108 break;
5111 // Arcane Potency
5112 if (dummySpell->SpellIconID == 2120)
5114 if(!procSpell)
5115 return false;
5117 target = this;
5118 switch (dummySpell->Id)
5120 case 31571: triggered_spell_id = 57529; break;
5121 case 31572: triggered_spell_id = 57531; break;
5122 default:
5123 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
5124 return false;
5126 break;
5129 // Hot Streak
5130 if (dummySpell->SpellIconID == 2999)
5132 if (effIndex!=0)
5133 return true;
5134 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
5135 if (!counter)
5136 return true;
5138 // Count spell criticals in a row in second aura
5139 Modifier *mod = counter->GetModifier();
5140 if (procEx & PROC_EX_CRITICAL_HIT)
5142 mod->m_amount *=2;
5143 if (mod->m_amount < 100) // not enough
5144 return true;
5145 // Crititcal counted -> roll chance
5146 if (roll_chance_i(triggerAmount))
5147 CastSpell(this, 48108, true, castItem, triggeredByAura);
5149 mod->m_amount = 25;
5150 return true;
5152 // Burnout
5153 if (dummySpell->SpellIconID == 2998)
5155 if(!procSpell)
5156 return false;
5158 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5159 basepoints0 = cost * triggerAmount/100;
5160 if( basepoints0 <=0 )
5161 return false;
5162 triggered_spell_id = 44450;
5163 target = this;
5164 break;
5166 // Incanter's Regalia set (add trigger chance to Mana Shield)
5167 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5169 if(GetTypeId() != TYPEID_PLAYER)
5170 return false;
5172 target = this;
5173 triggered_spell_id = 37436;
5174 break;
5176 switch(dummySpell->Id)
5178 // Ignite
5179 case 11119:
5180 case 11120:
5181 case 12846:
5182 case 12847:
5183 case 12848:
5185 switch (dummySpell->Id)
5187 case 11119: basepoints0 = int32(0.04f*damage); break;
5188 case 11120: basepoints0 = int32(0.08f*damage); break;
5189 case 12846: basepoints0 = int32(0.12f*damage); break;
5190 case 12847: basepoints0 = int32(0.16f*damage); break;
5191 case 12848: basepoints0 = int32(0.20f*damage); break;
5192 default:
5193 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
5194 return false;
5197 triggered_spell_id = 12654;
5198 break;
5200 // Combustion
5201 case 11129:
5203 //last charge and crit
5204 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
5206 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
5207 return true; // charge counting (will removed)
5210 CastSpell(this, 28682, true, castItem, triggeredByAura);
5211 return (procEx & PROC_EX_CRITICAL_HIT); // charge update only at crit hits, no hidden cooldowns
5213 // Glyph of Ice Block
5214 case 56372:
5216 if (GetTypeId() != TYPEID_PLAYER)
5217 return false;
5219 // not 100% safe with client version switches but for 3.1.3 no spells with cooldown that can have mage player except Frost Nova.
5220 ((Player*)this)->RemoveSpellCategoryCooldown(35, true);
5221 return true;
5223 // Glyph of Polymorph
5224 case 56375:
5226 if (!pVictim || !pVictim->isAlive())
5227 return false;
5229 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE);
5230 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
5231 return true;
5234 break;
5236 case SPELLFAMILY_WARRIOR:
5238 // Retaliation
5239 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000))
5241 // check attack comes not from behind
5242 if (!HasInArc(M_PI, pVictim))
5243 return false;
5245 triggered_spell_id = 22858;
5246 break;
5248 // Second Wind
5249 if (dummySpell->SpellIconID == 1697)
5251 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
5252 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5253 return false;
5254 // Need stun or root mechanic
5255 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_STUN_MASK))
5256 return false;
5258 switch (dummySpell->Id)
5260 case 29838: triggered_spell_id=29842; break;
5261 case 29834: triggered_spell_id=29841; break;
5262 case 42770: triggered_spell_id=42771; break;
5263 default:
5264 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
5265 return false;
5268 target = this;
5269 break;
5271 // Damage Shield
5272 if (dummySpell->SpellIconID == 3214)
5274 triggered_spell_id = 59653;
5275 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
5276 break;
5279 // Sweeping Strikes
5280 if (dummySpell->Id == 12328)
5282 // prevent chain of triggered spell from same triggered spell
5283 if(procSpell && procSpell->Id == 26654)
5284 return false;
5286 target = SelectNearbyTarget(pVictim);
5287 if(!target)
5288 return false;
5290 triggered_spell_id = 26654;
5291 break;
5293 break;
5295 case SPELLFAMILY_WARLOCK:
5297 // Seed of Corruption
5298 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
5300 Modifier* mod = triggeredByAura->GetModifier();
5301 // if damage is more than need or target die from damage deal finish spell
5302 if( mod->m_amount <= damage || GetHealth() <= damage )
5304 // remember guid before aura delete
5305 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5307 // Remove aura (before cast for prevent infinite loop handlers)
5308 RemoveAurasDueToSpell(triggeredByAura->GetId());
5310 // Cast finish spell (triggeredByAura already not exist!)
5311 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
5312 return true; // no hidden cooldown
5315 // Damage counting
5316 mod->m_amount-=damage;
5317 return true;
5319 // Seed of Corruption (Mobs cast) - no die req
5320 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932)
5322 Modifier* mod = triggeredByAura->GetModifier();
5323 // if damage is more than need deal finish spell
5324 if( mod->m_amount <= damage )
5326 // remember guid before aura delete
5327 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5329 // Remove aura (before cast for prevent infinite loop handlers)
5330 RemoveAurasDueToSpell(triggeredByAura->GetId());
5332 // Cast finish spell (triggeredByAura already not exist!)
5333 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5334 return true; // no hidden cooldown
5336 // Damage counting
5337 mod->m_amount-=damage;
5338 return true;
5340 // Fel Synergy
5341 if (dummySpell->SpellIconID == 3222)
5343 target = GetPet();
5344 if (!target)
5345 return false;
5346 basepoints0 = damage * triggerAmount / 100;
5347 triggered_spell_id = 54181;
5348 break;
5350 switch(dummySpell->Id)
5352 // Nightfall & Glyph of Corruption
5353 case 18094:
5354 case 18095:
5355 case 56218:
5357 target = this;
5358 triggered_spell_id = 17941;
5359 break;
5361 //Soul Leech
5362 case 30293:
5363 case 30295:
5364 case 30296:
5366 // health
5367 basepoints0 = int32(damage*triggerAmount/100);
5368 target = this;
5369 triggered_spell_id = 30294;
5370 break;
5372 // Shadowflame (Voidheart Raiment set bonus)
5373 case 37377:
5375 triggered_spell_id = 37379;
5376 break;
5378 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5379 case 37381:
5381 target = GetPet();
5382 if(!target)
5383 return false;
5385 // heal amount
5386 basepoints0 = damage * triggerAmount/100;
5387 triggered_spell_id = 37382;
5388 break;
5390 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5391 case 39437:
5393 triggered_spell_id = 37378;
5394 break;
5396 // Siphon Life
5397 case 63108:
5399 basepoints0 = int32(damage * triggerAmount / 100);
5400 triggered_spell_id = 63106;
5401 break;
5403 // Glyph of Life Tap
5404 case 63320:
5406 triggered_spell_id = 63321;
5407 break;
5410 break;
5412 case SPELLFAMILY_PRIEST:
5414 // Vampiric Touch
5415 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
5417 if(!pVictim || !pVictim->isAlive())
5418 return false;
5420 // pVictim is caster of aura
5421 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5422 return false;
5424 // Energize 0.25% of max. mana
5425 pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
5426 return true; // no hidden cooldown
5429 // Divine Aegis
5430 if (dummySpell->SpellIconID == 2820)
5432 basepoints0 = damage * triggerAmount/100;
5433 triggered_spell_id = 47753;
5434 break;
5436 // Improved Shadowform
5437 else if (dummySpell->SpellIconID == 217)
5439 if(!roll_chance_i(triggerAmount))
5440 return false;
5442 RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT);
5443 RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
5444 break;
5447 switch(dummySpell->Id)
5449 // Vampiric Embrace
5450 case 15286:
5452 if(!pVictim || !pVictim->isAlive())
5453 return false;
5455 // pVictim is caster of aura
5456 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5457 return false;
5459 // heal amount
5460 int32 team = triggerAmount*damage/500;
5461 int32 self = triggerAmount*damage/100 - team;
5462 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5463 return true; // no hidden cooldown
5465 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5466 case 40438:
5468 // Shadow Word: Pain
5469 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5470 triggered_spell_id = 40441;
5471 // Renew
5472 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5473 triggered_spell_id = 40440;
5474 else
5475 return false;
5477 target = this;
5478 break;
5480 // Oracle Healing Bonus ("Garments of the Oracle" set)
5481 case 26169:
5483 // heal amount
5484 basepoints0 = int32(damage * 10/100);
5485 target = this;
5486 triggered_spell_id = 26170;
5487 break;
5489 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5490 case 39372:
5492 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5493 return false;
5495 // heal amount
5496 basepoints0 = damage * triggerAmount/100;
5497 target = this;
5498 triggered_spell_id = 39373;
5499 break;
5501 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5502 case 28809:
5504 triggered_spell_id = 28810;
5505 break;
5507 // Glyph of Dispel Magic
5508 case 55677:
5510 if(!target->IsFriendlyTo(this))
5511 return false;
5513 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5514 triggered_spell_id = 56131;
5515 break;
5518 break;
5520 case SPELLFAMILY_DRUID:
5522 switch(dummySpell->Id)
5524 // Healing Touch (Dreamwalker Raiment set)
5525 case 28719:
5527 // mana back
5528 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5529 target = this;
5530 triggered_spell_id = 28742;
5531 break;
5533 // Healing Touch Refund (Idol of Longevity trinket)
5534 case 28847:
5536 target = this;
5537 triggered_spell_id = 28848;
5538 break;
5540 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5541 case 37288:
5542 case 37295:
5544 target = this;
5545 triggered_spell_id = 37238;
5546 break;
5548 // Druid Tier 6 Trinket
5549 case 40442:
5551 float chance;
5553 // Starfire
5554 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5556 triggered_spell_id = 40445;
5557 chance = 25.0f;
5559 // Rejuvenation
5560 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5562 triggered_spell_id = 40446;
5563 chance = 25.0f;
5565 // Mangle (Bear) and Mangle (Cat)
5566 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000))
5568 triggered_spell_id = 40452;
5569 chance = 40.0f;
5571 else
5572 return false;
5574 if (!roll_chance_f(chance))
5575 return false;
5577 target = this;
5578 break;
5580 // Maim Interrupt
5581 case 44835:
5583 // Deadly Interrupt Effect
5584 triggered_spell_id = 32747;
5585 break;
5588 // Eclipse
5589 if (dummySpell->SpellIconID == 2856)
5591 if (!procSpell)
5592 return false;
5593 // Only 0 aura can proc
5594 if (effIndex!=0)
5595 return true;
5596 // Wrath crit
5597 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
5599 if (!roll_chance_i(60))
5600 return false;
5601 triggered_spell_id = 48518;
5602 target = this;
5603 break;
5605 // Starfire crit
5606 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5608 triggered_spell_id = 48517;
5609 target = this;
5610 break;
5612 return false;
5614 // Living Seed
5615 else if (dummySpell->SpellIconID == 2860)
5617 triggered_spell_id = 48504;
5618 basepoints0 = triggerAmount * damage / 100;
5619 break;
5621 break;
5623 case SPELLFAMILY_ROGUE:
5625 switch(dummySpell->Id)
5627 // Deadly Throw Interrupt
5628 case 32748:
5630 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5631 if (this == pVictim)
5632 return false;
5634 triggered_spell_id = 32747;
5635 break;
5638 // Cut to the Chase
5639 if (dummySpell->SpellIconID == 2909)
5641 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5642 // lookup Slice and Dice
5643 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5644 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5646 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5647 if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5648 (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000)))
5650 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5651 (*itr)->RefreshAura();
5652 return true;
5655 return false;
5657 // Deadly Brew
5658 if (dummySpell->SpellIconID == 2963)
5660 triggered_spell_id = 44289;
5661 break;
5663 // Quick Recovery
5664 if (dummySpell->SpellIconID == 2116)
5666 if(!procSpell)
5667 return false;
5669 // energy cost save
5670 basepoints0 = procSpell->manaCost * triggerAmount/100;
5671 if (basepoints0 <= 0)
5672 return false;
5674 target = this;
5675 triggered_spell_id = 31663;
5676 break;
5678 break;
5680 case SPELLFAMILY_HUNTER:
5682 // Aspect of the Viper
5683 if (dummySpell->SpellFamilyFlags & UI64LIT(0x4000000000000))
5685 uint32 maxmana = GetMaxPower(POWER_MANA);
5686 basepoints0 = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f);
5688 target = this;
5689 triggered_spell_id = 34075;
5690 break;
5692 // Thrill of the Hunt
5693 if (dummySpell->SpellIconID == 2236)
5695 if(!procSpell)
5696 return false;
5698 // mana cost save
5699 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5700 basepoints0 = mana * 40/100;
5701 if(basepoints0 <= 0)
5702 return false;
5704 target = this;
5705 triggered_spell_id = 34720;
5706 break;
5708 // Hunting Party
5709 if ( dummySpell->SpellIconID == 3406 )
5711 triggered_spell_id = 57669;
5712 target = this;
5713 break;
5715 // Lock and Load
5716 if ( dummySpell->SpellIconID == 3579 )
5718 // Proc only from periodic (from trap activation proc another aura of this spell)
5719 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5720 return false;
5721 triggered_spell_id = 56453;
5722 target = this;
5723 break;
5725 // Rapid Recuperation
5726 if ( dummySpell->SpellIconID == 3560 )
5728 // This effect only from Rapid Killing (mana regen)
5729 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000)))
5730 return false;
5731 triggered_spell_id = 56654;
5732 target = this;
5733 break;
5735 break;
5737 case SPELLFAMILY_PALADIN:
5739 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5740 if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex==0)
5742 triggered_spell_id = 25742;
5743 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5744 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5745 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5746 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5747 break;
5749 // Sacred Shield
5750 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0008000000000000))
5752 triggered_spell_id = 58597;
5753 target = this;
5754 break;
5756 // Righteous Vengeance
5757 if (dummySpell->SpellIconID == 3025)
5759 // 4 damage tick
5760 basepoints0 = triggerAmount*damage/400;
5761 triggered_spell_id = 61840;
5762 break;
5764 // Sheath of Light
5765 if (dummySpell->SpellIconID == 3030)
5767 // 4 healing tick
5768 basepoints0 = triggerAmount*damage/400;
5769 triggered_spell_id = 54203;
5770 break;
5772 switch(dummySpell->Id)
5774 // Judgement of Light
5775 case 20185:
5777 // Get judgement caster
5778 Unit *caster = triggeredByAura->GetCaster();
5779 if (!caster)
5780 return false;
5781 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5782 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5783 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5784 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5785 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
5786 return true;
5788 // Judgement of Wisdom
5789 case 20186:
5791 if (pVictim->getPowerType() == POWER_MANA)
5793 // 2% of maximum base mana
5794 basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100);
5795 pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
5797 return true;
5799 // Heart of the Crusader (Rank 1)
5800 case 20335:
5801 triggered_spell_id = 21183;
5802 break;
5803 // Heart of the Crusader (Rank 2)
5804 case 20336:
5805 triggered_spell_id = 54498;
5806 break;
5807 // Heart of the Crusader (Rank 3)
5808 case 20337:
5809 triggered_spell_id = 54499;
5810 break;
5811 case 20911: // Blessing of Sanctuary
5812 case 25899: // Greater Blessing of Sanctuary
5814 target = this;
5815 switch (target->getPowerType())
5817 case POWER_MANA:
5818 triggered_spell_id = 57319;
5819 break;
5820 default:
5821 return false;
5823 break;
5825 // Holy Power (Redemption Armor set)
5826 case 28789:
5828 if(!pVictim)
5829 return false;
5831 // Set class defined buff
5832 switch (pVictim->getClass())
5834 case CLASS_PALADIN:
5835 case CLASS_PRIEST:
5836 case CLASS_SHAMAN:
5837 case CLASS_DRUID:
5838 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5839 break;
5840 case CLASS_MAGE:
5841 case CLASS_WARLOCK:
5842 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5843 break;
5844 case CLASS_HUNTER:
5845 case CLASS_ROGUE:
5846 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5847 break;
5848 case CLASS_WARRIOR:
5849 triggered_spell_id = 28790; // Increases the friendly target's armor
5850 break;
5851 default:
5852 return false;
5854 break;
5856 // Seal of Vengeance (damage calc on apply aura)
5857 case 31801:
5859 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5860 return false;
5862 triggered_spell_id = 31803;
5864 // Add 5-stack effect
5865 int8 stacks = 0;
5866 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
5867 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
5869 if( ((*itr)->GetId() == 31803) && (*itr)->GetCasterGUID()==GetGUID())
5871 stacks = (*itr)->GetStackAmount();
5872 break;
5875 if(stacks >= 5)
5876 CastSpell(target,42463,true,NULL,triggeredByAura);
5877 break;
5879 // Judgements of the Wise
5880 case 31876:
5881 case 31877:
5882 case 31878:
5883 // triggered only at casted Judgement spells, not at additional Judgement effects
5884 if(!procSpell || procSpell->Category != 1210)
5885 return false;
5887 target = this;
5888 triggered_spell_id = 31930;
5890 // Replenishment
5891 CastSpell(this, 57669, true, NULL, triggeredByAura);
5892 break;
5893 // Spiritual Attunement
5894 case 31785:
5895 case 33776:
5897 // if healed by another unit (pVictim)
5898 if(this == pVictim)
5899 return false;
5901 // heal amount
5902 basepoints0 = triggerAmount*damage/100;
5903 target = this;
5904 triggered_spell_id = 31786;
5905 break;
5907 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5908 case 40470:
5910 if (!procSpell)
5911 return false;
5913 float chance;
5915 // Flash of light/Holy light
5916 if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000))
5918 triggered_spell_id = 40471;
5919 chance = 15.0f;
5921 // Judgement (any)
5922 else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT)
5924 triggered_spell_id = 40472;
5925 chance = 50.0f;
5927 else
5928 return false;
5930 if (!roll_chance_f(chance))
5931 return false;
5933 break;
5935 // Seal of Corruption (damage calc on apply aura)
5936 case 53736:
5938 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5939 return false;
5941 triggered_spell_id = 53742;
5943 // Add 5-stack effect
5944 int8 stacks = 0;
5945 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
5946 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
5948 if( ((*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
5950 stacks = (*itr)->GetStackAmount();
5951 break;
5954 if(stacks >= 5)
5955 CastSpell(target,53739,true,NULL,triggeredByAura);
5956 break;
5958 // Light's Beacon (heal target area aura)
5959 case 53651:
5961 // not do bonus heal for explicit beacon focus healing
5962 if (GetGUID() == triggeredByAura->GetCasterGUID())
5963 return false;
5965 // beacon
5966 Unit* beacon = triggeredByAura->GetCaster();
5967 if (!beacon)
5968 return false;
5970 // find caster main aura at beacon
5971 Aura* dummy = NULL;
5972 Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_PERIODIC_TRIGGER_SPELL);
5973 for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i)
5975 if ((*i)->GetId() == 53563 && (*i)->GetCasterGUID() == pVictim->GetGUID())
5977 dummy = (*i);
5978 break;
5982 // original heal must be form beacon caster
5983 if (!dummy)
5984 return false;
5986 triggered_spell_id = 53652; // Beacon of Light
5987 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5989 // cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check
5990 beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID());
5991 return true;
5993 // Glyph of Divinity
5994 case 54939:
5996 // Lookup base amount mana restore
5997 for (int i=0; i<3;++i)
5998 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
6000 int32 mana = procSpell->EffectBasePoints[i];
6001 CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura);
6002 break;
6004 return true;
6006 // Glyph of Flash of Light
6007 case 54936:
6009 triggered_spell_id = 54957;
6010 basepoints0 = triggerAmount*damage/100;
6011 break;
6013 // Glyph of Holy Light
6014 case 54937:
6016 triggered_spell_id = 54968;
6017 basepoints0 = triggerAmount*damage/100;
6018 break;
6021 break;
6023 case SPELLFAMILY_SHAMAN:
6025 switch(dummySpell->Id)
6027 // Totemic Power (The Earthshatterer set)
6028 case 28823:
6030 if( !pVictim )
6031 return false;
6033 // Set class defined buff
6034 switch (pVictim->getClass())
6036 case CLASS_PALADIN:
6037 case CLASS_PRIEST:
6038 case CLASS_SHAMAN:
6039 case CLASS_DRUID:
6040 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6041 break;
6042 case CLASS_MAGE:
6043 case CLASS_WARLOCK:
6044 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6045 break;
6046 case CLASS_HUNTER:
6047 case CLASS_ROGUE:
6048 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
6049 break;
6050 case CLASS_WARRIOR:
6051 triggered_spell_id = 28827; // Increases the friendly target's armor
6052 break;
6053 default:
6054 return false;
6056 break;
6058 // Lesser Healing Wave (Totem of Flowing Water Relic)
6059 case 28849:
6061 target = this;
6062 triggered_spell_id = 28850;
6063 break;
6065 // Windfury Weapon (Passive) 1-5 Ranks
6066 case 33757:
6068 if(GetTypeId()!=TYPEID_PLAYER)
6069 return false;
6071 if(!castItem || !castItem->IsEquipped())
6072 return false;
6074 // custom cooldown processing case
6075 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6076 return false;
6078 // Now amount of extra power stored in 1 effect of Enchant spell
6079 // Get it by item enchant id
6080 uint32 spellId;
6081 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
6083 case 283: spellId = 8232; break; // 1 Rank
6084 case 284: spellId = 8235; break; // 2 Rank
6085 case 525: spellId = 10486; break; // 3 Rank
6086 case 1669:spellId = 16362; break; // 4 Rank
6087 case 2636:spellId = 25505; break; // 5 Rank
6088 case 3785:spellId = 58801; break; // 6 Rank
6089 case 3786:spellId = 58803; break; // 7 Rank
6090 case 3787:spellId = 58804; break; // 8 Rank
6091 default:
6093 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
6094 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
6095 return false;
6099 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
6100 if(!windfurySpellEntry)
6102 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
6103 return false;
6106 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
6108 // Off-Hand case
6109 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
6111 // Value gained from additional AP
6112 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
6113 triggered_spell_id = 33750;
6115 // Main-Hand case
6116 else
6118 // Value gained from additional AP
6119 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
6120 triggered_spell_id = 25504;
6123 // apply cooldown before cast to prevent processing itself
6124 if( cooldown )
6125 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6127 // Attack Twice
6128 for ( uint32 i = 0; i<2; ++i )
6129 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6131 return true;
6133 // Shaman Tier 6 Trinket
6134 case 40463:
6136 if( !procSpell )
6137 return false;
6139 float chance;
6140 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6142 triggered_spell_id = 40465; // Lightning Bolt
6143 chance = 15.0f;
6145 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))
6147 triggered_spell_id = 40465; // Lesser Healing Wave
6148 chance = 10.0f;
6150 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
6152 triggered_spell_id = 40466; // Stormstrike
6153 chance = 50.0f;
6155 else
6156 return false;
6158 if (!roll_chance_f(chance))
6159 return false;
6161 target = this;
6162 break;
6164 // Glyph of Healing Wave
6165 case 55440:
6167 // Not proc from self heals
6168 if (this==pVictim)
6169 return false;
6170 basepoints0 = triggerAmount * damage / 100;
6171 target = this;
6172 triggered_spell_id = 55533;
6173 break;
6175 // Spirit Hunt
6176 case 58877:
6178 // Cast on owner
6179 target = GetOwner();
6180 if(!target)
6181 return false;
6182 basepoints0 = triggerAmount * damage / 100;
6183 triggered_spell_id = 58879;
6184 break;
6186 // Shaman T8 Elemental 4P Bonus
6187 case 64928:
6189 basepoints0 = int32( triggerAmount * damage / 100 );
6190 triggered_spell_id = 64930; // Electrified
6191 break;
6194 // Storm, Earth and Fire
6195 if (dummySpell->SpellIconID == 3063)
6197 // Earthbind Totem summon only
6198 if(procSpell->Id != 2484)
6199 return false;
6201 float chance = triggerAmount;
6202 if (!roll_chance_f(chance))
6203 return false;
6205 triggered_spell_id = 64695;
6206 break;
6208 // Ancestral Awakening
6209 if (dummySpell->SpellIconID == 3065)
6211 triggered_spell_id = 52759;
6212 basepoints0 = triggerAmount * damage / 100;
6213 target = this;
6214 break;
6216 // Earth Shield
6217 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
6219 target = this;
6220 basepoints0 = triggerAmount;
6222 // Glyph of Earth Shield
6223 if (Aura* aur = GetDummyAura(63279))
6225 int32 aur_mod = aur->GetModifier()->m_amount;
6226 basepoints0 = int32(basepoints0 * (aur_mod + 100.0f) / 100.0f);
6229 triggered_spell_id = 379;
6230 break;
6232 // Improved Water Shield
6233 if (dummySpell->SpellIconID == 2287)
6235 // Lesser Healing Wave need aditional 60% roll
6236 if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60))
6237 return false;
6238 // lookup water shield
6239 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6240 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6242 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6243 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000)))
6245 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
6246 CastSpell(this, spell, true, castItem, triggeredByAura);
6247 if ((*itr)->DropAuraCharge())
6248 RemoveAurasDueToSpell((*itr)->GetId());
6249 return true;
6252 return false;
6253 break;
6255 // Lightning Overload
6256 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
6258 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
6259 return false;
6261 // custom cooldown processing case
6262 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6263 return false;
6265 uint32 spellId = 0;
6266 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
6267 switch (procSpell->Id)
6269 // Lightning Bolt
6270 case 403: spellId = 45284; break; // Rank 1
6271 case 529: spellId = 45286; break; // Rank 2
6272 case 548: spellId = 45287; break; // Rank 3
6273 case 915: spellId = 45288; break; // Rank 4
6274 case 943: spellId = 45289; break; // Rank 5
6275 case 6041: spellId = 45290; break; // Rank 6
6276 case 10391: spellId = 45291; break; // Rank 7
6277 case 10392: spellId = 45292; break; // Rank 8
6278 case 15207: spellId = 45293; break; // Rank 9
6279 case 15208: spellId = 45294; break; // Rank 10
6280 case 25448: spellId = 45295; break; // Rank 11
6281 case 25449: spellId = 45296; break; // Rank 12
6282 case 49237: spellId = 49239; break; // Rank 13
6283 case 49238: spellId = 49240; break; // Rank 14
6284 // Chain Lightning
6285 case 421: spellId = 45297; break; // Rank 1
6286 case 930: spellId = 45298; break; // Rank 2
6287 case 2860: spellId = 45299; break; // Rank 3
6288 case 10605: spellId = 45300; break; // Rank 4
6289 case 25439: spellId = 45301; break; // Rank 5
6290 case 25442: spellId = 45302; break; // Rank 6
6291 case 49270: spellId = 49268; break; // Rank 7
6292 case 49271: spellId = 49269; break; // Rank 8
6293 default:
6294 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
6295 return false;
6297 // No thread generated mod
6298 // TODO: exist special flag in spell attributes for this, need found and use!
6299 SpellModifier *mod = new SpellModifier;
6300 mod->op = SPELLMOD_THREAT;
6301 mod->value = -100;
6302 mod->type = SPELLMOD_PCT;
6303 mod->spellId = dummySpell->Id;
6304 mod->mask = UI64LIT(0x0000000000000003);
6305 mod->mask2= UI64LIT(0x0);
6306 ((Player*)this)->AddSpellMod(mod, true);
6308 // Remove cooldown (Chain Lightning - have Category Recovery time)
6309 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002))
6310 ((Player*)this)->RemoveSpellCooldown(spellId);
6312 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
6314 ((Player*)this)->AddSpellMod(mod, false);
6316 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6317 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6319 return true;
6321 // Static Shock
6322 if(dummySpell->SpellIconID == 3059)
6324 // lookup Lightning Shield
6325 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6326 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6328 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6329 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
6331 uint32 spell = 0;
6332 switch ((*itr)->GetId())
6334 case 324: spell = 26364; break;
6335 case 325: spell = 26365; break;
6336 case 905: spell = 26366; break;
6337 case 945: spell = 26367; break;
6338 case 8134: spell = 26369; break;
6339 case 10431: spell = 26370; break;
6340 case 10432: spell = 26363; break;
6341 case 25469: spell = 26371; break;
6342 case 25472: spell = 26372; break;
6343 case 49280: spell = 49278; break;
6344 case 49281: spell = 49279; break;
6345 default:
6346 return false;
6348 CastSpell(target, spell, true, castItem, triggeredByAura);
6349 if ((*itr)->DropAuraCharge())
6350 RemoveAurasDueToSpell((*itr)->GetId());
6351 return true;
6354 return false;
6355 break;
6357 break;
6359 case SPELLFAMILY_DEATHKNIGHT:
6361 // Blood Aura
6362 if (dummySpell->SpellIconID == 2636)
6364 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
6365 return false;
6366 basepoints0 = triggerAmount * damage / 100;
6367 triggered_spell_id = 53168;
6368 break;
6370 // Butchery
6371 if (dummySpell->SpellIconID == 2664)
6373 basepoints0 = triggerAmount;
6374 triggered_spell_id = 50163;
6375 target = this;
6376 break;
6378 // Dancing Rune Weapon
6379 if (dummySpell->Id == 49028)
6381 // 1 dummy aura for dismiss rune blade
6382 if (effIndex!=2)
6383 return false;
6384 // TODO: wite script for this "fights on its own, doing the same attacks"
6385 // NOTE: Trigger here on every attack and spell cast
6386 return false;
6388 // Mark of Blood
6389 if (dummySpell->Id == 49005)
6391 // TODO: need more info (cooldowns/PPM)
6392 triggered_spell_id = 61607;
6393 break;
6395 // Vendetta
6396 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000))
6398 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6399 triggered_spell_id = 50181;
6400 target = this;
6401 break;
6403 // Necrosis
6404 if (dummySpell->SpellIconID == 2709)
6406 basepoints0 = triggerAmount * damage / 100;
6407 triggered_spell_id = 51460;
6408 break;
6410 // Threat of Thassarian
6411 if (dummySpell->SpellIconID == 2023)
6413 // Must Dual Wield
6414 if (!procSpell || !haveOffhandWeapon())
6415 return false;
6416 // Chance as basepoints for dummy aura
6417 if (!roll_chance_i(triggerAmount))
6418 return false;
6420 switch (procSpell->Id)
6422 // Obliterate
6423 case 49020: // Rank 1
6424 triggered_spell_id = 66198; break;
6425 case 51423: // Rank 2
6426 triggered_spell_id = 66972; break;
6427 case 51424: // Rank 3
6428 triggered_spell_id = 66973; break;
6429 case 51425: // Rank 4
6430 triggered_spell_id = 66974; break;
6431 // Frost Strike
6432 case 49143: // Rank 1
6433 triggered_spell_id = 66196; break;
6434 case 51416: // Rank 2
6435 triggered_spell_id = 66958; break;
6436 case 51417: // Rank 3
6437 triggered_spell_id = 66959; break;
6438 case 51418: // Rank 4
6439 triggered_spell_id = 66960; break;
6440 case 51419: // Rank 5
6441 triggered_spell_id = 66961; break;
6442 case 51420: // Rank 6
6443 triggered_spell_id = 66962; break;
6444 // Plague Strike
6445 case 45462: // Rank 1
6446 triggered_spell_id = 66216; break;
6447 case 49917: // Rank 2
6448 triggered_spell_id = 66988; break;
6449 case 49918: // Rank 3
6450 triggered_spell_id = 66989; break;
6451 case 49919: // Rank 4
6452 triggered_spell_id = 66990; break;
6453 case 49920: // Rank 5
6454 triggered_spell_id = 66991; break;
6455 case 49921: // Rank 6
6456 triggered_spell_id = 66992; break;
6457 // Death Strike
6458 case 49998: // Rank 1
6459 triggered_spell_id = 66188; break;
6460 case 49999: // Rank 2
6461 triggered_spell_id = 66950; break;
6462 case 45463: // Rank 3
6463 triggered_spell_id = 66951; break;
6464 case 49923: // Rank 4
6465 triggered_spell_id = 66952; break;
6466 case 49924: // Rank 5
6467 triggered_spell_id = 66953; break;
6468 // Rune Strike
6469 case 56815:
6470 triggered_spell_id = 66217; break;
6471 // Blood Strike
6472 case 45902: // Rank 1
6473 triggered_spell_id = 66215; break;
6474 case 49926: // Rank 2
6475 triggered_spell_id = 66975; break;
6476 case 49927: // Rank 3
6477 triggered_spell_id = 66976; break;
6478 case 49928: // Rank 4
6479 triggered_spell_id = 66977; break;
6480 case 49929: // Rank 5
6481 triggered_spell_id = 66978; break;
6482 case 49930: // Rank 6
6483 triggered_spell_id = 66979; break;
6484 default:
6485 return false;
6487 break;
6489 // Runic Power Back on Snare/Root
6490 if (dummySpell->Id == 61257)
6492 // only for spells and hit/crit (trigger start always) and not start from self casted spells
6493 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6494 return false;
6495 // Need snare or root mechanic
6496 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_SNARE_MASK))
6497 return false;
6498 triggered_spell_id = 61258;
6499 target = this;
6500 break;
6502 // Wandering Plague
6503 if (dummySpell->SpellIconID == 1614)
6505 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
6506 return false;
6507 basepoints0 = triggerAmount * damage / 100;
6508 triggered_spell_id = 50526;
6509 break;
6511 // Blood-Caked Blade
6512 if (dummySpell->SpellIconID == 138)
6514 triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
6515 break;
6517 break;
6519 default:
6520 break;
6523 // processed charge only counting case
6524 if(!triggered_spell_id)
6525 return true;
6527 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6529 if(!triggerEntry)
6531 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
6532 return false;
6535 // default case
6536 if(!target || target!=this && !target->isAlive())
6537 return false;
6539 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6540 return false;
6542 if(basepoints0)
6543 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6544 else
6545 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
6547 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6548 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6550 return true;
6553 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
6555 // Get triggered aura spell info
6556 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
6558 // Basepoints of trigger aura
6559 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
6561 // Set trigger spell id, target, custom basepoints
6562 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
6563 Unit* target = NULL;
6564 int32 basepoints[3] = {0, 0, 0};
6566 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
6567 basepoints[0] = triggerAmount;
6569 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6570 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6572 // Try handle unknown trigger spells
6573 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
6575 switch (auraSpellInfo->SpellFamilyName)
6577 case SPELLFAMILY_GENERIC:
6578 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
6579 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6580 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6581 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6582 trigger_spell_id = 23781;
6583 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6584 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6586 // trigger_spell_id = 48877;
6588 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6590 // trigger_spell_id = 59233;
6592 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6594 // trigger_spell_id = 29471; // gain mana
6595 // 27526; // drain mana if possible
6597 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6598 //else if (auraSpellInfo->Id==54476) // Blood Presence
6599 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6600 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6601 //else if (auraSpellInfo->Id==52856) // Charge
6602 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6604 // Pct value stored in dummy
6605 basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6606 target = pVictim;
6607 break;
6609 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6610 // trigger_spell_id = 41249;
6611 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6612 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6613 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6614 // trigger_spell_id = 41055;
6615 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6616 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6617 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6619 float stat = 0.0f;
6620 // strength
6621 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6622 // agility
6623 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6624 // intellect
6625 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6626 // spirit
6627 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
6629 else if (auraSpellInfo->Id==67702) // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
6631 float stat = 0.0f;
6632 // strength
6633 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
6634 // agility
6635 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
6637 else if (auraSpellInfo->Id==67771) // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
6639 float stat = 0.0f;
6640 // strength
6641 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
6642 // agility
6643 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
6645 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6646 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6647 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6648 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6649 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6650 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6651 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6652 trigger_spell_id = 33898;
6653 //else if (auraSpellInfo->Id==18943) // Double Attack
6654 //else if (auraSpellInfo->Id==19194) // Double Attack
6655 //else if (auraSpellInfo->Id==19817) // Double Attack
6656 //else if (auraSpellInfo->Id==19818) // Double Attack
6657 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6658 // trigger_spell_id = 14822;
6660 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6662 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6664 case 34191:
6665 case 34329:
6666 case 34524:
6667 case 34582:
6668 case 36733:
6669 break;
6670 default:
6671 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6672 return false;
6674 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6675 switch (procSpell->School)
6677 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6678 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6679 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6680 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6681 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6682 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6683 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6684 default:
6685 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6686 return false;
6690 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6691 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6692 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6693 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6694 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6695 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6696 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6697 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6698 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6699 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6700 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6701 //else if (auraSpellInfo->Id==40250) // Improved Duration
6702 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6703 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6704 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6705 // Mana Drain Trigger
6707 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6708 if (this && this->isAlive())
6709 CastSpell(this, 29471, true, castItem, triggeredByAura);
6710 if (pVictim && pVictim->isAlive())
6711 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6712 return true;
6714 //else if (auraSpellInfo->Id==55580) // Mana Link
6715 //else if (auraSpellInfo->Id==45903) // Offensive State
6716 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6717 //else if (auraSpellInfo->Id==43453) // Rune Ward
6718 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6719 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6720 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6721 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6722 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6723 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6724 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6725 //else if (auraSpellInfo->Id==35205) // Vanish
6726 //else if (auraSpellInfo->Id==42730) // Woe Strike
6727 //else if (auraSpellInfo->Id==59735) // Woe Strike
6728 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6729 break;
6730 case SPELLFAMILY_MAGE:
6731 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6733 switch (auraSpellInfo->Id)
6735 case 31641: // Rank 1
6736 case 31642: // Rank 2
6737 trigger_spell_id = 31643;
6738 break;
6739 default:
6740 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6741 return false;
6744 break;
6745 case SPELLFAMILY_WARRIOR:
6746 if (auraSpellInfo->Id == 50421) // Scent of Blood
6747 trigger_spell_id = 50422;
6748 break;
6749 case SPELLFAMILY_WARLOCK:
6751 // Pyroclasm
6752 if (auraSpellInfo->SpellIconID == 1137)
6754 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6755 return false;
6756 // Calculate spell tick count for spells
6757 uint32 tick = 1; // Default tick = 1
6759 // Hellfire have 15 tick
6760 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000040))
6761 tick = 15;
6762 // Rain of Fire have 4 tick
6763 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020))
6764 tick = 4;
6765 else
6766 return false;
6768 // Calculate chance = baseChance / tick
6769 float chance = 0;
6770 switch (auraSpellInfo->Id)
6772 case 18096: chance = 13.0f / tick; break;
6773 case 18073: chance = 26.0f / tick; break;
6775 // Roll chance
6776 if (!roll_chance_f(chance))
6777 return false;
6779 trigger_spell_id = 18093;
6781 // Drain Soul
6782 else if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000))
6784 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6785 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6787 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6789 // Drain Soul
6790 CastCustomSpell(this, 18371, &basepoints[0], NULL, NULL, true, castItem, triggeredByAura);
6791 break;
6794 // Not remove charge (aura removed on death in any cases)
6795 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6796 return false;
6798 // Nether Protection
6799 else if (auraSpellInfo->SpellIconID == 1985)
6801 if (!procSpell)
6802 return false;
6803 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6805 case SPELL_SCHOOL_NORMAL:
6806 return false; // ignore
6807 case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
6808 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6809 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6810 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6811 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6812 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6813 default:
6814 return false;
6817 break;
6819 case SPELLFAMILY_PRIEST:
6821 // Greater Heal Refund
6822 if (auraSpellInfo->Id==37594)
6823 trigger_spell_id = 37595;
6824 // Blessed Recovery
6825 else if (auraSpellInfo->SpellIconID == 1875)
6827 switch (auraSpellInfo->Id)
6829 case 27811: trigger_spell_id = 27813; break;
6830 case 27815: trigger_spell_id = 27817; break;
6831 case 27816: trigger_spell_id = 27818; break;
6832 default:
6833 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6834 return false;
6836 basepoints[0] = damage * triggerAmount / 100 / 3;
6837 target = this;
6839 break;
6841 case SPELLFAMILY_DRUID:
6843 // Druid Forms Trinket
6844 if (auraSpellInfo->Id==37336)
6846 switch(m_form)
6848 case FORM_NONE: trigger_spell_id = 37344;break;
6849 case FORM_CAT: trigger_spell_id = 37341;break;
6850 case FORM_BEAR:
6851 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6852 case FORM_TREE: trigger_spell_id = 37342;break;
6853 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6854 default:
6855 return false;
6858 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6859 // trigger_spell_id = ????;
6860 // Leader of the Pack
6861 else if (auraSpellInfo->Id == 24932)
6863 if (triggerAmount == 0)
6864 return false;
6865 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
6866 trigger_spell_id = 34299;
6868 break;
6870 case SPELLFAMILY_HUNTER:
6871 // Piercing Shots
6872 if (auraSpellInfo->SpellIconID == 3247 && auraSpellInfo->SpellVisual[0] == 0)
6874 basepoints[0] = damage * triggerAmount / 100 / 8;
6875 trigger_spell_id = 63468;
6876 target = pVictim;
6878 break;
6879 case SPELLFAMILY_PALADIN:
6882 // Blessed Life
6883 if (auraSpellInfo->SpellIconID == 2137)
6885 switch (auraSpellInfo->Id)
6887 case 31828: // Rank 1
6888 case 31829: // Rank 2
6889 case 31830: // Rank 3
6890 break;
6891 default:
6892 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6893 return false;
6897 // Healing Discount
6898 if (auraSpellInfo->Id==37705)
6900 trigger_spell_id = 37706;
6901 target = this;
6903 // Soul Preserver
6904 if (auraSpellInfo->Id==60510)
6906 trigger_spell_id = 60515;
6907 target = this;
6909 // Illumination
6910 else if (auraSpellInfo->SpellIconID==241)
6912 if(!procSpell)
6913 return false;
6914 // procspell is triggered spell but we need mana cost of original casted spell
6915 uint32 originalSpellId = procSpell->Id;
6916 // Holy Shock heal
6917 if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000))
6919 switch(procSpell->Id)
6921 case 25914: originalSpellId = 20473; break;
6922 case 25913: originalSpellId = 20929; break;
6923 case 25903: originalSpellId = 20930; break;
6924 case 27175: originalSpellId = 27174; break;
6925 case 33074: originalSpellId = 33072; break;
6926 case 48820: originalSpellId = 48824; break;
6927 case 48821: originalSpellId = 48825; break;
6928 default:
6929 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6930 return false;
6933 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6934 if(!originalSpell)
6936 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6937 return false;
6939 // percent stored in effect 1 (class scripts) base points
6940 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6941 basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6942 trigger_spell_id = 20272;
6943 target = this;
6945 // Lightning Capacitor
6946 else if (auraSpellInfo->Id==37657)
6948 if(!pVictim || !pVictim->isAlive())
6949 return false;
6950 // stacking
6951 CastSpell(this, 37658, true, NULL, triggeredByAura);
6953 Aura * dummy = GetDummyAura(37658);
6954 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6955 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6956 return false;
6958 RemoveAurasDueToSpell(37658);
6959 trigger_spell_id = 37661;
6960 target = pVictim;
6962 // Thunder Capacitor
6963 else if (auraSpellInfo->Id == 54841)
6965 if(!pVictim || !pVictim->isAlive())
6966 return false;
6967 // stacking
6968 CastSpell(this, 54842, true, NULL, triggeredByAura);
6970 // counting
6971 Aura * dummy = GetDummyAura(54842);
6972 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6973 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6974 return false;
6976 RemoveAurasDueToSpell(54842);
6977 trigger_spell_id = 54843;
6978 target = pVictim;
6980 break;
6982 case SPELLFAMILY_SHAMAN:
6984 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6985 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400))
6987 switch(auraSpellInfo->Id)
6989 case 324: // Rank 1
6990 trigger_spell_id = 26364; break;
6991 case 325: // Rank 2
6992 trigger_spell_id = 26365; break;
6993 case 905: // Rank 3
6994 trigger_spell_id = 26366; break;
6995 case 945: // Rank 4
6996 trigger_spell_id = 26367; break;
6997 case 8134: // Rank 5
6998 trigger_spell_id = 26369; break;
6999 case 10431: // Rank 6
7000 trigger_spell_id = 26370; break;
7001 case 10432: // Rank 7
7002 trigger_spell_id = 26363; break;
7003 case 25469: // Rank 8
7004 trigger_spell_id = 26371; break;
7005 case 25472: // Rank 9
7006 trigger_spell_id = 26372; break;
7007 case 49280: // Rank 10
7008 trigger_spell_id = 49278; break;
7009 case 49281: // Rank 11
7010 trigger_spell_id = 49279; break;
7011 default:
7012 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
7013 return false;
7016 // Lightning Shield (The Ten Storms set)
7017 else if (auraSpellInfo->Id == 23551)
7019 trigger_spell_id = 23552;
7020 target = pVictim;
7022 // Damage from Lightning Shield (The Ten Storms set)
7023 else if (auraSpellInfo->Id == 23552)
7024 trigger_spell_id = 27635;
7025 // Mana Surge (The Earthfury set)
7026 else if (auraSpellInfo->Id == 23572)
7028 if(!procSpell)
7029 return false;
7030 basepoints[0] = procSpell->manaCost * 35 / 100;
7031 trigger_spell_id = 23571;
7032 target = this;
7034 // Nature's Guardian
7035 else if (auraSpellInfo->SpellIconID == 2013)
7037 // Check health condition - should drop to less 30% (damage deal after this!)
7038 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
7039 return false;
7041 if(pVictim && pVictim->isAlive())
7042 pVictim->getThreatManager().modifyThreatPercent(this,-10);
7044 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
7045 trigger_spell_id = 31616;
7046 target = this;
7048 break;
7050 case SPELLFAMILY_DEATHKNIGHT:
7052 // Acclimation
7053 if (auraSpellInfo->SpellIconID == 1930)
7055 if (!procSpell)
7056 return false;
7057 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7059 case SPELL_SCHOOL_NORMAL:
7060 return false; // ignore
7061 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
7062 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
7063 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
7064 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
7065 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
7066 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
7067 default:
7068 return false;
7071 // Blood Presence
7072 else if (auraSpellInfo->Id == 48266)
7074 if (GetTypeId() != TYPEID_PLAYER)
7075 return false;
7076 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
7077 return false;
7078 trigger_spell_id = 50475;
7079 basepoints[0] = damage * triggerAmount / 100;
7081 break;
7083 default:
7084 break;
7088 // All ok. Check current trigger spell
7089 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
7090 if ( triggerEntry == NULL )
7092 // Not cast unknown spell
7093 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
7094 return false;
7097 // not allow proc extra attack spell at extra attack
7098 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7099 return false;
7101 // Custom requirements (not listed in procEx) Warning! damage dealing after this
7102 // Custom triggered spells
7103 switch (auraSpellInfo->Id)
7105 // Persistent Shield (Scarab Brooch trinket)
7106 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
7107 case 26467:
7109 basepoints[0] = damage * 15 / 100;
7110 target = pVictim;
7111 trigger_spell_id = 26470;
7112 break;
7114 // Cheat Death
7115 case 28845:
7117 // When your health drops below 20% ....
7118 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
7119 return false;
7120 break;
7122 // Deadly Swiftness (Rank 1)
7123 case 31255:
7125 // whenever you deal damage to a target who is below 20% health.
7126 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
7127 return false;
7129 target = this;
7130 trigger_spell_id = 22588;
7132 // Greater Heal Refund (Avatar Raiment set)
7133 case 37594:
7135 // Not give if target already have full health
7136 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
7137 return false;
7138 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
7139 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
7140 return false;
7141 break;
7143 // Bonus Healing (Crystal Spire of Karabor mace)
7144 case 40971:
7146 // If your target is below $s1% health
7147 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
7148 return false;
7149 break;
7151 // Evasive Maneuvers (Commendation of Kael`thas trinket)
7152 case 45057:
7154 // reduce you below $s1% health
7155 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
7156 return false;
7157 break;
7159 // Rapid Recuperation
7160 case 53228:
7161 case 53232:
7163 // This effect only from Rapid Fire (ability cast)
7164 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020)))
7165 return false;
7166 break;
7168 // Decimation
7169 case 63156:
7170 case 63158:
7172 // Looking for dummy effect
7173 Aura *aur = GetAura(auraSpellInfo->Id, 1);
7174 if (!aur)
7175 return false;
7177 // If target's health is not below equal certain value (35%) not proc
7178 if ((pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount)
7179 return false;
7181 break;
7184 // Blade Barrier
7185 if (auraSpellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && auraSpellInfo->SpellIconID == 85)
7187 if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT ||
7188 !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
7189 return false;
7192 // Custom basepoints/target for exist spell
7193 // dummy basepoints or other customs
7194 switch(trigger_spell_id)
7196 // Cast positive spell on enemy target
7197 case 7099: // Curse of Mending
7198 case 39647: // Curse of Mending
7199 case 29494: // Temptation
7200 case 20233: // Improved Lay on Hands (cast on target)
7202 target = pVictim;
7203 break;
7205 // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
7206 case 15250: // Rogue Setup
7208 if(!pVictim || pVictim != getVictim()) // applied only for main target
7209 return false;
7210 break; // continue normal case
7212 // Finish movies that add combo
7213 case 14189: // Seal Fate (Netherblade set)
7214 case 14157: // Ruthlessness
7216 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
7217 break;
7219 // Bloodthirst (($m/100)% of max health)
7220 case 23880:
7222 basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100);
7223 break;
7225 // Shamanistic Rage triggered spell
7226 case 30824:
7228 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7229 break;
7231 // Enlightenment (trigger only from mana cost spells)
7232 case 35095:
7234 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
7235 return false;
7236 break;
7238 // Demonic Pact
7239 case 48090:
7241 // As the spell is proced from pet's attack - find owner
7242 Unit* owner = GetOwner();
7243 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
7244 return false;
7246 // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later.
7247 int32 curBonus = 0;
7248 if (Aura* aur = owner->GetAura(48090,0))
7249 curBonus = aur->GetModifier()->m_amount;
7250 int32 spellDamage = owner->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_MAGIC) - curBonus;
7251 if(spellDamage <= 0)
7252 return false;
7254 // percent stored in owner talent dummy
7255 AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
7256 for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
7258 if ((*i)->GetSpellProto()->SpellIconID == 3220)
7260 basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100);
7261 break;
7264 break;
7266 // Sword and Board
7267 case 50227:
7269 // Remove cooldown on Shield Slam
7270 if (GetTypeId() == TYPEID_PLAYER)
7271 ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
7272 break;
7274 // Maelstrom Weapon
7275 case 53817:
7277 // have rank dependent proc chance, ignore too often cases
7278 // PPM = 2.5 * (rank of talent),
7279 uint32 rank = sSpellMgr.GetSpellRank(auraSpellInfo->Id);
7280 // 5 rank -> 100% 4 rank -> 80% and etc from full rate
7281 if(!roll_chance_i(20*rank))
7282 return false;
7283 break;
7285 // Brain Freeze
7286 case 57761:
7288 if(!procSpell)
7289 return false;
7290 // For trigger from Blizzard need exist Improved Blizzard
7291 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)))
7293 bool found = false;
7294 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7295 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7297 int32 script = (*i)->GetModifier()->m_miscvalue;
7298 if(script==836 || script==988 || script==989)
7300 found=true;
7301 break;
7304 if(!found)
7305 return false;
7307 break;
7309 // Astral Shift
7310 case 52179:
7312 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7313 return false;
7315 // Need stun, fear or silence mechanic
7316 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_SILENCE_AND_STUN_AND_FEAR_MASK))
7317 return false;
7318 break;
7320 // Burning Determination
7321 case 54748:
7323 if(!procSpell)
7324 return false;
7325 // Need Interrupt or Silenced mechanic
7326 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_INTERRUPT_AND_SILENCE_MASK))
7327 return false;
7328 break;
7330 // Lock and Load
7331 case 56453:
7333 // Proc only from trap activation (from periodic proc another aura of this spell)
7334 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
7335 return false;
7336 break;
7338 // Druid - Savage Defense
7339 case 62606:
7341 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7342 break;
7346 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
7347 return false;
7349 // try detect target manually if not set
7350 if ( target == NULL )
7351 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
7353 // default case
7354 if(!target || target!=this && !target->isAlive())
7355 return false;
7357 if(basepoints[0] || basepoints[1] || basepoints[2])
7358 CastCustomSpell(target,trigger_spell_id,
7359 basepoints[0] ? &basepoints[0] : NULL,
7360 basepoints[1] ? &basepoints[1] : NULL,
7361 basepoints[2] ? &basepoints[2] : NULL,
7362 true,castItem,triggeredByAura);
7363 else
7364 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
7366 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7367 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
7369 return true;
7372 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
7374 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
7376 if(!pVictim || !pVictim->isAlive())
7377 return false;
7379 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7380 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7382 uint32 triggered_spell_id = 0;
7384 switch(scriptId)
7386 case 836: // Improved Blizzard (Rank 1)
7388 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7389 return false;
7390 triggered_spell_id = 12484;
7391 break;
7393 case 988: // Improved Blizzard (Rank 2)
7395 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7396 return false;
7397 triggered_spell_id = 12485;
7398 break;
7400 case 989: // Improved Blizzard (Rank 3)
7402 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7403 return false;
7404 triggered_spell_id = 12486;
7405 break;
7407 case 4086: // Improved Mend Pet (Rank 1)
7408 case 4087: // Improved Mend Pet (Rank 2)
7410 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
7411 if(!roll_chance_i(chance))
7412 return false;
7414 triggered_spell_id = 24406;
7415 break;
7417 case 4533: // Dreamwalker Raiment 2 pieces bonus
7419 // Chance 50%
7420 if (!roll_chance_i(50))
7421 return false;
7423 switch (pVictim->getPowerType())
7425 case POWER_MANA: triggered_spell_id = 28722; break;
7426 case POWER_RAGE: triggered_spell_id = 28723; break;
7427 case POWER_ENERGY: triggered_spell_id = 28724; break;
7428 default:
7429 return false;
7431 break;
7433 case 4537: // Dreamwalker Raiment 6 pieces bonus
7434 triggered_spell_id = 28750; // Blessing of the Claw
7435 break;
7436 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
7437 triggered_spell_id = 37445; // Mana Surge
7438 break;
7439 case 8152: // Serendipity
7441 // if heal your target over maximum health
7442 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
7443 return false;
7444 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
7445 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
7446 CastCustomSpell(this, 47762, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
7447 return true;
7451 // not processed
7452 if(!triggered_spell_id)
7453 return false;
7455 // standard non-dummy case
7456 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
7458 if(!triggerEntry)
7460 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
7461 return false;
7464 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
7465 return false;
7467 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
7469 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7470 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
7472 return true;
7475 void Unit::setPowerType(Powers new_powertype)
7477 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
7479 if(GetTypeId() == TYPEID_PLAYER)
7481 if(((Player*)this)->GetGroup())
7482 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
7484 else if(((Creature*)this)->isPet())
7486 Pet *pet = ((Pet*)this);
7487 if(pet->isControlled())
7489 Unit *owner = GetOwner();
7490 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
7491 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
7495 switch(new_powertype)
7497 default:
7498 case POWER_MANA:
7499 break;
7500 case POWER_RAGE:
7501 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
7502 SetPower( POWER_RAGE,0);
7503 break;
7504 case POWER_FOCUS:
7505 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
7506 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
7507 break;
7508 case POWER_ENERGY:
7509 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
7510 SetPower( POWER_ENERGY,0);
7511 break;
7512 case POWER_HAPPINESS:
7513 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
7514 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
7515 break;
7519 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
7521 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
7522 if(!entry)
7524 static uint64 guid = 0; // prevent repeating spam same faction problem
7526 if(GetGUID() != guid)
7528 if(GetTypeId() == TYPEID_PLAYER)
7529 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
7530 else
7531 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
7532 guid = GetGUID();
7535 return entry;
7538 bool Unit::IsHostileTo(Unit const* unit) const
7540 // always non-hostile to self
7541 if(unit==this)
7542 return false;
7544 // always non-hostile to GM in GM mode
7545 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7546 return false;
7548 // always hostile to enemy
7549 if(getVictim()==unit || unit->getVictim()==this)
7550 return true;
7552 // test pet/charm masters instead pers/charmeds
7553 Unit const* testerOwner = GetCharmerOrOwner();
7554 Unit const* targetOwner = unit->GetCharmerOrOwner();
7556 // always hostile to owner's enemy
7557 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7558 return true;
7560 // always hostile to enemy owner
7561 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7562 return true;
7564 // always hostile to owner of owner's enemy
7565 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7566 return true;
7568 Unit const* tester = testerOwner ? testerOwner : this;
7569 Unit const* target = targetOwner ? targetOwner : unit;
7571 // always non-hostile to target with common owner, or to owner/pet
7572 if(tester==target)
7573 return false;
7575 // special cases (Duel, etc)
7576 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7578 Player const* pTester = (Player const*)tester;
7579 Player const* pTarget = (Player const*)target;
7581 // Duel
7582 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
7583 return true;
7585 // Group
7586 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7587 return false;
7589 // Sanctuary
7590 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7591 return false;
7593 // PvP FFA state
7594 if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
7595 return true;
7597 //= PvP states
7598 // Green/Blue (can't attack)
7599 if(pTester->GetTeam()==pTarget->GetTeam())
7600 return false;
7602 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
7603 return pTester->IsPvP() && pTarget->IsPvP();
7606 // faction base cases
7607 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7608 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7609 if(!tester_faction || !target_faction)
7610 return false;
7612 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7613 return true;
7615 // PvC forced reaction and reputation case
7616 if(tester->GetTypeId()==TYPEID_PLAYER)
7618 // forced reaction
7619 if(target_faction->faction)
7621 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7622 return *force <= REP_HOSTILE;
7624 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
7625 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7626 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7627 return (factionState->Flags & FACTION_FLAG_AT_WAR);
7630 // CvP forced reaction and reputation case
7631 else if(target->GetTypeId()==TYPEID_PLAYER)
7633 // forced reaction
7634 if(tester_faction->faction)
7636 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7637 return *force <= REP_HOSTILE;
7639 // apply reputation state
7640 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
7641 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
7642 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
7646 // common faction based case (CvC,PvC,CvP)
7647 return tester_faction->IsHostileTo(*target_faction);
7650 bool Unit::IsFriendlyTo(Unit const* unit) const
7652 // always friendly to self
7653 if(unit==this)
7654 return true;
7656 // always friendly to GM in GM mode
7657 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7658 return true;
7660 // always non-friendly to enemy
7661 if(getVictim()==unit || unit->getVictim()==this)
7662 return false;
7664 // test pet/charm masters instead pers/charmeds
7665 Unit const* testerOwner = GetCharmerOrOwner();
7666 Unit const* targetOwner = unit->GetCharmerOrOwner();
7668 // always non-friendly to owner's enemy
7669 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7670 return false;
7672 // always non-friendly to enemy owner
7673 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7674 return false;
7676 // always non-friendly to owner of owner's enemy
7677 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7678 return false;
7680 Unit const* tester = testerOwner ? testerOwner : this;
7681 Unit const* target = targetOwner ? targetOwner : unit;
7683 // always friendly to target with common owner, or to owner/pet
7684 if(tester==target)
7685 return true;
7687 // special cases (Duel)
7688 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7690 Player const* pTester = (Player const*)tester;
7691 Player const* pTarget = (Player const*)target;
7693 // Duel
7694 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7695 return false;
7697 // Group
7698 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7699 return true;
7701 // Sanctuary
7702 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7703 return true;
7705 // PvP FFA state
7706 if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
7707 return false;
7709 //= PvP states
7710 // Green/Blue (non-attackable)
7711 if(pTester->GetTeam()==pTarget->GetTeam())
7712 return true;
7714 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7715 return !pTarget->IsPvP();
7718 // faction base cases
7719 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7720 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7721 if(!tester_faction || !target_faction)
7722 return false;
7724 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7725 return false;
7727 // PvC forced reaction and reputation case
7728 if(tester->GetTypeId()==TYPEID_PLAYER)
7730 // forced reaction
7731 if(target_faction->faction)
7733 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7734 return *force >= REP_FRIENDLY;
7736 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7737 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7738 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7739 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7742 // CvP forced reaction and reputation case
7743 else if(target->GetTypeId()==TYPEID_PLAYER)
7745 // forced reaction
7746 if(tester_faction->faction)
7748 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7749 return *force >= REP_FRIENDLY;
7751 // apply reputation state
7752 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7753 if(raw_tester_faction->reputationListID >=0 )
7754 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7758 // common faction based case (CvC,PvC,CvP)
7759 return tester_faction->IsFriendlyTo(*target_faction);
7762 bool Unit::IsHostileToPlayers() const
7764 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7765 if(!my_faction || !my_faction->faction)
7766 return false;
7768 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7769 if(raw_faction && raw_faction->reputationListID >=0 )
7770 return false;
7772 return my_faction->IsHostileToPlayers();
7775 bool Unit::IsNeutralToAll() const
7777 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7778 if(!my_faction || !my_faction->faction)
7779 return true;
7781 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7782 if(raw_faction && raw_faction->reputationListID >=0 )
7783 return false;
7785 return my_faction->IsNeutralToAll();
7788 bool Unit::Attack(Unit *victim, bool meleeAttack)
7790 if(!victim || victim == this)
7791 return false;
7793 // dead units can neither attack nor be attacked
7794 if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
7795 return false;
7797 // player cannot attack in mount state
7798 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7799 return false;
7801 // nobody can attack GM in GM-mode
7802 if(victim->GetTypeId()==TYPEID_PLAYER)
7804 if(((Player*)victim)->isGameMaster())
7805 return false;
7807 else
7809 if(((Creature*)victim)->IsInEvadeMode())
7810 return false;
7813 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7814 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7815 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7817 // in fighting already
7818 if (m_attacking)
7820 if (m_attacking == victim)
7822 // switch to melee attack from ranged/magic
7823 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7825 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7826 SendMeleeAttackStart(victim);
7827 return true;
7829 return false;
7832 // remove old target data
7833 AttackStop(true);
7835 // new battle
7836 else
7838 // set position before any AI calls/assistance
7839 if(GetTypeId()==TYPEID_UNIT)
7840 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7843 // Set our target
7844 SetTargetGUID(victim->GetGUID());
7846 if(meleeAttack)
7847 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7849 m_attacking = victim;
7850 m_attacking->_addAttacker(this);
7852 if (GetTypeId() == TYPEID_UNIT)
7854 ((Creature*)this)->SendAIReaction(AI_REACTION_AGGRO);
7855 ((Creature*)this)->CallAssistance();
7858 // delay offhand weapon attack to next attack time
7859 if(haveOffhandWeapon())
7860 resetAttackTimer(OFF_ATTACK);
7862 if(meleeAttack)
7863 SendMeleeAttackStart(victim);
7865 return true;
7868 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7870 if (!m_attacking)
7871 return false;
7873 Unit* victim = m_attacking;
7875 m_attacking->_removeAttacker(this);
7876 m_attacking = NULL;
7878 // Clear our target
7879 SetTargetGUID(0);
7881 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7883 InterruptSpell(CURRENT_MELEE_SPELL);
7885 // reset only at real combat stop
7886 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7888 ((Creature*)this)->SetNoCallAssistance(false);
7889 ((Creature*)this)->SetNoSearchAssistance(false);
7892 SendMeleeAttackStop(victim);
7894 return true;
7897 void Unit::CombatStop(bool includingCast)
7899 if (includingCast && IsNonMeleeSpellCasted(false))
7900 InterruptNonMeleeSpells(false);
7902 AttackStop();
7903 RemoveAllAttackers();
7904 if( GetTypeId()==TYPEID_PLAYER )
7905 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7906 ClearInCombat();
7909 void Unit::CombatStopWithPets(bool includingCast)
7911 CombatStop(includingCast);
7912 if(Pet* pet = GetPet())
7913 pet->CombatStop(includingCast);
7914 if(Unit* charm = GetCharm())
7915 charm->CombatStop(includingCast);
7917 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
7918 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7919 guardian->CombatStop(includingCast);
7922 bool Unit::isAttackingPlayer() const
7924 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7925 return true;
7927 Pet* pet = GetPet();
7928 if(pet && pet->isAttackingPlayer())
7929 return true;
7931 Unit* charmed = GetCharm();
7932 if(charmed && charmed->isAttackingPlayer())
7933 return true;
7935 for (int8 i = 0; i < MAX_TOTEM; ++i)
7937 if(m_TotemSlot[i])
7939 Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]);
7940 if(totem && totem->isAttackingPlayer())
7941 return true;
7945 return false;
7948 void Unit::RemoveAllAttackers()
7950 while (!m_attackers.empty())
7952 AttackerSet::iterator iter = m_attackers.begin();
7953 if(!(*iter)->AttackStop())
7955 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7956 m_attackers.erase(iter);
7961 bool Unit::HasAuraStateForCaster(AuraState flag, uint64 caster) const
7963 if(!HasAuraState(flag))
7964 return false;
7966 // single per-caster aura state
7967 if(flag == AURA_STATE_CONFLAGRATE)
7969 Unit::AuraList const& dotList = GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
7970 for(Unit::AuraList::const_iterator i = dotList.begin(); i != dotList.end(); ++i)
7972 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK &&
7973 (*i)->GetCasterGUID() == caster &&
7974 // Immolate
7975 (((*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000004)) ||
7976 // Shadowflame
7977 ((*i)->GetSpellProto()->SpellFamilyFlags2 & 0x00000002)))
7979 return true;
7983 return false;
7986 return true;
7989 void Unit::ModifyAuraState(AuraState flag, bool apply)
7991 if (apply)
7993 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7995 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7996 if(GetTypeId() == TYPEID_PLAYER)
7998 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7999 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
8001 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
8002 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
8003 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
8004 if (spellInfo->CasterAuraState == flag)
8005 CastSpell(this, itr->first, true, NULL);
8010 else
8012 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
8014 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8016 if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
8018 Unit::AuraMap& tAuras = GetAuras();
8019 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
8021 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
8022 if (spellProto->CasterAuraState == flag)
8024 // exceptions (applied at state but not removed at state change)
8025 // Rampage
8026 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
8028 ++itr;
8029 continue;
8032 RemoveAura(itr);
8034 else
8035 ++itr;
8042 Unit *Unit::GetOwner() const
8044 if(uint64 ownerid = GetOwnerGUID())
8045 return ObjectAccessor::GetUnit(*this, ownerid);
8046 return NULL;
8049 Unit *Unit::GetCharmer() const
8051 if(uint64 charmerid = GetCharmerGUID())
8052 return ObjectAccessor::GetUnit(*this, charmerid);
8053 return NULL;
8056 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
8058 uint64 guid = GetCharmerOrOwnerGUID();
8059 if(IS_PLAYER_GUID(guid))
8060 return ObjectAccessor::FindPlayer(guid);
8062 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
8065 Pet* Unit::GetPet() const
8067 if(uint64 pet_guid = GetPetGUID())
8069 if(Pet* pet = GetMap()->GetPet(pet_guid))
8070 return pet;
8072 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
8073 const_cast<Unit*>(this)->SetPet(0);
8076 return NULL;
8079 Unit* Unit::GetCharm() const
8081 if (uint64 charm_guid = GetCharmGUID())
8083 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
8084 return pet;
8086 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
8087 const_cast<Unit*>(this)->SetCharm(NULL);
8090 return NULL;
8093 void Unit::Uncharm()
8095 if (Unit* charm = GetCharm())
8097 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
8098 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
8102 float Unit::GetCombatDistance( const Unit* target ) const
8104 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
8105 float dx = GetPositionX() - target->GetPositionX();
8106 float dy = GetPositionY() - target->GetPositionY();
8107 float dz = GetPositionZ() - target->GetPositionZ();
8108 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
8109 return ( dist > 0 ? dist : 0);
8112 void Unit::SetPet(Pet* pet)
8114 SetPetGUID(pet ? pet->GetGUID() : 0);
8116 // FIXME: hack, speed must be set only at follow
8117 if(pet && GetTypeId()==TYPEID_PLAYER)
8118 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
8119 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
8122 void Unit::SetCharm(Unit* pet)
8124 SetCharmGUID(pet ? pet->GetGUID() : 0);
8127 void Unit::AddGuardian( Pet* pet )
8129 m_guardianPets.insert(pet->GetGUID());
8132 void Unit::RemoveGuardian( Pet* pet )
8134 m_guardianPets.erase(pet->GetGUID());
8137 void Unit::RemoveGuardians()
8139 while(!m_guardianPets.empty())
8141 uint64 guid = *m_guardianPets.begin();
8142 if(Pet* pet = GetMap()->GetPet(guid))
8143 pet->Remove(PET_SAVE_AS_DELETED);
8145 m_guardianPets.erase(guid);
8149 Pet* Unit::FindGuardianWithEntry(uint32 entry)
8151 // pet guid middle part is entry (and creature also)
8152 // and in guardian list must be guardians with same entry _always_
8153 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
8154 if(Pet* pet = GetMap()->GetPet(*itr))
8155 if (pet->GetEntry() == entry)
8156 return pet;
8158 return NULL;
8161 void Unit::UnsummonAllTotems()
8163 for (int8 i = 0; i < MAX_TOTEM; ++i)
8165 if(!m_TotemSlot[i])
8166 continue;
8168 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
8169 if (OldTotem && OldTotem->isTotem())
8170 ((Totem*)OldTotem)->UnSummon();
8174 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
8176 int32 gain = pVictim->ModifyHealth(int32(addhealth));
8178 Unit* unit = this;
8180 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8181 unit = GetOwner();
8183 if (unit->GetTypeId()==TYPEID_PLAYER)
8185 // overheal = addhealth - gain
8186 unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
8188 if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
8189 bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
8191 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
8192 if (gain)
8193 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
8195 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
8198 if (pVictim->GetTypeId()==TYPEID_PLAYER)
8200 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
8201 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
8204 return gain;
8207 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
8209 if(!victim)
8210 return NULL;
8212 // Magic case
8213 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
8215 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
8216 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
8217 if(Unit* magnet = (*itr)->GetCaster())
8218 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
8219 return magnet;
8221 // Melee && ranged case
8222 else
8224 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
8225 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
8226 if(Unit* magnet = (*i)->GetCaster())
8227 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
8228 if(roll_chance_i((*i)->GetModifier()->m_amount))
8229 return magnet;
8232 return victim;
8235 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
8237 // we guess size
8238 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
8239 data.append(pVictim->GetPackGUID());
8240 data.append(GetPackGUID());
8241 data << uint32(SpellID);
8242 data << uint32(Damage);
8243 data << uint32(OverHeal);
8244 data << uint8(critical ? 1 : 0);
8245 data << uint8(0); // unused in client?
8246 SendMessageToSet(&data, true);
8249 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8251 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
8252 data.append(pVictim->GetPackGUID());
8253 data.append(GetPackGUID());
8254 data << uint32(SpellID);
8255 data << uint32(powertype);
8256 data << uint32(Damage);
8257 SendMessageToSet(&data, true);
8260 void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8262 SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
8263 // needs to be called after sending spell log
8264 pVictim->ModifyPower(powertype, Damage);
8267 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
8269 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
8270 return pdamage;
8272 // For totems get damage bonus from owner (statue isn't totem in fact)
8273 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8275 if(Unit* owner = GetOwner())
8276 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
8279 // Taken/Done total percent damage auras
8280 float DoneTotalMod = 1.0f;
8281 float TakenTotalMod = 1.0f;
8282 int32 DoneTotal = 0;
8283 int32 TakenTotal = 0;
8285 // ..done
8286 // Creature damage
8287 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
8288 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
8290 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
8291 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
8293 if (((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
8294 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
8295 // -1 == any item class (not wand then)
8296 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0)
8297 // 0 == any inventory type (not wand then)
8299 DoneTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8303 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8304 // Add flat bonus from spell damage versus
8305 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
8306 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8307 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8308 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8309 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8311 // done scripted mod (take it from owner)
8312 Unit *owner = GetOwner();
8313 if (!owner) owner = this;
8314 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8315 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8317 if (!(*i)->isAffectedOnSpell(spellProto))
8318 continue;
8319 switch((*i)->GetModifier()->m_miscvalue)
8321 case 4920: // Molten Fury
8322 case 4919:
8323 case 6917: // Death's Embrace
8324 case 6926:
8325 case 6928:
8327 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8328 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8329 break;
8331 // Soul Siphon
8332 case 4992:
8333 case 4993:
8335 // effect 1 m_amount
8336 int32 maxPercent = (*i)->GetModifier()->m_amount;
8337 // effect 0 m_amount
8338 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
8339 // count affliction effects and calc additional damage in percentage
8340 int32 modPercent = 0;
8341 AuraMap const& victimAuras = pVictim->GetAuras();
8342 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8344 SpellEntry const* m_spell = itr->second->GetSpellProto();
8345 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & UI64LIT(0x0004071B8044C402)))
8346 continue;
8347 modPercent += stepPercent * itr->second->GetStackAmount();
8348 if (modPercent >= maxPercent)
8350 modPercent = maxPercent;
8351 break;
8354 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8355 break;
8357 case 6916: // Death's Embrace
8358 case 6925:
8359 case 6927:
8360 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
8361 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8362 break;
8363 case 5481: // Starfire Bonus
8365 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x0000000000200002)))
8366 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8367 break;
8369 case 4418: // Increased Shock Damage
8370 case 4554: // Increased Lightning Damage
8371 case 4555: // Improved Moonfire
8372 case 5142: // Increased Lightning Damage
8373 case 5147: // Improved Consecration / Libram of Resurgence
8374 case 5148: // Idol of the Shooting Star
8375 case 6008: // Increased Lightning Damage / Totem of Hex
8377 DoneTotal+=(*i)->GetModifier()->m_amount;
8378 break;
8380 // Tundra Stalker
8381 // Merciless Combat
8382 case 7277:
8384 // Merciless Combat
8385 if ((*i)->GetSpellProto()->SpellIconID == 2656)
8387 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8388 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8390 else // Tundra Stalker
8392 // Frost Fever (target debuff)
8393 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
8394 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8395 break;
8397 break;
8399 case 7293: // Rage of Rivendare
8401 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
8402 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8403 break;
8405 // Twisted Faith
8406 case 7377:
8408 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000000000008000), 0, GetGUID()))
8409 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8410 break;
8412 // Marked for Death
8413 case 7598:
8414 case 7599:
8415 case 7600:
8416 case 7601:
8417 case 7602:
8419 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
8420 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8421 break;
8426 // Custom scripted damage
8427 switch(spellProto->SpellFamilyName)
8429 case SPELLFAMILY_MAGE:
8431 // Ice Lance
8432 if (spellProto->SpellIconID == 186)
8434 if (pVictim->isFrozen())
8436 float multiplier = 3.0f;
8438 // if target have higher level
8439 if (pVictim->getLevel() > getLevel())
8440 // Glyph of Ice Lance
8441 if (Aura* glyph = GetDummyAura(56377))
8442 multiplier = glyph->GetModifier()->m_amount;
8444 DoneTotalMod *= multiplier;
8447 // Torment the weak affected (Arcane Barrage, Arcane Blast, Frostfire Bolt, Arcane Missiles, Fireball)
8448 if ((spellProto->SpellFamilyFlags & UI64LIT(0x0000900020200021)) &&
8449 (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED) || pVictim->HasAuraType(SPELL_AURA_MELEE_SLOW)))
8451 //Search for Torment the weak dummy aura
8452 Unit::AuraList const& ttw = GetAurasByType(SPELL_AURA_DUMMY);
8453 for(Unit::AuraList::const_iterator i = ttw.begin(); i != ttw.end(); ++i)
8455 if ((*i)->GetSpellProto()->SpellIconID == 3263)
8457 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
8458 break;
8462 break;
8464 case SPELLFAMILY_WARLOCK:
8466 // Drain Soul
8467 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000004000))
8469 if (pVictim->GetHealth() * 100 / pVictim->GetMaxHealth() <= 25)
8470 DoneTotalMod *= 4;
8472 break;
8474 case SPELLFAMILY_DEATHKNIGHT:
8476 // Icy Touch, Howling Blast and Frost Strike
8477 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000600000002))
8479 // search disease
8480 bool found = false;
8481 Unit::AuraMap const& auras = pVictim->GetAuras();
8482 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
8484 if(itr->second->GetSpellProto()->Dispel == DISPEL_DISEASE)
8486 found = true;
8487 break;
8490 if(!found)
8491 break;
8493 // search for Glacier Rot dummy aura
8494 Unit::AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
8495 for(Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
8497 if ((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()] == 7244)
8499 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
8500 break;
8504 break;
8506 default:
8507 break;
8511 // ..taken
8512 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8513 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8515 if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto))
8516 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8519 // .. taken pct: dummy auras
8520 if (pVictim->GetTypeId() == TYPEID_PLAYER)
8522 //Cheat Death
8523 if (Aura *dummy = pVictim->GetDummyAura(45182))
8525 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
8526 if (mod < dummy->GetModifier()->m_amount)
8527 mod = dummy->GetModifier()->m_amount;
8528 TakenTotalMod *= (mod+100.0f)/100.0f;
8532 // From caster spells
8533 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
8534 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
8536 if ((*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
8537 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8540 // Mod damage from spell mechanic
8541 if (uint32 mechanicMask = GetAllSpellMechanicMask(spellProto))
8543 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
8544 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
8546 if (mechanicMask & uint32(1 << ((*i)->GetModifier()->m_miscvalue)))
8547 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8551 // Mod damage taken from AoE spells
8552 if(IsAreaOfEffectSpell(spellProto))
8554 AuraList const& avoidAuras = pVictim->GetAurasByType(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
8555 for(AuraList::const_iterator itr = avoidAuras.begin(); itr != avoidAuras.end(); ++itr)
8556 TakenTotalMod *= ((*itr)->GetModifier()->m_amount + 100.0f) / 100.0f;
8559 // Taken/Done fixed damage bonus auras
8560 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
8561 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8563 // Pets just add their bonus damage to their spell damage
8564 // note that their spell damage is just gain of their own auras
8565 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
8566 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
8568 float LvlPenalty = CalculateLevelPenalty(spellProto);
8569 // Spellmod SpellDamage
8570 float SpellModSpellDamage = 100.0f;
8571 if(Player* modOwner = GetSpellModOwner())
8572 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
8573 SpellModSpellDamage /= 100.0f;
8575 // Check for table values
8576 if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
8578 float coeff;
8579 if (damagetype == DOT)
8580 coeff = bonus->dot_damage * LvlPenalty * stack;
8581 else
8582 coeff = bonus->direct_damage * LvlPenalty * stack;
8584 if (bonus->ap_bonus)
8585 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8587 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8588 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8590 // Default calculation
8591 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8593 // Damage over Time spells bonus calculation
8594 float DotFactor = 1.0f;
8595 if (damagetype == DOT)
8597 if (!IsChanneledSpell(spellProto))
8598 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
8600 if (uint16 DotTicks = GetSpellAuraMaxTicks(spellProto))
8602 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8603 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8606 // Distribute Damage over multiple effects, reduce by AoE
8607 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8608 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8609 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8610 for(int j = 0; j < 3; ++j)
8612 if (spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8613 (spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA &&
8614 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH))
8616 CastingTime /= 2;
8617 break;
8620 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
8621 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
8624 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
8625 // apply spellmod to Done damage (flat and pct)
8626 if(Player* modOwner = GetSpellModOwner())
8627 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
8629 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
8631 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
8634 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
8636 int32 DoneAdvertisedBenefit = 0;
8638 // ..done
8639 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
8640 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
8642 if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
8643 (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then)
8644 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then)
8645 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8648 if (GetTypeId() == TYPEID_PLAYER)
8650 // Base value
8651 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
8653 // Damage bonus from stats
8654 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
8655 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
8657 if((*i)->GetModifier()->m_miscvalue & schoolMask)
8659 // stat used stored in miscValueB for this aura
8660 Stats usedStat = Stats((*i)->GetMiscBValue());
8661 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8664 // ... and attack power
8665 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
8666 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
8668 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8669 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8673 return DoneAdvertisedBenefit;
8676 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8678 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8680 int32 TakenAdvertisedBenefit = 0;
8681 // ..done (for creature type by mask) in taken
8682 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8683 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8685 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8686 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8689 // ..taken
8690 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8691 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8693 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8694 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8697 return TakenAdvertisedBenefit;
8700 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
8702 // not critting spell
8703 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
8704 return false;
8706 float crit_chance = 0.0f;
8707 switch(spellProto->DmgClass)
8709 case SPELL_DAMAGE_CLASS_NONE:
8710 return false;
8711 case SPELL_DAMAGE_CLASS_MAGIC:
8713 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
8714 crit_chance = 0.0f;
8715 // For other schools
8716 else if (GetTypeId() == TYPEID_PLAYER)
8717 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
8718 else
8720 crit_chance = m_baseSpellCritChance;
8721 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
8723 // taken
8724 if (pVictim)
8726 if (!IsPositiveSpell(spellProto->Id))
8728 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
8729 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
8730 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
8731 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
8732 // Modify by player victim resilience
8733 crit_chance -= pVictim->GetSpellCritChanceReduction();
8736 // scripted (increase crit chance ... against ... target by x%)
8737 // scripted (Increases the critical effect chance of your .... by x% on targets ...)
8738 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8739 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8741 if (!((*i)->isAffectedOnSpell(spellProto)))
8742 continue;
8743 switch((*i)->GetModifier()->m_miscvalue)
8745 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
8746 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
8747 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
8748 case 7917: // Glyph of Shadowburn
8749 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8750 crit_chance+=(*i)->GetModifier()->m_amount;
8751 break;
8752 case 7997: // Renewed Hope
8753 case 7998:
8754 if (pVictim->HasAura(6788))
8755 crit_chance+=(*i)->GetModifier()->m_amount;
8756 break;
8757 default:
8758 break;
8761 // Custom crit by class
8762 switch(spellProto->SpellFamilyName)
8764 case SPELLFAMILY_PRIEST:
8765 // Flash Heal
8766 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000800))
8768 if (pVictim->GetHealth() > pVictim->GetMaxHealth()/2)
8769 break;
8770 AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
8771 for(AuraList::const_iterator i = mDummyAuras.begin(); i!= mDummyAuras.end(); ++i)
8773 // Improved Flash Heal
8774 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST &&
8775 (*i)->GetSpellProto()->SpellIconID == 2542)
8777 crit_chance+=(*i)->GetModifier()->m_amount;
8778 break;
8782 break;
8783 case SPELLFAMILY_PALADIN:
8784 // Sacred Shield
8785 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000040000000))
8787 Aura *aura = pVictim->GetDummyAura(58597);
8788 if (aura && aura->GetCasterGUID() == GetGUID())
8789 crit_chance+=aura->GetModifier()->m_amount;
8791 // Exorcism
8792 else if (spellProto->Category == 19)
8794 if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
8795 return true;
8797 break;
8798 case SPELLFAMILY_SHAMAN:
8799 // Lava Burst
8800 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000100000000000))
8802 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID()))
8804 // Consume shock aura if not have Glyph of Flame Shock
8805 if (!GetAura(55447, 0))
8806 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
8807 return true;
8810 break;
8813 break;
8815 case SPELL_DAMAGE_CLASS_MELEE:
8817 // Judgement of Command proc always crits on stunned target
8818 if(spellProto->SpellFamilyName == SPELLFAMILY_PALADIN)
8820 if(spellProto->SpellFamilyFlags & 0x0000000000800000LL && spellProto->SpellIconID == 561)
8822 if(pVictim->hasUnitState(UNIT_STAT_STUNNED))
8823 return true;
8827 case SPELL_DAMAGE_CLASS_RANGED:
8829 if (pVictim)
8831 crit_chance = GetUnitCriticalChance(attackType, pVictim);
8832 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
8834 break;
8836 default:
8837 return false;
8839 // percent done
8840 // only players use intelligence for critical chance computations
8841 if(Player* modOwner = GetSpellModOwner())
8842 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
8844 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
8845 if (roll_chance_f(crit_chance))
8846 return true;
8847 return false;
8850 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8852 // Calculate critical bonus
8853 int32 crit_bonus;
8854 switch(spellProto->DmgClass)
8856 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8857 case SPELL_DAMAGE_CLASS_RANGED:
8858 crit_bonus = damage;
8859 break;
8860 default:
8861 crit_bonus = damage / 2; // for spells is 50%
8862 break;
8865 // adds additional damage to crit_bonus (from talents)
8866 if(Player* modOwner = GetSpellModOwner())
8867 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
8869 if(!pVictim)
8870 return damage += crit_bonus;
8872 int32 critPctDamageMod = 0;
8873 if(spellProto->DmgClass >= SPELL_DAMAGE_CLASS_MELEE)
8875 if(GetWeaponAttackType(spellProto) == RANGED_ATTACK)
8876 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
8877 else
8879 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
8880 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
8883 else
8884 critPctDamageMod += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE,GetSpellSchoolMask(spellProto));
8886 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8887 critPctDamageMod += GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask);
8889 if(critPctDamageMod!=0)
8890 crit_bonus = int32(crit_bonus * float((100.0f + critPctDamageMod)/100.0f));
8892 if(crit_bonus > 0)
8893 damage += crit_bonus;
8895 return damage;
8898 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8900 // Calculate critical bonus
8901 int32 crit_bonus;
8902 switch(spellProto->DmgClass)
8904 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8905 case SPELL_DAMAGE_CLASS_RANGED:
8906 // TODO: write here full calculation for melee/ranged spells
8907 crit_bonus = damage;
8908 break;
8909 default:
8910 crit_bonus = damage / 2; // for spells is 50%
8911 break;
8914 if(pVictim)
8916 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8917 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8920 if(crit_bonus > 0)
8921 damage += crit_bonus;
8923 damage = int32(damage * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
8925 return damage;
8928 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
8930 // No heal amount for this class spells
8931 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
8932 return healamount;
8934 // For totems get healing bonus from owner (statue isn't totem in fact)
8935 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8936 if(Unit* owner = GetOwner())
8937 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
8939 // Healing Done
8940 // Taken/Done total percent damage auras
8941 float DoneTotalMod = 1.0f;
8942 float TakenTotalMod = 1.0f;
8943 int32 DoneTotal = 0;
8944 int32 TakenTotal = 0;
8946 // Healing done percent
8947 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8948 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8949 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8951 // done scripted mod (take it from owner)
8952 Unit *owner = GetOwner();
8953 if (!owner) owner = this;
8954 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8955 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8957 if (!(*i)->isAffectedOnSpell(spellProto))
8958 continue;
8959 switch((*i)->GetModifier()->m_miscvalue)
8961 case 4415: // Increased Rejuvenation Healing
8962 case 4953:
8963 case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind
8964 DoneTotal+=(*i)->GetModifier()->m_amount;
8965 break;
8966 case 7997: // Renewed Hope
8967 case 7998:
8968 if (pVictim->HasAura(6788))
8969 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8970 break;
8971 case 21: // Test of Faith
8972 case 6935:
8973 case 6918:
8974 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8975 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8976 break;
8977 case 7798: // Glyph of Regrowth
8979 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, UI64LIT(0x0000000000000040)))
8980 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8981 break;
8983 case 8477: // Nourish Heal Boost
8985 int32 stepPercent = (*i)->GetModifier()->m_amount;
8986 int32 modPercent = 0;
8987 AuraMap const& victimAuras = pVictim->GetAuras();
8988 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8990 if (itr->second->GetCasterGUID()!=GetGUID())
8991 continue;
8992 SpellEntry const* m_spell = itr->second->GetSpellProto();
8993 if (m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8994 !(m_spell->SpellFamilyFlags & UI64LIT(0x0000001000000050)))
8995 continue;
8996 modPercent += stepPercent * itr->second->GetStackAmount();
8998 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8999 break;
9001 case 7871: // Glyph of Lesser Healing Wave
9003 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, UI64LIT(0x0000040000000000), 0, GetGUID()))
9004 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9005 break;
9007 default:
9008 break;
9012 // Taken/Done fixed damage bonus auras
9013 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
9014 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
9016 float LvlPenalty = CalculateLevelPenalty(spellProto);
9017 // Spellmod SpellDamage
9018 float SpellModSpellDamage = 100.0f;
9019 if(Player* modOwner = GetSpellModOwner())
9020 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
9021 SpellModSpellDamage /= 100.0f;
9023 // Check for table values
9024 SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id);
9025 if (bonus)
9027 float coeff;
9028 if (damagetype == DOT)
9029 coeff = bonus->dot_damage * LvlPenalty * stack;
9030 else
9031 coeff = bonus->direct_damage * LvlPenalty * stack;
9033 if (bonus->ap_bonus)
9034 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
9036 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
9037 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
9039 // Default calculation
9040 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
9042 // Damage over Time spells bonus calculation
9043 float DotFactor = 1.0f;
9044 if(damagetype == DOT)
9046 if(!IsChanneledSpell(spellProto))
9047 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
9048 uint16 DotTicks = GetSpellAuraMaxTicks(spellProto);
9049 if(DotTicks)
9051 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
9052 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
9055 // Distribute Damage over multiple effects, reduce by AoE
9056 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
9057 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
9058 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
9059 for(int j = 0; j < 3; ++j)
9061 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
9062 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
9064 CastingTime /= 2;
9065 break;
9068 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
9069 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
9072 // use float as more appropriate for negative values and percent applying
9073 float heal = (healamount + DoneTotal)*DoneTotalMod;
9074 // apply spellmod to Done amount
9075 if(Player* modOwner = GetSpellModOwner())
9076 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
9078 // Taken mods
9079 // Healing Wave cast
9080 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000040)))
9082 // Search for Healing Way on Victim
9083 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
9084 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
9085 if((*itr)->GetId() == 29203)
9086 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
9089 // Healing taken percent
9090 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
9091 if(minval)
9092 TakenTotalMod *= (100.0f + minval) / 100.0f;
9094 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
9095 if(maxval)
9096 TakenTotalMod *= (100.0f + maxval) / 100.0f;
9098 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
9099 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
9100 if ((*i)->isAffectedOnSpell(spellProto))
9101 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9103 heal = (heal + TakenTotal) * TakenTotalMod;
9105 return heal < 0 ? 0 : uint32(heal);
9108 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
9110 int32 AdvertisedBenefit = 0;
9112 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
9113 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
9114 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
9115 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9117 // Healing bonus of spirit, intellect and strength
9118 if (GetTypeId() == TYPEID_PLAYER)
9120 // Base value
9121 AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
9123 // Healing bonus from stats
9124 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
9125 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
9127 // stat used dependent from misc value (stat index)
9128 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
9129 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
9132 // ... and attack power
9133 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
9134 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
9135 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9136 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
9138 return AdvertisedBenefit;
9141 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
9143 int32 AdvertisedBenefit = 0;
9144 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
9145 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9146 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9147 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9149 return AdvertisedBenefit;
9152 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
9154 //If m_immuneToSchool type contain this school type, IMMUNE damage.
9155 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9156 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9157 if (itr->type & shoolMask)
9158 return true;
9160 //If m_immuneToDamage type contain magic, IMMUNE damage.
9161 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
9162 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
9163 if (itr->type & shoolMask)
9164 return true;
9166 return false;
9169 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
9171 if (!spellInfo)
9172 return false;
9174 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
9175 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
9177 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
9178 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
9179 if (itr->type == spellInfo->Dispel)
9180 return true;
9182 if (!(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
9183 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
9185 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9186 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9187 if (!(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
9188 (itr->type & GetSpellSchoolMask(spellInfo)))
9189 return true;
9192 if(uint32 mechanic = spellInfo->Mechanic)
9194 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9195 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9196 if (itr->type == mechanic)
9197 return true;
9199 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9200 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9201 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9202 return true;
9205 return false;
9208 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
9210 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
9211 uint32 effect = spellInfo->Effect[index];
9212 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
9213 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
9214 if (itr->type == effect)
9215 return true;
9217 if(uint32 mechanic = spellInfo->EffectMechanic[index])
9219 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9220 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9221 if (itr->type == mechanic)
9222 return true;
9224 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9225 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9226 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9227 return true;
9230 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
9232 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
9233 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
9234 if (itr->type == aura)
9235 return true;
9237 // Check for immune to application of harmful magical effects
9238 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
9239 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9240 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
9241 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
9242 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
9243 return true;
9246 return false;
9249 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
9251 if (!spellInfo)
9252 return false;
9254 uint32 family = spellInfo->SpellFamilyName;
9255 uint64 flags = spellInfo->SpellFamilyFlags;
9257 if ((family == 5 && flags == 256) || //Searing Pain
9258 (family == 6 && flags == 8192) || //Mind Blast
9259 (family == 11 && flags == 1048576)) //Earth Shock
9260 return true;
9262 return false;
9265 uint32 Unit::MeleeDamageBonus(Unit *pVictim, uint32 pdamage,WeaponAttackType attType, SpellEntry const *spellProto, DamageEffectType damagetype, uint32 stack)
9267 if (!pVictim)
9268 return pdamage;
9270 if (pdamage == 0)
9271 return pdamage;
9273 // differentiate for weapon damage based spells
9274 bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE)));
9275 Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(attType) : NULL;
9276 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9277 uint32 schoolMask = spellProto ? spellProto->SchoolMask : GetMeleeDamageSchoolMask();
9278 uint32 mechanicMask = spellProto ? GetAllSpellMechanicMask(spellProto) : 0;
9280 // Shred also have bonus as MECHANIC_BLEED damages
9281 if (spellProto && spellProto->SpellFamilyName==SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags & UI64LIT(0x00008000))
9282 mechanicMask |= (1 << (MECHANIC_BLEED-1));
9285 // FLAT damage bonus auras
9286 // =======================
9287 int32 DoneFlat = 0;
9288 int32 TakenFlat = 0;
9289 int32 APbonus = 0;
9291 // ..done flat, already included in wepon damage based spells
9292 if (!isWeaponDamageBasedSpell)
9294 AuraList const& mModDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
9295 for(AuraList::const_iterator i = mModDamageDone.begin(); i != mModDamageDone.end(); ++i)
9297 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9298 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9299 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9300 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9302 DoneFlat += (*i)->GetModifier()->m_amount;
9306 // Pets just add their bonus damage to their melee damage
9307 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
9308 DoneFlat += ((Pet*)this)->GetBonusDamage();
9311 // ..done flat (by creature type mask)
9312 DoneFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask);
9314 // ..done flat (base at attack power for marked target and base at attack power for creature type)
9315 if (attType == RANGED_ATTACK)
9317 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
9318 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS, creatureTypeMask);
9319 TakenFlat += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
9321 else
9323 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
9324 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS, creatureTypeMask);
9325 TakenFlat += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
9328 // ..taken flat (by school mask)
9329 TakenFlat += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask);
9331 // PERCENT damage auras
9332 // ====================
9333 float DonePercent = 1.0f;
9334 float TakenPercent = 1.0f;
9336 // ..done pct, already included in weapon damage based spells
9337 if(!isWeaponDamageBasedSpell)
9339 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
9340 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
9342 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9343 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9344 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9345 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9347 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9351 if (attType == OFF_ATTACK)
9352 DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required
9355 // ..done pct (by creature type mask)
9356 DonePercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask);
9358 // ..taken pct (by school mask)
9359 TakenPercent *= pVictim->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask);
9361 // ..taken pct (by mechanic mask)
9362 TakenPercent *= pVictim->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT, mechanicMask);
9364 // ..taken pct (melee/ranged)
9365 if(attType == RANGED_ATTACK)
9366 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
9367 else
9368 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
9370 // ..taken pct (aoe avoidance)
9371 if(spellProto && IsAreaOfEffectSpell(spellProto))
9372 TakenPercent *= pVictim->GetTotalAuraMultiplier(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
9375 // special dummys/class sripts and other effects
9376 // =============================================
9377 Unit *owner = GetOwner();
9378 if (!owner)
9379 owner = this;
9381 // ..done (class scripts)
9382 if(spellProto)
9384 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9385 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9387 if (!(*i)->isAffectedOnSpell(spellProto))
9388 continue;
9390 switch((*i)->GetModifier()->m_miscvalue)
9392 // Tundra Stalker
9393 // Merciless Combat
9394 case 7277:
9396 // Merciless Combat
9397 if ((*i)->GetSpellProto()->SpellIconID == 2656)
9399 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9400 DonePercent *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
9402 else // Tundra Stalker
9404 // Frost Fever (target debuff)
9405 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
9406 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9407 break;
9409 break;
9411 case 7293: // Rage of Rivendare
9413 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
9414 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9415 break;
9417 // Marked for Death
9418 case 7598:
9419 case 7599:
9420 case 7600:
9421 case 7601:
9422 case 7602:
9424 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
9425 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9426 break;
9432 // .. taken (dummy auras)
9433 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
9434 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
9436 switch((*i)->GetSpellProto()->SpellIconID)
9438 //Cheat Death
9439 case 2109:
9440 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
9442 if(pVictim->GetTypeId() != TYPEID_PLAYER)
9443 continue;
9445 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
9446 if (mod < (*i)->GetModifier()->m_amount)
9447 mod = (*i)->GetModifier()->m_amount;
9449 TakenPercent *= (mod + 100.0f) / 100.0f;
9451 break;
9455 // .. taken (class scripts)
9456 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9457 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
9459 switch((*i)->GetMiscValue())
9461 // Dirty Deeds
9462 case 6427:
9463 case 6428:
9464 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9466 Aura* eff0 = GetAura((*i)->GetId(), 0);
9467 if (!eff0 || (*i)->GetEffIndex() != 1)
9469 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
9470 continue;
9473 // effect 0 have expected value but in negative state
9474 TakenPercent *= (-eff0->GetModifier()->m_amount + 100.0f) / 100.0f;
9476 break;
9481 // final calculation
9482 // =================
9484 // scaling of non weapon based spells
9485 if (!isWeaponDamageBasedSpell)
9487 float LvlPenalty = CalculateLevelPenalty(spellProto);
9489 // Check for table values
9490 if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
9492 float coeff;
9493 if (damagetype == DOT)
9494 coeff = bonus->dot_damage * LvlPenalty * stack;
9495 else
9496 coeff = bonus->direct_damage * LvlPenalty * stack;
9498 if (bonus->ap_bonus)
9499 DoneFlat += bonus->ap_bonus * (GetTotalAttackPowerValue(BASE_ATTACK) + APbonus) * stack;
9501 DoneFlat *= coeff;
9502 TakenFlat *= coeff;
9504 // Default calculation
9505 else if (DoneFlat || TakenFlat)
9507 // Damage over Time spells bonus calculation
9508 float DotFactor = 1.0f;
9509 if(damagetype == DOT)
9511 if(!IsChanneledSpell(spellProto))
9512 DotFactor = GetSpellDuration(spellProto) / 15000.0f;
9513 uint16 DotTicks = GetSpellAuraMaxTicks(spellProto);
9514 if(DotTicks)
9516 DoneFlat = DoneFlat * int32(stack) / DotTicks;
9517 TakenFlat = TakenFlat * int32(stack) / DotTicks;
9520 // Distribute Damage over multiple effects, reduce by AoE
9521 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
9522 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
9523 DoneFlat *= (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
9524 TakenFlat*= (CastingTime / 3500.0f) * DotFactor * LvlPenalty;
9527 // weapon damage based spells
9528 else if( APbonus || DoneFlat )
9530 bool normalized = spellProto ? IsSpellHaveEffect(spellProto, SPELL_EFFECT_NORMALIZED_WEAPON_DMG) : false;
9531 DoneFlat += int32(APbonus / 14.0f * GetAPMultiplier(attType,normalized));
9533 // for weapon damage based spells we still have to apply damage done percent mods
9534 // (that are already included into pdamage) to not-yet included DoneFlat
9535 // e.g. from doneVersusCreature, apBonusVs...
9536 UnitMods unitMod;
9537 switch(attType)
9539 default:
9540 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
9541 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
9542 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
9545 DoneFlat *= GetModifierValue(unitMod, TOTAL_PCT);
9548 float tmpDamage = float(int32(pdamage) + DoneFlat) * DonePercent;
9550 // apply spellmod to Done damage
9551 if(spellProto)
9553 if(Player* modOwner = GetSpellModOwner())
9554 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
9557 tmpDamage = (tmpDamage + TakenFlat) * TakenPercent;
9559 // bonus result can be negative
9560 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
9563 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
9565 if (apply)
9567 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
9569 next = itr; ++next;
9570 if(itr->type == type)
9572 m_spellImmune[op].erase(itr);
9573 next = m_spellImmune[op].begin();
9576 SpellImmune Immune;
9577 Immune.spellId = spellId;
9578 Immune.type = type;
9579 m_spellImmune[op].push_back(Immune);
9581 else
9583 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
9585 if(itr->spellId == spellId)
9587 m_spellImmune[op].erase(itr);
9588 break;
9595 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
9597 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
9599 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
9600 RemoveAurasWithDispelType(type);
9603 float Unit::GetWeaponProcChance() const
9605 // normalized proc chance for weapon attack speed
9606 // (odd formula...)
9607 if (isAttackReady(BASE_ATTACK))
9608 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
9609 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
9610 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
9612 return 0.0f;
9615 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
9617 // proc per minute chance calculation
9618 if (PPM <= 0.0f) return 0.0f;
9619 return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
9622 void Unit::Mount(uint32 mount)
9624 if(!mount)
9625 return;
9627 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
9629 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
9631 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
9633 // unsummon pet
9634 if(GetTypeId() == TYPEID_PLAYER)
9635 ((Player*)this)->UnsummonPetTemporaryIfAny();
9638 void Unit::Unmount()
9640 if (!IsMounted())
9641 return;
9643 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
9645 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
9646 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
9648 // only resummon old pet if the player is already added to a map
9649 // this prevents adding a pet to a not created map which would otherwise cause a crash
9650 // (it could probably happen when logging in after a previous crash)
9651 if(GetTypeId() == TYPEID_PLAYER)
9652 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
9655 void Unit::SetInCombatWith(Unit* enemy)
9657 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
9658 if (eOwner->IsPvP())
9660 SetInCombatState(true,enemy);
9661 return;
9664 //check for duel
9665 if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
9667 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
9668 if(((Player const*)eOwner)->duel->opponent == myOwner)
9670 SetInCombatState(true,enemy);
9671 return;
9675 SetInCombatState(false,enemy);
9678 void Unit::SetInCombatState(bool PvP, Unit* enemy)
9680 // only alive units can be in combat
9681 if (!isAlive())
9682 return;
9684 if (PvP)
9685 m_CombatTimer = 5000;
9687 bool creatureNotInCombat = GetTypeId()==TYPEID_UNIT && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9689 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9691 if (isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
9692 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
9694 if (creatureNotInCombat)
9696 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
9698 if (((Creature*)this)->AI())
9699 ((Creature*)this)->AI()->EnterCombat(enemy);
9703 void Unit::ClearInCombat()
9705 m_CombatTimer = 0;
9706 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9708 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
9709 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
9711 // Player's state will be cleared in Player::UpdateContestedPvP
9712 if (GetTypeId() != TYPEID_PLAYER)
9714 Creature* creature = (Creature*)this;
9715 if (creature->GetCreatureInfo() && creature->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE)
9716 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
9718 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
9720 else
9721 ((Player*)this)->UpdatePotionCooldown();
9724 bool Unit::isTargetableForAttack(bool inverseAlive /*=false*/) const
9726 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
9727 return false;
9729 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
9730 return false;
9732 // to be removed if unit by any reason enter combat
9733 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
9734 return false;
9736 // inversealive is needed for some spells which need to be casted at dead targets (aoe)
9737 if (isAlive() == inverseAlive)
9738 return false;
9740 return IsInWorld() && !hasUnitState(UNIT_STAT_DIED) && !isInFlight();
9743 int32 Unit::ModifyHealth(int32 dVal)
9745 int32 gain = 0;
9747 if(dVal==0)
9748 return 0;
9750 int32 curHealth = (int32)GetHealth();
9752 int32 val = dVal + curHealth;
9753 if(val <= 0)
9755 SetHealth(0);
9756 return -curHealth;
9759 int32 maxHealth = (int32)GetMaxHealth();
9761 if(val < maxHealth)
9763 SetHealth(val);
9764 gain = val - curHealth;
9766 else if(curHealth != maxHealth)
9768 SetHealth(maxHealth);
9769 gain = maxHealth - curHealth;
9772 return gain;
9775 int32 Unit::ModifyPower(Powers power, int32 dVal)
9777 int32 gain = 0;
9779 if(dVal==0)
9780 return 0;
9782 int32 curPower = (int32)GetPower(power);
9784 int32 val = dVal + curPower;
9785 if(val <= 0)
9787 SetPower(power,0);
9788 return -curPower;
9791 int32 maxPower = (int32)GetMaxPower(power);
9793 if(val < maxPower)
9795 SetPower(power,val);
9796 gain = val - curPower;
9798 else if(curPower != maxPower)
9800 SetPower(power,maxPower);
9801 gain = maxPower - curPower;
9804 return gain;
9807 bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool inVisibleList, bool is3dDistance) const
9809 if(!u || !IsInMap(u))
9810 return false;
9812 // Always can see self
9813 if (u==this)
9814 return true;
9816 // player visible for other player if not logout and at same transport
9817 // including case when player is out of world
9818 bool at_same_transport =
9819 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
9820 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
9821 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
9822 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
9824 // not in world
9825 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
9826 return false;
9828 // forbidden to seen (at GM respawn command)
9829 if(m_Visibility==VISIBILITY_RESPAWN)
9830 return false;
9832 Map& _map = *u->GetMap();
9833 // Grid dead/alive checks
9834 if (u->GetTypeId()==TYPEID_PLAYER)
9836 // non visible at grid for any stealth state
9837 if(!IsVisibleInGridForPlayer((Player *)u))
9838 return false;
9840 // if player is dead then he can't detect anyone in any cases
9841 if(!u->isAlive())
9842 detect = false;
9844 else
9846 // all dead creatures/players not visible for any creatures
9847 if(!u->isAlive() || !isAlive())
9848 return false;
9851 // always seen by owner
9852 if (GetCharmerOrOwnerGUID()==u->GetGUID())
9853 return true;
9855 // always seen by far sight caster
9856 if (u->GetTypeId()==TYPEID_PLAYER && ((Player*)u)->GetFarSight()==GetGUID())
9857 return true;
9859 // different visible distance checks
9860 if (u->isInFlight()) // what see player in flight
9862 // use object grey distance for all (only see objects any way)
9863 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
9864 return false;
9866 else if(!isAlive()) // distance for show body
9868 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
9869 return false;
9871 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
9873 if(u->GetTypeId()==TYPEID_PLAYER)
9875 // Players far than max visible distance for player or not in our map are not visible too
9876 if (!at_same_transport && !IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9877 return false;
9879 else
9881 // Units far than max visible distance for creature or not in our map are not visible too
9882 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9883 return false;
9886 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
9888 // Pet/charmed far than max visible distance for player or not in our map are not visible too
9889 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9890 return false;
9892 else // distance for show creature
9894 // Units far than max visible distance for creature or not in our map are not visible too
9895 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9896 return false;
9899 // isInvisibleForAlive() those units can only be seen by dead or if other
9900 // unit is also invisible for alive.. if an isinvisibleforalive unit dies we
9901 // should be able to see it too
9902 if (u->isAlive() && isAlive() && isInvisibleForAlive() != u->isInvisibleForAlive())
9903 if (u->GetTypeId() != TYPEID_PLAYER || !((Player *)u)->isGameMaster())
9904 return false;
9906 // Visible units, always are visible for all units, except for units under invisibility and phases
9907 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
9908 return true;
9910 // GMs see any players, not higher GMs and all units in any phase
9911 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
9913 if(GetTypeId() == TYPEID_PLAYER)
9914 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
9915 else
9916 return true;
9919 // non faction visibility non-breakable for non-GMs
9920 if (m_Visibility == VISIBILITY_OFF)
9921 return false;
9923 // phased visibility (both must phased in same way)
9924 if(!InSamePhase(u))
9925 return false;
9927 // raw invisibility
9928 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
9930 // detectable invisibility case
9931 if( invisible && (
9932 // Invisible units, always are visible for units under same invisibility type
9933 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
9934 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
9935 u->canDetectInvisibilityOf(this) ||
9936 // Units that can detect invisibility always are visible for units that can be detected
9937 canDetectInvisibilityOf(u) ))
9939 invisible = false;
9942 // special cases for always overwrite invisibility/stealth
9943 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
9945 // non-hostile case
9946 if (!u->IsHostileTo(this))
9948 // 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)
9949 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
9951 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
9952 return true;
9954 // else apply same rules as for hostile case (detecting check for stealth)
9957 // hostile case
9958 else
9960 // Hunter mark functionality
9961 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
9962 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
9963 if((*iter)->GetCasterGUID()==u->GetGUID())
9964 return true;
9966 // else apply detecting check for stealth
9969 // none other cases for detect invisibility, so invisible
9970 if(invisible)
9971 return false;
9973 // else apply stealth detecting check
9976 // unit got in stealth in this moment and must ignore old detected state
9977 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
9978 return false;
9980 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
9981 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
9982 return true;
9984 // NOW ONLY STEALTH CASE
9986 //if in non-detect mode then invisible for unit
9987 //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false)
9988 //players detect players only in Player::HandleStealthedUnitsDetection()
9989 if (!detect)
9990 return (u->GetTypeId() == TYPEID_PLAYER) ? ((Player*)u)->HaveAtClient(this) : false;
9992 // Special cases
9994 // If is attacked then stealth is lost, some creature can use stealth too
9995 if( !getAttackers().empty() )
9996 return true;
9998 // If there is collision rogue is seen regardless of level difference
9999 if (IsWithinDist(u,0.24f))
10000 return true;
10002 //If a mob or player is stunned he will not be able to detect stealth
10003 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
10004 return false;
10006 // set max ditance
10007 float visibleDistance = (u->GetTypeId() == TYPEID_PLAYER) ? MAX_PLAYER_STEALTH_DETECT_RANGE : ((Creature const*)u)->GetAttackDistance(this);
10009 //Always invisible from back (when stealth detection is on), also filter max distance cases
10010 bool isInFront = viewPoint->isInFrontInMap(this, visibleDistance);
10011 if(!isInFront)
10012 return false;
10014 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
10015 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
10017 //Calculation if target is in front
10019 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
10020 visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
10022 //Visible distance is modified by
10023 //-Level Diff (every level diff = 1.0f in visible distance)
10024 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
10026 //This allows to check talent tree and will add addition stealth dependent on used points)
10027 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
10028 if(stealthMod < 0)
10029 stealthMod = 0;
10031 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
10032 //based on wowwiki every 5 mod we have 1 more level diff in calculation
10033 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_DETECT)) - stealthMod)/5.0f;
10034 visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
10036 // recheck new distance
10037 if(visibleDistance <= 0 || !IsWithinDist(viewPoint,visibleDistance))
10038 return false;
10041 // Now check is target visible with LoS
10042 float ox,oy,oz;
10043 viewPoint->GetPosition(ox,oy,oz);
10044 return IsWithinLOS(ox,oy,oz);
10047 void Unit::SetVisibility(UnitVisibility x)
10049 m_Visibility = x;
10051 if(IsInWorld())
10053 Map *m = GetMap();
10055 if(GetTypeId()==TYPEID_PLAYER)
10056 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10057 else
10058 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10062 bool Unit::canDetectInvisibilityOf(Unit const* u) const
10064 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
10066 for(uint32 i = 0; i < 10; ++i)
10068 if(((1 << i) & mask)==0)
10069 continue;
10071 // find invisibility level
10072 uint32 invLevel = 0;
10073 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
10074 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
10075 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
10076 invLevel = (*itr)->GetModifier()->m_amount;
10078 // find invisibility detect level
10079 uint32 detectLevel = 0;
10080 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
10081 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
10082 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
10083 detectLevel = (*itr)->GetModifier()->m_amount;
10085 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
10087 detectLevel = ((Player*)this)->GetDrunkValue();
10090 if(invLevel <= detectLevel)
10091 return true;
10095 return false;
10098 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
10100 int32 main_speed_mod = 0;
10101 float stack_bonus = 1.0f;
10102 float non_stack_bonus = 1.0f;
10104 switch(mtype)
10106 case MOVE_WALK:
10107 return;
10108 case MOVE_RUN:
10110 if (IsMounted()) // Use on mount auras
10112 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
10113 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
10114 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
10116 else
10118 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
10119 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
10120 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
10122 break;
10124 case MOVE_RUN_BACK:
10125 return;
10126 case MOVE_SWIM:
10128 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
10129 break;
10131 case MOVE_SWIM_BACK:
10132 return;
10133 case MOVE_FLIGHT:
10135 if (IsMounted()) // Use on mount auras
10136 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
10137 else // Use not mount (shapeshift for example) auras (should stack)
10138 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
10139 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
10140 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
10141 break;
10143 case MOVE_FLIGHT_BACK:
10144 return;
10145 default:
10146 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
10147 return;
10150 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
10151 // now we ready for speed calculation
10152 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
10154 switch(mtype)
10156 case MOVE_RUN:
10157 case MOVE_SWIM:
10158 case MOVE_FLIGHT:
10160 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
10161 // TODO: possible affect only on MOVE_RUN
10162 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
10164 // Use speed from aura
10165 float max_speed = normalization / baseMoveSpeed[mtype];
10166 if (speed > max_speed)
10167 speed = max_speed;
10169 break;
10171 default:
10172 break;
10175 // Apply strongest slow aura mod to speed
10176 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
10177 if (slow)
10178 speed *=(100.0f + slow)/100.0f;
10179 SetSpeed(mtype, speed, forced);
10182 float Unit::GetSpeed( UnitMoveType mtype ) const
10184 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
10187 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
10189 if (rate < 0)
10190 rate = 0.0f;
10192 // Update speed only on change
10193 if (m_speed_rate[mtype] == rate)
10194 return;
10196 m_speed_rate[mtype] = rate;
10198 propagateSpeedChange();
10200 WorldPacket data;
10201 if(!forced)
10203 switch(mtype)
10205 case MOVE_WALK:
10206 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10207 break;
10208 case MOVE_RUN:
10209 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
10210 break;
10211 case MOVE_RUN_BACK:
10212 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10213 break;
10214 case MOVE_SWIM:
10215 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
10216 break;
10217 case MOVE_SWIM_BACK:
10218 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10219 break;
10220 case MOVE_TURN_RATE:
10221 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
10222 break;
10223 case MOVE_FLIGHT:
10224 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
10225 break;
10226 case MOVE_FLIGHT_BACK:
10227 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10228 break;
10229 case MOVE_PITCH_RATE:
10230 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
10231 break;
10232 default:
10233 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
10234 return;
10237 data.append(GetPackGUID());
10238 data << uint32(0); // movement flags
10239 data << uint16(0); // unk flags
10240 data << uint32(getMSTime());
10241 data << float(GetPositionX());
10242 data << float(GetPositionY());
10243 data << float(GetPositionZ());
10244 data << float(GetOrientation());
10245 data << uint32(0); // fall time
10246 data << float(GetSpeed(mtype));
10247 SendMessageToSet( &data, true );
10249 else
10251 if(GetTypeId() == TYPEID_PLAYER)
10253 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
10254 // and do it only for real sent packets and use run for run/mounted as client expected
10255 ++((Player*)this)->m_forced_speed_changes[mtype];
10258 switch(mtype)
10260 case MOVE_WALK:
10261 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
10262 break;
10263 case MOVE_RUN:
10264 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
10265 break;
10266 case MOVE_RUN_BACK:
10267 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
10268 break;
10269 case MOVE_SWIM:
10270 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
10271 break;
10272 case MOVE_SWIM_BACK:
10273 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
10274 break;
10275 case MOVE_TURN_RATE:
10276 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
10277 break;
10278 case MOVE_FLIGHT:
10279 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
10280 break;
10281 case MOVE_FLIGHT_BACK:
10282 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
10283 break;
10284 case MOVE_PITCH_RATE:
10285 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
10286 break;
10287 default:
10288 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
10289 return;
10291 data.append(GetPackGUID());
10292 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
10293 if (mtype == MOVE_RUN)
10294 data << uint8(0); // new 2.1.0
10295 data << float(GetSpeed(mtype));
10296 SendMessageToSet( &data, true );
10298 if(Pet* pet = GetPet())
10299 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
10302 void Unit::SetHover(bool on)
10304 if(on)
10305 CastSpell(this, 11010, true);
10306 else
10307 RemoveAurasDueToSpell(11010);
10310 void Unit::setDeathState(DeathState s)
10312 if (s != ALIVE && s!= JUST_ALIVED)
10314 CombatStop();
10315 DeleteThreatList();
10316 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
10318 if(IsNonMeleeSpellCasted(false))
10319 InterruptNonMeleeSpells(false);
10322 if (s == JUST_DIED)
10324 RemoveAllAurasOnDeath();
10325 RemoveGuardians();
10326 UnsummonAllTotems();
10328 // after removing a Fearaura (in RemoveAllAurasOnDeath)
10329 // Unit::SetFeared is called and makes that creatures attack player again
10330 StopMoving();
10332 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
10333 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
10334 // remove aurastates allowing special moves
10335 ClearAllReactives();
10336 ClearDiminishings();
10338 else if(s == JUST_ALIVED)
10340 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
10343 if (m_deathState != ALIVE && s == ALIVE)
10345 //_ApplyAllAuraMods();
10347 m_deathState = s;
10350 /*########################################
10351 ######## ########
10352 ######## AGGRO SYSTEM ########
10353 ######## ########
10354 ########################################*/
10355 bool Unit::CanHaveThreatList() const
10357 // only creatures can have threat list
10358 if( GetTypeId() != TYPEID_UNIT )
10359 return false;
10361 // only alive units can have threat list
10362 if( !isAlive() )
10363 return false;
10365 // totems can not have threat list
10366 if( ((Creature*)this)->isTotem() )
10367 return false;
10369 // vehicles can not have threat list
10370 if( ((Creature*)this)->isVehicle() )
10371 return false;
10373 // pets can not have a threat list, unless they are controlled by a creature
10374 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
10375 return false;
10377 return true;
10380 //======================================================================
10382 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
10384 if (!HasAuraType(SPELL_AURA_MOD_THREAT))
10385 return threat;
10387 if (schoolMask == SPELL_SCHOOL_MASK_NONE)
10388 return threat;
10390 SpellSchools school = GetFirstSchoolInMask(schoolMask);
10392 return threat * m_threatModifier[school];
10395 //======================================================================
10397 void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false*/, SpellSchoolMask schoolMask /*= SPELL_SCHOOL_MASK_NONE*/, SpellEntry const *threatSpell /*= NULL*/)
10399 // Only mobs can manage threat lists
10400 if(CanHaveThreatList())
10401 m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell);
10404 //======================================================================
10406 void Unit::DeleteThreatList()
10408 if(CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
10409 SendThreatClear();
10410 m_ThreatManager.clearReferences();
10413 //======================================================================
10415 void Unit::TauntApply(Unit* taunter)
10417 assert(GetTypeId()== TYPEID_UNIT);
10419 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
10420 return;
10422 if(!CanHaveThreatList())
10423 return;
10425 Unit *target = getVictim();
10426 if(target && target == taunter)
10427 return;
10429 SetInFront(taunter);
10430 if (((Creature*)this)->AI())
10431 ((Creature*)this)->AI()->AttackStart(taunter);
10433 m_ThreatManager.tauntApply(taunter);
10436 //======================================================================
10438 void Unit::TauntFadeOut(Unit *taunter)
10440 assert(GetTypeId()== TYPEID_UNIT);
10442 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
10443 return;
10445 if(!CanHaveThreatList())
10446 return;
10448 Unit *target = getVictim();
10449 if(!target || target != taunter)
10450 return;
10452 if(m_ThreatManager.isThreatListEmpty())
10454 if(((Creature*)this)->AI())
10455 ((Creature*)this)->AI()->EnterEvadeMode();
10456 return;
10459 m_ThreatManager.tauntFadeOut(taunter);
10460 target = m_ThreatManager.getHostileTarget();
10462 if (target && target != taunter)
10464 SetInFront(target);
10465 if (((Creature*)this)->AI())
10466 ((Creature*)this)->AI()->AttackStart(target);
10470 //======================================================================
10472 bool Unit::SelectHostileTarget()
10474 //function provides main threat functionality
10475 //next-victim-selection algorithm and evade mode are called
10476 //threat list sorting etc.
10478 assert(GetTypeId()== TYPEID_UNIT);
10480 if (!this->isAlive())
10481 return false;
10482 //This function only useful once AI has been initialized
10483 if (!((Creature*)this)->AI())
10484 return false;
10486 Unit* target = NULL;
10488 // First checking if we have some taunt on us
10489 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
10490 if ( !tauntAuras.empty() )
10492 Unit* caster;
10494 // The last taunt aura caster is alive an we are happy to attack him
10495 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
10496 return true;
10497 else if (tauntAuras.size() > 1)
10499 // We do not have last taunt aura caster but we have more taunt auras,
10500 // so find first available target
10502 // Auras are pushed_back, last caster will be on the end
10503 AuraList::const_iterator aura = --tauntAuras.end();
10506 --aura;
10507 if ( (caster = (*aura)->GetCaster()) &&
10508 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
10510 target = caster;
10511 break;
10513 }while (aura != tauntAuras.begin());
10517 if ( !target && !m_ThreatManager.isThreatListEmpty() )
10518 // No taunt aura or taunt aura caster is dead standart target selection
10519 target = m_ThreatManager.getHostileTarget();
10521 if(target)
10523 if(!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_DIED))
10524 SetInFront(target);
10525 ((Creature*)this)->AI()->AttackStart(target);
10526 return true;
10529 // no target but something prevent go to evade mode
10530 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
10531 return false;
10533 // last case when creature don't must go to evade mode:
10534 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
10535 // for example at owner command to pet attack some far away creature
10536 // Note: creature not have targeted movement generator but have attacker in this case
10537 if (GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE || hasUnitState(UNIT_STAT_FOLLOW))
10539 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
10541 if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this))
10542 return false;
10546 // enter in evade mode in other case
10547 ((Creature*)this)->AI()->EnterEvadeMode();
10549 return false;
10552 //======================================================================
10553 //======================================================================
10554 //======================================================================
10556 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
10558 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
10560 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
10562 int32 level = int32(getLevel());
10563 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
10564 level = (int32)spellProto->maxLevel;
10565 else if (level < (int32)spellProto->baseLevel)
10566 level = (int32)spellProto->baseLevel;
10567 level-= (int32)spellProto->spellLevel;
10569 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
10570 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
10571 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
10572 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
10573 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
10575 // range can have possitive and negative values, so order its for irand
10576 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
10577 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
10578 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
10580 int32 value = basePoints + randvalue;
10581 //random damage
10582 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
10583 value += (int32)(comboDamage * comboPoints);
10585 if(Player* modOwner = GetSpellModOwner())
10587 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
10588 switch(effect_index)
10590 case 0:
10591 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
10592 break;
10593 case 1:
10594 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
10595 break;
10596 case 2:
10597 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
10598 break;
10602 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
10603 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
10604 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
10605 (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED))
10606 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
10608 return value;
10611 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
10613 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
10615 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
10617 int32 minduration = GetSpellDuration(spellProto);
10618 int32 maxduration = GetSpellMaxDuration(spellProto);
10620 int32 duration;
10622 if( minduration != -1 && minduration != maxduration )
10623 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
10624 else
10625 duration = minduration;
10627 if (duration > 0)
10629 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
10630 // Find total mod value (negative bonus)
10631 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
10632 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
10633 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
10634 // Find max mod (negative bonus)
10635 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
10637 int32 durationMod = 0;
10638 // Select strongest negative mod
10639 if (durationMod_always > durationMod_not_stack)
10640 durationMod = durationMod_not_stack;
10641 else
10642 durationMod = durationMod_always;
10644 if (durationMod != 0)
10645 duration = int32(int64(duration) * (100+durationMod) /100);
10647 if (duration < 0) duration = 0;
10650 return duration;
10653 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
10655 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10657 if(i->DRGroup != group)
10658 continue;
10660 if(!i->hitCount)
10661 return DIMINISHING_LEVEL_1;
10663 if(!i->hitTime)
10664 return DIMINISHING_LEVEL_1;
10666 // If last spell was casted more than 15 seconds ago - reset the count.
10667 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
10669 i->hitCount = DIMINISHING_LEVEL_1;
10670 return DIMINISHING_LEVEL_1;
10672 // or else increase the count.
10673 else
10675 return DiminishingLevels(i->hitCount);
10678 return DIMINISHING_LEVEL_1;
10681 void Unit::IncrDiminishing(DiminishingGroup group)
10683 // Checking for existing in the table
10684 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10686 if(i->DRGroup != group)
10687 continue;
10688 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
10689 i->hitCount += 1;
10690 return;
10692 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
10695 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
10697 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
10698 return;
10700 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
10701 if(limitduration > 0 && duration > limitduration)
10703 // test pet/charm masters instead pets/charmeds
10704 Unit const* targetOwner = GetCharmerOrOwner();
10705 Unit const* casterOwner = caster->GetCharmerOrOwner();
10707 Unit const* target = targetOwner ? targetOwner : this;
10708 Unit const* source = casterOwner ? casterOwner : caster;
10710 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
10711 duration = limitduration;
10714 float mod = 1.0f;
10716 // Some diminishings applies to mobs too (for example, Stun)
10717 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
10719 DiminishingLevels diminish = Level;
10720 switch(diminish)
10722 case DIMINISHING_LEVEL_1: break;
10723 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
10724 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
10725 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
10726 default: break;
10730 duration = int32(duration * mod);
10733 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
10735 // Checking for existing in the table
10736 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10738 if(i->DRGroup != group)
10739 continue;
10741 if(apply)
10742 i->stack += 1;
10743 else if(i->stack)
10745 i->stack -= 1;
10746 // Remember time after last aura from group removed
10747 if (i->stack == 0)
10748 i->hitTime = getMSTime();
10750 break;
10754 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
10756 return ObjectAccessor::GetUnit(object,guid);
10759 bool Unit::isVisibleForInState( Player const* u, WorldObject const* viewPoint, bool inVisibleList ) const
10761 return isVisibleForOrDetect(u, viewPoint, false, inVisibleList, false);
10764 /// returns true if creature can't be seen by alive units
10765 bool Unit::isInvisibleForAlive() const
10767 if (m_AuraFlags & UNIT_AURAFLAG_ALIVE_INVISIBLE)
10768 return true;
10769 // TODO: maybe spiritservices also have just an aura
10770 return isSpiritService();
10773 uint32 Unit::GetCreatureType() const
10775 if(GetTypeId() == TYPEID_PLAYER)
10777 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
10778 if(ssEntry && ssEntry->creatureType > 0)
10779 return ssEntry->creatureType;
10780 else
10781 return CREATURE_TYPE_HUMANOID;
10783 else
10784 return ((Creature*)this)->GetCreatureInfo()->type;
10787 /*#######################################
10788 ######## ########
10789 ######## STAT SYSTEM ########
10790 ######## ########
10791 #######################################*/
10793 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
10795 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
10797 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
10798 return false;
10801 float val = 1.0f;
10803 switch(modifierType)
10805 case BASE_VALUE:
10806 case TOTAL_VALUE:
10807 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
10808 break;
10809 case BASE_PCT:
10810 case TOTAL_PCT:
10811 if(amount <= -100.0f) //small hack-fix for -100% modifiers
10812 amount = -200.0f;
10814 val = (100.0f + amount) / 100.0f;
10815 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
10816 break;
10818 default:
10819 break;
10822 if(!CanModifyStats())
10823 return false;
10825 switch(unitMod)
10827 case UNIT_MOD_STAT_STRENGTH:
10828 case UNIT_MOD_STAT_AGILITY:
10829 case UNIT_MOD_STAT_STAMINA:
10830 case UNIT_MOD_STAT_INTELLECT:
10831 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
10833 case UNIT_MOD_ARMOR: UpdateArmor(); break;
10834 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
10836 case UNIT_MOD_MANA:
10837 case UNIT_MOD_RAGE:
10838 case UNIT_MOD_FOCUS:
10839 case UNIT_MOD_ENERGY:
10840 case UNIT_MOD_HAPPINESS:
10841 case UNIT_MOD_RUNE:
10842 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
10844 case UNIT_MOD_RESISTANCE_HOLY:
10845 case UNIT_MOD_RESISTANCE_FIRE:
10846 case UNIT_MOD_RESISTANCE_NATURE:
10847 case UNIT_MOD_RESISTANCE_FROST:
10848 case UNIT_MOD_RESISTANCE_SHADOW:
10849 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
10851 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
10852 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
10854 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
10855 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
10856 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
10858 default:
10859 break;
10862 return true;
10865 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
10867 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
10869 sLog.outError("trial to access non existed modifier value from UnitMods!");
10870 return 0.0f;
10873 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
10874 return 0.0f;
10876 return m_auraModifiersGroup[unitMod][modifierType];
10879 float Unit::GetTotalStatValue(Stats stat) const
10881 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
10883 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
10884 return 0.0f;
10886 // value = ((base_value * base_pct) + total_value) * total_pct
10887 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
10888 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
10889 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
10890 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
10892 return value;
10895 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
10897 if(unitMod >= UNIT_MOD_END)
10899 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
10900 return 0.0f;
10903 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
10904 return 0.0f;
10906 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
10907 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
10908 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
10909 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
10911 return value;
10914 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
10916 SpellSchools school = SPELL_SCHOOL_NORMAL;
10918 switch(unitMod)
10920 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
10921 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
10922 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
10923 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
10924 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
10925 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
10927 default:
10928 break;
10931 return school;
10934 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
10936 Stats stat = STAT_STRENGTH;
10938 switch(unitMod)
10940 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
10941 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
10942 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
10943 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
10944 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
10946 default:
10947 break;
10950 return stat;
10953 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
10955 switch(unitMod)
10957 case UNIT_MOD_MANA: return POWER_MANA;
10958 case UNIT_MOD_RAGE: return POWER_RAGE;
10959 case UNIT_MOD_FOCUS: return POWER_FOCUS;
10960 case UNIT_MOD_ENERGY: return POWER_ENERGY;
10961 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
10962 case UNIT_MOD_RUNE: return POWER_RUNE;
10963 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
10964 default: return POWER_MANA;
10967 return POWER_MANA;
10970 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
10972 if (attType == RANGED_ATTACK)
10974 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
10975 if (ap < 0)
10976 return 0.0f;
10977 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
10979 else
10981 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
10982 if (ap < 0)
10983 return 0.0f;
10984 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
10988 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
10990 if (attType == OFF_ATTACK && !haveOffhandWeapon())
10991 return 0.0f;
10993 return m_weaponDamage[attType][type];
10996 void Unit::SetLevel(uint32 lvl)
10998 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
11000 // group update
11001 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
11002 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
11005 void Unit::SetHealth(uint32 val)
11007 uint32 maxHealth = GetMaxHealth();
11008 if(maxHealth < val)
11009 val = maxHealth;
11011 SetUInt32Value(UNIT_FIELD_HEALTH, val);
11013 // group update
11014 if(GetTypeId() == TYPEID_PLAYER)
11016 if(((Player*)this)->GetGroup())
11017 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
11019 else if(((Creature*)this)->isPet())
11021 Pet *pet = ((Pet*)this);
11022 if(pet->isControlled())
11024 Unit *owner = GetOwner();
11025 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11026 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
11031 void Unit::SetMaxHealth(uint32 val)
11033 uint32 health = GetHealth();
11034 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
11036 // group update
11037 if(GetTypeId() == TYPEID_PLAYER)
11039 if(((Player*)this)->GetGroup())
11040 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
11042 else if(((Creature*)this)->isPet())
11044 Pet *pet = ((Pet*)this);
11045 if(pet->isControlled())
11047 Unit *owner = GetOwner();
11048 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11049 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
11053 if(val < health)
11054 SetHealth(val);
11057 void Unit::SetPower(Powers power, uint32 val)
11059 if(GetPower(power) == val)
11060 return;
11062 uint32 maxPower = GetMaxPower(power);
11063 if(maxPower < val)
11064 val = maxPower;
11066 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
11068 WorldPacket data(SMSG_POWER_UPDATE);
11069 data.append(GetPackGUID());
11070 data << uint8(power);
11071 data << uint32(val);
11072 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
11074 // group update
11075 if(GetTypeId() == TYPEID_PLAYER)
11077 if(((Player*)this)->GetGroup())
11078 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11080 else if(((Creature*)this)->isPet())
11082 Pet *pet = ((Pet*)this);
11083 if(pet->isControlled())
11085 Unit *owner = GetOwner();
11086 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11087 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11090 // Update the pet's character sheet with happiness damage bonus
11091 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
11093 pet->UpdateDamagePhysical(BASE_ATTACK);
11098 void Unit::SetMaxPower(Powers power, uint32 val)
11100 uint32 cur_power = GetPower(power);
11101 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
11103 // group update
11104 if(GetTypeId() == TYPEID_PLAYER)
11106 if(((Player*)this)->GetGroup())
11107 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11109 else if(((Creature*)this)->isPet())
11111 Pet *pet = ((Pet*)this);
11112 if(pet->isControlled())
11114 Unit *owner = GetOwner();
11115 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11116 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11120 if(val < cur_power)
11121 SetPower(power, val);
11124 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
11126 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
11128 // group update
11129 if(GetTypeId() == TYPEID_PLAYER)
11131 if(((Player*)this)->GetGroup())
11132 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11134 else if(((Creature*)this)->isPet())
11136 Pet *pet = ((Pet*)this);
11137 if(pet->isControlled())
11139 Unit *owner = GetOwner();
11140 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11141 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11146 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
11148 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
11150 // group update
11151 if(GetTypeId() == TYPEID_PLAYER)
11153 if(((Player*)this)->GetGroup())
11154 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11156 else if(((Creature*)this)->isPet())
11158 Pet *pet = ((Pet*)this);
11159 if(pet->isControlled())
11161 Unit *owner = GetOwner();
11162 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11163 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11168 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
11170 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
11171 if(apply)
11172 tAuraProcTriggerDamage.push_back(aura);
11173 else
11174 tAuraProcTriggerDamage.remove(aura);
11177 uint32 Unit::GetCreatePowers( Powers power ) const
11179 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
11180 switch(power)
11182 case POWER_MANA: return GetCreateMana();
11183 case POWER_RAGE: return 1000;
11184 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
11185 case POWER_ENERGY: return 100;
11186 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
11187 case POWER_RUNIC_POWER: return 1000;
11188 case POWER_RUNE: return 0;
11189 case POWER_HEALTH: return 0;
11192 return 0;
11195 void Unit::AddToWorld()
11197 Object::AddToWorld();
11200 void Unit::RemoveFromWorld()
11202 // cleanup
11203 if (IsInWorld())
11205 Uncharm();
11206 RemoveNotOwnSingleTargetAuras();
11207 RemoveGuardians();
11208 RemoveAllGameObjects();
11209 RemoveAllDynObjects();
11212 Object::RemoveFromWorld();
11215 void Unit::CleanupsBeforeDelete()
11217 if(m_uint32Values) // only for fully created object
11219 InterruptNonMeleeSpells(true);
11220 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
11221 CombatStop();
11222 ClearComboPointHolders();
11223 DeleteThreatList();
11224 getHostileRefManager().setOnlineOfflineState(false);
11225 RemoveAllAuras(AURA_REMOVE_BY_DELETE);
11226 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
11228 WorldObject::CleanupsBeforeDelete();
11231 CharmInfo* Unit::InitCharmInfo(Unit *charm)
11233 if(!m_charmInfo)
11234 m_charmInfo = new CharmInfo(charm);
11235 return m_charmInfo;
11238 CharmInfo::CharmInfo(Unit* unit)
11239 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
11241 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
11242 m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
11245 void CharmInfo::InitPetActionBar()
11247 // the first 3 SpellOrActions are attack, follow and stay
11248 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
11249 SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
11251 // middle 4 SpellOrActions are spells/special attacks/abilities
11252 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
11253 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_DISABLED);
11255 // last 3 SpellOrActions are reactions
11256 for(uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
11257 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
11260 void CharmInfo::InitEmptyActionBar()
11262 SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
11263 for(uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
11264 SetActionBar(x,0,ACT_PASSIVE);
11267 void CharmInfo::InitPossessCreateSpells()
11269 InitEmptyActionBar(); //charm action bar
11271 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
11272 return;
11274 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11276 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
11277 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
11278 else
11279 AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
11283 void CharmInfo::InitCharmCreateSpells()
11285 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
11287 InitEmptyActionBar();
11288 return;
11291 InitPetActionBar();
11293 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11295 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
11297 if(!spellId)
11299 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
11300 continue;
11303 if (IsPassiveSpell(spellId))
11305 m_unit->CastSpell(m_unit, spellId, true);
11306 m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
11308 else
11310 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
11312 ActiveStates newstate;
11313 bool onlyselfcast = true;
11314 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
11316 if(!spellInfo) onlyselfcast = false;
11317 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
11319 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
11320 onlyselfcast = false;
11323 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
11324 newstate = ACT_DISABLED;
11325 else
11326 newstate = ACT_PASSIVE;
11328 AddSpellToActionBar(spellId, newstate);
11333 bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
11335 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
11337 // new spell rank can be already listed
11338 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11340 if (uint32 action = PetActionBar[i].GetAction())
11342 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
11344 PetActionBar[i].SetAction(spell_id);
11345 return true;
11350 // or use empty slot in other case
11351 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11353 if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
11355 SetActionBar(i,spell_id,newstate == ACT_DECIDE ? ACT_DISABLED : newstate);
11356 return true;
11359 return false;
11362 bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
11364 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
11366 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11368 if (uint32 action = PetActionBar[i].GetAction())
11370 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
11372 SetActionBar(i,0,ACT_DISABLED);
11373 return true;
11378 return false;
11381 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
11383 if(IsPassiveSpell(spellid))
11384 return;
11386 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
11387 if(spellid == m_charmspells[x].GetAction())
11388 m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
11391 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
11393 m_petnumber = petnumber;
11394 if(statwindow)
11395 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
11396 else
11397 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
11400 void CharmInfo::LoadPetActionBar(const std::string& data )
11402 InitPetActionBar();
11404 Tokens tokens = StrSplit(data, " ");
11406 if (tokens.size() != (ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START)*2)
11407 return; // non critical, will reset to default
11409 int index;
11410 Tokens::iterator iter;
11411 for(iter = tokens.begin(), index = ACTION_BAR_INDEX_PET_SPELL_START; index < ACTION_BAR_INDEX_PET_SPELL_END; ++iter, ++index )
11413 // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
11414 uint8 type = atol((*iter).c_str());
11415 ++iter;
11416 uint32 action = atol((*iter).c_str());
11418 PetActionBar[index].SetActionAndType(action,ActiveStates(type));
11420 // check correctness
11421 if(PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
11422 SetActionBar(index,0,ACT_DISABLED);
11426 void CharmInfo::BuildActionBar( WorldPacket* data )
11428 for(uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11429 *data << uint32(PetActionBar[i].packedData);
11432 void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
11434 for(int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11436 if(spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
11438 PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
11439 break;
11444 bool Unit::isFrozen() const
11446 return HasAuraState(AURA_STATE_FROZEN);
11449 struct ProcTriggeredData
11451 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
11452 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
11453 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
11455 SpellProcEventEntry const *spellProcEvent;
11456 Aura* triggeredByAura;
11457 Unit::spellEffectPair triggeredByAura_SpellPair;
11460 typedef std::list< ProcTriggeredData > ProcTriggeredList;
11461 typedef std::list< uint32> RemoveSpellList;
11463 // List of auras that CAN be trigger but may not exist in spell_proc_event
11464 // in most case need for drop charges
11465 // in some types of aura need do additional check
11466 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
11467 bool InitTriggerAuraData()
11469 for (int i=0;i<TOTAL_AURAS;++i)
11471 isTriggerAura[i]=false;
11472 isNonTriggerAura[i] = false;
11474 isTriggerAura[SPELL_AURA_DUMMY] = true;
11475 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
11476 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
11477 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
11478 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
11479 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
11480 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
11481 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
11482 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
11483 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
11484 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
11485 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
11486 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
11487 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
11488 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
11489 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
11490 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
11491 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
11492 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
11493 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
11494 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
11495 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
11496 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
11497 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
11498 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
11499 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
11500 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
11501 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
11502 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
11503 isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
11505 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
11506 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
11508 return true;
11511 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
11513 uint32 procEx = PROC_EX_NONE;
11514 // Check victim state
11515 if (missCondition!=SPELL_MISS_NONE)
11516 switch (missCondition)
11518 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
11519 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
11520 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
11521 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
11522 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
11523 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
11524 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
11525 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
11526 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
11527 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
11528 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
11529 default:
11530 break;
11532 else
11534 // On block
11535 if (damageInfo->blocked)
11536 procEx|=PROC_EX_BLOCK;
11537 // On absorb
11538 if (damageInfo->absorb)
11539 procEx|=PROC_EX_ABSORB;
11540 // On crit
11541 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
11542 procEx|=PROC_EX_CRITICAL_HIT;
11543 else
11544 procEx|=PROC_EX_NORMAL_HIT;
11546 return procEx;
11549 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
11551 // For melee/ranged based attack need update skills and set some Aura states
11552 if (procFlag & MELEE_BASED_TRIGGER_MASK)
11554 // Update skills here for players
11555 if (GetTypeId() == TYPEID_PLAYER)
11557 // On melee based hit/miss/resist need update skill (for victim and attacker)
11558 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
11560 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
11561 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
11563 // Update defence if player is victim and parry/dodge/block
11564 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
11565 ((Player*)this)->UpdateDefense();
11567 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
11568 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
11570 // for victim
11571 if (isVictim)
11573 // if victim and dodge attack
11574 if (procExtra&PROC_EX_DODGE)
11576 //Update AURA_STATE on dodge
11577 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
11579 ModifyAuraState(AURA_STATE_DEFENSE, true);
11580 StartReactiveTimer( REACTIVE_DEFENSE );
11583 // if victim and parry attack
11584 if (procExtra & PROC_EX_PARRY)
11586 // For Hunters only Counterattack (skip Mongoose bite)
11587 if (getClass() == CLASS_HUNTER)
11589 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
11590 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
11592 else
11594 ModifyAuraState(AURA_STATE_DEFENSE, true);
11595 StartReactiveTimer( REACTIVE_DEFENSE );
11598 // if and victim block attack
11599 if (procExtra & PROC_EX_BLOCK)
11601 ModifyAuraState(AURA_STATE_DEFENSE,true);
11602 StartReactiveTimer( REACTIVE_DEFENSE );
11605 else //For attacker
11607 // Overpower on victim dodge
11608 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
11610 ((Player*)this)->AddComboPoints(pTarget, 1);
11611 StartReactiveTimer( REACTIVE_OVERPOWER );
11617 RemoveSpellList removedSpells;
11618 ProcTriggeredList procTriggered;
11619 // Fill procTriggered list
11620 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
11622 // skip deleted auras (possible at recursive triggered call
11623 if(itr->second->IsDeleted())
11624 continue;
11626 SpellProcEventEntry const* spellProcEvent = NULL;
11627 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
11628 continue;
11630 itr->second->SetInUse(true); // prevent aura deletion
11631 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
11634 // Nothing found
11635 if (procTriggered.empty())
11636 return;
11638 // Handle effects proceed this time
11639 for(ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
11641 // Some auras can be deleted in function called in this loop (except first, ofc)
11642 Aura *triggeredByAura = i->triggeredByAura;
11643 if(triggeredByAura->IsDeleted())
11644 continue;
11646 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
11647 Modifier *auraModifier = triggeredByAura->GetModifier();
11648 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
11649 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
11650 // For players set spell cooldown if need
11651 uint32 cooldown = 0;
11652 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
11653 cooldown = spellProcEvent->cooldown;
11655 switch(auraModifier->m_auraname)
11657 case SPELL_AURA_PROC_TRIGGER_SPELL:
11659 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11660 // Don`t drop charge or add cooldown for not started trigger
11661 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11663 triggeredByAura->SetInUse(false);
11664 continue;
11666 break;
11668 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
11670 sLog.outDebug("ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", auraModifier->m_amount, spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11671 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
11672 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
11673 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
11674 SendSpellNonMeleeDamageLog(&damageInfo);
11675 DealSpellDamage(&damageInfo, true);
11676 break;
11678 case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
11679 case SPELL_AURA_MANA_SHIELD:
11680 case SPELL_AURA_OBS_MOD_MANA:
11681 case SPELL_AURA_DUMMY:
11683 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11684 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11686 triggeredByAura->SetInUse(false);
11687 continue;
11689 break;
11691 case SPELL_AURA_MOD_HASTE:
11693 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11694 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11696 triggeredByAura->SetInUse(false);
11697 continue;
11699 break;
11701 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
11703 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11704 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
11706 triggeredByAura->SetInUse(false);
11707 continue;
11709 break;
11711 case SPELL_AURA_PRAYER_OF_MENDING:
11713 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
11714 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
11716 HandleMendingAuraProc(triggeredByAura);
11717 break;
11719 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
11721 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11723 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11725 triggeredByAura->SetInUse(false);
11726 continue;
11728 break;
11730 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
11731 // Skip melee hits or instant cast spells
11732 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
11734 triggeredByAura->SetInUse(false);
11735 continue;
11737 break;
11738 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
11739 // Skip Melee hits and spells ws wrong school
11740 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
11742 triggeredByAura->SetInUse(false);
11743 continue;
11745 break;
11746 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
11747 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
11748 // Skip melee hits and spells ws wrong school or zero cost
11749 if (procSpell == NULL ||
11750 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
11751 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
11753 triggeredByAura->SetInUse(false);
11754 continue;
11756 break;
11757 case SPELL_AURA_MECHANIC_IMMUNITY:
11758 // Compare mechanic
11759 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
11761 triggeredByAura->SetInUse(false);
11762 continue;
11764 break;
11765 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
11766 // Compare mechanic
11767 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
11769 triggeredByAura->SetInUse(false);
11770 continue;
11772 break;
11773 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
11774 // Compare casters
11775 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
11777 triggeredByAura->SetInUse(false);
11778 continue;
11780 break;
11781 case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
11782 if (!procSpell)
11784 triggeredByAura->SetInUse(false);
11785 continue;
11787 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s spell crit chance aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11788 if (!HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11790 triggeredByAura->SetInUse(false);
11791 continue;
11793 break;
11794 default:
11795 // nothing do, just charges counter
11796 break;
11799 // Remove charge (aura can be removed by triggers)
11800 if(useCharges && !triggeredByAura->IsDeleted())
11802 // If last charge dropped add spell to remove list
11803 if(triggeredByAura->DropAuraCharge())
11804 removedSpells.push_back(triggeredByAura->GetId());
11807 triggeredByAura->SetInUse(false);
11809 if (!removedSpells.empty())
11811 // Sort spells and remove dublicates
11812 removedSpells.sort();
11813 removedSpells.unique();
11814 // Remove auras from removedAuras
11815 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();++i)
11816 RemoveAurasDueToSpell(*i);
11820 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
11822 return SPELL_SCHOOL_MASK_NORMAL;
11825 Player* Unit::GetSpellModOwner()
11827 if(GetTypeId()==TYPEID_PLAYER)
11828 return (Player*)this;
11829 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
11831 Unit* owner = GetOwner();
11832 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
11833 return (Player*)owner;
11835 return NULL;
11838 ///----------Pet responses methods-----------------
11839 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
11841 if(msg == SPELL_CAST_OK)
11842 return;
11844 Unit *owner = GetCharmerOrOwner();
11845 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11846 return;
11848 WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
11849 data << uint8(0); // cast count?
11850 data << uint32(spellid);
11851 data << uint8(msg);
11852 // uint32 for some reason
11853 // uint32 for some reason
11854 ((Player*)owner)->GetSession()->SendPacket(&data);
11857 void Unit::SendPetActionFeedback (uint8 msg)
11859 Unit* owner = GetOwner();
11860 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11861 return;
11863 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
11864 data << uint8(msg);
11865 ((Player*)owner)->GetSession()->SendPacket(&data);
11868 void Unit::SendPetTalk (uint32 pettalk)
11870 Unit* owner = GetOwner();
11871 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11872 return;
11874 WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
11875 data << uint64(GetGUID());
11876 data << uint32(pettalk);
11877 ((Player*)owner)->GetSession()->SendPacket(&data);
11880 void Unit::SendPetAIReaction(uint64 guid)
11882 Unit* owner = GetOwner();
11883 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11884 return;
11886 WorldPacket data(SMSG_AI_REACTION, 8 + 4);
11887 data << uint64(guid);
11888 data << uint32(AI_REACTION_AGGRO);
11889 ((Player*)owner)->GetSession()->SendPacket(&data);
11892 ///----------End of Pet responses methods----------
11894 void Unit::StopMoving()
11896 clearUnitState(UNIT_STAT_MOVING);
11898 // send explicit stop packet
11899 // player expected for correct work MONSTER_MOVE_WALK
11900 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, GetTypeId()==TYPEID_PLAYER ? MONSTER_MOVE_WALK : MONSTER_MOVE_NONE, 0);
11902 // update position and orientation for near players
11903 WorldPacket data;
11904 BuildHeartBeatMsg(&data);
11905 SendMessageToSet(&data,false);
11908 void Unit::SetFeared(bool apply, uint64 const& casterGUID, uint32 spellID, uint32 time)
11910 if( apply )
11912 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
11913 return;
11915 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
11917 GetMotionMaster()->MovementExpired(false);
11918 CastStop(GetGUID()==casterGUID ? spellID : 0);
11920 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
11922 GetMotionMaster()->MoveFleeing(caster, time); // caster==NULL processed in MoveFleeing
11924 else
11926 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
11928 GetMotionMaster()->MovementExpired(false);
11930 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
11932 // restore appropriate movement generator
11933 if(getVictim())
11934 GetMotionMaster()->MoveChase(getVictim());
11935 else
11936 GetMotionMaster()->Initialize();
11938 // attack caster if can
11939 Unit* caster = Unit::GetUnit(*this, casterGUID);
11940 if(caster && ((Creature*)this)->AI())
11941 ((Creature*)this)->AI()->AttackedBy(caster);
11945 if (GetTypeId() == TYPEID_PLAYER)
11946 ((Player*)this)->SetClientControl(this, !apply);
11949 void Unit::SetConfused(bool apply, uint64 const& casterGUID, uint32 spellID)
11951 if( apply )
11953 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
11955 CastStop(GetGUID()==casterGUID ? spellID : 0);
11957 GetMotionMaster()->MoveConfused();
11959 else
11961 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
11963 GetMotionMaster()->MovementExpired(false);
11965 if (GetTypeId() != TYPEID_PLAYER && isAlive())
11967 // restore appropriate movement generator
11968 if(getVictim())
11969 GetMotionMaster()->MoveChase(getVictim());
11970 else
11971 GetMotionMaster()->Initialize();
11975 if(GetTypeId() == TYPEID_PLAYER)
11976 ((Player*)this)->SetClientControl(this, !apply);
11979 void Unit::SetFeignDeath(bool apply, uint64 const& casterGUID, uint32 spellID)
11981 if( apply )
11984 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
11985 data<<GetGUID();
11986 data<<uint8(0);
11987 SendMessageToSet(&data,true);
11990 if(GetTypeId() != TYPEID_PLAYER)
11991 StopMoving();
11992 else
11993 ((Player*)this)->m_movementInfo.SetMovementFlags(MOVEMENTFLAG_NONE);
11995 // blizz like 2.0.x
11996 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
11997 // blizz like 2.0.x
11998 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
11999 // blizz like 2.0.x
12000 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12002 addUnitState(UNIT_STAT_DIED);
12003 CombatStop();
12004 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
12006 // prevent interrupt message
12007 if (casterGUID == GetGUID())
12008 FinishSpell(CURRENT_GENERIC_SPELL,false);
12009 InterruptNonMeleeSpells(true);
12010 getHostileRefManager().deleteReferences();
12012 else
12015 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12016 data<<GetGUID();
12017 data<<uint8(1);
12018 SendMessageToSet(&data,true);
12020 // blizz like 2.0.x
12021 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12022 // blizz like 2.0.x
12023 RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12024 // blizz like 2.0.x
12025 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12027 clearUnitState(UNIT_STAT_DIED);
12029 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12031 // restore appropriate movement generator
12032 if(getVictim())
12033 GetMotionMaster()->MoveChase(getVictim());
12034 else
12035 GetMotionMaster()->Initialize();
12041 bool Unit::IsSitState() const
12043 uint8 s = getStandState();
12044 return
12045 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
12046 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
12047 s == UNIT_STAND_STATE_SIT;
12050 bool Unit::IsStandState() const
12052 uint8 s = getStandState();
12053 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
12056 void Unit::SetStandState(uint8 state)
12058 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
12060 if (IsStandState())
12061 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
12063 if(GetTypeId()==TYPEID_PLAYER)
12065 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
12066 data << (uint8)state;
12067 ((Player*)this)->GetSession()->SendPacket(&data);
12071 bool Unit::IsPolymorphed() const
12073 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
12076 void Unit::SetDisplayId(uint32 modelId)
12078 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
12080 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
12082 Pet *pet = ((Pet*)this);
12083 if(!pet->isControlled())
12084 return;
12085 Unit *owner = GetOwner();
12086 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
12087 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
12091 void Unit::ClearComboPointHolders()
12093 while(!m_ComboPointHolders.empty())
12095 uint32 lowguid = *m_ComboPointHolders.begin();
12097 Player* plr = sObjectMgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
12098 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
12099 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
12100 else
12101 m_ComboPointHolders.erase(lowguid); // or remove manually
12105 void Unit::ClearAllReactives()
12107 for(int i=0; i < MAX_REACTIVE; ++i)
12108 m_reactiveTimer[i] = 0;
12110 if (HasAuraState( AURA_STATE_DEFENSE))
12111 ModifyAuraState(AURA_STATE_DEFENSE, false);
12112 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
12113 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12114 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12115 ((Player*)this)->ClearComboPoints();
12118 void Unit::UpdateReactives( uint32 p_time )
12120 for(int i = 0; i < MAX_REACTIVE; ++i)
12122 ReactiveType reactive = ReactiveType(i);
12124 if(!m_reactiveTimer[reactive])
12125 continue;
12127 if ( m_reactiveTimer[reactive] <= p_time)
12129 m_reactiveTimer[reactive] = 0;
12131 switch ( reactive )
12133 case REACTIVE_DEFENSE:
12134 if (HasAuraState(AURA_STATE_DEFENSE))
12135 ModifyAuraState(AURA_STATE_DEFENSE, false);
12136 break;
12137 case REACTIVE_HUNTER_PARRY:
12138 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
12139 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12140 break;
12141 case REACTIVE_OVERPOWER:
12142 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12143 ((Player*)this)->ClearComboPoints();
12144 break;
12145 default:
12146 break;
12149 else
12151 m_reactiveTimer[reactive] -= p_time;
12156 Unit* Unit::SelectNearbyTarget(Unit* except /*= NULL*/) const
12158 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
12159 Cell cell(p);
12160 cell.data.Part.reserved = ALL_DISTRICT;
12161 cell.SetNoCreate();
12163 std::list<Unit *> targets;
12166 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
12167 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
12169 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
12170 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
12172 CellLock<GridReadGuard> cell_lock(cell, p);
12173 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap(), *this, ATTACK_DISTANCE);
12174 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap(), *this, ATTACK_DISTANCE);
12177 // remove current target
12178 if(except)
12179 targets.remove(except);
12181 // remove not LoS targets
12182 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
12184 if(!IsWithinLOSInMap(*tIter))
12186 std::list<Unit *>::iterator tIter2 = tIter;
12187 ++tIter;
12188 targets.erase(tIter2);
12190 else
12191 ++tIter;
12194 // no appropriate targets
12195 if(targets.empty())
12196 return NULL;
12198 // select random
12199 uint32 rIdx = urand(0,targets.size()-1);
12200 std::list<Unit *>::const_iterator tcIter = targets.begin();
12201 for(uint32 i = 0; i < rIdx; ++i)
12202 ++tcIter;
12204 return *tcIter;
12207 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
12209 for (AuraMap::const_iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
12211 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
12212 return true;
12214 return false;
12217 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
12219 if(val > 0)
12221 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
12222 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
12224 else
12226 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
12227 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
12231 void Unit::ApplyCastTimePercentMod(float val, bool apply )
12233 if(val > 0)
12234 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
12235 else
12236 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
12239 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
12241 // Not apply this to creature casted spells with casttime==0
12242 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
12243 return 3500;
12245 if (CastingTime > 7000) CastingTime = 7000;
12246 if (CastingTime < 1500) CastingTime = 1500;
12248 if(damagetype == DOT && !IsChanneledSpell(spellProto))
12249 CastingTime = 3500;
12251 int32 overTime = 0;
12252 uint8 effects = 0;
12253 bool DirectDamage = false;
12254 bool AreaEffect = false;
12256 for ( uint32 i=0; i<3;++i)
12258 switch ( spellProto->Effect[i] )
12260 case SPELL_EFFECT_SCHOOL_DAMAGE:
12261 case SPELL_EFFECT_POWER_DRAIN:
12262 case SPELL_EFFECT_HEALTH_LEECH:
12263 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
12264 case SPELL_EFFECT_POWER_BURN:
12265 case SPELL_EFFECT_HEAL:
12266 DirectDamage = true;
12267 break;
12268 case SPELL_EFFECT_APPLY_AURA:
12269 switch ( spellProto->EffectApplyAuraName[i] )
12271 case SPELL_AURA_PERIODIC_DAMAGE:
12272 case SPELL_AURA_PERIODIC_HEAL:
12273 case SPELL_AURA_PERIODIC_LEECH:
12274 if ( GetSpellDuration(spellProto) )
12275 overTime = GetSpellDuration(spellProto);
12276 break;
12277 default:
12278 // -5% per additional effect
12279 ++effects;
12280 break;
12282 default:
12283 break;
12286 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
12287 AreaEffect = true;
12290 // Combined Spells with Both Over Time and Direct Damage
12291 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
12293 // mainly for DoTs which are 3500 here otherwise
12294 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
12295 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
12296 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
12297 // Portion to Over Time
12298 float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
12300 if ( damagetype == DOT )
12301 CastingTime = uint32(CastingTime * PtOT);
12302 else if ( PtOT < 1.0f )
12303 CastingTime = uint32(CastingTime * (1 - PtOT));
12304 else
12305 CastingTime = 0;
12308 // Area Effect Spells receive only half of bonus
12309 if ( AreaEffect )
12310 CastingTime /= 2;
12312 // -5% of total per any additional effect
12313 for ( uint8 i=0; i<effects; ++i)
12315 if ( CastingTime > 175 )
12317 CastingTime -= 175;
12319 else
12321 CastingTime = 0;
12322 break;
12326 return CastingTime;
12329 void Unit::UpdateAuraForGroup(uint8 slot)
12331 if(GetTypeId() == TYPEID_PLAYER)
12333 Player* player = (Player*)this;
12334 if(player->GetGroup())
12336 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
12337 player->SetAuraUpdateMask(slot);
12340 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
12342 Pet *pet = ((Pet*)this);
12343 if(pet->isControlled())
12345 Unit *owner = GetOwner();
12346 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
12348 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
12349 pet->SetAuraUpdateMask(slot);
12355 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
12357 if (!normalized || GetTypeId() != TYPEID_PLAYER)
12358 return float(GetAttackTime(attType))/1000.0f;
12360 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
12361 if (!Weapon)
12362 return 2.4; // fist attack
12364 switch (Weapon->GetProto()->InventoryType)
12366 case INVTYPE_2HWEAPON:
12367 return 3.3;
12368 case INVTYPE_RANGED:
12369 case INVTYPE_RANGEDRIGHT:
12370 case INVTYPE_THROWN:
12371 return 2.8;
12372 case INVTYPE_WEAPON:
12373 case INVTYPE_WEAPONMAINHAND:
12374 case INVTYPE_WEAPONOFFHAND:
12375 default:
12376 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
12380 Aura* Unit::GetDummyAura( uint32 spell_id ) const
12382 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
12383 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
12384 if ((*itr)->GetId() == spell_id)
12385 return *itr;
12387 return NULL;
12390 void Unit::SetContestedPvP(Player *attackedPlayer)
12392 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
12394 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
12395 return;
12397 player->SetContestedPvPTimer(30000);
12398 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
12400 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
12401 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
12402 // call MoveInLineOfSight for nearby contested guards
12403 SetVisibility(GetVisibility());
12405 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
12407 addUnitState(UNIT_STAT_ATTACK_PLAYER);
12408 // call MoveInLineOfSight for nearby contested guards
12409 SetVisibility(GetVisibility());
12413 void Unit::AddPetAura(PetAura const* petSpell)
12415 m_petAuras.insert(petSpell);
12416 if(Pet* pet = GetPet())
12417 pet->CastPetAura(petSpell);
12420 void Unit::RemovePetAura(PetAura const* petSpell)
12422 m_petAuras.erase(petSpell);
12423 if(Pet* pet = GetPet())
12424 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
12427 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
12429 Pet* pet = new Pet(HUNTER_PET);
12431 if(!pet->CreateBaseAtCreature(creatureTarget))
12433 delete pet;
12434 return NULL;
12437 pet->SetOwnerGUID(GetGUID());
12438 pet->SetCreatorGUID(GetGUID());
12439 pet->setFaction(getFaction());
12440 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
12442 if(GetTypeId()==TYPEID_PLAYER)
12443 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
12445 if(IsPvP())
12446 pet->SetPvP(true);
12448 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
12450 if(!pet->InitStatsForLevel(level))
12452 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
12453 delete pet;
12454 return NULL;
12457 pet->GetCharmInfo()->SetPetNumber(sObjectMgr.GeneratePetNumber(), true);
12458 // this enables pet details window (Shift+P)
12459 pet->AIM_Initialize();
12460 pet->InitPetCreateSpells();
12461 pet->InitLevelupSpellsForLevel();
12462 pet->InitTalentForLevel();
12463 pet->SetHealth(pet->GetMaxHealth());
12465 return pet;
12468 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
12470 SpellEntry const* spellProto = aura->GetSpellProto ();
12472 // Get proc Event Entry
12473 spellProcEvent = sSpellMgr.GetSpellProcEvent(spellProto->Id);
12475 // Aura info stored here
12476 Modifier *mod = aura->GetModifier();
12477 // Skip this auras
12478 if (isNonTriggerAura[mod->m_auraname])
12479 return false;
12480 // If not trigger by default and spellProcEvent==NULL - skip
12481 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
12482 return false;
12484 // Get EventProcFlag
12485 uint32 EventProcFlag;
12486 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
12487 EventProcFlag = spellProcEvent->procFlags;
12488 else
12489 EventProcFlag = spellProto->procFlags; // else get from spell proto
12490 // Continue if no trigger exist
12491 if (!EventProcFlag)
12492 return false;
12494 // Check spellProcEvent data requirements
12495 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
12496 return false;
12498 // In most cases req get honor or XP from kill
12499 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
12501 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
12502 // Shadow Word: Death - can trigger from every kill
12503 if (aura->GetId() == 32409)
12504 allow = true;
12505 if (!allow)
12506 return false;
12508 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
12509 // But except periodic triggers (can triggered from self)
12510 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
12511 return false;
12513 // Check if current equipment allows aura to proc
12514 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
12516 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
12518 Item *item = NULL;
12519 if(attType == BASE_ATTACK)
12520 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
12521 else if (attType == OFF_ATTACK)
12522 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
12523 else
12524 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
12526 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
12527 return false;
12529 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
12531 // Check if player is wearing shield
12532 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
12533 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
12534 return false;
12537 // Get chance from spell
12538 float chance = (float)spellProto->procChance;
12539 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
12540 if(spellProcEvent && spellProcEvent->customChance)
12541 chance = spellProcEvent->customChance;
12542 // If PPM exist calculate chance from PPM
12543 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
12545 uint32 WeaponSpeed = GetAttackTime(attType);
12546 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
12548 // Apply chance modifer aura
12549 if(Player* modOwner = GetSpellModOwner())
12551 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
12552 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
12555 return roll_chance_f(chance);
12558 bool Unit::HandleMendingAuraProc( Aura* triggeredByAura )
12560 // aura can be deleted at casts
12561 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
12562 uint32 effIdx = triggeredByAura->GetEffIndex();
12563 int32 heal = triggeredByAura->GetModifier()->m_amount;
12564 uint64 caster_guid = triggeredByAura->GetCasterGUID();
12566 // jumps
12567 int32 jumps = triggeredByAura->GetAuraCharges()-1;
12569 // current aura expire
12570 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
12572 // next target selection
12573 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
12575 float radius;
12576 if (spellProto->EffectRadiusIndex[effIdx])
12577 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
12578 else
12579 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
12581 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
12583 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
12585 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
12587 // aura will applied from caster, but spell casted from current aura holder
12588 SpellModifier *mod = new SpellModifier;
12589 mod->op = SPELLMOD_CHARGES;
12590 mod->value = jumps-5; // negative
12591 mod->type = SPELLMOD_FLAT;
12592 mod->spellId = spellProto->Id;
12593 mod->mask = spellProto->SpellFamilyFlags;
12594 mod->mask2 = spellProto->SpellFamilyFlags2;
12596 // remove before apply next (locked against deleted)
12597 triggeredByAura->SetInUse(true);
12598 RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID());
12600 caster->AddSpellMod(mod, true);
12601 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
12602 caster->AddSpellMod(mod, false);
12603 triggeredByAura->SetInUse(false);
12608 // heal
12609 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
12610 return true;
12613 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
12615 uint64 target_guid = GetChannelObjectGUID();
12617 if(!IS_UNIT_GUID(target_guid))
12618 return;
12620 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
12621 if(!target)
12622 return;
12624 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
12626 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
12627 target->RemoveAura(iter);
12628 else
12629 ++iter;
12633 void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/)
12635 Unit::AuraMap& auras = GetAuras();
12636 for(Unit::AuraMap::iterator iter = auras.begin(); iter != auras.end();)
12638 SpellEntry const *spell = iter->second->GetSpellProto();
12639 if (spell->Id == exceptSpellId)
12640 ++iter;
12641 else if (non_positive && iter->second->IsPositive())
12642 ++iter;
12643 else if (spell->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
12644 ++iter;
12645 else if (GetSpellMechanicMask(spell, iter->second->GetEffIndex()) & mechMask)
12647 RemoveAurasDueToSpell(spell->Id);
12648 if(auras.empty())
12649 break;
12650 else
12651 iter = auras.begin();
12653 else
12654 ++iter;
12658 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
12660 if(newPhaseMask==GetPhaseMask())
12661 return;
12663 if(IsInWorld())
12664 RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
12666 WorldObject::SetPhaseMask(newPhaseMask,update);
12668 if(IsInWorld())
12669 if(Pet* pet = GetPet())
12670 pet->SetPhaseMask(newPhaseMask,true);
12673 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
12675 if(GetTypeId() == TYPEID_PLAYER)
12676 ((Player*)this)->TeleportTo(GetMapId(), x, y, z, orientation, TELE_TO_NOT_LEAVE_TRANSPORT | TELE_TO_NOT_LEAVE_COMBAT | TELE_TO_NOT_UNSUMMON_PET | (casting ? TELE_TO_SPELL : 0));
12677 else
12679 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
12681 WorldPacket data;
12682 BuildHeartBeatMsg(&data);
12683 SendMessageToSet(&data, false);
12687 void Unit::SetPvP( bool state )
12689 if(state)
12690 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
12691 else
12692 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
12694 if(Pet* pet = GetPet())
12695 pet->SetPvP(state);
12696 if(Unit* charmed = GetCharm())
12697 charmed->SetPvP(state);
12699 for (int8 i = 0; i < MAX_TOTEM; ++i)
12700 if(m_TotemSlot[i])
12701 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
12702 totem->SetPvP(state);
12705 void Unit::KnockBackFrom(Unit* target, float horizintalSpeed, float verticalSpeed)
12707 float angle = this == target ? GetOrientation() + M_PI : target->GetAngle(this);
12708 float vsin = sin(angle);
12709 float vcos = cos(angle);
12711 // Effect propertly implemented only for players
12712 if(GetTypeId()==TYPEID_PLAYER)
12714 WorldPacket data(SMSG_MOVE_KNOCK_BACK, 8+4+4+4+4+4);
12715 data.append(GetPackGUID());
12716 data << uint32(0); // Sequence
12717 data << float(vcos); // x direction
12718 data << float(vsin); // y direction
12719 data << float(horizintalSpeed); // Horizontal speed
12720 data << float(-verticalSpeed); // Z Movement speed (vertical)
12721 ((Player*)this)->GetSession()->SendPacket(&data);
12723 else
12725 float dis = horizintalSpeed;
12727 float ox, oy, oz;
12728 GetPosition(ox, oy, oz);
12730 float fx = ox + dis * vcos;
12731 float fy = oy + dis * vsin;
12732 float fz = oz;
12734 float fx2, fy2, fz2; // getObjectHitPos overwrite last args in any result case
12735 if(VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), ox,oy,oz+0.5, fx,fy,oz+0.5,fx2,fy2,fz2, -0.5))
12737 fx = fx2;
12738 fy = fy2;
12739 fz = fz2;
12740 UpdateGroundPositionZ(fx, fy, fz);
12743 //FIXME: this mostly hack, must exist some packet for proper creature move at client side
12744 // with CreatureRelocation at server side
12745 NearTeleportTo(fx, fy, fz, GetOrientation(), this == target);
12749 float Unit::GetCombatRatingReduction(CombatRating cr) const
12751 if (GetTypeId() == TYPEID_PLAYER)
12752 return ((Player const*)this)->GetRatingBonusValue(cr);
12753 else if (((Creature const*)this)->isPet())
12755 // Player's pet have 0.4 resilience from owner
12756 if (Unit* owner = GetOwner())
12757 if(owner->GetTypeId() == TYPEID_PLAYER)
12758 return ((Player*)owner)->GetRatingBonusValue(cr) * 0.4f;
12761 return 0.0f;
12764 uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
12766 float percent = GetCombatRatingReduction(cr) * rate;
12767 if (percent > cap)
12768 percent = cap;
12769 return uint32 (percent * damage / 100.0f);
12772 void Unit::SendThreatUpdate()
12774 ThreatList const& tlist = getThreatManager().getThreatList();
12775 if (uint32 count = tlist.size())
12777 sLog.outDebug( "WORLD: Send SMSG_THREAT_UPDATE Message" );
12778 WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
12779 data.append(GetPackGUID());
12780 data << uint32(count);
12781 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
12783 data.appendPackGUID((*itr)->getUnitGuid());
12784 data << uint32((*itr)->getThreat());
12786 SendMessageToSet(&data, false);
12790 void Unit::SendHighestThreatUpdate(HostileReference* pHostilReference)
12792 ThreatList const& tlist = getThreatManager().getThreatList();
12793 if (uint32 count = tlist.size())
12795 sLog.outDebug( "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message" );
12796 WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
12797 data.append(GetPackGUID());
12798 data.appendPackGUID(pHostilReference->getUnitGuid());
12799 data << uint32(count);
12800 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
12802 data.appendPackGUID((*itr)->getUnitGuid());
12803 data << uint32((*itr)->getThreat());
12805 SendMessageToSet(&data, false);
12809 void Unit::SendThreatClear()
12811 sLog.outDebug( "WORLD: Send SMSG_THREAT_CLEAR Message" );
12812 WorldPacket data(SMSG_THREAT_CLEAR, 8);
12813 data.append(GetPackGUID());
12814 SendMessageToSet(&data, false);
12817 void Unit::SendThreatRemove(HostileReference* pHostileReference)
12819 sLog.outDebug( "WORLD: Send SMSG_THREAT_REMOVE Message" );
12820 WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
12821 data.append(GetPackGUID());
12822 data.appendPackGUID(pHostileReference->getUnitGuid());
12823 SendMessageToSet(&data, false);
12826 void Unit::StopAttackFaction(uint32 faction_id)
12828 if (Unit* victim = getVictim())
12830 if (victim->getFactionTemplateEntry()->faction==faction_id)
12832 AttackStop();
12833 if (IsNonMeleeSpellCasted(false))
12834 InterruptNonMeleeSpells(false);
12836 // melee and ranged forced attack cancel
12837 if (GetTypeId() == TYPEID_PLAYER)
12838 ((Player*)this)->SendAttackSwingCancelAttack();
12842 AttackerSet const& attackers = getAttackers();
12843 for(AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
12845 if ((*itr)->getFactionTemplateEntry()->faction==faction_id)
12847 (*itr)->AttackStop();
12848 itr = attackers.begin();
12850 else
12851 ++itr;
12854 getHostileRefManager().deleteReferencesForFaction(faction_id);
12856 if(Pet* pet = GetPet())
12857 pet->StopAttackFaction(faction_id);
12858 if(Unit* charm = GetCharm())
12859 charm->StopAttackFaction(faction_id);
12861 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
12862 if(Unit* guardian = Unit::GetUnit(*this,*itr))
12863 guardian->StopAttackFaction(faction_id);