[9986] Talent 51459 and ranks affect only melee auto-attacks.
[getmangos.git] / src / game / Unit.cpp
blob3644450ac4094c75eb186c676b7eab473898cf0a
1 /*
2 * Copyright (C) 2005-2010 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 "ObjectGuid.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 "TemporarySummon.h"
39 #include "Formulas.h"
40 #include "Pet.h"
41 #include "Util.h"
42 #include "Totem.h"
43 #include "BattleGround.h"
44 #include "InstanceSaveMgr.h"
45 #include "GridNotifiersImpl.h"
46 #include "CellImpl.h"
47 #include "Path.h"
48 #include "Traveller.h"
49 #include "VMapFactory.h"
50 #include "MovementGenerator.h"
52 #include <math.h>
53 #include <stdarg.h>
55 float baseMoveSpeed[MAX_MOVE_TYPE] =
57 2.5f, // MOVE_WALK
58 7.0f, // MOVE_RUN
59 2.5f, // MOVE_RUN_BACK
60 4.722222f, // MOVE_SWIM
61 4.5f, // MOVE_SWIM_BACK
62 3.141594f, // MOVE_TURN_RATE
63 7.0f, // MOVE_FLIGHT
64 4.5f, // MOVE_FLIGHT_BACK
65 3.14f // MOVE_PITCH_RATE
68 // Used for prepare can/can`t trigger aura
69 static bool InitTriggerAuraData();
70 // Define can trigger auras
71 static bool isTriggerAura[TOTAL_AURAS];
72 // Define can`t trigger auras (need for disable second trigger)
73 static bool isNonTriggerAura[TOTAL_AURAS];
74 // Prepare lists
75 static bool procPrepared = InitTriggerAuraData();
77 void MovementInfo::Read(ByteBuffer &data)
79 data >> moveFlags;
80 data >> moveFlags2;
81 data >> time;
82 data >> pos.x;
83 data >> pos.y;
84 data >> pos.z;
85 data >> pos.o;
87 if(HasMovementFlag(MOVEFLAG_ONTRANSPORT))
89 data >> t_guid.ReadAsPacked();
90 data >> t_pos.x;
91 data >> t_pos.y;
92 data >> t_pos.z;
93 data >> t_pos.o;
94 data >> t_time;
95 data >> t_seat;
97 if(moveFlags2 & MOVEFLAG2_INTERP_MOVEMENT)
98 data >> t_time2;
101 if((HasMovementFlag(MovementFlags(MOVEFLAG_SWIMMING | MOVEFLAG_FLYING))) || (moveFlags2 & MOVEFLAG2_ALLOW_PITCHING))
103 data >> s_pitch;
106 data >> fallTime;
108 if(HasMovementFlag(MOVEFLAG_FALLING))
110 data >> j_velocity;
111 data >> j_sinAngle;
112 data >> j_cosAngle;
113 data >> j_xyspeed;
116 if(HasMovementFlag(MOVEFLAG_SPLINE_ELEVATION))
118 data >> u_unk1;
122 void MovementInfo::Write(ByteBuffer &data) const
124 data << moveFlags;
125 data << moveFlags2;
126 data << time;
127 data << pos.x;
128 data << pos.y;
129 data << pos.z;
130 data << pos.o;
132 if(HasMovementFlag(MOVEFLAG_ONTRANSPORT))
134 data << t_guid.WriteAsPacked();
135 data << t_pos.x;
136 data << t_pos.y;
137 data << t_pos.z;
138 data << t_pos.o;
139 data << t_time;
140 data << t_seat;
142 if(moveFlags2 & MOVEFLAG2_INTERP_MOVEMENT)
143 data << t_time2;
146 if((HasMovementFlag(MovementFlags(MOVEFLAG_SWIMMING | MOVEFLAG_FLYING))) || (moveFlags2 & MOVEFLAG2_ALLOW_PITCHING))
148 data << s_pitch;
151 data << fallTime;
153 if(HasMovementFlag(MOVEFLAG_FALLING))
155 data << j_velocity;
156 data << j_sinAngle;
157 data << j_cosAngle;
158 data << j_xyspeed;
161 if(HasMovementFlag(MOVEFLAG_SPLINE_ELEVATION))
163 data << u_unk1;
167 Unit::Unit()
168 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostileRefManager(this)
170 m_objectType |= TYPEMASK_UNIT;
171 m_objectTypeId = TYPEID_UNIT;
173 m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
175 m_attackTimer[BASE_ATTACK] = 0;
176 m_attackTimer[OFF_ATTACK] = 0;
177 m_attackTimer[RANGED_ATTACK] = 0;
178 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
179 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
180 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
182 m_extraAttacks = 0;
184 m_state = 0;
185 m_form = FORM_NONE;
186 m_deathState = ALIVE;
188 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
189 m_currentSpells[i] = NULL;
191 m_castCounter = 0;
193 m_addDmgOnce = 0;
195 for(int i = 0; i < MAX_TOTEM_SLOT; ++i)
196 m_TotemSlot[i] = 0;
198 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
199 //m_Aura = NULL;
200 //m_AurasCheck = 2000;
201 //m_removeAuraTimer = 4;
202 m_AurasUpdateIterator = m_Auras.end();
203 m_AuraFlags = 0;
205 m_Visibility = VISIBILITY_ON;
207 m_detectInvisibilityMask = 0;
208 m_invisibilityMask = 0;
209 m_transform = 0;
210 m_ShapeShiftFormSpellId = 0;
211 m_canModifyStats = false;
213 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
214 m_spellImmune[i].clear();
215 for (int i = 0; i < UNIT_MOD_END; ++i)
217 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
218 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
219 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
220 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
222 // implement 50% base damage from offhand
223 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
225 for (int i = 0; i < MAX_ATTACK; ++i)
227 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
228 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
230 for (int i = 0; i < MAX_STATS; ++i)
231 m_createStats[i] = 0.0f;
233 m_attacking = NULL;
234 m_modMeleeHitChance = 0.0f;
235 m_modRangedHitChance = 0.0f;
236 m_modSpellHitChance = 0.0f;
237 m_baseSpellCritChance = 5;
239 m_CombatTimer = 0;
240 m_lastManaUseTimer = 0;
242 //m_victimThreat = 0.0f;
243 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
244 m_threatModifier[i] = 1.0f;
245 m_isSorted = true;
246 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
247 m_speed_rate[i] = 1.0f;
249 m_charmInfo = NULL;
251 // remove aurastates allowing special moves
252 for(int i=0; i < MAX_REACTIVE; ++i)
253 m_reactiveTimer[i] = 0;
256 Unit::~Unit()
258 // set current spells as deletable
259 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
261 if (m_currentSpells[i])
263 m_currentSpells[i]->SetReferencedFromCurrent(false);
264 m_currentSpells[i] = NULL;
268 if (m_charmInfo)
269 delete m_charmInfo;
271 // those should be already removed at "RemoveFromWorld()" call
272 ASSERT(m_gameObj.size() == 0);
273 ASSERT(m_dynObjGUIDs.size() == 0);
274 ASSERT(m_deletedAuras.size() == 0);
277 void Unit::Update( uint32 p_time )
279 if(!IsInWorld())
280 return;
282 /*if(p_time > m_AurasCheck)
284 m_AurasCheck = 2000;
285 _UpdateAura();
286 }else
287 m_AurasCheck -= p_time;*/
289 // WARNING! Order of execution here is important, do not change.
290 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
291 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
292 m_Events.Update( p_time );
293 _UpdateSpells( p_time );
295 CleanupDeletedAuras();
297 if (m_lastManaUseTimer)
299 if (p_time >= m_lastManaUseTimer)
300 m_lastManaUseTimer = 0;
301 else
302 m_lastManaUseTimer -= p_time;
305 if (CanHaveThreatList())
306 getThreatManager().UpdateForClient(p_time);
308 // update combat timer only for players and pets
309 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
311 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
312 // targets without stopping half way there and running off.
313 // These flags are reset after target dies or another command is given.
314 if (m_HostileRefManager.isEmpty())
316 // m_CombatTimer set at aura start and it will be freeze until aura removing
317 if (m_CombatTimer <= p_time)
318 CombatStop();
319 else
320 m_CombatTimer -= p_time;
324 if (uint32 base_att = getAttackTimer(BASE_ATTACK))
326 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
329 // update abilities available only for fraction of time
330 UpdateReactives( p_time );
332 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
333 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
334 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
336 i_motionMaster.UpdateMotion(p_time);
339 bool Unit::haveOffhandWeapon() const
341 if(GetTypeId() == TYPEID_PLAYER)
342 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true,true);
343 else
344 return false;
347 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, SplineType type, SplineFlags flags, uint32 Time, Player* player, ...)
350 va_list vargs;
351 va_start(vargs,player);
353 float moveTime = (float)Time;
355 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
356 data << GetPackGUID();
357 data << uint8(0); // new in 3.1 bool, used to toggle MOVEFLAG2_UNK4 = 0x0040 on client side
358 data << GetPositionX() << GetPositionY() << GetPositionZ();
359 data << uint32(getMSTime());
361 data << uint8(type); // unknown
362 switch(type)
364 case SPLINETYPE_NORMAL: // normal packet
365 break;
366 case SPLINETYPE_STOP: // stop packet (raw pos?)
367 va_end(vargs);
368 SendMessageToSet( &data, true );
369 return;
370 case SPLINETYPE_FACINGSPOT: // facing spot, not used currently
372 data << float(va_arg(vargs,double));
373 data << float(va_arg(vargs,double));
374 data << float(va_arg(vargs,double));
375 break;
377 case SPLINETYPE_FACINGTARGET:
378 data << uint64(va_arg(vargs,uint64));
379 break;
380 case SPLINETYPE_FACINGANGLE: // not used currently
381 data << float(va_arg(vargs,double)); // facing angle
382 break;
385 data << uint32(flags);
387 // enable me if things goes wrong or looks ugly, it is however an old hack
388 // if(flags & SPLINEFLAG_WALKMODE)
389 // moveTime *= 1.05f;
391 data << uint32(moveTime); // Time in between points
392 data << uint32(1); // 1 single waypoint
393 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
395 va_end(vargs);
397 if(player)
398 player->GetSession()->SendPacket(&data);
399 else
400 SendMessageToSet( &data, true );
403 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
405 if (!transitTime)
407 if(GetTypeId()==TYPEID_PLAYER)
409 Traveller<Player> traveller(*(Player*)this);
410 transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
412 else
414 Traveller<Creature> traveller(*(Creature*)this);
415 transitTime = traveller.GetTotalTrevelTimeTo(x, y, z);
418 //float orientation = (float)atan2((double)dy, (double)dx);
419 SplineFlags flags = GetTypeId() == TYPEID_PLAYER ? SPLINEFLAG_WALKMODE : ((Creature*)this)->GetSplineFlags();
420 SendMonsterMove(x, y, z, SPLINETYPE_NORMAL, flags, transitTime, player);
423 void Unit::BuildHeartBeatMsg(WorldPacket *data) const
425 MovementFlags move_flags = GetTypeId()==TYPEID_PLAYER
426 ? ((Player const*)this)->m_movementInfo.GetMovementFlags()
427 : MOVEFLAG_NONE;
429 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
430 *data << GetPackGUID();
431 *data << uint32(move_flags); // movement flags
432 *data << uint16(0); // 2.3.0
433 *data << uint32(getMSTime()); // time
434 *data << float(GetPositionX());
435 *data << float(GetPositionY());
436 *data << float(GetPositionZ());
437 *data << float(GetOrientation());
438 *data << uint32(0);
441 void Unit::resetAttackTimer(WeaponAttackType type)
443 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
446 bool Unit::canReachWithAttack(Unit *pVictim) const
448 ASSERT(pVictim);
449 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
450 if( reach <= 0.0f )
451 reach = 1.0f;
452 return IsWithinDistInMap(pVictim, reach);
455 void Unit::RemoveSpellsCausingAura(AuraType auraType)
457 if (auraType >= TOTAL_AURAS) return;
458 AuraList::const_iterator iter, next;
459 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
461 next = iter;
462 ++next;
464 if (*iter)
466 RemoveAurasDueToSpell((*iter)->GetId());
467 if (!m_modAuras[auraType].empty())
468 next = m_modAuras[auraType].begin();
469 else
470 return;
475 bool Unit::HasAuraType(AuraType auraType) const
477 return (!m_modAuras[auraType].empty());
480 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
481 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
483 if(!HasAuraType(auraType))
484 return;
486 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
487 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
488 float chance = float(damage) / max_dmg * 100.0f;
489 if (roll_chance_f(chance))
490 RemoveSpellsCausingAura(auraType);
493 void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
495 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
497 if(absorb)
498 *absorb += damage;
499 damage = 0;
500 return;
503 //You don't lose health from damage taken from another player while in a sanctuary
504 //You still see it in the combat log though
505 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
507 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
508 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
510 if(absorb)
511 *absorb += damage;
512 damage = 0;
516 uint32 originalDamage = damage;
518 //Script Event damage Deal
519 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
520 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
521 //Script Event damage taken
522 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
523 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
525 if(absorb && originalDamage > damage)
526 *absorb += (originalDamage - damage);
529 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
531 // remove affects from victim (including from 0 damage and DoTs)
532 if(pVictim != this)
533 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
535 // remove affects from attacker at any non-DoT damage (including 0 damage)
536 if( damagetype != DOT)
538 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
539 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
541 if(pVictim != this)
542 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
544 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
545 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
548 if(!damage)
550 // Rage from physical damage received .
551 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
552 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
554 return 0;
556 if (!spellProto || !IsSpellHaveAura(spellProto,SPELL_AURA_MOD_FEAR))
557 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
558 // root type spells do not dispel the root effect
559 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsSpellHaveAura(spellProto,SPELL_AURA_MOD_ROOT)))
560 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
562 // no xp,health if type 8 /critters/
563 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
565 pVictim->setDeathState(JUST_DIED);
566 pVictim->SetHealth(0);
568 // allow loot only if has loot_id in creature_template
569 ((Creature*)pVictim)->PrepareBodyLootState();
571 // some critters required for quests (need normal entry instead possible heroic in any cases)
572 if(GetTypeId() == TYPEID_PLAYER)
573 if(CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
574 ((Player*)this)->KilledMonster(normalInfo,pVictim->GetObjectGuid());
576 return damage;
579 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamageStart");
581 uint32 health = pVictim->GetHealth();
582 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"deal dmg:%d to health:%d ",damage,health);
584 // duel ends when player has 1 or less hp
585 bool duel_hasEnded = false;
586 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
588 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
589 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
590 damage = health-1;
592 duel_hasEnded = true;
594 //Get in CombatState
595 if(pVictim != this && damagetype != DOT)
597 SetInCombatWith(pVictim);
598 pVictim->SetInCombatWith(this);
600 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
601 SetContestedPvP(attackedPlayer);
604 // Rage from Damage made (only from direct weapon damage)
605 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
607 uint32 weaponSpeedHitFactor;
609 switch(cleanDamage->attackType)
611 case BASE_ATTACK:
613 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
614 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
615 else
616 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
618 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
620 break;
622 case OFF_ATTACK:
624 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
625 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
626 else
627 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
629 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
631 break;
633 case RANGED_ATTACK:
634 break;
638 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
640 Player *killer = ((Player*)this);
642 // in bg, count dmg if victim is also a player
643 if (pVictim->GetTypeId()==TYPEID_PLAYER)
645 if (BattleGround *bg = killer->GetBattleGround())
647 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
648 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
652 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
653 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
656 if (pVictim->GetTypeId() == TYPEID_PLAYER)
657 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
659 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->HasLootRecipient())
660 ((Creature*)pVictim)->SetLootRecipient(this);
662 if (health <= damage)
664 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamage: victim just died");
666 // find player: owner of controlled `this` or `this` itself maybe
667 // for loot will be sued only if group_tap==NULL
668 Player *player_tap = GetCharmerOrOwnerPlayerOrPlayerItself();
669 Group *group_tap = NULL;
671 // find owner of pVictim, used for creature cases, AI calls
672 Unit* pOwner = pVictim->GetCharmerOrOwner();
674 // in creature kill case group/player tap stored for creature
675 if (pVictim->GetTypeId() == TYPEID_UNIT)
677 group_tap = ((Creature*)pVictim)->GetGroupLootRecipient();
679 if (Player* recipient = ((Creature*)pVictim)->GetOriginalLootRecipient())
680 player_tap = recipient;
682 // in player kill case group tap selected by player_tap (killer-player itself, or charmer, or owner, etc)
683 else
685 if (player_tap)
686 group_tap = player_tap->GetGroup();
689 if (pVictim->GetTypeId() == TYPEID_PLAYER)
691 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
692 if (player_tap)
693 player_tap->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL,1,0,pVictim);
696 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
697 if(player_tap && player_tap != pVictim)
699 player_tap->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
701 WorldPacket data(SMSG_PARTYKILLLOG, (8+8)); //send event PARTY_KILL
702 data << player_tap->GetObjectGuid(); //player with killing blow
703 data << pVictim->GetObjectGuid(); //victim
705 if (group_tap)
706 group_tap->BroadcastPacket(&data, false, group_tap->GetMemberGroup(player_tap->GetGUID()),player_tap->GetGUID());
708 player_tap->SendDirectMessage(&data);
711 // Reward player, his pets, and group/raid members
712 if (player_tap != pVictim)
714 if (group_tap)
715 group_tap->RewardGroupAtKill(pVictim, player_tap);
716 else if (player_tap)
717 player_tap->RewardSinglePlayerAtKill(pVictim);
720 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamageAttackStop");
722 // stop combat
723 pVictim->CombatStop();
724 pVictim->getHostileRefManager().deleteReferences();
726 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
728 // if talent known but not triggered (check priest class for speedup check)
729 Aura* spiritOfRedemtionTalentReady = NULL;
730 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
731 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
733 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
734 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
736 if((*itr)->GetSpellProto()->SpellIconID==1654)
738 spiritOfRedemtionTalentReady = *itr;
739 break;
744 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"SET JUST_DIED");
745 if(!spiritOfRedemtionTalentReady)
746 pVictim->setDeathState(JUST_DIED);
748 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamageHealth1");
750 if(spiritOfRedemtionTalentReady)
752 // save value before aura remove
753 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
754 if(!ressSpellId)
755 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
757 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
758 pVictim->RemoveAllAurasOnDeath();
760 // restore for use at real death
761 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
763 // FORM_SPIRITOFREDEMPTION and related auras
764 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
766 else
767 pVictim->SetHealth(0);
769 // remember victim PvP death for corpse type and corpse reclaim delay
770 // at original death (not at SpiritOfRedemtionTalent timeout)
771 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
772 ((Player*)pVictim)->SetPvPDeath(player_tap != NULL);
774 // Call KilledUnit for creatures
775 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
776 ((Creature*)this)->AI()->KilledUnit(pVictim);
778 // achievement stuff
779 if (pVictim->GetTypeId() == TYPEID_PLAYER)
781 if (GetTypeId() == TYPEID_UNIT)
782 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
783 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
784 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
787 // 10% durability loss on death
788 // clean InHateListOf
789 if (pVictim->GetTypeId() == TYPEID_PLAYER)
791 // only if not player and not controlled by player pet. And not at BG
792 if (durabilityLoss && !player_tap && !((Player*)pVictim)->InBattleGround())
794 DEBUG_LOG("We are dead, loosing 10 percents durability");
795 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
796 // durability lost message
797 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
798 ((Player*)pVictim)->GetSession()->SendPacket(&data);
801 else // creature died
803 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamageNotPlayer");
804 Creature *cVictim = (Creature*)pVictim;
806 if(!cVictim->isPet())
808 cVictim->DeleteThreatList();
809 // only lootable if it has loot or can drop gold
810 cVictim->PrepareBodyLootState();
812 // Call creature just died function
813 if (cVictim->AI())
814 cVictim->AI()->JustDied(this);
816 if (cVictim->isTemporarySummon())
818 TemporarySummon* pSummon = (TemporarySummon*)cVictim;
819 if (pSummon->GetSummonerGuid().IsCreature())
820 if(Creature* pSummoner = cVictim->GetMap()->GetCreature(pSummon->GetSummonerGuid()))
821 if (pSummoner->AI())
822 pSummoner->AI()->SummonedCreatureJustDied(cVictim);
824 else if (pOwner && pOwner->GetTypeId() == TYPEID_UNIT)
826 if (((Creature*)pOwner)->AI())
827 ((Creature*)pOwner)->AI()->SummonedCreatureJustDied(cVictim);
830 // Dungeon specific stuff, only applies to players killing creatures
831 if(cVictim->GetInstanceId())
833 Map *m = cVictim->GetMap();
834 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
835 // TODO: do instance binding anyway if the charmer/owner is offline
837 if(m->IsDungeon() && creditedPlayer)
839 if (m->IsRaidOrHeroicDungeon())
841 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
842 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
844 else
846 // the reset time is set but not added to the scheduler
847 // until the players leave the instance
848 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
849 if(InstanceSave *save = sInstanceSaveMgr.GetInstanceSave(cVictim->GetInstanceId()))
850 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
856 // last damage from non duel opponent or opponent controlled creature
857 if(duel_hasEnded)
859 ASSERT(pVictim->GetTypeId()==TYPEID_PLAYER);
860 Player *he = (Player*)pVictim;
862 ASSERT(he->duel);
864 he->duel->opponent->CombatStopWithPets(true);
865 he->CombatStopWithPets(true);
867 he->DuelComplete(DUEL_INTERUPTED);
870 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
871 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
873 Player *killed = ((Player*)pVictim);
874 if(BattleGround *bg = killed->GetBattleGround())
875 if(player_tap)
876 bg->HandleKillPlayer(killed, player_tap);
878 else if(pVictim->GetTypeId() == TYPEID_UNIT)
880 if (player_tap)
881 if (BattleGround *bg = player_tap->GetBattleGround())
882 bg->HandleKillUnit((Creature*)pVictim, player_tap);
885 else // if (health <= damage)
887 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamageAlive");
889 if (pVictim->GetTypeId() == TYPEID_PLAYER)
890 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
892 pVictim->ModifyHealth(- (int32)damage);
894 if(damagetype != DOT)
896 if(!getVictim())
898 // if not have main target then attack state with target (including AI call)
899 //start melee attacks only after melee hit
900 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
903 // if damage pVictim call AI reaction
904 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
905 ((Creature*)pVictim)->AI()->AttackedBy(this);
908 // polymorphed, hex and other negative transformed cases
909 uint32 morphSpell = pVictim->getTransForm();
910 if (morphSpell && !IsPositiveSpell(morphSpell))
912 if (SpellEntry const* morphEntry = sSpellStore.LookupEntry(morphSpell))
914 if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_CONFUSE))
915 pVictim->RemoveAurasDueToSpell(morphSpell);
916 else if (IsSpellHaveAura(morphEntry, SPELL_AURA_MOD_PACIFY_SILENCE))
917 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_PACIFY_SILENCE, damage);
921 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
923 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
924 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
926 if (pVictim->GetTypeId() != TYPEID_PLAYER)
928 if(spellProto && IsDamageToThreatSpell(spellProto))
929 pVictim->AddThreat(this, float(damage*2), (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
930 else
931 pVictim->AddThreat(this, float(damage), (cleanDamage && cleanDamage->hitOutCome == MELEE_HIT_CRIT), damageSchoolMask, spellProto);
933 else // victim is a player
935 // Rage from damage received
936 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
938 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
939 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
942 // random durability for items (HIT TAKEN)
943 if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE)))
945 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
946 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
950 if(GetTypeId()==TYPEID_PLAYER)
952 // random durability for items (HIT DONE)
953 if (roll_chance_f(sWorld.getConfig(CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE)))
955 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
956 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
960 // TODO: Store auras by interrupt flag to speed this up.
961 AuraMap& vAuras = pVictim->GetAuras();
962 for (AuraMap::const_iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
964 const SpellEntry *se = i->second->GetSpellProto();
965 next = i; ++next;
966 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
967 continue;
968 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
970 bool remove = true;
971 if (se->procFlags & (1<<3))
973 if (!roll_chance_i(se->procChance))
974 remove = false;
976 if (remove)
978 pVictim->RemoveAurasDueToSpell(i->second->GetId());
979 // FIXME: this may cause the auras with proc chance to be rerolled several times
980 next = vAuras.begin();
985 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
987 if( damagetype != DOT )
989 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
991 // skip channeled spell (processed differently below)
992 if (i == CURRENT_CHANNELED_SPELL)
993 continue;
995 if(Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i)))
997 if(spell->getState() == SPELL_STATE_PREPARING)
999 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
1000 pVictim->InterruptSpell(CurrentSpellTypes(i));
1001 else
1002 spell->Delayed();
1008 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
1010 if (spell->getState() == SPELL_STATE_CASTING)
1012 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
1013 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
1015 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
1016 spell->DelayedChannel();
1018 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
1020 DETAIL_LOG("Spell %u canceled at damage!",spell->m_spellInfo->Id);
1021 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
1024 else if (spell->getState() == SPELL_STATE_DELAYED)
1025 // break channeled spell in delayed state on damage
1027 DETAIL_LOG("Spell %u canceled at damage!",spell->m_spellInfo->Id);
1028 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
1033 // last damage from duel opponent
1034 if(duel_hasEnded)
1036 ASSERT(pVictim->GetTypeId()==TYPEID_PLAYER);
1037 Player *he = (Player*)pVictim;
1039 ASSERT(he->duel);
1041 he->SetHealth(1);
1043 he->duel->opponent->CombatStopWithPets(true);
1044 he->CombatStopWithPets(true);
1046 he->CastSpell(he, 7267, true); // beg
1047 he->DuelComplete(DUEL_WON);
1051 DEBUG_FILTER_LOG(LOG_FILTER_DAMAGE,"DealDamageEnd returned %d damage", damage);
1053 return damage;
1056 void Unit::CastStop(uint32 except_spellid)
1058 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
1059 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
1060 InterruptSpell(CurrentSpellTypes(i),false);
1063 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster)
1065 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
1067 if(!spellInfo)
1069 sLog.outError("CastSpell: unknown spell id %i by caster: %s", spellId, GetObjectGuid().GetString().c_str());
1070 return;
1073 CastSpell(Victim, spellInfo, triggered, castItem, triggeredByAura, originalCaster);
1076 void Unit::CastSpell(Unit* Victim, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster)
1078 if(!spellInfo)
1080 sLog.outError("CastSpell: unknown spell by caster: %s", GetObjectGuid().GetString().c_str());
1081 return;
1084 if (castItem)
1085 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id);
1087 if(originalCaster.IsEmpty() && triggeredByAura)
1088 originalCaster = triggeredByAura->GetCasterGUID();
1090 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
1092 SpellCastTargets targets;
1093 targets.setUnitTarget( Victim );
1094 spell->m_CastItem = castItem;
1095 spell->prepare(&targets, triggeredByAura);
1098 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster)
1100 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
1102 if(!spellInfo)
1104 sLog.outError("CastCustomSpell: unknown spell id %i by caster: %s", spellId, GetObjectGuid().GetString().c_str());
1105 return;
1108 CastCustomSpell(Victim, spellInfo, bp0, bp1, bp2, triggered, castItem, triggeredByAura, originalCaster);
1111 void Unit::CastCustomSpell(Unit* Victim, SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster)
1113 if(!spellInfo)
1115 sLog.outError("CastCustomSpell: unknown spell by caster: %s", GetObjectGuid().GetString().c_str());
1116 return;
1119 if (castItem)
1120 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id);
1122 if(originalCaster.IsEmpty() && triggeredByAura)
1123 originalCaster = triggeredByAura->GetCasterGUID();
1125 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
1127 if(bp0)
1128 spell->m_currentBasePoints[EFFECT_INDEX_0] = *bp0;
1130 if(bp1)
1131 spell->m_currentBasePoints[EFFECT_INDEX_1] = *bp1;
1133 if(bp2)
1134 spell->m_currentBasePoints[EFFECT_INDEX_2] = *bp2;
1136 SpellCastTargets targets;
1137 targets.setUnitTarget( Victim );
1138 spell->m_CastItem = castItem;
1139 spell->prepare(&targets, triggeredByAura);
1142 // used for scripting
1143 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster)
1145 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
1147 if(!spellInfo)
1149 sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s", spellId, GetObjectGuid().GetString().c_str());
1150 return;
1153 CastSpell(x, y, z, spellInfo, triggered, castItem, triggeredByAura, originalCaster);
1156 // used for scripting
1157 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, ObjectGuid originalCaster)
1159 if(!spellInfo)
1161 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s", GetObjectGuid().GetString().c_str());
1162 return;
1165 if (castItem)
1166 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "WORLD: cast Item spellId - %i", spellInfo->Id);
1168 if(originalCaster.IsEmpty() && triggeredByAura)
1169 originalCaster = triggeredByAura->GetCasterGUID();
1171 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
1173 SpellCastTargets targets;
1174 targets.setDestination(x, y, z);
1175 spell->m_CastItem = castItem;
1176 spell->prepare(&targets, triggeredByAura);
1179 // Obsolete func need remove, here only for comotability vs another patches
1180 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
1182 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
1183 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
1184 CalculateSpellDamage(&damageInfo, damage, spellInfo);
1185 damageInfo.target->CalculateAbsorbResistBlock(this, &damageInfo, spellInfo);
1186 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
1187 SendSpellNonMeleeDamageLog(&damageInfo);
1188 DealSpellDamage(&damageInfo, true);
1189 return damageInfo.damage;
1192 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
1194 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
1195 Unit *pVictim = damageInfo->target;
1197 if (damage < 0)
1198 return;
1200 if(!this || !pVictim)
1201 return;
1202 if(!this->isAlive() || !pVictim->isAlive())
1203 return;
1205 // Check spell crit chance
1206 bool crit = IsSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1208 // damage bonus (per damage class)
1209 switch (spellInfo->DmgClass)
1211 // Melee and Ranged Spells
1212 case SPELL_DAMAGE_CLASS_RANGED:
1213 case SPELL_DAMAGE_CLASS_MELEE:
1215 //Calculate damage bonus
1216 damage = MeleeDamageBonusDone(pVictim, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE);
1217 damage = pVictim->MeleeDamageBonusTaken(this, damage, attackType, spellInfo, SPELL_DIRECT_DAMAGE);
1219 // if crit add critical bonus
1220 if (crit)
1222 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1223 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1224 // Resilience - reduce crit damage
1225 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1226 if (attackType != RANGED_ATTACK)
1227 damage -= pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1228 else
1229 damage -= pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1232 break;
1233 // Magical Attacks
1234 case SPELL_DAMAGE_CLASS_NONE:
1235 case SPELL_DAMAGE_CLASS_MAGIC:
1237 // Calculate damage bonus
1238 damage = SpellDamageBonusDone(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1239 damage = pVictim->SpellDamageBonusTaken(this, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1241 // If crit add critical bonus
1242 if (crit)
1244 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1245 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1246 // Resilience - reduce crit damage
1247 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1248 damage -= pVictim->GetSpellCritDamageReduction(redunction_affected_damage);
1251 break;
1254 // only from players
1255 if (GetTypeId() == TYPEID_PLAYER)
1257 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1258 damage -= pVictim->GetSpellDamageReduction(redunction_affected_damage);
1261 // damage mitigation
1262 if (damage > 0)
1264 // physical damage => armor
1265 if (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL)
1267 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageSchoolMask);
1268 damage = damage - armor_affected_damage + CalcArmorReducedDamage(pVictim, armor_affected_damage);
1271 else
1272 damage = 0;
1273 damageInfo->damage = damage;
1276 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1278 if (!damageInfo)
1279 return;
1281 Unit *pVictim = damageInfo->target;
1283 if(!this || !pVictim)
1284 return;
1286 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1287 return;
1289 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1290 if (spellProto == NULL)
1292 sLog.outError("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1293 return;
1296 //You don't lose health from damage taken from another player while in a sanctuary
1297 //You still see it in the combat log though
1298 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1300 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1301 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1302 return;
1305 // Call default DealDamage (send critical in hit info for threat calculation)
1306 CleanDamage cleanDamage(0, BASE_ATTACK, damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT ? MELEE_HIT_CRIT : MELEE_HIT_NORMAL);
1307 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1310 //TODO for melee need create structure as in
1311 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1313 damageInfo->attacker = this;
1314 damageInfo->target = pVictim;
1315 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1316 damageInfo->attackType = attackType;
1317 damageInfo->damage = 0;
1318 damageInfo->cleanDamage = 0;
1319 damageInfo->absorb = 0;
1320 damageInfo->resist = 0;
1321 damageInfo->blocked_amount = 0;
1323 damageInfo->TargetState = 0;
1324 damageInfo->HitInfo = 0;
1325 damageInfo->procAttacker = PROC_FLAG_NONE;
1326 damageInfo->procVictim = PROC_FLAG_NONE;
1327 damageInfo->procEx = PROC_EX_NONE;
1328 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1330 if(!this || !pVictim)
1331 return;
1332 if(!this->isAlive() || !pVictim->isAlive())
1333 return;
1335 // Select HitInfo/procAttacker/procVictim flag based on attack type
1336 switch (attackType)
1338 case BASE_ATTACK:
1339 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
1340 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1341 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1342 break;
1343 case OFF_ATTACK:
1344 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1345 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1346 damageInfo->HitInfo = HITINFO_LEFTSWING;
1347 break;
1348 case RANGED_ATTACK:
1349 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1350 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1351 damageInfo->HitInfo = 0x08;// test
1352 break;
1353 default:
1354 break;
1357 // Physical Immune check
1358 if (damageInfo->target->IsImmunedToDamage(damageInfo->damageSchoolMask))
1360 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1361 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1363 damageInfo->procEx |=PROC_EX_IMMUNE;
1364 damageInfo->damage = 0;
1365 damageInfo->cleanDamage = 0;
1366 return;
1368 damage += CalculateDamage (damageInfo->attackType, false);
1369 // Add melee damage bonus
1370 damage = MeleeDamageBonusDone(damageInfo->target, damage, damageInfo->attackType);
1371 damage = damageInfo->target->MeleeDamageBonusTaken(this, damage, damageInfo->attackType);
1372 // Calculate armor reduction
1374 uint32 armor_affected_damage = CalcNotIgnoreDamageRedunction(damage,damageInfo->damageSchoolMask);
1375 damageInfo->damage = damage - armor_affected_damage + CalcArmorReducedDamage(damageInfo->target, armor_affected_damage);
1376 damageInfo->cleanDamage += damage - damageInfo->damage;
1378 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1380 // Disable parry or dodge for ranged attack
1381 if (damageInfo->attackType == RANGED_ATTACK)
1383 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1384 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1387 switch(damageInfo->hitOutCome)
1389 case MELEE_HIT_EVADE:
1391 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1392 damageInfo->TargetState = VICTIMSTATE_EVADES;
1394 damageInfo->procEx|=PROC_EX_EVADE;
1395 damageInfo->damage = 0;
1396 damageInfo->cleanDamage = 0;
1397 return;
1399 case MELEE_HIT_MISS:
1401 damageInfo->HitInfo |= HITINFO_MISS;
1402 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1404 damageInfo->procEx|=PROC_EX_MISS;
1405 damageInfo->damage = 0;
1406 damageInfo->cleanDamage = 0;
1407 break;
1409 case MELEE_HIT_NORMAL:
1410 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1411 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1412 break;
1413 case MELEE_HIT_CRIT:
1415 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1416 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1418 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1419 // Crit bonus calc
1420 damageInfo->damage += damageInfo->damage;
1421 int32 mod=0;
1422 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1423 if(damageInfo->attackType == RANGED_ATTACK)
1424 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1425 else
1426 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1428 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, SPELL_SCHOOL_MASK_NORMAL);
1430 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1432 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1433 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1434 if (mod!=0)
1435 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1437 // Resilience - reduce crit damage
1438 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damageInfo->damage,damageInfo->damageSchoolMask);
1439 uint32 resilienceReduction;
1440 if (attackType != RANGED_ATTACK)
1441 resilienceReduction = pVictim->GetMeleeCritDamageReduction(redunction_affected_damage);
1442 else
1443 resilienceReduction = pVictim->GetRangedCritDamageReduction(redunction_affected_damage);
1445 damageInfo->damage -= resilienceReduction;
1446 damageInfo->cleanDamage += resilienceReduction;
1447 break;
1449 case MELEE_HIT_PARRY:
1450 damageInfo->TargetState = VICTIMSTATE_PARRY;
1451 damageInfo->procEx |= PROC_EX_PARRY;
1452 damageInfo->cleanDamage += damageInfo->damage;
1453 damageInfo->damage = 0;
1454 break;
1456 case MELEE_HIT_DODGE:
1457 damageInfo->TargetState = VICTIMSTATE_DODGE;
1458 damageInfo->procEx|=PROC_EX_DODGE;
1459 damageInfo->cleanDamage += damageInfo->damage;
1460 damageInfo->damage = 0;
1461 break;
1462 case MELEE_HIT_BLOCK:
1464 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1465 damageInfo->HitInfo |= HITINFO_BLOCK;
1466 damageInfo->procEx |= PROC_EX_BLOCK;
1467 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1469 // Target has a chance to double the blocked amount if it has SPELL_AURA_MOD_BLOCK_CRIT_CHANCE
1470 if (roll_chance_i(pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_CRIT_CHANCE)))
1471 damageInfo->blocked_amount *= 2;
1473 if (damageInfo->blocked_amount >= damageInfo->damage)
1475 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1476 damageInfo->blocked_amount = damageInfo->damage;
1477 damageInfo->procEx |= PROC_EX_FULL_BLOCK;
1479 else
1480 damageInfo->procEx |= PROC_EX_NORMAL_HIT; // Partial blocks can still cause attacker procs
1482 damageInfo->damage -= damageInfo->blocked_amount;
1483 damageInfo->cleanDamage += damageInfo->blocked_amount;
1484 break;
1486 case MELEE_HIT_GLANCING:
1488 damageInfo->HitInfo |= HITINFO_GLANCING;
1489 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1490 damageInfo->procEx |= PROC_EX_NORMAL_HIT;
1491 float reducePercent = 1.0f; //damage factor
1492 // calculate base values and mods
1493 float baseLowEnd = 1.3f;
1494 float baseHighEnd = 1.2f;
1495 switch(getClass()) // lowering base values for casters
1497 case CLASS_SHAMAN:
1498 case CLASS_PRIEST:
1499 case CLASS_MAGE:
1500 case CLASS_WARLOCK:
1501 case CLASS_DRUID:
1502 baseLowEnd -= 0.7f;
1503 baseHighEnd -= 0.3f;
1504 break;
1507 float maxLowEnd = 0.6f;
1508 switch(getClass()) // upper for melee classes
1510 case CLASS_WARRIOR:
1511 case CLASS_ROGUE:
1512 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1515 // calculate values
1516 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1517 float lowEnd = baseLowEnd - ( 0.05f * diff );
1518 float highEnd = baseHighEnd - ( 0.03f * diff );
1520 // apply max/min bounds
1521 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1522 lowEnd = 0.01f;
1523 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1524 lowEnd = maxLowEnd;
1526 if ( highEnd < 0.2f ) //high end limits
1527 highEnd = 0.2f;
1528 if ( highEnd > 0.99f )
1529 highEnd = 0.99f;
1531 if(lowEnd > highEnd) // prevent negative range size
1532 lowEnd = highEnd;
1534 reducePercent = lowEnd + rand_norm_f() * ( highEnd - lowEnd );
1536 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1537 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1538 break;
1540 case MELEE_HIT_CRUSHING:
1542 damageInfo->HitInfo |= HITINFO_CRUSHING;
1543 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1544 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1545 // 150% normal damage
1546 damageInfo->damage += (damageInfo->damage / 2);
1547 break;
1549 default:
1551 break;
1554 // only from players
1555 if (GetTypeId() == TYPEID_PLAYER)
1557 uint32 redunction_affected_damage = CalcNotIgnoreDamageRedunction(damageInfo->damage,damageInfo->damageSchoolMask);
1558 uint32 resilienceReduction;
1559 if (attackType != RANGED_ATTACK)
1560 resilienceReduction = pVictim->GetMeleeDamageReduction(redunction_affected_damage);
1561 else
1562 resilienceReduction = pVictim->GetRangedDamageReduction(redunction_affected_damage);
1563 damageInfo->damage -= resilienceReduction;
1564 damageInfo->cleanDamage += resilienceReduction;
1567 // Calculate absorb resist
1568 if(int32(damageInfo->damage) > 0)
1570 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1572 // Calculate absorb & resists
1573 uint32 absorb_affected_damage = CalcNotIgnoreAbsorbDamage(damageInfo->damage,damageInfo->damageSchoolMask);
1574 damageInfo->target->CalculateAbsorbAndResist(this, damageInfo->damageSchoolMask, DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, true);
1575 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1576 if (damageInfo->absorb)
1578 damageInfo->HitInfo|=HITINFO_ABSORB;
1579 damageInfo->procEx|=PROC_EX_ABSORB;
1581 if (damageInfo->resist)
1582 damageInfo->HitInfo|=HITINFO_RESIST;
1585 else // Umpossible get negative result but....
1586 damageInfo->damage = 0;
1589 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1591 if (damageInfo==0) return;
1592 Unit *pVictim = damageInfo->target;
1594 if(!this || !pVictim)
1595 return;
1597 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1598 return;
1600 //You don't lose health from damage taken from another player while in a sanctuary
1601 //You still see it in the combat log though
1602 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1604 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1605 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1606 return;
1609 // Hmmmm dont like this emotes client must by self do all animations
1610 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1611 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1612 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1613 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1615 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1617 // Get attack timers
1618 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1619 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1620 // Reduce attack time
1621 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1623 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1624 float percent60 = 3.0f * percent20;
1625 if(offtime > percent20 && offtime <= percent60)
1627 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1629 else if(offtime > percent60)
1631 offtime -= 2.0f * percent20;
1632 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1635 else
1637 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20f;
1638 float percent60 = 3.0f * percent20;
1639 if(basetime > percent20 && basetime <= percent60)
1641 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1643 else if(basetime > percent60)
1645 basetime -= 2.0f * percent20;
1646 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1651 // Call default DealDamage
1652 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1653 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, damageInfo->damageSchoolMask, NULL, durabilityLoss);
1655 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1656 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1657 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI_F, this) )
1659 // -probability is between 0% and 40%
1660 // 20% base chance
1661 float Probability = 20.0f;
1663 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1664 if( pVictim->getLevel() < 30 )
1665 Probability = 0.65f*pVictim->getLevel()+0.5f;
1667 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1668 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1670 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1672 if(Probability > 40.0f)
1673 Probability = 40.0f;
1675 if(roll_chance_f(Probability))
1676 CastSpell(pVictim, 1604, true);
1679 // If not miss
1680 if (!(damageInfo->HitInfo & HITINFO_MISS))
1682 // on weapon hit casts
1683 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1684 ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType);
1686 // victim's damage shield
1687 std::set<Aura*> alreadyDone;
1688 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1689 for(AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();)
1691 if (alreadyDone.find(*i) == alreadyDone.end())
1693 alreadyDone.insert(*i);
1694 uint32 damage=(*i)->GetModifier()->m_amount;
1695 SpellEntry const *i_spellProto = (*i)->GetSpellProto();
1696 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1697 //uint32 absorb;
1698 //uint32 resist;
1699 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1700 //damage-=absorb + resist;
1702 pVictim->DealDamageMods(this,damage,NULL);
1704 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1705 data << uint64(pVictim->GetGUID());
1706 data << uint64(GetGUID());
1707 data << uint32(i_spellProto->Id);
1708 data << uint32(damage); // Damage
1709 data << uint32(0); // Overkill
1710 data << uint32(i_spellProto->SchoolMask);
1711 pVictim->SendMessageToSet(&data, true );
1713 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
1715 i = vDamageShields.begin();
1717 else
1718 ++i;
1724 void Unit::HandleEmoteCommand(uint32 anim_id)
1726 WorldPacket data( SMSG_EMOTE, 4 + 8 );
1727 data << uint32(anim_id);
1728 data << uint64(GetGUID());
1729 SendMessageToSet(&data, true);
1732 void Unit::HandleEmoteState(uint32 anim_id)
1734 SetUInt32Value(UNIT_NPC_EMOTESTATE, anim_id);
1737 void Unit::HandleEmote(uint32 anim_id)
1739 if (!anim_id)
1740 HandleEmoteState(0);
1741 else if (EmotesEntry const* emoteEntry = sEmotesStore.LookupEntry(anim_id))
1743 if (emoteEntry->EmoteType) // 1,2 states, 0 command
1744 HandleEmoteState(anim_id);
1745 else
1746 HandleEmoteCommand(anim_id);
1750 uint32 Unit::CalcNotIgnoreAbsorbDamage( uint32 damage, SpellSchoolMask damageSchoolMask, SpellEntry const* spellInfo /*= NULL*/)
1752 float absorb_affected_rate = 1.0f;
1753 Unit::AuraList const& ignoreAbsorbSchool = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL);
1754 for(Unit::AuraList::const_iterator i = ignoreAbsorbSchool.begin(); i != ignoreAbsorbSchool.end(); ++i)
1755 if ((*i)->GetMiscValue() & damageSchoolMask)
1756 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1758 if(spellInfo)
1760 Unit::AuraList const& ignoreAbsorbForSpell = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1761 for(Unit::AuraList::const_iterator citr = ignoreAbsorbForSpell.begin(); citr != ignoreAbsorbForSpell.end(); ++citr)
1762 if ((*citr)->isAffectedOnSpell(spellInfo))
1763 absorb_affected_rate *= (100.0f - (*citr)->GetModifier()->m_amount)/100.0f;
1766 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1769 uint32 Unit::CalcNotIgnoreDamageRedunction( uint32 damage, SpellSchoolMask damageSchoolMask)
1771 float absorb_affected_rate = 1.0f;
1772 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL);
1773 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1774 if ((*i)->GetMiscValue() & damageSchoolMask)
1775 absorb_affected_rate *= (100.0f - (*i)->GetModifier()->m_amount)/100.0f;
1777 return absorb_affected_rate <= 0.0f ? 0 : (absorb_affected_rate < 1.0f ? uint32(damage * absorb_affected_rate) : damage);
1780 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1782 uint32 newdamage = 0;
1783 float armor = (float)pVictim->GetArmor();
1785 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1786 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1788 // Apply Player CR_ARMOR_PENETRATION rating and percent talents
1789 if (GetTypeId()==TYPEID_PLAYER)
1790 armor *= 1.0f - ((Player*)this)->GetArmorPenetrationPct() / 100.0f;
1792 if (armor < 0.0f)
1793 armor = 0.0f;
1795 float levelModifier = (float)getLevel();
1796 if (levelModifier > 59)
1797 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1799 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1800 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1802 if (tmpvalue < 0.0f)
1803 tmpvalue = 0.0f;
1804 if (tmpvalue > 0.75f)
1805 tmpvalue = 0.75f;
1807 newdamage = uint32(damage - (damage * tmpvalue));
1809 return (newdamage > 1) ? newdamage : 1;
1812 void Unit::CalculateAbsorbAndResist(Unit *pCaster, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, bool canReflect)
1814 if(!pCaster || !isAlive() || !damage)
1815 return;
1817 // Magic damage, check for resists
1818 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1820 // Get base victim resistance for school
1821 float tmpvalue2 = (float)GetResistance(GetFirstSchoolInMask(schoolMask));
1822 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1823 tmpvalue2 += (float)pCaster->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1825 tmpvalue2 *= (float)(0.15f / getLevel());
1826 if (tmpvalue2 < 0.0f)
1827 tmpvalue2 = 0.0f;
1828 if (tmpvalue2 > 0.75f)
1829 tmpvalue2 = 0.75f;
1830 uint32 ran = urand(0, 100);
1831 float faq[4] = {24.0f,6.0f,4.0f,6.0f};
1832 uint8 m = 0;
1833 float Binom = 0.0f;
1834 for (uint8 i = 0; i < 4; ++i)
1836 Binom += 2400 *( powf(tmpvalue2, float(i)) * powf( (1-tmpvalue2), float(4-i)))/faq[i];
1837 if (ran > Binom )
1838 ++m;
1839 else
1840 break;
1842 if (damagetype == DOT && m == 4)
1843 *resist += uint32(damage - 1);
1844 else
1845 *resist += uint32(damage * m / 4);
1846 if(*resist > damage)
1847 *resist = damage;
1849 else
1850 *resist = 0;
1852 int32 RemainingDamage = damage - *resist;
1854 // Get unit state (need for some absorb check)
1855 uint32 unitflag = GetUInt32Value(UNIT_FIELD_FLAGS);
1856 // Reflect damage spells (not cast any damage spell in aura lookup)
1857 uint32 reflectSpell = 0;
1858 int32 reflectDamage = 0;
1859 Aura* reflectTriggeredBy = NULL; // expected as not expired at reflect as in current cases
1860 // Death Prevention Aura
1861 SpellEntry const* preventDeathSpell = NULL;
1862 int32 preventDeathAmount = 0;
1864 // full absorb cases (by chance)
1865 AuraList const& vAbsorb = GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1866 for(AuraList::const_iterator i = vAbsorb.begin(); i != vAbsorb.end() && RemainingDamage > 0; ++i)
1868 // only work with proper school mask damage
1869 Modifier* i_mod = (*i)->GetModifier();
1870 if (!(i_mod->m_miscvalue & schoolMask))
1871 continue;
1873 SpellEntry const* i_spellProto = (*i)->GetSpellProto();
1874 // Fire Ward or Frost Ward
1875 if(i_spellProto->SpellFamilyName == SPELLFAMILY_MAGE && i_spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000108))
1877 int chance = 0;
1878 Unit::AuraList const& auras = GetAurasByType(SPELL_AURA_ADD_PCT_MODIFIER);
1879 for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
1881 SpellEntry const* itr_spellProto = (*itr)->GetSpellProto();
1882 // Frost Warding (chance full absorb)
1883 if (itr_spellProto->SpellFamilyName == SPELLFAMILY_MAGE && itr_spellProto->SpellIconID == 501)
1885 // chance stored in next dummy effect
1886 chance = itr_spellProto->CalculateSimpleValue(EFFECT_INDEX_1);
1887 break;
1890 if(roll_chance_i(chance))
1892 int32 amount = RemainingDamage;
1893 RemainingDamage = 0;
1895 // Frost Warding (mana regen)
1896 CastCustomSpell(this, 57776, &amount, NULL, NULL, true, NULL, *i);
1897 break;
1902 // Need remove expired auras after
1903 bool existExpired = false;
1905 // Incanter's Absorption, for converting to spell power
1906 int32 incanterAbsorption = 0;
1908 // absorb without mana cost
1909 AuraList const& vSchoolAbsorb = GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1910 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1912 Modifier* mod = (*i)->GetModifier();
1913 if (!(mod->m_miscvalue & schoolMask))
1914 continue;
1916 SpellEntry const* spellProto = (*i)->GetSpellProto();
1918 // Max Amount can be absorbed by this aura
1919 int32 currentAbsorb = mod->m_amount;
1921 // Found empty aura (impossible but..)
1922 if (currentAbsorb <=0)
1924 existExpired = true;
1925 continue;
1927 // Handle custom absorb auras
1928 // TODO: try find better way
1929 switch(spellProto->SpellFamilyName)
1931 case SPELLFAMILY_GENERIC:
1933 // Astral Shift
1934 if (spellProto->SpellIconID == 3066)
1936 //reduces all damage taken while stun, fear or silence
1937 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1938 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1939 continue;
1941 // Nerves of Steel
1942 if (spellProto->SpellIconID == 2115)
1944 // while affected by Stun and Fear
1945 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1946 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1947 continue;
1949 // Spell Deflection
1950 if (spellProto->SpellIconID == 3006)
1952 // You have a chance equal to your Parry chance
1953 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1954 roll_chance_f(GetUnitParryChance())) // Roll chance
1955 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1956 continue;
1958 // Reflective Shield (Lady Malande boss)
1959 if (spellProto->Id == 41475 && canReflect)
1961 if(RemainingDamage < currentAbsorb)
1962 reflectDamage = RemainingDamage / 2;
1963 else
1964 reflectDamage = currentAbsorb / 2;
1965 reflectSpell = 33619;
1966 reflectTriggeredBy = *i;
1967 break;
1969 if (spellProto->Id == 39228 || // Argussian Compass
1970 spellProto->Id == 60218) // Essence of Gossamer
1972 // Max absorb stored in 1 dummy effect
1973 int32 max_absorb = spellProto->CalculateSimpleValue(EFFECT_INDEX_1);
1974 if (max_absorb < currentAbsorb)
1975 currentAbsorb = max_absorb;
1976 break;
1978 break;
1980 case SPELLFAMILY_DRUID:
1982 // Primal Tenacity
1983 if (spellProto->SpellIconID == 2253)
1985 //reduces all damage taken while Stunned and in Cat Form
1986 if (m_form == FORM_CAT && (unitflag & UNIT_FLAG_STUNNED))
1987 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1988 continue;
1990 break;
1992 case SPELLFAMILY_ROGUE:
1994 // Cheat Death (make less prio with Guardian Spirit case)
1995 if (!preventDeathSpell && spellProto->SpellIconID == 2109 &&
1996 GetTypeId()==TYPEID_PLAYER && // Only players
1997 !((Player*)this)->HasSpellCooldown(31231) &&
1998 // Only if no cooldown
1999 roll_chance_i((*i)->GetModifier()->m_amount))
2000 // Only if roll
2002 preventDeathSpell = (*i)->GetSpellProto();
2003 continue;
2005 break;
2007 case SPELLFAMILY_PRIEST:
2009 // Guardian Spirit
2010 if (spellProto->SpellIconID == 2873)
2012 preventDeathSpell = (*i)->GetSpellProto();
2013 preventDeathAmount = (*i)->GetModifier()->m_amount;
2014 continue;
2016 // Reflective Shield
2017 if (spellProto->SpellFamilyFlags == 0x1 && canReflect)
2019 if (pCaster == this)
2020 break;
2021 Unit* caster = (*i)->GetCaster();
2022 if (!caster)
2023 break;
2024 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
2025 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
2027 switch((*k)->GetModifier()->m_miscvalue)
2029 case 5065: // Rank 1
2030 case 5064: // Rank 2
2032 if(RemainingDamage >= currentAbsorb)
2033 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
2034 else
2035 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
2036 reflectSpell = 33619;
2037 reflectTriggeredBy = *i;
2038 } break;
2039 default: break;
2042 break;
2044 break;
2046 case SPELLFAMILY_SHAMAN:
2048 // Astral Shift
2049 if (spellProto->SpellIconID == 3066)
2051 //reduces all damage taken while stun, fear or silence
2052 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
2053 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
2054 continue;
2056 break;
2058 case SPELLFAMILY_DEATHKNIGHT:
2060 // Shadow of Death
2061 if (spellProto->SpellIconID == 1958)
2063 // TODO: absorb only while transform
2064 continue;
2066 // Anti-Magic Shell (on self)
2067 if (spellProto->Id == 48707)
2069 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
2070 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
2071 int32 absorbed = RemainingDamage * currentAbsorb / 100;
2072 int32 regen = absorbed * 2 / 10;
2073 CastCustomSpell(this, 49088, &regen, NULL, NULL, true, NULL, *i);
2074 RemainingDamage -= absorbed;
2075 continue;
2077 // Anti-Magic Shell (on single party/raid member)
2078 if (spellProto->Id == 50462)
2080 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
2081 continue;
2083 // Anti-Magic Zone
2084 if (spellProto->Id == 50461)
2086 Unit* caster = (*i)->GetCaster();
2087 if (!caster)
2088 continue;
2089 int32 absorbed = RemainingDamage * currentAbsorb / 100;
2090 int32 canabsorb = caster->GetHealth();
2091 if (canabsorb < absorbed)
2092 absorbed = canabsorb;
2094 RemainingDamage -= absorbed;
2096 uint32 ab_damage = absorbed;
2097 pCaster->DealDamageMods(caster,ab_damage,NULL);
2098 pCaster->DealDamage(caster, ab_damage, NULL, damagetype, schoolMask, 0, false);
2099 continue;
2101 break;
2103 default:
2104 break;
2107 // currentAbsorb - damage can be absorbed by shield
2108 // If need absorb less damage
2109 if (RemainingDamage < currentAbsorb)
2110 currentAbsorb = RemainingDamage;
2112 RemainingDamage -= currentAbsorb;
2114 // Fire Ward or Frost Ward or Ice Barrier (or Mana Shield)
2115 // for Incanter's Absorption converting to spell power
2116 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellFamilyFlags2 & 0x000008)
2117 incanterAbsorption += currentAbsorb;
2119 // Reduce shield amount
2120 mod->m_amount-=currentAbsorb;
2121 if((*i)->DropAuraCharge())
2122 mod->m_amount = 0;
2123 // Need remove it later
2124 if (mod->m_amount<=0)
2125 existExpired = true;
2128 // Remove all expired absorb auras
2129 if (existExpired)
2131 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
2133 if ((*i)->GetModifier()->m_amount<=0)
2135 RemoveAurasDueToSpell((*i)->GetId());
2136 i = vSchoolAbsorb.begin();
2138 else
2139 ++i;
2143 // Cast back reflect damage spell
2144 if (canReflect && reflectSpell)
2145 CastCustomSpell(pCaster, reflectSpell, &reflectDamage, NULL, NULL, true, NULL, reflectTriggeredBy);
2147 // absorb by mana cost
2148 AuraList const& vManaShield = GetAurasByType(SPELL_AURA_MANA_SHIELD);
2149 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
2151 next = i; ++next;
2153 // check damage school mask
2154 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2155 continue;
2157 int32 currentAbsorb;
2158 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
2159 currentAbsorb = (*i)->GetModifier()->m_amount;
2160 else
2161 currentAbsorb = RemainingDamage;
2163 if (float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()])
2165 if(Player *modOwner = GetSpellModOwner())
2166 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
2168 int32 maxAbsorb = int32(GetPower(POWER_MANA) / manaMultiplier);
2169 if (currentAbsorb > maxAbsorb)
2170 currentAbsorb = maxAbsorb;
2172 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
2173 ApplyPowerMod(POWER_MANA, manaReduction, false);
2176 // Mana Shield (or Fire Ward or Frost Ward or Ice Barrier)
2177 // for Incanter's Absorption converting to spell power
2178 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_MAGE && (*i)->GetSpellProto()->SpellFamilyFlags2 & 0x000008)
2179 incanterAbsorption += currentAbsorb;
2181 (*i)->GetModifier()->m_amount -= currentAbsorb;
2182 if((*i)->GetModifier()->m_amount <= 0)
2184 RemoveAurasDueToSpell((*i)->GetId());
2185 next = vManaShield.begin();
2188 RemainingDamage -= currentAbsorb;
2191 // effects dependent from full absorb amount
2192 // Incanter's Absorption, if have affective absorbing
2193 if (incanterAbsorption)
2195 Unit::AuraList const& auras = GetAurasByType(SPELL_AURA_DUMMY);
2196 for (Unit::AuraList::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
2198 SpellEntry const* itr_spellProto = (*itr)->GetSpellProto();
2200 // Incanter's Absorption
2201 if (itr_spellProto->SpellFamilyName == SPELLFAMILY_GENERIC &&
2202 itr_spellProto->SpellIconID == 2941)
2205 int32 amount = int32(incanterAbsorption * (*itr)->GetModifier()->m_amount / 100);
2207 // apply normalized part of already accumulated amount in aura
2208 if (Aura* spdAura = GetAura(44413, EFFECT_INDEX_0))
2209 amount += spdAura->GetModifier()->m_amount * spdAura->GetAuraDuration() / spdAura->GetAuraMaxDuration();
2211 // Incanter's Absorption (triggered absorb based spell power, will replace existed if any)
2212 CastCustomSpell(this, 44413, &amount, NULL, NULL, true);
2213 break;
2218 // only split damage if not damaging yourself
2219 if(pCaster != this)
2221 AuraList const& vSplitDamageFlat = GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
2222 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
2224 next = i; ++next;
2226 // check damage school mask
2227 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2228 continue;
2230 // Damage can be splitted only if aura has an alive caster
2231 Unit *caster = (*i)->GetCaster();
2232 if(!caster || caster == this || !caster->IsInWorld() || !caster->isAlive())
2233 continue;
2235 int32 currentAbsorb;
2236 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
2237 currentAbsorb = (*i)->GetModifier()->m_amount;
2238 else
2239 currentAbsorb = RemainingDamage;
2241 RemainingDamage -= currentAbsorb;
2244 uint32 splitted = currentAbsorb;
2245 uint32 splitted_absorb = 0;
2246 pCaster->DealDamageMods(caster,splitted,&splitted_absorb);
2248 pCaster->SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
2250 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2251 pCaster->DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2254 AuraList const& vSplitDamagePct = GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
2255 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
2257 next = i; ++next;
2259 // check damage school mask
2260 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
2261 continue;
2263 // Damage can be splitted only if aura has an alive caster
2264 Unit *caster = (*i)->GetCaster();
2265 if(!caster || caster == this || !caster->IsInWorld() || !caster->isAlive())
2266 continue;
2268 uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
2270 RemainingDamage -= int32(splitted);
2272 uint32 split_absorb = 0;
2273 pCaster->DealDamageMods(caster,splitted,&split_absorb);
2275 pCaster->SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
2277 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
2278 pCaster->DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
2282 // Apply death prevention spells effects
2283 if (preventDeathSpell && RemainingDamage >= (int32)GetHealth())
2285 switch(preventDeathSpell->SpellFamilyName)
2287 // Cheat Death
2288 case SPELLFAMILY_ROGUE:
2290 // Cheat Death
2291 if (preventDeathSpell->SpellIconID == 2109)
2293 CastSpell(this,31231,true);
2294 ((Player*)this)->AddSpellCooldown(31231,0,time(NULL)+60);
2295 // with health > 10% lost health until health==10%, in other case no losses
2296 uint32 health10 = GetMaxHealth()/10;
2297 RemainingDamage = GetHealth() > health10 ? GetHealth() - health10 : 0;
2299 break;
2301 // Guardian Spirit
2302 case SPELLFAMILY_PRIEST:
2304 // Guardian Spirit
2305 if (preventDeathSpell->SpellIconID == 2873)
2307 int32 healAmount = GetMaxHealth() * preventDeathAmount / 100;
2308 CastCustomSpell(this, 48153, &healAmount, NULL, NULL, true);
2309 RemoveAurasDueToSpell(preventDeathSpell->Id);
2310 RemainingDamage = 0;
2312 break;
2317 *absorb = damage - RemainingDamage - *resist;
2320 void Unit::CalculateAbsorbResistBlock(Unit *pCaster, SpellNonMeleeDamage *damageInfo, SpellEntry const* spellProto, WeaponAttackType attType)
2322 bool blocked = false;
2323 // Get blocked status
2324 switch (spellProto->DmgClass)
2326 // Melee and Ranged Spells
2327 case SPELL_DAMAGE_CLASS_RANGED:
2328 case SPELL_DAMAGE_CLASS_MELEE:
2329 blocked = IsSpellBlocked(pCaster, spellProto, attType);
2330 break;
2331 default:
2332 break;
2335 if (blocked)
2337 damageInfo->blocked = GetShieldBlockValue();
2338 if (damageInfo->damage < (int32)damageInfo->blocked)
2339 damageInfo->blocked = damageInfo->damage;
2340 damageInfo->damage-=damageInfo->blocked;
2343 uint32 absorb_affected_damage = pCaster->CalcNotIgnoreAbsorbDamage(damageInfo->damage,GetSpellSchoolMask(spellProto),spellProto);
2344 CalculateAbsorbAndResist(pCaster, GetSpellSchoolMask(spellProto), SPELL_DIRECT_DAMAGE, absorb_affected_damage, &damageInfo->absorb, &damageInfo->resist, !(spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_REFLECTED));
2345 damageInfo->damage-= damageInfo->absorb + damageInfo->resist;
2348 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
2350 if(hasUnitState(UNIT_STAT_CAN_NOT_REACT) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
2351 return;
2353 if (!pVictim->isAlive())
2354 return;
2356 if(IsNonMeleeSpellCasted(false))
2357 return;
2359 uint32 hitInfo;
2360 if (attType == BASE_ATTACK)
2361 hitInfo = HITINFO_NORMALSWING2;
2362 else if (attType == OFF_ATTACK)
2363 hitInfo = HITINFO_LEFTSWING;
2364 else
2365 return; // ignore ranged case
2367 uint32 extraAttacks = m_extraAttacks;
2369 // melee attack spell casted at main hand attack only
2370 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
2372 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
2374 // not recent extra attack only at any non extra attack (melee spell case)
2375 if(!extra && extraAttacks)
2377 while(m_extraAttacks)
2379 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2380 if(m_extraAttacks > 0)
2381 --m_extraAttacks;
2384 return;
2387 // attack can be redirected to another target
2388 pVictim = SelectMagnetTarget(pVictim);
2390 CalcDamageInfo damageInfo;
2391 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
2392 // Send log damage message to client
2393 DealDamageMods(pVictim,damageInfo.damage,&damageInfo.absorb);
2394 SendAttackStateUpdate(&damageInfo);
2395 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
2396 DealMeleeDamage(&damageInfo,true);
2398 if (GetTypeId() == TYPEID_PLAYER)
2399 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT,"AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2400 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2401 else
2402 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT,"AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2403 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2405 // if damage pVictim call AI reaction
2406 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2407 ((Creature*)pVictim)->AI()->AttackedBy(this);
2409 // extra attack only at any non extra attack (normal case)
2410 if(!extra && extraAttacks)
2412 while(m_extraAttacks)
2414 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2415 if(m_extraAttacks > 0)
2416 --m_extraAttacks;
2421 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2423 // This is only wrapper
2425 // Miss chance based on melee
2426 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2428 // Critical hit chance
2429 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2431 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2432 float dodge_chance = pVictim->GetUnitDodgeChance();
2433 float block_chance = pVictim->GetUnitBlockChance();
2434 float parry_chance = pVictim->GetUnitParryChance();
2436 // Useful if want to specify crit & miss chances for melee, else it could be removed
2437 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT,"MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2439 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2442 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2444 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2445 return MELEE_HIT_EVADE;
2447 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2448 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2450 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2451 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2453 // bonus from skills is 0.04%
2454 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2455 int32 sum = 0, tmp = 0;
2456 int32 roll = urand (0, 10000);
2458 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2459 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2460 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2462 tmp = miss_chance;
2464 if (tmp > 0 && roll < (sum += tmp ))
2466 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: MISS");
2467 return MELEE_HIT_MISS;
2470 // always crit against a sitting target (except 0 crit chance)
2471 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2473 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2474 return MELEE_HIT_CRIT;
2477 // Dodge chance
2479 // only players can't dodge if attacker is behind
2480 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI_F,this))
2482 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2484 else
2486 // Reduce dodge chance by attacker expertise rating
2487 if (GetTypeId() == TYPEID_PLAYER)
2488 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2489 else
2490 dodge_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2492 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2493 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2495 tmp = dodge_chance;
2496 if ( (tmp > 0) // check if unit _can_ dodge
2497 && ((tmp -= skillBonus) > 0)
2498 && roll < (sum += tmp))
2500 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2501 return MELEE_HIT_DODGE;
2505 // parry & block chances
2507 // check if attack comes from behind, nobody can parry or block if attacker is behind
2508 if (!pVictim->HasInArc(M_PI_F,this))
2510 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: attack came from behind.");
2512 else
2514 // Reduce parry chance by attacker expertise rating
2515 if (GetTypeId() == TYPEID_PLAYER)
2516 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2517 else
2518 parry_chance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2520 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2522 int32 tmp2 = int32(parry_chance);
2523 if ( (tmp2 > 0) // check if unit _can_ parry
2524 && ((tmp2 -= skillBonus) > 0)
2525 && (roll < (sum += tmp2)))
2527 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
2528 return MELEE_HIT_PARRY;
2532 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2534 tmp = block_chance;
2535 if ( (tmp > 0) // check if unit _can_ block
2536 && ((tmp -= skillBonus) > 0)
2537 && (roll < (sum += tmp)))
2539 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2540 return MELEE_HIT_BLOCK;
2545 // Critical chance
2546 tmp = crit_chance;
2548 if (tmp > 0 && roll < (sum += tmp))
2550 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2551 return MELEE_HIT_CRIT;
2554 // 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)
2555 if( attType != RANGED_ATTACK &&
2556 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2557 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2558 getLevel() < pVictim->getLevelForTarget(this) )
2560 // cap possible value (with bonuses > max skill)
2561 int32 skill = attackerWeaponSkill;
2562 int32 maxskill = attackerMaxSkillValueForLevel;
2563 skill = (skill > maxskill) ? maxskill : skill;
2565 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2566 tmp = tmp > 4000 ? 4000 : tmp;
2567 if (roll < (sum += tmp))
2569 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2570 return MELEE_HIT_GLANCING;
2574 // mobs can score crushing blows if they're 4 or more levels above victim
2575 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2576 // can be from by creature (if can) or from controlled player that considered as creature
2577 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2578 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2579 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2581 // when their weapon skill is 15 or more above victim's defense skill
2582 tmp = victimDefenseSkill;
2583 int32 tmpmax = victimMaxSkillValueForLevel;
2584 // having defense above your maximum (from items, talents etc.) has no effect
2585 tmp = tmp > tmpmax ? tmpmax : tmp;
2586 // tmp = mob's level * 5 - player's current defense skill
2587 tmp = attackerMaxSkillValueForLevel - tmp;
2588 if(tmp >= 15)
2590 // add 2% chance per lacking skill point, min. is 15%
2591 tmp = tmp * 200 - 1500;
2592 if (roll < (sum += tmp))
2594 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2595 return MELEE_HIT_CRUSHING;
2600 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "RollMeleeOutcomeAgainst: NORMAL");
2601 return MELEE_HIT_NORMAL;
2604 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2606 float min_damage, max_damage;
2608 if (normalized && GetTypeId()==TYPEID_PLAYER)
2609 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2610 else
2612 switch (attType)
2614 case RANGED_ATTACK:
2615 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2616 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2617 break;
2618 case BASE_ATTACK:
2619 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2620 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2621 break;
2622 case OFF_ATTACK:
2623 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2624 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2625 break;
2626 // Just for good manner
2627 default:
2628 min_damage = 0.0f;
2629 max_damage = 0.0f;
2630 break;
2634 if (min_damage > max_damage)
2636 std::swap(min_damage,max_damage);
2639 if(max_damage == 0.0f)
2640 max_damage = 5.0f;
2642 return urand((uint32)min_damage, (uint32)max_damage);
2645 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2647 if(spellProto->spellLevel <= 0)
2648 return 1.0f;
2650 float LvlPenalty = 0.0f;
2652 if(spellProto->spellLevel < 20)
2653 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2654 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2655 if(LvlFactor > 1.0f)
2656 LvlFactor = 1.0f;
2658 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2661 void Unit::SendMeleeAttackStart(Unit* pVictim)
2663 WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
2664 data << uint64(GetGUID());
2665 data << uint64(pVictim->GetGUID());
2667 SendMessageToSet(&data, true);
2668 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2671 void Unit::SendMeleeAttackStop(Unit* victim)
2673 if(!victim)
2674 return;
2676 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2677 data << GetPackGUID();
2678 data << victim->GetPackGUID(); // can be 0x00...
2679 data << uint32(0); // can be 0x1
2680 SendMessageToSet(&data, true);
2681 DETAIL_FILTER_LOG(LOG_FILTER_COMBAT, "%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2683 /*if(victim->GetTypeId() == TYPEID_UNIT)
2684 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2687 bool Unit::IsSpellBlocked(Unit *pCaster, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
2689 if (HasInArc(M_PI_F,pCaster))
2691 /* Currently not exist spells with ignore block
2692 // Ignore combat result aura (parry/dodge check on prepare)
2693 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2694 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2696 if (!(*i)->isAffectedOnSpell(spellProto))
2697 continue;
2698 if ((*i)->GetModifier()->m_miscvalue == )
2699 return false;
2703 // Check creatures flags_extra for disable block
2704 if(GetTypeId()==TYPEID_UNIT &&
2705 ((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2706 return false;
2708 float blockChance = GetUnitBlockChance();
2709 blockChance += (int32(pCaster->GetWeaponSkillValue(attackType)) - int32(GetMaxSkillValueForLevel()))*0.04f;
2710 if (roll_chance_f(blockChance))
2711 return true;
2713 return false;
2716 // Melee based spells can be miss, parry or dodge on this step
2717 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2718 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2720 // Calculate hit chance (more correct for chance mod)
2721 int32 HitChance;
2723 // PvP - PvE melee chances
2724 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2725 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2726 if(leveldif < 3)
2727 HitChance = 95 - leveldif;
2728 else
2729 HitChance = 93 - (leveldif - 2) * lchance;
2731 // Hit chance depends from victim auras
2732 if(attType == RANGED_ATTACK)
2733 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2734 else
2735 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2737 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2738 if(Player *modOwner = GetSpellModOwner())
2739 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2741 // Miss = 100 - hit
2742 float miss_chance= 100.0f - HitChance;
2744 // Bonuses from attacker aura and ratings
2745 if (attType == RANGED_ATTACK)
2746 miss_chance -= m_modRangedHitChance;
2747 else
2748 miss_chance -= m_modMeleeHitChance;
2750 // bonus from skills is 0.04%
2751 miss_chance -= skillDiff * 0.04f;
2753 // Limit miss chance from 0 to 60%
2754 if (miss_chance < 0.0f)
2755 return 0.0f;
2756 if (miss_chance > 60.0f)
2757 return 60.0f;
2758 return miss_chance;
2761 // Melee based spells hit result calculations
2762 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2764 WeaponAttackType attType = BASE_ATTACK;
2766 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2767 attType = RANGED_ATTACK;
2769 // bonus from skills is 0.04% per skill Diff
2770 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2771 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2772 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2774 uint32 roll = urand (0, 10000);
2776 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2777 // Roll miss
2778 uint32 tmp = missChance;
2779 if (roll < tmp)
2780 return SPELL_MISS_MISS;
2782 // Chance resist mechanic (select max value from every mechanic spell effect)
2783 int32 resist_mech = 0;
2784 // Get effects mechanic and chance
2785 for(int eff = 0; eff < MAX_EFFECT_INDEX; ++eff)
2787 int32 effect_mech = GetEffectMechanic(spell, SpellEffectIndex(eff));
2788 if (effect_mech)
2790 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2791 if (resist_mech < temp*100)
2792 resist_mech = temp*100;
2795 // Roll chance
2796 tmp += resist_mech;
2797 if (roll < tmp)
2798 return SPELL_MISS_RESIST;
2800 bool canDodge = true;
2801 bool canParry = true;
2803 // Same spells cannot be parry/dodge
2804 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2805 return SPELL_MISS_NONE;
2807 // Ranged attack cannot be parry/dodge only deflect
2808 if (attType == RANGED_ATTACK)
2810 // only if in front
2811 if (pVictim->HasInArc(M_PI_F,this))
2813 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2814 tmp+=deflect_chance;
2815 if (roll < tmp)
2816 return SPELL_MISS_DEFLECT;
2818 return SPELL_MISS_NONE;
2821 // Check for attack from behind
2822 if (!pVictim->HasInArc(M_PI_F,this))
2824 // Can`t dodge from behind in PvP (but its possible in PvE)
2825 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2826 canDodge = false;
2827 // Can`t parry
2828 canParry = false;
2830 // Check creatures flags_extra for disable parry
2831 if(pVictim->GetTypeId()==TYPEID_UNIT)
2833 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2834 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2835 canParry = false;
2837 // Ignore combat result aura
2838 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2839 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2841 if (!(*i)->isAffectedOnSpell(spell))
2842 continue;
2843 switch((*i)->GetModifier()->m_miscvalue)
2845 case MELEE_HIT_DODGE: canDodge = false; break;
2846 case MELEE_HIT_BLOCK: break; // Block check in hit step
2847 case MELEE_HIT_PARRY: canParry = false; break;
2848 default:
2849 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2850 break;
2854 if (canDodge)
2856 // Roll dodge
2857 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2858 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2859 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2860 // Reduce dodge chance by attacker expertise rating
2861 if (GetTypeId() == TYPEID_PLAYER)
2862 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2863 else
2864 dodgeChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2865 if (dodgeChance < 0)
2866 dodgeChance = 0;
2868 tmp += dodgeChance;
2869 if (roll < tmp)
2870 return SPELL_MISS_DODGE;
2873 if (canParry)
2875 // Roll parry
2876 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2877 // Reduce parry chance by attacker expertise rating
2878 if (GetTypeId() == TYPEID_PLAYER)
2879 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2880 else
2881 parryChance -= GetTotalAuraModifier(SPELL_AURA_MOD_EXPERTISE)*25;
2882 if (parryChance < 0)
2883 parryChance = 0;
2885 tmp += parryChance;
2886 if (roll < tmp)
2887 return SPELL_MISS_PARRY;
2890 return SPELL_MISS_NONE;
2893 // TODO need use unit spell resistances in calculations
2894 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2896 // Can`t miss on dead target (on skinning for example)
2897 if (!pVictim->isAlive())
2898 return SPELL_MISS_NONE;
2900 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2901 // PvP - PvE spell misschances per leveldif > 2
2902 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2903 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2905 // Base hit chance from attacker and victim levels
2906 int32 modHitChance;
2907 if(leveldif < 3)
2908 modHitChance = 96 - leveldif;
2909 else
2910 modHitChance = 94 - (leveldif - 2) * lchance;
2912 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2913 if(Player *modOwner = GetSpellModOwner())
2914 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2915 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2916 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2917 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2918 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2919 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2920 if (IsAreaOfEffectSpell(spell))
2921 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2922 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2923 if (IsDispelSpell(spell))
2924 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2925 // Chance resist mechanic (select max value from every mechanic spell effect)
2926 int32 resist_mech = 0;
2927 // Get effects mechanic and chance
2928 for(int eff = 0; eff < MAX_EFFECT_INDEX; ++eff)
2930 int32 effect_mech = GetEffectMechanic(spell, SpellEffectIndex(eff));
2931 if (effect_mech)
2933 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2934 if (resist_mech < temp)
2935 resist_mech = temp;
2938 // Apply mod
2939 modHitChance-=resist_mech;
2941 // Chance resist debuff
2942 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2944 int32 HitChance = modHitChance * 100;
2945 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2946 HitChance += int32(m_modSpellHitChance*100.0f);
2948 // Decrease hit chance from victim rating bonus
2949 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2950 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2952 if (HitChance < 100) HitChance = 100;
2953 if (HitChance > 10000) HitChance = 10000;
2955 int32 tmp = 10000 - HitChance;
2957 int32 rand = irand(0,10000);
2959 if (rand < tmp)
2960 return SPELL_MISS_MISS;
2962 // cast by caster in front of victim
2963 if (pVictim->HasInArc(M_PI_F,this))
2965 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2966 tmp+=deflect_chance;
2967 if (rand < tmp)
2968 return SPELL_MISS_DEFLECT;
2971 return SPELL_MISS_NONE;
2974 // Calculate spell hit result can be:
2975 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2976 // For melee based spells:
2977 // Miss
2978 // Dodge
2979 // Parry
2980 // For spells
2981 // Resist
2982 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2984 // Return evade for units in evade mode
2985 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2986 return SPELL_MISS_EVADE;
2988 // Check for immune
2989 if (pVictim->IsImmunedToSpell(spell))
2990 return SPELL_MISS_IMMUNE;
2992 // All positive spells can`t miss
2993 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2994 if (IsPositiveSpell(spell->Id))
2995 return SPELL_MISS_NONE;
2997 // Check for immune
2998 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2999 return SPELL_MISS_IMMUNE;
3001 // Try victim reflect spell
3002 if (CanReflect)
3004 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
3005 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
3006 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
3007 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
3008 reflectchance += (*i)->GetModifier()->m_amount;
3009 if (reflectchance > 0 && roll_chance_i(reflectchance))
3011 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
3012 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
3013 return SPELL_MISS_REFLECT;
3017 switch (spell->DmgClass)
3019 case SPELL_DAMAGE_CLASS_NONE:
3020 return SPELL_MISS_NONE;
3021 case SPELL_DAMAGE_CLASS_MAGIC:
3022 return MagicSpellHitResult(pVictim, spell);
3023 case SPELL_DAMAGE_CLASS_MELEE:
3024 case SPELL_DAMAGE_CLASS_RANGED:
3025 return MeleeSpellHitResult(pVictim, spell);
3027 return SPELL_MISS_NONE;
3030 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
3032 if(!pVictim)
3033 return 0.0f;
3035 // Base misschance 5%
3036 float misschance = 5.0f;
3038 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
3039 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
3041 bool isNormal = false;
3042 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
3044 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
3046 isNormal = true;
3047 break;
3050 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
3051 misschance = 5.0f;
3052 else
3053 misschance = 24.0f;
3056 // PvP : PvE melee misschances per leveldif > 2
3057 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
3059 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
3060 if(leveldif < 0)
3061 leveldif = 0;
3063 // Hit chance from attacker based on ratings and auras
3064 float m_modHitChance;
3065 if (attType == RANGED_ATTACK)
3066 m_modHitChance = m_modRangedHitChance;
3067 else
3068 m_modHitChance = m_modMeleeHitChance;
3070 if(leveldif < 3)
3071 misschance += (leveldif - m_modHitChance);
3072 else
3073 misschance += ((leveldif - 2) * chance - m_modHitChance);
3075 // Hit chance for victim based on ratings
3076 if (pVictim->GetTypeId()==TYPEID_PLAYER)
3078 if (attType == RANGED_ATTACK)
3079 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
3080 else
3081 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
3084 // Modify miss chance by victim auras
3085 if(attType == RANGED_ATTACK)
3086 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
3087 else
3088 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
3090 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
3091 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
3092 misschance -= skillBonus * 0.04f;
3094 // Limit miss chance from 0 to 60%
3095 if ( misschance < 0.0f)
3096 return 0.0f;
3097 if ( misschance > 60.0f)
3098 return 60.0f;
3100 return misschance;
3103 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
3105 if(GetTypeId() == TYPEID_PLAYER)
3107 // in PvP use full skill instead current skill value
3108 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
3109 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
3110 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
3111 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
3112 return value;
3114 else
3115 return GetUnitMeleeSkill(target);
3118 float Unit::GetUnitDodgeChance() const
3120 if(hasUnitState(UNIT_STAT_STUNNED))
3121 return 0.0f;
3122 if( GetTypeId() == TYPEID_PLAYER )
3123 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
3124 else
3126 if(((Creature const*)this)->isTotem())
3127 return 0.0f;
3128 else
3130 float dodge = 5.0f;
3131 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
3132 return dodge > 0.0f ? dodge : 0.0f;
3137 float Unit::GetUnitParryChance() const
3139 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
3140 return 0.0f;
3142 float chance = 0.0f;
3144 if(GetTypeId() == TYPEID_PLAYER)
3146 Player const* player = (Player const*)this;
3147 if(player->CanParry() )
3149 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true,true);
3150 if(!tmpitem)
3151 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true,true);
3153 if(tmpitem)
3154 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
3157 else if(GetTypeId() == TYPEID_UNIT)
3159 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
3161 chance = 5.0f;
3162 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
3166 return chance > 0.0f ? chance : 0.0f;
3169 float Unit::GetUnitBlockChance() const
3171 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
3172 return 0.0f;
3174 if(GetTypeId() == TYPEID_PLAYER)
3176 Player const* player = (Player const*)this;
3177 if(player->CanBlock() )
3179 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
3180 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
3181 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
3183 // is player but has no block ability or no not broken shield equipped
3184 return 0.0f;
3186 else
3188 if(((Creature const*)this)->isTotem())
3189 return 0.0f;
3190 else
3192 float block = 5.0f;
3193 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
3194 return block > 0.0f ? block : 0.0f;
3199 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
3201 float crit;
3203 if(GetTypeId() == TYPEID_PLAYER)
3205 switch(attackType)
3207 case BASE_ATTACK:
3208 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
3209 break;
3210 case OFF_ATTACK:
3211 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
3212 break;
3213 case RANGED_ATTACK:
3214 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
3215 break;
3216 // Just for good manner
3217 default:
3218 crit = 0.0f;
3219 break;
3222 else
3224 crit = 5.0f;
3225 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
3228 // flat aura mods
3229 if(attackType == RANGED_ATTACK)
3230 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
3231 else
3232 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
3234 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
3236 // reduce crit chance from Rating for players
3237 if (attackType != RANGED_ATTACK)
3238 crit -= pVictim->GetMeleeCritChanceReduction();
3239 else
3240 crit -= pVictim->GetRangedCritChanceReduction();
3242 // Apply crit chance from defence skill
3243 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
3245 if (crit < 0.0f)
3246 crit = 0.0f;
3247 return crit;
3250 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
3252 uint32 value = 0;
3253 if(GetTypeId() == TYPEID_PLAYER)
3255 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true,true);
3257 // feral or unarmed skill only for base attack
3258 if(attType != BASE_ATTACK && !item )
3259 return 0;
3261 if(IsInFeralForm())
3262 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
3264 // weapon skill or (unarmed for base attack)
3265 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
3267 // in PvP use full skill instead current skill value
3268 value = (target && target->GetTypeId() == TYPEID_PLAYER)
3269 ? ((Player*)this)->GetMaxSkillValue(skill)
3270 : ((Player*)this)->GetSkillValue(skill);
3271 // Modify value from ratings
3272 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
3273 switch (attType)
3275 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
3276 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
3277 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
3280 else
3281 value = GetUnitMeleeSkill(target);
3282 return value;
3285 void Unit::_UpdateSpells( uint32 time )
3287 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
3288 _UpdateAutoRepeatSpell();
3290 // remove finished spells from current pointers
3291 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3293 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
3295 m_currentSpells[i]->SetReferencedFromCurrent(false);
3296 m_currentSpells[i] = NULL; // remove pointer
3300 // update auras
3301 // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras
3302 for (m_AurasUpdateIterator = m_Auras.begin(); m_AurasUpdateIterator != m_Auras.end();)
3304 Aura* i_aura = m_AurasUpdateIterator->second;
3305 ++m_AurasUpdateIterator; // need shift to next for allow update if need into aura update
3306 i_aura->UpdateAura(time);
3309 // remove expired auras
3310 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
3312 if ((*i).second)
3314 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
3315 RemoveAura(i);
3316 else
3317 ++i;
3319 else
3320 ++i;
3323 if(!m_gameObj.empty())
3325 GameObjectList::iterator ite1, dnext1;
3326 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
3328 dnext1 = ite1;
3329 //(*i)->Update( difftime );
3330 if( !(*ite1)->isSpawned() )
3332 (*ite1)->SetOwnerGUID(0);
3333 (*ite1)->SetRespawnTime(0);
3334 (*ite1)->Delete();
3335 dnext1 = m_gameObj.erase(ite1);
3337 else
3338 ++dnext1;
3343 void Unit::_UpdateAutoRepeatSpell()
3345 bool isAutoShot = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id == SPELL_ID_AUTOSHOT;
3347 //check movement
3348 if (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving())
3350 // cancel wand shoot
3351 if(!isAutoShot)
3352 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3353 // auto shot just waits
3354 return;
3357 // check spell casts
3358 if (IsNonMeleeSpellCasted(false, false, true))
3360 // cancel wand shoot
3361 if(!isAutoShot)
3363 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3364 return;
3366 // auto shot is delayed by everythihng, except ranged(!) CURRENT_GENERIC_SPELL's -> recheck that
3367 else if (!(m_currentSpells[CURRENT_GENERIC_SPELL] && m_currentSpells[CURRENT_GENERIC_SPELL]->IsRangedSpell()))
3368 return;
3371 //castroutine
3372 if (isAttackReady(RANGED_ATTACK))
3374 // Check if able to cast
3375 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
3377 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3378 return;
3381 // we want to shoot
3382 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
3383 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
3385 // all went good, reset attack
3386 resetAttackTimer(RANGED_ATTACK);
3390 void Unit::SetCurrentCastedSpell( Spell * pSpell )
3392 ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
3394 CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
3396 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3398 // break same type spell if it is not delayed
3399 InterruptSpell(CSpellType,false);
3401 // special breakage effects:
3402 switch (CSpellType)
3404 case CURRENT_GENERIC_SPELL:
3406 // generic spells always break channeled not delayed spells
3407 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3409 // autorepeat breaking
3410 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3412 // break autorepeat if not Auto Shot
3413 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3414 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3416 } break;
3418 case CURRENT_CHANNELED_SPELL:
3420 // channel spells always break generic non-delayed and any channeled spells
3421 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3422 InterruptSpell(CURRENT_CHANNELED_SPELL);
3424 // it also does break autorepeat if not Auto Shot
3425 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3426 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3427 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3428 } break;
3430 case CURRENT_AUTOREPEAT_SPELL:
3432 // only Auto Shoot does not break anything
3433 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3435 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3436 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3437 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3438 // special action: first cast delay
3439 if ( getAttackTimer(RANGED_ATTACK) < 500 )
3440 setAttackTimer(RANGED_ATTACK,500);
3442 } break;
3444 default:
3446 // other spell types don't break anything now
3447 } break;
3450 // current spell (if it is still here) may be safely deleted now
3451 if (m_currentSpells[CSpellType])
3452 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3454 // set new current spell
3455 m_currentSpells[CSpellType] = pSpell;
3456 pSpell->SetReferencedFromCurrent(true);
3458 pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
3461 void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed, bool sendAutoRepeatCancelToClient)
3463 ASSERT(spellType < CURRENT_MAX_SPELL);
3465 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3467 // send autorepeat cancel message for autorepeat spells
3468 if (spellType == CURRENT_AUTOREPEAT_SPELL && sendAutoRepeatCancelToClient)
3470 if(GetTypeId() == TYPEID_PLAYER)
3471 ((Player*)this)->SendAutoRepeatCancel(this);
3474 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3475 m_currentSpells[spellType]->cancel();
3477 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3478 if (m_currentSpells[spellType])
3480 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3481 m_currentSpells[spellType] = NULL;
3486 void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
3488 Spell* spell = m_currentSpells[spellType];
3489 if (!spell)
3490 return;
3492 if (spellType == CURRENT_CHANNELED_SPELL)
3493 spell->SendChannelUpdate(0);
3495 spell->finish(ok);
3499 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3501 // We don't do loop here to explicitly show that melee spell is excluded.
3502 // Maybe later some special spells will be excluded too.
3504 // generic spells are casted when they are not finished and not delayed
3505 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3506 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3507 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3508 return(true);
3510 // channeled spells may be delayed, but they are still considered casted
3511 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3512 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3513 return(true);
3515 // autorepeat spells may be finished or delayed, but they are still considered casted
3516 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3517 return(true);
3519 return(false);
3522 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3524 // generic spells are interrupted if they are not finished or delayed
3525 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3526 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3528 // autorepeat spells are interrupted if they are not finished or delayed
3529 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3530 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3532 // channeled spells are interrupted if they are not finished, even if they are delayed
3533 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3534 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3537 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3539 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3540 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3541 return m_currentSpells[i];
3542 return NULL;
3545 void Unit::SetInFront(Unit const* target)
3547 SetOrientation(GetAngle(target));
3550 void Unit::SetFacingTo(float ori)
3552 // update orientation at server
3553 SetOrientation(ori);
3555 // and client
3556 WorldPacket data;
3557 BuildHeartBeatMsg(&data);
3558 SendMessageToSet(&data, false);
3561 // Consider move this to Creature:: since only creature appear to be able to use this
3562 void Unit::SetFacingToObject(WorldObject* pObject)
3564 if (GetTypeId() != TYPEID_UNIT)
3565 return;
3567 // never face when already moving
3568 if (!IsStopped())
3569 return;
3571 // TODO: figure out under what conditions creature will move towards object instead of facing it where it currently is.
3573 SetOrientation(GetAngle(pObject));
3574 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), SPLINETYPE_FACINGTARGET, ((Creature*)this)->GetSplineFlags(), 0, NULL, pObject->GetGUID());
3577 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3579 if(IsInWater())
3580 return c->canSwim();
3581 else
3582 return c->canWalk() || c->canFly();
3585 bool Unit::IsInWater() const
3587 return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3590 bool Unit::IsUnderWater() const
3592 return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3595 void Unit::DeMorph()
3597 SetDisplayId(GetNativeDisplayId());
3600 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3602 int32 modifier = 0;
3604 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3605 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3606 modifier += (*i)->GetModifier()->m_amount;
3608 return modifier;
3611 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3613 float multiplier = 1.0f;
3615 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3616 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3617 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3619 return multiplier;
3622 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3624 int32 modifier = 0;
3626 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3627 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3628 if ((*i)->GetModifier()->m_amount > modifier)
3629 modifier = (*i)->GetModifier()->m_amount;
3631 return modifier;
3634 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3636 int32 modifier = 0;
3638 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3639 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3640 if ((*i)->GetModifier()->m_amount < modifier)
3641 modifier = (*i)->GetModifier()->m_amount;
3643 return modifier;
3646 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3648 if(!misc_mask)
3649 return 0;
3651 int32 modifier = 0;
3653 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3654 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3656 Modifier* mod = (*i)->GetModifier();
3657 if (mod->m_miscvalue & misc_mask)
3658 modifier += mod->m_amount;
3660 return modifier;
3663 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3665 if(!misc_mask)
3666 return 1.0f;
3668 float multiplier = 1.0f;
3670 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3671 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3673 Modifier* mod = (*i)->GetModifier();
3674 if (mod->m_miscvalue & misc_mask)
3675 multiplier *= (100.0f + mod->m_amount)/100.0f;
3677 return multiplier;
3680 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3682 if(!misc_mask)
3683 return 0;
3685 int32 modifier = 0;
3687 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3688 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3690 Modifier* mod = (*i)->GetModifier();
3691 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3692 modifier = mod->m_amount;
3695 return modifier;
3698 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3700 if(!misc_mask)
3701 return 0;
3703 int32 modifier = 0;
3705 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3706 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3708 Modifier* mod = (*i)->GetModifier();
3709 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3710 modifier = mod->m_amount;
3713 return modifier;
3716 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3718 int32 modifier = 0;
3720 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3721 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3723 Modifier* mod = (*i)->GetModifier();
3724 if (mod->m_miscvalue == misc_value)
3725 modifier += mod->m_amount;
3727 return modifier;
3730 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3732 float multiplier = 1.0f;
3734 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3735 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3737 Modifier* mod = (*i)->GetModifier();
3738 if (mod->m_miscvalue == misc_value)
3739 multiplier *= (100.0f + mod->m_amount)/100.0f;
3741 return multiplier;
3744 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3746 int32 modifier = 0;
3748 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3749 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3751 Modifier* mod = (*i)->GetModifier();
3752 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3753 modifier = mod->m_amount;
3756 return modifier;
3759 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3761 int32 modifier = 0;
3763 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3764 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3766 Modifier* mod = (*i)->GetModifier();
3767 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3768 modifier = mod->m_amount;
3771 return modifier;
3774 float Unit::GetTotalAuraMultiplierByMiscValueForMask(AuraType auratype, uint32 mask) const
3776 if(!mask)
3777 return 1.0f;
3779 float multiplier = 1.0f;
3781 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3782 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3784 Modifier* mod = (*i)->GetModifier();
3785 if (mask & (1 << (mod->m_miscvalue -1)))
3786 multiplier *= (100.0f + mod->m_amount)/100.0f;
3788 return multiplier;
3791 bool Unit::AddAura(Aura *Aur)
3793 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3795 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3796 if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
3797 !IsDeathOnlySpell(aurSpellInfo) &&
3798 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3800 delete Aur;
3801 return false;
3804 if(Aur->GetTarget() != this)
3806 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3807 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3808 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3809 delete Aur;
3810 return false;
3813 // m_auraname can be modified to SPELL_AURA_NONE for area auras, this expected for this value
3814 AuraType aurName = Aur->GetModifier()->m_auraname;
3816 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3817 AuraMap::iterator i = m_Auras.find( spair );
3819 // take out same spell
3820 if (i != m_Auras.end())
3822 // passive and persistent auras can stack with themselves any number of times
3823 if (!Aur->IsPassive() && !Aur->IsPersistent())
3825 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3827 Aura* aur2 = i2->second;
3828 if(aur2->GetCasterGUID()==Aur->GetCasterGUID())
3830 // Aura can stack on self -> Stack it;
3831 if(aurSpellInfo->StackAmount)
3833 // can be created with >1 stack by some spell mods
3834 aur2->modStackAmount(Aur->GetStackAmount());
3835 delete Aur;
3836 return false;
3839 // Check for coexisting Weapon-proced Auras
3840 if (Aur->isWeaponBuffCoexistableWith(aur2))
3841 continue;
3843 // Carry over removed Aura's remaining damage if Aura still has ticks remaining
3844 if (aur2->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_STACK_DOT_MODIFIER && aurName == SPELL_AURA_PERIODIC_DAMAGE && aur2->GetAuraDuration() > 0)
3846 int32 remainingTicks = aur2->GetAuraMaxTicks() - aur2->GetAuraTicks();
3847 int32 remainingDamage = aur2->GetModifier()->m_amount * remainingTicks;
3849 Aur->GetModifier()->m_amount += int32(remainingDamage / Aur->GetAuraMaxTicks());
3851 // can be only single (this check done at _each_ aura add
3852 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3853 break;
3856 bool stop = false;
3858 // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original
3859 AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()]);
3861 switch(aurNameReal)
3863 // DoT/HoT/etc
3864 case SPELL_AURA_DUMMY: // allow stack
3865 case SPELL_AURA_PERIODIC_DAMAGE:
3866 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3867 case SPELL_AURA_PERIODIC_LEECH:
3868 case SPELL_AURA_PERIODIC_HEAL:
3869 case SPELL_AURA_OBS_MOD_HEALTH:
3870 case SPELL_AURA_PERIODIC_MANA_LEECH:
3871 case SPELL_AURA_OBS_MOD_MANA:
3872 case SPELL_AURA_POWER_BURN_MANA:
3873 break;
3874 case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable
3875 default: // not allow
3876 // can be only single (this check done at _each_ aura add
3877 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3878 stop = true;
3879 break;
3882 if(stop)
3883 break;
3888 // passive auras not stacable with other ranks
3889 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3891 if (!RemoveNoStackAurasDueToAura(Aur))
3893 delete Aur;
3894 return false; // couldn't remove conflicting aura with higher rank
3898 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3899 if (Aur->IsSingleTarget() && Aur->GetTarget())
3901 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3902 for(;;)
3904 Unit* caster = Aur->GetCaster();
3905 if(!caster) // caster deleted and not required adding scAura
3906 break;
3908 bool restart = false;
3909 AuraList& scAuras = caster->GetSingleCastAuras();
3910 for(AuraList::const_iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3912 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3913 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3915 if ((*itr)->IsInUse())
3917 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());
3918 continue;
3920 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3921 restart = true;
3922 break;
3926 if(!restart)
3928 // done
3929 scAuras.push_back(Aur);
3930 break;
3935 // add aura, register in lists and arrays
3936 Aur->_AddAura();
3937 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3938 if (aurName < TOTAL_AURAS)
3940 m_modAuras[aurName].push_back(Aur);
3943 Aur->ApplyModifier(true,true);
3944 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura %u now is in use", aurName);
3946 // if aura deleted before boosts apply ignore
3947 // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier
3948 if (Aur->IsDeleted())
3949 return false;
3951 if(IsSpellLastAuraEffect(aurSpellInfo,Aur->GetEffIndex()))
3952 Aur->HandleSpellSpecificBoosts(true);
3954 return true;
3957 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3959 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3960 if(!spellInfo)
3961 return;
3962 AuraMap::const_iterator i,next;
3963 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3965 next = i;
3966 ++next;
3967 uint32 i_spellId = (*i).second->GetId();
3968 if((*i).second && i_spellId && i_spellId != spellId)
3970 if(sSpellMgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3972 RemoveAurasDueToSpell(i_spellId);
3974 if( m_Auras.empty() )
3975 break;
3976 else
3977 next = m_Auras.begin();
3983 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3985 if (!Aur)
3986 return false;
3988 SpellEntry const* spellProto = Aur->GetSpellProto();
3989 if (!spellProto)
3990 return false;
3992 uint32 spellId = Aur->GetId();
3993 SpellEffectIndex effIndex = Aur->GetEffIndex();
3995 // passive spell special case (only non stackable with ranks)
3996 if(IsPassiveSpell(spellId))
3998 if(IsPassiveSpellStackableWithRanks(spellProto))
3999 return true;
4002 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
4004 AuraMap::iterator i,next;
4005 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
4007 next = i;
4008 ++next;
4009 if (!(*i).second) continue;
4011 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
4013 if (!i_spellProto)
4014 continue;
4016 uint32 i_spellId = i_spellProto->Id;
4018 // early checks that spellId is passive non stackable spell
4019 if(IsPassiveSpell(i_spellId))
4021 // passive non-stackable spells not stackable only for same caster
4022 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
4023 continue;
4025 // passive non-stackable spells not stackable only with another rank of same spell
4026 if (!sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
4027 continue;
4030 SpellEffectIndex i_effIndex = (*i).second->GetEffIndex();
4032 if(i_spellId == spellId) continue;
4034 bool is_triggered_by_spell = false;
4035 // prevent triggering aura of removing aura that triggered it
4036 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
4037 if (i_spellProto->EffectTriggerSpell[j] == spellId)
4038 is_triggered_by_spell = true;
4040 // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
4041 for(int j = 0; j < MAX_EFFECT_INDEX; ++j)
4042 if (spellProto->EffectTriggerSpell[j] == i_spellId)
4043 is_triggered_by_spell = true;
4045 if (is_triggered_by_spell)
4046 continue;
4048 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
4050 // single allowed spell specific from same caster or from any caster at target
4051 bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec,i_spellId_spec);
4052 bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec,i_spellId_spec);
4053 if( is_spellSpecPerTarget || is_spellSpecPerTargetPerCaster && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
4055 // cannot remove higher rank
4056 if (sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
4057 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
4058 return false;
4060 // Its a parent aura (create this aura in ApplyModifier)
4061 if ((*i).second->IsInUse())
4063 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());
4064 continue;
4066 RemoveAurasDueToSpell(i_spellId);
4068 if( m_Auras.empty() )
4069 break;
4070 else
4071 next = m_Auras.begin();
4073 continue;
4076 // spell with spell specific that allow single ranks for spell from diff caster
4077 // same caster case processed or early or later
4078 bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec,i_spellId_spec);
4079 if ( is_spellPerTarget && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && sSpellMgr.IsRankSpellDueToSpell(spellProto, i_spellId))
4081 // cannot remove higher rank
4082 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
4083 return false;
4085 // Its a parent aura (create this aura in ApplyModifier)
4086 if ((*i).second->IsInUse())
4088 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());
4089 continue;
4091 RemoveAurasDueToSpell(i_spellId);
4093 if( m_Auras.empty() )
4094 break;
4095 else
4096 next = m_Auras.begin();
4098 continue;
4101 // non single (per caster) per target spell specific (possible single spell per target at caster)
4102 if( !is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && sSpellMgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
4104 // Its a parent aura (create this aura in ApplyModifier)
4105 if ((*i).second->IsInUse())
4107 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());
4108 continue;
4110 RemoveAurasDueToSpell(i_spellId);
4112 if( m_Auras.empty() )
4113 break;
4114 else
4115 next = m_Auras.begin();
4117 continue;
4120 // Potions stack aura by aura (elixirs/flask already checked)
4121 if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
4123 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
4125 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
4126 return false; // cannot remove higher rank
4128 // Its a parent aura (create this aura in ApplyModifier)
4129 if ((*i).second->IsInUse())
4131 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());
4132 continue;
4134 RemoveAura(i);
4135 next = i;
4139 return true;
4142 void Unit::RemoveAura(uint32 spellId, SpellEffectIndex effindex, Aura* except)
4144 spellEffectPair spair = spellEffectPair(spellId, effindex);
4145 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4147 if(iter->second!=except)
4149 RemoveAura(iter);
4150 iter = m_Auras.lower_bound(spair);
4152 else
4153 ++iter;
4157 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
4159 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4161 Aura *aur = iter->second;
4162 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4163 RemoveAura(iter);
4164 else
4165 ++iter;
4169 void Unit::RemoveAurasByCasterSpell(uint32 spellId, SpellEffectIndex effindex, uint64 casterGUID)
4171 spellEffectPair spair = spellEffectPair(spellId, effindex);
4172 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4174 Aura *aur = iter->second;
4175 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4177 RemoveAura(iter);
4178 iter = m_Auras.lower_bound(spair);
4180 else
4181 ++iter;
4185 void Unit::RemoveSingleAuraDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
4187 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellId);
4189 // Custom dispel cases
4190 // Unstable Affliction
4191 if(spellEntry->SpellFamilyName == SPELLFAMILY_WARLOCK && (spellEntry->SpellFamilyFlags & UI64LIT(0x010000000000)))
4193 if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE,SPELLFAMILY_WARLOCK,UI64LIT(0x010000000000),0x00000000,casterGUID))
4195 // use clean value for initial damage
4196 int32 damage = dotAura->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_0);
4197 damage *= 9;
4199 // Remove spell auras from stack
4200 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4202 // backfire damage and silence
4203 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,casterGUID);
4204 return;
4207 // Flame Shock
4208 else if (spellEntry->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellEntry->SpellFamilyFlags & UI64LIT(0x10000000)))
4210 Unit* caster = NULL;
4211 uint32 triggeredSpell = 0;
4213 if (Aura* dotAura = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x10000000), 0x00000000, casterGUID))
4214 caster = dotAura->GetCaster();
4216 if (caster && !caster->isDead())
4218 Unit::AuraList const& auras = caster->GetAurasByType(SPELL_AURA_DUMMY);
4219 for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); ++i)
4221 switch((*i)->GetId())
4223 case 51480: triggeredSpell=64694; break;// Lava Flows, Rank 1
4224 case 51481: triggeredSpell=65263; break;// Lava Flows, Rank 2
4225 case 51482: triggeredSpell=65264; break;// Lava Flows, Rank 3
4226 default: continue;
4228 break;
4232 // Remove spell auras from stack
4233 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4235 // Haste
4236 if (triggeredSpell)
4237 caster->CastSpell(caster, triggeredSpell, true);
4238 return;
4240 // Vampiric touch (first dummy aura)
4241 else if (spellEntry->SpellFamilyName == SPELLFAMILY_PRIEST && spellEntry->SpellFamilyFlags & UI64LIT(0x0000040000000000))
4243 if (Aura *dot = GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000040000000000), 0x00000000, casterGUID))
4245 if(Unit* caster = dot->GetCaster())
4247 // use clean value for initial damage
4248 int32 bp0 = dot->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_1);
4249 bp0 *= 8;
4251 // Remove spell auras from stack
4252 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4254 CastCustomSpell(this, 64085, &bp0, NULL, NULL, true, NULL, NULL, casterGUID);
4255 return;
4260 RemoveSingleSpellAurasByCasterSpell(spellId, casterGUID, AURA_REMOVE_BY_DISPEL);
4263 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
4265 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4267 Aura *aur = iter->second;
4268 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4270 int32 basePoints = aur->GetBasePoints();
4271 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
4272 // some different constructors
4273 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
4275 // set its duration and maximum duration
4276 // max duration 2 minutes (in msecs)
4277 int32 dur = aur->GetAuraDuration();
4278 int32 max_dur = 2*MINUTE*IN_MILLISECONDS;
4279 int32 new_max_dur = max_dur > dur ? dur : max_dur;
4280 new_aur->SetAuraMaxDuration( new_max_dur );
4281 new_aur->SetAuraDuration( new_max_dur );
4283 // set periodic to do at least one tick (for case when original aura has been at last tick preparing)
4284 int32 periodic = aur->GetModifier()->periodictime;
4285 new_aur->GetModifier()->periodictime = periodic < new_max_dur ? periodic : new_max_dur;
4287 // Unregister _before_ adding to stealer
4288 aur->UnregisterSingleCastAura();
4290 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
4291 new_aur->SetIsSingleTarget(false);
4293 // add the new aura to stealer
4294 stealer->AddAura(new_aur);
4296 // Remove aura as dispel
4297 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
4299 else
4300 ++iter;
4304 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
4306 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4308 if (iter->second->GetId() == spellId)
4309 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
4310 else
4311 ++iter;
4315 void Unit::RemoveAurasWithDispelType( DispelType type )
4317 // Create dispel mask by dispel type
4318 uint32 dispelMask = GetDispellMask(type);
4319 // Dispel all existing auras vs current dispel type
4320 AuraMap& auras = GetAuras();
4321 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
4323 SpellEntry const* spell = itr->second->GetSpellProto();
4324 if( (1<<spell->Dispel) & dispelMask )
4326 // Dispel aura
4327 RemoveAurasDueToSpell(spell->Id);
4328 itr = auras.begin();
4330 else
4331 ++itr;
4335 void Unit::RemoveSingleAuraFromStack(AuraMap::iterator &i, AuraRemoveMode mode)
4337 if (i->second->modStackAmount(-1))
4338 RemoveAura(i,mode);
4342 void Unit::RemoveSingleAuraFromStack(uint32 spellId, SpellEffectIndex effindex, AuraRemoveMode mode)
4344 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4345 if(iter != m_Auras.end())
4346 RemoveSingleAuraFromStack(iter,mode);
4349 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId, AuraRemoveMode mode)
4351 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
4352 RemoveSingleAuraFromStack(spellId, SpellEffectIndex(i), mode);
4355 void Unit::RemoveSingleSpellAurasByCasterSpell(uint32 spellId, uint64 casterGUID, AuraRemoveMode mode)
4357 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
4358 RemoveSingleAuraByCasterSpell(spellId, SpellEffectIndex(i), casterGUID, mode);
4361 void Unit::RemoveSingleAuraByCasterSpell(uint32 spellId, SpellEffectIndex effindex, uint64 casterGUID, AuraRemoveMode mode)
4363 spellEffectPair spair = spellEffectPair(spellId, effindex);
4364 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
4366 Aura *aur = iter->second;
4367 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
4369 RemoveSingleAuraFromStack(iter,mode);
4370 break;
4376 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
4378 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
4379 RemoveAura(spellId,SpellEffectIndex(i),except);
4382 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
4384 for (int k=0; k < MAX_EFFECT_INDEX; ++k)
4386 spellEffectPair spair = spellEffectPair(spellId, SpellEffectIndex(k));
4387 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
4389 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
4391 RemoveAura(iter);
4392 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
4394 else
4395 ++iter;
4400 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
4402 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4404 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
4405 RemoveAura(iter);
4406 else
4407 ++iter;
4411 void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
4413 // single target auras from other casters
4414 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
4416 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
4418 if(!newPhase)
4419 RemoveAura(iter);
4420 else
4422 Unit* caster = iter->second->GetCaster();
4423 if(!caster || !caster->InSamePhase(newPhase))
4424 RemoveAura(iter);
4425 else
4426 ++iter;
4429 else
4430 ++iter;
4433 // single target auras at other targets
4434 AuraList& scAuras = GetSingleCastAuras();
4435 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
4437 Aura* aura = *iter;
4438 if (aura->GetTarget() != this && !aura->GetTarget()->InSamePhase(newPhase))
4440 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
4441 aura->GetTarget()->RemoveAura(aura);
4442 iter = scAuras.begin();
4444 else
4445 ++iter;
4450 void Unit::RemoveAura(Aura* aura, AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4452 AuraMap::iterator i = m_Auras.lower_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4453 AuraMap::iterator upperBound = m_Auras.upper_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
4454 for (; i != upperBound; ++i)
4456 if (i->second == aura)
4458 RemoveAura(i,mode);
4459 return;
4462 DEBUG_LOG("Trying to remove aura id %u effect %u by pointer but aura not found on target", aura->GetId(), aura->GetEffIndex());
4465 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
4467 Aura* Aur = i->second;
4468 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
4470 Aur->UnregisterSingleCastAura();
4472 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
4473 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
4475 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
4478 // Set remove mode
4479 Aur->SetRemoveMode(mode);
4481 // if unit currently update aura list then make safe update iterator shift to next
4482 if (m_AurasUpdateIterator == i)
4483 ++m_AurasUpdateIterator;
4485 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
4486 // remove aura from list before to prevent deleting it before
4487 m_Auras.erase(i);
4489 // now aura removed from from list and can't be deleted by indirect call but can be referenced from callers
4491 // Statue unsummoned at aura remove
4492 Totem* statue = NULL;
4493 if(IsChanneledSpell(AurSpellInfo))
4494 if(Unit* caster = Aur->GetCaster())
4495 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
4496 statue = ((Totem*)caster);
4498 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
4500 // some auras also need to apply modifier (on caster) on remove
4501 if (mode != AURA_REMOVE_BY_DELETE || Aur->GetModifier()->m_auraname == SPELL_AURA_MOD_POSSESS)
4502 Aur->ApplyModifier(false,true);
4504 if (Aur->_RemoveAura())
4506 // last aura in stack removed
4507 if (mode != AURA_REMOVE_BY_DELETE && IsSpellLastAuraEffect(Aur->GetSpellProto(),Aur->GetEffIndex()))
4508 Aur->HandleSpellSpecificBoosts(false);
4511 // If aura in use (removed from code that plan access to it data after return)
4512 // store it in aura list with delayed deletion
4513 if (Aur->IsInUse())
4514 m_deletedAuras.push_back(Aur);
4515 else
4516 delete Aur;
4518 if(statue)
4519 statue->UnSummon();
4521 // only way correctly remove all auras from list
4522 if( m_Auras.empty() )
4523 i = m_Auras.end();
4524 else
4525 i = m_Auras.begin();
4529 void Unit::RemoveAllAuras(AuraRemoveMode mode /*= AURA_REMOVE_BY_DEFAULT*/)
4531 while (!m_Auras.empty())
4533 AuraMap::iterator iter = m_Auras.begin();
4534 RemoveAura(iter,mode);
4538 void Unit::RemoveArenaAuras(bool onleave)
4540 // in join, remove positive buffs, on end, remove negative
4541 // used to remove positive visible auras in arenas
4542 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4544 if (!(iter->second->GetSpellProto()->AttributesEx4 & SPELL_ATTR_EX4_UNK21) &&
4545 // don't remove stances, shadowform, pally/hunter auras
4546 !iter->second->IsPassive() && // don't remove passive auras
4547 (!(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) ||
4548 !(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) &&
4549 // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
4550 (iter->second->IsPositive() != onleave)) // remove positive buffs on enter, negative buffs on leave
4551 RemoveAura(iter);
4552 else
4553 ++iter;
4557 void Unit::RemoveAllAurasOnDeath()
4559 // used just after dieing to remove all visible auras
4560 // and disable the mods for the passive ones
4561 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4563 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
4564 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
4565 else
4566 ++iter;
4570 void Unit::DelayAura(uint32 spellId, SpellEffectIndex effindex, int32 delaytime)
4572 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4573 if (iter != m_Auras.end())
4575 if (iter->second->GetAuraDuration() < delaytime)
4576 iter->second->SetAuraDuration(0);
4577 else
4578 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
4579 iter->second->SendAuraUpdate(false);
4580 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
4584 void Unit::_RemoveAllAuraMods()
4586 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4588 (*i).second->ApplyModifier(false);
4592 void Unit::_ApplyAllAuraMods()
4594 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4596 (*i).second->ApplyModifier(true);
4600 Aura* Unit::GetAura(uint32 spellId, SpellEffectIndex effindex)
4602 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4603 if (iter != m_Auras.end())
4604 return iter->second;
4605 return NULL;
4608 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
4610 AuraList const& auras = GetAurasByType(type);
4611 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
4613 SpellEntry const *spell = (*i)->GetSpellProto();
4614 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
4616 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
4617 continue;
4618 return (*i);
4621 return NULL;
4624 bool Unit::HasAura(uint32 spellId) const
4626 for (int i = 0; i < MAX_EFFECT_INDEX ; ++i)
4628 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, SpellEffectIndex(i)));
4629 if (iter != m_Auras.end())
4630 return true;
4632 return false;
4635 void Unit::AddDynObject(DynamicObject* dynObj)
4637 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4640 void Unit::RemoveDynObject(uint32 spellid)
4642 if(m_dynObjGUIDs.empty())
4643 return;
4644 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4646 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4647 if(!dynObj)
4649 i = m_dynObjGUIDs.erase(i);
4651 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4653 dynObj->Delete();
4654 i = m_dynObjGUIDs.erase(i);
4656 else
4657 ++i;
4661 void Unit::RemoveAllDynObjects()
4663 while(!m_dynObjGUIDs.empty())
4665 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4666 if(dynObj)
4667 dynObj->Delete();
4668 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4672 DynamicObject * Unit::GetDynObject(uint32 spellId, SpellEffectIndex effIndex)
4674 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4676 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4677 if(!dynObj)
4679 i = m_dynObjGUIDs.erase(i);
4680 continue;
4683 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4684 return dynObj;
4685 ++i;
4687 return NULL;
4690 DynamicObject * Unit::GetDynObject(uint32 spellId)
4692 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4694 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4695 if(!dynObj)
4697 i = m_dynObjGUIDs.erase(i);
4698 continue;
4701 if (dynObj->GetSpellId() == spellId)
4702 return dynObj;
4703 ++i;
4705 return NULL;
4708 GameObject* Unit::GetGameObject(uint32 spellId) const
4710 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
4711 if ((*i)->GetSpellId() == spellId)
4712 return *i;
4714 return NULL;
4717 void Unit::AddGameObject(GameObject* gameObj)
4719 ASSERT(gameObj && gameObj->GetOwnerGUID()==0);
4720 m_gameObj.push_back(gameObj);
4721 gameObj->SetOwnerGUID(GetGUID());
4723 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4725 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4726 // Need disable spell use for owner
4727 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4728 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4729 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4733 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4735 ASSERT(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4737 gameObj->SetOwnerGUID(0);
4739 // GO created by some spell
4740 if (uint32 spellid = gameObj->GetSpellId())
4742 RemoveAurasDueToSpell(spellid);
4744 if (GetTypeId()==TYPEID_PLAYER)
4746 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4747 // Need activate spell use for owner
4748 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4749 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4750 ((Player*)this)->SendCooldownEvent(createBySpell);
4754 m_gameObj.remove(gameObj);
4756 if(del)
4758 gameObj->SetRespawnTime(0);
4759 gameObj->Delete();
4763 void Unit::RemoveGameObject(uint32 spellid, bool del)
4765 if(m_gameObj.empty())
4766 return;
4767 GameObjectList::iterator i, next;
4768 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4770 next = i;
4771 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4773 (*i)->SetOwnerGUID(0);
4774 if(del)
4776 (*i)->SetRespawnTime(0);
4777 (*i)->Delete();
4780 next = m_gameObj.erase(i);
4782 else
4783 ++next;
4787 void Unit::RemoveAllGameObjects()
4789 // remove references to unit
4790 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4792 (*i)->SetOwnerGUID(0);
4793 (*i)->SetRespawnTime(0);
4794 (*i)->Delete();
4795 i = m_gameObj.erase(i);
4799 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4801 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
4802 data << log->target->GetPackGUID();
4803 data << log->attacker->GetPackGUID();
4804 data << uint32(log->SpellID);
4805 data << uint32(log->damage); // damage amount
4806 data << uint32(log->overkill); // overkill
4807 data << uint8 (log->schoolMask); // damage school
4808 data << uint32(log->absorb); // AbsorbedDamage
4809 data << uint32(log->resist); // resist
4810 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
4811 data << uint8 (log->unused); // unused
4812 data << uint32(log->blocked); // blocked
4813 data << uint32(log->HitInfo);
4814 data << uint8 (0); // flag to use extend data
4815 SendMessageToSet( &data, true );
4818 void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4820 SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
4821 log.damage = Damage - AbsorbedDamage - Resist - Blocked;
4822 log.absorb = AbsorbedDamage;
4823 log.resist = Resist;
4824 log.physicalLog = PhysicalDamage;
4825 log.blocked = Blocked;
4826 log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
4827 if(CriticalHit)
4828 log.HitInfo |= SPELL_HIT_TYPE_CRIT;
4829 SendSpellNonMeleeDamageLog(&log);
4832 void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
4834 Aura *aura = pInfo->aura;
4835 Modifier *mod = aura->GetModifier();
4837 WorldPacket data(SMSG_PERIODICAURALOG, 30);
4838 data << aura->GetTarget()->GetPackGUID();
4839 data.appendPackGUID(aura->GetCasterGUID());
4840 data << uint32(aura->GetId()); // spellId
4841 data << uint32(1); // count
4842 data << uint32(mod->m_auraname); // auraId
4843 switch(mod->m_auraname)
4845 case SPELL_AURA_PERIODIC_DAMAGE:
4846 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
4847 data << uint32(pInfo->damage); // damage
4848 data << uint32(pInfo->overDamage); // overkill?
4849 data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
4850 data << uint32(pInfo->absorb); // absorb
4851 data << uint32(pInfo->resist); // resist
4852 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4853 break;
4854 case SPELL_AURA_PERIODIC_HEAL:
4855 case SPELL_AURA_OBS_MOD_HEALTH:
4856 data << uint32(pInfo->damage); // damage
4857 data << uint32(pInfo->overDamage); // overheal?
4858 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4859 break;
4860 case SPELL_AURA_OBS_MOD_MANA:
4861 case SPELL_AURA_PERIODIC_ENERGIZE:
4862 data << uint32(mod->m_miscvalue); // power type
4863 data << uint32(pInfo->damage); // damage
4864 break;
4865 case SPELL_AURA_PERIODIC_MANA_LEECH:
4866 data << uint32(mod->m_miscvalue); // power type
4867 data << uint32(pInfo->damage); // amount
4868 data << float(pInfo->multiplier); // gain multiplier
4869 break;
4870 default:
4871 sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(mod->m_auraname));
4872 return;
4875 aura->GetTarget()->SendMessageToSet(&data, true);
4878 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4880 // Not much to do if no flags are set.
4881 if (procAttacker)
4882 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4883 // Now go on with a victim's events'n'auras
4884 // Not much to do if no flags are set or there is no victim
4885 if(pVictim && pVictim->isAlive() && procVictim)
4886 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4889 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4891 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4892 data << uint32(spellID);
4893 data << uint64(GetGUID());
4894 data << uint8(0); // can be 0 or 1
4895 data << uint32(1); // target count
4896 // for(i = 0; i < target count; ++i)
4897 data << uint64(target->GetGUID()); // target GUID
4898 data << uint8(missInfo);
4899 // end loop
4900 SendMessageToSet(&data, true);
4903 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4905 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4907 uint32 count = 1;
4908 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
4909 data << uint32(damageInfo->HitInfo);
4910 data << damageInfo->attacker->GetPackGUID();
4911 data << damageInfo->target->GetPackGUID();
4912 data << uint32(damageInfo->damage); // Full damage
4913 data << uint32(0); // overkill value
4914 data << uint8(count); // Sub damage count
4916 for(uint32 i = 0; i < count; ++i)
4918 data << uint32(damageInfo->damageSchoolMask); // School of sub damage
4919 data << float(damageInfo->damage); // sub damage
4920 data << uint32(damageInfo->damage); // Sub Damage
4923 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4925 for(uint32 i = 0; i < count; ++i)
4926 data << uint32(damageInfo->absorb); // Absorb
4929 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4931 for(uint32 i = 0; i < count; ++i)
4932 data << uint32(damageInfo->resist); // Resist
4935 data << uint8(damageInfo->TargetState);
4936 data << uint32(0);
4937 data << uint32(0);
4939 if(damageInfo->HitInfo & HITINFO_BLOCK)
4940 data << uint32(damageInfo->blocked_amount);
4942 if(damageInfo->HitInfo & HITINFO_UNK3)
4943 data << uint32(0);
4945 if(damageInfo->HitInfo & HITINFO_UNK1)
4947 data << uint32(0);
4948 data << float(0);
4949 data << float(0);
4950 data << float(0);
4951 data << float(0);
4952 data << float(0);
4953 data << float(0);
4954 data << float(0);
4955 data << float(0);
4956 for(uint8 i = 0; i < 5; ++i)
4958 data << float(0);
4959 data << float(0);
4961 data << uint32(0);
4964 SendMessageToSet( &data, true );
4967 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 /*SwingType*/, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4969 CalcDamageInfo dmgInfo;
4970 dmgInfo.HitInfo = HitInfo;
4971 dmgInfo.attacker = this;
4972 dmgInfo.target = target;
4973 dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
4974 dmgInfo.damageSchoolMask = damageSchoolMask;
4975 dmgInfo.absorb = AbsorbDamage;
4976 dmgInfo.resist = Resist;
4977 dmgInfo.TargetState = TargetState;
4978 dmgInfo.blocked_amount = BlockedAmount;
4979 SendAttackStateUpdate(&dmgInfo);
4982 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4984 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4986 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4987 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4989 uint32 triggered_spell_id = 0;
4990 Unit* target = pVictim;
4991 int32 basepoints0 = 0;
4993 switch(hasteSpell->SpellFamilyName)
4995 case SPELLFAMILY_ROGUE:
4997 switch(hasteSpell->Id)
4999 // Blade Flurry
5000 case 13877:
5001 case 33735:
5003 target = SelectRandomUnfriendlyTarget(pVictim);
5004 if(!target)
5005 return false;
5006 basepoints0 = damage;
5007 triggered_spell_id = 22482;
5008 break;
5011 break;
5015 // processed charge only counting case
5016 if(!triggered_spell_id)
5017 return true;
5019 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5021 if(!triggerEntry)
5023 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
5024 return false;
5027 // default case
5028 if(!target || target!=this && !target->isAlive())
5029 return false;
5031 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5032 return false;
5034 if(basepoints0)
5035 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5036 else
5037 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5039 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5040 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5042 return true;
5045 bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
5047 SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
5049 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5050 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5052 uint32 triggered_spell_id = 0;
5053 Unit* target = pVictim;
5054 int32 basepoints0 = 0;
5056 switch(triggeredByAuraSpell->SpellFamilyName)
5058 case SPELLFAMILY_MAGE:
5060 switch(triggeredByAuraSpell->Id)
5062 // Focus Magic
5063 case 54646:
5065 Unit* caster = triggeredByAura->GetCaster();
5066 if(!caster)
5067 return false;
5069 triggered_spell_id = 54648;
5070 target = caster;
5071 break;
5077 // processed charge only counting case
5078 if(!triggered_spell_id)
5079 return true;
5081 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5083 if(!triggerEntry)
5085 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
5086 return false;
5089 // default case
5090 if(!target || target!=this && !target->isAlive())
5091 return false;
5093 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5094 return false;
5096 if(basepoints0)
5097 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5098 else
5099 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5101 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5102 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5104 return true;
5107 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
5109 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
5110 SpellEffectIndex effIndex = triggeredByAura->GetEffIndex();
5111 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5113 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
5114 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
5116 uint32 triggered_spell_id = 0;
5117 Unit* target = pVictim;
5118 int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0};
5120 switch(dummySpell->SpellFamilyName)
5122 case SPELLFAMILY_GENERIC:
5124 switch (dummySpell->Id)
5126 // Eye for an Eye
5127 case 9799:
5128 case 25988:
5130 // return damage % to attacker but < 50% own total health
5131 basepoints[0] = triggerAmount*int32(damage)/100;
5132 if (basepoints[0] > (int32)GetMaxHealth()/2)
5133 basepoints[0] = (int32)GetMaxHealth()/2;
5135 triggered_spell_id = 25997;
5136 break;
5138 // Sweeping Strikes (NPC spells may be)
5139 case 18765:
5140 case 35429:
5142 // prevent chain of triggered spell from same triggered spell
5143 if (procSpell && procSpell->Id == 26654)
5144 return false;
5146 target = SelectRandomUnfriendlyTarget(pVictim);
5147 if(!target)
5148 return false;
5150 triggered_spell_id = 26654;
5151 break;
5153 // Twisted Reflection (boss spell)
5154 case 21063:
5155 triggered_spell_id = 21064;
5156 break;
5157 // Unstable Power
5158 case 24658:
5160 if (!procSpell || procSpell->Id == 24659)
5161 return false;
5162 // Need remove one 24659 aura
5163 RemoveSingleSpellAurasFromStack(24659);
5164 return true;
5166 // Restless Strength
5167 case 24661:
5169 // Need remove one 24662 aura
5170 RemoveSingleSpellAurasFromStack(24662);
5171 return true;
5173 // Adaptive Warding (Frostfire Regalia set)
5174 case 28764:
5176 if(!procSpell)
5177 return false;
5179 // find Mage Armor
5180 bool found = false;
5181 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
5182 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
5184 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
5186 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000)))
5188 found=true;
5189 break;
5193 if(!found)
5194 return false;
5196 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5198 case SPELL_SCHOOL_NORMAL:
5199 case SPELL_SCHOOL_HOLY:
5200 return false; // ignored
5201 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
5202 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
5203 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
5204 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
5205 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
5206 default:
5207 return false;
5210 target = this;
5211 break;
5213 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
5214 case 27539:
5216 if(!procSpell)
5217 return false;
5219 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
5221 case SPELL_SCHOOL_NORMAL:
5222 return false; // ignore
5223 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
5224 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
5225 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
5226 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
5227 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
5228 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
5229 default:
5230 return false;
5233 target = this;
5234 break;
5236 // Mana Leech (Passive) (Priest Pet Aura)
5237 case 28305:
5239 // Cast on owner
5240 target = GetOwner();
5241 if(!target)
5242 return false;
5244 triggered_spell_id = 34650;
5245 break;
5247 // Divine purpose
5248 case 31871:
5249 case 31872:
5251 // Roll chane
5252 if (!roll_chance_i(triggerAmount))
5253 return false;
5255 // Remove any stun effect on target
5256 AuraMap& Auras = pVictim->GetAuras();
5257 for(AuraMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
5259 SpellEntry const *spell = iter->second->GetSpellProto();
5260 if( spell->Mechanic == MECHANIC_STUN ||
5261 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
5263 pVictim->RemoveAurasDueToSpell(spell->Id);
5264 iter = Auras.begin();
5266 else
5267 ++iter;
5269 return true;
5271 // Mark of Malice
5272 case 33493:
5274 // Cast finish spell at last charge
5275 if (triggeredByAura->GetAuraCharges() > 1)
5276 return false;
5278 target = this;
5279 triggered_spell_id = 33494;
5280 break;
5282 // Vampiric Aura (boss spell)
5283 case 38196:
5285 basepoints[0] = 3 * damage; // 300%
5286 if (basepoints[0] < 0)
5287 return false;
5289 triggered_spell_id = 31285;
5290 target = this;
5291 break;
5293 // Aura of Madness (Darkmoon Card: Madness trinket)
5294 //=====================================================
5295 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
5296 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
5297 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
5298 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5299 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
5300 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
5301 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
5302 // 41011 Martyr Complex: +35 stamina (All classes)
5303 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5304 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
5305 case 39446:
5307 if(GetTypeId() != TYPEID_PLAYER)
5308 return false;
5310 // Select class defined buff
5311 switch (getClass())
5313 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
5314 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
5316 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
5317 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5318 break;
5320 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
5321 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
5323 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
5324 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5325 break;
5327 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
5328 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
5329 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
5330 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
5332 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
5333 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5334 break;
5336 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
5338 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
5339 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
5340 break;
5342 default:
5343 return false;
5346 target = this;
5347 if (roll_chance_i(10))
5348 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
5349 break;
5351 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
5352 // cast 45479 Light's Wrath if Exalted by Aldor
5353 // cast 45429 Arcane Bolt if Exalted by Scryers
5354 case 45481:
5356 if(GetTypeId() != TYPEID_PLAYER)
5357 return false;
5359 // Get Aldor reputation rank
5360 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5362 target = this;
5363 triggered_spell_id = 45479;
5364 break;
5366 // Get Scryers reputation rank
5367 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5369 // triggered at positive/self casts also, current attack target used then
5370 if(IsFriendlyTo(target))
5372 target = getVictim();
5373 if(!target)
5375 uint64 selected_guid = ((Player *)this)->GetSelection();
5376 target = ObjectAccessor::GetUnit(*this,selected_guid);
5377 if(!target)
5378 return false;
5380 if(IsFriendlyTo(target))
5381 return false;
5384 triggered_spell_id = 45429;
5385 break;
5387 return false;
5389 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
5390 // cast 45480 Light's Strength if Exalted by Aldor
5391 // cast 45428 Arcane Strike if Exalted by Scryers
5392 case 45482:
5394 if(GetTypeId() != TYPEID_PLAYER)
5395 return false;
5397 // Get Aldor reputation rank
5398 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5400 target = this;
5401 triggered_spell_id = 45480;
5402 break;
5404 // Get Scryers reputation rank
5405 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5407 triggered_spell_id = 45428;
5408 break;
5410 return false;
5412 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
5413 // cast 45431 Arcane Insight if Exalted by Aldor
5414 // cast 45432 Light's Ward if Exalted by Scryers
5415 case 45483:
5417 if(GetTypeId() != TYPEID_PLAYER)
5418 return false;
5420 // Get Aldor reputation rank
5421 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5423 target = this;
5424 triggered_spell_id = 45432;
5425 break;
5427 // Get Scryers reputation rank
5428 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5430 target = this;
5431 triggered_spell_id = 45431;
5432 break;
5434 return false;
5436 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
5437 // cast 45478 Light's Salvation if Exalted by Aldor
5438 // cast 45430 Arcane Surge if Exalted by Scryers
5439 case 45484:
5441 if(GetTypeId() != TYPEID_PLAYER)
5442 return false;
5444 // Get Aldor reputation rank
5445 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
5447 target = this;
5448 triggered_spell_id = 45478;
5449 break;
5451 // Get Scryers reputation rank
5452 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
5454 triggered_spell_id = 45430;
5455 break;
5457 return false;
5460 // Sunwell Exalted Caster Neck (??? neck)
5461 // cast ??? Light's Wrath if Exalted by Aldor
5462 // cast ??? Arcane Bolt if Exalted by Scryers*/
5463 case 46569:
5464 return false; // old unused version
5465 // Living Seed
5466 case 48504:
5468 triggered_spell_id = 48503;
5469 basepoints[0] = triggerAmount;
5470 target = this;
5471 break;
5473 // Vampiric Touch (generic, used by some boss)
5474 case 52723:
5475 case 60501:
5477 triggered_spell_id = 52724;
5478 basepoints[0] = damage / 2;
5479 target = this;
5480 break;
5482 // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend)
5483 case 57989:
5485 Unit *owner = GetOwner();
5486 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
5487 return false;
5489 // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown)
5490 owner->CastSpell(owner,58227,true,castItem,triggeredByAura);
5491 return true;
5493 // Glyph of Life Tap
5494 case 63320:
5495 triggered_spell_id = 63321;
5496 break;
5497 // Item - Shadowmourne Legendary
5498 case 71903:
5500 if (!roll_chance_i(triggerAmount))
5501 return false;
5503 Aura *aur = GetAura(71905, EFFECT_INDEX_0);
5504 if (aur && uint32(aur->GetStackAmount() + 1) >= aur->GetSpellProto()->StackAmount)
5506 RemoveAurasDueToSpell(71905);
5507 CastSpell(this, 71904, true); // Chaos Bane
5508 return true;
5510 else
5511 triggered_spell_id = 71905;
5513 break;
5516 break;
5518 case SPELLFAMILY_MAGE:
5520 // Magic Absorption
5521 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
5523 if (getPowerType() != POWER_MANA)
5524 return false;
5526 // mana reward
5527 basepoints[0] = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
5528 target = this;
5529 triggered_spell_id = 29442;
5530 break;
5532 // Master of Elements
5533 if (dummySpell->SpellIconID == 1920)
5535 if(!procSpell)
5536 return false;
5538 // mana cost save
5539 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5540 basepoints[0] = cost * triggerAmount/100;
5541 if (basepoints[0] <=0)
5542 return false;
5544 target = this;
5545 triggered_spell_id = 29077;
5546 break;
5549 // Arcane Potency
5550 if (dummySpell->SpellIconID == 2120)
5552 if(!procSpell)
5553 return false;
5555 target = this;
5556 switch (dummySpell->Id)
5558 case 31571: triggered_spell_id = 57529; break;
5559 case 31572: triggered_spell_id = 57531; break;
5560 default:
5561 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
5562 return false;
5564 break;
5567 // Hot Streak
5568 if (dummySpell->SpellIconID == 2999)
5570 if (effIndex != EFFECT_INDEX_0)
5571 return true;
5572 Aura *counter = GetAura(triggeredByAura->GetId(), EFFECT_INDEX_1);
5573 if (!counter)
5574 return true;
5576 // Count spell criticals in a row in second aura
5577 Modifier *mod = counter->GetModifier();
5578 if (procEx & PROC_EX_CRITICAL_HIT)
5580 mod->m_amount *=2;
5581 if (mod->m_amount < 100) // not enough
5582 return true;
5583 // Crititcal counted -> roll chance
5584 if (roll_chance_i(triggerAmount))
5585 CastSpell(this, 48108, true, castItem, triggeredByAura);
5587 mod->m_amount = 25;
5588 return true;
5590 // Burnout
5591 if (dummySpell->SpellIconID == 2998)
5593 if(!procSpell)
5594 return false;
5596 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5597 basepoints[0] = cost * triggerAmount/100;
5598 if (basepoints[0] <=0)
5599 return false;
5600 triggered_spell_id = 44450;
5601 target = this;
5602 break;
5604 // Incanter's Regalia set (add trigger chance to Mana Shield)
5605 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5607 if (GetTypeId() != TYPEID_PLAYER)
5608 return false;
5610 target = this;
5611 triggered_spell_id = 37436;
5612 break;
5614 switch(dummySpell->Id)
5616 // Ignite
5617 case 11119:
5618 case 11120:
5619 case 12846:
5620 case 12847:
5621 case 12848:
5623 switch (dummySpell->Id)
5625 case 11119: basepoints[0] = int32(0.04f*damage); break;
5626 case 11120: basepoints[0] = int32(0.08f*damage); break;
5627 case 12846: basepoints[0] = int32(0.12f*damage); break;
5628 case 12847: basepoints[0] = int32(0.16f*damage); break;
5629 case 12848: basepoints[0] = int32(0.20f*damage); break;
5630 default:
5631 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
5632 return false;
5635 triggered_spell_id = 12654;
5636 break;
5638 // Combustion
5639 case 11129:
5641 //last charge and crit
5642 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
5643 return true; // charge counting (will removed)
5645 CastSpell(this, 28682, true, castItem, triggeredByAura);
5646 return (procEx & PROC_EX_CRITICAL_HIT); // charge update only at crit hits, no hidden cooldowns
5648 // Glyph of Ice Block
5649 case 56372:
5651 if (GetTypeId() != TYPEID_PLAYER)
5652 return false;
5654 // not 100% safe with client version switches but for 3.1.3 no spells with cooldown that can have mage player except Frost Nova.
5655 ((Player*)this)->RemoveSpellCategoryCooldown(35, true);
5656 return true;
5658 // Glyph of Polymorph
5659 case 56375:
5661 if (!pVictim || !pVictim->isAlive())
5662 return false;
5664 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE);
5665 pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE_PERCENT);
5666 return true;
5668 // Blessing of Ancient Kings
5669 case 64411:
5671 // for DOT procs
5672 if (!IsPositiveSpell(procSpell->Id))
5673 return false;
5675 triggered_spell_id = 64413;
5676 basepoints[0] = damage * 15 / 100;
5677 break;
5680 break;
5682 case SPELLFAMILY_WARRIOR:
5684 // Retaliation
5685 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000))
5687 // check attack comes not from behind
5688 if (!HasInArc(M_PI_F, pVictim))
5689 return false;
5691 triggered_spell_id = 22858;
5692 break;
5694 // Second Wind
5695 if (dummySpell->SpellIconID == 1697)
5697 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
5698 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5699 return false;
5700 // Need stun or root mechanic
5701 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_STUN_MASK))
5702 return false;
5704 switch (dummySpell->Id)
5706 case 29838: triggered_spell_id=29842; break;
5707 case 29834: triggered_spell_id=29841; break;
5708 case 42770: triggered_spell_id=42771; break;
5709 default:
5710 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
5711 return false;
5714 target = this;
5715 break;
5717 // Damage Shield
5718 if (dummySpell->SpellIconID == 3214)
5720 triggered_spell_id = 59653;
5721 basepoints[0] = GetShieldBlockValue() * triggerAmount / 100;
5722 break;
5725 // Sweeping Strikes
5726 if (dummySpell->Id == 12328)
5728 // prevent chain of triggered spell from same triggered spell
5729 if(procSpell && procSpell->Id == 26654)
5730 return false;
5732 target = SelectRandomUnfriendlyTarget(pVictim);
5733 if(!target)
5734 return false;
5736 triggered_spell_id = 26654;
5737 break;
5739 break;
5741 case SPELLFAMILY_WARLOCK:
5743 // Seed of Corruption
5744 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
5746 Modifier* mod = triggeredByAura->GetModifier();
5747 // if damage is more than need or target die from damage deal finish spell
5748 if( mod->m_amount <= (int32)damage || GetHealth() <= damage )
5750 // remember guid before aura delete
5751 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5753 // Remove aura (before cast for prevent infinite loop handlers)
5754 RemoveAurasDueToSpell(triggeredByAura->GetId());
5756 // Cast finish spell (triggeredByAura already not exist!)
5757 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
5758 return true; // no hidden cooldown
5761 // Damage counting
5762 mod->m_amount-=damage;
5763 return true;
5765 // Seed of Corruption (Mobs cast) - no die req
5766 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932)
5768 Modifier* mod = triggeredByAura->GetModifier();
5769 // if damage is more than need deal finish spell
5770 if( mod->m_amount <= (int32)damage )
5772 // remember guid before aura delete
5773 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5775 // Remove aura (before cast for prevent infinite loop handlers)
5776 RemoveAurasDueToSpell(triggeredByAura->GetId());
5778 // Cast finish spell (triggeredByAura already not exist!)
5779 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5780 return true; // no hidden cooldown
5782 // Damage counting
5783 mod->m_amount-=damage;
5784 return true;
5786 // Fel Synergy
5787 if (dummySpell->SpellIconID == 3222)
5789 target = GetPet();
5790 if (!target)
5791 return false;
5792 basepoints[0] = damage * triggerAmount / 100;
5793 triggered_spell_id = 54181;
5794 break;
5796 switch(dummySpell->Id)
5798 // Nightfall & Glyph of Corruption
5799 case 18094:
5800 case 18095:
5801 case 56218:
5803 target = this;
5804 triggered_spell_id = 17941;
5805 break;
5807 //Soul Leech
5808 case 30293:
5809 case 30295:
5810 case 30296:
5812 // health
5813 basepoints[0] = int32(damage*triggerAmount/100);
5814 target = this;
5815 triggered_spell_id = 30294;
5816 break;
5818 // Shadowflame (Voidheart Raiment set bonus)
5819 case 37377:
5821 triggered_spell_id = 37379;
5822 break;
5824 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5825 case 37381:
5827 target = GetPet();
5828 if (!target)
5829 return false;
5831 // heal amount
5832 basepoints[0] = damage * triggerAmount/100;
5833 triggered_spell_id = 37382;
5834 break;
5836 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5837 case 39437:
5839 triggered_spell_id = 37378;
5840 break;
5842 // Siphon Life
5843 case 63108:
5845 if (triggeredByAura->GetEffIndex() != EFFECT_INDEX_0)
5846 return false;
5848 // Glyph of Siphon Life
5849 if (Aura *aur = GetAura(56216, EFFECT_INDEX_0))
5850 triggerAmount += triggerAmount * aur->GetModifier()->m_amount / 100;
5852 basepoints[0] = int32(damage * triggerAmount / 100);
5853 triggered_spell_id = 63106;
5854 break;
5857 break;
5859 case SPELLFAMILY_PRIEST:
5861 // Vampiric Touch
5862 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
5864 if(!pVictim || !pVictim->isAlive())
5865 return false;
5867 // pVictim is caster of aura
5868 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5869 return false;
5871 // Energize 0.25% of max. mana
5872 pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
5873 return true; // no hidden cooldown
5876 switch(dummySpell->SpellIconID)
5878 // Improved Shadowform
5879 case 217:
5881 if(!roll_chance_i(triggerAmount))
5882 return false;
5884 RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT);
5885 RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
5886 break;
5888 // Divine Aegis
5889 case 2820:
5891 basepoints[0] = damage * triggerAmount/100;
5892 triggered_spell_id = 47753;
5893 break;
5895 // Empowered Renew
5896 case 3021:
5898 if (!procSpell)
5899 return false;
5901 Aura* healingAura = pVictim->GetAura(procSpell->Id, EFFECT_INDEX_0);
5902 if (!healingAura)
5903 return false;
5905 int32 healingfromticks = healingAura->GetModifier()->m_amount * GetSpellAuraMaxTicks(procSpell);
5907 basepoints[0] = healingfromticks * triggerAmount / 100;
5908 triggered_spell_id = 63544;
5909 break;
5911 // Improved Devouring Plague
5912 case 3790:
5914 if (!procSpell)
5915 return false;
5917 if (triggeredByAura->GetEffIndex() != EFFECT_INDEX_1)
5918 return false;
5920 Aura* leachAura = pVictim->GetAura(SPELL_AURA_PERIODIC_LEECH, SPELLFAMILY_PRIEST, UI64LIT(0x02000000), NULL, GetGUID());
5921 if (!leachAura)
5922 return false;
5924 int32 damagefromticks = leachAura->GetModifier()->m_amount * GetSpellAuraMaxTicks(procSpell);
5925 basepoints[0] = damagefromticks * triggerAmount / 100;
5926 triggered_spell_id = 63675;
5927 break;
5931 switch(dummySpell->Id)
5933 // Vampiric Embrace
5934 case 15286:
5936 // Return if self damage
5937 if (this == pVictim)
5938 return false;
5940 // Heal amount - Self/Team
5941 int32 team = triggerAmount*damage/500;
5942 int32 self = triggerAmount*damage/100 - team;
5943 CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5944 return true; // no hidden cooldown
5946 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5947 case 40438:
5949 // Shadow Word: Pain
5950 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5951 triggered_spell_id = 40441;
5952 // Renew
5953 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5954 triggered_spell_id = 40440;
5955 else
5956 return false;
5958 target = this;
5959 break;
5961 // Oracle Healing Bonus ("Garments of the Oracle" set)
5962 case 26169:
5964 // heal amount
5965 basepoints[0] = int32(damage * 10/100);
5966 target = this;
5967 triggered_spell_id = 26170;
5968 break;
5970 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5971 case 39372:
5973 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5974 return false;
5976 // heal amount
5977 basepoints[0] = damage * triggerAmount/100;
5978 target = this;
5979 triggered_spell_id = 39373;
5980 break;
5982 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5983 case 28809:
5985 triggered_spell_id = 28810;
5986 break;
5988 // Glyph of Dispel Magic
5989 case 55677:
5991 if(!target->IsFriendlyTo(this))
5992 return false;
5994 basepoints[0] = int32(target->GetMaxHealth() * triggerAmount / 100);
5995 triggered_spell_id = 56131;
5996 break;
5999 break;
6001 case SPELLFAMILY_DRUID:
6003 switch(dummySpell->Id)
6005 // Leader of the Pack
6006 case 24932:
6008 // dummy m_amount store health percent (!=0 if Improved Leader of the Pack applied)
6009 int32 heal_percent = triggeredByAura->GetModifier()->m_amount;
6010 if (!heal_percent)
6011 return false;
6013 // check explicitly only to prevent mana cast when halth cast cooldown
6014 if (cooldown && ((Player*)this)->HasSpellCooldown(34299))
6015 return false;
6017 // health
6018 triggered_spell_id = 34299;
6019 basepoints[0] = GetMaxHealth() * heal_percent / 100;
6020 target = this;
6022 // mana to caster
6023 if (triggeredByAura->GetCasterGUID() == GetGUID())
6025 if (SpellEntry const* manaCastEntry = sSpellStore.LookupEntry(60889))
6027 int32 mana_percent = manaCastEntry->CalculateSimpleValue(EFFECT_INDEX_0) * heal_percent;
6028 CastCustomSpell(this, manaCastEntry, &mana_percent, NULL, NULL, true, castItem, triggeredByAura);
6031 break;
6033 // Healing Touch (Dreamwalker Raiment set)
6034 case 28719:
6036 // mana back
6037 basepoints[0] = int32(procSpell->manaCost * 30 / 100);
6038 target = this;
6039 triggered_spell_id = 28742;
6040 break;
6042 // Healing Touch Refund (Idol of Longevity trinket)
6043 case 28847:
6045 target = this;
6046 triggered_spell_id = 28848;
6047 break;
6049 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
6050 case 37288:
6051 case 37295:
6053 target = this;
6054 triggered_spell_id = 37238;
6055 break;
6057 // Druid Tier 6 Trinket
6058 case 40442:
6060 float chance;
6062 // Starfire
6063 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
6065 triggered_spell_id = 40445;
6066 chance = 25.0f;
6068 // Rejuvenation
6069 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
6071 triggered_spell_id = 40446;
6072 chance = 25.0f;
6074 // Mangle (Bear) and Mangle (Cat)
6075 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000))
6077 triggered_spell_id = 40452;
6078 chance = 40.0f;
6080 else
6081 return false;
6083 if (!roll_chance_f(chance))
6084 return false;
6086 target = this;
6087 break;
6089 // Maim Interrupt
6090 case 44835:
6092 // Deadly Interrupt Effect
6093 triggered_spell_id = 32747;
6094 break;
6096 // Glyph of Rejuvenation
6097 case 54754:
6099 // less 50% health
6100 if (pVictim->GetMaxHealth() < 2 * pVictim->GetHealth())
6101 return false;
6102 basepoints[0] = triggerAmount * damage / 100;
6103 triggered_spell_id = 54755;
6104 break;
6106 // Item - Druid T10 Restoration 4P Bonus (Rejuvenation)
6107 case 70664:
6109 if (!procSpell || GetTypeId() != TYPEID_PLAYER)
6110 return false;
6112 float radius;
6113 if (procSpell->EffectRadiusIndex[EFFECT_INDEX_0])
6114 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(procSpell->EffectRadiusIndex[EFFECT_INDEX_0]));
6115 else
6116 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(procSpell->rangeIndex));
6118 ((Player*)this)->ApplySpellMod(procSpell->Id, SPELLMOD_RADIUS, radius,NULL);
6120 Unit *second = pVictim->SelectRandomFriendlyTarget(pVictim, radius);
6122 if (!second)
6123 return false;
6125 pVictim->CastSpell(second, procSpell, true, NULL, triggeredByAura, GetGUID());
6126 return true;
6129 // Eclipse
6130 if (dummySpell->SpellIconID == 2856)
6132 if (!procSpell)
6133 return false;
6134 // Only 0 aura can proc
6135 if (effIndex != EFFECT_INDEX_0)
6136 return true;
6137 // Wrath crit
6138 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6140 if (HasAura(48517))
6141 return false;
6142 if (!roll_chance_i(60))
6143 return false;
6144 triggered_spell_id = 48518;
6145 target = this;
6146 break;
6148 // Starfire crit
6149 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
6151 if (HasAura(48518))
6152 return false;
6153 triggered_spell_id = 48517;
6154 target = this;
6155 break;
6157 return false;
6159 // Living Seed
6160 else if (dummySpell->SpellIconID == 2860)
6162 triggered_spell_id = 48504;
6163 basepoints[0] = triggerAmount * damage / 100;
6164 break;
6166 break;
6168 case SPELLFAMILY_ROGUE:
6170 switch(dummySpell->Id)
6172 // Deadly Throw Interrupt
6173 case 32748:
6175 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
6176 if (this == pVictim)
6177 return false;
6179 triggered_spell_id = 32747;
6180 break;
6183 // Cut to the Chase
6184 if (dummySpell->SpellIconID == 2909)
6186 // "refresh your Slice and Dice duration to its 5 combo point maximum"
6187 // lookup Slice and Dice
6188 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
6189 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
6191 SpellEntry const *spellProto = (*itr)->GetSpellProto();
6192 if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
6193 (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000)))
6195 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
6196 (*itr)->RefreshAura();
6197 return true;
6200 return false;
6202 // Deadly Brew
6203 if (dummySpell->SpellIconID == 2963)
6205 triggered_spell_id = 44289;
6206 break;
6208 // Quick Recovery
6209 if (dummySpell->SpellIconID == 2116)
6211 if(!procSpell)
6212 return false;
6214 // energy cost save
6215 basepoints[0] = procSpell->manaCost * triggerAmount/100;
6216 if (basepoints[0] <= 0)
6217 return false;
6219 target = this;
6220 triggered_spell_id = 31663;
6221 break;
6223 break;
6225 case SPELLFAMILY_HUNTER:
6227 // Aspect of the Viper
6228 if (dummySpell->SpellFamilyFlags & UI64LIT(0x4000000000000))
6230 uint32 maxmana = GetMaxPower(POWER_MANA);
6231 basepoints[0] = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f);
6233 target = this;
6234 triggered_spell_id = 34075;
6235 break;
6237 // Thrill of the Hunt
6238 if (dummySpell->SpellIconID == 2236)
6240 if (!procSpell)
6241 return false;
6243 // mana cost save
6244 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6245 basepoints[0] = mana * 40/100;
6246 if (basepoints[0] <= 0)
6247 return false;
6249 target = this;
6250 triggered_spell_id = 34720;
6251 break;
6253 // Hunting Party
6254 if (dummySpell->SpellIconID == 3406)
6256 triggered_spell_id = 57669;
6257 target = this;
6258 break;
6260 // Lock and Load
6261 if ( dummySpell->SpellIconID == 3579 )
6263 // Proc only from periodic (from trap activation proc another aura of this spell)
6264 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
6265 return false;
6266 triggered_spell_id = 56453;
6267 target = this;
6268 break;
6270 // Rapid Recuperation
6271 if ( dummySpell->SpellIconID == 3560 )
6273 // This effect only from Rapid Killing (mana regen)
6274 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000)))
6275 return false;
6277 target = this;
6279 switch(dummySpell->Id)
6281 case 53228: // Rank 1
6282 triggered_spell_id = 56654;
6283 break;
6284 case 53232: // Rank 2
6285 triggered_spell_id = 58882;
6286 break;
6288 break;
6290 // Glyph of Mend Pet
6291 if(dummySpell->Id == 57870)
6293 pVictim->CastSpell(pVictim, 57894, true, NULL, NULL, GetGUID());
6294 return true;
6296 break;
6298 case SPELLFAMILY_PALADIN:
6300 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
6301 if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex == EFFECT_INDEX_0)
6303 triggered_spell_id = 25742;
6304 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
6305 int32 holy = SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_HOLY);
6306 if (holy < 0)
6307 holy = 0;
6308 basepoints[0] = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
6309 break;
6311 // Righteous Vengeance
6312 if (dummySpell->SpellIconID == 3025)
6314 // 4 damage tick
6315 basepoints[0] = triggerAmount*damage/400;
6316 triggered_spell_id = 61840;
6317 break;
6319 // Sheath of Light
6320 if (dummySpell->SpellIconID == 3030)
6322 // 4 healing tick
6323 basepoints[0] = triggerAmount*damage/400;
6324 triggered_spell_id = 54203;
6325 break;
6327 switch(dummySpell->Id)
6329 // Judgement of Light
6330 case 20185:
6332 basepoints[0] = int32( pVictim->GetMaxHealth() * triggeredByAura->GetModifier()->m_amount / 100 );
6333 pVictim->CastCustomSpell(pVictim, 20267, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura);
6334 return true;
6336 // Judgement of Wisdom
6337 case 20186:
6339 if (pVictim->getPowerType() == POWER_MANA)
6341 // 2% of maximum base mana
6342 basepoints[0] = int32(pVictim->GetCreateMana() * 2 / 100);
6343 pVictim->CastCustomSpell(pVictim, 20268, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura);
6345 return true;
6347 // Heart of the Crusader (Rank 1)
6348 case 20335:
6349 triggered_spell_id = 21183;
6350 break;
6351 // Heart of the Crusader (Rank 2)
6352 case 20336:
6353 triggered_spell_id = 54498;
6354 break;
6355 // Heart of the Crusader (Rank 3)
6356 case 20337:
6357 triggered_spell_id = 54499;
6358 break;
6359 case 20911: // Blessing of Sanctuary
6360 case 25899: // Greater Blessing of Sanctuary
6362 target = this;
6363 switch (target->getPowerType())
6365 case POWER_MANA:
6366 triggered_spell_id = 57319;
6367 break;
6368 default:
6369 return false;
6371 break;
6373 // Holy Power (Redemption Armor set)
6374 case 28789:
6376 if(!pVictim)
6377 return false;
6379 // Set class defined buff
6380 switch (pVictim->getClass())
6382 case CLASS_PALADIN:
6383 case CLASS_PRIEST:
6384 case CLASS_SHAMAN:
6385 case CLASS_DRUID:
6386 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6387 break;
6388 case CLASS_MAGE:
6389 case CLASS_WARLOCK:
6390 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6391 break;
6392 case CLASS_HUNTER:
6393 case CLASS_ROGUE:
6394 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
6395 break;
6396 case CLASS_WARRIOR:
6397 triggered_spell_id = 28790; // Increases the friendly target's armor
6398 break;
6399 default:
6400 return false;
6402 break;
6404 // Spiritual Attunement
6405 case 31785:
6406 case 33776:
6408 // if healed by another unit (pVictim)
6409 if (this == pVictim)
6410 return false;
6412 // heal amount
6413 basepoints[0] = triggerAmount*damage/100;
6414 target = this;
6415 triggered_spell_id = 31786;
6416 break;
6418 // Seal of Vengeance (damage calc on apply aura)
6419 case 31801:
6421 if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code
6422 return false;
6424 // At melee attack or Hammer of the Righteous spell damage considered as melee attack
6425 if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) )
6426 triggered_spell_id = 31803; // Holy Vengeance
6428 // Add 5-stack effect from Holy Vengeance
6429 int8 stacks = 0;
6430 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
6431 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
6433 if( ((*itr)->GetId() == 31803) && (*itr)->GetCasterGUID()==GetGUID())
6435 stacks = (*itr)->GetStackAmount();
6436 break;
6439 if(stacks >= 5)
6440 CastSpell(target,42463,true,NULL,triggeredByAura);
6441 break;
6443 // Judgements of the Wise
6444 case 31876:
6445 case 31877:
6446 case 31878:
6447 // triggered only at casted Judgement spells, not at additional Judgement effects
6448 if(!procSpell || procSpell->Category != 1210)
6449 return false;
6451 target = this;
6452 triggered_spell_id = 31930;
6454 // Replenishment
6455 CastSpell(this, 57669, true, NULL, triggeredByAura);
6456 break;
6457 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
6458 case 40470:
6460 if (!procSpell)
6461 return false;
6463 float chance;
6465 // Flash of light/Holy light
6466 if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000))
6468 triggered_spell_id = 40471;
6469 chance = 15.0f;
6471 // Judgement (any)
6472 else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT)
6474 triggered_spell_id = 40472;
6475 chance = 50.0f;
6477 else
6478 return false;
6480 if (!roll_chance_f(chance))
6481 return false;
6483 break;
6485 // Light's Beacon (heal target area aura)
6486 case 53651:
6488 // not do bonus heal for explicit beacon focus healing
6489 if (GetGUID() == triggeredByAura->GetCasterGUID())
6490 return false;
6492 // beacon
6493 Unit* beacon = triggeredByAura->GetCaster();
6494 if (!beacon)
6495 return false;
6497 // find caster main aura at beacon
6498 Aura* dummy = NULL;
6499 Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_PERIODIC_TRIGGER_SPELL);
6500 for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i)
6502 if ((*i)->GetId() == 53563 && (*i)->GetCasterGUID() == pVictim->GetGUID())
6504 dummy = (*i);
6505 break;
6509 // original heal must be form beacon caster
6510 if (!dummy)
6511 return false;
6513 triggered_spell_id = 53652; // Beacon of Light
6514 basepoints[0] = triggeredByAura->GetModifier()->m_amount*damage/100;
6516 // cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check
6517 beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID());
6518 return true;
6520 // Seal of Corruption (damage calc on apply aura)
6521 case 53736:
6523 if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code
6524 return false;
6526 // At melee attack or Hammer of the Righteous spell damage considered as melee attack
6527 if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595))
6528 triggered_spell_id = 53742; // Blood Corruption
6530 // Add 5-stack effect from Blood Corruption
6531 int8 stacks = 0;
6532 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
6533 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
6535 if( ((*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
6537 stacks = (*itr)->GetStackAmount();
6538 break;
6541 if(stacks >= 5)
6542 CastSpell(target,53739,true,NULL,triggeredByAura);
6543 break;
6545 // Glyph of Holy Light
6546 case 54937:
6548 triggered_spell_id = 54968;
6549 basepoints[0] = triggerAmount*damage/100;
6550 break;
6552 // Glyph of Divinity
6553 case 54939:
6555 // Lookup base amount mana restore
6556 for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
6558 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
6560 int32 mana = procSpell->CalculateSimpleValue(SpellEffectIndex(i));
6561 CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura);
6562 break;
6565 return true;
6567 // Sacred Shield (buff)
6568 case 58597:
6570 triggered_spell_id = 66922;
6571 SpellEntry const* triggeredEntry = sSpellStore.LookupEntry(triggered_spell_id);
6572 if (!triggeredEntry)
6573 return false;
6575 basepoints[0] = int32(damage / (GetSpellDuration(triggeredEntry) / triggeredEntry->EffectAmplitude[EFFECT_INDEX_0]));
6576 target = this;
6577 break;
6579 // Sacred Shield (talent rank)
6580 case 53601:
6582 triggered_spell_id = 58597;
6583 target = this;
6584 break;
6587 break;
6589 case SPELLFAMILY_SHAMAN:
6591 switch(dummySpell->Id)
6593 // Totemic Power (The Earthshatterer set)
6594 case 28823:
6596 if( !pVictim )
6597 return false;
6599 // Set class defined buff
6600 switch (pVictim->getClass())
6602 case CLASS_PALADIN:
6603 case CLASS_PRIEST:
6604 case CLASS_SHAMAN:
6605 case CLASS_DRUID:
6606 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
6607 break;
6608 case CLASS_MAGE:
6609 case CLASS_WARLOCK:
6610 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
6611 break;
6612 case CLASS_HUNTER:
6613 case CLASS_ROGUE:
6614 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
6615 break;
6616 case CLASS_WARRIOR:
6617 triggered_spell_id = 28827; // Increases the friendly target's armor
6618 break;
6619 default:
6620 return false;
6622 break;
6624 // Lesser Healing Wave (Totem of Flowing Water Relic)
6625 case 28849:
6627 target = this;
6628 triggered_spell_id = 28850;
6629 break;
6631 // Windfury Weapon (Passive) 1-5 Ranks
6632 case 33757:
6634 if(GetTypeId()!=TYPEID_PLAYER)
6635 return false;
6637 if(!castItem || !castItem->IsEquipped())
6638 return false;
6640 // custom cooldown processing case
6641 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6642 return false;
6644 // Now amount of extra power stored in 1 effect of Enchant spell
6645 // Get it by item enchant id
6646 uint32 spellId;
6647 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
6649 case 283: spellId = 8232; break; // 1 Rank
6650 case 284: spellId = 8235; break; // 2 Rank
6651 case 525: spellId = 10486; break; // 3 Rank
6652 case 1669:spellId = 16362; break; // 4 Rank
6653 case 2636:spellId = 25505; break; // 5 Rank
6654 case 3785:spellId = 58801; break; // 6 Rank
6655 case 3786:spellId = 58803; break; // 7 Rank
6656 case 3787:spellId = 58804; break; // 8 Rank
6657 default:
6659 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
6660 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
6661 return false;
6665 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
6666 if(!windfurySpellEntry)
6668 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
6669 return false;
6672 int32 extra_attack_power = CalculateSpellDamage(pVictim, windfurySpellEntry, EFFECT_INDEX_1);
6674 // Off-Hand case
6675 if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
6677 // Value gained from additional AP
6678 basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
6679 triggered_spell_id = 33750;
6681 // Main-Hand case
6682 else
6684 // Value gained from additional AP
6685 basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
6686 triggered_spell_id = 25504;
6689 // apply cooldown before cast to prevent processing itself
6690 if( cooldown )
6691 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6693 // Attack Twice
6694 for ( uint32 i = 0; i<2; ++i )
6695 CastCustomSpell(pVictim,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura);
6697 return true;
6699 // Shaman Tier 6 Trinket
6700 case 40463:
6702 if( !procSpell )
6703 return false;
6705 float chance;
6706 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6708 triggered_spell_id = 40465; // Lightning Bolt
6709 chance = 15.0f;
6711 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))
6713 triggered_spell_id = 40465; // Lesser Healing Wave
6714 chance = 10.0f;
6716 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
6718 triggered_spell_id = 40466; // Stormstrike
6719 chance = 50.0f;
6721 else
6722 return false;
6724 if (!roll_chance_f(chance))
6725 return false;
6727 target = this;
6728 break;
6730 // Glyph of Healing Wave
6731 case 55440:
6733 // Not proc from self heals
6734 if (this==pVictim)
6735 return false;
6736 basepoints[0] = triggerAmount * damage / 100;
6737 target = this;
6738 triggered_spell_id = 55533;
6739 break;
6741 // Spirit Hunt
6742 case 58877:
6744 // Cast on owner
6745 target = GetOwner();
6746 if (!target)
6747 return false;
6748 basepoints[0] = triggerAmount * damage / 100;
6749 triggered_spell_id = 58879;
6750 break;
6752 // Glyph of Totem of Wrath
6753 case 63280:
6755 Totem* totem = GetTotem(TOTEM_SLOT_FIRE);
6756 if (!totem)
6757 return false;
6759 // find totem aura bonus
6760 AuraList const& spellPower = totem->GetAurasByType(SPELL_AURA_NONE);
6761 for(AuraList::const_iterator i = spellPower.begin();i != spellPower.end(); ++i)
6763 // select proper aura for format aura type in spell proto
6764 if ((*i)->GetTarget()==totem && (*i)->GetSpellProto()->EffectApplyAuraName[(*i)->GetEffIndex()] == SPELL_AURA_MOD_HEALING_DONE &&
6765 (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000004000000))
6767 basepoints[0] = triggerAmount * (*i)->GetModifier()->m_amount / 100;
6768 break;
6772 if (!basepoints[0])
6773 return false;
6775 basepoints[1] = basepoints[0];
6776 triggered_spell_id = 63283; // Totem of Wrath, caster bonus
6777 target = this;
6778 break;
6780 // Shaman T8 Elemental 4P Bonus
6781 case 64928:
6783 basepoints[0] = int32( triggerAmount * damage / 100 );
6784 triggered_spell_id = 64930; // Electrified
6785 break;
6787 // Shaman T9 Elemental 4P Bonus
6788 case 67228:
6790 basepoints[0] = int32( triggerAmount * damage / 100 );
6791 triggered_spell_id = 71824;
6792 break;
6795 // Storm, Earth and Fire
6796 if (dummySpell->SpellIconID == 3063)
6798 // Earthbind Totem summon only
6799 if(procSpell->Id != 2484)
6800 return false;
6802 if (!roll_chance_i(triggerAmount))
6803 return false;
6805 triggered_spell_id = 64695;
6806 break;
6808 // Ancestral Awakening
6809 if (dummySpell->SpellIconID == 3065)
6811 triggered_spell_id = 52759;
6812 basepoints[0] = triggerAmount * damage / 100;
6813 target = this;
6814 break;
6816 // Earth Shield
6817 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
6819 target = this;
6820 basepoints[0] = triggerAmount;
6822 // Glyph of Earth Shield
6823 if (Aura* aur = GetDummyAura(63279))
6825 int32 aur_mod = aur->GetModifier()->m_amount;
6826 basepoints[0] = int32(basepoints[0] * (aur_mod + 100.0f) / 100.0f);
6829 triggered_spell_id = 379;
6830 break;
6832 // Improved Water Shield
6833 if (dummySpell->SpellIconID == 2287)
6835 // Lesser Healing Wave need aditional 60% roll
6836 if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60))
6837 return false;
6838 // Chain Heal needs additional 30% roll
6839 if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000100)) && !roll_chance_i(30))
6840 return false;
6841 // lookup water shield
6842 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6843 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6845 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6846 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000)))
6848 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
6849 CastSpell(this, spell, true, castItem, triggeredByAura);
6850 return true;
6853 return false;
6855 // Lightning Overload
6856 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
6858 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
6859 return false;
6861 // custom cooldown processing case
6862 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6863 return false;
6865 uint32 spellId = 0;
6866 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
6867 switch (procSpell->Id)
6869 // Lightning Bolt
6870 case 403: spellId = 45284; break; // Rank 1
6871 case 529: spellId = 45286; break; // Rank 2
6872 case 548: spellId = 45287; break; // Rank 3
6873 case 915: spellId = 45288; break; // Rank 4
6874 case 943: spellId = 45289; break; // Rank 5
6875 case 6041: spellId = 45290; break; // Rank 6
6876 case 10391: spellId = 45291; break; // Rank 7
6877 case 10392: spellId = 45292; break; // Rank 8
6878 case 15207: spellId = 45293; break; // Rank 9
6879 case 15208: spellId = 45294; break; // Rank 10
6880 case 25448: spellId = 45295; break; // Rank 11
6881 case 25449: spellId = 45296; break; // Rank 12
6882 case 49237: spellId = 49239; break; // Rank 13
6883 case 49238: spellId = 49240; break; // Rank 14
6884 // Chain Lightning
6885 case 421: spellId = 45297; break; // Rank 1
6886 case 930: spellId = 45298; break; // Rank 2
6887 case 2860: spellId = 45299; break; // Rank 3
6888 case 10605: spellId = 45300; break; // Rank 4
6889 case 25439: spellId = 45301; break; // Rank 5
6890 case 25442: spellId = 45302; break; // Rank 6
6891 case 49270: spellId = 49268; break; // Rank 7
6892 case 49271: spellId = 49269; break; // Rank 8
6893 default:
6894 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
6895 return false;
6897 // No thread generated mod
6898 // TODO: exist special flag in spell attributes for this, need found and use!
6899 SpellModifier *mod = new SpellModifier(SPELLMOD_THREAT,SPELLMOD_PCT,-100,triggeredByAura);
6901 ((Player*)this)->AddSpellMod(mod, true);
6903 // Remove cooldown (Chain Lightning - have Category Recovery time)
6904 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002))
6905 ((Player*)this)->RemoveSpellCooldown(spellId);
6907 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
6909 ((Player*)this)->AddSpellMod(mod, false);
6911 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6912 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6914 return true;
6916 // Static Shock
6917 if(dummySpell->SpellIconID == 3059)
6919 // lookup Lightning Shield
6920 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6921 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6923 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6924 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
6926 uint32 spell = 0;
6927 switch ((*itr)->GetId())
6929 case 324: spell = 26364; break;
6930 case 325: spell = 26365; break;
6931 case 905: spell = 26366; break;
6932 case 945: spell = 26367; break;
6933 case 8134: spell = 26369; break;
6934 case 10431: spell = 26370; break;
6935 case 10432: spell = 26363; break;
6936 case 25469: spell = 26371; break;
6937 case 25472: spell = 26372; break;
6938 case 49280: spell = 49278; break;
6939 case 49281: spell = 49279; break;
6940 default:
6941 return false;
6943 CastSpell(target, spell, true, castItem, triggeredByAura);
6944 if ((*itr)->DropAuraCharge())
6945 RemoveSingleSpellAurasFromStack((*itr)->GetId());
6946 return true;
6949 return false;
6951 // Frozen Power
6952 if (dummySpell->SpellIconID == 3780)
6954 Unit *caster = triggeredByAura->GetCaster();
6956 if (!procSpell || !caster)
6957 return false;
6959 float distance = caster->GetDistance(pVictim);
6960 int32 chance = triggerAmount;
6962 if (distance < 15.0f || !roll_chance_i(chance))
6963 return false;
6965 // make triggered cast apply after current damage spell processing for prevent remove by it
6966 if(Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
6967 spell->AddTriggeredSpell(63685);
6968 return true;
6970 break;
6972 case SPELLFAMILY_DEATHKNIGHT:
6974 // Butchery
6975 if (dummySpell->SpellIconID == 2664)
6977 basepoints[0] = triggerAmount;
6978 triggered_spell_id = 50163;
6979 target = this;
6980 break;
6982 // Dancing Rune Weapon
6983 if (dummySpell->Id == 49028)
6985 // 1 dummy aura for dismiss rune blade
6986 if (effIndex != EFFECT_INDEX_2)
6987 return false;
6988 // TODO: wite script for this "fights on its own, doing the same attacks"
6989 // NOTE: Trigger here on every attack and spell cast
6990 return false;
6992 // Mark of Blood
6993 if (dummySpell->Id == 49005)
6995 // TODO: need more info (cooldowns/PPM)
6996 triggered_spell_id = 61607;
6997 break;
6999 // Vendetta
7000 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000))
7002 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
7003 triggered_spell_id = 50181;
7004 target = this;
7005 break;
7007 // Necrosis
7008 if (dummySpell->SpellIconID == 2709)
7010 // only melee auto attack affected
7011 if (!(procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT))
7012 return false;
7014 basepoints[0] = triggerAmount * damage / 100;
7015 triggered_spell_id = 51460;
7016 break;
7018 // Threat of Thassarian
7019 if (dummySpell->SpellIconID == 2023)
7021 // Must Dual Wield
7022 if (!procSpell || !haveOffhandWeapon())
7023 return false;
7024 // Chance as basepoints for dummy aura
7025 if (!roll_chance_i(triggerAmount))
7026 return false;
7028 switch (procSpell->Id)
7030 // Obliterate
7031 case 49020: // Rank 1
7032 triggered_spell_id = 66198; break;
7033 case 51423: // Rank 2
7034 triggered_spell_id = 66972; break;
7035 case 51424: // Rank 3
7036 triggered_spell_id = 66973; break;
7037 case 51425: // Rank 4
7038 triggered_spell_id = 66974; break;
7039 // Frost Strike
7040 case 49143: // Rank 1
7041 triggered_spell_id = 66196; break;
7042 case 51416: // Rank 2
7043 triggered_spell_id = 66958; break;
7044 case 51417: // Rank 3
7045 triggered_spell_id = 66959; break;
7046 case 51418: // Rank 4
7047 triggered_spell_id = 66960; break;
7048 case 51419: // Rank 5
7049 triggered_spell_id = 66961; break;
7050 case 55268: // Rank 6
7051 triggered_spell_id = 66962; break;
7052 // Plague Strike
7053 case 45462: // Rank 1
7054 triggered_spell_id = 66216; break;
7055 case 49917: // Rank 2
7056 triggered_spell_id = 66988; break;
7057 case 49918: // Rank 3
7058 triggered_spell_id = 66989; break;
7059 case 49919: // Rank 4
7060 triggered_spell_id = 66990; break;
7061 case 49920: // Rank 5
7062 triggered_spell_id = 66991; break;
7063 case 49921: // Rank 6
7064 triggered_spell_id = 66992; break;
7065 // Death Strike
7066 case 49998: // Rank 1
7067 triggered_spell_id = 66188; break;
7068 case 49999: // Rank 2
7069 triggered_spell_id = 66950; break;
7070 case 45463: // Rank 3
7071 triggered_spell_id = 66951; break;
7072 case 49923: // Rank 4
7073 triggered_spell_id = 66952; break;
7074 case 49924: // Rank 5
7075 triggered_spell_id = 66953; break;
7076 // Rune Strike
7077 case 56815:
7078 triggered_spell_id = 66217; break;
7079 // Blood Strike
7080 case 45902: // Rank 1
7081 triggered_spell_id = 66215; break;
7082 case 49926: // Rank 2
7083 triggered_spell_id = 66975; break;
7084 case 49927: // Rank 3
7085 triggered_spell_id = 66976; break;
7086 case 49928: // Rank 4
7087 triggered_spell_id = 66977; break;
7088 case 49929: // Rank 5
7089 triggered_spell_id = 66978; break;
7090 case 49930: // Rank 6
7091 triggered_spell_id = 66979; break;
7092 default:
7093 return false;
7095 break;
7097 // Runic Power Back on Snare/Root
7098 if (dummySpell->Id == 61257)
7100 // only for spells and hit/crit (trigger start always) and not start from self casted spells
7101 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7102 return false;
7103 // Need snare or root mechanic
7104 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_SNARE_MASK))
7105 return false;
7106 triggered_spell_id = 61258;
7107 target = this;
7108 break;
7110 // Wandering Plague
7111 if (dummySpell->SpellIconID == 1614)
7113 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
7114 return false;
7115 basepoints[0] = triggerAmount * damage / 100;
7116 triggered_spell_id = 50526;
7117 break;
7119 // Blood-Caked Blade
7120 if (dummySpell->SpellIconID == 138)
7122 triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
7123 break;
7125 break;
7127 default:
7128 break;
7131 // processed charge only counting case
7132 if(!triggered_spell_id)
7133 return true;
7135 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
7137 if(!triggerEntry)
7139 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
7140 return false;
7143 // default case
7144 if(!target || target!=this && !target->isAlive())
7145 return false;
7147 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
7148 return false;
7150 if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2])
7151 CastCustomSpell(target, triggered_spell_id,
7152 basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL,
7153 basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL,
7154 basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL,
7155 true, castItem, triggeredByAura);
7156 else
7157 CastSpell(target, triggered_spell_id, true, castItem, triggeredByAura);
7159 if (cooldown && GetTypeId()==TYPEID_PLAYER)
7160 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
7162 return true;
7165 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
7167 // Get triggered aura spell info
7168 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
7170 // Basepoints of trigger aura
7171 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
7173 // Set trigger spell id, target, custom basepoints
7174 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
7175 Unit* target = NULL;
7176 int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0};
7178 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
7179 basepoints[0] = triggerAmount;
7181 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7182 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7184 // Try handle unknown trigger spells
7185 // Custom requirements (not listed in procEx) Warning! damage dealing after this
7186 // Custom triggered spells
7187 switch (auraSpellInfo->SpellFamilyName)
7189 case SPELLFAMILY_GENERIC:
7190 switch(auraSpellInfo->Id)
7192 //case 191: // Elemental Response
7193 // switch (procSpell->School)
7194 // {
7195 // case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
7196 // case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
7197 // case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
7198 // case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
7199 // case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
7200 // case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
7201 // case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
7202 // }
7203 // break;
7204 //case 5301: break; // Defensive State (DND)
7205 //case 7137: break: // Shadow Charge (Rank 1)
7206 //case 7377: break: // Take Immune Periodic Damage <Not Working>
7207 //case 13358: break; // Defensive State (DND)
7208 //case 16092: break; // Defensive State (DND)
7209 //case 18943: break; // Double Attack
7210 //case 19194: break; // Double Attack
7211 //case 19817: break; // Double Attack
7212 //case 19818: break; // Double Attack
7213 //case 22835: break; // Drunken Rage
7214 // trigger_spell_id = 14822; break;
7215 case 23780: // Aegis of Preservation (Aegis of Preservation trinket)
7216 trigger_spell_id = 23781;
7217 break;
7218 //case 24949: break; // Defensive State 2 (DND)
7219 case 27522: // Mana Drain Trigger
7220 case 40336: // Mana Drain Trigger
7221 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
7222 if (isAlive())
7223 CastSpell(this, 29471, true, castItem, triggeredByAura);
7224 if (pVictim && pVictim->isAlive())
7225 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
7226 return true;
7227 case 31255: // Deadly Swiftness (Rank 1)
7228 // whenever you deal damage to a target who is below 20% health.
7229 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
7230 return false;
7232 target = this;
7233 trigger_spell_id = 22588;
7234 break;
7235 //case 33207: break; // Gossip NPC Periodic - Fidget
7236 case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
7237 trigger_spell_id = 33898;
7238 break;
7239 //case 34082: break; // Advantaged State (DND)
7240 //case 34783: break: // Spell Reflection
7241 //case 35205: break: // Vanish
7242 //case 35321: break; // Gushing Wound
7243 //case 36096: break: // Spell Reflection
7244 //case 36207: break: // Steal Weapon
7245 //case 36576: break: // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
7246 //case 37030: break; // Chaotic Temperament
7247 //case 38363: break; // Gushing Wound
7248 //case 39215: break; // Gushing Wound
7249 //case 40250: break; // Improved Duration
7250 //case 40329: break; // Demo Shout Sensor
7251 //case 40364: break; // Entangling Roots Sensor
7252 //case 41054: break; // Copy Weapon
7253 // trigger_spell_id = 41055; break;
7254 //case 41248: break; // Consuming Strikes
7255 // trigger_spell_id = 41249; break;
7256 //case 42730: break: // Woe Strike
7257 //case 43453: break: // Rune Ward
7258 //case 43504: break; // Alterac Valley OnKill Proc Aura
7259 //case 44326: break: // Pure Energy Passive
7260 //case 44526: break; // Hate Monster (Spar) (30 sec)
7261 //case 44527: break; // Hate Monster (Spar Buddy) (30 sec)
7262 //case 44819: break; // Hate Monster (Spar Buddy) (>30% Health)
7263 //case 44820: break; // Hate Monster (Spar) (<30%)
7264 case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket)
7265 // reduce you below $s1% health
7266 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
7267 return false;
7268 break;
7269 //case 45903: break: // Offensive State
7270 //case 46146: break: // [PH] Ahune Spanky Hands
7271 //case 46939: break; // Black Bow of the Betrayer
7272 // trigger_spell_id = 29471; - gain mana
7273 // 27526; - drain mana if possible
7274 case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
7275 // Pct value stored in dummy
7276 basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1) / 100;
7277 target = pVictim;
7278 break;
7279 //case 45205: break; // Copy Offhand Weapon
7280 //case 45343: break; // Dark Flame Aura
7281 //case 47300: break; // Dark Flame Aura
7282 //case 48876: break; // Beast's Mark
7283 // trigger_spell_id = 48877; break;
7284 //case 49059: break; // Horde, Hate Monster (Spar Buddy) (>30% Health)
7285 //case 50051: break; // Ethereal Pet Aura
7286 //case 50689: break; // Blood Presence (Rank 1)
7287 //case 50844: break; // Blood Mirror
7288 //case 52856: break; // Charge
7289 //case 54072: break; // Knockback Ball Passive
7290 //case 54476: break; // Blood Presence
7291 //case 54775: break; // Abandon Vehicle on Poly
7292 case 57345: // Darkmoon Card: Greatness
7294 float stat = 0.0f;
7295 // strength
7296 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
7297 // agility
7298 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
7299 // intellect
7300 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
7301 // spirit
7302 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; }
7303 break;
7305 //case 55580: break: // Mana Link
7306 //case 57587: break: // Steal Ranged ()
7307 //case 57594: break; // Copy Ranged Weapon
7308 //case 59237: break; // Beast's Mark
7309 // trigger_spell_id = 59233; break;
7310 //case 59288: break; // Infra-Green Shield
7311 //case 59532: break; // Abandon Passengers on Poly
7312 //case 59735: break: // Woe Strike
7313 case 64415: // // Val'anyr Hammer of Ancient Kings - Equip Effect
7315 // for DOT procs
7316 if (!IsPositiveSpell(procSpell->Id))
7317 return false;
7318 break;
7320 case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket
7322 float stat = 0.0f;
7323 // strength
7324 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); }
7325 // agility
7326 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; }
7327 break;
7329 case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket
7331 float stat = 0.0f;
7332 // strength
7333 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); }
7334 // agility
7335 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; }
7336 break;
7339 break;
7340 case SPELLFAMILY_MAGE:
7341 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
7343 switch (auraSpellInfo->Id)
7345 case 31641: // Rank 1
7346 case 31642: // Rank 2
7347 trigger_spell_id = 31643;
7348 break;
7349 default:
7350 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
7351 return false;
7354 // Persistent Shield (Scarab Brooch trinket)
7355 else if(auraSpellInfo->Id == 26467)
7357 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
7358 basepoints[0] = damage * 15 / 100;
7359 target = pVictim;
7360 trigger_spell_id = 26470;
7362 break;
7363 case SPELLFAMILY_WARRIOR:
7364 // Deep Wounds (replace triggered spells to directly apply DoT), dot spell have finilyflags
7365 if (auraSpellInfo->SpellFamilyFlags == UI64LIT(0x0) && auraSpellInfo->SpellIconID == 243)
7367 float weaponDamage;
7368 // DW should benefit of attack power, damage percent mods etc.
7369 // TODO: check if using offhand damage is correct and if it should be divided by 2
7370 if (haveOffhandWeapon() && getAttackTimer(BASE_ATTACK) > getAttackTimer(OFF_ATTACK))
7371 weaponDamage = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE))/2;
7372 else
7373 weaponDamage = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE))/2;
7375 switch (auraSpellInfo->Id)
7377 case 12834: basepoints[0] = int32(weaponDamage * 16 / 100); break;
7378 case 12849: basepoints[0] = int32(weaponDamage * 32 / 100); break;
7379 case 12867: basepoints[0] = int32(weaponDamage * 48 / 100); break;
7380 // Impossible case
7381 default:
7382 sLog.outError("Unit::HandleProcTriggerSpell: DW unknown spell rank %u",auraSpellInfo->Id);
7383 return false;
7386 // 1 tick/sec * 6 sec = 6 ticks
7387 basepoints[0] /= 6;
7389 trigger_spell_id = 12721;
7390 break;
7392 if (auraSpellInfo->Id == 50421) // Scent of Blood
7393 trigger_spell_id = 50422;
7394 break;
7395 case SPELLFAMILY_WARLOCK:
7397 // Drain Soul
7398 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000))
7400 // search for "Improved Drain Soul" dummy aura
7401 Unit::AuraList const& mDummyAura = GetAurasByType(SPELL_AURA_DUMMY);
7402 for(Unit::AuraList::const_iterator i = mDummyAura.begin(); i != mDummyAura.end(); ++i)
7404 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (*i)->GetSpellProto()->SpellIconID == 113)
7406 // basepoints of trigger spell stored in dummyeffect of spellProto
7407 int32 basepoints = GetMaxPower(POWER_MANA) * (*i)->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_2) / 100;
7408 CastCustomSpell(this, 18371, &basepoints, NULL, NULL, true, castItem, triggeredByAura);
7409 break;
7412 // Not remove charge (aura removed on death in any cases)
7413 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
7414 return false;
7416 // Nether Protection
7417 else if (auraSpellInfo->SpellIconID == 1985)
7419 if (!procSpell)
7420 return false;
7421 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7423 case SPELL_SCHOOL_NORMAL:
7424 return false; // ignore
7425 case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
7426 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
7427 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
7428 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
7429 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
7430 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
7431 default:
7432 return false;
7435 // Cheat Death
7436 else if (auraSpellInfo->Id == 28845)
7438 // When your health drops below 20% ....
7439 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
7440 return false;
7442 // Decimation
7443 else if (auraSpellInfo->Id == 63156 || auraSpellInfo->Id == 63158)
7445 // Looking for dummy effect
7446 Aura *aur = GetAura(auraSpellInfo->Id, EFFECT_INDEX_1);
7447 if (!aur)
7448 return false;
7450 // If target's health is not below equal certain value (35%) not proc
7451 if (int32(pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount)
7452 return false;
7454 break;
7456 case SPELLFAMILY_PRIEST:
7458 // Greater Heal Refund (Avatar Raiment set)
7459 if (auraSpellInfo->Id==37594)
7461 // Not give if target already have full health
7462 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
7463 return false;
7464 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
7465 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
7466 return false;
7467 trigger_spell_id = 37595;
7469 // Blessed Recovery
7470 else if (auraSpellInfo->SpellIconID == 1875)
7472 switch (auraSpellInfo->Id)
7474 case 27811: trigger_spell_id = 27813; break;
7475 case 27815: trigger_spell_id = 27817; break;
7476 case 27816: trigger_spell_id = 27818; break;
7477 default:
7478 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
7479 return false;
7481 basepoints[0] = damage * triggerAmount / 100 / 3;
7482 target = this;
7484 break;
7486 case SPELLFAMILY_DRUID:
7488 // Druid Forms Trinket
7489 if (auraSpellInfo->Id==37336)
7491 switch(m_form)
7493 case FORM_NONE: trigger_spell_id = 37344;break;
7494 case FORM_CAT: trigger_spell_id = 37341;break;
7495 case FORM_BEAR:
7496 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
7497 case FORM_TREE: trigger_spell_id = 37342;break;
7498 case FORM_MOONKIN: trigger_spell_id = 37343;break;
7499 default:
7500 return false;
7503 // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred)
7504 else if (auraSpellInfo->Id==67353)
7506 switch(m_form)
7508 case FORM_CAT: trigger_spell_id = 67355; break;
7509 case FORM_BEAR:
7510 case FORM_DIREBEAR: trigger_spell_id = 67354; break;
7511 default:
7512 return false;
7515 break;
7517 case SPELLFAMILY_HUNTER:
7518 // Piercing Shots
7519 if (auraSpellInfo->SpellIconID == 3247 && auraSpellInfo->SpellVisual[0] == 0)
7521 basepoints[0] = damage * triggerAmount / 100 / 8;
7522 trigger_spell_id = 63468;
7523 target = pVictim;
7525 // Rapid Recuperation
7526 else if (auraSpellInfo->Id == 53228 || auraSpellInfo->Id == 53232)
7528 // This effect only from Rapid Fire (ability cast)
7529 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020)))
7530 return false;
7532 break;
7533 case SPELLFAMILY_PALADIN:
7536 // Blessed Life
7537 if (auraSpellInfo->SpellIconID == 2137)
7539 switch (auraSpellInfo->Id)
7541 case 31828: // Rank 1
7542 case 31829: // Rank 2
7543 case 31830: // Rank 3
7544 break;
7545 default:
7546 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
7547 return false;
7551 // Healing Discount
7552 if (auraSpellInfo->Id==37705)
7554 trigger_spell_id = 37706;
7555 target = this;
7557 // Soul Preserver
7558 if (auraSpellInfo->Id==60510)
7560 trigger_spell_id = 60515;
7561 target = this;
7563 // Illumination
7564 else if (auraSpellInfo->SpellIconID==241)
7566 if(!procSpell)
7567 return false;
7568 // procspell is triggered spell but we need mana cost of original casted spell
7569 uint32 originalSpellId = procSpell->Id;
7570 // Holy Shock heal
7571 if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000))
7573 switch(procSpell->Id)
7575 case 25914: originalSpellId = 20473; break;
7576 case 25913: originalSpellId = 20929; break;
7577 case 25903: originalSpellId = 20930; break;
7578 case 27175: originalSpellId = 27174; break;
7579 case 33074: originalSpellId = 33072; break;
7580 case 48820: originalSpellId = 48824; break;
7581 case 48821: originalSpellId = 48825; break;
7582 default:
7583 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
7584 return false;
7587 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
7588 if(!originalSpell)
7590 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
7591 return false;
7593 // percent stored in effect 1 (class scripts) base points
7594 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
7595 basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1)/100;
7596 trigger_spell_id = 20272;
7597 target = this;
7599 // Lightning Capacitor
7600 else if (auraSpellInfo->Id==37657)
7602 if(!pVictim || !pVictim->isAlive())
7603 return false;
7604 // stacking
7605 CastSpell(this, 37658, true, NULL, triggeredByAura);
7607 Aura * dummy = GetDummyAura(37658);
7608 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
7609 if(!dummy || dummy->GetStackAmount() < triggerAmount)
7610 return false;
7612 RemoveAurasDueToSpell(37658);
7613 trigger_spell_id = 37661;
7614 target = pVictim;
7616 // Bonus Healing (Crystal Spire of Karabor mace)
7617 else if (auraSpellInfo->Id == 40971)
7619 // If your target is below $s1% health
7620 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
7621 return false;
7623 // Thunder Capacitor
7624 else if (auraSpellInfo->Id == 54841)
7626 if(!pVictim || !pVictim->isAlive())
7627 return false;
7628 // stacking
7629 CastSpell(this, 54842, true, NULL, triggeredByAura);
7631 // counting
7632 Aura * dummy = GetDummyAura(54842);
7633 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
7634 if(!dummy || dummy->GetStackAmount() < triggerAmount)
7635 return false;
7637 RemoveAurasDueToSpell(54842);
7638 trigger_spell_id = 54843;
7639 target = pVictim;
7641 break;
7643 case SPELLFAMILY_SHAMAN:
7645 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
7646 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400))
7648 switch(auraSpellInfo->Id)
7650 case 324: // Rank 1
7651 trigger_spell_id = 26364; break;
7652 case 325: // Rank 2
7653 trigger_spell_id = 26365; break;
7654 case 905: // Rank 3
7655 trigger_spell_id = 26366; break;
7656 case 945: // Rank 4
7657 trigger_spell_id = 26367; break;
7658 case 8134: // Rank 5
7659 trigger_spell_id = 26369; break;
7660 case 10431: // Rank 6
7661 trigger_spell_id = 26370; break;
7662 case 10432: // Rank 7
7663 trigger_spell_id = 26363; break;
7664 case 25469: // Rank 8
7665 trigger_spell_id = 26371; break;
7666 case 25472: // Rank 9
7667 trigger_spell_id = 26372; break;
7668 case 49280: // Rank 10
7669 trigger_spell_id = 49278; break;
7670 case 49281: // Rank 11
7671 trigger_spell_id = 49279; break;
7672 default:
7673 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
7674 return false;
7677 // Lightning Shield (The Ten Storms set)
7678 else if (auraSpellInfo->Id == 23551)
7680 trigger_spell_id = 23552;
7681 target = pVictim;
7683 // Damage from Lightning Shield (The Ten Storms set)
7684 else if (auraSpellInfo->Id == 23552)
7685 trigger_spell_id = 27635;
7686 // Mana Surge (The Earthfury set)
7687 else if (auraSpellInfo->Id == 23572)
7689 if(!procSpell)
7690 return false;
7691 basepoints[0] = procSpell->manaCost * 35 / 100;
7692 trigger_spell_id = 23571;
7693 target = this;
7695 // Nature's Guardian
7696 else if (auraSpellInfo->SpellIconID == 2013)
7698 // Check health condition - should drop to less 30% (damage deal after this!)
7699 if (!(10*(int32(GetHealth() - damage)) < int32(3 * GetMaxHealth())))
7700 return false;
7702 if(pVictim && pVictim->isAlive())
7703 pVictim->getThreatManager().modifyThreatPercent(this,-10);
7705 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
7706 trigger_spell_id = 31616;
7707 target = this;
7709 break;
7711 case SPELLFAMILY_DEATHKNIGHT:
7713 // Acclimation
7714 if (auraSpellInfo->SpellIconID == 1930)
7716 if (!procSpell)
7717 return false;
7718 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
7720 case SPELL_SCHOOL_NORMAL:
7721 return false; // ignore
7722 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
7723 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
7724 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
7725 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
7726 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
7727 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break;
7728 default:
7729 return false;
7732 // Blade Barrier
7733 else if (auraSpellInfo->SpellIconID == 85)
7735 if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT ||
7736 !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD))
7737 return false;
7739 // Improved Blood Presence
7740 else if (auraSpellInfo->Id == 63611)
7742 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim) || !damage)
7743 return false;
7744 basepoints[0] = triggerAmount * damage / 100;
7745 trigger_spell_id = 50475;
7747 break;
7749 default:
7750 break;
7753 // All ok. Check current trigger spell
7754 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
7755 if (!triggerEntry)
7757 // Not cast unknown spell
7758 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
7759 return false;
7762 // not allow proc extra attack spell at extra attack
7763 if (m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS))
7764 return false;
7766 // Custom basepoints/target for exist spell
7767 // dummy basepoints or other customs
7768 switch(trigger_spell_id)
7770 // Cast positive spell on enemy target
7771 case 7099: // Curse of Mending
7772 case 39647: // Curse of Mending
7773 case 29494: // Temptation
7774 case 20233: // Improved Lay on Hands (cast on target)
7776 target = pVictim;
7777 break;
7779 // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
7780 case 15250: // Rogue Setup
7782 if(!pVictim || pVictim != getVictim()) // applied only for main target
7783 return false;
7784 break; // continue normal case
7786 // Finish movies that add combo
7787 case 14189: // Seal Fate (Netherblade set)
7788 case 14157: // Ruthlessness
7790 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
7791 break;
7793 // Bloodthirst (($m/100)% of max health)
7794 case 23880:
7796 basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100);
7797 break;
7799 // Shamanistic Rage triggered spell
7800 case 30824:
7802 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7803 break;
7805 // Enlightenment (trigger only from mana cost spells)
7806 case 35095:
7808 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
7809 return false;
7810 break;
7812 // Demonic Pact
7813 case 48090:
7815 // As the spell is proced from pet's attack - find owner
7816 Unit* owner = GetOwner();
7817 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
7818 return false;
7820 // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later.
7821 int32 curBonus = 0;
7822 if (Aura* aur = owner->GetAura(48090, EFFECT_INDEX_0))
7823 curBonus = aur->GetModifier()->m_amount;
7824 int32 spellDamage = owner->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_MAGIC) - curBonus;
7825 if(spellDamage <= 0)
7826 return false;
7828 // percent stored in owner talent dummy
7829 AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
7830 for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
7832 if ((*i)->GetSpellProto()->SpellIconID == 3220)
7834 basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100);
7835 break;
7838 break;
7840 // Sword and Board
7841 case 50227:
7843 // Remove cooldown on Shield Slam
7844 if (GetTypeId() == TYPEID_PLAYER)
7845 ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
7846 break;
7848 // Maelstrom Weapon
7849 case 53817:
7851 // have rank dependent proc chance, ignore too often cases
7852 // PPM = 2.5 * (rank of talent),
7853 uint32 rank = sSpellMgr.GetSpellRank(auraSpellInfo->Id);
7854 // 5 rank -> 100% 4 rank -> 80% and etc from full rate
7855 if(!roll_chance_i(20*rank))
7856 return false;
7857 break;
7859 // Brain Freeze
7860 case 57761:
7862 if(!procSpell)
7863 return false;
7864 // For trigger from Blizzard need exist Improved Blizzard
7865 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)))
7867 bool found = false;
7868 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7869 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7871 int32 script = (*i)->GetModifier()->m_miscvalue;
7872 if(script==836 || script==988 || script==989)
7874 found=true;
7875 break;
7878 if(!found)
7879 return false;
7881 break;
7883 // Astral Shift
7884 case 52179:
7886 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7887 return false;
7889 // Need stun, fear or silence mechanic
7890 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_SILENCE_AND_STUN_AND_FEAR_MASK))
7891 return false;
7892 break;
7894 // Burning Determination
7895 case 54748:
7897 if(!procSpell)
7898 return false;
7899 // Need Interrupt or Silenced mechanic
7900 if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_INTERRUPT_AND_SILENCE_MASK))
7901 return false;
7902 break;
7904 // Lock and Load
7905 case 56453:
7907 // Proc only from trap activation (from periodic proc another aura of this spell)
7908 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
7909 return false;
7910 break;
7912 // Freezing Fog (Rime triggered)
7913 case 59052:
7915 // Howling Blast cooldown reset
7916 if (GetTypeId() == TYPEID_PLAYER)
7917 ((Player*)this)->RemoveSpellCategoryCooldown(1248, true);
7918 break;
7920 // Druid - Savage Defense
7921 case 62606:
7923 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7924 break;
7928 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
7929 return false;
7931 // try detect target manually if not set
7932 if (target == NULL)
7933 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
7935 // default case
7936 if (!target || target!=this && !target->isAlive())
7937 return false;
7939 if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2])
7940 CastCustomSpell(target,trigger_spell_id,
7941 basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL,
7942 basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL,
7943 basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL,
7944 true, castItem, triggeredByAura);
7945 else
7946 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
7948 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7949 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
7951 return true;
7954 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 /*damage*/, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
7956 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
7958 if(!pVictim || !pVictim->isAlive())
7959 return false;
7961 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7962 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7964 // Basepoints of trigger aura
7965 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
7967 uint32 triggered_spell_id = 0;
7969 switch(scriptId)
7971 case 836: // Improved Blizzard (Rank 1)
7973 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7974 return false;
7975 triggered_spell_id = 12484;
7976 break;
7978 case 988: // Improved Blizzard (Rank 2)
7980 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7981 return false;
7982 triggered_spell_id = 12485;
7983 break;
7985 case 989: // Improved Blizzard (Rank 3)
7987 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7988 return false;
7989 triggered_spell_id = 12486;
7990 break;
7992 case 4086: // Improved Mend Pet (Rank 1)
7993 case 4087: // Improved Mend Pet (Rank 2)
7995 if(!roll_chance_i(triggerAmount))
7996 return false;
7998 triggered_spell_id = 24406;
7999 break;
8001 case 4533: // Dreamwalker Raiment 2 pieces bonus
8003 // Chance 50%
8004 if (!roll_chance_i(50))
8005 return false;
8007 switch (pVictim->getPowerType())
8009 case POWER_MANA: triggered_spell_id = 28722; break;
8010 case POWER_RAGE: triggered_spell_id = 28723; break;
8011 case POWER_ENERGY: triggered_spell_id = 28724; break;
8012 default:
8013 return false;
8015 break;
8017 case 4537: // Dreamwalker Raiment 6 pieces bonus
8018 triggered_spell_id = 28750; // Blessing of the Claw
8019 break;
8020 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
8021 triggered_spell_id = 37445; // Mana Surge
8022 break;
8023 case 6953: // Warbringer
8024 RemoveAurasAtMechanicImmunity(IMMUNE_TO_ROOT_AND_SNARE_MASK,0,true);
8025 return true;
8026 case 7010: // Revitalize (rank 1)
8027 case 7011: // Revitalize (rank 2)
8028 case 7012: // Revitalize (rank 3)
8030 if(!roll_chance_i(triggerAmount))
8031 return false;
8033 switch( pVictim->getPowerType() )
8035 case POWER_MANA: triggered_spell_id = 48542; break;
8036 case POWER_RAGE: triggered_spell_id = 48541; break;
8037 case POWER_ENERGY: triggered_spell_id = 48540; break;
8038 case POWER_RUNIC_POWER: triggered_spell_id = 48543; break;
8039 default: return false;
8041 break;
8045 // not processed
8046 if(!triggered_spell_id)
8047 return false;
8049 // standard non-dummy case
8050 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
8052 if(!triggerEntry)
8054 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
8055 return false;
8058 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
8059 return false;
8061 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
8063 if( cooldown && GetTypeId()==TYPEID_PLAYER )
8064 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
8066 return true;
8069 void Unit::setPowerType(Powers new_powertype)
8071 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
8073 if(GetTypeId() == TYPEID_PLAYER)
8075 if(((Player*)this)->GetGroup())
8076 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
8078 else if(((Creature*)this)->isPet())
8080 Pet *pet = ((Pet*)this);
8081 if(pet->isControlled())
8083 Unit *owner = GetOwner();
8084 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
8085 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
8089 switch(new_powertype)
8091 default:
8092 case POWER_MANA:
8093 break;
8094 case POWER_RAGE:
8095 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
8096 SetPower( POWER_RAGE,0);
8097 break;
8098 case POWER_FOCUS:
8099 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
8100 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
8101 break;
8102 case POWER_ENERGY:
8103 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
8104 break;
8105 case POWER_HAPPINESS:
8106 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
8107 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
8108 break;
8112 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
8114 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
8115 if(!entry)
8117 static uint64 guid = 0; // prevent repeating spam same faction problem
8119 if(GetGUID() != guid)
8121 if(GetTypeId() == TYPEID_PLAYER)
8122 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
8123 else
8124 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
8125 guid = GetGUID();
8128 return entry;
8131 bool Unit::IsHostileTo(Unit const* unit) const
8133 // always non-hostile to self
8134 if(unit==this)
8135 return false;
8137 // always non-hostile to GM in GM mode
8138 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
8139 return false;
8141 // always hostile to enemy
8142 if(getVictim()==unit || unit->getVictim()==this)
8143 return true;
8145 // test pet/charm masters instead pers/charmeds
8146 Unit const* testerOwner = GetCharmerOrOwner();
8147 Unit const* targetOwner = unit->GetCharmerOrOwner();
8149 // always hostile to owner's enemy
8150 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
8151 return true;
8153 // always hostile to enemy owner
8154 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
8155 return true;
8157 // always hostile to owner of owner's enemy
8158 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
8159 return true;
8161 Unit const* tester = testerOwner ? testerOwner : this;
8162 Unit const* target = targetOwner ? targetOwner : unit;
8164 // always non-hostile to target with common owner, or to owner/pet
8165 if(tester==target)
8166 return false;
8168 // special cases (Duel, etc)
8169 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
8171 Player const* pTester = (Player const*)tester;
8172 Player const* pTarget = (Player const*)target;
8174 // Duel
8175 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
8176 return true;
8178 // Group
8179 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
8180 return false;
8182 // Sanctuary
8183 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
8184 return false;
8186 // PvP FFA state
8187 if(pTester->IsFFAPvP() && pTarget->IsFFAPvP())
8188 return true;
8190 //= PvP states
8191 // Green/Blue (can't attack)
8192 if(pTester->GetTeam()==pTarget->GetTeam())
8193 return false;
8195 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
8196 return pTester->IsPvP() && pTarget->IsPvP();
8199 // faction base cases
8200 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
8201 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
8202 if(!tester_faction || !target_faction)
8203 return false;
8205 if(target->isAttackingPlayer() && tester->IsContestedGuard())
8206 return true;
8208 // PvC forced reaction and reputation case
8209 if(tester->GetTypeId()==TYPEID_PLAYER)
8211 // forced reaction
8212 if(target_faction->faction)
8214 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
8215 return *force <= REP_HOSTILE;
8217 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
8218 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
8219 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
8220 return (factionState->Flags & FACTION_FLAG_AT_WAR);
8223 // CvP forced reaction and reputation case
8224 else if(target->GetTypeId()==TYPEID_PLAYER)
8226 // forced reaction
8227 if(tester_faction->faction)
8229 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
8230 return *force <= REP_HOSTILE;
8232 // apply reputation state
8233 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
8234 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
8235 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
8239 // common faction based case (CvC,PvC,CvP)
8240 return tester_faction->IsHostileTo(*target_faction);
8243 bool Unit::IsFriendlyTo(Unit const* unit) const
8245 // always friendly to self
8246 if(unit==this)
8247 return true;
8249 // always friendly to GM in GM mode
8250 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
8251 return true;
8253 // always non-friendly to enemy
8254 if(getVictim()==unit || unit->getVictim()==this)
8255 return false;
8257 // test pet/charm masters instead pers/charmeds
8258 Unit const* testerOwner = GetCharmerOrOwner();
8259 Unit const* targetOwner = unit->GetCharmerOrOwner();
8261 // always non-friendly to owner's enemy
8262 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
8263 return false;
8265 // always non-friendly to enemy owner
8266 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
8267 return false;
8269 // always non-friendly to owner of owner's enemy
8270 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
8271 return false;
8273 Unit const* tester = testerOwner ? testerOwner : this;
8274 Unit const* target = targetOwner ? targetOwner : unit;
8276 // always friendly to target with common owner, or to owner/pet
8277 if(tester==target)
8278 return true;
8280 // special cases (Duel)
8281 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
8283 Player const* pTester = (Player const*)tester;
8284 Player const* pTarget = (Player const*)target;
8286 // Duel
8287 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
8288 return false;
8290 // Group
8291 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
8292 return true;
8294 // Sanctuary
8295 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
8296 return true;
8298 // PvP FFA state
8299 if(pTester->IsFFAPvP() && pTarget->IsFFAPvP())
8300 return false;
8302 //= PvP states
8303 // Green/Blue (non-attackable)
8304 if(pTester->GetTeam()==pTarget->GetTeam())
8305 return true;
8307 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
8308 return !pTarget->IsPvP();
8311 // faction base cases
8312 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
8313 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
8314 if(!tester_faction || !target_faction)
8315 return false;
8317 if(target->isAttackingPlayer() && tester->IsContestedGuard())
8318 return false;
8320 // PvC forced reaction and reputation case
8321 if(tester->GetTypeId()==TYPEID_PLAYER)
8323 // forced reaction
8324 if(target_faction->faction)
8326 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
8327 return *force >= REP_FRIENDLY;
8329 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
8330 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
8331 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
8332 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
8335 // CvP forced reaction and reputation case
8336 else if(target->GetTypeId()==TYPEID_PLAYER)
8338 // forced reaction
8339 if(tester_faction->faction)
8341 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
8342 return *force >= REP_FRIENDLY;
8344 // apply reputation state
8345 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
8346 if(raw_tester_faction->reputationListID >=0 )
8347 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
8351 // common faction based case (CvC,PvC,CvP)
8352 return tester_faction->IsFriendlyTo(*target_faction);
8355 bool Unit::IsHostileToPlayers() const
8357 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
8358 if(!my_faction || !my_faction->faction)
8359 return false;
8361 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
8362 if(raw_faction && raw_faction->reputationListID >=0 )
8363 return false;
8365 return my_faction->IsHostileToPlayers();
8368 bool Unit::IsNeutralToAll() const
8370 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
8371 if(!my_faction || !my_faction->faction)
8372 return true;
8374 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
8375 if(raw_faction && raw_faction->reputationListID >=0 )
8376 return false;
8378 return my_faction->IsNeutralToAll();
8381 bool Unit::Attack(Unit *victim, bool meleeAttack)
8383 if(!victim || victim == this)
8384 return false;
8386 // dead units can neither attack nor be attacked
8387 if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
8388 return false;
8390 // player cannot attack in mount state
8391 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
8392 return false;
8394 // nobody can attack GM in GM-mode
8395 if(victim->GetTypeId()==TYPEID_PLAYER)
8397 if(((Player*)victim)->isGameMaster())
8398 return false;
8400 else
8402 if(((Creature*)victim)->IsInEvadeMode())
8403 return false;
8406 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
8407 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
8408 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
8410 // in fighting already
8411 if (m_attacking)
8413 if (m_attacking == victim)
8415 // switch to melee attack from ranged/magic
8416 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
8418 addUnitState(UNIT_STAT_MELEE_ATTACKING);
8419 SendMeleeAttackStart(victim);
8420 return true;
8422 return false;
8425 // remove old target data
8426 AttackStop(true);
8428 // new battle
8429 else
8431 // set position before any AI calls/assistance
8432 if(GetTypeId()==TYPEID_UNIT)
8433 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
8436 // Set our target
8437 SetTargetGUID(victim->GetGUID());
8439 if(meleeAttack)
8440 addUnitState(UNIT_STAT_MELEE_ATTACKING);
8442 m_attacking = victim;
8443 m_attacking->_addAttacker(this);
8445 if (GetTypeId() == TYPEID_UNIT)
8447 ((Creature*)this)->SendAIReaction(AI_REACTION_HOSTILE);
8448 ((Creature*)this)->CallAssistance();
8451 // delay offhand weapon attack to next attack time
8452 if(haveOffhandWeapon())
8453 resetAttackTimer(OFF_ATTACK);
8455 if(meleeAttack)
8456 SendMeleeAttackStart(victim);
8458 return true;
8461 bool Unit::AttackStop(bool targetSwitch /*=false*/)
8463 if (!m_attacking)
8464 return false;
8466 Unit* victim = m_attacking;
8468 m_attacking->_removeAttacker(this);
8469 m_attacking = NULL;
8471 // Clear our target
8472 SetTargetGUID(0);
8474 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
8476 InterruptSpell(CURRENT_MELEE_SPELL);
8478 // reset only at real combat stop
8479 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
8481 ((Creature*)this)->SetNoCallAssistance(false);
8483 if (((Creature*)this)->HasSearchedAssistance())
8485 ((Creature*)this)->SetNoSearchAssistance(false);
8486 UpdateSpeed(MOVE_RUN, false);
8490 SendMeleeAttackStop(victim);
8492 return true;
8495 void Unit::CombatStop(bool includingCast)
8497 if (includingCast && IsNonMeleeSpellCasted(false))
8498 InterruptNonMeleeSpells(false);
8500 AttackStop();
8501 RemoveAllAttackers();
8502 if( GetTypeId()==TYPEID_PLAYER )
8503 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
8504 ClearInCombat();
8507 struct CombatStopWithPetsHelper
8509 explicit CombatStopWithPetsHelper(bool _includingCast) : includingCast(_includingCast) {}
8510 void operator()(Unit* unit) const { unit->CombatStop(includingCast); }
8511 bool includingCast;
8514 void Unit::CombatStopWithPets(bool includingCast)
8516 CombatStop(includingCast);
8517 CallForAllControlledUnits(CombatStopWithPetsHelper(includingCast),false,true,true);
8520 struct IsAttackingPlayerHelper
8522 explicit IsAttackingPlayerHelper() {}
8523 bool operator()(Unit* unit) const { return unit->isAttackingPlayer(); }
8526 bool Unit::isAttackingPlayer() const
8528 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
8529 return true;
8531 return CheckAllControlledUnits(IsAttackingPlayerHelper(),true,true,true);
8534 void Unit::RemoveAllAttackers()
8536 while (!m_attackers.empty())
8538 AttackerSet::iterator iter = m_attackers.begin();
8539 if(!(*iter)->AttackStop())
8541 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
8542 m_attackers.erase(iter);
8547 bool Unit::HasAuraStateForCaster(AuraState flag, uint64 caster) const
8549 if(!HasAuraState(flag))
8550 return false;
8552 // single per-caster aura state
8553 if(flag == AURA_STATE_CONFLAGRATE)
8555 Unit::AuraList const& dotList = GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
8556 for(Unit::AuraList::const_iterator i = dotList.begin(); i != dotList.end(); ++i)
8558 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK &&
8559 (*i)->GetCasterGUID() == caster &&
8560 // Immolate
8561 (((*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000004)) ||
8562 // Shadowflame
8563 ((*i)->GetSpellProto()->SpellFamilyFlags2 & 0x00000002)))
8565 return true;
8569 return false;
8572 return true;
8575 void Unit::ModifyAuraState(AuraState flag, bool apply)
8577 if (apply)
8579 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
8581 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8582 if(GetTypeId() == TYPEID_PLAYER)
8584 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
8585 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
8587 if(itr->second.state == PLAYERSPELL_REMOVED) continue;
8588 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
8589 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
8590 if (spellInfo->CasterAuraState == flag)
8591 CastSpell(this, itr->first, true, NULL);
8596 else
8598 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
8600 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
8602 if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
8604 Unit::AuraMap& tAuras = GetAuras();
8605 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
8607 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
8608 if (spellProto->CasterAuraState == flag)
8609 RemoveAura(itr);
8610 else
8611 ++itr;
8618 Unit *Unit::GetOwner() const
8620 if(uint64 ownerid = GetOwnerGUID())
8621 return ObjectAccessor::GetUnit(*this, ownerid);
8622 return NULL;
8625 Unit *Unit::GetCharmer() const
8627 if(uint64 charmerid = GetCharmerGUID())
8628 return ObjectAccessor::GetUnit(*this, charmerid);
8629 return NULL;
8632 bool Unit::IsCharmerOrOwnerPlayerOrPlayerItself() const
8634 if (GetTypeId()==TYPEID_PLAYER)
8635 return true;
8637 return IS_PLAYER_GUID(GetCharmerOrOwnerGUID());
8640 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
8642 uint64 guid = GetCharmerOrOwnerGUID();
8643 if(IS_PLAYER_GUID(guid))
8644 return ObjectAccessor::FindPlayer(guid);
8646 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
8649 Pet* Unit::GetPet() const
8651 if(uint64 pet_guid = GetPetGUID())
8653 if(Pet* pet = GetMap()->GetPet(pet_guid))
8654 return pet;
8656 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
8657 const_cast<Unit*>(this)->SetPet(0);
8660 return NULL;
8663 Unit* Unit::GetCharm() const
8665 if (uint64 charm_guid = GetCharmGUID())
8667 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
8668 return pet;
8670 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
8671 const_cast<Unit*>(this)->SetCharm(NULL);
8674 return NULL;
8677 void Unit::Uncharm()
8679 if (Unit* charm = GetCharm())
8681 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
8682 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
8686 float Unit::GetCombatDistance( const Unit* target ) const
8688 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
8689 float dx = GetPositionX() - target->GetPositionX();
8690 float dy = GetPositionY() - target->GetPositionY();
8691 float dz = GetPositionZ() - target->GetPositionZ();
8692 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
8693 return ( dist > 0 ? dist : 0);
8696 void Unit::SetPet(Pet* pet)
8698 SetPetGUID(pet ? pet->GetGUID() : 0);
8700 if(pet && GetTypeId() == TYPEID_PLAYER)
8701 ((Player*)this)->SendPetGUIDs();
8704 void Unit::SetCharm(Unit* pet)
8706 SetCharmGUID(pet ? pet->GetGUID() : 0);
8709 void Unit::AddGuardian( Pet* pet )
8711 m_guardianPets.insert(pet->GetGUID());
8714 void Unit::RemoveGuardian( Pet* pet )
8716 m_guardianPets.erase(pet->GetGUID());
8719 void Unit::RemoveGuardians()
8721 while(!m_guardianPets.empty())
8723 uint64 guid = *m_guardianPets.begin();
8724 if(Pet* pet = GetMap()->GetPet(guid))
8725 pet->Remove(PET_SAVE_AS_DELETED);
8727 m_guardianPets.erase(guid);
8731 Pet* Unit::FindGuardianWithEntry(uint32 entry)
8733 // pet guid middle part is entry (and creature also)
8734 // and in guardian list must be guardians with same entry _always_
8735 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
8736 if(Pet* pet = GetMap()->GetPet(*itr))
8737 if (pet->GetEntry() == entry)
8738 return pet;
8740 return NULL;
8743 Unit* Unit::_GetTotem(TotemSlot slot) const
8745 return GetTotem(slot);
8748 Totem* Unit::GetTotem(TotemSlot slot ) const
8750 if(slot >= MAX_TOTEM_SLOT || !IsInWorld())
8751 return NULL;
8753 Creature *totem = GetMap()->GetCreature(m_TotemSlot[slot]);
8754 return totem && totem->isTotem() ? (Totem*)totem : NULL;
8757 bool Unit::IsAllTotemSlotsUsed() const
8759 for (int i = 0; i < MAX_TOTEM_SLOT; ++i)
8760 if (!m_TotemSlot[i])
8761 return false;
8762 return true;
8765 void Unit::_AddTotem(TotemSlot slot, Totem* totem)
8767 m_TotemSlot[slot] = totem->GetGUID();
8770 void Unit::_RemoveTotem(Totem* totem)
8772 for(int i = 0; i < MAX_TOTEM_SLOT; ++i)
8774 if (m_TotemSlot[i] == totem->GetGUID())
8776 m_TotemSlot[i] = 0;
8777 break;
8784 void Unit::UnsummonAllTotems()
8786 for (int i = 0; i < MAX_TOTEM_SLOT; ++i)
8787 if (Totem* totem = GetTotem(TotemSlot(i)))
8788 totem->UnSummon();
8791 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
8793 int32 gain = pVictim->ModifyHealth(int32(addhealth));
8795 Unit* unit = this;
8797 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8798 unit = GetOwner();
8800 if (unit->GetTypeId()==TYPEID_PLAYER)
8802 // overheal = addhealth - gain
8803 unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
8805 if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
8806 bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
8808 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
8809 if (gain)
8810 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
8812 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
8815 if (pVictim->GetTypeId()==TYPEID_PLAYER)
8817 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
8818 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
8821 return gain;
8824 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
8826 if(!victim)
8827 return NULL;
8829 // Magic case
8830 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
8832 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
8833 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
8834 if(Unit* magnet = (*itr)->GetCaster())
8835 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
8836 return magnet;
8838 // Melee && ranged case
8839 else
8841 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
8842 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
8843 if(Unit* magnet = (*i)->GetCaster())
8844 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
8845 if(roll_chance_i((*i)->GetModifier()->m_amount))
8846 return magnet;
8849 return victim;
8852 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
8854 // we guess size
8855 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
8856 data << pVictim->GetPackGUID();
8857 data << GetPackGUID();
8858 data << uint32(SpellID);
8859 data << uint32(Damage);
8860 data << uint32(OverHeal);
8861 data << uint8(critical ? 1 : 0);
8862 data << uint8(0); // unused in client?
8863 SendMessageToSet(&data, true);
8866 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8868 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
8869 data << pVictim->GetPackGUID();
8870 data << GetPackGUID();
8871 data << uint32(SpellID);
8872 data << uint32(powertype);
8873 data << uint32(Damage);
8874 SendMessageToSet(&data, true);
8877 void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8879 SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
8880 // needs to be called after sending spell log
8881 pVictim->ModifyPower(powertype, Damage);
8884 int32 Unit::SpellBonusWithCoeffs(SpellEntry const *spellProto, int32 total, int32 benefit, int32 ap_benefit, DamageEffectType damagetype, bool donePart, float defCoeffMod)
8886 // Distribute Damage over multiple effects, reduce by AoE
8887 float coeff;
8889 // Not apply this to creature casted spells
8890 if (GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
8891 coeff = 1.0f;
8892 // Check for table values
8893 else if (SpellBonusEntry const* bonus = sSpellMgr.GetSpellBonusData(spellProto->Id))
8895 coeff = damagetype == DOT ? bonus->dot_damage : bonus->direct_damage;
8897 // apply ap bonus at done part calculation only (it flat total mod so common with taken)
8898 if (donePart && bonus->ap_bonus)
8899 total += int32(bonus->ap_bonus * (GetTotalAttackPowerValue(BASE_ATTACK) + ap_benefit));
8901 // Default calculation
8902 else if (benefit)
8903 coeff = CalculateDefaultCoefficient(spellProto, damagetype) * defCoeffMod;
8905 if (benefit)
8907 float LvlPenalty = CalculateLevelPenalty(spellProto);
8909 // Spellmod SpellDamage
8910 if(Player* modOwner = GetSpellModOwner())
8912 coeff *= 100.0f;
8913 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE, coeff);
8914 coeff /= 100.0f;
8917 total += int32(benefit * coeff * LvlPenalty);
8920 return total;
8924 * Calculates caster part of spell damage bonuses,
8925 * also includes different bonuses dependent from target auras
8927 uint32 Unit::SpellDamageBonusDone(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
8929 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
8930 return pdamage;
8932 // For totems get damage bonus from owner (statue isn't totem in fact)
8933 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8935 if(Unit* owner = GetOwner())
8936 return owner->SpellDamageBonusDone(pVictim, spellProto, pdamage, damagetype);
8939 float DoneTotalMod = 1.0f;
8940 int32 DoneTotal = 0;
8942 // Creature damage
8943 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
8944 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
8946 if (!(spellProto->AttributesEx6 & SPELL_ATTR_EX6_NO_DMG_PERCENT_MODS))
8948 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
8949 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
8951 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
8952 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
8953 // -1 == any item class (not wand then)
8954 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
8955 // 0 == any inventory type (not wand then)
8957 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8962 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8963 // Add flat bonus from spell damage versus
8964 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
8965 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8966 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8967 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8968 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8970 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8971 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8973 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8974 DoneTotalMod += ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8977 // done scripted mod (take it from owner)
8978 Unit *owner = GetOwner();
8979 if (!owner) owner = this;
8980 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8981 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8983 if (!(*i)->isAffectedOnSpell(spellProto))
8984 continue;
8985 switch((*i)->GetModifier()->m_miscvalue)
8987 case 4920: // Molten Fury
8988 case 4919:
8989 case 6917: // Death's Embrace
8990 case 6926:
8991 case 6928:
8993 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8994 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8995 break;
8997 // Soul Siphon
8998 case 4992:
8999 case 4993:
9001 // effect 1 m_amount
9002 int32 maxPercent = (*i)->GetModifier()->m_amount;
9003 // effect 0 m_amount
9004 int32 stepPercent = CalculateSpellDamage(this, (*i)->GetSpellProto(), EFFECT_INDEX_0);
9005 // count affliction effects and calc additional damage in percentage
9006 int32 modPercent = 0;
9007 AuraMap const& victimAuras = pVictim->GetAuras();
9008 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
9010 SpellEntry const* m_spell = itr->second->GetSpellProto();
9011 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & UI64LIT(0x0004071B8044C402)))
9012 continue;
9013 modPercent += stepPercent * itr->second->GetStackAmount();
9014 if (modPercent >= maxPercent)
9016 modPercent = maxPercent;
9017 break;
9020 DoneTotalMod *= (modPercent+100.0f)/100.0f;
9021 break;
9023 case 6916: // Death's Embrace
9024 case 6925:
9025 case 6927:
9026 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
9027 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
9028 break;
9029 case 5481: // Starfire Bonus
9031 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x0000000000200002)))
9032 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9033 break;
9035 case 4418: // Increased Shock Damage
9036 case 4554: // Increased Lightning Damage
9037 case 4555: // Improved Moonfire
9038 case 5142: // Increased Lightning Damage
9039 case 5147: // Improved Consecration / Libram of Resurgence
9040 case 5148: // Idol of the Shooting Star
9041 case 6008: // Increased Lightning Damage
9042 case 8627: // Totem of Hex
9044 DoneTotal+=(*i)->GetModifier()->m_amount;
9045 break;
9047 // Tundra Stalker
9048 // Merciless Combat
9049 case 7277:
9051 // Merciless Combat
9052 if ((*i)->GetSpellProto()->SpellIconID == 2656)
9054 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9055 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
9057 else // Tundra Stalker
9059 // Frost Fever (target debuff)
9060 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
9061 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9062 break;
9064 break;
9066 case 7293: // Rage of Rivendare
9068 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
9069 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9070 break;
9072 // Twisted Faith
9073 case 7377:
9075 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000000000008000), 0, GetGUID()))
9076 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9077 break;
9079 // Marked for Death
9080 case 7598:
9081 case 7599:
9082 case 7600:
9083 case 7601:
9084 case 7602:
9086 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
9087 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9088 break;
9093 // Custom scripted damage
9094 switch(spellProto->SpellFamilyName)
9096 case SPELLFAMILY_MAGE:
9098 // Ice Lance
9099 if (spellProto->SpellIconID == 186)
9101 if (pVictim->isFrozen())
9103 float multiplier = 3.0f;
9105 // if target have higher level
9106 if (pVictim->getLevel() > getLevel())
9107 // Glyph of Ice Lance
9108 if (Aura* glyph = GetDummyAura(56377))
9109 multiplier = glyph->GetModifier()->m_amount;
9111 DoneTotalMod *= multiplier;
9114 // Torment the weak affected (Arcane Barrage, Arcane Blast, Frostfire Bolt, Arcane Missiles, Fireball)
9115 if ((spellProto->SpellFamilyFlags & UI64LIT(0x0000900020200021)) &&
9116 (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED) || pVictim->HasAuraType(SPELL_AURA_HASTE_ALL)))
9118 //Search for Torment the weak dummy aura
9119 Unit::AuraList const& ttw = GetAurasByType(SPELL_AURA_DUMMY);
9120 for(Unit::AuraList::const_iterator i = ttw.begin(); i != ttw.end(); ++i)
9122 if ((*i)->GetSpellProto()->SpellIconID == 3263)
9124 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9125 break;
9129 break;
9131 case SPELLFAMILY_WARLOCK:
9132 break;
9133 case SPELLFAMILY_PRIEST:
9135 // Glyph of Smite
9136 if (spellProto->SpellFamilyFlags & UI64LIT(0x00000080))
9138 // Holy Fire
9139 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x00100000), NULL))
9140 if (Aura *aur = GetAura(55692, EFFECT_INDEX_0))
9141 DoneTotalMod *= (aur->GetModifier()->m_amount+100.0f) / 100.0f;
9143 break;
9145 case SPELLFAMILY_DRUID:
9147 // Improved Insect Swarm (Wrath part)
9148 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000001))
9150 // if Insect Swarm on target
9151 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x000000000200000), 0, GetGUID()))
9153 Unit::AuraList const& improvedSwarm = GetAurasByType(SPELL_AURA_DUMMY);
9154 for(Unit::AuraList::const_iterator iter = improvedSwarm.begin(); iter != improvedSwarm.end(); ++iter)
9156 if ((*iter)->GetSpellProto()->SpellIconID == 1771)
9158 DoneTotalMod *= ((*iter)->GetModifier()->m_amount+100.0f) / 100.0f;
9159 break;
9164 break;
9166 case SPELLFAMILY_DEATHKNIGHT:
9168 // Icy Touch and Howling Blast
9169 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000200000002))
9171 // search disease
9172 bool found = false;
9173 Unit::AuraMap const& auras = pVictim->GetAuras();
9174 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
9176 if(itr->second->GetSpellProto()->Dispel == DISPEL_DISEASE)
9178 found = true;
9179 break;
9182 if(!found)
9183 break;
9185 // search for Glacier Rot dummy aura
9186 Unit::AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
9187 for(Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
9189 if ((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()] == 7244)
9191 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9192 break;
9196 break;
9198 default:
9199 break;
9202 // Done fixed damage bonus auras
9203 int32 DoneAdvertisedBenefit = SpellBaseDamageBonusDone(GetSpellSchoolMask(spellProto));
9205 // Pets just add their bonus damage to their spell damage
9206 // note that their spell damage is just gain of their own auras
9207 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
9208 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
9210 // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties
9211 DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true);
9213 float tmpDamage = (int32(pdamage) + DoneTotal * int32(stack)) * DoneTotalMod;
9214 // apply spellmod to Done damage (flat and pct)
9215 if(Player* modOwner = GetSpellModOwner())
9216 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
9218 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
9222 * Calculates target part of spell damage bonuses,
9223 * will be called on each tick for periodic damage over time auras
9225 uint32 Unit::SpellDamageBonusTaken(Unit *pCaster, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
9227 if(!spellProto || !pCaster || damagetype==DIRECT_DAMAGE )
9228 return pdamage;
9230 // Taken total percent damage auras
9231 float TakenTotalMod = 1.0f;
9232 int32 TakenTotal = 0;
9234 // ..taken
9235 AuraList const& mModDamagePercentTaken = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
9236 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
9238 if ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto))
9239 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9242 // .. taken pct: dummy auras
9243 if (GetTypeId() == TYPEID_PLAYER)
9245 //Cheat Death
9246 if (Aura *dummy = GetDummyAura(45182))
9248 float mod = -((Player*)this)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
9249 if (mod < float(dummy->GetModifier()->m_amount))
9250 mod = float(dummy->GetModifier()->m_amount);
9251 TakenTotalMod *= (mod+100.0f)/100.0f;
9255 // From caster spells
9256 AuraList const& mOwnerTaken = GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
9257 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
9259 if ((*i)->GetCasterGUID() == pCaster->GetGUID() && (*i)->isAffectedOnSpell(spellProto))
9260 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9263 // Mod damage from spell mechanic
9264 TakenTotalMod *= GetTotalAuraMultiplierByMiscValueForMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT,GetAllSpellMechanicMask(spellProto));
9266 // Mod damage taken from AoE spells
9267 if(IsAreaOfEffectSpell(spellProto))
9269 AuraList const& avoidAuras = GetAurasByType(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
9270 for(AuraList::const_iterator itr = avoidAuras.begin(); itr != avoidAuras.end(); ++itr)
9271 TakenTotalMod *= ((*itr)->GetModifier()->m_amount + 100.0f) / 100.0f;
9274 // Taken fixed damage bonus auras
9275 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusTaken(GetSpellSchoolMask(spellProto));
9277 // apply benefit affected by spell power implicit coeffs and spell level penalties
9278 TakenTotal = SpellBonusWithCoeffs(spellProto, TakenTotal, TakenAdvertisedBenefit, 0, damagetype, false);
9280 float tmpDamage = (int32(pdamage) + TakenTotal * int32(stack)) * TakenTotalMod;
9282 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
9285 int32 Unit::SpellBaseDamageBonusDone(SpellSchoolMask schoolMask)
9287 int32 DoneAdvertisedBenefit = 0;
9289 // ..done
9290 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
9291 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
9293 if (((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
9294 (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand then)
9295 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand then)
9296 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
9299 if (GetTypeId() == TYPEID_PLAYER)
9301 // Base value
9302 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
9304 // Damage bonus from stats
9305 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
9306 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
9308 if((*i)->GetModifier()->m_miscvalue & schoolMask)
9310 // stat used stored in miscValueB for this aura
9311 Stats usedStat = Stats((*i)->GetMiscBValue());
9312 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
9315 // ... and attack power
9316 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
9317 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
9319 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9320 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
9324 return DoneAdvertisedBenefit;
9327 int32 Unit::SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask)
9329 int32 TakenAdvertisedBenefit = 0;
9331 // ..taken
9332 AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
9333 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9335 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
9336 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
9339 return TakenAdvertisedBenefit;
9342 bool Unit::IsSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
9344 // not critting spell
9345 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
9346 return false;
9348 float crit_chance = 0.0f;
9349 switch(spellProto->DmgClass)
9351 case SPELL_DAMAGE_CLASS_NONE:
9352 return false;
9353 case SPELL_DAMAGE_CLASS_MAGIC:
9355 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
9356 crit_chance = 0.0f;
9357 // For other schools
9358 else if (GetTypeId() == TYPEID_PLAYER)
9359 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
9360 else
9362 crit_chance = float(m_baseSpellCritChance);
9363 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
9365 // taken
9366 if (pVictim)
9368 if (!IsPositiveSpell(spellProto->Id))
9370 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
9371 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
9372 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
9373 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
9374 // Modify by player victim resilience
9375 crit_chance -= pVictim->GetSpellCritChanceReduction();
9378 // scripted (increase crit chance ... against ... target by x%)
9379 // scripted (Increases the critical effect chance of your .... by x% on targets ...)
9380 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9381 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9383 if (!((*i)->isAffectedOnSpell(spellProto)))
9384 continue;
9385 switch((*i)->GetModifier()->m_miscvalue)
9387 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
9388 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
9389 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
9390 case 7917: // Glyph of Shadowburn
9391 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9392 crit_chance+=(*i)->GetModifier()->m_amount;
9393 break;
9394 case 7997: // Renewed Hope
9395 case 7998:
9396 if (pVictim->HasAura(6788))
9397 crit_chance+=(*i)->GetModifier()->m_amount;
9398 break;
9399 default:
9400 break;
9403 // Custom crit by class
9404 switch(spellProto->SpellFamilyName)
9406 case SPELLFAMILY_PRIEST:
9407 // Flash Heal
9408 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000800))
9410 if (pVictim->GetHealth() > pVictim->GetMaxHealth()/2)
9411 break;
9412 AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
9413 for(AuraList::const_iterator i = mDummyAuras.begin(); i!= mDummyAuras.end(); ++i)
9415 // Improved Flash Heal
9416 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST &&
9417 (*i)->GetSpellProto()->SpellIconID == 2542)
9419 crit_chance+=(*i)->GetModifier()->m_amount;
9420 break;
9424 break;
9425 case SPELLFAMILY_DRUID:
9426 // Improved Insect Swarm (Starfire part)
9427 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000004))
9429 // search for Moonfire on target
9430 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x000000000000002), 0, GetGUID()))
9432 Unit::AuraList const& improvedSwarm = GetAurasByType(SPELL_AURA_DUMMY);
9433 for(Unit::AuraList::const_iterator iter = improvedSwarm.begin(); iter != improvedSwarm.end(); ++iter)
9435 if ((*iter)->GetSpellProto()->SpellIconID == 1771)
9437 crit_chance += (*iter)->GetModifier()->m_amount;
9438 break;
9443 break;
9444 case SPELLFAMILY_PALADIN:
9445 // Sacred Shield
9446 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000040000000))
9448 Aura *aura = pVictim->GetDummyAura(58597);
9449 if (aura && aura->GetCasterGUID() == GetGUID())
9450 crit_chance+=aura->GetModifier()->m_amount;
9452 // Exorcism
9453 else if (spellProto->Category == 19)
9455 if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
9456 return true;
9458 break;
9459 case SPELLFAMILY_SHAMAN:
9460 // Lava Burst
9461 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000100000000000))
9463 // Flame Shock
9464 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID()))
9465 return true;
9467 break;
9470 break;
9472 case SPELL_DAMAGE_CLASS_MELEE:
9473 case SPELL_DAMAGE_CLASS_RANGED:
9475 if (pVictim)
9476 crit_chance = GetUnitCriticalChance(attackType, pVictim);
9478 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
9479 break;
9481 default:
9482 return false;
9484 // percent done
9485 // only players use intelligence for critical chance computations
9486 if(Player* modOwner = GetSpellModOwner())
9487 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
9489 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
9490 if (roll_chance_f(crit_chance))
9491 return true;
9492 return false;
9495 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
9497 // Calculate critical bonus
9498 int32 crit_bonus;
9499 switch(spellProto->DmgClass)
9501 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
9502 case SPELL_DAMAGE_CLASS_RANGED:
9503 crit_bonus = damage;
9504 break;
9505 default:
9506 crit_bonus = damage / 2; // for spells is 50%
9507 break;
9510 // adds additional damage to crit_bonus (from talents)
9511 if(Player* modOwner = GetSpellModOwner())
9512 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
9514 if(!pVictim)
9515 return damage += crit_bonus;
9517 int32 critPctDamageMod = 0;
9518 if(spellProto->DmgClass >= SPELL_DAMAGE_CLASS_MELEE)
9520 if(GetWeaponAttackType(spellProto) == RANGED_ATTACK)
9521 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
9522 else
9523 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
9525 else
9526 critPctDamageMod += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE,GetSpellSchoolMask(spellProto));
9528 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS, GetSpellSchoolMask(spellProto));
9530 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9531 critPctDamageMod += GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask);
9533 if(critPctDamageMod!=0)
9534 crit_bonus = int32(crit_bonus * float((100.0f + critPctDamageMod)/100.0f));
9536 if(crit_bonus > 0)
9537 damage += crit_bonus;
9539 return damage;
9542 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
9544 // Calculate critical bonus
9545 int32 crit_bonus;
9546 switch(spellProto->DmgClass)
9548 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
9549 case SPELL_DAMAGE_CLASS_RANGED:
9550 // TODO: write here full calculation for melee/ranged spells
9551 crit_bonus = damage;
9552 break;
9553 default:
9554 crit_bonus = damage / 2; // for spells is 50%
9555 break;
9558 if(pVictim)
9560 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9561 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
9564 if(crit_bonus > 0)
9565 damage += crit_bonus;
9567 damage = int32(damage * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
9569 return damage;
9573 * Calculates caster part of healing spell bonuses,
9574 * also includes different bonuses dependent from target auras
9576 uint32 Unit::SpellHealingBonusDone(Unit *pVictim, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack)
9578 // For totems get healing bonus from owner (statue isn't totem in fact)
9579 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
9580 if(Unit* owner = GetOwner())
9581 return owner->SpellHealingBonusDone(pVictim, spellProto, healamount, damagetype, stack);
9583 // No heal amount for this class spells
9584 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
9585 return healamount < 0 ? 0 : healamount;
9587 // Healing Done
9588 // Done total percent damage auras
9589 float DoneTotalMod = 1.0f;
9590 int32 DoneTotal = 0;
9592 // Healing done percent
9593 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
9594 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
9595 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
9597 // done scripted mod (take it from owner)
9598 Unit *owner = GetOwner();
9599 if (!owner) owner = this;
9600 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9601 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9603 if (!(*i)->isAffectedOnSpell(spellProto))
9604 continue;
9605 switch((*i)->GetModifier()->m_miscvalue)
9607 case 4415: // Increased Rejuvenation Healing
9608 case 4953:
9609 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
9610 DoneTotal+=(*i)->GetModifier()->m_amount;
9611 break;
9612 case 7997: // Renewed Hope
9613 case 7998:
9614 if (pVictim->HasAura(6788))
9615 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
9616 break;
9617 case 21: // Test of Faith
9618 case 6935:
9619 case 6918:
9620 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
9621 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
9622 break;
9623 case 7798: // Glyph of Regrowth
9625 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, UI64LIT(0x0000000000000040)))
9626 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9627 break;
9629 case 8477: // Nourish Heal Boost
9631 int32 stepPercent = (*i)->GetModifier()->m_amount;
9633 int ownHotCount = 0; // counted HoT types amount, not stacks
9635 Unit::AuraList const& RejorRegr = pVictim->GetAurasByType(SPELL_AURA_PERIODIC_HEAL);
9636 for(Unit::AuraList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i)
9637 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID &&
9638 (*i)->GetCasterGUID() == GetGUID())
9639 ++ownHotCount;
9641 if (ownHotCount)
9642 DoneTotalMod *= (stepPercent * ownHotCount + 100.0f) / 100.0f;
9643 break;
9645 case 7871: // Glyph of Lesser Healing Wave
9647 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, UI64LIT(0x0000040000000000), 0, GetGUID()))
9648 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9649 break;
9651 default:
9652 break;
9656 // Nourish 20% of heal increase if target is affected by Druids HOTs
9657 if (spellProto->SpellFamilyName == SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags & UI64LIT(0x0200000000000000)))
9659 int ownHotCount = 0; // counted HoT types amount, not stacks
9660 Unit::AuraList const& RejorRegr = pVictim->GetAurasByType(SPELL_AURA_PERIODIC_HEAL);
9661 for(Unit::AuraList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i)
9662 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID &&
9663 (*i)->GetCasterGUID() == GetGUID())
9664 ++ownHotCount;
9666 if (ownHotCount)
9668 DoneTotalMod *= 1.2f; // base bonus at HoTs
9670 if (Aura* glyph = GetAura(62971, EFFECT_INDEX_0))// Glyph of Nourish
9671 DoneTotalMod *= (glyph->GetModifier()->m_amount * ownHotCount + 100.0f) / 100.0f;
9675 // Done fixed damage bonus auras
9676 int32 DoneAdvertisedBenefit = SpellBaseHealingBonusDone(GetSpellSchoolMask(spellProto));
9678 // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties
9679 DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneAdvertisedBenefit, 0, damagetype, true, 1.88f);
9681 // use float as more appropriate for negative values and percent applying
9682 float heal = (healamount + DoneTotal * int32(stack))*DoneTotalMod;
9683 // apply spellmod to Done amount
9684 if(Player* modOwner = GetSpellModOwner())
9685 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
9687 return heal < 0 ? 0 : uint32(heal);
9691 * Calculates target part of healing spell bonuses,
9692 * will be called on each tick for periodic damage over time auras
9694 uint32 Unit::SpellHealingBonusTaken(Unit *pCaster, SpellEntry const *spellProto, int32 healamount, DamageEffectType damagetype, uint32 stack)
9696 float TakenTotalMod = 1.0f;
9698 // Healing taken percent
9699 float minval = float(GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT));
9700 if(minval)
9701 TakenTotalMod *= (100.0f + minval) / 100.0f;
9703 float maxval = float(GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT));
9704 if(maxval)
9705 TakenTotalMod *= (100.0f + maxval) / 100.0f;
9707 // No heal amount for this class spells
9708 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
9710 healamount = int32(healamount * TakenTotalMod);
9711 return healamount < 0 ? 0 : healamount;
9714 // Healing Done
9715 // Done total percent damage auras
9716 int32 TakenTotal = 0;
9718 // Taken fixed damage bonus auras
9719 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusTaken(GetSpellSchoolMask(spellProto));
9721 // apply benefit affected by spell power implicit coeffs and spell level penalties
9722 TakenTotal = SpellBonusWithCoeffs(spellProto, TakenTotal, TakenAdvertisedBenefit, 0, damagetype, false, 1.88f);
9724 AuraList const& mHealingGet= GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
9725 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
9726 if ((*i)->isAffectedOnSpell(spellProto))
9727 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
9729 // use float as more appropriate for negative values and percent applying
9730 float heal = (healamount + TakenTotal * int32(stack)) * TakenTotalMod;
9732 return heal < 0 ? 0 : uint32(heal);
9735 int32 Unit::SpellBaseHealingBonusDone(SpellSchoolMask schoolMask)
9737 int32 AdvertisedBenefit = 0;
9739 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
9740 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
9741 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
9742 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9744 // Healing bonus of spirit, intellect and strength
9745 if (GetTypeId() == TYPEID_PLAYER)
9747 // Base value
9748 AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
9750 // Healing bonus from stats
9751 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
9752 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
9754 // stat used dependent from misc value (stat index)
9755 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
9756 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
9759 // ... and attack power
9760 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
9761 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
9762 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9763 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
9765 return AdvertisedBenefit;
9768 int32 Unit::SpellBaseHealingBonusTaken(SpellSchoolMask schoolMask)
9770 int32 AdvertisedBenefit = 0;
9771 AuraList const& mDamageTaken = GetAurasByType(SPELL_AURA_MOD_HEALING);
9772 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9773 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
9774 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
9776 return AdvertisedBenefit;
9779 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
9781 //If m_immuneToSchool type contain this school type, IMMUNE damage.
9782 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9783 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9784 if (itr->type & shoolMask)
9785 return true;
9787 //If m_immuneToDamage type contain magic, IMMUNE damage.
9788 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
9789 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
9790 if (itr->type & shoolMask)
9791 return true;
9793 return false;
9796 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
9798 if (!spellInfo)
9799 return false;
9801 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
9802 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
9804 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
9805 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
9806 if (itr->type == spellInfo->Dispel)
9807 return true;
9809 if (!(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
9810 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
9812 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
9813 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
9814 if (!(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
9815 (itr->type & GetSpellSchoolMask(spellInfo)))
9816 return true;
9819 if(uint32 mechanic = spellInfo->Mechanic)
9821 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9822 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9823 if (itr->type == mechanic)
9824 return true;
9826 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9827 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9828 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9829 return true;
9832 return false;
9835 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
9837 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
9838 uint32 effect = spellInfo->Effect[index];
9839 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
9840 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
9841 if (itr->type == effect)
9842 return true;
9844 if(uint32 mechanic = spellInfo->EffectMechanic[index])
9846 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
9847 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
9848 if (itr->type == mechanic)
9849 return true;
9851 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MECHANIC_IMMUNITY_MASK);
9852 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9853 if ((*iter)->GetModifier()->m_miscvalue & (1 << (mechanic-1)))
9854 return true;
9857 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
9859 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
9860 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
9861 if (itr->type == aura)
9862 return true;
9864 // Check for immune to application of harmful magical effects
9865 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
9866 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
9867 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
9868 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
9869 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
9870 return true;
9873 return false;
9876 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
9878 if (!spellInfo)
9879 return false;
9881 uint32 family = spellInfo->SpellFamilyName;
9882 uint64 flags = spellInfo->SpellFamilyFlags;
9884 if ((family == 5 && flags == 256) || //Searing Pain
9885 (family == 6 && flags == 8192) || //Mind Blast
9886 (family == 11 && flags == 1048576)) //Earth Shock
9887 return true;
9889 return false;
9893 * Calculates caster part of melee damage bonuses,
9894 * also includes different bonuses dependent from target auras
9896 uint32 Unit::MeleeDamageBonusDone(Unit *pVictim, uint32 pdamage,WeaponAttackType attType, SpellEntry const *spellProto, DamageEffectType damagetype, uint32 stack)
9898 if (!pVictim)
9899 return pdamage;
9901 if (pdamage == 0)
9902 return pdamage;
9904 // differentiate for weapon damage based spells
9905 bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE)));
9906 Item* pWeapon = GetTypeId() == TYPEID_PLAYER ? ((Player*)this)->GetWeaponForAttack(attType,true,false) : NULL;
9907 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
9908 uint32 schoolMask = spellProto ? spellProto->SchoolMask : GetMeleeDamageSchoolMask();
9909 uint32 mechanicMask = spellProto ? GetAllSpellMechanicMask(spellProto) : 0;
9911 // Shred also have bonus as MECHANIC_BLEED damages
9912 if (spellProto && spellProto->SpellFamilyName==SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags & UI64LIT(0x00008000))
9913 mechanicMask |= (1 << (MECHANIC_BLEED-1));
9916 // FLAT damage bonus auras
9917 // =======================
9918 int32 DoneFlat = 0;
9919 int32 APbonus = 0;
9921 // ..done flat, already included in wepon damage based spells
9922 if (!isWeaponDamageBasedSpell)
9924 AuraList const& mModDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
9925 for(AuraList::const_iterator i = mModDamageDone.begin(); i != mModDamageDone.end(); ++i)
9927 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9928 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9929 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9930 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9932 DoneFlat += (*i)->GetModifier()->m_amount;
9936 // Pets just add their bonus damage to their melee damage
9937 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
9938 DoneFlat += ((Pet*)this)->GetBonusDamage();
9941 // ..done flat (by creature type mask)
9942 DoneFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE, creatureTypeMask);
9944 // ..done flat (base at attack power for marked target and base at attack power for creature type)
9945 if (attType == RANGED_ATTACK)
9947 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
9948 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS, creatureTypeMask);
9950 else
9952 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
9953 APbonus += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS, creatureTypeMask);
9956 // PERCENT damage auras
9957 // ====================
9958 float DonePercent = 1.0f;
9960 // ..done pct, already included in weapon damage based spells
9961 if(!isWeaponDamageBasedSpell)
9963 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
9964 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
9966 if ((*i)->GetModifier()->m_miscvalue & schoolMask && // schoolmask has to fit with the intrinsic spell school
9967 (*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask() && // AND schoolmask has to fit with weapon damage school (essential for non-physical spells)
9968 ((*i)->GetSpellProto()->EquippedItemClass == -1 || // general, weapon independent
9969 pWeapon && pWeapon->IsFitToSpellRequirements((*i)->GetSpellProto()))) // OR used weapon fits aura requirements
9971 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
9975 if (attType == OFF_ATTACK)
9976 DonePercent *= GetModifierValue(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_PCT); // no school check required
9979 // ..done pct (by creature type mask)
9980 DonePercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS, creatureTypeMask);
9982 // special dummys/class sripts and other effects
9983 // =============================================
9984 Unit *owner = GetOwner();
9985 if (!owner)
9986 owner = this;
9988 // ..done (class scripts)
9989 if(spellProto)
9991 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9992 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
9994 if (!(*i)->isAffectedOnSpell(spellProto))
9995 continue;
9997 switch((*i)->GetModifier()->m_miscvalue)
9999 // Tundra Stalker
10000 // Merciless Combat
10001 case 7277:
10003 // Merciless Combat
10004 if ((*i)->GetSpellProto()->SpellIconID == 2656)
10006 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
10007 DonePercent *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
10009 else // Tundra Stalker
10011 // Frost Fever (target debuff)
10012 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
10013 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
10014 break;
10016 break;
10018 case 7293: // Rage of Rivendare
10020 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
10021 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
10022 break;
10024 // Marked for Death
10025 case 7598:
10026 case 7599:
10027 case 7600:
10028 case 7601:
10029 case 7602:
10031 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
10032 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
10033 break;
10039 // .. done (class scripts)
10040 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
10041 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
10043 switch((*i)->GetMiscValue())
10045 // Dirty Deeds
10046 case 6427:
10047 case 6428:
10048 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
10050 Aura* eff0 = GetAura((*i)->GetId(), EFFECT_INDEX_0);
10051 if (!eff0 || (*i)->GetEffIndex() != EFFECT_INDEX_1)
10053 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
10054 continue;
10057 // effect 0 have expected value but in negative state
10058 DonePercent *= (-eff0->GetModifier()->m_amount + 100.0f) / 100.0f;
10060 break;
10064 // Frost Strike
10065 if (spellProto && spellProto->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && spellProto->SpellFamilyFlags & UI64LIT(0x0000000400000000))
10067 // search disease
10068 bool found = false;
10069 Unit::AuraMap const& auras = pVictim->GetAuras();
10070 for(Unit::AuraMap::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
10072 if(itr->second->GetSpellProto()->Dispel == DISPEL_DISEASE)
10074 found = true;
10075 break;
10079 if(found)
10081 // search for Glacier Rot dummy aura
10082 Unit::AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
10083 for(Unit::AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
10085 if ((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()] == 7244)
10087 DonePercent *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
10088 break;
10095 // final calculation
10096 // =================
10098 float DoneTotal = 0.0f;
10100 // scaling of non weapon based spells
10101 if (!isWeaponDamageBasedSpell)
10103 // apply ap bonus and benefit affected by spell power implicit coeffs and spell level penalties
10104 DoneTotal = SpellBonusWithCoeffs(spellProto, DoneTotal, DoneFlat, APbonus, damagetype, true);
10106 // weapon damage based spells
10107 else if( APbonus || DoneFlat )
10109 bool normalized = spellProto ? IsSpellHaveEffect(spellProto, SPELL_EFFECT_NORMALIZED_WEAPON_DMG) : false;
10110 DoneTotal += int32(APbonus / 14.0f * GetAPMultiplier(attType,normalized));
10112 // for weapon damage based spells we still have to apply damage done percent mods
10113 // (that are already included into pdamage) to not-yet included DoneFlat
10114 // e.g. from doneVersusCreature, apBonusVs...
10115 UnitMods unitMod;
10116 switch(attType)
10118 default:
10119 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
10120 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
10121 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
10124 DoneTotal += DoneFlat;
10126 DoneTotal *= GetModifierValue(unitMod, TOTAL_PCT);
10129 float tmpDamage = float(int32(pdamage) + DoneTotal * int32(stack)) * DonePercent;
10131 // apply spellmod to Done damage
10132 if(spellProto)
10134 if(Player* modOwner = GetSpellModOwner())
10135 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
10138 // bonus result can be negative
10139 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
10143 * Calculates target part of melee damage bonuses,
10144 * will be called on each tick for periodic damage over time auras
10146 uint32 Unit::MeleeDamageBonusTaken(Unit *pCaster, uint32 pdamage,WeaponAttackType attType, SpellEntry const *spellProto, DamageEffectType damagetype, uint32 stack)
10148 if (!pCaster)
10149 return pdamage;
10151 if (pdamage == 0)
10152 return pdamage;
10154 // differentiate for weapon damage based spells
10155 bool isWeaponDamageBasedSpell = !(spellProto && (damagetype == DOT || IsSpellHaveEffect(spellProto, SPELL_EFFECT_SCHOOL_DAMAGE)));
10156 uint32 schoolMask = spellProto ? spellProto->SchoolMask : GetMeleeDamageSchoolMask();
10157 uint32 mechanicMask = spellProto ? GetAllSpellMechanicMask(spellProto) : 0;
10159 // Shred also have bonus as MECHANIC_BLEED damages
10160 if (spellProto && spellProto->SpellFamilyName==SPELLFAMILY_DRUID && spellProto->SpellFamilyFlags & UI64LIT(0x00008000))
10161 mechanicMask |= (1 << (MECHANIC_BLEED-1));
10164 // FLAT damage bonus auras
10165 // =======================
10166 int32 TakenFlat = 0;
10168 // ..taken flat (base at attack power for marked target and base at attack power for creature type)
10169 if (attType == RANGED_ATTACK)
10170 TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
10171 else
10172 TakenFlat += GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
10174 // ..taken flat (by school mask)
10175 TakenFlat += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_DAMAGE_TAKEN, schoolMask);
10177 // PERCENT damage auras
10178 // ====================
10179 float TakenPercent = 1.0f;
10181 // ..taken pct (by school mask)
10182 TakenPercent *= GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN, schoolMask);
10184 // ..taken pct (by mechanic mask)
10185 TakenPercent *= GetTotalAuraMultiplierByMiscValueForMask(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT,mechanicMask);
10187 // ..taken pct (melee/ranged)
10188 if(attType == RANGED_ATTACK)
10189 TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
10190 else
10191 TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
10193 // ..taken pct (aoe avoidance)
10194 if(spellProto && IsAreaOfEffectSpell(spellProto))
10195 TakenPercent *= GetTotalAuraMultiplier(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
10198 // special dummys/class scripts and other effects
10199 // =============================================
10201 // .. taken (dummy auras)
10202 AuraList const& mDummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
10203 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
10205 switch((*i)->GetSpellProto()->SpellIconID)
10207 //Cheat Death
10208 case 2109:
10209 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
10211 if(GetTypeId() != TYPEID_PLAYER)
10212 continue;
10214 float mod = ((Player*)this)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
10215 if (mod < float((*i)->GetModifier()->m_amount))
10216 mod = float((*i)->GetModifier()->m_amount);
10218 TakenPercent *= (mod + 100.0f) / 100.0f;
10220 break;
10224 // final calculation
10225 // =================
10227 // scaling of non weapon based spells
10228 if (!isWeaponDamageBasedSpell)
10230 // apply benefit affected by spell power implicit coeffs and spell level penalties
10231 TakenFlat = SpellBonusWithCoeffs(spellProto, 0, TakenFlat, 0, damagetype, false);
10234 float tmpDamage = float(int32(pdamage) + TakenFlat * int32(stack)) * TakenPercent;
10236 // bonus result can be negative
10237 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
10240 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
10242 if (apply)
10244 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
10246 next = itr; ++next;
10247 if(itr->type == type)
10249 m_spellImmune[op].erase(itr);
10250 next = m_spellImmune[op].begin();
10253 SpellImmune Immune;
10254 Immune.spellId = spellId;
10255 Immune.type = type;
10256 m_spellImmune[op].push_back(Immune);
10258 else
10260 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
10262 if(itr->spellId == spellId)
10264 m_spellImmune[op].erase(itr);
10265 break;
10272 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
10274 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
10276 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
10277 RemoveAurasWithDispelType(type);
10280 float Unit::GetWeaponProcChance() const
10282 // normalized proc chance for weapon attack speed
10283 // (odd formula...)
10284 if (isAttackReady(BASE_ATTACK))
10285 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
10286 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
10287 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
10289 return 0.0f;
10292 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
10294 // proc per minute chance calculation
10295 if (PPM <= 0.0f)
10296 return 0.0f;
10297 return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
10300 void Unit::Mount(uint32 mount, uint32 spellId)
10302 if (!mount)
10303 return;
10305 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
10307 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
10309 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
10311 if (GetTypeId() == TYPEID_PLAYER)
10313 // Called by Taxi system / GM command
10314 if (!spellId)
10315 ((Player*)this)->UnsummonPetTemporaryIfAny();
10316 // Called by mount aura
10317 else if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId))
10319 // Flying case (Unsummon any pet)
10320 if (IsSpellHaveAura(spellInfo, SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED))
10321 ((Player*)this)->UnsummonPetTemporaryIfAny();
10322 // Normal case (Unsummon only permanent pet)
10323 else if (Pet* pet = GetPet())
10325 if (pet->IsPermanentPetFor((Player*)this) && !((Player*)this)->InArena())
10326 ((Player*)this)->UnsummonPetTemporaryIfAny();
10327 else
10328 pet->ApplyModeFlags(PET_MODE_DISABLE_ACTIONS,true);
10334 void Unit::Unmount()
10336 if (!IsMounted())
10337 return;
10339 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
10341 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
10342 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
10344 // only resummon old pet if the player is already added to a map
10345 // this prevents adding a pet to a not created map which would otherwise cause a crash
10346 // (it could probably happen when logging in after a previous crash)
10347 if(GetTypeId() == TYPEID_PLAYER)
10349 if(Pet* pet = GetPet())
10350 pet->ApplyModeFlags(PET_MODE_DISABLE_ACTIONS,false);
10351 else
10352 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
10356 void Unit::SetInCombatWith(Unit* enemy)
10358 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
10359 if (eOwner->IsPvP())
10361 SetInCombatState(true,enemy);
10362 return;
10365 //check for duel
10366 if (eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
10368 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
10369 if(((Player const*)eOwner)->duel->opponent == myOwner)
10371 SetInCombatState(true,enemy);
10372 return;
10376 SetInCombatState(false,enemy);
10379 void Unit::SetInCombatState(bool PvP, Unit* enemy)
10381 // only alive units can be in combat
10382 if (!isAlive())
10383 return;
10385 if (PvP)
10386 m_CombatTimer = 5000;
10388 bool creatureNotInCombat = GetTypeId()==TYPEID_UNIT && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
10390 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
10392 if (isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
10393 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
10395 if (creatureNotInCombat)
10397 // should probably be removed for the attacked (+ it's party/group) only, not global
10398 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
10400 if (((Creature*)this)->AI())
10401 ((Creature*)this)->AI()->EnterCombat(enemy);
10405 void Unit::ClearInCombat()
10407 m_CombatTimer = 0;
10408 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
10410 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
10411 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
10413 // Player's state will be cleared in Player::UpdateContestedPvP
10414 if (GetTypeId() != TYPEID_PLAYER)
10416 Creature* creature = (Creature*)this;
10417 if (creature->GetCreatureInfo() && creature->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE)
10418 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
10420 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
10422 else
10423 ((Player*)this)->UpdatePotionCooldown();
10426 bool Unit::isTargetableForAttack(bool inverseAlive /*=false*/) const
10428 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
10429 return false;
10431 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
10432 return false;
10434 // to be removed if unit by any reason enter combat
10435 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
10436 return false;
10438 // inversealive is needed for some spells which need to be casted at dead targets (aoe)
10439 if (isAlive() == inverseAlive)
10440 return false;
10442 return IsInWorld() && !hasUnitState(UNIT_STAT_DIED) && !isInFlight();
10445 int32 Unit::ModifyHealth(int32 dVal)
10447 int32 gain = 0;
10449 if(dVal==0)
10450 return 0;
10452 int32 curHealth = (int32)GetHealth();
10454 int32 val = dVal + curHealth;
10455 if(val <= 0)
10457 SetHealth(0);
10458 return -curHealth;
10461 int32 maxHealth = (int32)GetMaxHealth();
10463 if(val < maxHealth)
10465 SetHealth(val);
10466 gain = val - curHealth;
10468 else if(curHealth != maxHealth)
10470 SetHealth(maxHealth);
10471 gain = maxHealth - curHealth;
10474 return gain;
10477 int32 Unit::ModifyPower(Powers power, int32 dVal)
10479 int32 gain = 0;
10481 if(dVal==0)
10482 return 0;
10484 int32 curPower = (int32)GetPower(power);
10486 int32 val = dVal + curPower;
10487 if(val <= 0)
10489 SetPower(power,0);
10490 return -curPower;
10493 int32 maxPower = (int32)GetMaxPower(power);
10495 if(val < maxPower)
10497 SetPower(power,val);
10498 gain = val - curPower;
10500 else if(curPower != maxPower)
10502 SetPower(power,maxPower);
10503 gain = maxPower - curPower;
10506 return gain;
10509 bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool inVisibleList, bool is3dDistance) const
10511 if(!u || !IsInMap(u))
10512 return false;
10514 // Always can see self
10515 if (u==this)
10516 return true;
10518 // player visible for other player if not logout and at same transport
10519 // including case when player is out of world
10520 bool at_same_transport =
10521 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
10522 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
10523 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
10524 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
10526 // not in world
10527 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
10528 return false;
10530 // forbidden to seen (at GM respawn command)
10531 if(m_Visibility==VISIBILITY_RESPAWN)
10532 return false;
10534 Map& _map = *u->GetMap();
10535 // Grid dead/alive checks
10536 if (u->GetTypeId()==TYPEID_PLAYER)
10538 // non visible at grid for any stealth state
10539 if(!IsVisibleInGridForPlayer((Player *)u))
10540 return false;
10542 // if player is dead then he can't detect anyone in any cases
10543 if(!u->isAlive())
10544 detect = false;
10546 else
10548 // all dead creatures/players not visible for any creatures
10549 if(!u->isAlive() || !isAlive())
10550 return false;
10553 // always seen by far sight caster
10554 if (u->GetTypeId()==TYPEID_PLAYER && ((Player*)u)->GetFarSight()==GetGUID())
10555 return true;
10557 // different visible distance checks
10558 if (u->isInFlight()) // what see player in flight
10560 // use object grey distance for all (only see objects any way)
10561 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
10562 return false;
10564 else if(!isAlive()) // distance for show body
10566 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
10567 return false;
10569 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
10571 if(u->GetTypeId()==TYPEID_PLAYER)
10573 // Players far than max visible distance for player or not in our map are not visible too
10574 if (!at_same_transport && !IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10575 return false;
10577 else
10579 // Units far than max visible distance for creature or not in our map are not visible too
10580 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10581 return false;
10584 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
10586 // Pet/charmed far than max visible distance for player or not in our map are not visible too
10587 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10588 return false;
10590 else // distance for show creature
10592 // Units far than max visible distance for creature or not in our map are not visible too
10593 if (!IsWithinDistInMap(viewPoint, _map.GetVisibilityDistance() + (inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
10594 return false;
10597 // always seen by owner
10598 if (GetCharmerOrOwnerGUID()==u->GetGUID())
10599 return true;
10601 // isInvisibleForAlive() those units can only be seen by dead or if other
10602 // unit is also invisible for alive.. if an isinvisibleforalive unit dies we
10603 // should be able to see it too
10604 if (u->isAlive() && isAlive() && isInvisibleForAlive() != u->isInvisibleForAlive())
10605 if (u->GetTypeId() != TYPEID_PLAYER || !((Player *)u)->isGameMaster())
10606 return false;
10608 // Visible units, always are visible for all units, except for units under invisibility and phases
10609 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
10610 return true;
10612 // GMs see any players, not higher GMs and all units in any phase
10613 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
10615 if(GetTypeId() == TYPEID_PLAYER)
10616 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
10617 else
10618 return true;
10621 // non faction visibility non-breakable for non-GMs
10622 if (m_Visibility == VISIBILITY_OFF)
10623 return false;
10625 // phased visibility (both must phased in same way)
10626 if(!InSamePhase(u))
10627 return false;
10629 // raw invisibility
10630 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
10632 // detectable invisibility case
10633 if( invisible && (
10634 // Invisible units, always are visible for units under same invisibility type
10635 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
10636 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
10637 u->canDetectInvisibilityOf(this) ||
10638 // Units that can detect invisibility always are visible for units that can be detected
10639 canDetectInvisibilityOf(u) ))
10641 invisible = false;
10644 // special cases for always overwrite invisibility/stealth
10645 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
10647 // non-hostile case
10648 if (!u->IsHostileTo(this))
10650 // 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)
10651 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
10653 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
10654 return true;
10656 // else apply same rules as for hostile case (detecting check for stealth)
10659 // hostile case
10660 else
10662 // Hunter mark functionality
10663 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
10664 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
10665 if((*iter)->GetCasterGUID()==u->GetGUID())
10666 return true;
10668 // else apply detecting check for stealth
10671 // none other cases for detect invisibility, so invisible
10672 if(invisible)
10673 return false;
10675 // else apply stealth detecting check
10678 // unit got in stealth in this moment and must ignore old detected state
10679 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
10680 return false;
10682 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
10683 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
10684 return true;
10686 // NOW ONLY STEALTH CASE
10688 //if in non-detect mode then invisible for unit
10689 //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false)
10690 //players detect players only in Player::HandleStealthedUnitsDetection()
10691 if (!detect)
10692 return (u->GetTypeId() == TYPEID_PLAYER) ? ((Player*)u)->HaveAtClient(this) : false;
10694 // Special cases
10696 // If is attacked then stealth is lost, some creature can use stealth too
10697 if( !getAttackers().empty() )
10698 return true;
10700 // If there is collision rogue is seen regardless of level difference
10701 if (IsWithinDist(u,0.24f))
10702 return true;
10704 //If a mob or player is stunned he will not be able to detect stealth
10705 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
10706 return false;
10708 // set max ditance
10709 float visibleDistance = (u->GetTypeId() == TYPEID_PLAYER) ? MAX_PLAYER_STEALTH_DETECT_RANGE : ((Creature const*)u)->GetAttackDistance(this);
10711 //Always invisible from back (when stealth detection is on), also filter max distance cases
10712 bool isInFront = viewPoint->isInFrontInMap(this, visibleDistance);
10713 if(!isInFront)
10714 return false;
10716 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
10717 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
10719 //Calculation if target is in front
10721 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
10722 visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
10724 //Visible distance is modified by
10725 //-Level Diff (every level diff = 1.0f in visible distance)
10726 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
10728 //This allows to check talent tree and will add addition stealth dependent on used points)
10729 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
10730 if(stealthMod < 0)
10731 stealthMod = 0;
10733 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
10734 //based on wowwiki every 5 mod we have 1 more level diff in calculation
10735 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_DETECT)) - stealthMod)/5.0f;
10736 visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
10738 // recheck new distance
10739 if(visibleDistance <= 0 || !IsWithinDist(viewPoint,visibleDistance))
10740 return false;
10743 // Now check is target visible with LoS
10744 float ox,oy,oz;
10745 viewPoint->GetPosition(ox,oy,oz);
10746 return IsWithinLOS(ox,oy,oz);
10749 void Unit::SetVisibility(UnitVisibility x)
10751 m_Visibility = x;
10753 if(IsInWorld())
10755 Map *m = GetMap();
10757 if(GetTypeId()==TYPEID_PLAYER)
10758 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10759 else
10760 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
10764 bool Unit::canDetectInvisibilityOf(Unit const* u) const
10766 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
10768 for(uint32 i = 0; i < 10; ++i)
10770 if(((1 << i) & mask)==0)
10771 continue;
10773 // find invisibility level
10774 int32 invLevel = 0;
10775 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
10776 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
10777 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
10778 invLevel = (*itr)->GetModifier()->m_amount;
10780 // find invisibility detect level
10781 int32 detectLevel = 0;
10782 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
10783 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
10784 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
10785 detectLevel = (*itr)->GetModifier()->m_amount;
10787 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
10789 detectLevel = ((Player*)this)->GetDrunkValue();
10792 if(invLevel <= detectLevel)
10793 return true;
10797 return false;
10800 struct UpdateWalkModeHelper
10802 explicit UpdateWalkModeHelper(Unit* _source) : source(_source) {}
10803 void operator()(Unit* unit) const { unit->UpdateWalkMode(source, true); }
10804 Unit* source;
10807 void Unit::UpdateWalkMode(Unit* source, bool self)
10809 if (GetTypeId() == TYPEID_PLAYER)
10810 ((Player*)this)->CallForAllControlledUnits(UpdateWalkModeHelper(source), false, true, true, true);
10811 else if (self)
10813 bool on = source->GetTypeId() == TYPEID_PLAYER
10814 ? ((Player*)source)->HasMovementFlag(MOVEFLAG_WALK_MODE)
10815 : ((Creature*)source)->HasSplineFlag(SPLINEFLAG_WALKMODE);
10817 if (on)
10819 if (((Creature*)this)->isPet() && hasUnitState(UNIT_STAT_FOLLOW))
10820 ((Creature*)this)->AddSplineFlag(SPLINEFLAG_WALKMODE);
10822 else
10824 if (((Creature*)this)->isPet())
10825 ((Creature*)this)->RemoveSplineFlag(SPLINEFLAG_WALKMODE);
10828 else
10829 CallForAllControlledUnits(UpdateWalkModeHelper(source), false, true, true);
10832 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced, float ratio)
10834 // not in combat pet have same speed as owner
10835 switch(mtype)
10837 case MOVE_RUN:
10838 case MOVE_WALK:
10839 case MOVE_SWIM:
10840 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet() && hasUnitState(UNIT_STAT_FOLLOW))
10842 if(Unit* owner = GetOwner())
10844 SetSpeedRate(mtype, owner->GetSpeedRate(mtype), forced);
10845 return;
10848 break;
10851 int32 main_speed_mod = 0;
10852 float stack_bonus = 1.0f;
10853 float non_stack_bonus = 1.0f;
10855 switch(mtype)
10857 case MOVE_WALK:
10858 return;
10859 case MOVE_RUN:
10861 if (IsMounted()) // Use on mount auras
10863 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
10864 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
10865 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
10867 else
10869 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
10870 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
10871 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
10873 break;
10875 case MOVE_RUN_BACK:
10876 return;
10877 case MOVE_SWIM:
10879 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
10880 break;
10882 case MOVE_SWIM_BACK:
10883 return;
10884 case MOVE_FLIGHT:
10886 if (IsMounted()) // Use on mount auras
10888 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED);
10889 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_STACKING);
10890 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_NOT_STACKING))/100.0f;
10892 else // Use not mount (shapeshift for example) auras (should stack)
10894 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED);
10895 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_STACKING);
10896 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACKING))/100.0f;
10898 break;
10900 case MOVE_FLIGHT_BACK:
10901 return;
10902 default:
10903 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
10904 return;
10907 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
10908 // now we ready for speed calculation
10909 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
10911 switch(mtype)
10913 case MOVE_RUN:
10914 case MOVE_SWIM:
10915 case MOVE_FLIGHT:
10917 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
10918 // TODO: possible affect only on MOVE_RUN
10919 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
10921 // Use speed from aura
10922 float max_speed = normalization / baseMoveSpeed[mtype];
10923 if (speed > max_speed)
10924 speed = max_speed;
10926 break;
10928 default:
10929 break;
10932 // for creature case, we check explicit if mob searched for assistance
10933 if (GetTypeId() == TYPEID_UNIT)
10935 if (((Creature*)this)->HasSearchedAssistance())
10936 speed *= 0.66f; // best guessed value, so this will be 33% reduction. Based off initial speed, mob can then "run", "walk fast" or "walk".
10939 // Apply strongest slow aura mod to speed
10940 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
10941 if (slow)
10943 speed *=(100.0f + slow)/100.0f;
10944 float min_speed = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED) / 100.0f;
10945 if (speed < min_speed)
10946 speed = min_speed;
10948 SetSpeedRate(mtype, speed * ratio, forced);
10951 float Unit::GetSpeed( UnitMoveType mtype ) const
10953 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
10956 struct SetSpeedRateHelper
10958 explicit SetSpeedRateHelper(UnitMoveType _mtype, bool _forced) : mtype(_mtype), forced(_forced) {}
10959 void operator()(Unit* unit) const { unit->UpdateSpeed(mtype,forced); }
10960 UnitMoveType mtype;
10961 bool forced;
10964 void Unit::SetSpeedRate(UnitMoveType mtype, float rate, bool forced)
10966 if (rate < 0)
10967 rate = 0.0f;
10969 // Update speed only on change
10970 if (m_speed_rate[mtype] == rate)
10971 return;
10973 m_speed_rate[mtype] = rate;
10975 propagateSpeedChange();
10977 WorldPacket data;
10978 if(!forced)
10980 switch(mtype)
10982 case MOVE_WALK:
10983 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10984 break;
10985 case MOVE_RUN:
10986 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
10987 break;
10988 case MOVE_RUN_BACK:
10989 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10990 break;
10991 case MOVE_SWIM:
10992 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
10993 break;
10994 case MOVE_SWIM_BACK:
10995 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
10996 break;
10997 case MOVE_TURN_RATE:
10998 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
10999 break;
11000 case MOVE_FLIGHT:
11001 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
11002 break;
11003 case MOVE_FLIGHT_BACK:
11004 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
11005 break;
11006 case MOVE_PITCH_RATE:
11007 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
11008 break;
11009 default:
11010 sLog.outError("Unit::SetSpeedRate: Unsupported move type (%d), data not sent to client.",mtype);
11011 return;
11014 data << GetPackGUID();
11015 data << uint32(0); // movement flags
11016 data << uint16(0); // unk flags
11017 data << uint32(getMSTime());
11018 data << float(GetPositionX());
11019 data << float(GetPositionY());
11020 data << float(GetPositionZ());
11021 data << float(GetOrientation());
11022 data << uint32(0); // fall time
11023 data << float(GetSpeed(mtype));
11024 SendMessageToSet( &data, true );
11026 else
11028 if(GetTypeId() == TYPEID_PLAYER)
11030 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
11031 // and do it only for real sent packets and use run for run/mounted as client expected
11032 ++((Player*)this)->m_forced_speed_changes[mtype];
11035 switch(mtype)
11037 case MOVE_WALK:
11038 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
11039 break;
11040 case MOVE_RUN:
11041 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
11042 break;
11043 case MOVE_RUN_BACK:
11044 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
11045 break;
11046 case MOVE_SWIM:
11047 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
11048 break;
11049 case MOVE_SWIM_BACK:
11050 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
11051 break;
11052 case MOVE_TURN_RATE:
11053 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
11054 break;
11055 case MOVE_FLIGHT:
11056 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
11057 break;
11058 case MOVE_FLIGHT_BACK:
11059 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
11060 break;
11061 case MOVE_PITCH_RATE:
11062 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
11063 break;
11064 default:
11065 sLog.outError("Unit::SetSpeedRate: Unsupported move type (%d), data not sent to client.",mtype);
11066 return;
11068 data << GetPackGUID();
11069 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
11070 if (mtype == MOVE_RUN)
11071 data << uint8(0); // new 2.1.0
11072 data << float(GetSpeed(mtype));
11073 SendMessageToSet( &data, true );
11076 if (GetTypeId() == TYPEID_PLAYER) // need include minpet
11077 ((Player*)this)->CallForAllControlledUnits(SetSpeedRateHelper(mtype,forced),false,true,true,true);
11078 else
11079 CallForAllControlledUnits(SetSpeedRateHelper(mtype,forced),false,true,true);
11082 void Unit::SetHover(bool on)
11084 if(on)
11085 CastSpell(this, 11010, true);
11086 else
11087 RemoveAurasDueToSpell(11010);
11090 void Unit::setDeathState(DeathState s)
11092 if (s != ALIVE && s!= JUST_ALIVED)
11094 CombatStop();
11095 DeleteThreatList();
11096 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
11098 if(IsNonMeleeSpellCasted(false))
11099 InterruptNonMeleeSpells(false);
11102 if (s == JUST_DIED)
11104 RemoveAllAurasOnDeath();
11105 RemoveGuardians();
11106 UnsummonAllTotems();
11108 // after removing a Fearaura (in RemoveAllAurasOnDeath)
11109 // Unit::SetFeared is called and makes that creatures attack player again
11110 StopMoving();
11112 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
11113 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
11114 // remove aurastates allowing special moves
11115 ClearAllReactives();
11116 ClearDiminishings();
11118 else if(s == JUST_ALIVED)
11120 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
11123 if (m_deathState != ALIVE && s == ALIVE)
11125 //_ApplyAllAuraMods();
11127 m_deathState = s;
11130 /*########################################
11131 ######## ########
11132 ######## AGGRO SYSTEM ########
11133 ######## ########
11134 ########################################*/
11135 bool Unit::CanHaveThreatList() const
11137 // only creatures can have threat list
11138 if( GetTypeId() != TYPEID_UNIT )
11139 return false;
11141 // only alive units can have threat list
11142 if( !isAlive() )
11143 return false;
11145 // totems can not have threat list
11146 if( ((Creature*)this)->isTotem() )
11147 return false;
11149 // vehicles can not have threat list
11150 if( ((Creature*)this)->isVehicle() )
11151 return false;
11153 // pets can not have a threat list, unless they are controlled by a creature
11154 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
11155 return false;
11157 return true;
11160 //======================================================================
11162 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
11164 if (!HasAuraType(SPELL_AURA_MOD_THREAT))
11165 return threat;
11167 if (schoolMask == SPELL_SCHOOL_MASK_NONE)
11168 return threat;
11170 SpellSchools school = GetFirstSchoolInMask(schoolMask);
11172 return threat * m_threatModifier[school];
11175 //======================================================================
11177 void Unit::AddThreat(Unit* pVictim, float threat /*= 0.0f*/, bool crit /*= false*/, SpellSchoolMask schoolMask /*= SPELL_SCHOOL_MASK_NONE*/, SpellEntry const *threatSpell /*= NULL*/)
11179 // Only mobs can manage threat lists
11180 if(CanHaveThreatList())
11181 m_ThreatManager.addThreat(pVictim, threat, crit, schoolMask, threatSpell);
11184 //======================================================================
11186 void Unit::DeleteThreatList()
11188 if(CanHaveThreatList() && !m_ThreatManager.isThreatListEmpty())
11189 SendThreatClear();
11190 m_ThreatManager.clearReferences();
11193 //======================================================================
11195 void Unit::TauntApply(Unit* taunter)
11197 ASSERT(GetTypeId()== TYPEID_UNIT);
11199 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
11200 return;
11202 if(!CanHaveThreatList())
11203 return;
11205 Unit *target = getVictim();
11206 if(target && target == taunter)
11207 return;
11209 SetInFront(taunter);
11210 if (((Creature*)this)->AI())
11211 ((Creature*)this)->AI()->AttackStart(taunter);
11213 m_ThreatManager.tauntApply(taunter);
11216 //======================================================================
11218 void Unit::TauntFadeOut(Unit *taunter)
11220 ASSERT(GetTypeId()== TYPEID_UNIT);
11222 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
11223 return;
11225 if(!CanHaveThreatList())
11226 return;
11228 Unit *target = getVictim();
11229 if(!target || target != taunter)
11230 return;
11232 if(m_ThreatManager.isThreatListEmpty())
11234 if(((Creature*)this)->AI())
11235 ((Creature*)this)->AI()->EnterEvadeMode();
11236 return;
11239 m_ThreatManager.tauntFadeOut(taunter);
11240 target = m_ThreatManager.getHostileTarget();
11242 if (target && target != taunter)
11244 SetInFront(target);
11245 if (((Creature*)this)->AI())
11246 ((Creature*)this)->AI()->AttackStart(target);
11250 //======================================================================
11252 bool Unit::SelectHostileTarget()
11254 //function provides main threat functionality
11255 //next-victim-selection algorithm and evade mode are called
11256 //threat list sorting etc.
11258 ASSERT(GetTypeId()== TYPEID_UNIT);
11260 if (!this->isAlive())
11261 return false;
11262 //This function only useful once AI has been initialized
11263 if (!((Creature*)this)->AI())
11264 return false;
11266 Unit* target = NULL;
11268 // First checking if we have some taunt on us
11269 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
11270 if ( !tauntAuras.empty() )
11272 Unit* caster;
11274 // The last taunt aura caster is alive an we are happy to attack him
11275 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
11276 return true;
11277 else if (tauntAuras.size() > 1)
11279 // We do not have last taunt aura caster but we have more taunt auras,
11280 // so find first available target
11282 // Auras are pushed_back, last caster will be on the end
11283 AuraList::const_iterator aura = --tauntAuras.end();
11286 --aura;
11287 if ( (caster = (*aura)->GetCaster()) &&
11288 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
11290 target = caster;
11291 break;
11293 }while (aura != tauntAuras.begin());
11297 if ( !target && !m_ThreatManager.isThreatListEmpty() )
11298 // No taunt aura or taunt aura caster is dead standart target selection
11299 target = m_ThreatManager.getHostileTarget();
11301 if (target)
11303 if (!hasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_DIED))
11305 SetInFront(target);
11306 ((Creature*)this)->AI()->AttackStart(target);
11308 return true;
11311 // no target but something prevent go to evade mode
11312 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
11313 return false;
11315 // last case when creature don't must go to evade mode:
11316 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
11317 // for example at owner command to pet attack some far away creature
11318 // Note: creature not have targeted movement generator but have attacker in this case
11319 if (GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE)
11321 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
11323 if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this))
11324 return false;
11328 // enter in evade mode in other case
11329 ((Creature*)this)->AI()->EnterEvadeMode();
11331 return false;
11334 //======================================================================
11335 //======================================================================
11336 //======================================================================
11338 int32 Unit::CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, SpellEffectIndex effect_index, int32 const* effBasePoints)
11340 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
11342 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
11344 int32 level = int32(getLevel());
11345 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
11346 level = (int32)spellProto->maxLevel;
11347 else if (level < (int32)spellProto->baseLevel)
11348 level = (int32)spellProto->baseLevel;
11349 level-= (int32)spellProto->spellLevel;
11351 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
11352 int32 basePoints = effBasePoints ? *effBasePoints - 1 : spellProto->EffectBasePoints[effect_index];
11353 basePoints += int32(level * basePointsPerLevel);
11354 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index]);
11355 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
11357 switch(randomPoints)
11359 case 0: // not used
11360 case 1: basePoints += 1; break; // range 1..1
11361 default:
11362 // range can have positive (1..rand) and negative (rand..1) values, so order its for irand
11363 int32 randvalue = (randomPoints >= 1)
11364 ? irand(1, randomPoints)
11365 : irand(randomPoints, 1);
11367 basePoints += randvalue;
11368 break;
11371 int32 value = basePoints;
11373 // random damage
11374 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
11375 value += (int32)(comboDamage * comboPoints);
11377 if(Player* modOwner = GetSpellModOwner())
11379 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value);
11380 switch(effect_index)
11382 case 0:
11383 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value);
11384 break;
11385 case 1:
11386 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value);
11387 break;
11388 case 2:
11389 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value);
11390 break;
11394 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
11395 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
11396 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
11397 (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED))
11398 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
11400 return value;
11403 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, SpellEffectIndex effect_index, Unit const* target)
11405 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
11407 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
11409 int32 minduration = GetSpellDuration(spellProto);
11410 int32 maxduration = GetSpellMaxDuration(spellProto);
11412 int32 duration;
11414 if( minduration != -1 && minduration != maxduration )
11415 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
11416 else
11417 duration = minduration;
11419 if (duration > 0)
11421 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
11422 // Find total mod value (negative bonus)
11423 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
11424 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura for negatve effects (stack always ?)
11425 if (!IsPositiveEffect(spellProto->Id, effect_index))
11426 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
11427 // Find max mod (negative bonus)
11428 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
11430 if (!IsPositiveSpell(spellProto->Id))
11431 durationMod_always += target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_MAGIC_EFFECTS, spellProto->DmgClass);
11433 int32 durationMod = 0;
11434 // Select strongest negative mod
11435 if (durationMod_always > durationMod_not_stack)
11436 durationMod = durationMod_not_stack;
11437 else
11438 durationMod = durationMod_always;
11440 if (durationMod != 0)
11441 duration = int32(int64(duration) * (100+durationMod) /100);
11443 if (duration < 0) duration = 0;
11446 return duration;
11449 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
11451 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11453 if(i->DRGroup != group)
11454 continue;
11456 if(!i->hitCount)
11457 return DIMINISHING_LEVEL_1;
11459 if(!i->hitTime)
11460 return DIMINISHING_LEVEL_1;
11462 // If last spell was casted more than 15 seconds ago - reset the count.
11463 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
11465 i->hitCount = DIMINISHING_LEVEL_1;
11466 return DIMINISHING_LEVEL_1;
11468 // or else increase the count.
11469 else
11471 return DiminishingLevels(i->hitCount);
11474 return DIMINISHING_LEVEL_1;
11477 void Unit::IncrDiminishing(DiminishingGroup group)
11479 // Checking for existing in the table
11480 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11482 if(i->DRGroup != group)
11483 continue;
11484 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
11485 i->hitCount += 1;
11486 return;
11488 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
11491 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
11493 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
11494 return;
11496 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
11497 if(limitduration > 0 && duration > limitduration)
11499 // test pet/charm masters instead pets/charmeds
11500 Unit const* targetOwner = GetCharmerOrOwner();
11501 Unit const* casterOwner = caster->GetCharmerOrOwner();
11503 Unit const* target = targetOwner ? targetOwner : this;
11504 Unit const* source = casterOwner ? casterOwner : caster;
11506 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
11507 duration = limitduration;
11510 float mod = 1.0f;
11512 // Some diminishings applies to mobs too (for example, Stun)
11513 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
11515 DiminishingLevels diminish = Level;
11516 switch(diminish)
11518 case DIMINISHING_LEVEL_1: break;
11519 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
11520 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
11521 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
11522 default: break;
11526 duration = int32(duration * mod);
11529 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
11531 // Checking for existing in the table
11532 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
11534 if(i->DRGroup != group)
11535 continue;
11537 if(apply)
11538 i->stack += 1;
11539 else if(i->stack)
11541 i->stack -= 1;
11542 // Remember time after last aura from group removed
11543 if (i->stack == 0)
11544 i->hitTime = getMSTime();
11546 break;
11550 Unit* Unit::GetUnit(WorldObject const& object, uint64 guid)
11552 return ObjectAccessor::GetUnit(object,guid);
11555 bool Unit::isVisibleForInState( Player const* u, WorldObject const* viewPoint, bool inVisibleList ) const
11557 return isVisibleForOrDetect(u, viewPoint, false, inVisibleList, false);
11560 /// returns true if creature can't be seen by alive units
11561 bool Unit::isInvisibleForAlive() const
11563 if (m_AuraFlags & UNIT_AURAFLAG_ALIVE_INVISIBLE)
11564 return true;
11565 // TODO: maybe spiritservices also have just an aura
11566 return isSpiritService();
11569 uint32 Unit::GetCreatureType() const
11571 if(GetTypeId() == TYPEID_PLAYER)
11573 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
11574 if(ssEntry && ssEntry->creatureType > 0)
11575 return ssEntry->creatureType;
11576 else
11577 return CREATURE_TYPE_HUMANOID;
11579 else
11580 return ((Creature*)this)->GetCreatureInfo()->type;
11583 /*#######################################
11584 ######## ########
11585 ######## STAT SYSTEM ########
11586 ######## ########
11587 #######################################*/
11589 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
11591 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
11593 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
11594 return false;
11597 float val = 1.0f;
11599 switch(modifierType)
11601 case BASE_VALUE:
11602 case TOTAL_VALUE:
11603 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
11604 break;
11605 case BASE_PCT:
11606 case TOTAL_PCT:
11607 if(amount <= -100.0f) //small hack-fix for -100% modifiers
11608 amount = -200.0f;
11610 val = (100.0f + amount) / 100.0f;
11611 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
11612 break;
11614 default:
11615 break;
11618 if(!CanModifyStats())
11619 return false;
11621 switch(unitMod)
11623 case UNIT_MOD_STAT_STRENGTH:
11624 case UNIT_MOD_STAT_AGILITY:
11625 case UNIT_MOD_STAT_STAMINA:
11626 case UNIT_MOD_STAT_INTELLECT:
11627 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
11629 case UNIT_MOD_ARMOR: UpdateArmor(); break;
11630 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
11632 case UNIT_MOD_MANA:
11633 case UNIT_MOD_RAGE:
11634 case UNIT_MOD_FOCUS:
11635 case UNIT_MOD_ENERGY:
11636 case UNIT_MOD_HAPPINESS:
11637 case UNIT_MOD_RUNE:
11638 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
11640 case UNIT_MOD_RESISTANCE_HOLY:
11641 case UNIT_MOD_RESISTANCE_FIRE:
11642 case UNIT_MOD_RESISTANCE_NATURE:
11643 case UNIT_MOD_RESISTANCE_FROST:
11644 case UNIT_MOD_RESISTANCE_SHADOW:
11645 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
11647 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
11648 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
11650 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
11651 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
11652 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
11654 default:
11655 break;
11658 return true;
11661 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
11663 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
11665 sLog.outError("trial to access non existed modifier value from UnitMods!");
11666 return 0.0f;
11669 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
11670 return 0.0f;
11672 return m_auraModifiersGroup[unitMod][modifierType];
11675 float Unit::GetTotalStatValue(Stats stat) const
11677 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
11679 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
11680 return 0.0f;
11682 // value = ((base_value * base_pct) + total_value) * total_pct
11683 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
11684 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
11685 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
11686 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
11688 return value;
11691 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
11693 if(unitMod >= UNIT_MOD_END)
11695 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
11696 return 0.0f;
11699 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
11700 return 0.0f;
11702 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
11703 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
11704 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
11705 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
11707 return value;
11710 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
11712 SpellSchools school = SPELL_SCHOOL_NORMAL;
11714 switch(unitMod)
11716 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
11717 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
11718 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
11719 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
11720 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
11721 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
11723 default:
11724 break;
11727 return school;
11730 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
11732 Stats stat = STAT_STRENGTH;
11734 switch(unitMod)
11736 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
11737 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
11738 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
11739 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
11740 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
11742 default:
11743 break;
11746 return stat;
11749 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
11751 switch(unitMod)
11753 case UNIT_MOD_MANA: return POWER_MANA;
11754 case UNIT_MOD_RAGE: return POWER_RAGE;
11755 case UNIT_MOD_FOCUS: return POWER_FOCUS;
11756 case UNIT_MOD_ENERGY: return POWER_ENERGY;
11757 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
11758 case UNIT_MOD_RUNE: return POWER_RUNE;
11759 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
11760 default: return POWER_MANA;
11763 return POWER_MANA;
11766 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
11768 if (attType == RANGED_ATTACK)
11770 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
11771 if (ap < 0)
11772 return 0.0f;
11773 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
11775 else
11777 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
11778 if (ap < 0)
11779 return 0.0f;
11780 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
11784 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
11786 if (attType == OFF_ATTACK && !haveOffhandWeapon())
11787 return 0.0f;
11789 return m_weaponDamage[attType][type];
11792 void Unit::SetLevel(uint32 lvl)
11794 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
11796 // group update
11797 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
11798 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
11801 void Unit::SetHealth(uint32 val)
11803 uint32 maxHealth = GetMaxHealth();
11804 if(maxHealth < val)
11805 val = maxHealth;
11807 SetUInt32Value(UNIT_FIELD_HEALTH, val);
11809 // group update
11810 if(GetTypeId() == TYPEID_PLAYER)
11812 if(((Player*)this)->GetGroup())
11813 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
11815 else if(((Creature*)this)->isPet())
11817 Pet *pet = ((Pet*)this);
11818 if(pet->isControlled())
11820 Unit *owner = GetOwner();
11821 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11822 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
11827 void Unit::SetMaxHealth(uint32 val)
11829 uint32 health = GetHealth();
11830 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
11832 // group update
11833 if(GetTypeId() == TYPEID_PLAYER)
11835 if(((Player*)this)->GetGroup())
11836 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
11838 else if(((Creature*)this)->isPet())
11840 Pet *pet = ((Pet*)this);
11841 if(pet->isControlled())
11843 Unit *owner = GetOwner();
11844 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11845 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
11849 if(val < health)
11850 SetHealth(val);
11853 void Unit::SetHealthPercent(float percent)
11855 uint32 newHealth = GetMaxHealth() * percent/100.0f;
11856 SetHealth(newHealth);
11859 void Unit::SetPower(Powers power, uint32 val)
11861 if(GetPower(power) == val)
11862 return;
11864 uint32 maxPower = GetMaxPower(power);
11865 if(maxPower < val)
11866 val = maxPower;
11868 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
11870 WorldPacket data(SMSG_POWER_UPDATE);
11871 data << GetPackGUID();
11872 data << uint8(power);
11873 data << uint32(val);
11874 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
11876 // group update
11877 if(GetTypeId() == TYPEID_PLAYER)
11879 if(((Player*)this)->GetGroup())
11880 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11882 else if(((Creature*)this)->isPet())
11884 Pet *pet = ((Pet*)this);
11885 if(pet->isControlled())
11887 Unit *owner = GetOwner();
11888 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11889 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11892 // Update the pet's character sheet with happiness damage bonus
11893 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
11895 pet->UpdateDamagePhysical(BASE_ATTACK);
11900 void Unit::SetMaxPower(Powers power, uint32 val)
11902 uint32 cur_power = GetPower(power);
11903 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
11905 // group update
11906 if(GetTypeId() == TYPEID_PLAYER)
11908 if(((Player*)this)->GetGroup())
11909 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11911 else if(((Creature*)this)->isPet())
11913 Pet *pet = ((Pet*)this);
11914 if(pet->isControlled())
11916 Unit *owner = GetOwner();
11917 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11918 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11922 if(val < cur_power)
11923 SetPower(power, val);
11926 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
11928 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
11930 // group update
11931 if(GetTypeId() == TYPEID_PLAYER)
11933 if(((Player*)this)->GetGroup())
11934 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
11936 else if(((Creature*)this)->isPet())
11938 Pet *pet = ((Pet*)this);
11939 if(pet->isControlled())
11941 Unit *owner = GetOwner();
11942 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11943 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
11948 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
11950 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
11952 // group update
11953 if(GetTypeId() == TYPEID_PLAYER)
11955 if(((Player*)this)->GetGroup())
11956 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
11958 else if(((Creature*)this)->isPet())
11960 Pet *pet = ((Pet*)this);
11961 if(pet->isControlled())
11963 Unit *owner = GetOwner();
11964 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11965 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
11970 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
11972 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
11973 if(apply)
11974 tAuraProcTriggerDamage.push_back(aura);
11975 else
11976 tAuraProcTriggerDamage.remove(aura);
11979 uint32 Unit::GetCreatePowers( Powers power ) const
11981 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
11982 switch(power)
11984 case POWER_HEALTH: return 0;
11985 case POWER_MANA: return GetCreateMana();
11986 case POWER_RAGE: return 1000;
11987 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
11988 case POWER_ENERGY: return 100;
11989 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
11990 case POWER_RUNIC_POWER: return 1000;
11991 case POWER_RUNE: return 0;
11994 return 0;
11997 void Unit::AddToWorld()
11999 Object::AddToWorld();
12002 void Unit::RemoveFromWorld()
12004 // cleanup
12005 if (IsInWorld())
12007 Uncharm();
12008 RemoveNotOwnSingleTargetAuras();
12009 RemoveGuardians();
12010 RemoveAllGameObjects();
12011 RemoveAllDynObjects();
12012 CleanupDeletedAuras();
12015 Object::RemoveFromWorld();
12018 void Unit::CleanupsBeforeDelete()
12020 if(m_uint32Values) // only for fully created object
12022 InterruptNonMeleeSpells(true);
12023 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
12024 CombatStop();
12025 ClearComboPointHolders();
12026 DeleteThreatList();
12027 if (GetTypeId()==TYPEID_PLAYER)
12028 getHostileRefManager().setOnlineOfflineState(false);
12029 else
12030 getHostileRefManager().deleteReferences();
12031 RemoveAllAuras(AURA_REMOVE_BY_DELETE);
12032 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
12034 WorldObject::CleanupsBeforeDelete();
12037 CharmInfo* Unit::InitCharmInfo(Unit *charm)
12039 if(!m_charmInfo)
12040 m_charmInfo = new CharmInfo(charm);
12041 return m_charmInfo;
12044 CharmInfo::CharmInfo(Unit* unit)
12045 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
12047 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
12048 m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
12051 void CharmInfo::InitPetActionBar()
12053 // the first 3 SpellOrActions are attack, follow and stay
12054 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
12055 SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
12057 // middle 4 SpellOrActions are spells/special attacks/abilities
12058 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
12059 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_DISABLED);
12061 // last 3 SpellOrActions are reactions
12062 for(uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
12063 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
12066 void CharmInfo::InitEmptyActionBar()
12068 SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
12069 for(uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
12070 SetActionBar(x,0,ACT_PASSIVE);
12073 void CharmInfo::InitPossessCreateSpells()
12075 InitEmptyActionBar(); //charm action bar
12077 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
12078 return;
12080 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
12082 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
12083 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
12084 else
12085 AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
12089 void CharmInfo::InitCharmCreateSpells()
12091 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
12093 InitEmptyActionBar();
12094 return;
12097 InitPetActionBar();
12099 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
12101 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
12103 if(!spellId)
12105 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
12106 continue;
12109 if (IsPassiveSpell(spellId))
12111 m_unit->CastSpell(m_unit, spellId, true);
12112 m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
12114 else
12116 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
12118 ActiveStates newstate;
12119 bool onlyselfcast = true;
12120 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
12122 if(!spellInfo) onlyselfcast = false;
12123 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
12125 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
12126 onlyselfcast = false;
12129 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
12130 newstate = ACT_DISABLED;
12131 else
12132 newstate = ACT_PASSIVE;
12134 AddSpellToActionBar(spellId, newstate);
12139 bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
12141 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
12143 // new spell rank can be already listed
12144 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12146 if (uint32 action = PetActionBar[i].GetAction())
12148 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
12150 PetActionBar[i].SetAction(spell_id);
12151 return true;
12156 // or use empty slot in other case
12157 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12159 if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
12161 SetActionBar(i,spell_id,newstate == ACT_DECIDE ? ACT_DISABLED : newstate);
12162 return true;
12165 return false;
12168 bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
12170 uint32 first_id = sSpellMgr.GetFirstSpellInChain(spell_id);
12172 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12174 if (uint32 action = PetActionBar[i].GetAction())
12176 if (PetActionBar[i].IsActionBarForSpell() && sSpellMgr.GetFirstSpellInChain(action) == first_id)
12178 SetActionBar(i,0,ACT_DISABLED);
12179 return true;
12184 return false;
12187 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
12189 if(IsPassiveSpell(spellid))
12190 return;
12192 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
12193 if(spellid == m_charmspells[x].GetAction())
12194 m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
12197 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
12199 m_petnumber = petnumber;
12200 if(statwindow)
12201 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
12202 else
12203 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
12206 void CharmInfo::LoadPetActionBar(const std::string& data )
12208 InitPetActionBar();
12210 Tokens tokens = StrSplit(data, " ");
12212 if (tokens.size() != (ACTION_BAR_INDEX_END-ACTION_BAR_INDEX_START)*2)
12213 return; // non critical, will reset to default
12215 int index;
12216 Tokens::iterator iter;
12217 for(iter = tokens.begin(), index = ACTION_BAR_INDEX_START; index < ACTION_BAR_INDEX_END; ++iter, ++index )
12219 // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
12220 uint8 type = (uint8)atol((*iter).c_str());
12221 ++iter;
12222 uint32 action = atol((*iter).c_str());
12224 PetActionBar[index].SetActionAndType(action,ActiveStates(type));
12226 // check correctness
12227 if(PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
12228 SetActionBar(index,0,ACT_DISABLED);
12232 void CharmInfo::BuildActionBar( WorldPacket* data )
12234 for(uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12235 *data << uint32(PetActionBar[i].packedData);
12238 void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
12240 for(int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
12242 if(spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
12244 PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
12245 break;
12250 bool Unit::isFrozen() const
12252 return HasAuraState(AURA_STATE_FROZEN);
12255 struct ProcTriggeredData
12257 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
12258 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
12259 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
12261 SpellProcEventEntry const *spellProcEvent;
12262 Aura* triggeredByAura;
12263 Unit::spellEffectPair triggeredByAura_SpellPair;
12266 typedef std::list< ProcTriggeredData > ProcTriggeredList;
12267 typedef std::list< uint32> RemoveSpellList;
12269 // List of auras that CAN be trigger but may not exist in spell_proc_event
12270 // in most case need for drop charges
12271 // in some types of aura need do additional check
12272 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
12273 bool InitTriggerAuraData()
12275 for (int i=0;i<TOTAL_AURAS;++i)
12277 isTriggerAura[i]=false;
12278 isNonTriggerAura[i] = false;
12280 isTriggerAura[SPELL_AURA_DUMMY] = true;
12281 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
12282 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
12283 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
12284 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
12285 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
12286 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
12287 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
12288 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
12289 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
12290 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
12291 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
12292 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
12293 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
12294 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
12295 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
12296 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
12297 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
12298 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
12299 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
12300 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
12301 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
12302 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
12303 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
12304 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
12305 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
12306 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
12307 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
12308 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
12309 isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
12310 isTriggerAura[SPELL_AURA_MAELSTROM_WEAPON] = true;
12312 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
12313 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
12315 return true;
12318 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
12320 uint32 procEx = PROC_EX_NONE;
12321 // Check victim state
12322 if (missCondition!=SPELL_MISS_NONE)
12323 switch (missCondition)
12325 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
12326 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
12327 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
12328 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
12329 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
12330 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
12331 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
12332 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
12333 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
12334 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
12335 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
12336 default:
12337 break;
12339 else
12341 // On block
12342 if (damageInfo->blocked)
12343 procEx|=PROC_EX_BLOCK;
12344 // On absorb
12345 if (damageInfo->absorb)
12346 procEx|=PROC_EX_ABSORB;
12347 // On crit
12348 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
12349 procEx|=PROC_EX_CRITICAL_HIT;
12350 else
12351 procEx|=PROC_EX_NORMAL_HIT;
12353 return procEx;
12356 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
12358 // For melee/ranged based attack need update skills and set some Aura states
12359 if (procFlag & MELEE_BASED_TRIGGER_MASK)
12361 // Update skills here for players
12362 if (GetTypeId() == TYPEID_PLAYER)
12364 // On melee based hit/miss/resist need update skill (for victim and attacker)
12365 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
12367 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
12368 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
12370 // Update defence if player is victim and parry/dodge/block
12371 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
12372 ((Player*)this)->UpdateDefense();
12374 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
12375 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
12377 // for victim
12378 if (isVictim)
12380 // if victim and dodge attack
12381 if (procExtra&PROC_EX_DODGE)
12383 //Update AURA_STATE on dodge
12384 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
12386 ModifyAuraState(AURA_STATE_DEFENSE, true);
12387 StartReactiveTimer( REACTIVE_DEFENSE );
12390 // if victim and parry attack
12391 if (procExtra & PROC_EX_PARRY)
12393 // For Hunters only Counterattack (skip Mongoose bite)
12394 if (getClass() == CLASS_HUNTER)
12396 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
12397 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
12399 else
12401 ModifyAuraState(AURA_STATE_DEFENSE, true);
12402 StartReactiveTimer( REACTIVE_DEFENSE );
12405 // if and victim block attack
12406 if (procExtra & PROC_EX_BLOCK)
12408 ModifyAuraState(AURA_STATE_DEFENSE,true);
12409 StartReactiveTimer( REACTIVE_DEFENSE );
12412 else //For attacker
12414 // Overpower on victim dodge
12415 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
12417 ((Player*)this)->AddComboPoints(pTarget, 1);
12418 StartReactiveTimer( REACTIVE_OVERPOWER );
12424 RemoveSpellList removedSpells;
12425 ProcTriggeredList procTriggered;
12426 // Fill procTriggered list
12427 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
12429 // skip deleted auras (possible at recursive triggered call
12430 if(itr->second->IsDeleted())
12431 continue;
12433 SpellProcEventEntry const* spellProcEvent = NULL;
12434 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
12435 continue;
12437 itr->second->SetInUse(true); // prevent aura deletion
12438 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
12441 // Nothing found
12442 if (procTriggered.empty())
12443 return;
12445 // Handle effects proceed this time
12446 for(ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
12448 // Some auras can be deleted in function called in this loop (except first, ofc)
12449 Aura *triggeredByAura = i->triggeredByAura;
12450 if(triggeredByAura->IsDeleted())
12451 continue;
12453 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
12454 Modifier *auraModifier = triggeredByAura->GetModifier();
12455 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
12456 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
12457 // For players set spell cooldown if need
12458 uint32 cooldown = 0;
12459 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
12460 cooldown = spellProcEvent->cooldown;
12462 switch(auraModifier->m_auraname)
12464 case SPELL_AURA_PROC_TRIGGER_SPELL:
12466 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12467 // Don`t drop charge or add cooldown for not started trigger
12468 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12470 triggeredByAura->SetInUse(false);
12471 continue;
12473 break;
12475 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
12477 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "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());
12478 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
12479 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
12480 damageInfo.target->CalculateAbsorbResistBlock(this, &damageInfo, spellInfo);
12481 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
12482 SendSpellNonMeleeDamageLog(&damageInfo);
12483 DealSpellDamage(&damageInfo, true);
12484 break;
12486 case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
12487 case SPELL_AURA_MANA_SHIELD:
12488 case SPELL_AURA_OBS_MOD_MANA:
12489 case SPELL_AURA_ADD_PCT_MODIFIER:
12490 case SPELL_AURA_DUMMY:
12492 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12493 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12495 triggeredByAura->SetInUse(false);
12496 continue;
12498 break;
12500 case SPELL_AURA_MOD_HASTE:
12502 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12503 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12505 triggeredByAura->SetInUse(false);
12506 continue;
12508 break;
12510 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
12512 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12513 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
12515 triggeredByAura->SetInUse(false);
12516 continue;
12518 break;
12520 case SPELL_AURA_PRAYER_OF_MENDING:
12522 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
12523 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
12525 HandleMendingAuraProc(triggeredByAura);
12526 break;
12528 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
12530 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12532 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12534 triggeredByAura->SetInUse(false);
12535 continue;
12537 break;
12539 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
12540 // Skip melee hits or instant cast spells
12541 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
12543 triggeredByAura->SetInUse(false);
12544 continue;
12546 break;
12547 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
12548 // Skip Melee hits and spells ws wrong school
12549 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
12551 triggeredByAura->SetInUse(false);
12552 continue;
12554 break;
12555 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
12556 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
12557 // Skip melee hits and spells ws wrong school or zero cost
12558 if (procSpell == NULL ||
12559 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
12560 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
12562 triggeredByAura->SetInUse(false);
12563 continue;
12565 break;
12566 case SPELL_AURA_MECHANIC_IMMUNITY:
12567 // Compare mechanic
12568 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
12570 triggeredByAura->SetInUse(false);
12571 continue;
12573 break;
12574 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
12575 // Compare mechanic
12576 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
12578 triggeredByAura->SetInUse(false);
12579 continue;
12581 break;
12582 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
12583 // Compare casters
12584 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
12586 triggeredByAura->SetInUse(false);
12587 continue;
12589 break;
12590 case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
12591 if (!procSpell)
12593 triggeredByAura->SetInUse(false);
12594 continue;
12596 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "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());
12597 if (!HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
12599 triggeredByAura->SetInUse(false);
12600 continue;
12602 break;
12603 case SPELL_AURA_MAELSTROM_WEAPON:
12604 DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: casting spell id %u (triggered by %s maelstrom aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
12606 // remove all stack;
12607 RemoveSpellsCausingAura(SPELL_AURA_MAELSTROM_WEAPON);
12608 triggeredByAura->SetInUse(false); // this safe, aura locked
12609 continue; // avoid re-remove attempts
12610 default:
12611 // nothing do, just charges counter
12612 break;
12615 // Remove charge (aura can be removed by triggers)
12616 if(useCharges && !triggeredByAura->IsDeleted())
12618 // If last charge dropped add spell to remove list
12619 if(triggeredByAura->DropAuraCharge())
12620 removedSpells.push_back(triggeredByAura->GetId());
12623 triggeredByAura->SetInUse(false);
12625 if (!removedSpells.empty())
12627 // Sort spells and remove dublicates
12628 removedSpells.sort();
12629 removedSpells.unique();
12630 // Remove auras from removedAuras
12631 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();++i)
12632 RemoveSingleSpellAurasFromStack(*i);
12636 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
12638 return SPELL_SCHOOL_MASK_NORMAL;
12641 Player* Unit::GetSpellModOwner()
12643 if(GetTypeId()==TYPEID_PLAYER)
12644 return (Player*)this;
12645 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
12647 Unit* owner = GetOwner();
12648 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
12649 return (Player*)owner;
12651 return NULL;
12654 ///----------Pet responses methods-----------------
12655 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
12657 if(msg == SPELL_CAST_OK)
12658 return;
12660 Unit *owner = GetCharmerOrOwner();
12661 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12662 return;
12664 WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
12665 data << uint8(0); // cast count?
12666 data << uint32(spellid);
12667 data << uint8(msg);
12668 // uint32 for some reason
12669 // uint32 for some reason
12670 ((Player*)owner)->GetSession()->SendPacket(&data);
12673 void Unit::SendPetActionFeedback (uint8 msg)
12675 Unit* owner = GetOwner();
12676 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12677 return;
12679 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
12680 data << uint8(msg);
12681 ((Player*)owner)->GetSession()->SendPacket(&data);
12684 void Unit::SendPetTalk (uint32 pettalk)
12686 Unit* owner = GetOwner();
12687 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12688 return;
12690 WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
12691 data << uint64(GetGUID());
12692 data << uint32(pettalk);
12693 ((Player*)owner)->GetSession()->SendPacket(&data);
12696 void Unit::SendPetAIReaction(uint64 guid)
12698 Unit* owner = GetOwner();
12699 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
12700 return;
12702 WorldPacket data(SMSG_AI_REACTION, 8 + 4);
12703 data << uint64(guid);
12704 data << uint32(AI_REACTION_HOSTILE);
12705 ((Player*)owner)->GetSession()->SendPacket(&data);
12708 ///----------End of Pet responses methods----------
12710 void Unit::StopMoving()
12712 clearUnitState(UNIT_STAT_MOVING);
12714 // send explicit stop packet
12715 // player expected for correct work SPLINEFLAG_WALKMODE
12716 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), SPLINETYPE_NORMAL, GetTypeId() == TYPEID_PLAYER ? SPLINEFLAG_WALKMODE : SPLINEFLAG_NONE, 0);
12718 // update position and orientation for near players
12719 WorldPacket data;
12720 BuildHeartBeatMsg(&data);
12721 SendMessageToSet(&data, false);
12724 void Unit::SetFeared(bool apply, uint64 const& casterGUID, uint32 spellID, uint32 time)
12726 if( apply )
12728 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
12729 return;
12731 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
12733 GetMotionMaster()->MovementExpired(false);
12734 CastStop(GetGUID() == casterGUID ? spellID : 0);
12736 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
12738 GetMotionMaster()->MoveFleeing(caster, time); // caster==NULL processed in MoveFleeing
12740 else
12742 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
12744 GetMotionMaster()->MovementExpired(false);
12746 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
12748 // restore appropriate movement generator
12749 if(getVictim())
12750 GetMotionMaster()->MoveChase(getVictim());
12751 else
12752 GetMotionMaster()->Initialize();
12754 // attack caster if can
12755 Unit* caster = Unit::GetUnit(*this, casterGUID);
12756 if(caster && ((Creature*)this)->AI())
12757 ((Creature*)this)->AI()->AttackedBy(caster);
12761 if (GetTypeId() == TYPEID_PLAYER)
12762 ((Player*)this)->SetClientControl(this, !apply);
12765 void Unit::SetConfused(bool apply, uint64 const& casterGUID, uint32 spellID)
12767 if( apply )
12769 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
12771 CastStop(GetGUID()==casterGUID ? spellID : 0);
12773 GetMotionMaster()->MoveConfused();
12775 else
12777 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
12779 GetMotionMaster()->MovementExpired(false);
12781 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12783 // restore appropriate movement generator
12784 if(getVictim())
12785 GetMotionMaster()->MoveChase(getVictim());
12786 else
12787 GetMotionMaster()->Initialize();
12791 if(GetTypeId() == TYPEID_PLAYER)
12792 ((Player*)this)->SetClientControl(this, !apply);
12795 void Unit::SetFeignDeath(bool apply, uint64 const& casterGUID, uint32 /*spellID*/)
12797 if( apply )
12800 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12801 data<<GetGUID();
12802 data<<uint8(0);
12803 SendMessageToSet(&data,true);
12806 if(GetTypeId() != TYPEID_PLAYER)
12807 StopMoving();
12808 else
12809 ((Player*)this)->m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
12811 // blizz like 2.0.x
12812 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12813 // blizz like 2.0.x
12814 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12815 // blizz like 2.0.x
12816 SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12818 addUnitState(UNIT_STAT_DIED);
12819 CombatStop();
12820 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_IMMUNE_OR_LOST_SELECTION);
12822 // prevent interrupt message
12823 if (casterGUID == GetGUID())
12824 FinishSpell(CURRENT_GENERIC_SPELL,false);
12825 InterruptNonMeleeSpells(true);
12826 getHostileRefManager().deleteReferences();
12828 else
12831 WorldPacket data(SMSG_FEIGN_DEATH_RESISTED, 9);
12832 data<<GetGUID();
12833 data<<uint8(1);
12834 SendMessageToSet(&data,true);
12836 // blizz like 2.0.x
12837 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_29);
12838 // blizz like 2.0.x
12839 RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH);
12840 // blizz like 2.0.x
12841 RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD);
12843 clearUnitState(UNIT_STAT_DIED);
12845 if (GetTypeId() != TYPEID_PLAYER && isAlive())
12847 // restore appropriate movement generator
12848 if(getVictim())
12849 GetMotionMaster()->MoveChase(getVictim());
12850 else
12851 GetMotionMaster()->Initialize();
12857 bool Unit::IsSitState() const
12859 uint8 s = getStandState();
12860 return
12861 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
12862 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
12863 s == UNIT_STAND_STATE_SIT;
12866 bool Unit::IsStandState() const
12868 uint8 s = getStandState();
12869 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
12872 void Unit::SetStandState(uint8 state)
12874 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
12876 if (IsStandState())
12877 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
12879 if(GetTypeId()==TYPEID_PLAYER)
12881 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
12882 data << (uint8)state;
12883 ((Player*)this)->GetSession()->SendPacket(&data);
12887 bool Unit::IsPolymorphed() const
12889 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
12892 void Unit::SetDisplayId(uint32 modelId)
12894 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
12896 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
12898 Pet *pet = ((Pet*)this);
12899 if(!pet->isControlled())
12900 return;
12901 Unit *owner = GetOwner();
12902 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
12903 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
12907 void Unit::ClearComboPointHolders()
12909 while(!m_ComboPointHolders.empty())
12911 uint32 lowguid = *m_ComboPointHolders.begin();
12913 Player* plr = sObjectMgr.GetPlayer(ObjectGuid(HIGHGUID_PLAYER, lowguid));
12914 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
12915 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
12916 else
12917 m_ComboPointHolders.erase(lowguid); // or remove manually
12921 void Unit::ClearAllReactives()
12923 for(int i=0; i < MAX_REACTIVE; ++i)
12924 m_reactiveTimer[i] = 0;
12926 if (HasAuraState( AURA_STATE_DEFENSE))
12927 ModifyAuraState(AURA_STATE_DEFENSE, false);
12928 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
12929 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12930 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12931 ((Player*)this)->ClearComboPoints();
12934 void Unit::UpdateReactives( uint32 p_time )
12936 for(int i = 0; i < MAX_REACTIVE; ++i)
12938 ReactiveType reactive = ReactiveType(i);
12940 if(!m_reactiveTimer[reactive])
12941 continue;
12943 if ( m_reactiveTimer[reactive] <= p_time)
12945 m_reactiveTimer[reactive] = 0;
12947 switch ( reactive )
12949 case REACTIVE_DEFENSE:
12950 if (HasAuraState(AURA_STATE_DEFENSE))
12951 ModifyAuraState(AURA_STATE_DEFENSE, false);
12952 break;
12953 case REACTIVE_HUNTER_PARRY:
12954 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
12955 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
12956 break;
12957 case REACTIVE_OVERPOWER:
12958 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
12959 ((Player*)this)->ClearComboPoints();
12960 break;
12961 default:
12962 break;
12965 else
12967 m_reactiveTimer[reactive] -= p_time;
12972 Unit* Unit::SelectRandomUnfriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const
12974 std::list<Unit *> targets;
12976 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, radius);
12977 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
12978 Cell::VisitAllObjects(this, searcher, radius);
12980 // remove current target
12981 if(except)
12982 targets.remove(except);
12984 // remove not LoS targets
12985 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
12987 if(!IsWithinLOSInMap(*tIter))
12989 std::list<Unit *>::iterator tIter2 = tIter;
12990 ++tIter;
12991 targets.erase(tIter2);
12993 else
12994 ++tIter;
12997 // no appropriate targets
12998 if(targets.empty())
12999 return NULL;
13001 // select random
13002 uint32 rIdx = urand(0,targets.size()-1);
13003 std::list<Unit *>::const_iterator tcIter = targets.begin();
13004 for(uint32 i = 0; i < rIdx; ++i)
13005 ++tcIter;
13007 return *tcIter;
13010 Unit* Unit::SelectRandomFriendlyTarget(Unit* except /*= NULL*/, float radius /*= ATTACK_DISTANCE*/) const
13012 std::list<Unit *> targets;
13014 MaNGOS::AnyFriendlyUnitInObjectRangeCheck u_check(this, radius);
13015 MaNGOS::UnitListSearcher<MaNGOS::AnyFriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
13017 Cell::VisitAllObjects(this, searcher, radius);
13018 // remove current target
13019 if(except)
13020 targets.remove(except);
13022 // remove not LoS targets
13023 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
13025 if(!IsWithinLOSInMap(*tIter))
13027 std::list<Unit *>::iterator tIter2 = tIter;
13028 ++tIter;
13029 targets.erase(tIter2);
13031 else
13032 ++tIter;
13035 // no appropriate targets
13036 if(targets.empty())
13037 return NULL;
13039 // select random
13040 uint32 rIdx = urand(0,targets.size()-1);
13041 std::list<Unit *>::const_iterator tcIter = targets.begin();
13042 for(uint32 i = 0; i < rIdx; ++i)
13043 ++tcIter;
13045 return *tcIter;
13048 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
13050 for (AuraMap::const_iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
13052 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
13053 return true;
13055 return false;
13058 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
13060 if(val > 0)
13062 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
13063 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
13065 else
13067 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
13068 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
13072 void Unit::ApplyCastTimePercentMod(float val, bool apply )
13074 if(val > 0)
13075 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
13076 else
13077 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
13080 void Unit::UpdateAuraForGroup(uint8 slot)
13082 if(GetTypeId() == TYPEID_PLAYER)
13084 Player* player = (Player*)this;
13085 if(player->GetGroup())
13087 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
13088 player->SetAuraUpdateMask(slot);
13091 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
13093 Pet *pet = ((Pet*)this);
13094 if(pet->isControlled())
13096 Unit *owner = GetOwner();
13097 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
13099 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
13100 pet->SetAuraUpdateMask(slot);
13106 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
13108 if (!normalized || GetTypeId() != TYPEID_PLAYER)
13109 return float(GetAttackTime(attType))/1000.0f;
13111 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType, true, false);
13112 if (!Weapon)
13113 return 2.4f; // fist attack
13115 switch (Weapon->GetProto()->InventoryType)
13117 case INVTYPE_2HWEAPON:
13118 return 3.3f;
13119 case INVTYPE_RANGED:
13120 case INVTYPE_RANGEDRIGHT:
13121 case INVTYPE_THROWN:
13122 return 2.8f;
13123 case INVTYPE_WEAPON:
13124 case INVTYPE_WEAPONMAINHAND:
13125 case INVTYPE_WEAPONOFFHAND:
13126 default:
13127 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7f : 2.4f;
13131 Aura* Unit::GetDummyAura( uint32 spell_id ) const
13133 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
13134 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
13135 if ((*itr)->GetId() == spell_id)
13136 return *itr;
13138 return NULL;
13141 void Unit::SetContestedPvP(Player *attackedPlayer)
13143 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
13145 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
13146 return;
13148 player->SetContestedPvPTimer(30000);
13149 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
13151 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
13152 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
13153 // call MoveInLineOfSight for nearby contested guards
13154 SetVisibility(GetVisibility());
13156 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
13158 addUnitState(UNIT_STAT_ATTACK_PLAYER);
13159 // call MoveInLineOfSight for nearby contested guards
13160 SetVisibility(GetVisibility());
13164 void Unit::AddPetAura(PetAura const* petSpell)
13166 m_petAuras.insert(petSpell);
13167 if(Pet* pet = GetPet())
13168 pet->CastPetAura(petSpell);
13171 void Unit::RemovePetAura(PetAura const* petSpell)
13173 m_petAuras.erase(petSpell);
13174 if(Pet* pet = GetPet())
13175 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
13178 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
13180 Pet* pet = new Pet(HUNTER_PET);
13182 if(!pet->CreateBaseAtCreature(creatureTarget))
13184 delete pet;
13185 return NULL;
13188 pet->SetOwnerGUID(GetGUID());
13189 pet->SetCreatorGUID(GetGUID());
13190 pet->setFaction(getFaction());
13191 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
13193 if(GetTypeId()==TYPEID_PLAYER)
13194 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
13196 if(IsPvP())
13197 pet->SetPvP(true);
13199 if(IsFFAPvP())
13200 pet->SetFFAPvP(true);
13202 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
13204 if(!pet->InitStatsForLevel(level))
13206 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
13207 delete pet;
13208 return NULL;
13211 pet->GetCharmInfo()->SetPetNumber(sObjectMgr.GeneratePetNumber(), true);
13212 // this enables pet details window (Shift+P)
13213 pet->AIM_Initialize();
13214 pet->InitPetCreateSpells();
13215 pet->InitLevelupSpellsForLevel();
13216 pet->InitTalentForLevel();
13217 pet->SetHealth(pet->GetMaxHealth());
13219 return pet;
13222 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
13224 SpellEntry const* spellProto = aura->GetSpellProto ();
13226 // Get proc Event Entry
13227 spellProcEvent = sSpellMgr.GetSpellProcEvent(spellProto->Id);
13229 // Aura info stored here
13230 Modifier *mod = aura->GetModifier();
13231 // Skip this auras
13232 if (isNonTriggerAura[mod->m_auraname])
13233 return false;
13234 // If not trigger by default and spellProcEvent==NULL - skip
13235 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
13236 return false;
13238 // Get EventProcFlag
13239 uint32 EventProcFlag;
13240 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
13241 EventProcFlag = spellProcEvent->procFlags;
13242 else
13243 EventProcFlag = spellProto->procFlags; // else get from spell proto
13244 // Continue if no trigger exist
13245 if (!EventProcFlag)
13246 return false;
13248 // Check spellProcEvent data requirements
13249 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
13250 return false;
13252 // In most cases req get honor or XP from kill
13253 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
13255 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
13256 // Shadow Word: Death - can trigger from every kill
13257 if (aura->GetId() == 32409)
13258 allow = true;
13259 if (!allow)
13260 return false;
13262 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
13263 // But except periodic triggers (can triggered from self)
13264 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags & PROC_FLAG_ON_TAKE_PERIODIC))
13265 return false;
13267 // Check if current equipment allows aura to proc
13268 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
13270 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
13272 Item *item = NULL;
13273 if(attType == BASE_ATTACK)
13274 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
13275 else if (attType == OFF_ATTACK)
13276 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
13277 else
13278 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
13280 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
13281 return false;
13283 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
13285 // Check if player is wearing shield
13286 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
13287 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
13288 return false;
13291 // Get chance from spell
13292 float chance = (float)spellProto->procChance;
13293 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
13294 if(spellProcEvent && spellProcEvent->customChance)
13295 chance = spellProcEvent->customChance;
13296 // If PPM exist calculate chance from PPM
13297 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
13299 uint32 WeaponSpeed = GetAttackTime(attType);
13300 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
13302 // Apply chance modifer aura
13303 if(Player* modOwner = GetSpellModOwner())
13305 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
13306 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
13309 return roll_chance_f(chance);
13312 bool Unit::HandleMendingAuraProc( Aura* triggeredByAura )
13314 // aura can be deleted at casts
13315 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
13316 SpellEffectIndex effIdx = triggeredByAura->GetEffIndex();
13317 int32 heal = triggeredByAura->GetModifier()->m_amount;
13318 uint64 caster_guid = triggeredByAura->GetCasterGUID();
13320 // jumps
13321 int32 jumps = triggeredByAura->GetAuraCharges()-1;
13323 // current aura expire
13324 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
13326 // next target selection
13327 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
13329 float radius;
13330 if (spellProto->EffectRadiusIndex[effIdx])
13331 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
13332 else
13333 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
13335 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
13337 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
13339 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
13341 // aura will applied from caster, but spell casted from current aura holder
13342 SpellModifier *mod = new SpellModifier(SPELLMOD_CHARGES,SPELLMOD_FLAT,jumps-5,spellProto->Id,spellProto->SpellFamilyFlags,spellProto->SpellFamilyFlags2);
13344 // remove before apply next (locked against deleted)
13345 triggeredByAura->SetInUse(true);
13346 RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID());
13348 caster->AddSpellMod(mod, true);
13349 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
13350 caster->AddSpellMod(mod, false);
13351 triggeredByAura->SetInUse(false);
13356 // heal
13357 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
13358 return true;
13361 void Unit::RemoveAurasAtMechanicImmunity(uint32 mechMask, uint32 exceptSpellId, bool non_positive /*= false*/)
13363 Unit::AuraMap& auras = GetAuras();
13364 for(Unit::AuraMap::iterator iter = auras.begin(); iter != auras.end();)
13366 SpellEntry const *spell = iter->second->GetSpellProto();
13367 if (spell->Id == exceptSpellId)
13368 ++iter;
13369 else if (non_positive && iter->second->IsPositive())
13370 ++iter;
13371 else if (spell->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY)
13372 ++iter;
13373 else if (GetSpellMechanicMask(spell, iter->second->GetEffIndex()) & mechMask)
13375 RemoveAurasDueToSpell(spell->Id);
13376 if(auras.empty())
13377 break;
13378 else
13379 iter = auras.begin();
13381 else
13382 ++iter;
13386 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
13388 if(newPhaseMask==GetPhaseMask())
13389 return;
13391 if(IsInWorld())
13392 RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
13394 WorldObject::SetPhaseMask(newPhaseMask,update);
13396 if(IsInWorld())
13397 if(Pet* pet = GetPet())
13398 pet->SetPhaseMask(newPhaseMask,true);
13401 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
13403 if(GetTypeId() == TYPEID_PLAYER)
13404 ((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));
13405 else
13407 Creature* c = (Creature*)this;
13408 // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly
13409 if (!c->GetMotionMaster()->empty())
13410 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13411 movgen->Interrupt(*c);
13413 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
13415 WorldPacket data;
13416 BuildHeartBeatMsg(&data);
13417 SendMessageToSet(&data, false);
13418 // finished relocation, movegen can different from top before creature relocation,
13419 // but apply Reset expected to be safe in any case
13420 if (!c->GetMotionMaster()->empty())
13421 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13422 movgen->Reset(*c);
13426 void Unit::MonsterMove(float x, float y, float z, uint32 transitTime)
13428 SplineFlags flags = GetTypeId() == TYPEID_PLAYER ? SPLINEFLAG_WALKMODE : ((Creature*)this)->GetSplineFlags();
13429 SendMonsterMove(x, y, z, SPLINETYPE_NORMAL, flags, transitTime);
13431 if (GetTypeId() != TYPEID_PLAYER)
13433 Creature* c = (Creature*)this;
13434 // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly
13435 if (!c->GetMotionMaster()->empty())
13436 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13437 movgen->Interrupt(*c);
13439 GetMap()->CreatureRelocation((Creature*)this, x, y, z, 0.0f);
13441 // finished relocation, movegen can different from top before creature relocation,
13442 // but apply Reset expected to be safe in any case
13443 if (!c->GetMotionMaster()->empty())
13444 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13445 movgen->Reset(*c);
13449 void Unit::MonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime)
13451 SendMonsterMoveWithSpeed(x, y, z, transitTime );
13453 if (GetTypeId() != TYPEID_PLAYER)
13455 Creature* c = (Creature*)this;
13456 // Creature relocation acts like instant movement generator, so current generator expects interrupt/reset calls to react properly
13457 if (!c->GetMotionMaster()->empty())
13458 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13459 movgen->Interrupt(*c);
13461 GetMap()->CreatureRelocation((Creature*)this, x, y, z, 0.0f);
13463 // finished relocation, movegen can different from top before creature relocation,
13464 // but apply Reset expected to be safe in any case
13465 if (!c->GetMotionMaster()->empty())
13466 if (MovementGenerator *movgen = c->GetMotionMaster()->top())
13467 movgen->Reset(*c);
13471 struct SetPvPHelper
13473 explicit SetPvPHelper(bool _state) : state(_state) {}
13474 void operator()(Unit* unit) const { unit->SetPvP(state); }
13475 bool state;
13478 void Unit::SetPvP( bool state )
13480 if(state)
13481 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
13482 else
13483 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
13485 CallForAllControlledUnits(SetPvPHelper(state),true,true,true);
13488 struct SetFFAPvPHelper
13490 explicit SetFFAPvPHelper(bool _state) : state(_state) {}
13491 void operator()(Unit* unit) const { unit->SetFFAPvP(state); }
13492 bool state;
13495 void Unit::SetFFAPvP( bool state )
13497 if(state)
13498 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
13499 else
13500 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP);
13502 CallForAllControlledUnits(SetFFAPvPHelper(state),true,true,true);
13505 void Unit::KnockBackFrom(Unit* target, float horizontalSpeed, float verticalSpeed)
13507 float angle = this == target ? GetOrientation() + M_PI_F : target->GetAngle(this);
13508 float vsin = sin(angle);
13509 float vcos = cos(angle);
13511 // Effect propertly implemented only for players
13512 if(GetTypeId()==TYPEID_PLAYER)
13514 WorldPacket data(SMSG_MOVE_KNOCK_BACK, 8+4+4+4+4+4);
13515 data << GetPackGUID();
13516 data << uint32(0); // Sequence
13517 data << float(vcos); // x direction
13518 data << float(vsin); // y direction
13519 data << float(horizontalSpeed); // Horizontal speed
13520 data << float(-verticalSpeed); // Z Movement speed (vertical)
13521 ((Player*)this)->GetSession()->SendPacket(&data);
13523 else
13525 float dis = horizontalSpeed;
13527 float ox, oy, oz;
13528 GetPosition(ox, oy, oz);
13530 float fx = ox + dis * vcos;
13531 float fy = oy + dis * vsin;
13532 float fz = oz;
13534 float fx2, fy2, fz2; // getObjectHitPos overwrite last args in any result case
13535 if(VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), ox,oy,oz+0.5f, fx,fy,oz+0.5f,fx2,fy2,fz2, -0.5f))
13537 fx = fx2;
13538 fy = fy2;
13539 fz = fz2;
13542 UpdateGroundPositionZ(fx, fy, fz);
13544 //FIXME: this mostly hack, must exist some packet for proper creature move at client side
13545 // with CreatureRelocation at server side
13546 NearTeleportTo(fx, fy, fz, GetOrientation(), this == target);
13550 float Unit::GetCombatRatingReduction(CombatRating cr) const
13552 if (GetTypeId() == TYPEID_PLAYER)
13553 return ((Player const*)this)->GetRatingBonusValue(cr);
13554 else if (((Creature const*)this)->isPet())
13556 // Player's pet have 0.4 resilience from owner
13557 if (Unit* owner = GetOwner())
13558 if(owner->GetTypeId() == TYPEID_PLAYER)
13559 return ((Player*)owner)->GetRatingBonusValue(cr) * 0.4f;
13562 return 0.0f;
13565 uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const
13567 float percent = GetCombatRatingReduction(cr) * rate;
13568 if (percent > cap)
13569 percent = cap;
13570 return uint32 (percent * damage / 100.0f);
13573 void Unit::SendThreatUpdate()
13575 ThreatList const& tlist = getThreatManager().getThreatList();
13576 if (uint32 count = tlist.size())
13578 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Send SMSG_THREAT_UPDATE Message");
13579 WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8);
13580 data << GetPackGUID();
13581 data << uint32(count);
13582 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
13584 data.appendPackGUID((*itr)->getUnitGuid());
13585 data << uint32((*itr)->getThreat());
13587 SendMessageToSet(&data, false);
13591 void Unit::SendHighestThreatUpdate(HostileReference* pHostilReference)
13593 ThreatList const& tlist = getThreatManager().getThreatList();
13594 if (uint32 count = tlist.size())
13596 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Send SMSG_HIGHEST_THREAT_UPDATE Message");
13597 WorldPacket data(SMSG_HIGHEST_THREAT_UPDATE, 8 + 8 + count * 8);
13598 data << GetPackGUID();
13599 data.appendPackGUID(pHostilReference->getUnitGuid());
13600 data << uint32(count);
13601 for (ThreatList::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr)
13603 data.appendPackGUID((*itr)->getUnitGuid());
13604 data << uint32((*itr)->getThreat());
13606 SendMessageToSet(&data, false);
13610 void Unit::SendThreatClear()
13612 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Send SMSG_THREAT_CLEAR Message");
13613 WorldPacket data(SMSG_THREAT_CLEAR, 8);
13614 data << GetPackGUID();
13615 SendMessageToSet(&data, false);
13618 void Unit::SendThreatRemove(HostileReference* pHostileReference)
13620 DEBUG_FILTER_LOG(LOG_FILTER_COMBAT, "WORLD: Send SMSG_THREAT_REMOVE Message");
13621 WorldPacket data(SMSG_THREAT_REMOVE, 8 + 8);
13622 data << GetPackGUID();
13623 data.appendPackGUID(pHostileReference->getUnitGuid());
13624 SendMessageToSet(&data, false);
13627 struct StopAttackFactionHelper
13629 explicit StopAttackFactionHelper(uint32 _faction_id) : faction_id(_faction_id) {}
13630 void operator()(Unit* unit) const { unit->StopAttackFaction(faction_id); }
13631 uint32 faction_id;
13634 void Unit::StopAttackFaction(uint32 faction_id)
13636 if (Unit* victim = getVictim())
13638 if (victim->getFactionTemplateEntry()->faction==faction_id)
13640 AttackStop();
13641 if (IsNonMeleeSpellCasted(false))
13642 InterruptNonMeleeSpells(false);
13644 // melee and ranged forced attack cancel
13645 if (GetTypeId() == TYPEID_PLAYER)
13646 ((Player*)this)->SendAttackSwingCancelAttack();
13650 AttackerSet const& attackers = getAttackers();
13651 for(AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();)
13653 if ((*itr)->getFactionTemplateEntry()->faction==faction_id)
13655 (*itr)->AttackStop();
13656 itr = attackers.begin();
13658 else
13659 ++itr;
13662 getHostileRefManager().deleteReferencesForFaction(faction_id);
13664 CallForAllControlledUnits(StopAttackFactionHelper(faction_id),false,true,true);
13667 void Unit::CleanupDeletedAuras()
13669 // really delete auras "deleted" while processing its ApplyModify code
13670 for(AuraList::const_iterator itr = m_deletedAuras.begin(); itr != m_deletedAuras.end(); ++itr)
13671 delete *itr;
13672 m_deletedAuras.clear();
13675 bool Unit::CheckAndIncreaseCastCounter()
13677 uint32 maxCasts = sWorld.getConfig(CONFIG_UINT32_MAX_SPELL_CASTS_IN_CHAIN);
13679 if (maxCasts && m_castCounter >= maxCasts)
13680 return false;
13682 ++m_castCounter;
13683 return true;