[8497] Fixes in talent 53563 work and other area auras spells.
[getmangos.git] / src / game / Unit.cpp
blobf73262e2e800024eba97901650564a193bf62e14
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Log.h"
21 #include "Opcodes.h"
22 #include "WorldPacket.h"
23 #include "WorldSession.h"
24 #include "World.h"
25 #include "ObjectMgr.h"
26 #include "SpellMgr.h"
27 #include "Unit.h"
28 #include "QuestDef.h"
29 #include "Player.h"
30 #include "Creature.h"
31 #include "Spell.h"
32 #include "Group.h"
33 #include "SpellAuras.h"
34 #include "MapManager.h"
35 #include "ObjectAccessor.h"
36 #include "CreatureAI.h"
37 #include "Formulas.h"
38 #include "Pet.h"
39 #include "Util.h"
40 #include "Totem.h"
41 #include "BattleGround.h"
42 #include "InstanceSaveMgr.h"
43 #include "GridNotifiersImpl.h"
44 #include "CellImpl.h"
45 #include "Path.h"
46 #include "Traveller.h"
47 #include "VMapFactory.h"
49 #include <math.h>
51 float baseMoveSpeed[MAX_MOVE_TYPE] =
53 2.5f, // MOVE_WALK
54 7.0f, // MOVE_RUN
55 1.25f, // MOVE_RUN_BACK
56 4.722222f, // MOVE_SWIM
57 4.5f, // MOVE_SWIM_BACK
58 3.141594f, // MOVE_TURN_RATE
59 7.0f, // MOVE_FLIGHT
60 4.5f, // MOVE_FLIGHT_BACK
61 3.14f // MOVE_PITCH_RATE
64 // Used for prepare can/can`t triggr aura
65 static bool InitTriggerAuraData();
66 // Define can trigger auras
67 static bool isTriggerAura[TOTAL_AURAS];
68 // Define can`t trigger auras (need for disable second trigger)
69 static bool isNonTriggerAura[TOTAL_AURAS];
70 // Prepare lists
71 static bool procPrepared = InitTriggerAuraData();
73 Unit::Unit()
74 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
76 m_objectType |= TYPEMASK_UNIT;
77 m_objectTypeId = TYPEID_UNIT;
79 m_updateFlag = (UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
81 m_attackTimer[BASE_ATTACK] = 0;
82 m_attackTimer[OFF_ATTACK] = 0;
83 m_attackTimer[RANGED_ATTACK] = 0;
84 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
85 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
86 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
88 m_extraAttacks = 0;
90 m_state = 0;
91 m_form = FORM_NONE;
92 m_deathState = ALIVE;
94 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
95 m_currentSpells[i] = NULL;
97 m_addDmgOnce = 0;
99 for(int i = 0; i < MAX_TOTEM; ++i)
100 m_TotemSlot[i] = 0;
102 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
103 //m_Aura = NULL;
104 //m_AurasCheck = 2000;
105 //m_removeAuraTimer = 4;
106 m_AurasUpdateIterator = m_Auras.end();
108 m_Visibility = VISIBILITY_ON;
110 m_detectInvisibilityMask = 0;
111 m_invisibilityMask = 0;
112 m_transform = 0;
113 m_ShapeShiftFormSpellId = 0;
114 m_canModifyStats = false;
116 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
117 m_spellImmune[i].clear();
118 for (int i = 0; i < UNIT_MOD_END; ++i)
120 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
121 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
122 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
123 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
125 // implement 50% base damage from offhand
126 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
128 for (int i = 0; i < MAX_ATTACK; ++i)
130 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
131 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
133 for (int i = 0; i < MAX_STATS; ++i)
134 m_createStats[i] = 0.0f;
136 m_attacking = NULL;
137 m_modMeleeHitChance = 0.0f;
138 m_modRangedHitChance = 0.0f;
139 m_modSpellHitChance = 0.0f;
140 m_baseSpellCritChance = 5;
142 m_CombatTimer = 0;
143 m_lastManaUseTimer = 0;
145 //m_victimThreat = 0.0f;
146 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
147 m_threatModifier[i] = 1.0f;
148 m_isSorted = true;
149 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
150 m_speed_rate[i] = 1.0f;
152 m_charmInfo = NULL;
154 // remove aurastates allowing special moves
155 for(int i=0; i < MAX_REACTIVE; ++i)
156 m_reactiveTimer[i] = 0;
159 Unit::~Unit()
161 // set current spells as deletable
162 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
164 if (m_currentSpells[i])
166 m_currentSpells[i]->SetReferencedFromCurrent(false);
167 m_currentSpells[i] = NULL;
171 RemoveAllGameObjects();
172 RemoveAllDynObjects();
174 if(m_charmInfo) delete m_charmInfo;
177 void Unit::Update( uint32 p_time )
179 if(!IsInWorld())
180 return;
182 /*if(p_time > m_AurasCheck)
184 m_AurasCheck = 2000;
185 _UpdateAura();
186 }else
187 m_AurasCheck -= p_time;*/
189 // WARNING! Order of execution here is important, do not change.
190 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
191 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
192 m_Events.Update( p_time );
193 _UpdateSpells( p_time );
195 if (m_lastManaUseTimer)
197 if (p_time >= m_lastManaUseTimer)
198 m_lastManaUseTimer = 0;
199 else
200 m_lastManaUseTimer -= p_time;
203 // really delete auras "deleted" while processing its ApplyModify code
204 for(AuraList::const_iterator itr = m_deletedAuras.begin(); itr != m_deletedAuras.begin(); ++itr)
205 delete *itr;
206 m_deletedAuras.clear();
208 // update combat timer only for players and pets
209 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
211 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
212 // targets without stopping half way there and running off.
213 // These flags are reset after target dies or another command is given.
214 if( m_HostilRefManager.isEmpty() )
216 // m_CombatTimer set at aura start and it will be freeze until aura removing
217 if ( m_CombatTimer <= p_time )
218 ClearInCombat();
219 else
220 m_CombatTimer -= p_time;
224 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
226 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
229 // update abilities available only for fraction of time
230 UpdateReactives( p_time );
232 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
233 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
234 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
236 i_motionMaster.UpdateMotion(p_time);
239 bool Unit::haveOffhandWeapon() const
241 if(GetTypeId() == TYPEID_PLAYER)
242 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
243 else
244 return false;
247 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, MonsterMovementFlags flags, uint32 Time, Player* player)
249 float moveTime = Time;
251 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
252 data.append(GetPackGUID());
253 data << uint8(0); // new in 3.1
254 data << GetPositionX() << GetPositionY() << GetPositionZ();
255 data << uint32(getMSTime());
257 data << uint8(type); // unknown
258 switch(type)
260 case 0: // normal packet
261 break;
262 case 1: // stop packet (raw pos?)
263 SendMessageToSet( &data, true );
264 return;
265 case 2: // facing spot, not used currently
266 data << float(0);
267 data << float(0);
268 data << float(0);
269 break;
270 case 3: // not used currently
271 data << uint64(0); // probably target guid (facing target?)
272 break;
273 case 4: // not used currently
274 data << float(0); // facing angle
275 break;
278 data << uint32(flags);
280 if(flags & MONSTER_MOVE_WALK)
281 moveTime *= 1.05f;
283 data << uint32(moveTime); // Time in between points
284 data << uint32(1); // 1 single waypoint
285 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
287 if(player)
288 player->GetSession()->SendPacket(&data);
289 else
290 SendMessageToSet( &data, true );
293 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, MonsterMovementFlags flags)
295 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
297 uint32 pathSize = end - start;
299 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+1+4+4+4+4+1+4+4+4+pathSize*4*3) );
300 data.append(GetPackGUID());
301 data << uint8(0);
302 data << GetPositionX();
303 data << GetPositionY();
304 data << GetPositionZ();
305 data << uint32(getMSTime());
306 data << uint8(0);
307 data << uint32(flags);
308 data << uint32(traveltime);
309 data << uint32(pathSize);
310 data.append((char*)path.GetNodes(start), pathSize * 4 * 3);
311 SendMessageToSet(&data, true);
314 void Unit::BuildHeartBeatMsg(WorldPacket *data) const
316 MovementFlags move_flags = GetTypeId()==TYPEID_PLAYER
317 ? ((Player const*)this)->m_movementInfo.GetMovementFlags()
318 : MOVEMENTFLAG_NONE;
320 data->Initialize(MSG_MOVE_HEARTBEAT, 32);
321 data->append(GetPackGUID());
322 *data << uint32(move_flags); // movement flags
323 *data << uint16(0); // 2.3.0
324 *data << uint32(getMSTime()); // time
325 *data << float(GetPositionX());
326 *data << float(GetPositionY());
327 *data << float(GetPositionZ());
328 *data << float(GetOrientation());
329 *data << uint32(0);
332 void Unit::resetAttackTimer(WeaponAttackType type)
334 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
337 bool Unit::canReachWithAttack(Unit *pVictim) const
339 assert(pVictim);
340 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
341 if( reach <= 0.0f )
342 reach = 1.0f;
343 return IsWithinDistInMap(pVictim, reach);
346 void Unit::RemoveSpellsCausingAura(AuraType auraType)
348 if (auraType >= TOTAL_AURAS) return;
349 AuraList::const_iterator iter, next;
350 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
352 next = iter;
353 ++next;
355 if (*iter)
357 RemoveAurasDueToSpell((*iter)->GetId());
358 if (!m_modAuras[auraType].empty())
359 next = m_modAuras[auraType].begin();
360 else
361 return;
366 bool Unit::HasAuraType(AuraType auraType) const
368 return (!m_modAuras[auraType].empty());
371 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
372 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
374 if(!HasAuraType(auraType))
375 return;
377 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
378 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
379 float chance = float(damage) / max_dmg * 100.0f;
380 if (roll_chance_f(chance))
381 RemoveSpellsCausingAura(auraType);
384 void Unit::DealDamageMods(Unit *pVictim, uint32 &damage, uint32* absorb)
386 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
388 if(absorb)
389 absorb += damage;
390 damage = 0;
391 return;
394 //You don't lose health from damage taken from another player while in a sanctuary
395 //You still see it in the combat log though
396 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
398 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
399 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
401 if(absorb)
402 absorb += damage;
403 damage = 0;
407 uint32 originalDamage = damage;
409 //Script Event damage Deal
410 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
411 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
412 //Script Event damage taken
413 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
414 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
416 if(absorb && originalDamage > damage)
417 absorb += (originalDamage - damage);
420 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
422 // remove affects from victim (including from 0 damage and DoTs)
423 if(pVictim != this)
424 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
426 // remove affects from attacker at any non-DoT damage (including 0 damage)
427 if( damagetype != DOT)
429 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
430 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
432 if(pVictim != this)
433 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
435 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
436 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
439 if(!damage)
441 // Rage from physical damage received .
442 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
443 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
445 return 0;
447 if (!spellProto || !IsSpellHaveAura(spellProto,SPELL_AURA_MOD_FEAR))
448 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
449 // root type spells do not dispel the root effect
450 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsSpellHaveAura(spellProto,SPELL_AURA_MOD_ROOT)))
451 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
453 // no xp,health if type 8 /critters/
454 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
456 pVictim->setDeathState(JUST_DIED);
457 pVictim->SetHealth(0);
459 // allow loot only if has loot_id in creature_template
460 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
461 if(cInfo && cInfo->lootid)
462 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
464 // some critters required for quests (need normal entry instead possible heroic in any cases)
465 if(GetTypeId() == TYPEID_PLAYER)
466 if(CreatureInfo const* normalInfo = objmgr.GetCreatureTemplate(pVictim->GetEntry()))
467 ((Player*)this)->KilledMonster(normalInfo,pVictim->GetGUID());
469 return damage;
472 DEBUG_LOG("DealDamageStart");
474 uint32 health = pVictim->GetHealth();
475 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
477 // duel ends when player has 1 or less hp
478 bool duel_hasEnded = false;
479 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
481 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
482 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
483 damage = health-1;
485 duel_hasEnded = true;
487 //Get in CombatState
488 if(pVictim != this && damagetype != DOT)
490 SetInCombatWith(pVictim);
491 pVictim->SetInCombatWith(this);
493 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
494 SetContestedPvP(attackedPlayer);
497 // Rage from Damage made (only from direct weapon damage)
498 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
500 uint32 weaponSpeedHitFactor;
502 switch(cleanDamage->attackType)
504 case BASE_ATTACK:
506 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
507 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
508 else
509 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
511 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
513 break;
515 case OFF_ATTACK:
517 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
518 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
519 else
520 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
522 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
524 break;
526 case RANGED_ATTACK:
527 break;
531 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
533 Player *killer = ((Player*)this);
535 // in bg, count dmg if victim is also a player
536 if (pVictim->GetTypeId()==TYPEID_PLAYER)
538 if (BattleGround *bg = killer->GetBattleGround())
540 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
541 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
545 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE, damage, 0, pVictim);
546 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
549 if (pVictim->GetTypeId() == TYPEID_PLAYER)
550 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
552 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
553 ((Creature*)pVictim)->SetLootRecipient(this);
555 if (health <= damage)
557 DEBUG_LOG("DealDamage: victim just died");
559 if (pVictim->GetTypeId() == TYPEID_PLAYER)
560 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
562 // find player: owner of controlled `this` or `this` itself maybe
563 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
565 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
566 player = ((Creature*)pVictim)->GetLootRecipient();
567 // Reward player, his pets, and group/raid members
568 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
569 if(player && player!=pVictim)
571 player->RewardPlayerAndGroupAtKill(pVictim);
572 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
575 DEBUG_LOG("DealDamageAttackStop");
577 // stop combat
578 pVictim->CombatStop();
579 pVictim->getHostilRefManager().deleteReferences();
581 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
583 // if talent known but not triggered (check priest class for speedup check)
584 Aura* spiritOfRedemtionTalentReady = NULL;
585 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
586 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
588 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
589 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
591 if((*itr)->GetSpellProto()->SpellIconID==1654)
593 spiritOfRedemtionTalentReady = *itr;
594 break;
599 DEBUG_LOG("SET JUST_DIED");
600 if(!spiritOfRedemtionTalentReady)
601 pVictim->setDeathState(JUST_DIED);
603 DEBUG_LOG("DealDamageHealth1");
605 if(spiritOfRedemtionTalentReady)
607 // save value before aura remove
608 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
609 if(!ressSpellId)
610 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
612 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
613 pVictim->RemoveAllAurasOnDeath();
615 // restore for use at real death
616 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
618 // FORM_SPIRITOFREDEMPTION and related auras
619 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
621 else
622 pVictim->SetHealth(0);
624 // remember victim PvP death for corpse type and corpse reclaim delay
625 // at original death (not at SpiritOfRedemtionTalent timeout)
626 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
627 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
629 // Call KilledUnit for creatures
630 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
631 ((Creature*)this)->AI()->KilledUnit(pVictim);
633 // achievement stuff
634 if (pVictim->GetTypeId() == TYPEID_PLAYER)
636 if (GetTypeId() == TYPEID_UNIT)
637 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
638 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
639 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
642 // 10% durability loss on death
643 // clean InHateListOf
644 if (pVictim->GetTypeId() == TYPEID_PLAYER)
646 // only if not player and not controlled by player pet. And not at BG
647 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
649 DEBUG_LOG("We are dead, loosing 10 percents durability");
650 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
651 // durability lost message
652 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
653 ((Player*)pVictim)->GetSession()->SendPacket(&data);
656 else // creature died
658 DEBUG_LOG("DealDamageNotPlayer");
659 Creature *cVictim = (Creature*)pVictim;
661 if(!cVictim->isPet())
663 cVictim->DeleteThreatList();
664 // only lootable if it has loot or can drop gold
665 if(cVictim->GetCreatureInfo()->lootid || cVictim->GetCreatureInfo()->maxgold > 0)
666 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
667 else
668 cVictim->lootForBody = true; // needed for skinning
670 // Call creature just died function
671 if (cVictim->AI())
672 cVictim->AI()->JustDied(this);
674 // Dungeon specific stuff, only applies to players killing creatures
675 if(cVictim->GetInstanceId())
677 Map *m = cVictim->GetMap();
678 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
679 // TODO: do instance binding anyway if the charmer/owner is offline
681 if(m->IsDungeon() && creditedPlayer)
683 if(m->IsRaid() || m->IsHeroic())
685 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
686 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
688 else
690 // the reset time is set but not added to the scheduler
691 // until the players leave the instance
692 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
693 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
694 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
700 // last damage from non duel opponent or opponent controlled creature
701 if(duel_hasEnded)
703 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
704 Player *he = (Player*)pVictim;
706 assert(he->duel);
708 he->duel->opponent->CombatStopWithPets(true);
709 he->CombatStopWithPets(true);
711 he->DuelComplete(DUEL_INTERUPTED);
714 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
715 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
717 Player *killed = ((Player*)pVictim);
718 if(BattleGround *bg = killed->GetBattleGround())
719 if(player)
720 bg->HandleKillPlayer(killed, player);
721 //later we can add support for creature->player kills here i'm
722 //not sure, but i guess those kills also get counted in av
723 //else if(GetTypeId() == TYPEID_UNIT)
724 // bg->HandleKillPlayer(killed,(Creature*)this);
727 else // if (health <= damage)
729 DEBUG_LOG("DealDamageAlive");
731 if (pVictim->GetTypeId() == TYPEID_PLAYER)
732 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
734 pVictim->ModifyHealth(- (int32)damage);
736 if(damagetype != DOT)
738 if(!getVictim())
740 // if not have main target then attack state with target (including AI call)
741 //start melee attacks only after melee hit
742 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
745 // if damage pVictim call AI reaction
746 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
747 ((Creature*)pVictim)->AI()->AttackedBy(this);
750 // polymorphed and other negative transformed cases
751 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
752 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
754 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
756 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
757 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
759 if (pVictim->GetTypeId() != TYPEID_PLAYER)
761 if(spellProto && IsDamageToThreatSpell(spellProto))
762 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
763 else
764 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
766 else // victim is a player
768 // Rage from damage received
769 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
771 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
772 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
775 // random durability for items (HIT TAKEN)
776 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
778 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
779 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
783 if(GetTypeId()==TYPEID_PLAYER)
785 // random durability for items (HIT DONE)
786 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
788 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
789 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
793 // TODO: Store auras by interrupt flag to speed this up.
794 AuraMap& vAuras = pVictim->GetAuras();
795 for (AuraMap::const_iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
797 const SpellEntry *se = i->second->GetSpellProto();
798 next = i; ++next;
799 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
800 continue;
801 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
803 bool remove = true;
804 if (se->procFlags & (1<<3))
806 if (!roll_chance_i(se->procChance))
807 remove = false;
809 if (remove)
811 pVictim->RemoveAurasDueToSpell(i->second->GetId());
812 // FIXME: this may cause the auras with proc chance to be rerolled several times
813 next = vAuras.begin();
818 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
820 if( damagetype != DOT )
822 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
824 // skip channeled spell (processed differently below)
825 if (i == CURRENT_CHANNELED_SPELL)
826 continue;
828 if(Spell* spell = pVictim->GetCurrentSpell(CurrentSpellTypes(i)))
830 if(spell->getState() == SPELL_STATE_PREPARING)
832 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
833 pVictim->InterruptSpell(CurrentSpellTypes(i));
834 else
835 spell->Delayed();
841 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
843 if (spell->getState() == SPELL_STATE_CASTING)
845 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
846 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
848 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
849 spell->DelayedChannel();
851 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
853 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
854 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
857 else if (spell->getState() == SPELL_STATE_DELAYED)
858 // break channeled spell in delayed state on damage
860 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
861 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
866 // last damage from duel opponent
867 if(duel_hasEnded)
869 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
870 Player *he = (Player*)pVictim;
872 assert(he->duel);
874 he->SetHealth(1);
876 he->duel->opponent->CombatStopWithPets(true);
877 he->CombatStopWithPets(true);
879 he->CastSpell(he, 7267, true); // beg
880 he->DuelComplete(DUEL_WON);
884 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
886 return damage;
889 void Unit::CastStop(uint32 except_spellid)
891 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
892 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
893 InterruptSpell(CurrentSpellTypes(i),false);
896 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
898 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
900 if(!spellInfo)
902 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
903 return;
906 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
909 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
911 if(!spellInfo)
913 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
914 return;
917 if (castItem)
918 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
920 if(!originalCaster && triggeredByAura)
921 originalCaster = triggeredByAura->GetCasterGUID();
923 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
925 SpellCastTargets targets;
926 targets.setUnitTarget( Victim );
927 spell->m_CastItem = castItem;
928 spell->prepare(&targets, triggeredByAura);
931 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
933 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
935 if(!spellInfo)
937 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
938 return;
941 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
944 void Unit::CastCustomSpell(Unit* Victim,SpellEntry const *spellInfo, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
946 if(!spellInfo)
948 sLog.outError("CastCustomSpell: unknown spell");
949 return;
952 if (castItem)
953 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
955 if(!originalCaster && triggeredByAura)
956 originalCaster = triggeredByAura->GetCasterGUID();
958 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
960 if(bp0)
961 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
963 if(bp1)
964 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
966 if(bp2)
967 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
969 SpellCastTargets targets;
970 targets.setUnitTarget( Victim );
971 spell->m_CastItem = castItem;
972 spell->prepare(&targets, triggeredByAura);
975 // used for scripting
976 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
978 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
980 if(!spellInfo)
982 sLog.outError("CastSpell(x,y,z): unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
983 return;
986 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
989 // used for scripting
990 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
992 if(!spellInfo)
994 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
995 return;
998 if (castItem)
999 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
1001 if(!originalCaster && triggeredByAura)
1002 originalCaster = triggeredByAura->GetCasterGUID();
1004 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
1006 SpellCastTargets targets;
1007 targets.setDestination(x, y, z);
1008 spell->m_CastItem = castItem;
1009 spell->prepare(&targets, triggeredByAura);
1012 // Obsolete func need remove, here only for comotability vs another patches
1013 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage)
1015 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
1016 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
1017 CalculateSpellDamage(&damageInfo, damage, spellInfo);
1018 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
1019 SendSpellNonMeleeDamageLog(&damageInfo);
1020 DealSpellDamage(&damageInfo, true);
1021 return damageInfo.damage;
1024 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
1026 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
1027 Unit *pVictim = damageInfo->target;
1029 if (damage < 0)
1030 return;
1032 if(!this || !pVictim)
1033 return;
1034 if(!this->isAlive() || !pVictim->isAlive())
1035 return;
1037 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
1038 // Check spell crit chance
1039 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1040 bool blocked = false;
1041 // Per-school calc
1042 switch (spellInfo->DmgClass)
1044 // Melee and Ranged Spells
1045 case SPELL_DAMAGE_CLASS_RANGED:
1046 case SPELL_DAMAGE_CLASS_MELEE:
1048 // Physical Damage
1049 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1051 //Calculate armor mitigation
1052 damage = CalcArmorReducedDamage(pVictim, damage);
1053 // Get blocked status
1054 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1056 // Magical Damage
1057 else
1059 // Calculate damage bonus
1060 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1062 if (crit)
1064 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1066 // Calculate crit bonus
1067 uint32 crit_bonus = damage;
1068 // Apply crit_damage bonus for melee spells
1069 if(Player* modOwner = GetSpellModOwner())
1070 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1071 damage += crit_bonus;
1073 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1074 int32 critPctDamageMod=0;
1075 if(attackType == RANGED_ATTACK)
1076 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1077 else
1079 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1080 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1082 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1083 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1085 if (critPctDamageMod!=0)
1086 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1088 // Resilience - reduce crit damage
1089 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1090 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1092 // Spell weapon based damage CAN BE crit & blocked at same time
1093 if (blocked)
1095 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1096 if (damage < damageInfo->blocked)
1097 damageInfo->blocked = damage;
1098 damage-=damageInfo->blocked;
1101 break;
1102 // Magical Attacks
1103 case SPELL_DAMAGE_CLASS_NONE:
1104 case SPELL_DAMAGE_CLASS_MAGIC:
1106 // Calculate damage bonus
1107 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1108 // If crit add critical bonus
1109 if (crit)
1111 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1112 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1113 // Resilience - reduce crit damage
1114 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1115 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1118 break;
1121 // Calculate absorb resist
1122 if(damage > 0)
1124 // lookup absorb/resist ignore auras on caster for spell
1125 bool ignore = false;
1126 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1127 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1128 if ((*i)->isAffectedOnSpell(spellInfo))
1130 ignore = true;
1131 break;
1134 if (!ignore)
1136 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1137 damage-= damageInfo->absorb + damageInfo->resist;
1140 else
1141 damage = 0;
1142 damageInfo->damage = damage;
1145 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1147 if (damageInfo==0)
1148 return;
1150 Unit *pVictim = damageInfo->target;
1152 if(!this || !pVictim)
1153 return;
1155 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1156 return;
1158 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1159 if (spellProto == NULL)
1161 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1162 return;
1165 //You don't lose health from damage taken from another player while in a sanctuary
1166 //You still see it in the combat log though
1167 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1169 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1170 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1171 return;
1174 // Call default DealDamage
1175 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1176 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1179 //TODO for melee need create structure as in
1180 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1182 damageInfo->attacker = this;
1183 damageInfo->target = pVictim;
1184 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1185 damageInfo->attackType = attackType;
1186 damageInfo->damage = 0;
1187 damageInfo->cleanDamage = 0;
1188 damageInfo->absorb = 0;
1189 damageInfo->resist = 0;
1190 damageInfo->blocked_amount = 0;
1192 damageInfo->TargetState = 0;
1193 damageInfo->HitInfo = 0;
1194 damageInfo->procAttacker = PROC_FLAG_NONE;
1195 damageInfo->procVictim = PROC_FLAG_NONE;
1196 damageInfo->procEx = PROC_EX_NONE;
1197 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1199 if(!this || !pVictim)
1200 return;
1201 if(!this->isAlive() || !pVictim->isAlive())
1202 return;
1204 // Select HitInfo/procAttacker/procVictim flag based on attack type
1205 switch (attackType)
1207 case BASE_ATTACK:
1208 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT;
1209 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1210 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1211 break;
1212 case OFF_ATTACK:
1213 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MELEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1214 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1215 damageInfo->HitInfo = HITINFO_LEFTSWING;
1216 break;
1217 case RANGED_ATTACK:
1218 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1219 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1220 damageInfo->HitInfo = 0x08;// test
1221 break;
1222 default:
1223 break;
1226 // Physical Immune check
1227 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1229 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1230 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1232 damageInfo->procEx |=PROC_EX_IMMUNE;
1233 damageInfo->damage = 0;
1234 damageInfo->cleanDamage = 0;
1235 return;
1237 damage += CalculateDamage (damageInfo->attackType, false);
1238 // Add melee damage bonus
1239 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1240 // Calculate armor reduction
1241 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1242 damageInfo->cleanDamage += damage - damageInfo->damage;
1244 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1246 // Disable parry or dodge for ranged attack
1247 if(damageInfo->attackType == RANGED_ATTACK)
1249 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1250 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1253 switch(damageInfo->hitOutCome)
1255 case MELEE_HIT_EVADE:
1257 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1258 damageInfo->TargetState = VICTIMSTATE_EVADES;
1260 damageInfo->procEx|=PROC_EX_EVADE;
1261 damageInfo->damage = 0;
1262 damageInfo->cleanDamage = 0;
1263 return;
1265 case MELEE_HIT_MISS:
1267 damageInfo->HitInfo |= HITINFO_MISS;
1268 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1270 damageInfo->procEx|=PROC_EX_MISS;
1271 damageInfo->damage = 0;
1272 damageInfo->cleanDamage = 0;
1273 break;
1275 case MELEE_HIT_NORMAL:
1276 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1277 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1278 break;
1279 case MELEE_HIT_CRIT:
1281 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1282 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1284 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1285 // Crit bonus calc
1286 damageInfo->damage += damageInfo->damage;
1287 int32 mod=0;
1288 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1289 if(damageInfo->attackType == RANGED_ATTACK)
1290 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1291 else
1293 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1294 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1297 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1299 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1300 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1301 if (mod!=0)
1302 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1304 // Resilience - reduce crit damage
1305 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1307 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1308 damageInfo->damage -= resilienceReduction;
1309 damageInfo->cleanDamage += resilienceReduction;
1311 break;
1313 case MELEE_HIT_PARRY:
1314 damageInfo->TargetState = VICTIMSTATE_PARRY;
1315 damageInfo->procEx|=PROC_EX_PARRY;
1316 damageInfo->cleanDamage += damageInfo->damage;
1317 damageInfo->damage = 0;
1318 break;
1320 case MELEE_HIT_DODGE:
1321 damageInfo->TargetState = VICTIMSTATE_DODGE;
1322 damageInfo->procEx|=PROC_EX_DODGE;
1323 damageInfo->cleanDamage += damageInfo->damage;
1324 damageInfo->damage = 0;
1325 break;
1326 case MELEE_HIT_BLOCK:
1328 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1329 damageInfo->HitInfo |= HITINFO_BLOCK;
1330 damageInfo->procEx|=PROC_EX_BLOCK;
1331 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1332 if (damageInfo->blocked_amount >= damageInfo->damage)
1334 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1335 damageInfo->blocked_amount = damageInfo->damage;
1337 damageInfo->damage -= damageInfo->blocked_amount;
1338 damageInfo->cleanDamage += damageInfo->blocked_amount;
1339 break;
1341 case MELEE_HIT_GLANCING:
1343 damageInfo->HitInfo |= HITINFO_GLANCING;
1344 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1345 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1346 float reducePercent = 1.0f; //damage factor
1347 // calculate base values and mods
1348 float baseLowEnd = 1.3f;
1349 float baseHighEnd = 1.2f;
1350 switch(getClass()) // lowering base values for casters
1352 case CLASS_SHAMAN:
1353 case CLASS_PRIEST:
1354 case CLASS_MAGE:
1355 case CLASS_WARLOCK:
1356 case CLASS_DRUID:
1357 baseLowEnd -= 0.7f;
1358 baseHighEnd -= 0.3f;
1359 break;
1362 float maxLowEnd = 0.6f;
1363 switch(getClass()) // upper for melee classes
1365 case CLASS_WARRIOR:
1366 case CLASS_ROGUE:
1367 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1370 // calculate values
1371 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1372 float lowEnd = baseLowEnd - ( 0.05f * diff );
1373 float highEnd = baseHighEnd - ( 0.03f * diff );
1375 // apply max/min bounds
1376 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1377 lowEnd = 0.01f;
1378 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1379 lowEnd = maxLowEnd;
1381 if ( highEnd < 0.2f ) //high end limits
1382 highEnd = 0.2f;
1383 if ( highEnd > 0.99f )
1384 highEnd = 0.99f;
1386 if(lowEnd > highEnd) // prevent negative range size
1387 lowEnd = highEnd;
1389 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1391 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1392 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1393 break;
1395 case MELEE_HIT_CRUSHING:
1397 damageInfo->HitInfo |= HITINFO_CRUSHING;
1398 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1399 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1400 // 150% normal damage
1401 damageInfo->damage += (damageInfo->damage / 2);
1402 break;
1404 default:
1406 break;
1409 // Calculate absorb resist
1410 if(int32(damageInfo->damage) > 0)
1412 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1413 // Calculate absorb & resists
1414 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1415 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1416 if (damageInfo->absorb)
1418 damageInfo->HitInfo|=HITINFO_ABSORB;
1419 damageInfo->procEx|=PROC_EX_ABSORB;
1421 if (damageInfo->resist)
1422 damageInfo->HitInfo|=HITINFO_RESIST;
1425 else // Umpossible get negative result but....
1426 damageInfo->damage = 0;
1429 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1431 if (damageInfo==0) return;
1432 Unit *pVictim = damageInfo->target;
1434 if(!this || !pVictim)
1435 return;
1437 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1438 return;
1440 //You don't lose health from damage taken from another player while in a sanctuary
1441 //You still see it in the combat log though
1442 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1444 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1445 if(area && area->flags & AREA_FLAG_SANCTUARY) // sanctuary
1446 return;
1449 // Hmmmm dont like this emotes client must by self do all animations
1450 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1451 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1452 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1453 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1455 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1457 // Get attack timers
1458 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1459 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1460 // Reduce attack time
1461 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1463 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1464 float percent60 = 3.0f * percent20;
1465 if(offtime > percent20 && offtime <= percent60)
1467 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1469 else if(offtime > percent60)
1471 offtime -= 2.0f * percent20;
1472 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1475 else
1477 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1478 float percent60 = 3.0f * percent20;
1479 if(basetime > percent20 && basetime <= percent60)
1481 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1483 else if(basetime > percent60)
1485 basetime -= 2.0f * percent20;
1486 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1491 // Call default DealDamage
1492 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1493 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1495 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1496 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1497 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1499 // -probability is between 0% and 40%
1500 // 20% base chance
1501 float Probability = 20.0f;
1503 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1504 if( pVictim->getLevel() < 30 )
1505 Probability = 0.65f*pVictim->getLevel()+0.5f;
1507 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1508 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1510 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1512 if(Probability > 40.0f)
1513 Probability = 40.0f;
1515 if(roll_chance_f(Probability))
1516 CastSpell(pVictim, 1604, true);
1519 // If not miss
1520 if (!(damageInfo->HitInfo & HITINFO_MISS))
1522 // on weapon hit casts
1523 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1524 ((Player*)this)->CastItemCombatSpell(pVictim, damageInfo->attackType);
1526 // victim's damage shield
1527 std::set<Aura*> alreadyDone;
1528 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1529 for(AuraList::const_iterator i = vDamageShields.begin(); i != vDamageShields.end();)
1531 if (alreadyDone.find(*i) == alreadyDone.end())
1533 alreadyDone.insert(*i);
1534 uint32 damage=(*i)->GetModifier()->m_amount;
1535 SpellEntry const *i_spellProto = (*i)->GetSpellProto();
1536 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1537 //uint32 absorb;
1538 //uint32 resist;
1539 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1540 //damage-=absorb + resist;
1542 pVictim->DealDamageMods(this,damage,NULL);
1544 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1545 data << uint64(pVictim->GetGUID());
1546 data << uint64(GetGUID());
1547 data << uint32(i_spellProto->Id);
1548 data << uint32(damage); // Damage
1549 data << uint32(0); // Overkill
1550 data << uint32(i_spellProto->SchoolMask);
1551 pVictim->SendMessageToSet(&data, true );
1553 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(i_spellProto), i_spellProto, true);
1555 i = vDamageShields.begin();
1557 else
1558 ++i;
1564 void Unit::HandleEmoteCommand(uint32 anim_id)
1566 WorldPacket data( SMSG_EMOTE, 4 + 8 );
1567 data << uint32(anim_id);
1568 data << uint64(GetGUID());
1569 SendMessageToSet(&data, true);
1572 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1574 uint32 newdamage = 0;
1575 float armor = pVictim->GetArmor();
1577 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1578 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1580 // Apply Player CR_ARMOR_PENETRATION rating and percent talents
1581 if (GetTypeId()==TYPEID_PLAYER)
1582 armor *= 1.0f - ((Player*)this)->GetArmorPenetrationPct() / 100.0f;
1584 if (armor < 0.0f)
1585 armor = 0.0f;
1587 float levelModifier = getLevel();
1588 if (levelModifier > 59)
1589 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1591 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1592 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1594 if (tmpvalue < 0.0f)
1595 tmpvalue = 0.0f;
1596 if (tmpvalue > 0.75f)
1597 tmpvalue = 0.75f;
1599 newdamage = uint32(damage - (damage * tmpvalue));
1601 return (newdamage > 1) ? newdamage : 1;
1604 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1606 if(!pVictim || !pVictim->isAlive() || !damage)
1607 return;
1609 // Magic damage, check for resists
1610 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1612 // Get base victim resistance for school
1613 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1614 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1615 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1617 tmpvalue2 *= (float)(0.15f / getLevel());
1618 if (tmpvalue2 < 0.0f)
1619 tmpvalue2 = 0.0f;
1620 if (tmpvalue2 > 0.75f)
1621 tmpvalue2 = 0.75f;
1622 uint32 ran = urand(0, 100);
1623 uint32 faq[4] = {24,6,4,6};
1624 uint8 m = 0;
1625 float Binom = 0.0f;
1626 for (uint8 i = 0; i < 4; ++i)
1628 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1629 if (ran > Binom )
1630 ++m;
1631 else
1632 break;
1634 if (damagetype == DOT && m == 4)
1635 *resist += uint32(damage - 1);
1636 else
1637 *resist += uint32(damage * m / 4);
1638 if(*resist > damage)
1639 *resist = damage;
1641 else
1642 *resist = 0;
1644 int32 RemainingDamage = damage - *resist;
1646 // Get unit state (need for some absorb check)
1647 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1648 // Reflect damage spells (not cast any damage spell in aura lookup)
1649 uint32 reflectSpell = 0;
1650 int32 reflectDamage = 0;
1651 Aura* reflectTriggeredBy = NULL; // expected as not expired at reflect as in current cases
1652 // Death Prevention Aura
1653 SpellEntry const* preventDeathSpell = NULL;
1654 int32 preventDeathAmount = 0;
1655 // Need remove expired auras after
1656 bool existExpired = false;
1657 // absorb without mana cost
1658 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1659 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1661 Modifier* mod = (*i)->GetModifier();
1662 if (!(mod->m_miscvalue & schoolMask))
1663 continue;
1665 SpellEntry const* spellProto = (*i)->GetSpellProto();
1667 // Max Amount can be absorbed by this aura
1668 int32 currentAbsorb = mod->m_amount;
1670 // Found empty aura (impossible but..)
1671 if (currentAbsorb <=0)
1673 existExpired = true;
1674 continue;
1676 // Handle custom absorb auras
1677 // TODO: try find better way
1678 switch(spellProto->SpellFamilyName)
1680 case SPELLFAMILY_GENERIC:
1682 // Astral Shift
1683 if (spellProto->SpellIconID == 3066)
1685 //reduces all damage taken while stun, fear or silence
1686 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1687 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1688 continue;
1690 // Nerves of Steel
1691 if (spellProto->SpellIconID == 2115)
1693 // while affected by Stun and Fear
1694 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1695 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1696 continue;
1698 // Spell Deflection
1699 if (spellProto->SpellIconID == 3006)
1701 // You have a chance equal to your Parry chance
1702 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1703 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1704 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1705 continue;
1707 // Reflective Shield (Lady Malande boss)
1708 if (spellProto->Id == 41475)
1710 if(RemainingDamage < currentAbsorb)
1711 reflectDamage = RemainingDamage / 2;
1712 else
1713 reflectDamage = currentAbsorb / 2;
1714 reflectSpell = 33619;
1715 reflectTriggeredBy = *i;
1716 break;
1718 if (spellProto->Id == 39228 || // Argussian Compass
1719 spellProto->Id == 60218) // Essence of Gossamer
1721 // Max absorb stored in 1 dummy effect
1722 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1723 currentAbsorb = spellProto->EffectBasePoints[1];
1724 break;
1726 break;
1728 case SPELLFAMILY_DRUID:
1730 // Primal Tenacity
1731 if (spellProto->SpellIconID == 2253)
1733 //reduces all damage taken while Stunned
1734 if (unitflag & UNIT_FLAG_STUNNED)
1735 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1736 continue;
1738 break;
1740 case SPELLFAMILY_ROGUE:
1742 // Cheat Death (make less prio with Guardian Spirit case)
1743 if (!preventDeathSpell && spellProto->SpellIconID == 2109 &&
1744 pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1745 !((Player*)pVictim)->HasSpellCooldown(31231) &&
1746 // Only if no cooldown
1747 roll_chance_i((*i)->GetModifier()->m_amount))
1748 // Only if roll
1750 preventDeathSpell = (*i)->GetSpellProto();
1751 continue;
1753 break;
1755 case SPELLFAMILY_PRIEST:
1757 // Guardian Spirit
1758 if (spellProto->SpellIconID == 2873)
1760 preventDeathSpell = (*i)->GetSpellProto();
1761 preventDeathAmount = (*i)->GetModifier()->m_amount;
1762 continue;
1765 // Reflective Shield
1766 if (spellProto->SpellFamilyFlags == 0x1)
1768 if (pVictim == this)
1769 break;
1770 Unit* caster = (*i)->GetCaster();
1771 if (!caster)
1772 break;
1773 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1774 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1776 switch((*k)->GetModifier()->m_miscvalue)
1778 case 5065: // Rank 1
1779 case 5064: // Rank 2
1781 if(RemainingDamage >= currentAbsorb)
1782 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1783 else
1784 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1785 reflectSpell = 33619;
1786 reflectTriggeredBy = *i;
1787 } break;
1788 default: break;
1791 break;
1793 break;
1795 case SPELLFAMILY_SHAMAN:
1797 // Astral Shift
1798 if (spellProto->SpellIconID == 3066)
1800 //reduces all damage taken while stun, fear or silence
1801 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1802 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1803 continue;
1805 break;
1807 case SPELLFAMILY_DEATHKNIGHT:
1809 // Shadow of Death
1810 if (spellProto->SpellIconID == 1958)
1812 // TODO: absorb only while transform
1813 continue;
1815 // Anti-Magic Shell (on self)
1816 if (spellProto->Id == 48707)
1818 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1819 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1820 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1821 int32 regen = absorbed * 2 / 10;
1822 pVictim->CastCustomSpell(pVictim, 49088, &regen, NULL, NULL, true, NULL, *i);
1823 RemainingDamage -= absorbed;
1824 continue;
1826 // Anti-Magic Shell (on single party/raid member)
1827 if (spellProto->Id == 50462)
1829 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1830 continue;
1832 // Anti-Magic Zone
1833 if (spellProto->Id == 50461)
1835 Unit* caster = (*i)->GetCaster();
1836 if (!caster)
1837 continue;
1838 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1839 int32 canabsorb = caster->GetHealth();
1840 if (canabsorb < absorbed)
1841 absorbed = canabsorb;
1843 RemainingDamage -= absorbed;
1845 uint32 ab_damage = absorbed;
1846 DealDamageMods(caster,ab_damage,NULL);
1847 DealDamage(caster, ab_damage, NULL, damagetype, schoolMask, 0, false);
1848 continue;
1850 break;
1852 default:
1853 break;
1856 // currentAbsorb - damage can be absorbed by shield
1857 // If need absorb less damage
1858 if (RemainingDamage < currentAbsorb)
1859 currentAbsorb = RemainingDamage;
1861 RemainingDamage -= currentAbsorb;
1863 // Reduce shield amount
1864 mod->m_amount-=currentAbsorb;
1865 // Need remove it later
1866 if (mod->m_amount<=0)
1867 existExpired = true;
1870 // Remove all expired absorb auras
1871 if (existExpired)
1873 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1875 if ((*i)->GetModifier()->m_amount<=0)
1877 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1878 i = vSchoolAbsorb.begin();
1880 else
1881 ++i;
1885 // Cast back reflect damage spell
1886 if (reflectSpell)
1887 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true, NULL, reflectTriggeredBy);
1889 // absorb by mana cost
1890 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1891 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1893 next = i; ++next;
1895 // check damage school mask
1896 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1897 continue;
1899 int32 currentAbsorb;
1900 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1901 currentAbsorb = (*i)->GetModifier()->m_amount;
1902 else
1903 currentAbsorb = RemainingDamage;
1905 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1906 if(Player *modOwner = pVictim->GetSpellModOwner())
1907 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1909 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1910 if (currentAbsorb > maxAbsorb)
1911 currentAbsorb = maxAbsorb;
1913 (*i)->GetModifier()->m_amount -= currentAbsorb;
1914 if((*i)->GetModifier()->m_amount <= 0)
1916 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1917 next = vManaShield.begin();
1920 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1921 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1923 RemainingDamage -= currentAbsorb;
1926 // only split damage if not damaging yourself
1927 if(pVictim != this)
1929 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1930 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1932 next = i; ++next;
1934 // check damage school mask
1935 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1936 continue;
1938 // Damage can be splitted only if aura has an alive caster
1939 Unit *caster = (*i)->GetCaster();
1940 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1941 continue;
1943 int32 currentAbsorb;
1944 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1945 currentAbsorb = (*i)->GetModifier()->m_amount;
1946 else
1947 currentAbsorb = RemainingDamage;
1949 RemainingDamage -= currentAbsorb;
1952 uint32 splitted = currentAbsorb;
1953 uint32 splitted_absorb = 0;
1954 DealDamageMods(caster,splitted,&splitted_absorb);
1956 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false);
1958 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1959 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1962 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1963 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1965 next = i; ++next;
1967 // check damage school mask
1968 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1969 continue;
1971 // Damage can be splitted only if aura has an alive caster
1972 Unit *caster = (*i)->GetCaster();
1973 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1974 continue;
1976 uint32 splitted = uint32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1978 RemainingDamage -= int32(splitted);
1980 uint32 split_absorb = 0;
1981 DealDamageMods(caster,splitted,&split_absorb);
1983 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false);
1985 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1986 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1990 // Apply death prevention spells effects
1991 if (preventDeathSpell && RemainingDamage >= pVictim->GetHealth())
1993 switch(preventDeathSpell->SpellFamilyName)
1995 // Cheat Death
1996 case SPELLFAMILY_ROGUE:
1998 // Cheat Death
1999 if (preventDeathSpell->SpellIconID == 2109)
2001 pVictim->CastSpell(pVictim,31231,true);
2002 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
2003 // with health > 10% lost health until health==10%, in other case no losses
2004 uint32 health10 = pVictim->GetMaxHealth()/10;
2005 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
2007 break;
2009 // Guardian Spirit
2010 case SPELLFAMILY_PRIEST:
2012 // Guardian Spirit
2013 if (preventDeathSpell->SpellIconID == 2873)
2015 int32 healAmount = pVictim->GetMaxHealth() * preventDeathAmount / 100;
2016 pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true);
2017 pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id);
2018 RemainingDamage = 0;
2020 break;
2025 *absorb = damage - RemainingDamage - *resist;
2028 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
2030 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
2031 return;
2033 if (!pVictim->isAlive())
2034 return;
2036 if(IsNonMeleeSpellCasted(false))
2037 return;
2039 uint32 hitInfo;
2040 if (attType == BASE_ATTACK)
2041 hitInfo = HITINFO_NORMALSWING2;
2042 else if (attType == OFF_ATTACK)
2043 hitInfo = HITINFO_LEFTSWING;
2044 else
2045 return; // ignore ranged case
2047 uint32 extraAttacks = m_extraAttacks;
2049 // melee attack spell casted at main hand attack only
2050 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
2052 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
2054 // not recent extra attack only at any non extra attack (melee spell case)
2055 if(!extra && extraAttacks)
2057 while(m_extraAttacks)
2059 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2060 if(m_extraAttacks > 0)
2061 --m_extraAttacks;
2064 return;
2067 // attack can be redirected to another target
2068 pVictim = SelectMagnetTarget(pVictim);
2070 CalcDamageInfo damageInfo;
2071 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
2072 // Send log damage message to client
2073 DealDamageMods(pVictim,damageInfo.damage,&damageInfo.absorb);
2074 SendAttackStateUpdate(&damageInfo);
2075 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
2076 DealMeleeDamage(&damageInfo,true);
2078 if (GetTypeId() == TYPEID_PLAYER)
2079 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2080 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2081 else
2082 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
2083 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
2085 // if damage pVictim call AI reaction
2086 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2087 ((Creature*)pVictim)->AI()->AttackedBy(this);
2089 // extra attack only at any non extra attack (normal case)
2090 if(!extra && extraAttacks)
2092 while(m_extraAttacks)
2094 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2095 if(m_extraAttacks > 0)
2096 --m_extraAttacks;
2101 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2103 // This is only wrapper
2105 // Miss chance based on melee
2106 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2108 // Critical hit chance
2109 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2111 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2112 float dodge_chance = pVictim->GetUnitDodgeChance();
2113 float block_chance = pVictim->GetUnitBlockChance();
2114 float parry_chance = pVictim->GetUnitParryChance();
2116 // Useful if want to specify crit & miss chances for melee, else it could be removed
2117 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2119 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2122 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2124 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2125 return MELEE_HIT_EVADE;
2127 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2128 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2130 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2131 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2133 // bonus from skills is 0.04%
2134 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2135 int32 sum = 0, tmp = 0;
2136 int32 roll = urand (0, 10000);
2138 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2139 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2140 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2142 tmp = miss_chance;
2144 if (tmp > 0 && roll < (sum += tmp ))
2146 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2147 return MELEE_HIT_MISS;
2150 // always crit against a sitting target (except 0 crit chance)
2151 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2153 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2154 return MELEE_HIT_CRIT;
2157 // Dodge chance
2159 // only players can't dodge if attacker is behind
2160 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2162 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2164 else
2166 // Reduce dodge chance by attacker expertise rating
2167 if (GetTypeId() == TYPEID_PLAYER)
2168 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2170 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2171 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2173 tmp = dodge_chance;
2174 if ( (tmp > 0) // check if unit _can_ dodge
2175 && ((tmp -= skillBonus) > 0)
2176 && roll < (sum += tmp))
2178 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2179 return MELEE_HIT_DODGE;
2183 // parry & block chances
2185 // check if attack comes from behind, nobody can parry or block if attacker is behind
2186 if (!pVictim->HasInArc(M_PI,this))
2188 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2190 else
2192 // Reduce parry chance by attacker expertise rating
2193 if (GetTypeId() == TYPEID_PLAYER)
2194 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2196 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2198 int32 tmp2 = int32(parry_chance);
2199 if ( (tmp2 > 0) // check if unit _can_ parry
2200 && ((tmp2 -= skillBonus) > 0)
2201 && (roll < (sum += tmp2)))
2203 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp2, sum);
2204 return MELEE_HIT_PARRY;
2208 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2210 tmp = block_chance;
2211 if ( (tmp > 0) // check if unit _can_ block
2212 && ((tmp -= skillBonus) > 0)
2213 && (roll < (sum += tmp)))
2215 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2216 return MELEE_HIT_BLOCK;
2221 // Critical chance
2222 tmp = crit_chance;
2224 if (tmp > 0 && roll < (sum += tmp))
2226 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2227 return MELEE_HIT_CRIT;
2230 // 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)
2231 if( attType != RANGED_ATTACK &&
2232 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2233 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2234 getLevel() < pVictim->getLevelForTarget(this) )
2236 // cap possible value (with bonuses > max skill)
2237 int32 skill = attackerWeaponSkill;
2238 int32 maxskill = attackerMaxSkillValueForLevel;
2239 skill = (skill > maxskill) ? maxskill : skill;
2241 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2242 tmp = tmp > 4000 ? 4000 : tmp;
2243 if (roll < (sum += tmp))
2245 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2246 return MELEE_HIT_GLANCING;
2250 // mobs can score crushing blows if they're 4 or more levels above victim
2251 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2252 // can be from by creature (if can) or from controlled player that considered as creature
2253 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2254 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2255 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2257 // when their weapon skill is 15 or more above victim's defense skill
2258 tmp = victimDefenseSkill;
2259 int32 tmpmax = victimMaxSkillValueForLevel;
2260 // having defense above your maximum (from items, talents etc.) has no effect
2261 tmp = tmp > tmpmax ? tmpmax : tmp;
2262 // tmp = mob's level * 5 - player's current defense skill
2263 tmp = attackerMaxSkillValueForLevel - tmp;
2264 if(tmp >= 15)
2266 // add 2% chance per lacking skill point, min. is 15%
2267 tmp = tmp * 200 - 1500;
2268 if (roll < (sum += tmp))
2270 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2271 return MELEE_HIT_CRUSHING;
2276 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2277 return MELEE_HIT_NORMAL;
2280 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2282 float min_damage, max_damage;
2284 if (normalized && GetTypeId()==TYPEID_PLAYER)
2285 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2286 else
2288 switch (attType)
2290 case RANGED_ATTACK:
2291 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2292 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2293 break;
2294 case BASE_ATTACK:
2295 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2296 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2297 break;
2298 case OFF_ATTACK:
2299 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2300 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2301 break;
2302 // Just for good manner
2303 default:
2304 min_damage = 0.0f;
2305 max_damage = 0.0f;
2306 break;
2310 if (min_damage > max_damage)
2312 std::swap(min_damage,max_damage);
2315 if(max_damage == 0.0f)
2316 max_damage = 5.0f;
2318 return urand((uint32)min_damage, (uint32)max_damage);
2321 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2323 if(spellProto->spellLevel <= 0)
2324 return 1.0f;
2326 float LvlPenalty = 0.0f;
2328 if(spellProto->spellLevel < 20)
2329 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2330 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2331 if(LvlFactor > 1.0f)
2332 LvlFactor = 1.0f;
2334 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2337 void Unit::SendMeleeAttackStart(Unit* pVictim)
2339 WorldPacket data( SMSG_ATTACKSTART, 8 + 8 );
2340 data << uint64(GetGUID());
2341 data << uint64(pVictim->GetGUID());
2343 SendMessageToSet(&data, true);
2344 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2347 void Unit::SendMeleeAttackStop(Unit* victim)
2349 if(!victim)
2350 return;
2352 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2353 data.append(GetPackGUID());
2354 data.append(victim->GetPackGUID()); // can be 0x00...
2355 data << uint32(0); // can be 0x1
2356 SendMessageToSet(&data, true);
2357 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2359 /*if(victim->GetTypeId() == TYPEID_UNIT)
2360 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2363 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const * /*spellProto*/, WeaponAttackType attackType)
2365 if (pVictim->HasInArc(M_PI,this))
2367 /* Currently not exist spells with ignore block
2368 // Ignore combat result aura (parry/dodge check on prepare)
2369 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2370 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2372 if (!(*i)->isAffectedOnSpell(spellProto))
2373 continue;
2374 if ((*i)->GetModifier()->m_miscvalue == )
2375 return false;
2379 // Check creatures flags_extra for disable block
2380 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2381 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2382 return false;
2384 float blockChance = pVictim->GetUnitBlockChance();
2385 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2386 if (roll_chance_f(blockChance))
2387 return true;
2389 return false;
2392 // Melee based spells can be miss, parry or dodge on this step
2393 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2394 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2396 // Calculate hit chance (more correct for chance mod)
2397 int32 HitChance;
2399 // PvP - PvE melee chances
2400 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2401 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2402 if(leveldif < 3)
2403 HitChance = 95 - leveldif;
2404 else
2405 HitChance = 93 - (leveldif - 2) * lchance;
2407 // Hit chance depends from victim auras
2408 if(attType == RANGED_ATTACK)
2409 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2410 else
2411 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2413 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2414 if(Player *modOwner = GetSpellModOwner())
2415 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2417 // Miss = 100 - hit
2418 float miss_chance= 100.0f - HitChance;
2420 // Bonuses from attacker aura and ratings
2421 if (attType == RANGED_ATTACK)
2422 miss_chance -= m_modRangedHitChance;
2423 else
2424 miss_chance -= m_modMeleeHitChance;
2426 // bonus from skills is 0.04%
2427 miss_chance -= skillDiff * 0.04f;
2429 // Limit miss chance from 0 to 60%
2430 if (miss_chance < 0.0f)
2431 return 0.0f;
2432 if (miss_chance > 60.0f)
2433 return 60.0f;
2434 return miss_chance;
2437 // Melee based spells hit result calculations
2438 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2440 WeaponAttackType attType = BASE_ATTACK;
2442 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2443 attType = RANGED_ATTACK;
2445 // bonus from skills is 0.04% per skill Diff
2446 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2447 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2448 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2450 uint32 roll = urand (0, 10000);
2452 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2453 // Roll miss
2454 uint32 tmp = missChance;
2455 if (roll < tmp)
2456 return SPELL_MISS_MISS;
2458 // Chance resist mechanic (select max value from every mechanic spell effect)
2459 int32 resist_mech = 0;
2460 // Get effects mechanic and chance
2461 for(int eff = 0; eff < 3; ++eff)
2463 int32 effect_mech = GetEffectMechanic(spell, eff);
2464 if (effect_mech)
2466 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2467 if (resist_mech < temp*100)
2468 resist_mech = temp*100;
2471 // Roll chance
2472 tmp += resist_mech;
2473 if (roll < tmp)
2474 return SPELL_MISS_RESIST;
2476 bool canDodge = true;
2477 bool canParry = true;
2479 // Same spells cannot be parry/dodge
2480 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2481 return SPELL_MISS_NONE;
2483 // Ranged attack cannot be parry/dodge only deflect
2484 if (attType == RANGED_ATTACK)
2486 // only if in front
2487 if (pVictim->HasInArc(M_PI,this))
2489 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2490 tmp+=deflect_chance;
2491 if (roll < tmp)
2492 return SPELL_MISS_DEFLECT;
2494 return SPELL_MISS_NONE;
2497 // Check for attack from behind
2498 if (!pVictim->HasInArc(M_PI,this))
2500 // Can`t dodge from behind in PvP (but its possible in PvE)
2501 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2502 canDodge = false;
2503 // Can`t parry
2504 canParry = false;
2506 // Check creatures flags_extra for disable parry
2507 if(pVictim->GetTypeId()==TYPEID_UNIT)
2509 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2510 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2511 canParry = false;
2513 // Ignore combat result aura
2514 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2515 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2517 if (!(*i)->isAffectedOnSpell(spell))
2518 continue;
2519 switch((*i)->GetModifier()->m_miscvalue)
2521 case MELEE_HIT_DODGE: canDodge = false; break;
2522 case MELEE_HIT_BLOCK: break; // Block check in hit step
2523 case MELEE_HIT_PARRY: canParry = false; break;
2524 default:
2525 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2526 break;
2530 if (canDodge)
2532 // Roll dodge
2533 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2534 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2535 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2536 // Reduce dodge chance by attacker expertise rating
2537 if (GetTypeId() == TYPEID_PLAYER)
2538 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2539 if (dodgeChance < 0)
2540 dodgeChance = 0;
2542 tmp += dodgeChance;
2543 if (roll < tmp)
2544 return SPELL_MISS_DODGE;
2547 if (canParry)
2549 // Roll parry
2550 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2551 // Reduce parry chance by attacker expertise rating
2552 if (GetTypeId() == TYPEID_PLAYER)
2553 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2554 if (parryChance < 0)
2555 parryChance = 0;
2557 tmp += parryChance;
2558 if (roll < tmp)
2559 return SPELL_MISS_PARRY;
2562 return SPELL_MISS_NONE;
2565 // TODO need use unit spell resistances in calculations
2566 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2568 // Can`t miss on dead target (on skinning for example)
2569 if (!pVictim->isAlive())
2570 return SPELL_MISS_NONE;
2572 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2573 // PvP - PvE spell misschances per leveldif > 2
2574 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2575 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2577 // Base hit chance from attacker and victim levels
2578 int32 modHitChance;
2579 if(leveldif < 3)
2580 modHitChance = 96 - leveldif;
2581 else
2582 modHitChance = 94 - (leveldif - 2) * lchance;
2584 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2585 if(Player *modOwner = GetSpellModOwner())
2586 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2587 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2588 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2589 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2590 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2591 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2592 if (IsAreaOfEffectSpell(spell))
2593 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2594 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2595 if (IsDispelSpell(spell))
2596 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2597 // Chance resist mechanic (select max value from every mechanic spell effect)
2598 int32 resist_mech = 0;
2599 // Get effects mechanic and chance
2600 for(int eff = 0; eff < 3; ++eff)
2602 int32 effect_mech = GetEffectMechanic(spell, eff);
2603 if (effect_mech)
2605 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2606 if (resist_mech < temp)
2607 resist_mech = temp;
2610 // Apply mod
2611 modHitChance-=resist_mech;
2613 // Chance resist debuff
2614 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2616 int32 HitChance = modHitChance * 100;
2617 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2618 HitChance += int32(m_modSpellHitChance*100.0f);
2620 // Decrease hit chance from victim rating bonus
2621 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2622 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2624 if (HitChance < 100) HitChance = 100;
2625 if (HitChance > 10000) HitChance = 10000;
2627 int32 tmp = 10000 - HitChance;
2629 uint32 rand = urand(0,10000);
2631 if (rand < tmp)
2632 return SPELL_MISS_RESIST;
2634 // cast by caster in front of victim
2635 if (pVictim->HasInArc(M_PI,this))
2637 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2638 tmp+=deflect_chance;
2639 if (rand < tmp)
2640 return SPELL_MISS_DEFLECT;
2643 return SPELL_MISS_NONE;
2646 // Calculate spell hit result can be:
2647 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2648 // For melee based spells:
2649 // Miss
2650 // Dodge
2651 // Parry
2652 // For spells
2653 // Resist
2654 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2656 // Return evade for units in evade mode
2657 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2658 return SPELL_MISS_EVADE;
2660 // Check for immune
2661 if (pVictim->IsImmunedToSpell(spell))
2662 return SPELL_MISS_IMMUNE;
2664 // All positive spells can`t miss
2665 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2666 if (IsPositiveSpell(spell->Id))
2667 return SPELL_MISS_NONE;
2669 // Check for immune
2670 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2671 return SPELL_MISS_IMMUNE;
2673 // Try victim reflect spell
2674 if (CanReflect)
2676 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2677 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2678 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2679 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2680 reflectchance += (*i)->GetModifier()->m_amount;
2681 if (reflectchance > 0 && roll_chance_i(reflectchance))
2683 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2684 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2685 return SPELL_MISS_REFLECT;
2689 switch (spell->DmgClass)
2691 case SPELL_DAMAGE_CLASS_RANGED:
2692 case SPELL_DAMAGE_CLASS_MELEE:
2693 return MeleeSpellHitResult(pVictim, spell);
2694 case SPELL_DAMAGE_CLASS_NONE:
2695 case SPELL_DAMAGE_CLASS_MAGIC:
2696 return MagicSpellHitResult(pVictim, spell);
2698 return SPELL_MISS_NONE;
2701 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2703 if(!pVictim)
2704 return 0.0f;
2706 // Base misschance 5%
2707 float misschance = 5.0f;
2709 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2710 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2712 bool isNormal = false;
2713 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i)
2715 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2717 isNormal = true;
2718 break;
2721 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2722 misschance = 5.0f;
2723 else
2724 misschance = 24.0f;
2727 // PvP : PvE melee misschances per leveldif > 2
2728 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2730 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2731 if(leveldif < 0)
2732 leveldif = 0;
2734 // Hit chance from attacker based on ratings and auras
2735 float m_modHitChance;
2736 if (attType == RANGED_ATTACK)
2737 m_modHitChance = m_modRangedHitChance;
2738 else
2739 m_modHitChance = m_modMeleeHitChance;
2741 if(leveldif < 3)
2742 misschance += (leveldif - m_modHitChance);
2743 else
2744 misschance += ((leveldif - 2) * chance - m_modHitChance);
2746 // Hit chance for victim based on ratings
2747 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2749 if (attType == RANGED_ATTACK)
2750 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2751 else
2752 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2755 // Modify miss chance by victim auras
2756 if(attType == RANGED_ATTACK)
2757 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2758 else
2759 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2761 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2762 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2763 misschance -= skillBonus * 0.04f;
2765 // Limit miss chance from 0 to 60%
2766 if ( misschance < 0.0f)
2767 return 0.0f;
2768 if ( misschance > 60.0f)
2769 return 60.0f;
2771 return misschance;
2774 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2776 if(GetTypeId() == TYPEID_PLAYER)
2778 // in PvP use full skill instead current skill value
2779 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2780 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2781 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2782 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2783 return value;
2785 else
2786 return GetUnitMeleeSkill(target);
2789 float Unit::GetUnitDodgeChance() const
2791 if(hasUnitState(UNIT_STAT_STUNNED))
2792 return 0.0f;
2793 if( GetTypeId() == TYPEID_PLAYER )
2794 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2795 else
2797 if(((Creature const*)this)->isTotem())
2798 return 0.0f;
2799 else
2801 float dodge = 5.0f;
2802 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2803 return dodge > 0.0f ? dodge : 0.0f;
2808 float Unit::GetUnitParryChance() const
2810 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2811 return 0.0f;
2813 float chance = 0.0f;
2815 if(GetTypeId() == TYPEID_PLAYER)
2817 Player const* player = (Player const*)this;
2818 if(player->CanParry() )
2820 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2821 if(!tmpitem)
2822 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2824 if(tmpitem)
2825 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2828 else if(GetTypeId() == TYPEID_UNIT)
2830 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2832 chance = 5.0f;
2833 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2837 return chance > 0.0f ? chance : 0.0f;
2840 float Unit::GetUnitBlockChance() const
2842 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2843 return 0.0f;
2845 if(GetTypeId() == TYPEID_PLAYER)
2847 Player const* player = (Player const*)this;
2848 if(player->CanBlock() )
2850 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2851 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2852 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2854 // is player but has no block ability or no not broken shield equipped
2855 return 0.0f;
2857 else
2859 if(((Creature const*)this)->isTotem())
2860 return 0.0f;
2861 else
2863 float block = 5.0f;
2864 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2865 return block > 0.0f ? block : 0.0f;
2870 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2872 float crit;
2874 if(GetTypeId() == TYPEID_PLAYER)
2876 switch(attackType)
2878 case BASE_ATTACK:
2879 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2880 break;
2881 case OFF_ATTACK:
2882 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2883 break;
2884 case RANGED_ATTACK:
2885 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2886 break;
2887 // Just for good manner
2888 default:
2889 crit = 0.0f;
2890 break;
2893 else
2895 crit = 5.0f;
2896 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2899 // flat aura mods
2900 if(attackType == RANGED_ATTACK)
2901 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2902 else
2903 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2905 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2907 // reduce crit chance from Rating for players
2908 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2910 if (attackType==RANGED_ATTACK)
2911 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2912 else
2913 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2916 // Apply crit chance from defence skill
2917 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2919 if (crit < 0.0f)
2920 crit = 0.0f;
2921 return crit;
2924 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2926 uint32 value = 0;
2927 if(GetTypeId() == TYPEID_PLAYER)
2929 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2931 // feral or unarmed skill only for base attack
2932 if(attType != BASE_ATTACK && !item )
2933 return 0;
2935 if(IsInFeralForm())
2936 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2938 // weapon skill or (unarmed for base attack)
2939 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2941 // in PvP use full skill instead current skill value
2942 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2943 ? ((Player*)this)->GetMaxSkillValue(skill)
2944 : ((Player*)this)->GetSkillValue(skill);
2945 // Modify value from ratings
2946 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2947 switch (attType)
2949 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2950 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2951 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2954 else
2955 value = GetUnitMeleeSkill(target);
2956 return value;
2959 void Unit::_UpdateSpells( uint32 time )
2961 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2962 _UpdateAutoRepeatSpell();
2964 // remove finished spells from current pointers
2965 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
2967 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2969 m_currentSpells[i]->SetReferencedFromCurrent(false);
2970 m_currentSpells[i] = NULL; // remove pointer
2974 // update auras
2975 // m_AurasUpdateIterator can be updated in inderect called code at aura remove to skip next planned to update but removed auras
2976 for (m_AurasUpdateIterator = m_Auras.begin(); m_AurasUpdateIterator != m_Auras.end();)
2978 Aura* i_aura = m_AurasUpdateIterator->second;
2979 ++m_AurasUpdateIterator; // need shift to next for allow update if need into aura update
2980 i_aura->UpdateAura(time);
2983 // remove expired auras
2984 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2986 if ((*i).second)
2988 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2989 RemoveAura(i);
2990 else
2991 ++i;
2993 else
2994 ++i;
2997 if(!m_gameObj.empty())
2999 GameObjectList::iterator ite1, dnext1;
3000 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
3002 dnext1 = ite1;
3003 //(*i)->Update( difftime );
3004 if( !(*ite1)->isSpawned() )
3006 (*ite1)->SetOwnerGUID(0);
3007 (*ite1)->SetRespawnTime(0);
3008 (*ite1)->Delete();
3009 dnext1 = m_gameObj.erase(ite1);
3011 else
3012 ++dnext1;
3017 void Unit::_UpdateAutoRepeatSpell()
3019 //check "realtime" interrupts
3020 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
3022 // cancel wand shoot
3023 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3024 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3025 m_AutoRepeatFirstCast = true;
3026 return;
3029 //apply delay
3030 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
3031 setAttackTimer(RANGED_ATTACK,500);
3032 m_AutoRepeatFirstCast = false;
3034 //castroutine
3035 if (isAttackReady(RANGED_ATTACK))
3037 // Check if able to cast
3038 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
3040 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3041 return;
3044 // we want to shoot
3045 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
3046 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
3048 // all went good, reset attack
3049 resetAttackTimer(RANGED_ATTACK);
3053 void Unit::SetCurrentCastedSpell( Spell * pSpell )
3055 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
3057 CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer();
3059 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3061 // break same type spell if it is not delayed
3062 InterruptSpell(CSpellType,false);
3064 // special breakage effects:
3065 switch (CSpellType)
3067 case CURRENT_GENERIC_SPELL:
3069 // generic spells always break channeled not delayed spells
3070 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3072 // autorepeat breaking
3073 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3075 // break autorepeat if not Auto Shot
3076 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3077 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3078 m_AutoRepeatFirstCast = true;
3080 } break;
3082 case CURRENT_CHANNELED_SPELL:
3084 // channel spells always break generic non-delayed and any channeled spells
3085 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3086 InterruptSpell(CURRENT_CHANNELED_SPELL);
3088 // it also does break autorepeat if not Auto Shot
3089 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3090 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3091 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3092 } break;
3094 case CURRENT_AUTOREPEAT_SPELL:
3096 // only Auto Shoot does not break anything
3097 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3099 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3100 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3101 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3103 // special action: set first cast flag
3104 m_AutoRepeatFirstCast = true;
3105 } break;
3107 default:
3109 // other spell types don't break anything now
3110 } break;
3113 // current spell (if it is still here) may be safely deleted now
3114 if (m_currentSpells[CSpellType])
3115 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3117 // set new current spell
3118 m_currentSpells[CSpellType] = pSpell;
3119 pSpell->SetReferencedFromCurrent(true);
3121 pSpell->m_selfContainer = &(m_currentSpells[pSpell->GetCurrentContainer()]);
3124 void Unit::InterruptSpell(CurrentSpellTypes spellType, bool withDelayed)
3126 assert(spellType < CURRENT_MAX_SPELL);
3128 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3130 // send autorepeat cancel message for autorepeat spells
3131 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3133 if(GetTypeId() == TYPEID_PLAYER)
3134 ((Player*)this)->SendAutoRepeatCancel(this);
3137 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3138 m_currentSpells[spellType]->cancel();
3140 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3141 if (m_currentSpells[spellType])
3143 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3144 m_currentSpells[spellType] = NULL;
3149 void Unit::FinishSpell(CurrentSpellTypes spellType, bool ok /*= true*/)
3151 Spell* spell = m_currentSpells[spellType];
3152 if (!spell)
3153 return;
3155 if (spellType == CURRENT_CHANNELED_SPELL)
3156 spell->SendChannelUpdate(0);
3158 spell->finish(ok);
3162 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3164 // We don't do loop here to explicitly show that melee spell is excluded.
3165 // Maybe later some special spells will be excluded too.
3167 // generic spells are casted when they are not finished and not delayed
3168 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3169 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3170 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3171 return(true);
3173 // channeled spells may be delayed, but they are still considered casted
3174 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3175 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3176 return(true);
3178 // autorepeat spells may be finished or delayed, but they are still considered casted
3179 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3180 return(true);
3182 return(false);
3185 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3187 // generic spells are interrupted if they are not finished or delayed
3188 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3189 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3191 // autorepeat spells are interrupted if they are not finished or delayed
3192 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3193 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3195 // channeled spells are interrupted if they are not finished, even if they are delayed
3196 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3197 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3200 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3202 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
3203 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3204 return m_currentSpells[i];
3205 return NULL;
3208 void Unit::SetInFront(Unit const* target)
3210 SetOrientation(GetAngle(target));
3213 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3215 if(IsInWater())
3216 return c->canSwim();
3217 else
3218 return c->canWalk() || c->canFly();
3221 bool Unit::IsInWater() const
3223 return GetBaseMap()->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3226 bool Unit::IsUnderWater() const
3228 return GetBaseMap()->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3231 void Unit::DeMorph()
3233 SetDisplayId(GetNativeDisplayId());
3236 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3238 int32 modifier = 0;
3240 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3241 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3242 modifier += (*i)->GetModifier()->m_amount;
3244 return modifier;
3247 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3249 float multiplier = 1.0f;
3251 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3252 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3253 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3255 return multiplier;
3258 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3260 int32 modifier = 0;
3262 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3263 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3264 if ((*i)->GetModifier()->m_amount > modifier)
3265 modifier = (*i)->GetModifier()->m_amount;
3267 return modifier;
3270 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3272 int32 modifier = 0;
3274 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3275 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3276 if ((*i)->GetModifier()->m_amount < modifier)
3277 modifier = (*i)->GetModifier()->m_amount;
3279 return modifier;
3282 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3284 int32 modifier = 0;
3286 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3287 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3289 Modifier* mod = (*i)->GetModifier();
3290 if (mod->m_miscvalue & misc_mask)
3291 modifier += mod->m_amount;
3293 return modifier;
3296 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3298 float multiplier = 1.0f;
3300 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3301 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3303 Modifier* mod = (*i)->GetModifier();
3304 if (mod->m_miscvalue & misc_mask)
3305 multiplier *= (100.0f + mod->m_amount)/100.0f;
3307 return multiplier;
3310 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3312 int32 modifier = 0;
3314 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3315 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3317 Modifier* mod = (*i)->GetModifier();
3318 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3319 modifier = mod->m_amount;
3322 return modifier;
3325 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3327 int32 modifier = 0;
3329 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3330 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3332 Modifier* mod = (*i)->GetModifier();
3333 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3334 modifier = mod->m_amount;
3337 return modifier;
3340 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3342 int32 modifier = 0;
3344 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3345 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3347 Modifier* mod = (*i)->GetModifier();
3348 if (mod->m_miscvalue == misc_value)
3349 modifier += mod->m_amount;
3351 return modifier;
3354 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3356 float multiplier = 1.0f;
3358 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3359 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3361 Modifier* mod = (*i)->GetModifier();
3362 if (mod->m_miscvalue == misc_value)
3363 multiplier *= (100.0f + mod->m_amount)/100.0f;
3365 return multiplier;
3368 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3370 int32 modifier = 0;
3372 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3373 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3375 Modifier* mod = (*i)->GetModifier();
3376 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3377 modifier = mod->m_amount;
3380 return modifier;
3383 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3385 int32 modifier = 0;
3387 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3388 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3390 Modifier* mod = (*i)->GetModifier();
3391 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3392 modifier = mod->m_amount;
3395 return modifier;
3398 bool Unit::AddAura(Aura *Aur)
3400 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3402 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3403 if( !isAlive() && !IsDeathPersistentSpell(aurSpellInfo) &&
3404 Aur->GetId() != 2584 && // Waiting to Resurrect (not have death persistence flag)
3405 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3407 delete Aur;
3408 return false;
3411 if(Aur->GetTarget() != this)
3413 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3414 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3415 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3416 delete Aur;
3417 return false;
3420 // m_auraname can be modified to SPELL_AURA_NONE for area auras, this expected for this value
3421 AuraType aurName = Aur->GetModifier()->m_auraname;
3423 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3424 AuraMap::iterator i = m_Auras.find( spair );
3426 // take out same spell
3427 if (i != m_Auras.end())
3429 // passive and persistent auras can stack with themselves any number of times
3430 if (!Aur->IsPassive() && !Aur->IsPersistent())
3432 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3434 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3436 // Aura can stack on self -> Stack it;
3437 if(aurSpellInfo->StackAmount)
3439 i2->second->modStackAmount(1);
3440 delete Aur;
3441 return false;
3443 // can be only single (this check done at _each_ aura add
3444 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3445 break;
3448 bool stop = false;
3450 // m_auraname can be modified to SPELL_AURA_NONE for area auras, use original
3451 AuraType aurNameReal = AuraType(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()]);
3453 switch(aurNameReal)
3455 // DoT/HoT/etc
3456 case SPELL_AURA_DUMMY: // allow stack
3457 case SPELL_AURA_PERIODIC_DAMAGE:
3458 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3459 case SPELL_AURA_PERIODIC_LEECH:
3460 case SPELL_AURA_PERIODIC_HEAL:
3461 case SPELL_AURA_OBS_MOD_HEALTH:
3462 case SPELL_AURA_PERIODIC_MANA_LEECH:
3463 case SPELL_AURA_OBS_MOD_MANA:
3464 case SPELL_AURA_POWER_BURN_MANA:
3465 break;
3466 case SPELL_AURA_PERIODIC_ENERGIZE: // all or self or clear non-stackable
3467 default: // not allow
3468 // can be only single (this check done at _each_ aura add
3469 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3470 stop = true;
3471 break;
3474 if(stop)
3475 break;
3480 // passive auras not stacable with other ranks
3481 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3483 if (!RemoveNoStackAurasDueToAura(Aur))
3485 delete Aur;
3486 return false; // couldn't remove conflicting aura with higher rank
3490 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3491 if (Aur->IsSingleTarget() && Aur->GetTarget())
3493 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3494 for(;;)
3496 Unit* caster = Aur->GetCaster();
3497 if(!caster) // caster deleted and not required adding scAura
3498 break;
3500 bool restart = false;
3501 AuraList& scAuras = caster->GetSingleCastAuras();
3502 for(AuraList::const_iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3504 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3505 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3507 if ((*itr)->IsInUse())
3509 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());
3510 continue;
3512 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3513 restart = true;
3514 break;
3518 if(!restart)
3520 // done
3521 scAuras.push_back(Aur);
3522 break;
3527 // add aura, register in lists and arrays
3528 Aur->_AddAura();
3529 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3530 if (aurName < TOTAL_AURAS)
3532 m_modAuras[aurName].push_back(Aur);
3535 Aur->ApplyModifier(true,true);
3536 sLog.outDebug("Aura %u now is in use", aurName);
3538 // if aura deleted before boosts apply ignore
3539 // this can be possible it it removed indirectly by triggered spell effect at ApplyModifier
3540 if (Aur->IsDeleted())
3541 return false;
3543 if(IsSpellLastAuraEffect(aurSpellInfo,Aur->GetEffIndex()))
3544 Aur->HandleSpellSpecificBoosts(true);
3546 return true;
3549 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3551 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3552 if(!spellInfo)
3553 return;
3554 AuraMap::const_iterator i,next;
3555 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3557 next = i;
3558 ++next;
3559 uint32 i_spellId = (*i).second->GetId();
3560 if((*i).second && i_spellId && i_spellId != spellId)
3562 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3564 RemoveAurasDueToSpell(i_spellId);
3566 if( m_Auras.empty() )
3567 break;
3568 else
3569 next = m_Auras.begin();
3575 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3577 if (!Aur)
3578 return false;
3580 SpellEntry const* spellProto = Aur->GetSpellProto();
3581 if (!spellProto)
3582 return false;
3584 uint32 spellId = Aur->GetId();
3585 uint32 effIndex = Aur->GetEffIndex();
3587 // passive spell special case (only non stackable with ranks)
3588 if(IsPassiveSpell(spellId))
3590 if(IsPassiveSpellStackableWithRanks(spellProto))
3591 return true;
3594 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3596 AuraMap::iterator i,next;
3597 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3599 next = i;
3600 ++next;
3601 if (!(*i).second) continue;
3603 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3605 if (!i_spellProto)
3606 continue;
3608 uint32 i_spellId = i_spellProto->Id;
3610 // early checks that spellId is passive non stackable spell
3611 if(IsPassiveSpell(i_spellId))
3613 // passive non-stackable spells not stackable only for same caster
3614 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3615 continue;
3617 // passive non-stackable spells not stackable only with another rank of same spell
3618 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3619 continue;
3622 uint32 i_effIndex = (*i).second->GetEffIndex();
3624 if(i_spellId == spellId) continue;
3626 bool is_triggered_by_spell = false;
3627 // prevent triggering aura of removing aura that triggered it
3628 for(int j = 0; j < 3; ++j)
3629 if (i_spellProto->EffectTriggerSpell[j] == spellId)
3630 is_triggered_by_spell = true;
3632 // prevent triggered aura of removing aura that triggering it (triggered effect early some aura of parent spell
3633 for(int j = 0; j < 3; ++j)
3634 if (spellProto->EffectTriggerSpell[j] == i_spellId)
3635 is_triggered_by_spell = true;
3637 if (is_triggered_by_spell)
3638 continue;
3640 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3642 // single allowed spell specific from same caster or from any caster at target
3643 bool is_spellSpecPerTargetPerCaster = IsSingleFromSpellSpecificPerTargetPerCaster(spellId_spec,i_spellId_spec);
3644 bool is_spellSpecPerTarget = IsSingleFromSpellSpecificPerTarget(spellId_spec,i_spellId_spec);
3645 if( is_spellSpecPerTarget || is_spellSpecPerTargetPerCaster && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3647 // cannot remove higher rank
3648 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3649 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3650 return false;
3652 // Its a parent aura (create this aura in ApplyModifier)
3653 if ((*i).second->IsInUse())
3655 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());
3656 continue;
3658 RemoveAurasDueToSpell(i_spellId);
3660 if( m_Auras.empty() )
3661 break;
3662 else
3663 next = m_Auras.begin();
3665 continue;
3668 // spell with spell specific that allow single ranks for spell from diff caster
3669 // same caster case processed or early or later
3670 bool is_spellPerTarget = IsSingleFromSpellSpecificSpellRanksPerTarget(spellId_spec,i_spellId_spec);
3671 if ( is_spellPerTarget && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3673 // cannot remove higher rank
3674 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3675 return false;
3677 // Its a parent aura (create this aura in ApplyModifier)
3678 if ((*i).second->IsInUse())
3680 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());
3681 continue;
3683 RemoveAurasDueToSpell(i_spellId);
3685 if( m_Auras.empty() )
3686 break;
3687 else
3688 next = m_Auras.begin();
3690 continue;
3693 // non single (per caster) per target spell specific (possible single spell per target at caster)
3694 if( !is_spellSpecPerTargetPerCaster && !is_spellSpecPerTarget && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3696 // Its a parent aura (create this aura in ApplyModifier)
3697 if ((*i).second->IsInUse())
3699 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());
3700 continue;
3702 RemoveAurasDueToSpell(i_spellId);
3704 if( m_Auras.empty() )
3705 break;
3706 else
3707 next = m_Auras.begin();
3709 continue;
3712 // Potions stack aura by aura (elixirs/flask already checked)
3713 if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3715 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3717 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3718 return false; // cannot remove higher rank
3720 // Its a parent aura (create this aura in ApplyModifier)
3721 if ((*i).second->IsInUse())
3723 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());
3724 continue;
3726 RemoveAura(i);
3727 next = i;
3731 return true;
3734 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3736 spellEffectPair spair = spellEffectPair(spellId, effindex);
3737 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3739 if(iter->second!=except)
3741 RemoveAura(iter);
3742 iter = m_Auras.lower_bound(spair);
3744 else
3745 ++iter;
3749 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3751 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3753 Aura *aur = iter->second;
3754 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3755 RemoveAura(iter);
3756 else
3757 ++iter;
3761 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint32 effindex, uint64 casterGUID)
3763 spellEffectPair spair = spellEffectPair(spellId, effindex);
3764 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3766 Aura *aur = iter->second;
3767 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3769 RemoveAura(iter);
3770 iter = m_Auras.lower_bound(spair);
3772 else
3773 ++iter;
3777 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3779 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3781 Aura *aur = iter->second;
3782 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3784 // Custom dispel case
3785 // Unstable Affliction
3786 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x010000000000)))
3788 int32 damage = aur->GetModifier()->m_amount*9;
3789 uint64 caster_guid = aur->GetCasterGUID();
3791 // Remove aura
3792 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3794 // backfire damage and silence
3795 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3797 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3799 else
3800 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3802 else
3803 ++iter;
3807 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3809 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3811 Aura *aur = iter->second;
3812 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3814 int32 basePoints = aur->GetBasePoints();
3815 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3816 // some different constructors
3817 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3819 // set its duration and maximum duration
3820 // max duration 2 minutes (in msecs)
3821 int32 dur = aur->GetAuraDuration();
3822 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3823 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3824 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3826 // Unregister _before_ adding to stealer
3827 aur->UnregisterSingleCastAura();
3829 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3830 new_aur->SetIsSingleTarget(false);
3832 // add the new aura to stealer
3833 stealer->AddAura(new_aur);
3835 // Remove aura as dispel
3836 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3838 else
3839 ++iter;
3843 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3845 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3847 if (iter->second->GetId() == spellId)
3848 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3849 else
3850 ++iter;
3854 void Unit::RemoveAurasWithDispelType( DispelType type )
3856 // Create dispel mask by dispel type
3857 uint32 dispelMask = GetDispellMask(type);
3858 // Dispel all existing auras vs current dispel type
3859 AuraMap& auras = GetAuras();
3860 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3862 SpellEntry const* spell = itr->second->GetSpellProto();
3863 if( (1<<spell->Dispel) & dispelMask )
3865 // Dispel aura
3866 RemoveAurasDueToSpell(spell->Id);
3867 itr = auras.begin();
3869 else
3870 ++itr;
3874 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3876 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3877 if(iter != m_Auras.end())
3879 if (iter->second->modStackAmount(-1))
3880 RemoveAura(iter);
3884 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3886 for (int i=0; i<3; ++i)
3887 RemoveSingleAuraFromStack(spellId, i);
3890 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3892 for (int i = 0; i < 3; ++i)
3893 RemoveAura(spellId,i,except);
3896 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3898 for (int k=0; k < 3; ++k)
3900 spellEffectPair spair = spellEffectPair(spellId, k);
3901 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3903 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3905 RemoveAura(iter);
3906 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3908 else
3909 ++iter;
3914 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3916 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3918 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3919 RemoveAura(iter);
3920 else
3921 ++iter;
3925 void Unit::RemoveNotOwnSingleTargetAuras(uint32 newPhase)
3927 // single target auras from other casters
3928 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3930 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3932 if(!newPhase)
3933 RemoveAura(iter);
3934 else
3936 Unit* caster = iter->second->GetCaster();
3937 if(!caster || !caster->InSamePhase(newPhase))
3938 RemoveAura(iter);
3939 else
3940 ++iter;
3943 else
3944 ++iter;
3947 // single target auras at other targets
3948 AuraList& scAuras = GetSingleCastAuras();
3949 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3951 Aura* aura = *iter;
3952 if (aura->GetTarget() != this && !aura->GetTarget()->InSamePhase(newPhase))
3954 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3955 aura->GetTarget()->RemoveAura(aura);
3956 iter = scAuras.begin();
3958 else
3959 ++iter;
3964 void Unit::RemoveAura(Aura* aura)
3966 AuraMap::iterator i = m_Auras.lower_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
3967 AuraMap::iterator upperBound = m_Auras.upper_bound(spellEffectPair(aura->GetId(), aura->GetEffIndex()));
3968 for (; i != upperBound; ++i)
3970 if (i->second == aura)
3972 RemoveAura(i);
3973 return;
3976 sLog.outDebug("Trying to remove aura id %u effect %u by pointer but aura not found on target", aura->GetId(), aura->GetEffIndex());
3979 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3981 Aura* Aur = i->second;
3982 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3984 Aur->UnregisterSingleCastAura();
3986 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3987 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3989 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3992 // Set remove mode
3993 Aur->SetRemoveMode(mode);
3995 // if unit currently update aura list then make safe update iterator shift to next
3996 if (m_AurasUpdateIterator == i)
3997 ++m_AurasUpdateIterator;
3999 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
4000 // remove aura from list before to prevent deleting it before
4001 m_Auras.erase(i);
4003 // now aura removed from from list and can't be deleted by indirect call but can be referenced from callers
4005 // Statue unsummoned at aura remove
4006 Totem* statue = NULL;
4007 bool caster_channeled = false;
4008 if(IsChanneledSpell(AurSpellInfo))
4010 Unit* caster = Aur->GetCaster();
4012 if(caster)
4014 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
4015 statue = ((Totem*)caster);
4016 else
4017 caster_channeled = caster==this;
4021 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
4022 Aur->ApplyModifier(false,true);
4024 if(Aur->_RemoveAura())
4026 // last aura in stack removed
4027 if(IsSpellLastAuraEffect(Aur->GetSpellProto(),Aur->GetEffIndex()))
4028 Aur->HandleSpellSpecificBoosts(false);
4031 // If aura in use (removed from code that plan access to it data after return)
4032 // store it in aura list with delayed deletion
4033 if (Aur->IsInUse())
4034 m_deletedAuras.push_back(Aur);
4035 else
4036 delete Aur;
4038 if(caster_channeled)
4039 RemoveAurasAtChanneledTarget (AurSpellInfo);
4041 if(statue)
4042 statue->UnSummon();
4044 // only way correctly remove all auras from list
4045 if( m_Auras.empty() )
4046 i = m_Auras.end();
4047 else
4048 i = m_Auras.begin();
4051 void Unit::RemoveAllAuras()
4053 while (!m_Auras.empty())
4055 AuraMap::iterator iter = m_Auras.begin();
4056 RemoveAura(iter);
4060 void Unit::RemoveArenaAuras(bool onleave)
4062 // in join, remove positive buffs, on end, remove negative
4063 // used to remove positive visible auras in arenas
4064 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4066 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
4067 && !iter->second->IsPassive() // don't remove passive auras
4068 && (!(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNAFFECTED_BY_INVULNERABILITY) || !(iter->second->GetSpellProto()->Attributes & SPELL_ATTR_UNK8)) // not unaffected by invulnerability auras or not having that unknown flag (that seemed the most probable)
4069 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
4070 RemoveAura(iter);
4071 else
4072 ++iter;
4076 void Unit::RemoveAllAurasOnDeath()
4078 // used just after dieing to remove all visible auras
4079 // and disable the mods for the passive ones
4080 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
4082 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
4083 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
4084 else
4085 ++iter;
4089 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
4091 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4092 if (iter != m_Auras.end())
4094 if (iter->second->GetAuraDuration() < delaytime)
4095 iter->second->SetAuraDuration(0);
4096 else
4097 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
4098 iter->second->SendAuraUpdate(false);
4099 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
4103 void Unit::_RemoveAllAuraMods()
4105 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4107 (*i).second->ApplyModifier(false);
4111 void Unit::_ApplyAllAuraMods()
4113 for (AuraMap::const_iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
4115 (*i).second->ApplyModifier(true);
4119 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
4121 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
4122 if (iter != m_Auras.end())
4123 return iter->second;
4124 return NULL;
4127 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
4129 AuraList const& auras = GetAurasByType(type);
4130 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
4132 SpellEntry const *spell = (*i)->GetSpellProto();
4133 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
4135 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
4136 continue;
4137 return (*i);
4140 return NULL;
4143 bool Unit::HasAura(uint32 spellId) const
4145 for (int i = 0; i < 3 ; ++i)
4147 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
4148 if (iter != m_Auras.end())
4149 return true;
4151 return false;
4154 void Unit::AddDynObject(DynamicObject* dynObj)
4156 m_dynObjGUIDs.push_back(dynObj->GetGUID());
4159 void Unit::RemoveDynObject(uint32 spellid)
4161 if(m_dynObjGUIDs.empty())
4162 return;
4163 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4165 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4166 if(!dynObj)
4168 i = m_dynObjGUIDs.erase(i);
4170 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4172 dynObj->Delete();
4173 i = m_dynObjGUIDs.erase(i);
4175 else
4176 ++i;
4180 void Unit::RemoveAllDynObjects()
4182 while(!m_dynObjGUIDs.empty())
4184 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4185 if(dynObj)
4186 dynObj->Delete();
4187 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4191 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4193 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4195 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4196 if(!dynObj)
4198 i = m_dynObjGUIDs.erase(i);
4199 continue;
4202 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4203 return dynObj;
4204 ++i;
4206 return NULL;
4209 DynamicObject * Unit::GetDynObject(uint32 spellId)
4211 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4213 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4214 if(!dynObj)
4216 i = m_dynObjGUIDs.erase(i);
4217 continue;
4220 if (dynObj->GetSpellId() == spellId)
4221 return dynObj;
4222 ++i;
4224 return NULL;
4227 GameObject* Unit::GetGameObject(uint32 spellId) const
4229 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end(); ++i)
4230 if ((*i)->GetSpellId() == spellId)
4231 return *i;
4233 return NULL;
4236 void Unit::AddGameObject(GameObject* gameObj)
4238 assert(gameObj && gameObj->GetOwnerGUID()==0);
4239 m_gameObj.push_back(gameObj);
4240 gameObj->SetOwnerGUID(GetGUID());
4242 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4244 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4245 // Need disable spell use for owner
4246 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4247 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4248 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4252 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4254 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4256 gameObj->SetOwnerGUID(0);
4258 // GO created by some spell
4259 if (uint32 spellid = gameObj->GetSpellId())
4261 RemoveAurasDueToSpell(spellid);
4263 if (GetTypeId()==TYPEID_PLAYER)
4265 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4266 // Need activate spell use for owner
4267 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4268 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4269 ((Player*)this)->SendCooldownEvent(createBySpell);
4273 m_gameObj.remove(gameObj);
4275 if(del)
4277 gameObj->SetRespawnTime(0);
4278 gameObj->Delete();
4282 void Unit::RemoveGameObject(uint32 spellid, bool del)
4284 if(m_gameObj.empty())
4285 return;
4286 GameObjectList::iterator i, next;
4287 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4289 next = i;
4290 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4292 (*i)->SetOwnerGUID(0);
4293 if(del)
4295 (*i)->SetRespawnTime(0);
4296 (*i)->Delete();
4299 next = m_gameObj.erase(i);
4301 else
4302 ++next;
4306 void Unit::RemoveAllGameObjects()
4308 // remove references to unit
4309 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4311 (*i)->SetOwnerGUID(0);
4312 (*i)->SetRespawnTime(0);
4313 (*i)->Delete();
4314 i = m_gameObj.erase(i);
4318 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4320 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+4+1+4+4+1+1+4+4+1)); // we guess size
4321 data.append(log->target->GetPackGUID());
4322 data.append(log->attacker->GetPackGUID());
4323 data << uint32(log->SpellID);
4324 data << uint32(log->damage); // damage amount
4325 data << uint32(log->overkill); // overkill
4326 data << uint8 (log->schoolMask); // damage school
4327 data << uint32(log->absorb); // AbsorbedDamage
4328 data << uint32(log->resist); // resist
4329 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
4330 data << uint8 (log->unused); // unused
4331 data << uint32(log->blocked); // blocked
4332 data << uint32(log->HitInfo);
4333 data << uint8 (0); // flag to use extend data
4334 SendMessageToSet( &data, true );
4337 void Unit::SendSpellNonMeleeDamageLog(Unit *target, uint32 SpellID, uint32 Damage, SpellSchoolMask damageSchoolMask, uint32 AbsorbedDamage, uint32 Resist, bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4339 SpellNonMeleeDamage log(this, target, SpellID, damageSchoolMask);
4340 log.damage = Damage - AbsorbedDamage - Resist - Blocked;
4341 log.absorb = AbsorbedDamage;
4342 log.resist = Resist;
4343 log.physicalLog = PhysicalDamage;
4344 log.blocked = Blocked;
4345 log.HitInfo = SPELL_HIT_TYPE_UNK1 | SPELL_HIT_TYPE_UNK3 | SPELL_HIT_TYPE_UNK6;
4346 if(CriticalHit)
4347 log.HitInfo |= SPELL_HIT_TYPE_CRIT;
4348 SendSpellNonMeleeDamageLog(&log);
4351 void Unit::SendPeriodicAuraLog(SpellPeriodicAuraLogInfo *pInfo)
4353 Aura *aura = pInfo->aura;
4354 Modifier *mod = aura->GetModifier();
4356 WorldPacket data(SMSG_PERIODICAURALOG, 30);
4357 data.append(aura->GetTarget()->GetPackGUID());
4358 data.appendPackGUID(aura->GetCasterGUID());
4359 data << uint32(aura->GetId()); // spellId
4360 data << uint32(1); // count
4361 data << uint32(mod->m_auraname); // auraId
4362 switch(mod->m_auraname)
4364 case SPELL_AURA_PERIODIC_DAMAGE:
4365 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
4366 data << uint32(pInfo->damage); // damage
4367 data << uint32(pInfo->overDamage); // overkill?
4368 data << uint32(GetSpellSchoolMask(aura->GetSpellProto()));
4369 data << uint32(pInfo->absorb); // absorb
4370 data << uint32(pInfo->resist); // resist
4371 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4372 break;
4373 case SPELL_AURA_PERIODIC_HEAL:
4374 case SPELL_AURA_OBS_MOD_HEALTH:
4375 data << uint32(pInfo->damage); // damage
4376 data << uint32(pInfo->overDamage); // overheal?
4377 data << uint8(pInfo->critical ? 1 : 0); // new 3.1.2 critical flag
4378 break;
4379 case SPELL_AURA_OBS_MOD_MANA:
4380 case SPELL_AURA_PERIODIC_ENERGIZE:
4381 data << uint32(mod->m_miscvalue); // power type
4382 data << uint32(pInfo->damage); // damage
4383 break;
4384 case SPELL_AURA_PERIODIC_MANA_LEECH:
4385 data << uint32(mod->m_miscvalue); // power type
4386 data << uint32(pInfo->damage); // amount
4387 data << float(pInfo->multiplier); // gain multiplier
4388 break;
4389 default:
4390 sLog.outError("Unit::SendPeriodicAuraLog: unknown aura %u", uint32(mod->m_auraname));
4391 return;
4394 aura->GetTarget()->SendMessageToSet(&data, true);
4397 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4399 // Not much to do if no flags are set.
4400 if (procAttacker)
4401 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4402 // Now go on with a victim's events'n'auras
4403 // Not much to do if no flags are set or there is no victim
4404 if(pVictim && pVictim->isAlive() && procVictim)
4405 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4408 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4410 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4411 data << uint32(spellID);
4412 data << uint64(GetGUID());
4413 data << uint8(0); // can be 0 or 1
4414 data << uint32(1); // target count
4415 // for(i = 0; i < target count; ++i)
4416 data << uint64(target->GetGUID()); // target GUID
4417 data << uint8(missInfo);
4418 // end loop
4419 SendMessageToSet(&data, true);
4422 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4424 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4426 uint32 count = 1;
4427 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, 16 + 45); // we guess size
4428 data << uint32(damageInfo->HitInfo);
4429 data.append(damageInfo->attacker->GetPackGUID());
4430 data.append(damageInfo->target->GetPackGUID());
4431 data << uint32(damageInfo->damage); // Full damage
4432 data << uint32(0); // overkill value
4433 data << uint8(count); // Sub damage count
4435 for(int i = 0; i < count; ++i)
4437 data << uint32(damageInfo->damageSchoolMask); // School of sub damage
4438 data << float(damageInfo->damage); // sub damage
4439 data << uint32(damageInfo->damage); // Sub Damage
4442 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4444 for(int i = 0; i < count; ++i)
4445 data << uint32(damageInfo->absorb); // Absorb
4448 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4450 for(int i = 0; i < count; ++i)
4451 data << uint32(damageInfo->resist); // Resist
4454 data << uint8(damageInfo->TargetState);
4455 data << uint32(0);
4456 data << uint32(0);
4458 if(damageInfo->HitInfo & HITINFO_BLOCK)
4459 data << uint32(damageInfo->blocked_amount);
4461 if(damageInfo->HitInfo & HITINFO_UNK3)
4462 data << uint32(0);
4464 if(damageInfo->HitInfo & HITINFO_UNK1)
4466 data << uint32(0);
4467 data << float(0);
4468 data << float(0);
4469 data << float(0);
4470 data << float(0);
4471 data << float(0);
4472 data << float(0);
4473 data << float(0);
4474 data << float(0);
4475 for(uint8 i = 0; i < 5; ++i)
4477 data << float(0);
4478 data << float(0);
4480 data << uint32(0);
4483 SendMessageToSet( &data, true );
4486 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4488 CalcDamageInfo dmgInfo;
4489 dmgInfo.HitInfo = HitInfo;
4490 dmgInfo.attacker = this;
4491 dmgInfo.target = target;
4492 dmgInfo.damage = Damage - AbsorbDamage - Resist - BlockedAmount;
4493 dmgInfo.damageSchoolMask = damageSchoolMask;
4494 dmgInfo.absorb = AbsorbDamage;
4495 dmgInfo.resist = Resist;
4496 dmgInfo.TargetState = TargetState;
4497 dmgInfo.blocked_amount = BlockedAmount;
4498 SendAttackStateUpdate(&dmgInfo);
4501 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4503 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4505 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4506 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4508 uint32 triggered_spell_id = 0;
4509 Unit* target = pVictim;
4510 int32 basepoints0 = 0;
4512 switch(hasteSpell->SpellFamilyName)
4514 case SPELLFAMILY_ROGUE:
4516 switch(hasteSpell->Id)
4518 // Blade Flurry
4519 case 13877:
4520 case 33735:
4522 target = SelectNearbyTarget(pVictim);
4523 if(!target)
4524 return false;
4525 basepoints0 = damage;
4526 triggered_spell_id = 22482;
4527 break;
4530 break;
4534 // processed charge only counting case
4535 if(!triggered_spell_id)
4536 return true;
4538 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4540 if(!triggerEntry)
4542 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4543 return false;
4546 // default case
4547 if(!target || target!=this && !target->isAlive())
4548 return false;
4550 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4551 return false;
4553 if(basepoints0)
4554 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4555 else
4556 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4558 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4559 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4561 return true;
4564 bool Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4566 SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto();
4568 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4569 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4571 uint32 triggered_spell_id = 0;
4572 Unit* target = pVictim;
4573 int32 basepoints0 = 0;
4575 switch(triggeredByAuraSpell->SpellFamilyName)
4577 case SPELLFAMILY_MAGE:
4579 switch(triggeredByAuraSpell->Id)
4581 // Focus Magic
4582 case 54646:
4584 Unit* caster = triggeredByAura->GetCaster();
4585 if(!caster)
4586 return false;
4588 triggered_spell_id = 54648;
4589 target = caster;
4590 break;
4596 // processed charge only counting case
4597 if(!triggered_spell_id)
4598 return true;
4600 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4602 if(!triggerEntry)
4604 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id);
4605 return false;
4608 // default case
4609 if(!target || target!=this && !target->isAlive())
4610 return false;
4612 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4613 return false;
4615 if(basepoints0)
4616 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4617 else
4618 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4620 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4621 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4623 return true;
4626 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4628 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4629 uint32 effIndex = triggeredByAura->GetEffIndex();
4630 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4632 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4633 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4635 uint32 triggered_spell_id = 0;
4636 Unit* target = pVictim;
4637 int32 basepoints0 = 0;
4639 switch(dummySpell->SpellFamilyName)
4641 case SPELLFAMILY_GENERIC:
4643 switch (dummySpell->Id)
4645 // Eye for an Eye
4646 case 9799:
4647 case 25988:
4649 // return damage % to attacker but < 50% own total health
4650 basepoints0 = triggerAmount*int32(damage)/100;
4651 if(basepoints0 > GetMaxHealth()/2)
4652 basepoints0 = GetMaxHealth()/2;
4654 triggered_spell_id = 25997;
4655 break;
4657 // Sweeping Strikes (NPC spells may be)
4658 case 18765:
4659 case 35429:
4661 // prevent chain of triggered spell from same triggered spell
4662 if(procSpell && procSpell->Id == 26654)
4663 return false;
4665 target = SelectNearbyTarget(pVictim);
4666 if(!target)
4667 return false;
4669 triggered_spell_id = 26654;
4670 break;
4672 // Unstable Power
4673 case 24658:
4675 if (!procSpell || procSpell->Id == 24659)
4676 return false;
4677 // Need remove one 24659 aura
4678 RemoveSingleSpellAurasFromStack(24659);
4679 return true;
4681 // Restless Strength
4682 case 24661:
4684 // Need remove one 24662 aura
4685 RemoveSingleSpellAurasFromStack(24662);
4686 return true;
4688 // Adaptive Warding (Frostfire Regalia set)
4689 case 28764:
4691 if(!procSpell)
4692 return false;
4694 // find Mage Armor
4695 bool found = false;
4696 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4697 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4699 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4701 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000)))
4703 found=true;
4704 break;
4708 if(!found)
4709 return false;
4711 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4713 case SPELL_SCHOOL_NORMAL:
4714 case SPELL_SCHOOL_HOLY:
4715 return false; // ignored
4716 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4717 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4718 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4719 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4720 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4721 default:
4722 return false;
4725 target = this;
4726 break;
4728 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4729 case 27539:
4731 if(!procSpell)
4732 return false;
4734 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4736 case SPELL_SCHOOL_NORMAL:
4737 return false; // ignore
4738 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4739 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4740 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4741 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4742 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4743 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4744 default:
4745 return false;
4748 target = this;
4749 break;
4751 // Mana Leech (Passive) (Priest Pet Aura)
4752 case 28305:
4754 // Cast on owner
4755 target = GetOwner();
4756 if(!target)
4757 return false;
4759 triggered_spell_id = 34650;
4760 break;
4762 // Mark of Malice
4763 case 33493:
4765 // Cast finish spell at last charge
4766 if (triggeredByAura->GetAuraCharges() > 1)
4767 return false;
4769 target = this;
4770 triggered_spell_id = 33494;
4771 break;
4773 // Twisted Reflection (boss spell)
4774 case 21063:
4775 triggered_spell_id = 21064;
4776 break;
4777 // Vampiric Aura (boss spell)
4778 case 38196:
4780 basepoints0 = 3 * damage; // 300%
4781 if (basepoints0 < 0)
4782 return false;
4784 triggered_spell_id = 31285;
4785 target = this;
4786 break;
4788 // Aura of Madness (Darkmoon Card: Madness trinket)
4789 //=====================================================
4790 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4791 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4792 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4793 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4794 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4795 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4796 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4797 // 41011 Martyr Complex: +35 stamina (All classes)
4798 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4799 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4800 case 39446:
4802 if(GetTypeId() != TYPEID_PLAYER)
4803 return false;
4805 // Select class defined buff
4806 switch (getClass())
4808 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4809 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4811 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4812 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4813 break;
4815 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4816 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4818 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4819 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4820 break;
4822 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4823 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4824 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4825 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4827 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4828 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4829 break;
4831 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4833 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4834 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4835 break;
4837 default:
4838 return false;
4841 target = this;
4842 if (roll_chance_i(10))
4843 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4844 break;
4847 // Sunwell Exalted Caster Neck (??? neck)
4848 // cast ??? Light's Wrath if Exalted by Aldor
4849 // cast ??? Arcane Bolt if Exalted by Scryers*/
4850 case 46569:
4851 return false; // old unused version
4852 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4853 // cast 45479 Light's Wrath if Exalted by Aldor
4854 // cast 45429 Arcane Bolt if Exalted by Scryers
4855 case 45481:
4857 if(GetTypeId() != TYPEID_PLAYER)
4858 return false;
4860 // Get Aldor reputation rank
4861 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4863 target = this;
4864 triggered_spell_id = 45479;
4865 break;
4867 // Get Scryers reputation rank
4868 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4870 // triggered at positive/self casts also, current attack target used then
4871 if(IsFriendlyTo(target))
4873 target = getVictim();
4874 if(!target)
4876 uint64 selected_guid = ((Player *)this)->GetSelection();
4877 target = ObjectAccessor::GetUnit(*this,selected_guid);
4878 if(!target)
4879 return false;
4881 if(IsFriendlyTo(target))
4882 return false;
4885 triggered_spell_id = 45429;
4886 break;
4888 return false;
4890 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4891 // cast 45480 Light's Strength if Exalted by Aldor
4892 // cast 45428 Arcane Strike if Exalted by Scryers
4893 case 45482:
4895 if(GetTypeId() != TYPEID_PLAYER)
4896 return false;
4898 // Get Aldor reputation rank
4899 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4901 target = this;
4902 triggered_spell_id = 45480;
4903 break;
4905 // Get Scryers reputation rank
4906 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4908 triggered_spell_id = 45428;
4909 break;
4911 return false;
4913 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4914 // cast 45431 Arcane Insight if Exalted by Aldor
4915 // cast 45432 Light's Ward if Exalted by Scryers
4916 case 45483:
4918 if(GetTypeId() != TYPEID_PLAYER)
4919 return false;
4921 // Get Aldor reputation rank
4922 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4924 target = this;
4925 triggered_spell_id = 45432;
4926 break;
4928 // Get Scryers reputation rank
4929 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4931 target = this;
4932 triggered_spell_id = 45431;
4933 break;
4935 return false;
4937 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4938 // cast 45478 Light's Salvation if Exalted by Aldor
4939 // cast 45430 Arcane Surge if Exalted by Scryers
4940 case 45484:
4942 if(GetTypeId() != TYPEID_PLAYER)
4943 return false;
4945 // Get Aldor reputation rank
4946 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4948 target = this;
4949 triggered_spell_id = 45478;
4950 break;
4952 // Get Scryers reputation rank
4953 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4955 triggered_spell_id = 45430;
4956 break;
4958 return false;
4960 // Living Seed
4961 case 48504:
4963 triggered_spell_id = 48503;
4964 basepoints0 = triggerAmount;
4965 target = this;
4966 break;
4968 // Vampiric Touch (generic, used by some boss)
4969 case 52723:
4970 case 60501:
4972 triggered_spell_id = 52724;
4973 basepoints0 = damage / 2;
4974 target = this;
4975 break;
4977 // Divine purpose
4978 case 31871:
4979 case 31872:
4981 // Roll chane
4982 if (!roll_chance_i(triggerAmount))
4983 return false;
4985 // Remove any stun effect on target
4986 AuraMap& Auras = pVictim->GetAuras();
4987 for(AuraMap::const_iterator iter = Auras.begin(); iter != Auras.end();)
4989 SpellEntry const *spell = iter->second->GetSpellProto();
4990 if( spell->Mechanic == MECHANIC_STUN ||
4991 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4993 pVictim->RemoveAurasDueToSpell(spell->Id);
4994 iter = Auras.begin();
4996 else
4997 ++iter;
4999 return true;
5002 break;
5004 case SPELLFAMILY_MAGE:
5006 // Magic Absorption
5007 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
5009 if (getPowerType() != POWER_MANA)
5010 return false;
5012 // mana reward
5013 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
5014 target = this;
5015 triggered_spell_id = 29442;
5016 break;
5018 // Master of Elements
5019 if (dummySpell->SpellIconID == 1920)
5021 if(!procSpell)
5022 return false;
5024 // mana cost save
5025 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5026 basepoints0 = cost * triggerAmount/100;
5027 if( basepoints0 <=0 )
5028 return false;
5030 target = this;
5031 triggered_spell_id = 29077;
5032 break;
5035 // Arcane Potency
5036 if (dummySpell->SpellIconID == 2120)
5038 if(!procSpell)
5039 return false;
5041 target = this;
5042 switch (dummySpell->Id)
5044 case 31571: triggered_spell_id = 57529; break;
5045 case 31572: triggered_spell_id = 57531; break;
5046 default:
5047 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id);
5048 return false;
5050 break;
5053 // Hot Streak
5054 if (dummySpell->SpellIconID == 2999)
5056 if (effIndex!=0)
5057 return true;
5058 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
5059 if (!counter)
5060 return true;
5062 // Count spell criticals in a row in second aura
5063 Modifier *mod = counter->GetModifier();
5064 if (procEx & PROC_EX_CRITICAL_HIT)
5066 mod->m_amount *=2;
5067 if (mod->m_amount < 100) // not enough
5068 return true;
5069 // Crititcal counted -> roll chance
5070 if (roll_chance_i(triggerAmount))
5071 CastSpell(this, 48108, true, castItem, triggeredByAura);
5073 mod->m_amount = 25;
5074 return true;
5076 // Burnout
5077 if (dummySpell->SpellIconID == 2998)
5079 if(!procSpell)
5080 return false;
5082 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5083 basepoints0 = cost * triggerAmount/100;
5084 if( basepoints0 <=0 )
5085 return false;
5086 triggered_spell_id = 44450;
5087 target = this;
5088 break;
5090 // Incanter's Regalia set (add trigger chance to Mana Shield)
5091 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5093 if(GetTypeId() != TYPEID_PLAYER)
5094 return false;
5096 target = this;
5097 triggered_spell_id = 37436;
5098 break;
5100 switch(dummySpell->Id)
5102 // Ignite
5103 case 11119:
5104 case 11120:
5105 case 12846:
5106 case 12847:
5107 case 12848:
5109 switch (dummySpell->Id)
5111 case 11119: basepoints0 = int32(0.04f*damage); break;
5112 case 11120: basepoints0 = int32(0.08f*damage); break;
5113 case 12846: basepoints0 = int32(0.12f*damage); break;
5114 case 12847: basepoints0 = int32(0.16f*damage); break;
5115 case 12848: basepoints0 = int32(0.20f*damage); break;
5116 default:
5117 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
5118 return false;
5121 triggered_spell_id = 12654;
5122 break;
5124 // Combustion
5125 case 11129:
5127 //last charge and crit
5128 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
5130 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
5131 return true; // charge counting (will removed)
5134 CastSpell(this, 28682, true, castItem, triggeredByAura);
5135 return (procEx & PROC_EX_CRITICAL_HIT); // charge update only at crit hits, no hidden cooldowns
5138 break;
5140 case SPELLFAMILY_WARRIOR:
5142 // Retaliation
5143 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000))
5145 // check attack comes not from behind
5146 if (!HasInArc(M_PI, pVictim))
5147 return false;
5149 triggered_spell_id = 22858;
5150 break;
5152 // Second Wind
5153 if (dummySpell->SpellIconID == 1697)
5155 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
5156 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5157 return false;
5158 // Need stun or root mechanic
5159 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
5160 return false;
5162 switch (dummySpell->Id)
5164 case 29838: triggered_spell_id=29842; break;
5165 case 29834: triggered_spell_id=29841; break;
5166 case 42770: triggered_spell_id=42771; break;
5167 default:
5168 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
5169 return false;
5172 target = this;
5173 break;
5175 // Damage Shield
5176 if (dummySpell->SpellIconID == 3214)
5178 triggered_spell_id = 59653;
5179 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
5180 break;
5183 // Sweeping Strikes
5184 if (dummySpell->Id == 12328)
5186 // prevent chain of triggered spell from same triggered spell
5187 if(procSpell && procSpell->Id == 26654)
5188 return false;
5190 target = SelectNearbyTarget(pVictim);
5191 if(!target)
5192 return false;
5194 triggered_spell_id = 26654;
5195 break;
5197 break;
5199 case SPELLFAMILY_WARLOCK:
5201 // Seed of Corruption
5202 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
5204 Modifier* mod = triggeredByAura->GetModifier();
5205 // if damage is more than need or target die from damage deal finish spell
5206 if( mod->m_amount <= damage || GetHealth() <= damage )
5208 // remember guid before aura delete
5209 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5211 // Remove aura (before cast for prevent infinite loop handlers)
5212 RemoveAurasDueToSpell(triggeredByAura->GetId());
5214 // Cast finish spell (triggeredByAura already not exist!)
5215 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
5216 return true; // no hidden cooldown
5219 // Damage counting
5220 mod->m_amount-=damage;
5221 return true;
5223 // Seed of Corruption (Mobs cast) - no die req
5224 if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932)
5226 Modifier* mod = triggeredByAura->GetModifier();
5227 // if damage is more than need deal finish spell
5228 if( mod->m_amount <= damage )
5230 // remember guid before aura delete
5231 uint64 casterGuid = triggeredByAura->GetCasterGUID();
5233 // Remove aura (before cast for prevent infinite loop handlers)
5234 RemoveAurasDueToSpell(triggeredByAura->GetId());
5236 // Cast finish spell (triggeredByAura already not exist!)
5237 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5238 return true; // no hidden cooldown
5240 // Damage counting
5241 mod->m_amount-=damage;
5242 return true;
5244 // Fel Synergy
5245 if (dummySpell->SpellIconID == 3222)
5247 target = GetPet();
5248 if (!target)
5249 return false;
5250 basepoints0 = damage * triggerAmount / 100;
5251 triggered_spell_id = 54181;
5252 break;
5254 switch(dummySpell->Id)
5256 // Nightfall
5257 case 18094:
5258 case 18095:
5260 target = this;
5261 triggered_spell_id = 17941;
5262 break;
5264 //Soul Leech
5265 case 30293:
5266 case 30295:
5267 case 30296:
5269 // health
5270 basepoints0 = int32(damage*triggerAmount/100);
5271 target = this;
5272 triggered_spell_id = 30294;
5273 break;
5275 // Shadowflame (Voidheart Raiment set bonus)
5276 case 37377:
5278 triggered_spell_id = 37379;
5279 break;
5281 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5282 case 37381:
5284 target = GetPet();
5285 if(!target)
5286 return false;
5288 // heal amount
5289 basepoints0 = damage * triggerAmount/100;
5290 triggered_spell_id = 37382;
5291 break;
5293 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5294 case 39437:
5296 triggered_spell_id = 37378;
5297 break;
5299 // Siphon Life
5300 case 63108:
5302 basepoints0 = int32(damage * triggerAmount / 100);
5303 triggered_spell_id = 63106;
5304 break;
5307 break;
5309 case SPELLFAMILY_PRIEST:
5311 // Vampiric Touch
5312 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
5314 if(!pVictim || !pVictim->isAlive())
5315 return false;
5317 // pVictim is caster of aura
5318 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5319 return false;
5321 // Energize 0.25% of max. mana
5322 pVictim->CastSpell(pVictim,57669,true,castItem,triggeredByAura);
5323 return true; // no hidden cooldown
5326 // Divine Aegis
5327 if (dummySpell->SpellIconID == 2820)
5329 basepoints0 = damage * triggerAmount/100;
5330 triggered_spell_id = 47753;
5331 break;
5333 // Improved Shadowform
5334 else if (dummySpell->SpellIconID == 217)
5336 if(!roll_chance_i(triggerAmount))
5337 return false;
5339 RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT);
5340 RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED);
5341 break;
5344 switch(dummySpell->Id)
5346 // Vampiric Embrace
5347 case 15286:
5349 if(!pVictim || !pVictim->isAlive())
5350 return false;
5352 // pVictim is caster of aura
5353 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5354 return false;
5356 // heal amount
5357 int32 team = triggerAmount*damage/500;
5358 int32 self = triggerAmount*damage/100 - team;
5359 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5360 return true; // no hidden cooldown
5362 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5363 case 40438:
5365 // Shadow Word: Pain
5366 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000))
5367 triggered_spell_id = 40441;
5368 // Renew
5369 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5370 triggered_spell_id = 40440;
5371 else
5372 return false;
5374 target = this;
5375 break;
5377 // Oracle Healing Bonus ("Garments of the Oracle" set)
5378 case 26169:
5380 // heal amount
5381 basepoints0 = int32(damage * 10/100);
5382 target = this;
5383 triggered_spell_id = 26170;
5384 break;
5386 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5387 case 39372:
5389 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5390 return false;
5392 // heal amount
5393 basepoints0 = damage * triggerAmount/100;
5394 target = this;
5395 triggered_spell_id = 39373;
5396 break;
5398 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5399 case 28809:
5401 triggered_spell_id = 28810;
5402 break;
5404 // Glyph of Dispel Magic
5405 case 55677:
5407 if(!target->IsFriendlyTo(this))
5408 return false;
5410 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5411 triggered_spell_id = 56131;
5412 break;
5415 break;
5417 case SPELLFAMILY_DRUID:
5419 switch(dummySpell->Id)
5421 // Healing Touch (Dreamwalker Raiment set)
5422 case 28719:
5424 // mana back
5425 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5426 target = this;
5427 triggered_spell_id = 28742;
5428 break;
5430 // Healing Touch Refund (Idol of Longevity trinket)
5431 case 28847:
5433 target = this;
5434 triggered_spell_id = 28848;
5435 break;
5437 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5438 case 37288:
5439 case 37295:
5441 target = this;
5442 triggered_spell_id = 37238;
5443 break;
5445 // Druid Tier 6 Trinket
5446 case 40442:
5448 float chance;
5450 // Starfire
5451 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5453 triggered_spell_id = 40445;
5454 chance = 25.0f;
5456 // Rejuvenation
5457 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010))
5459 triggered_spell_id = 40446;
5460 chance = 25.0f;
5462 // Mangle (Bear) and Mangle (Cat)
5463 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000))
5465 triggered_spell_id = 40452;
5466 chance = 40.0f;
5468 else
5469 return false;
5471 if (!roll_chance_f(chance))
5472 return false;
5474 target = this;
5475 break;
5477 // Maim Interrupt
5478 case 44835:
5480 // Deadly Interrupt Effect
5481 triggered_spell_id = 32747;
5482 break;
5485 // Eclipse
5486 if (dummySpell->SpellIconID == 2856)
5488 if (!procSpell)
5489 return false;
5490 // Only 0 aura can proc
5491 if (effIndex!=0)
5492 return true;
5493 // Wrath crit
5494 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
5496 if (!roll_chance_i(60))
5497 return false;
5498 triggered_spell_id = 48518;
5499 target = this;
5500 break;
5502 // Starfire crit
5503 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004))
5505 triggered_spell_id = 48517;
5506 target = this;
5507 break;
5509 return false;
5511 // Living Seed
5512 else if (dummySpell->SpellIconID == 2860)
5514 triggered_spell_id = 48504;
5515 basepoints0 = triggerAmount * damage / 100;
5516 break;
5518 break;
5520 case SPELLFAMILY_ROGUE:
5522 switch(dummySpell->Id)
5524 // Deadly Throw Interrupt
5525 case 32748:
5527 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5528 if (this == pVictim)
5529 return false;
5531 triggered_spell_id = 32747;
5532 break;
5535 // Cut to the Chase
5536 if (dummySpell->SpellIconID == 2909)
5538 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5539 // lookup Slice and Dice
5540 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5541 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5543 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5544 if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5545 (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000)))
5547 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5548 (*itr)->RefreshAura();
5549 return true;
5552 return false;
5554 // Deadly Brew
5555 if (dummySpell->SpellIconID == 2963)
5557 triggered_spell_id = 44289;
5558 break;
5560 // Quick Recovery
5561 if (dummySpell->SpellIconID == 2116)
5563 if(!procSpell)
5564 return false;
5566 // energy cost save
5567 basepoints0 = procSpell->manaCost * triggerAmount/100;
5568 if (basepoints0 <= 0)
5569 return false;
5571 target = this;
5572 triggered_spell_id = 31663;
5573 break;
5575 break;
5577 case SPELLFAMILY_HUNTER:
5579 // Aspect of the Viper
5580 if (dummySpell->SpellFamilyFlags & UI64LIT(0x4000000000000))
5582 uint32 maxmana = GetMaxPower(POWER_MANA);
5583 basepoints0 = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f);
5585 target = this;
5586 triggered_spell_id = 34075;
5587 break;
5589 // Thrill of the Hunt
5590 if (dummySpell->SpellIconID == 2236)
5592 if(!procSpell)
5593 return false;
5595 // mana cost save
5596 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5597 basepoints0 = mana * 40/100;
5598 if(basepoints0 <= 0)
5599 return false;
5601 target = this;
5602 triggered_spell_id = 34720;
5603 break;
5605 // Hunting Party
5606 if ( dummySpell->SpellIconID == 3406 )
5608 triggered_spell_id = 57669;
5609 target = this;
5610 break;
5612 // Lock and Load
5613 if ( dummySpell->SpellIconID == 3579 )
5615 // Proc only from periodic (from trap activation proc another aura of this spell)
5616 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5617 return false;
5618 triggered_spell_id = 56453;
5619 target = this;
5620 break;
5622 // Rapid Recuperation
5623 if ( dummySpell->SpellIconID == 3560 )
5625 // This effect only from Rapid Killing (mana regen)
5626 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000)))
5627 return false;
5628 triggered_spell_id = 56654;
5629 target = this;
5630 break;
5632 break;
5634 case SPELLFAMILY_PALADIN:
5636 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5637 if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex==0)
5639 triggered_spell_id = 25742;
5640 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5641 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5642 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5643 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5644 break;
5646 // Sacred Shield
5647 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0008000000000000))
5649 triggered_spell_id = 58597;
5650 target = this;
5651 break;
5653 // Righteous Vengeance
5654 if (dummySpell->SpellIconID == 3025)
5656 // 4 damage tick
5657 basepoints0 = triggerAmount*damage/400;
5658 triggered_spell_id = 61840;
5659 break;
5661 // Sheath of Light
5662 if (dummySpell->SpellIconID == 3030)
5664 // 4 healing tick
5665 basepoints0 = triggerAmount*damage/400;
5666 triggered_spell_id = 54203;
5667 break;
5669 switch(dummySpell->Id)
5671 // Judgement of Light
5672 case 20185:
5674 // Get judgement caster
5675 Unit *caster = triggeredByAura->GetCaster();
5676 if (!caster)
5677 return false;
5678 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5679 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5680 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5681 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5682 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
5683 return true;
5685 // Judgement of Wisdom
5686 case 20186:
5688 if (pVictim->getPowerType() == POWER_MANA)
5690 // 2% of maximum base mana
5691 basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100);
5692 pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
5694 return true;
5696 // Judgements of the Wise
5697 case 31876:
5698 case 31877:
5699 case 31878:
5700 // triggered only at casted Judgement spells, not at additional Judgement effects
5701 if(!procSpell || procSpell->Category != 1210)
5702 return false;
5704 target = this;
5705 triggered_spell_id = 31930;
5707 // Replenishment
5708 CastSpell(this, 57669, true, NULL, triggeredByAura);
5709 break;
5710 // Holy Power (Redemption Armor set)
5711 case 28789:
5713 if(!pVictim)
5714 return false;
5716 // Set class defined buff
5717 switch (pVictim->getClass())
5719 case CLASS_PALADIN:
5720 case CLASS_PRIEST:
5721 case CLASS_SHAMAN:
5722 case CLASS_DRUID:
5723 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5724 break;
5725 case CLASS_MAGE:
5726 case CLASS_WARLOCK:
5727 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5728 break;
5729 case CLASS_HUNTER:
5730 case CLASS_ROGUE:
5731 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5732 break;
5733 case CLASS_WARRIOR:
5734 triggered_spell_id = 28790; // Increases the friendly target's armor
5735 break;
5736 default:
5737 return false;
5739 break;
5741 case 25899: // Greater Blessing of Sanctuary
5742 case 20911: // Blessing of Sanctuary
5744 target = this;
5745 switch (target->getPowerType())
5747 case POWER_MANA:
5748 triggered_spell_id = 57319;
5749 break;
5750 default:
5751 return false;
5753 break;
5755 // Seal of Vengeance (damage calc on apply aura)
5756 case 31801:
5758 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5759 return false;
5761 triggered_spell_id = 31803;
5763 // Add 5-stack effect
5764 int8 stacks = 0;
5765 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
5766 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
5768 if( ((*itr)->GetId() == 31803) && (*itr)->GetCasterGUID()==GetGUID())
5770 stacks = (*itr)->GetStackAmount();
5771 break;
5774 if(stacks >= 5)
5775 CastSpell(target,42463,true,NULL,triggeredByAura);
5776 break;
5778 // Seal of Corruption (damage calc on apply aura)
5779 case 53736:
5781 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5782 return false;
5784 triggered_spell_id = 53742;
5786 // Add 5-stack effect
5787 int8 stacks = 0;
5788 AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
5789 for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr)
5791 if( ((*itr)->GetId() == 53742) && (*itr)->GetCasterGUID()==GetGUID())
5793 stacks = (*itr)->GetStackAmount();
5794 break;
5797 if(stacks >= 5)
5798 CastSpell(target,53739,true,NULL,triggeredByAura);
5799 break;
5801 // Spiritual Attunement
5802 case 31785:
5803 case 33776:
5805 // if healed by another unit (pVictim)
5806 if(this == pVictim)
5807 return false;
5809 // heal amount
5810 basepoints0 = triggerAmount*damage/100;
5811 target = this;
5812 triggered_spell_id = 31786;
5813 break;
5815 // Seal of Blood do damage trigger
5816 case 31892:
5818 // 0 effect - is proc on enemy
5819 if (effIndex == 0 && (procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT))
5820 triggered_spell_id = 31893;
5821 else
5822 return true;
5823 break;
5825 // Light's Beacon (heal target area aura)
5826 case 53651:
5828 // not do bonus heal for explicit beacon focus healing
5829 if (GetGUID() == triggeredByAura->GetCasterGUID())
5830 return false;
5832 // beacon
5833 Unit* beacon = triggeredByAura->GetCaster();
5834 if (!beacon)
5835 return false;
5837 // find caster main aura at beacon
5838 Aura* dummy = NULL;
5839 Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_DUMMY);
5840 for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i)
5842 if ((*i)->GetId() == 53563 && (*i)->GetCasterGUID() == pVictim->GetGUID())
5844 dummy = (*i);
5845 break;
5849 // original heal must be form beacon caster
5850 if (!dummy)
5851 return false;
5853 triggered_spell_id = 53652; // Beacon of Light
5854 basepoints0 = triggeredByAura->GetModifier()->m_amount*damage/100;
5856 // cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check
5857 beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID());
5858 return true;
5860 // Seal of the Martyr do damage trigger
5861 case 53720:
5863 // 0 effect - is proc on enemy
5864 if (effIndex == 0 && (procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT))
5865 triggered_spell_id = 53719;
5866 else
5867 return true;
5868 break;
5870 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5871 case 40470:
5873 if (!procSpell)
5874 return false;
5876 float chance;
5878 // Flash of light/Holy light
5879 if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000))
5881 triggered_spell_id = 40471;
5882 chance = 15.0f;
5884 // Judgement (any)
5885 else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT)
5887 triggered_spell_id = 40472;
5888 chance = 50.0f;
5890 else
5891 return false;
5893 if (!roll_chance_f(chance))
5894 return false;
5896 break;
5898 // Glyph of Divinity
5899 case 54939:
5901 // Lookup base amount mana restore
5902 for (int i=0; i<3;++i)
5903 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5905 int32 mana = procSpell->EffectBasePoints[i];
5906 CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura);
5907 break;
5909 return true;
5911 // Glyph of Flash of Light
5912 case 54936:
5914 triggered_spell_id = 54957;
5915 basepoints0 = triggerAmount*damage/100;
5916 break;
5918 // Glyph of Holy Light
5919 case 54937:
5921 triggered_spell_id = 54968;
5922 basepoints0 = triggerAmount*damage/100;
5923 break;
5926 break;
5928 case SPELLFAMILY_SHAMAN:
5930 switch(dummySpell->Id)
5932 // Totemic Power (The Earthshatterer set)
5933 case 28823:
5935 if( !pVictim )
5936 return false;
5938 // Set class defined buff
5939 switch (pVictim->getClass())
5941 case CLASS_PALADIN:
5942 case CLASS_PRIEST:
5943 case CLASS_SHAMAN:
5944 case CLASS_DRUID:
5945 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5946 break;
5947 case CLASS_MAGE:
5948 case CLASS_WARLOCK:
5949 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5950 break;
5951 case CLASS_HUNTER:
5952 case CLASS_ROGUE:
5953 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5954 break;
5955 case CLASS_WARRIOR:
5956 triggered_spell_id = 28827; // Increases the friendly target's armor
5957 break;
5958 default:
5959 return false;
5961 break;
5963 // Lesser Healing Wave (Totem of Flowing Water Relic)
5964 case 28849:
5966 target = this;
5967 triggered_spell_id = 28850;
5968 break;
5970 // Windfury Weapon (Passive) 1-5 Ranks
5971 case 33757:
5973 if(GetTypeId()!=TYPEID_PLAYER)
5974 return false;
5976 if(!castItem || !castItem->IsEquipped())
5977 return false;
5979 // custom cooldown processing case
5980 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5981 return false;
5983 // Now amount of extra power stored in 1 effect of Enchant spell
5984 // Get it by item enchant id
5985 uint32 spellId;
5986 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5988 case 283: spellId = 8232; break; // 1 Rank
5989 case 284: spellId = 8235; break; // 2 Rank
5990 case 525: spellId = 10486; break; // 3 Rank
5991 case 1669:spellId = 16362; break; // 4 Rank
5992 case 2636:spellId = 25505; break; // 5 Rank
5993 case 3785:spellId = 58801; break; // 6 Rank
5994 case 3786:spellId = 58803; break; // 7 Rank
5995 case 3787:spellId = 58804; break; // 8 Rank
5996 default:
5998 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5999 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
6000 return false;
6004 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
6005 if(!windfurySpellEntry)
6007 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
6008 return false;
6011 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
6013 // Off-Hand case
6014 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
6016 // Value gained from additional AP
6017 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
6018 triggered_spell_id = 33750;
6020 // Main-Hand case
6021 else
6023 // Value gained from additional AP
6024 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
6025 triggered_spell_id = 25504;
6028 // apply cooldown before cast to prevent processing itself
6029 if( cooldown )
6030 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6032 // Attack Twice
6033 for ( uint32 i = 0; i<2; ++i )
6034 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6036 return true;
6038 // Shaman Tier 6 Trinket
6039 case 40463:
6041 if( !procSpell )
6042 return false;
6044 float chance;
6045 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001))
6047 triggered_spell_id = 40465; // Lightning Bolt
6048 chance = 15.0f;
6050 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))
6052 triggered_spell_id = 40465; // Lesser Healing Wave
6053 chance = 10.0f;
6055 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000))
6057 triggered_spell_id = 40466; // Stormstrike
6058 chance = 50.0f;
6060 else
6061 return false;
6063 if (!roll_chance_f(chance))
6064 return false;
6066 target = this;
6067 break;
6069 // Glyph of Healing Wave
6070 case 55440:
6072 // Not proc from self heals
6073 if (this==pVictim)
6074 return false;
6075 basepoints0 = triggerAmount * damage / 100;
6076 target = this;
6077 triggered_spell_id = 55533;
6078 break;
6080 // Spirit Hunt
6081 case 58877:
6083 // Cast on owner
6084 target = GetOwner();
6085 if(!target)
6086 return false;
6087 basepoints0 = triggerAmount * damage / 100;
6088 triggered_spell_id = 58879;
6089 break;
6091 // Shaman T8 Elemental 4P Bonus
6092 case 64928:
6094 basepoints0 = int32( triggerAmount * damage / 100 );
6095 triggered_spell_id = 64930; // Electrified
6096 break;
6099 // Storm, Earth and Fire
6100 if (dummySpell->SpellIconID == 3063)
6102 // Earthbind Totem summon only
6103 if(procSpell->Id != 2484)
6104 return false;
6106 float chance = triggerAmount;
6107 if (!roll_chance_f(chance))
6108 return false;
6110 triggered_spell_id = 64695;
6111 break;
6113 // Ancestral Awakening
6114 if (dummySpell->SpellIconID == 3065)
6116 triggered_spell_id = 52759;
6117 basepoints0 = triggerAmount * damage / 100;
6118 target = this;
6119 break;
6121 // Earth Shield
6122 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000))
6124 basepoints0 = triggerAmount;
6125 target = this;
6126 triggered_spell_id = 379;
6127 break;
6129 // Improved Water Shield
6130 if (dummySpell->SpellIconID == 2287)
6132 // Lesser Healing Wave need aditional 60% roll
6133 if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60))
6134 return false;
6135 // lookup water shield
6136 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6137 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6139 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6140 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000)))
6142 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
6143 CastSpell(this, spell, true, castItem, triggeredByAura);
6144 if ((*itr)->DropAuraCharge())
6145 RemoveAurasDueToSpell((*itr)->GetId());
6146 return true;
6149 return false;
6150 break;
6152 // Lightning Overload
6153 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
6155 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
6156 return false;
6158 // custom cooldown processing case
6159 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
6160 return false;
6162 uint32 spellId = 0;
6163 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
6164 switch (procSpell->Id)
6166 // Lightning Bolt
6167 case 403: spellId = 45284; break; // Rank 1
6168 case 529: spellId = 45286; break; // Rank 2
6169 case 548: spellId = 45287; break; // Rank 3
6170 case 915: spellId = 45288; break; // Rank 4
6171 case 943: spellId = 45289; break; // Rank 5
6172 case 6041: spellId = 45290; break; // Rank 6
6173 case 10391: spellId = 45291; break; // Rank 7
6174 case 10392: spellId = 45292; break; // Rank 8
6175 case 15207: spellId = 45293; break; // Rank 9
6176 case 15208: spellId = 45294; break; // Rank 10
6177 case 25448: spellId = 45295; break; // Rank 11
6178 case 25449: spellId = 45296; break; // Rank 12
6179 case 49237: spellId = 49239; break; // Rank 13
6180 case 49238: spellId = 49240; break; // Rank 14
6181 // Chain Lightning
6182 case 421: spellId = 45297; break; // Rank 1
6183 case 930: spellId = 45298; break; // Rank 2
6184 case 2860: spellId = 45299; break; // Rank 3
6185 case 10605: spellId = 45300; break; // Rank 4
6186 case 25439: spellId = 45301; break; // Rank 5
6187 case 25442: spellId = 45302; break; // Rank 6
6188 case 49268: spellId = 49270; break; // Rank 7
6189 case 49269: spellId = 49271; break; // Rank 8
6190 default:
6191 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
6192 return false;
6194 // No thread generated mod
6195 // TODO: exist special flag in spell attributes for this, need found and use!
6196 SpellModifier *mod = new SpellModifier;
6197 mod->op = SPELLMOD_THREAT;
6198 mod->value = -100;
6199 mod->type = SPELLMOD_PCT;
6200 mod->spellId = dummySpell->Id;
6201 mod->mask = UI64LIT(0x0000000000000003);
6202 mod->mask2= UI64LIT(0x0);
6203 ((Player*)this)->AddSpellMod(mod, true);
6205 // Remove cooldown (Chain Lightning - have Category Recovery time)
6206 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002))
6207 ((Player*)this)->RemoveSpellCooldown(spellId);
6209 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
6211 ((Player*)this)->AddSpellMod(mod, false);
6213 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6214 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
6216 return true;
6218 // Static Shock
6219 if(dummySpell->SpellIconID == 3059)
6221 // lookup Lightning Shield
6222 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
6223 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
6225 if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
6226 ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400)))
6228 uint32 spell = 0;
6229 switch ((*itr)->GetId())
6231 case 324: spell = 26364; break;
6232 case 325: spell = 26365; break;
6233 case 905: spell = 26366; break;
6234 case 945: spell = 26367; break;
6235 case 8134: spell = 26369; break;
6236 case 10431: spell = 26370; break;
6237 case 10432: spell = 26363; break;
6238 case 25469: spell = 26371; break;
6239 case 25472: spell = 26372; break;
6240 case 49280: spell = 49278; break;
6241 case 49281: spell = 49279; break;
6242 default:
6243 return false;
6245 CastSpell(target, spell, true, castItem, triggeredByAura);
6246 if ((*itr)->DropAuraCharge())
6247 RemoveAurasDueToSpell((*itr)->GetId());
6248 return true;
6251 return false;
6252 break;
6254 break;
6256 case SPELLFAMILY_DEATHKNIGHT:
6258 // Blood Aura
6259 if (dummySpell->SpellIconID == 2636)
6261 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
6262 return false;
6263 basepoints0 = triggerAmount * damage / 100;
6264 triggered_spell_id = 53168;
6265 break;
6267 // Butchery
6268 if (dummySpell->SpellIconID == 2664)
6270 basepoints0 = triggerAmount;
6271 triggered_spell_id = 50163;
6272 target = this;
6273 break;
6275 // Dancing Rune Weapon
6276 if (dummySpell->Id == 49028)
6278 // 1 dummy aura for dismiss rune blade
6279 if (effIndex!=2)
6280 return false;
6281 // TODO: wite script for this "fights on its own, doing the same attacks"
6282 // NOTE: Trigger here on every attack and spell cast
6283 return false;
6285 // Mark of Blood
6286 if (dummySpell->Id == 49005)
6288 // TODO: need more info (cooldowns/PPM)
6289 triggered_spell_id = 61607;
6290 break;
6292 // Vendetta
6293 if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000))
6295 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6296 triggered_spell_id = 50181;
6297 target = this;
6298 break;
6300 // Necrosis
6301 if (dummySpell->SpellIconID == 2709)
6303 basepoints0 = triggerAmount * damage / 100;
6304 triggered_spell_id = 51460;
6305 break;
6307 // Runic Power Back on Snare/Root
6308 if (dummySpell->Id == 61257)
6310 // only for spells and hit/crit (trigger start always) and not start from self casted spells
6311 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6312 return false;
6313 // Need snare or root mechanic
6314 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
6315 return false;
6316 triggered_spell_id = 61258;
6317 target = this;
6318 break;
6320 // Wandering Plague
6321 if (dummySpell->SpellIconID == 1614)
6323 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
6324 return false;
6325 basepoints0 = triggerAmount * damage / 100;
6326 triggered_spell_id = 50526;
6327 break;
6329 // Blood-Caked Blade
6330 if (dummySpell->SpellIconID == 138)
6332 triggered_spell_id = dummySpell->EffectTriggerSpell[effIndex];
6333 break;
6335 break;
6337 default:
6338 break;
6341 // processed charge only counting case
6342 if(!triggered_spell_id)
6343 return true;
6345 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6347 if(!triggerEntry)
6349 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
6350 return false;
6353 // default case
6354 if(!target || target!=this && !target->isAlive())
6355 return false;
6357 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6358 return false;
6360 if(basepoints0)
6361 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6362 else
6363 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
6365 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6366 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6368 return true;
6371 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
6373 // Get triggered aura spell info
6374 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
6376 // Basepoints of trigger aura
6377 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
6379 // Set trigger spell id, target, custom basepoints
6380 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
6381 Unit* target = NULL;
6382 int32 basepoints[3] = {0, 0, 0};
6384 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
6385 basepoints[0] = triggerAmount;
6387 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6388 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6390 // Try handle unknown trigger spells
6391 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
6393 switch (auraSpellInfo->SpellFamilyName)
6395 case SPELLFAMILY_GENERIC:
6396 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
6397 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6398 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6399 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6400 trigger_spell_id = 23781;
6401 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6402 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6404 // trigger_spell_id = 48877;
6406 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6408 // trigger_spell_id = 59233;
6410 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6412 // trigger_spell_id = 29471; // gain mana
6413 // 27526; // drain mana if possible
6415 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6416 //else if (auraSpellInfo->Id==54476) // Blood Presence
6417 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6418 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6419 //else if (auraSpellInfo->Id==52856) // Charge
6420 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6422 // Pct value stored in dummy
6423 basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6424 target = pVictim;
6425 break;
6427 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6428 // trigger_spell_id = 41249;
6429 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6430 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6431 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6432 // trigger_spell_id = 41055;
6433 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6434 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6435 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6437 float stat = 0.0f;
6438 // strength
6439 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6440 // agility
6441 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6442 // intellect
6443 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6444 // spirit
6445 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6447 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6448 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6449 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6450 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6451 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6452 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6453 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6454 trigger_spell_id = 33898;
6455 //else if (auraSpellInfo->Id==18943) // Double Attack
6456 //else if (auraSpellInfo->Id==19194) // Double Attack
6457 //else if (auraSpellInfo->Id==19817) // Double Attack
6458 //else if (auraSpellInfo->Id==19818) // Double Attack
6459 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6460 // trigger_spell_id = 14822;
6462 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6464 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6466 case 34191:
6467 case 34329:
6468 case 34524:
6469 case 34582:
6470 case 36733:
6471 break;
6472 default:
6473 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6474 return false;
6476 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6477 switch (procSpell->School)
6479 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6480 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6481 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6482 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6483 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6484 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6485 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6486 default:
6487 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6488 return false;
6492 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6493 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6494 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6495 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6496 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6497 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6498 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6499 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6500 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6501 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6502 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6503 //else if (auraSpellInfo->Id==40250) // Improved Duration
6504 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6505 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6506 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6507 // Mana Drain Trigger
6509 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6510 if (this && this->isAlive())
6511 CastSpell(this, 29471, true, castItem, triggeredByAura);
6512 if (pVictim && pVictim->isAlive())
6513 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6514 return true;
6516 //else if (auraSpellInfo->Id==55580) // Mana Link
6517 //else if (auraSpellInfo->Id==45903) // Offensive State
6518 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6519 //else if (auraSpellInfo->Id==43453) // Rune Ward
6520 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6521 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6522 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6523 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6524 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6525 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6526 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6527 //else if (auraSpellInfo->Id==35205) // Vanish
6528 //else if (auraSpellInfo->Id==42730) // Woe Strike
6529 //else if (auraSpellInfo->Id==59735) // Woe Strike
6530 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6531 break;
6532 case SPELLFAMILY_MAGE:
6533 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6535 switch (auraSpellInfo->Id)
6537 case 31641: // Rank 1
6538 case 31642: // Rank 2
6539 trigger_spell_id = 31643;
6540 break;
6541 default:
6542 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6543 return false;
6546 break;
6547 case SPELLFAMILY_WARRIOR:
6548 if (auraSpellInfo->Id == 50421) // Scent of Blood
6549 trigger_spell_id = 50422;
6550 break;
6551 case SPELLFAMILY_WARLOCK:
6553 // Pyroclasm
6554 if (auraSpellInfo->SpellIconID == 1137)
6556 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6557 return false;
6558 // Calculate spell tick count for spells
6559 uint32 tick = 1; // Default tick = 1
6561 // Hellfire have 15 tick
6562 if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000040))
6563 tick = 15;
6564 // Rain of Fire have 4 tick
6565 else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020))
6566 tick = 4;
6567 else
6568 return false;
6570 // Calculate chance = baseChance / tick
6571 float chance = 0;
6572 switch (auraSpellInfo->Id)
6574 case 18096: chance = 13.0f / tick; break;
6575 case 18073: chance = 26.0f / tick; break;
6577 // Roll chance
6578 if (!roll_chance_f(chance))
6579 return false;
6581 trigger_spell_id = 18093;
6583 // Drain Soul
6584 else if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000))
6586 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6587 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6589 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6591 // Drain Soul
6592 CastCustomSpell(this, 18371, &basepoints[0], NULL, NULL, true, castItem, triggeredByAura);
6593 break;
6596 // Not remove charge (aura removed on death in any cases)
6597 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6598 return false;
6600 // Nether Protection
6601 else if (auraSpellInfo->SpellIconID == 1985)
6603 if (!procSpell)
6604 return false;
6605 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6607 case SPELL_SCHOOL_NORMAL:
6608 return false; // ignore
6609 case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break;
6610 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6611 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6612 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6613 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6614 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6615 default:
6616 return false;
6619 break;
6621 case SPELLFAMILY_PRIEST:
6623 // Greater Heal Refund
6624 if (auraSpellInfo->Id==37594)
6625 trigger_spell_id = 37595;
6626 // Blessed Recovery
6627 else if (auraSpellInfo->SpellIconID == 1875)
6629 switch (auraSpellInfo->Id)
6631 case 27811: trigger_spell_id = 27813; break;
6632 case 27815: trigger_spell_id = 27817; break;
6633 case 27816: trigger_spell_id = 27818; break;
6634 default:
6635 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6636 return false;
6638 basepoints[0] = damage * triggerAmount / 100 / 3;
6639 target = this;
6641 break;
6643 case SPELLFAMILY_DRUID:
6645 // Druid Forms Trinket
6646 if (auraSpellInfo->Id==37336)
6648 switch(m_form)
6650 case FORM_NONE: trigger_spell_id = 37344;break;
6651 case FORM_CAT: trigger_spell_id = 37341;break;
6652 case FORM_BEAR:
6653 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6654 case FORM_TREE: trigger_spell_id = 37342;break;
6655 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6656 default:
6657 return false;
6660 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6661 // trigger_spell_id = ????;
6662 // Leader of the Pack
6663 else if (auraSpellInfo->Id == 24932)
6665 if (triggerAmount == 0)
6666 return false;
6667 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
6668 trigger_spell_id = 34299;
6670 break;
6672 case SPELLFAMILY_HUNTER:
6673 break;
6674 case SPELLFAMILY_PALADIN:
6677 // Blessed Life
6678 if (auraSpellInfo->SpellIconID == 2137)
6680 switch (auraSpellInfo->Id)
6682 case 31828: // Rank 1
6683 case 31829: // Rank 2
6684 case 31830: // Rank 3
6685 break;
6686 default:
6687 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6688 return false;
6692 // Healing Discount
6693 if (auraSpellInfo->Id==37705)
6695 trigger_spell_id = 37706;
6696 target = this;
6698 // Soul Preserver
6699 if (auraSpellInfo->Id==60510)
6701 trigger_spell_id = 60515;
6702 target = this;
6704 // Illumination
6705 else if (auraSpellInfo->SpellIconID==241)
6707 if(!procSpell)
6708 return false;
6709 // procspell is triggered spell but we need mana cost of original casted spell
6710 uint32 originalSpellId = procSpell->Id;
6711 // Holy Shock heal
6712 if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000))
6714 switch(procSpell->Id)
6716 case 25914: originalSpellId = 20473; break;
6717 case 25913: originalSpellId = 20929; break;
6718 case 25903: originalSpellId = 20930; break;
6719 case 27175: originalSpellId = 27174; break;
6720 case 33074: originalSpellId = 33072; break;
6721 case 48820: originalSpellId = 48824; break;
6722 case 48821: originalSpellId = 48825; break;
6723 default:
6724 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6725 return false;
6728 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6729 if(!originalSpell)
6731 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6732 return false;
6734 // percent stored in effect 1 (class scripts) base points
6735 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6736 basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6737 trigger_spell_id = 20272;
6738 target = this;
6740 // Lightning Capacitor
6741 else if (auraSpellInfo->Id==37657)
6743 if(!pVictim || !pVictim->isAlive())
6744 return false;
6745 // stacking
6746 CastSpell(this, 37658, true, NULL, triggeredByAura);
6748 Aura * dummy = GetDummyAura(37658);
6749 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6750 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6751 return false;
6753 RemoveAurasDueToSpell(37658);
6754 trigger_spell_id = 37661;
6755 target = pVictim;
6757 // Thunder Capacitor
6758 else if (auraSpellInfo->Id == 54841)
6760 if(!pVictim || !pVictim->isAlive())
6761 return false;
6762 // stacking
6763 CastSpell(this, 54842, true, NULL, triggeredByAura);
6765 // counting
6766 Aura * dummy = GetDummyAura(54842);
6767 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6768 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6769 return false;
6771 RemoveAurasDueToSpell(54842);
6772 trigger_spell_id = 54843;
6773 target = pVictim;
6775 break;
6777 case SPELLFAMILY_SHAMAN:
6779 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6780 if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400))
6782 switch(auraSpellInfo->Id)
6784 case 324: // Rank 1
6785 trigger_spell_id = 26364; break;
6786 case 325: // Rank 2
6787 trigger_spell_id = 26365; break;
6788 case 905: // Rank 3
6789 trigger_spell_id = 26366; break;
6790 case 945: // Rank 4
6791 trigger_spell_id = 26367; break;
6792 case 8134: // Rank 5
6793 trigger_spell_id = 26369; break;
6794 case 10431: // Rank 6
6795 trigger_spell_id = 26370; break;
6796 case 10432: // Rank 7
6797 trigger_spell_id = 26363; break;
6798 case 25469: // Rank 8
6799 trigger_spell_id = 26371; break;
6800 case 25472: // Rank 9
6801 trigger_spell_id = 26372; break;
6802 case 49280: // Rank 10
6803 trigger_spell_id = 49278; break;
6804 case 49281: // Rank 11
6805 trigger_spell_id = 49279; break;
6806 default:
6807 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6808 return false;
6811 // Lightning Shield (The Ten Storms set)
6812 else if (auraSpellInfo->Id == 23551)
6814 trigger_spell_id = 23552;
6815 target = pVictim;
6817 // Damage from Lightning Shield (The Ten Storms set)
6818 else if (auraSpellInfo->Id == 23552)
6819 trigger_spell_id = 27635;
6820 // Mana Surge (The Earthfury set)
6821 else if (auraSpellInfo->Id == 23572)
6823 if(!procSpell)
6824 return false;
6825 basepoints[0] = procSpell->manaCost * 35 / 100;
6826 trigger_spell_id = 23571;
6827 target = this;
6829 // Nature's Guardian
6830 else if (auraSpellInfo->SpellIconID == 2013)
6832 // Check health condition - should drop to less 30% (damage deal after this!)
6833 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6834 return false;
6836 if(pVictim && pVictim->isAlive())
6837 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6839 basepoints[0] = triggerAmount * GetMaxHealth() / 100;
6840 trigger_spell_id = 31616;
6841 target = this;
6843 break;
6845 case SPELLFAMILY_DEATHKNIGHT:
6847 // Acclimation
6848 if (auraSpellInfo->SpellIconID == 1930)
6850 if (!procSpell)
6851 return false;
6852 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6854 case SPELL_SCHOOL_NORMAL:
6855 return false; // ignore
6856 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6857 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6858 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6859 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6860 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6861 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6862 default:
6863 return false;
6866 // Blood Presence
6867 else if (auraSpellInfo->Id == 48266)
6869 if (GetTypeId() != TYPEID_PLAYER)
6870 return false;
6871 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6872 return false;
6873 trigger_spell_id = 50475;
6874 basepoints[0] = damage * triggerAmount / 100;
6876 break;
6878 default:
6879 break;
6883 // All ok. Check current trigger spell
6884 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6885 if ( triggerEntry == NULL )
6887 // Not cast unknown spell
6888 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6889 return false;
6892 // not allow proc extra attack spell at extra attack
6893 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6894 return false;
6896 // Custom requirements (not listed in procEx) Warning! damage dealing after this
6897 // Custom triggered spells
6898 switch (auraSpellInfo->Id)
6900 // Persistent Shield (Scarab Brooch trinket)
6901 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6902 case 26467:
6904 basepoints[0] = damage * 15 / 100;
6905 target = pVictim;
6906 trigger_spell_id = 26470;
6907 break;
6909 // Cheat Death
6910 case 28845:
6912 // When your health drops below 20% ....
6913 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6914 return false;
6915 break;
6917 // Deadly Swiftness (Rank 1)
6918 case 31255:
6920 // whenever you deal damage to a target who is below 20% health.
6921 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6922 return false;
6924 target = this;
6925 trigger_spell_id = 22588;
6927 // Greater Heal Refund (Avatar Raiment set)
6928 case 37594:
6930 // Not give if target already have full health
6931 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6932 return false;
6933 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6934 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6935 return false;
6936 break;
6938 // Bonus Healing (Crystal Spire of Karabor mace)
6939 case 40971:
6941 // If your target is below $s1% health
6942 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6943 return false;
6944 break;
6946 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6947 case 45057:
6949 // reduce you below $s1% health
6950 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6951 return false;
6952 break;
6954 // Rapid Recuperation
6955 case 53228:
6956 case 53232:
6958 // This effect only from Rapid Fire (ability cast)
6959 if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020)))
6960 return false;
6961 break;
6963 // Decimation
6964 case 63156:
6965 case 63158:
6967 // Looking for dummy effect
6968 Aura *aur = GetAura(auraSpellInfo->Id, 1);
6969 if (!aur)
6970 return false;
6972 // If target's health is not below equal certain value (35%) not proc
6973 if ((pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount)
6974 return false;
6976 break;
6980 // Custom basepoints/target for exist spell
6981 // dummy basepoints or other customs
6982 switch(trigger_spell_id)
6984 // Cast positive spell on enemy target
6985 case 7099: // Curse of Mending
6986 case 39647: // Curse of Mending
6987 case 29494: // Temptation
6988 case 20233: // Improved Lay on Hands (cast on target)
6990 target = pVictim;
6991 break;
6993 // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset)
6994 case 15250: // Rogue Setup
6996 if(!pVictim || pVictim != getVictim()) // applied only for main target
6997 return false;
6998 break; // continue normal case
7000 // Finish movies that add combo
7001 case 14189: // Seal Fate (Netherblade set)
7002 case 14157: // Ruthlessness
7004 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
7005 break;
7007 // Bloodthirst (($m/100)% of max health)
7008 case 23880:
7010 basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100);
7011 break;
7013 // Shamanistic Rage triggered spell
7014 case 30824:
7016 basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
7017 break;
7019 // Enlightenment (trigger only from mana cost spells)
7020 case 35095:
7022 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
7023 return false;
7024 break;
7026 // Demonic Pact
7027 case 48090:
7029 // As the spell is proced from pet's attack - find owner
7030 Unit* owner = GetOwner();
7031 if (!owner || owner->GetTypeId() != TYPEID_PLAYER)
7032 return false;
7034 // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later.
7035 int32 curBonus = 0;
7036 if (Aura* aur = owner->GetAura(48090,0))
7037 curBonus = aur->GetModifier()->m_amount;
7038 int32 spellDamage = owner->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_MAGIC) - curBonus;
7039 if(spellDamage <= 0)
7040 return false;
7042 // percent stored in owner talent dummy
7043 AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY);
7044 for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i)
7046 if ((*i)->GetSpellProto()->SpellIconID == 3220)
7048 basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100);
7049 break;
7052 break;
7054 // Sword and Board
7055 case 50227:
7057 // Remove cooldown on Shield Slam
7058 if (GetTypeId() == TYPEID_PLAYER)
7059 ((Player*)this)->RemoveSpellCategoryCooldown(1209, true);
7060 break;
7062 // Maelstrom Weapon
7063 case 53817:
7065 // have rank dependent proc chance, ignore too often cases
7066 // PPM = 2.5 * (rank of talent),
7067 uint32 rank = spellmgr.GetSpellRank(auraSpellInfo->Id);
7068 // 5 rank -> 100% 4 rank -> 80% and etc from full rate
7069 if(!roll_chance_i(20*rank))
7070 return false;
7071 break;
7073 // Brain Freeze
7074 case 57761:
7076 if(!procSpell)
7077 return false;
7078 // For trigger from Blizzard need exist Improved Blizzard
7079 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)))
7081 bool found = false;
7082 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7083 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7085 int32 script = (*i)->GetModifier()->m_miscvalue;
7086 if(script==836 || script==988 || script==989)
7088 found=true;
7089 break;
7092 if(!found)
7093 return false;
7095 break;
7097 // Astral Shift
7098 case 52179:
7100 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
7101 return false;
7103 // Need stun, fear or silence mechanic
7104 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
7105 return false;
7106 break;
7108 // Burning Determination
7109 case 54748:
7111 if(!procSpell)
7112 return false;
7113 // Need Interrupt or Silenced mechanic
7114 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
7115 return false;
7116 break;
7118 // Lock and Load
7119 case 56453:
7121 // Proc only from trap activation (from periodic proc another aura of this spell)
7122 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
7123 return false;
7124 break;
7128 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
7129 return false;
7131 // try detect target manually if not set
7132 if ( target == NULL )
7133 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
7135 // default case
7136 if(!target || target!=this && !target->isAlive())
7137 return false;
7139 if(basepoints[0] || basepoints[1] || basepoints[2])
7140 CastCustomSpell(target,trigger_spell_id,
7141 basepoints[0] ? &basepoints[0] : NULL,
7142 basepoints[1] ? &basepoints[1] : NULL,
7143 basepoints[2] ? &basepoints[2] : NULL,
7144 true,castItem,triggeredByAura);
7145 else
7146 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
7148 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7149 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
7151 return true;
7154 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
7156 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
7158 if(!pVictim || !pVictim->isAlive())
7159 return false;
7161 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
7162 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
7164 uint32 triggered_spell_id = 0;
7166 switch(scriptId)
7168 case 836: // Improved Blizzard (Rank 1)
7170 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7171 return false;
7172 triggered_spell_id = 12484;
7173 break;
7175 case 988: // Improved Blizzard (Rank 2)
7177 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7178 return false;
7179 triggered_spell_id = 12485;
7180 break;
7182 case 989: // Improved Blizzard (Rank 3)
7184 if (!procSpell || procSpell->SpellVisual[0]!=9487)
7185 return false;
7186 triggered_spell_id = 12486;
7187 break;
7189 case 4086: // Improved Mend Pet (Rank 1)
7190 case 4087: // Improved Mend Pet (Rank 2)
7192 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
7193 if(!roll_chance_i(chance))
7194 return false;
7196 triggered_spell_id = 24406;
7197 break;
7199 case 4533: // Dreamwalker Raiment 2 pieces bonus
7201 // Chance 50%
7202 if (!roll_chance_i(50))
7203 return false;
7205 switch (pVictim->getPowerType())
7207 case POWER_MANA: triggered_spell_id = 28722; break;
7208 case POWER_RAGE: triggered_spell_id = 28723; break;
7209 case POWER_ENERGY: triggered_spell_id = 28724; break;
7210 default:
7211 return false;
7213 break;
7215 case 4537: // Dreamwalker Raiment 6 pieces bonus
7216 triggered_spell_id = 28750; // Blessing of the Claw
7217 break;
7218 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
7219 triggered_spell_id = 37445; // Mana Surge
7220 break;
7221 case 8152: // Serendipity
7223 // if heal your target over maximum health
7224 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
7225 return false;
7226 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
7227 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
7228 CastCustomSpell(this, 47762, &basepoints0, NULL, NULL, true, NULL, triggeredByAura);
7229 return true;
7233 // not processed
7234 if(!triggered_spell_id)
7235 return false;
7237 // standard non-dummy case
7238 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
7240 if(!triggerEntry)
7242 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
7243 return false;
7246 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
7247 return false;
7249 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
7251 if( cooldown && GetTypeId()==TYPEID_PLAYER )
7252 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
7254 return true;
7257 void Unit::setPowerType(Powers new_powertype)
7259 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
7261 if(GetTypeId() == TYPEID_PLAYER)
7263 if(((Player*)this)->GetGroup())
7264 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
7266 else if(((Creature*)this)->isPet())
7268 Pet *pet = ((Pet*)this);
7269 if(pet->isControlled())
7271 Unit *owner = GetOwner();
7272 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
7273 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
7277 switch(new_powertype)
7279 default:
7280 case POWER_MANA:
7281 break;
7282 case POWER_RAGE:
7283 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
7284 SetPower( POWER_RAGE,0);
7285 break;
7286 case POWER_FOCUS:
7287 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
7288 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
7289 break;
7290 case POWER_ENERGY:
7291 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
7292 SetPower( POWER_ENERGY,0);
7293 break;
7294 case POWER_HAPPINESS:
7295 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
7296 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
7297 break;
7301 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
7303 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
7304 if(!entry)
7306 static uint64 guid = 0; // prevent repeating spam same faction problem
7308 if(GetGUID() != guid)
7310 if(GetTypeId() == TYPEID_PLAYER)
7311 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
7312 else
7313 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
7314 guid = GetGUID();
7317 return entry;
7320 bool Unit::IsHostileTo(Unit const* unit) const
7322 // always non-hostile to self
7323 if(unit==this)
7324 return false;
7326 // always non-hostile to GM in GM mode
7327 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7328 return false;
7330 // always hostile to enemy
7331 if(getVictim()==unit || unit->getVictim()==this)
7332 return true;
7334 // test pet/charm masters instead pers/charmeds
7335 Unit const* testerOwner = GetCharmerOrOwner();
7336 Unit const* targetOwner = unit->GetCharmerOrOwner();
7338 // always hostile to owner's enemy
7339 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7340 return true;
7342 // always hostile to enemy owner
7343 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7344 return true;
7346 // always hostile to owner of owner's enemy
7347 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7348 return true;
7350 Unit const* tester = testerOwner ? testerOwner : this;
7351 Unit const* target = targetOwner ? targetOwner : unit;
7353 // always non-hostile to target with common owner, or to owner/pet
7354 if(tester==target)
7355 return false;
7357 // special cases (Duel, etc)
7358 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7360 Player const* pTester = (Player const*)tester;
7361 Player const* pTarget = (Player const*)target;
7363 // Duel
7364 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
7365 return true;
7367 // Group
7368 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7369 return false;
7371 // Sanctuary
7372 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7373 return false;
7375 // PvP FFA state
7376 if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
7377 return true;
7379 //= PvP states
7380 // Green/Blue (can't attack)
7381 if(pTester->GetTeam()==pTarget->GetTeam())
7382 return false;
7384 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
7385 return pTester->IsPvP() && pTarget->IsPvP();
7388 // faction base cases
7389 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7390 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7391 if(!tester_faction || !target_faction)
7392 return false;
7394 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7395 return true;
7397 // PvC forced reaction and reputation case
7398 if(tester->GetTypeId()==TYPEID_PLAYER)
7400 // forced reaction
7401 if(target_faction->faction)
7403 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7404 return *force <= REP_HOSTILE;
7406 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
7407 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7408 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7409 return (factionState->Flags & FACTION_FLAG_AT_WAR);
7412 // CvP forced reaction and reputation case
7413 else if(target->GetTypeId()==TYPEID_PLAYER)
7415 // forced reaction
7416 if(tester_faction->faction)
7418 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7419 return *force <= REP_HOSTILE;
7421 // apply reputation state
7422 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
7423 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
7424 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
7428 // common faction based case (CvC,PvC,CvP)
7429 return tester_faction->IsHostileTo(*target_faction);
7432 bool Unit::IsFriendlyTo(Unit const* unit) const
7434 // always friendly to self
7435 if(unit==this)
7436 return true;
7438 // always friendly to GM in GM mode
7439 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
7440 return true;
7442 // always non-friendly to enemy
7443 if(getVictim()==unit || unit->getVictim()==this)
7444 return false;
7446 // test pet/charm masters instead pers/charmeds
7447 Unit const* testerOwner = GetCharmerOrOwner();
7448 Unit const* targetOwner = unit->GetCharmerOrOwner();
7450 // always non-friendly to owner's enemy
7451 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7452 return false;
7454 // always non-friendly to enemy owner
7455 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7456 return false;
7458 // always non-friendly to owner of owner's enemy
7459 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7460 return false;
7462 Unit const* tester = testerOwner ? testerOwner : this;
7463 Unit const* target = targetOwner ? targetOwner : unit;
7465 // always friendly to target with common owner, or to owner/pet
7466 if(tester==target)
7467 return true;
7469 // special cases (Duel)
7470 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7472 Player const* pTester = (Player const*)tester;
7473 Player const* pTarget = (Player const*)target;
7475 // Duel
7476 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7477 return false;
7479 // Group
7480 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7481 return true;
7483 // Sanctuary
7484 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7485 return true;
7487 // PvP FFA state
7488 if(pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP) && pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP))
7489 return false;
7491 //= PvP states
7492 // Green/Blue (non-attackable)
7493 if(pTester->GetTeam()==pTarget->GetTeam())
7494 return true;
7496 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7497 return !pTarget->IsPvP();
7500 // faction base cases
7501 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7502 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7503 if(!tester_faction || !target_faction)
7504 return false;
7506 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7507 return false;
7509 // PvC forced reaction and reputation case
7510 if(tester->GetTypeId()==TYPEID_PLAYER)
7512 // forced reaction
7513 if(target_faction->faction)
7515 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7516 return *force >= REP_FRIENDLY;
7518 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7519 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7520 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7521 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7524 // CvP forced reaction and reputation case
7525 else if(target->GetTypeId()==TYPEID_PLAYER)
7527 // forced reaction
7528 if(tester_faction->faction)
7530 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7531 return *force >= REP_FRIENDLY;
7533 // apply reputation state
7534 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7535 if(raw_tester_faction->reputationListID >=0 )
7536 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7540 // common faction based case (CvC,PvC,CvP)
7541 return tester_faction->IsFriendlyTo(*target_faction);
7544 bool Unit::IsHostileToPlayers() const
7546 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7547 if(!my_faction || !my_faction->faction)
7548 return false;
7550 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7551 if(raw_faction && raw_faction->reputationListID >=0 )
7552 return false;
7554 return my_faction->IsHostileToPlayers();
7557 bool Unit::IsNeutralToAll() const
7559 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7560 if(!my_faction || !my_faction->faction)
7561 return true;
7563 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7564 if(raw_faction && raw_faction->reputationListID >=0 )
7565 return false;
7567 return my_faction->IsNeutralToAll();
7570 bool Unit::Attack(Unit *victim, bool meleeAttack)
7572 if(!victim || victim == this)
7573 return false;
7575 // dead units can neither attack nor be attacked
7576 if(!isAlive() || !victim->IsInWorld() || !victim->isAlive())
7577 return false;
7579 // player cannot attack in mount state
7580 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7581 return false;
7583 // nobody can attack GM in GM-mode
7584 if(victim->GetTypeId()==TYPEID_PLAYER)
7586 if(((Player*)victim)->isGameMaster())
7587 return false;
7589 else
7591 if(((Creature*)victim)->IsInEvadeMode())
7592 return false;
7595 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7596 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7597 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7599 // in fighting already
7600 if (m_attacking)
7602 if (m_attacking == victim)
7604 // switch to melee attack from ranged/magic
7605 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7607 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7608 SendMeleeAttackStart(victim);
7609 return true;
7611 return false;
7614 // remove old target data
7615 AttackStop(true);
7617 // new battle
7618 else
7620 // set position before any AI calls/assistance
7621 if(GetTypeId()==TYPEID_UNIT)
7622 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7625 //Set our target
7626 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7628 if(meleeAttack)
7629 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7631 m_attacking = victim;
7632 m_attacking->_addAttacker(this);
7634 if(GetTypeId()==TYPEID_UNIT)
7636 WorldPacket data(SMSG_AI_REACTION, 12);
7637 data << uint64(GetGUID());
7638 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7639 ((WorldObject*)this)->SendMessageToSet(&data, true);
7641 ((Creature*)this)->CallAssistance();
7644 // delay offhand weapon attack to next attack time
7645 if(haveOffhandWeapon())
7646 resetAttackTimer(OFF_ATTACK);
7648 if(meleeAttack)
7649 SendMeleeAttackStart(victim);
7651 return true;
7654 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7656 if (!m_attacking)
7657 return false;
7659 Unit* victim = m_attacking;
7661 m_attacking->_removeAttacker(this);
7662 m_attacking = NULL;
7664 //Clear our target
7665 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7667 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7669 InterruptSpell(CURRENT_MELEE_SPELL);
7671 // reset only at real combat stop
7672 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7674 ((Creature*)this)->SetNoCallAssistance(false);
7675 ((Creature*)this)->SetNoSearchAssistance(false);
7678 SendMeleeAttackStop(victim);
7680 return true;
7683 void Unit::CombatStop(bool includingCast)
7685 if (includingCast && IsNonMeleeSpellCasted(false))
7686 InterruptNonMeleeSpells(false);
7688 AttackStop();
7689 RemoveAllAttackers();
7690 if( GetTypeId()==TYPEID_PLAYER )
7691 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7692 ClearInCombat();
7695 void Unit::CombatStopWithPets(bool includingCast)
7697 CombatStop(includingCast);
7698 if(Pet* pet = GetPet())
7699 pet->CombatStop(includingCast);
7700 if(Unit* charm = GetCharm())
7701 charm->CombatStop(includingCast);
7703 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
7704 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7705 guardian->CombatStop(includingCast);
7708 bool Unit::isAttackingPlayer() const
7710 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7711 return true;
7713 Pet* pet = GetPet();
7714 if(pet && pet->isAttackingPlayer())
7715 return true;
7717 Unit* charmed = GetCharm();
7718 if(charmed && charmed->isAttackingPlayer())
7719 return true;
7721 for (int8 i = 0; i < MAX_TOTEM; ++i)
7723 if(m_TotemSlot[i])
7725 Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]);
7726 if(totem && totem->isAttackingPlayer())
7727 return true;
7731 return false;
7734 void Unit::RemoveAllAttackers()
7736 while (!m_attackers.empty())
7738 AttackerSet::iterator iter = m_attackers.begin();
7739 if(!(*iter)->AttackStop())
7741 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7742 m_attackers.erase(iter);
7747 bool Unit::HasAuraStateForCaster(AuraState flag, uint64 caster) const
7749 if(!HasAuraState(flag))
7750 return false;
7752 // single per-caster aura state
7753 if(flag == AURA_STATE_CONFLAGRATE)
7755 Unit::AuraList const& dotList = GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE);
7756 for(Unit::AuraList::const_iterator i = dotList.begin(); i != dotList.end(); ++i)
7758 if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK &&
7759 (*i)->GetCasterGUID() == caster &&
7760 // Immolate
7761 (((*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000004)) ||
7762 // Shadowflame
7763 ((*i)->GetSpellProto()->SpellFamilyFlags2 & 0x00000002)))
7765 return true;
7769 return false;
7772 return true;
7775 void Unit::ModifyAuraState(AuraState flag, bool apply)
7777 if (apply)
7779 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7781 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7782 if(GetTypeId() == TYPEID_PLAYER)
7784 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7785 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
7787 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
7788 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
7789 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
7790 if (spellInfo->CasterAuraState == flag)
7791 CastSpell(this, itr->first, true, NULL);
7796 else
7798 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
7800 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7802 if (flag != AURA_STATE_ENRAGE) // enrage aura state triggering continues auras
7804 Unit::AuraMap& tAuras = GetAuras();
7805 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
7807 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
7808 if (spellProto->CasterAuraState == flag)
7810 // exceptions (applied at state but not removed at state change)
7811 // Rampage
7812 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
7814 ++itr;
7815 continue;
7818 RemoveAura(itr);
7820 else
7821 ++itr;
7827 Unit *Unit::GetOwner() const
7829 if(uint64 ownerid = GetOwnerGUID())
7830 return ObjectAccessor::GetUnit(*this, ownerid);
7831 return NULL;
7834 Unit *Unit::GetCharmer() const
7836 if(uint64 charmerid = GetCharmerGUID())
7837 return ObjectAccessor::GetUnit(*this, charmerid);
7838 return NULL;
7841 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7843 uint64 guid = GetCharmerOrOwnerGUID();
7844 if(IS_PLAYER_GUID(guid))
7845 return ObjectAccessor::GetPlayer(*this, guid);
7847 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7850 Pet* Unit::GetPet() const
7852 if(uint64 pet_guid = GetPetGUID())
7854 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7855 return pet;
7857 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7858 const_cast<Unit*>(this)->SetPet(0);
7861 return NULL;
7864 Unit* Unit::GetCharm() const
7866 if(uint64 charm_guid = GetCharmGUID())
7868 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7869 return pet;
7871 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7872 const_cast<Unit*>(this)->SetCharm(NULL);
7875 return NULL;
7878 float Unit::GetCombatDistance( const Unit* target ) const
7880 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
7881 float dx = GetPositionX() - target->GetPositionX();
7882 float dy = GetPositionY() - target->GetPositionY();
7883 float dz = GetPositionZ() - target->GetPositionZ();
7884 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
7885 return ( dist > 0 ? dist : 0);
7888 void Unit::SetPet(Pet* pet)
7890 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7892 // FIXME: hack, speed must be set only at follow
7893 if(pet && GetTypeId()==TYPEID_PLAYER)
7894 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7895 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7898 void Unit::SetCharm(Unit* pet)
7900 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7904 void Unit::AddGuardian( Pet* pet )
7906 m_guardianPets.insert(pet->GetGUID());
7910 void Unit::RemoveGuardian( Pet* pet )
7912 m_guardianPets.erase(pet->GetGUID());
7915 void Unit::RemoveGuardians()
7917 while(!m_guardianPets.empty())
7919 uint64 guid = *m_guardianPets.begin();
7920 if(Pet* pet = ObjectAccessor::GetPet(guid))
7921 pet->Remove(PET_SAVE_AS_DELETED);
7923 m_guardianPets.erase(guid);
7927 Pet* Unit::FindGuardianWithEntry(uint32 entry)
7929 // pet guid middle part is entry (and creature also)
7930 // and in guardian list must be guardians with same entry _always_
7931 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
7933 if(Pet* pet = ObjectAccessor::GetPet(*itr))
7934 if (pet->GetEntry() == entry)
7935 return pet;
7938 return NULL;
7941 void Unit::UnsummonAllTotems()
7943 for (int8 i = 0; i < MAX_TOTEM; ++i)
7945 if(!m_TotemSlot[i])
7946 continue;
7948 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
7949 if (OldTotem && OldTotem->isTotem())
7950 ((Totem*)OldTotem)->UnSummon();
7954 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
7956 int32 gain = pVictim->ModifyHealth(int32(addhealth));
7958 Unit* unit = this;
7960 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7961 unit = GetOwner();
7963 if (unit->GetTypeId()==TYPEID_PLAYER)
7965 // overheal = addhealth - gain
7966 unit->SendHealSpellLog(pVictim, spellProto->Id, addhealth, addhealth - gain, critical);
7968 if (BattleGround *bg = ((Player*)unit)->GetBattleGround())
7969 bg->UpdatePlayerScore((Player*)unit, SCORE_HEALING_DONE, gain);
7971 // use the actual gain, as the overheal shall not be counted, skip gain 0 (it ignored anyway in to criteria)
7972 if (gain)
7973 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain, 0, pVictim);
7975 ((Player*)unit)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
7978 if (pVictim->GetTypeId()==TYPEID_PLAYER)
7980 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
7981 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
7984 return gain;
7987 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
7989 if(!victim)
7990 return NULL;
7992 // Magic case
7993 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
7995 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
7996 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
7997 if(Unit* magnet = (*itr)->GetCaster())
7998 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
7999 return magnet;
8001 // Melee && ranged case
8002 else
8004 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
8005 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
8006 if(Unit* magnet = (*i)->GetCaster())
8007 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
8008 if(roll_chance_i((*i)->GetModifier()->m_amount))
8009 return magnet;
8012 return victim;
8015 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, uint32 OverHeal, bool critical)
8017 // we guess size
8018 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
8019 data.append(pVictim->GetPackGUID());
8020 data.append(GetPackGUID());
8021 data << uint32(SpellID);
8022 data << uint32(Damage);
8023 data << uint32(OverHeal);
8024 data << uint8(critical ? 1 : 0);
8025 data << uint8(0); // unused in client?
8026 SendMessageToSet(&data, true);
8029 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8031 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
8032 data.append(pVictim->GetPackGUID());
8033 data.append(GetPackGUID());
8034 data << uint32(SpellID);
8035 data << uint32(powertype);
8036 data << uint32(Damage);
8037 SendMessageToSet(&data, true);
8040 void Unit::EnergizeBySpell(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
8042 SendEnergizeSpellLog(pVictim, SpellID, Damage, powertype);
8043 // needs to be called after sending spell log
8044 ModifyPower(powertype, Damage);
8047 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
8049 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
8050 return pdamage;
8052 // For totems get damage bonus from owner (statue isn't totem in fact)
8053 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8055 if(Unit* owner = GetOwner())
8056 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
8059 // Taken/Done total percent damage auras
8060 float DoneTotalMod = 1.0f;
8061 float TakenTotalMod = 1.0f;
8062 int32 DoneTotal = 0;
8063 int32 TakenTotal = 0;
8065 // ..done
8066 // Pet damage
8067 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
8068 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
8070 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
8071 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
8073 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
8074 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
8075 // -1 == any item class (not wand then)
8076 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
8077 // 0 == any inventory type (not wand then)
8079 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8083 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8084 // Add flat bonus from spell damage versus
8085 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
8086 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8087 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8088 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8089 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8091 // done scripted mod (take it from owner)
8092 Unit *owner = GetOwner();
8093 if (!owner) owner = this;
8094 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8095 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8097 if (!(*i)->isAffectedOnSpell(spellProto))
8098 continue;
8099 switch((*i)->GetModifier()->m_miscvalue)
8101 case 4920: // Molten Fury
8102 case 4919:
8103 case 6917: // Death's Embrace
8104 case 6926:
8105 case 6928:
8107 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8108 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8109 break;
8111 // Soul Siphon
8112 case 4992:
8113 case 4993:
8115 // effect 1 m_amount
8116 int32 maxPercent = (*i)->GetModifier()->m_amount;
8117 // effect 0 m_amount
8118 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
8119 // count affliction effects and calc additional damage in percentage
8120 int32 modPercent = 0;
8121 AuraMap const& victimAuras = pVictim->GetAuras();
8122 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8124 SpellEntry const* m_spell = itr->second->GetSpellProto();
8125 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & UI64LIT(0x0004071B8044C402)))
8126 continue;
8127 modPercent += stepPercent * itr->second->GetStackAmount();
8128 if (modPercent >= maxPercent)
8130 modPercent = maxPercent;
8131 break;
8134 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8135 break;
8137 case 6916: // Death's Embrace
8138 case 6925:
8139 case 6927:
8140 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
8141 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8142 break;
8143 case 5481: // Starfire Bonus
8145 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, UI64LIT(0x0000000000200002)))
8146 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8147 break;
8149 case 4418: // Increased Shock Damage
8150 case 4554: // Increased Lightning Damage
8151 case 4555: // Improved Moonfire
8152 case 5142: // Increased Lightning Damage
8153 case 5147: // Improved Consecration / Libram of Resurgence
8154 case 5148: // Idol of the Shooting Star
8155 case 6008: // Increased Lightning Damage / Totem of Hex
8157 DoneTotal+=(*i)->GetModifier()->m_amount;
8158 break;
8160 // Tundra Stalker
8161 // Merciless Combat
8162 case 7277:
8164 // Merciless Combat
8165 if ((*i)->GetSpellProto()->SpellIconID == 2656)
8167 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8168 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8170 else // Tundra Stalker
8172 // Frost Fever (target debuff)
8173 if (pVictim->GetAura(SPELL_AURA_MOD_HASTE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0000000000000000), 0x00000002))
8174 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8175 break;
8177 break;
8179 case 7293: // Rage of Rivendare
8181 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, UI64LIT(0x0200000000000000)))
8182 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8183 break;
8185 // Twisted Faith
8186 case 7377:
8188 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, UI64LIT(0x0000000000008000), 0, GetGUID()))
8189 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8190 break;
8192 // Marked for Death
8193 case 7598:
8194 case 7599:
8195 case 7600:
8196 case 7601:
8197 case 7602:
8199 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, UI64LIT(0x0000000000000400)))
8200 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8201 break;
8206 // Custom scripted damage
8207 switch(spellProto->SpellFamilyName)
8209 case SPELLFAMILY_MAGE:
8211 // Ice Lance
8212 if (spellProto->SpellIconID == 186)
8214 if (pVictim->isFrozen())
8215 DoneTotalMod *= 3.0f;
8217 // Torment the weak affected (Arcane Barrage, Arcane Blast, Frostfire Bolt, Arcane Missiles, Fireball)
8218 if ((spellProto->SpellFamilyFlags & UI64LIT(0x0000900020200021)) &&
8219 (pVictim->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED) || pVictim->HasAuraType(SPELL_AURA_MELEE_SLOW)))
8221 //Search for Torment the weak dummy aura
8222 Unit::AuraList const& ttw = GetAurasByType(SPELL_AURA_DUMMY);
8223 for(Unit::AuraList::const_iterator i = ttw.begin(); i != ttw.end(); ++i)
8225 if ((*i)->GetSpellProto()->SpellIconID == 3263)
8227 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f) / 100.0f;
8228 break;
8232 break;
8234 default:
8235 break;
8239 // ..taken
8240 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8241 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8242 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
8243 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8245 // .. taken pct: dummy auras
8246 if (pVictim->GetTypeId() == TYPEID_PLAYER)
8248 //Cheat Death
8249 if (Aura *dummy = pVictim->GetDummyAura(45182))
8251 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
8252 if (mod < dummy->GetModifier()->m_amount)
8253 mod = dummy->GetModifier()->m_amount;
8254 TakenTotalMod *= (mod+100.0f)/100.0f;
8258 // From caster spells
8259 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
8260 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
8261 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
8262 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8264 // Mod damage from spell mechanic
8265 if (uint32 mechanicMask = GetAllSpellMechanicMask(spellProto))
8267 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
8268 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
8269 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
8270 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8273 // Mod damage taken from AoE spells
8274 if(IsAreaOfEffectSpell(spellProto))
8276 AuraList const& avoidAuras = pVictim->GetAurasByType(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
8277 for(AuraList::const_iterator itr = avoidAuras.begin(); itr != avoidAuras.end(); ++itr)
8278 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f)/100.0f;
8281 // Taken/Done fixed damage bonus auras
8282 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
8283 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8285 // Pets just add their bonus damage to their spell damage
8286 // note that their spell damage is just gain of their own auras
8287 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
8288 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
8290 float LvlPenalty = CalculateLevelPenalty(spellProto);
8291 // Spellmod SpellDamage
8292 float SpellModSpellDamage = 100.0f;
8293 if(Player* modOwner = GetSpellModOwner())
8294 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
8295 SpellModSpellDamage /= 100.0f;
8297 // Check for table values
8298 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8299 if (bonus)
8301 float coeff;
8302 if (damagetype == DOT)
8303 coeff = bonus->dot_damage * LvlPenalty * stack;
8304 else
8305 coeff = bonus->direct_damage * LvlPenalty * stack;
8307 if (bonus->ap_bonus)
8308 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8310 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8311 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8313 // Default calculation
8314 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8316 // Damage Done from spell damage bonus
8317 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8318 // Damage over Time spells bonus calculation
8319 float DotFactor = 1.0f;
8320 if(damagetype == DOT)
8322 int32 DotDuration = GetSpellDuration(spellProto);
8323 // 200% limit
8324 if(DotDuration > 0)
8326 if(DotDuration > 30000) DotDuration = 30000;
8327 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8328 int x = 0;
8329 for(int j = 0; j < 3; j++)
8331 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8332 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8333 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8335 x = j;
8336 break;
8339 int32 DotTicks = 6;
8340 if(spellProto->EffectAmplitude[x] != 0)
8341 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8342 if(DotTicks)
8344 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8345 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8349 // Distribute Damage over multiple effects, reduce by AoE
8350 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8351 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8352 for(int j = 0; j < 3; ++j)
8354 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8355 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8357 CastingTime /= 2;
8358 break;
8361 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
8362 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
8365 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
8366 // apply spellmod to Done damage (flat and pct)
8367 if(Player* modOwner = GetSpellModOwner())
8368 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
8370 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
8372 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
8375 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
8377 int32 DoneAdvertisedBenefit = 0;
8379 // ..done
8380 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
8381 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
8382 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
8383 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
8384 // -1 == any item class (not wand then)
8385 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
8386 // 0 == any inventory type (not wand then)
8387 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8389 if (GetTypeId() == TYPEID_PLAYER)
8391 // Base value
8392 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
8394 // Damage bonus from stats
8395 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
8396 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
8398 if((*i)->GetModifier()->m_miscvalue & schoolMask)
8400 // stat used stored in miscValueB for this aura
8401 Stats usedStat = Stats((*i)->GetMiscBValue());
8402 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8405 // ... and attack power
8406 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
8407 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
8408 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8409 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8412 return DoneAdvertisedBenefit;
8415 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8417 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8419 int32 TakenAdvertisedBenefit = 0;
8420 // ..done (for creature type by mask) in taken
8421 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8422 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8423 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8424 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8426 // ..taken
8427 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8428 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8429 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8430 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
8432 return TakenAdvertisedBenefit;
8435 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
8437 // not critting spell
8438 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
8439 return false;
8441 float crit_chance = 0.0f;
8442 switch(spellProto->DmgClass)
8444 case SPELL_DAMAGE_CLASS_NONE:
8445 return false;
8446 case SPELL_DAMAGE_CLASS_MAGIC:
8448 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
8449 crit_chance = 0.0f;
8450 // For other schools
8451 else if (GetTypeId() == TYPEID_PLAYER)
8452 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
8453 else
8455 crit_chance = m_baseSpellCritChance;
8456 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
8458 // taken
8459 if (pVictim)
8461 if (!IsPositiveSpell(spellProto->Id))
8463 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
8464 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
8465 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
8466 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
8467 // Modify by player victim resilience
8468 if (pVictim->GetTypeId() == TYPEID_PLAYER)
8469 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
8472 // scripted (increase crit chance ... against ... target by x%
8473 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8474 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8476 if (!((*i)->isAffectedOnSpell(spellProto)))
8477 continue;
8478 switch((*i)->GetModifier()->m_miscvalue)
8480 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
8481 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
8482 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
8483 case 7917: // Glyph of Shadowburn
8484 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8485 crit_chance+=(*i)->GetModifier()->m_amount;
8486 break;
8487 case 7997: // Renewed Hope
8488 case 7998:
8489 if (pVictim->HasAura(6788))
8490 crit_chance+=(*i)->GetModifier()->m_amount;
8491 break;
8492 case 21: // Test of Faith
8493 case 6935:
8494 case 6918:
8495 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8496 crit_chance+=(*i)->GetModifier()->m_amount;
8497 break;
8498 default:
8499 break;
8502 // Custom crit by class
8503 switch(spellProto->SpellFamilyName)
8505 case SPELLFAMILY_PALADIN:
8506 // Sacred Shield
8507 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000000040000000))
8509 Aura *aura = pVictim->GetDummyAura(58597);
8510 if (aura && aura->GetCasterGUID() == GetGUID())
8511 crit_chance+=aura->GetModifier()->m_amount;
8512 break;
8514 // Exorcism
8515 else if (spellProto->Category == 19)
8517 if (pVictim->GetCreatureTypeMask() & CREATURE_TYPEMASK_DEMON_OR_UNDEAD)
8518 return true;
8519 break;
8521 break;
8522 case SPELLFAMILY_SHAMAN:
8523 // Lava Burst
8524 if (spellProto->SpellFamilyFlags & UI64LIT(0x0000100000000000))
8526 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID()))
8528 // Consume shock aura if not have Glyph of Flame Shock
8529 if (!GetAura(55447, 0))
8530 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
8531 return true;
8533 break;
8535 break;
8538 break;
8540 case SPELL_DAMAGE_CLASS_MELEE:
8542 // Judgement of Command proc always crits on stunned target
8543 if(spellProto->SpellFamilyName == SPELLFAMILY_PALADIN)
8545 if(spellProto->SpellFamilyFlags & 0x0000000000800000LL && spellProto->SpellIconID == 561)
8547 if(pVictim->hasUnitState(UNIT_STAT_STUNNED))
8548 return true;
8552 case SPELL_DAMAGE_CLASS_RANGED:
8554 if (pVictim)
8556 crit_chance = GetUnitCriticalChance(attackType, pVictim);
8557 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
8559 break;
8561 default:
8562 return false;
8564 // percent done
8565 // only players use intelligence for critical chance computations
8566 if(Player* modOwner = GetSpellModOwner())
8567 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
8569 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
8570 if (roll_chance_f(crit_chance))
8571 return true;
8572 return false;
8575 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8577 // Calculate critical bonus
8578 int32 crit_bonus;
8579 switch(spellProto->DmgClass)
8581 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8582 case SPELL_DAMAGE_CLASS_RANGED:
8583 // TODO: write here full calculation for melee/ranged spells
8584 crit_bonus = damage;
8585 break;
8586 default:
8587 crit_bonus = damage / 2; // for spells is 50%
8588 break;
8591 // adds additional damage to crit_bonus (from talents)
8592 if(Player* modOwner = GetSpellModOwner())
8593 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
8595 if(pVictim)
8597 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8598 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8601 if(crit_bonus > 0)
8602 damage += crit_bonus;
8604 return damage;
8607 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8609 // Calculate critical bonus
8610 int32 crit_bonus;
8611 switch(spellProto->DmgClass)
8613 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8614 case SPELL_DAMAGE_CLASS_RANGED:
8615 // TODO: write here full calculation for melee/ranged spells
8616 crit_bonus = damage;
8617 break;
8618 default:
8619 crit_bonus = damage / 2; // for spells is 50%
8620 break;
8623 if(pVictim)
8625 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8626 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8629 if(crit_bonus > 0)
8630 damage += crit_bonus;
8632 damage = int32(damage * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT));
8634 return damage;
8637 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
8639 // No heal amount for this class spells
8640 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
8641 return healamount;
8643 // For totems get healing bonus from owner (statue isn't totem in fact)
8644 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8645 if(Unit* owner = GetOwner())
8646 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
8648 // Healing Done
8649 // Taken/Done total percent damage auras
8650 float DoneTotalMod = 1.0f;
8651 float TakenTotalMod = 1.0f;
8652 int32 DoneTotal = 0;
8653 int32 TakenTotal = 0;
8655 // Healing done percent
8656 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8657 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8658 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8660 // done scripted mod (take it from owner)
8661 Unit *owner = GetOwner();
8662 if (!owner) owner = this;
8663 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8664 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8666 if (!(*i)->isAffectedOnSpell(spellProto))
8667 continue;
8668 switch((*i)->GetModifier()->m_miscvalue)
8670 case 4415: // Increased Rejuvenation Healing
8671 case 4953:
8672 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
8673 DoneTotal+=(*i)->GetModifier()->m_amount;
8674 break;
8675 case 7997: // Renewed Hope
8676 case 7998:
8677 if (pVictim->HasAura(6788))
8678 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8679 break;
8680 case 21: // Test of Faith
8681 case 6935:
8682 case 6918:
8683 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8684 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8685 break;
8686 case 7798: // Glyph of Regrowth
8688 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, UI64LIT(0x0000000000000040)))
8689 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8690 break;
8692 case 8477: // Nourish Heal Boost
8694 int32 stepPercent = (*i)->GetModifier()->m_amount;
8695 int32 modPercent = 0;
8696 AuraMap const& victimAuras = pVictim->GetAuras();
8697 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8699 if (itr->second->GetCasterGUID()!=GetGUID())
8700 continue;
8701 SpellEntry const* m_spell = itr->second->GetSpellProto();
8702 if (m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8703 !(m_spell->SpellFamilyFlags & UI64LIT(0x0000001000000050)))
8704 continue;
8705 modPercent += stepPercent * itr->second->GetStackAmount();
8707 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8708 break;
8710 case 7871: // Glyph of Lesser Healing Wave
8712 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, UI64LIT(0x0000040000000000), 0, GetGUID()))
8713 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8714 break;
8716 default:
8717 break;
8721 // Taken/Done fixed damage bonus auras
8722 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8723 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8725 float LvlPenalty = CalculateLevelPenalty(spellProto);
8726 // Spellmod SpellDamage
8727 float SpellModSpellDamage = 100.0f;
8728 if(Player* modOwner = GetSpellModOwner())
8729 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8730 SpellModSpellDamage /= 100.0f;
8732 // Check for table values
8733 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8734 if (bonus)
8736 float coeff;
8737 if (damagetype == DOT)
8738 coeff = bonus->dot_damage * LvlPenalty * stack;
8739 else
8740 coeff = bonus->direct_damage * LvlPenalty * stack;
8742 if (bonus->ap_bonus)
8743 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8745 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8746 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8748 // Default calculation
8749 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8751 // Damage Done from spell damage bonus
8752 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8753 // Damage over Time spells bonus calculation
8754 float DotFactor = 1.0f;
8755 if(damagetype == DOT)
8757 int32 DotDuration = GetSpellDuration(spellProto);
8758 // 200% limit
8759 if(DotDuration > 0)
8761 if(DotDuration > 30000) DotDuration = 30000;
8762 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8763 int x = 0;
8764 for(int j = 0; j < 3; j++)
8766 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8767 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8768 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8770 x = j;
8771 break;
8774 int32 DotTicks = 6;
8775 if(spellProto->EffectAmplitude[x] != 0)
8776 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8777 if(DotTicks)
8779 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8780 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8784 // Distribute Damage over multiple effects, reduce by AoE
8785 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8786 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8787 for(int j = 0; j < 3; ++j)
8789 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8790 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8792 CastingTime /= 2;
8793 break;
8796 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
8797 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
8800 // use float as more appropriate for negative values and percent applying
8801 float heal = (healamount + DoneTotal)*DoneTotalMod;
8802 // apply spellmod to Done amount
8803 if(Player* modOwner = GetSpellModOwner())
8804 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8806 // Taken mods
8807 // Healing Wave cast
8808 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000000040)))
8810 // Search for Healing Way on Victim
8811 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8812 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8813 if((*itr)->GetId() == 29203)
8814 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8817 // Healing taken percent
8818 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8819 if(minval)
8820 TakenTotalMod *= (100.0f + minval) / 100.0f;
8822 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8823 if(maxval)
8824 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8826 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8827 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8828 if ((*i)->isAffectedOnSpell(spellProto))
8829 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8831 heal = (heal + TakenTotal) * TakenTotalMod;
8833 return heal < 0 ? 0 : uint32(heal);
8836 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8838 int32 AdvertisedBenefit = 0;
8840 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8841 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8842 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8843 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8845 // Healing bonus of spirit, intellect and strength
8846 if (GetTypeId() == TYPEID_PLAYER)
8848 // Base value
8849 AdvertisedBenefit +=((Player*)this)->GetBaseSpellPowerBonus();
8851 // Healing bonus from stats
8852 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8853 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8855 // stat used dependent from misc value (stat index)
8856 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8857 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8860 // ... and attack power
8861 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8862 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8863 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8864 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8866 return AdvertisedBenefit;
8869 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8871 int32 AdvertisedBenefit = 0;
8872 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8873 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8874 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8875 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8876 return AdvertisedBenefit;
8879 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8881 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8882 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8883 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8884 if(itr->type & shoolMask)
8885 return true;
8887 //If m_immuneToDamage type contain magic, IMMUNE damage.
8888 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8889 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8890 if(itr->type & shoolMask)
8891 return true;
8893 return false;
8896 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8898 if (!spellInfo)
8899 return false;
8901 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
8902 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
8904 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8905 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8906 if(itr->type == spellInfo->Dispel)
8907 return true;
8909 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8910 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8912 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8913 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8914 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8915 (itr->type & GetSpellSchoolMask(spellInfo)) )
8916 return true;
8919 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8920 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8922 if(itr->type == spellInfo->Mechanic)
8924 return true;
8928 return false;
8931 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8933 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8934 uint32 effect = spellInfo->Effect[index];
8935 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8936 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8937 if(itr->type == effect)
8938 return true;
8940 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8942 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8943 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8944 if(itr->type == mechanic)
8945 return true;
8948 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8950 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8951 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8952 if(itr->type == aura)
8953 return true;
8954 // Check for immune to application of harmful magical effects
8955 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8956 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8957 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8958 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8959 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8960 return true;
8963 return false;
8966 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8968 if(!spellInfo)
8969 return false;
8971 uint32 family = spellInfo->SpellFamilyName;
8972 uint64 flags = spellInfo->SpellFamilyFlags;
8974 if((family == 5 && flags == 256) || //Searing Pain
8975 (family == 6 && flags == 8192) || //Mind Blast
8976 (family == 11 && flags == 1048576)) //Earth Shock
8977 return true;
8979 return false;
8982 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8984 if(!pVictim)
8985 return;
8987 if(*pdamage == 0)
8988 return;
8990 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8992 // Taken/Done fixed damage bonus auras
8993 int32 DoneFlatBenefit = 0;
8994 int32 TakenFlatBenefit = 0;
8996 // ..done (for creature type by mask) in taken
8997 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8998 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8999 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
9000 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
9002 // ..done
9003 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
9005 // ..done (base at attack power for marked target and base at attack power for creature type)
9006 int32 APbonus = 0;
9007 if(attType == RANGED_ATTACK)
9009 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
9011 // ..done (base at attack power and creature type)
9012 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
9013 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
9014 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
9015 APbonus += (*i)->GetModifier()->m_amount;
9017 else
9019 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
9021 // ..done (base at attack power and creature type)
9022 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
9023 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
9024 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
9025 APbonus += (*i)->GetModifier()->m_amount;
9028 if (APbonus!=0) // Can be negative
9030 bool normalized = false;
9031 if(spellProto)
9033 for (uint8 i = 0; i<3;++i)
9035 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
9037 normalized = true;
9038 break;
9043 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
9046 // ..taken
9047 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
9048 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
9049 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
9050 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
9052 if(attType!=RANGED_ATTACK)
9053 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
9054 else
9055 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
9057 // Done/Taken total percent damage auras
9058 float DoneTotalMod = 1.0f;
9059 float TakenTotalMod = 1.0f;
9061 // ..done
9062 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
9063 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
9065 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
9066 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
9067 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
9068 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9070 // ..taken
9071 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
9072 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
9073 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
9074 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9076 // .. taken pct (special attacks)
9077 if (spellProto)
9079 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
9081 // Shred also have bonus as MECHANIC_BLEED damages
9082 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags & UI64LIT(0x00008000)))
9083 mechanicMask |= (1 << MECHANIC_BLEED);
9085 // Mod damage from spell mechanic
9086 if (mechanicMask)
9088 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
9089 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
9090 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
9091 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9095 // .. taken pct: dummy auras
9096 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
9097 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
9099 switch((*i)->GetSpellProto()->SpellIconID)
9101 //Cheat Death
9102 case 2109:
9103 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
9105 if(pVictim->GetTypeId() != TYPEID_PLAYER)
9106 continue;
9107 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
9108 if (mod < (*i)->GetModifier()->m_amount)
9109 mod = (*i)->GetModifier()->m_amount;
9110 TakenTotalMod *= (mod+100.0f)/100.0f;
9112 break;
9116 // .. taken pct: class scripts
9117 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
9118 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
9120 switch((*i)->GetMiscValue())
9122 case 6427: case 6428: // Dirty Deeds
9123 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
9125 Aura* eff0 = GetAura((*i)->GetId(),0);
9126 if(!eff0 || (*i)->GetEffIndex()!=1)
9128 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
9129 continue;
9132 // effect 0 have expected value but in negative state
9133 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
9135 break;
9139 if(attType != RANGED_ATTACK)
9141 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
9142 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
9143 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9145 else
9147 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
9148 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
9149 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
9152 // Mod damage taken from AoE spells
9153 if(spellProto && IsAreaOfEffectSpell(spellProto))
9155 AuraList const& avoidAuras = pVictim->GetAurasByType(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE);
9156 for(AuraList::const_iterator itr = avoidAuras.begin(); itr != avoidAuras.end(); ++itr)
9157 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f)/100.0f;
9160 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
9162 // apply spellmod to Done damage
9163 if(spellProto)
9165 if(Player* modOwner = GetSpellModOwner())
9166 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
9169 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
9171 // bonus result can be negative
9172 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
9175 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
9177 if (apply)
9179 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
9181 next = itr; ++next;
9182 if(itr->type == type)
9184 m_spellImmune[op].erase(itr);
9185 next = m_spellImmune[op].begin();
9188 SpellImmune Immune;
9189 Immune.spellId = spellId;
9190 Immune.type = type;
9191 m_spellImmune[op].push_back(Immune);
9193 else
9195 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
9197 if(itr->spellId == spellId)
9199 m_spellImmune[op].erase(itr);
9200 break;
9207 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
9209 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
9211 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
9212 RemoveAurasWithDispelType(type);
9215 float Unit::GetWeaponProcChance() const
9217 // normalized proc chance for weapon attack speed
9218 // (odd formula...)
9219 if(isAttackReady(BASE_ATTACK))
9220 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
9221 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
9222 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
9223 return 0;
9226 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
9228 // proc per minute chance calculation
9229 if (PPM <= 0) return 0.0f;
9230 return WeaponSpeed * PPM / 600.0f; // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
9233 void Unit::Mount(uint32 mount)
9235 if(!mount)
9236 return;
9238 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
9240 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
9242 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
9244 // unsummon pet
9245 if(GetTypeId() == TYPEID_PLAYER)
9246 ((Player*)this)->UnsummonPetTemporaryIfAny();
9249 void Unit::Unmount()
9251 if(!IsMounted())
9252 return;
9254 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
9256 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
9257 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
9259 // only resummon old pet if the player is already added to a map
9260 // this prevents adding a pet to a not created map which would otherwise cause a crash
9261 // (it could probably happen when logging in after a previous crash)
9262 if(GetTypeId() == TYPEID_PLAYER)
9263 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
9266 void Unit::SetInCombatWith(Unit* enemy)
9268 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
9269 if(eOwner->IsPvP())
9271 SetInCombatState(true,enemy);
9272 return;
9275 //check for duel
9276 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
9278 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
9279 if(((Player const*)eOwner)->duel->opponent == myOwner)
9281 SetInCombatState(true,enemy);
9282 return;
9285 SetInCombatState(false,enemy);
9288 void Unit::SetInCombatState(bool PvP, Unit* enemy)
9290 // only alive units can be in combat
9291 if(!isAlive())
9292 return;
9294 if(PvP)
9295 m_CombatTimer = 5000;
9297 bool creatureNotInCombat = GetTypeId()==TYPEID_UNIT && !HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9299 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9301 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
9302 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
9304 if (creatureNotInCombat)
9306 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
9308 if (((Creature*)this)->AI())
9309 ((Creature*)this)->AI()->EnterCombat(enemy);
9313 void Unit::ClearInCombat()
9315 m_CombatTimer = 0;
9316 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
9318 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
9319 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
9321 // Player's state will be cleared in Player::UpdateContestedPvP
9322 if (GetTypeId() != TYPEID_PLAYER)
9324 if (((Creature*)this)->GetCreatureInfo()->unit_flags & UNIT_FLAG_OOC_NOT_ATTACKABLE)
9325 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE);
9327 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
9329 else
9330 ((Player*)this)->UpdatePotionCooldown();
9333 bool Unit::isTargetableForAttack() const
9335 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
9336 return false;
9338 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
9339 return false;
9341 // to be removed if unit by any reason enter combat
9342 if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE))
9343 return false;
9345 return IsInWorld() && isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
9348 int32 Unit::ModifyHealth(int32 dVal)
9350 int32 gain = 0;
9352 if(dVal==0)
9353 return 0;
9355 int32 curHealth = (int32)GetHealth();
9357 int32 val = dVal + curHealth;
9358 if(val <= 0)
9360 SetHealth(0);
9361 return -curHealth;
9364 int32 maxHealth = (int32)GetMaxHealth();
9366 if(val < maxHealth)
9368 SetHealth(val);
9369 gain = val - curHealth;
9371 else if(curHealth != maxHealth)
9373 SetHealth(maxHealth);
9374 gain = maxHealth - curHealth;
9377 return gain;
9380 int32 Unit::ModifyPower(Powers power, int32 dVal)
9382 int32 gain = 0;
9384 if(dVal==0)
9385 return 0;
9387 int32 curPower = (int32)GetPower(power);
9389 int32 val = dVal + curPower;
9390 if(val <= 0)
9392 SetPower(power,0);
9393 return -curPower;
9396 int32 maxPower = (int32)GetMaxPower(power);
9398 if(val < maxPower)
9400 SetPower(power,val);
9401 gain = val - curPower;
9403 else if(curPower != maxPower)
9405 SetPower(power,maxPower);
9406 gain = maxPower - curPower;
9409 return gain;
9412 bool Unit::isVisibleForOrDetect(Unit const* u, WorldObject const* viewPoint, bool detect, bool inVisibleList, bool is3dDistance) const
9414 if(!u)
9415 return false;
9417 // Always can see self
9418 if (u==this)
9419 return true;
9421 // player visible for other player if not logout and at same transport
9422 // including case when player is out of world
9423 bool at_same_transport =
9424 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
9425 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
9426 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
9427 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
9429 // not in world
9430 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
9431 return false;
9433 // forbidden to seen (at GM respawn command)
9434 if(m_Visibility==VISIBILITY_RESPAWN)
9435 return false;
9437 // Grid dead/alive checks
9438 if( u->GetTypeId()==TYPEID_PLAYER)
9440 // non visible at grid for any stealth state
9441 if(!IsVisibleInGridForPlayer((Player *)u))
9442 return false;
9444 // if player is dead then he can't detect anyone in any cases
9445 if(!u->isAlive())
9446 detect = false;
9448 else
9450 // all dead creatures/players not visible for any creatures
9451 if(!u->isAlive() || !isAlive())
9452 return false;
9455 // always seen by owner
9456 if(GetCharmerOrOwnerGUID()==u->GetGUID())
9457 return true;
9459 // always seen by far sight caster
9460 if( u->GetTypeId()==TYPEID_PLAYER && ((Player*)u)->GetFarSight()==GetGUID())
9461 return true;
9463 // different visible distance checks
9464 if(u->isInFlight()) // what see player in flight
9466 // use object grey distance for all (only see objects any way)
9467 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
9468 return false;
9470 else if(!isAlive()) // distance for show body
9472 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
9473 return false;
9475 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
9477 if(u->GetTypeId()==TYPEID_PLAYER)
9479 // Players far than max visible distance for player or not in our map are not visible too
9480 if (!at_same_transport && !IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9481 return false;
9483 else
9485 // Units far than max visible distance for creature or not in our map are not visible too
9486 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9487 return false;
9490 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
9492 // Pet/charmed far than max visible distance for player or not in our map are not visible too
9493 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9494 return false;
9496 else // distance for show creature
9498 // Units far than max visible distance for creature or not in our map are not visible too
9499 if (!IsWithinDistInMap(viewPoint,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
9500 return false;
9503 // Visible units, always are visible for all units, except for units under invisibility and phases
9504 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
9505 return true;
9507 // GMs see any players, not higher GMs and all units in any phase
9508 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
9510 if(GetTypeId() == TYPEID_PLAYER)
9511 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
9512 else
9513 return true;
9516 // non faction visibility non-breakable for non-GMs
9517 if (m_Visibility == VISIBILITY_OFF)
9518 return false;
9520 // phased visibility (both must phased in same way)
9521 if(!InSamePhase(u))
9522 return false;
9524 // raw invisibility
9525 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
9527 // detectable invisibility case
9528 if( invisible && (
9529 // Invisible units, always are visible for units under same invisibility type
9530 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
9531 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
9532 u->canDetectInvisibilityOf(this) ||
9533 // Units that can detect invisibility always are visible for units that can be detected
9534 canDetectInvisibilityOf(u) ))
9536 invisible = false;
9539 // special cases for always overwrite invisibility/stealth
9540 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
9542 // non-hostile case
9543 if (!u->IsHostileTo(this))
9545 // 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)
9546 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
9548 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
9549 return true;
9551 // else apply same rules as for hostile case (detecting check for stealth)
9554 // hostile case
9555 else
9557 // Hunter mark functionality
9558 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
9559 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
9560 if((*iter)->GetCasterGUID()==u->GetGUID())
9561 return true;
9563 // else apply detecting check for stealth
9566 // none other cases for detect invisibility, so invisible
9567 if(invisible)
9568 return false;
9570 // else apply stealth detecting check
9573 // unit got in stealth in this moment and must ignore old detected state
9574 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
9575 return false;
9577 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
9578 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
9579 return true;
9581 // NOW ONLY STEALTH CASE
9583 //if in non-detect mode then invisible for unit
9584 //mobs always detect players (detect == true)... return 'false' for those mobs which have (detect == false)
9585 //players detect players only in Player::HandleStealthedUnitsDetection()
9586 if (!detect)
9587 return (u->GetTypeId() == TYPEID_PLAYER) ? ((Player*)u)->HaveAtClient(this) : false;
9589 // Special cases
9591 // If is attacked then stealth is lost, some creature can use stealth too
9592 if( !getAttackers().empty() )
9593 return true;
9595 // If there is collision rogue is seen regardless of level difference
9596 if (IsWithinDist(u,0.24f))
9597 return true;
9599 //If a mob or player is stunned he will not be able to detect stealth
9600 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
9601 return false;
9603 // set max ditance
9604 float visibleDistance = (u->GetTypeId() == TYPEID_PLAYER) ? MAX_PLAYER_STEALTH_DETECT_RANGE : ((Creature const*)u)->GetAttackDistance(this);
9606 //Always invisible from back (when stealth detection is on), also filter max distance cases
9607 bool isInFront = viewPoint->isInFrontInMap(this, visibleDistance);
9608 if(!isInFront)
9609 return false;
9611 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
9612 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
9614 //Calculation if target is in front
9616 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
9617 visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
9619 //Visible distance is modified by
9620 //-Level Diff (every level diff = 1.0f in visible distance)
9621 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
9623 //This allows to check talent tree and will add addition stealth dependent on used points)
9624 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
9625 if(stealthMod < 0)
9626 stealthMod = 0;
9628 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
9629 //based on wowwiki every 5 mod we have 1 more level diff in calculation
9630 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
9631 visibleDistance = visibleDistance > MAX_PLAYER_STEALTH_DETECT_RANGE ? MAX_PLAYER_STEALTH_DETECT_RANGE : visibleDistance;
9633 // recheck new distance
9634 if(visibleDistance <= 0 || !IsWithinDist(viewPoint,visibleDistance))
9635 return false;
9638 // Now check is target visible with LoS
9639 float ox,oy,oz;
9640 viewPoint->GetPosition(ox,oy,oz);
9641 return IsWithinLOS(ox,oy,oz);
9644 void Unit::SetVisibility(UnitVisibility x)
9646 m_Visibility = x;
9648 if(IsInWorld())
9650 Map *m = GetMap();
9652 if(GetTypeId()==TYPEID_PLAYER)
9653 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9654 else
9655 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9659 bool Unit::canDetectInvisibilityOf(Unit const* u) const
9661 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
9663 for(uint32 i = 0; i < 10; ++i)
9665 if(((1 << i) & mask)==0)
9666 continue;
9668 // find invisibility level
9669 uint32 invLevel = 0;
9670 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
9671 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
9672 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
9673 invLevel = (*itr)->GetModifier()->m_amount;
9675 // find invisibility detect level
9676 uint32 detectLevel = 0;
9677 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
9678 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
9679 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
9680 detectLevel = (*itr)->GetModifier()->m_amount;
9682 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
9684 detectLevel = ((Player*)this)->GetDrunkValue();
9687 if(invLevel <= detectLevel)
9688 return true;
9692 return false;
9695 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
9697 int32 main_speed_mod = 0;
9698 float stack_bonus = 1.0f;
9699 float non_stack_bonus = 1.0f;
9701 switch(mtype)
9703 case MOVE_WALK:
9704 return;
9705 case MOVE_RUN:
9707 if (IsMounted()) // Use on mount auras
9709 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
9710 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
9711 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
9713 else
9715 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
9716 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
9717 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
9719 break;
9721 case MOVE_RUN_BACK:
9722 return;
9723 case MOVE_SWIM:
9725 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
9726 break;
9728 case MOVE_SWIM_BACK:
9729 return;
9730 case MOVE_FLIGHT:
9732 if (IsMounted()) // Use on mount auras
9733 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9734 else // Use not mount (shapeshift for example) auras (should stack)
9735 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9736 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9737 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9738 break;
9740 case MOVE_FLIGHT_BACK:
9741 return;
9742 default:
9743 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9744 return;
9747 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9748 // now we ready for speed calculation
9749 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9751 switch(mtype)
9753 case MOVE_RUN:
9754 case MOVE_SWIM:
9755 case MOVE_FLIGHT:
9757 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9758 // TODO: possible affect only on MOVE_RUN
9759 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9761 // Use speed from aura
9762 float max_speed = normalization / baseMoveSpeed[mtype];
9763 if (speed > max_speed)
9764 speed = max_speed;
9766 break;
9768 default:
9769 break;
9772 // Apply strongest slow aura mod to speed
9773 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9774 if (slow)
9775 speed *=(100.0f + slow)/100.0f;
9776 SetSpeed(mtype, speed, forced);
9779 float Unit::GetSpeed( UnitMoveType mtype ) const
9781 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9784 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9786 if (rate < 0)
9787 rate = 0.0f;
9789 // Update speed only on change
9790 if (m_speed_rate[mtype] == rate)
9791 return;
9793 m_speed_rate[mtype] = rate;
9795 propagateSpeedChange();
9797 WorldPacket data;
9798 if(!forced)
9800 switch(mtype)
9802 case MOVE_WALK:
9803 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9804 break;
9805 case MOVE_RUN:
9806 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9807 break;
9808 case MOVE_RUN_BACK:
9809 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9810 break;
9811 case MOVE_SWIM:
9812 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9813 break;
9814 case MOVE_SWIM_BACK:
9815 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9816 break;
9817 case MOVE_TURN_RATE:
9818 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9819 break;
9820 case MOVE_FLIGHT:
9821 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9822 break;
9823 case MOVE_FLIGHT_BACK:
9824 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9825 break;
9826 case MOVE_PITCH_RATE:
9827 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9828 break;
9829 default:
9830 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9831 return;
9834 data.append(GetPackGUID());
9835 data << uint32(0); // movement flags
9836 data << uint16(0); // unk flags
9837 data << uint32(getMSTime());
9838 data << float(GetPositionX());
9839 data << float(GetPositionY());
9840 data << float(GetPositionZ());
9841 data << float(GetOrientation());
9842 data << uint32(0); // fall time
9843 data << float(GetSpeed(mtype));
9844 SendMessageToSet( &data, true );
9846 else
9848 if(GetTypeId() == TYPEID_PLAYER)
9850 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9851 // and do it only for real sent packets and use run for run/mounted as client expected
9852 ++((Player*)this)->m_forced_speed_changes[mtype];
9855 switch(mtype)
9857 case MOVE_WALK:
9858 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9859 break;
9860 case MOVE_RUN:
9861 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9862 break;
9863 case MOVE_RUN_BACK:
9864 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9865 break;
9866 case MOVE_SWIM:
9867 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9868 break;
9869 case MOVE_SWIM_BACK:
9870 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9871 break;
9872 case MOVE_TURN_RATE:
9873 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9874 break;
9875 case MOVE_FLIGHT:
9876 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9877 break;
9878 case MOVE_FLIGHT_BACK:
9879 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9880 break;
9881 case MOVE_PITCH_RATE:
9882 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9883 break;
9884 default:
9885 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9886 return;
9888 data.append(GetPackGUID());
9889 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9890 if (mtype == MOVE_RUN)
9891 data << uint8(0); // new 2.1.0
9892 data << float(GetSpeed(mtype));
9893 SendMessageToSet( &data, true );
9895 if(Pet* pet = GetPet())
9896 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9899 void Unit::SetHover(bool on)
9901 if(on)
9902 CastSpell(this, 11010, true);
9903 else
9904 RemoveAurasDueToSpell(11010);
9907 void Unit::setDeathState(DeathState s)
9909 if (s != ALIVE && s!= JUST_ALIVED)
9911 CombatStop();
9912 DeleteThreatList();
9913 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9915 if(IsNonMeleeSpellCasted(false))
9916 InterruptNonMeleeSpells(false);
9919 if (s == JUST_DIED)
9921 RemoveAllAurasOnDeath();
9922 RemoveGuardians();
9923 UnsummonAllTotems();
9925 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9926 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9927 // remove aurastates allowing special moves
9928 ClearAllReactives();
9929 ClearDiminishings();
9931 else if(s == JUST_ALIVED)
9933 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9936 if (m_deathState != ALIVE && s == ALIVE)
9938 //_ApplyAllAuraMods();
9940 m_deathState = s;
9943 /*########################################
9944 ######## ########
9945 ######## AGGRO SYSTEM ########
9946 ######## ########
9947 ########################################*/
9948 bool Unit::CanHaveThreatList() const
9950 // only creatures can have threat list
9951 if( GetTypeId() != TYPEID_UNIT )
9952 return false;
9954 // only alive units can have threat list
9955 if( !isAlive() )
9956 return false;
9958 // totems can not have threat list
9959 if( ((Creature*)this)->isTotem() )
9960 return false;
9962 // vehicles can not have threat list
9963 if( ((Creature*)this)->isVehicle() )
9964 return false;
9966 // pets can not have a threat list, unless they are controlled by a creature
9967 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9968 return false;
9970 return true;
9973 //======================================================================
9975 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9977 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9978 return threat;
9980 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9982 return threat * m_threatModifier[school];
9985 //======================================================================
9987 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9989 // Only mobs can manage threat lists
9990 if(CanHaveThreatList())
9991 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9994 //======================================================================
9996 void Unit::DeleteThreatList()
9998 m_ThreatManager.clearReferences();
10001 //======================================================================
10003 void Unit::TauntApply(Unit* taunter)
10005 assert(GetTypeId()== TYPEID_UNIT);
10007 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
10008 return;
10010 if(!CanHaveThreatList())
10011 return;
10013 Unit *target = getVictim();
10014 if(target && target == taunter)
10015 return;
10017 SetInFront(taunter);
10018 if (((Creature*)this)->AI())
10019 ((Creature*)this)->AI()->AttackStart(taunter);
10021 m_ThreatManager.tauntApply(taunter);
10024 //======================================================================
10026 void Unit::TauntFadeOut(Unit *taunter)
10028 assert(GetTypeId()== TYPEID_UNIT);
10030 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
10031 return;
10033 if(!CanHaveThreatList())
10034 return;
10036 Unit *target = getVictim();
10037 if(!target || target != taunter)
10038 return;
10040 if(m_ThreatManager.isThreatListEmpty())
10042 if(((Creature*)this)->AI())
10043 ((Creature*)this)->AI()->EnterEvadeMode();
10044 return;
10047 m_ThreatManager.tauntFadeOut(taunter);
10048 target = m_ThreatManager.getHostilTarget();
10050 if (target && target != taunter)
10052 SetInFront(target);
10053 if (((Creature*)this)->AI())
10054 ((Creature*)this)->AI()->AttackStart(target);
10058 //======================================================================
10060 bool Unit::SelectHostilTarget()
10062 //function provides main threat functionality
10063 //next-victim-selection algorithm and evade mode are called
10064 //threat list sorting etc.
10066 assert(GetTypeId()== TYPEID_UNIT);
10068 if (!this->isAlive())
10069 return false;
10070 //This function only useful once AI has been initialized
10071 if (!((Creature*)this)->AI())
10072 return false;
10074 Unit* target = NULL;
10076 // First checking if we have some taunt on us
10077 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
10078 if ( !tauntAuras.empty() )
10080 Unit* caster;
10082 // The last taunt aura caster is alive an we are happy to attack him
10083 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
10084 return true;
10085 else if (tauntAuras.size() > 1)
10087 // We do not have last taunt aura caster but we have more taunt auras,
10088 // so find first available target
10090 // Auras are pushed_back, last caster will be on the end
10091 AuraList::const_iterator aura = --tauntAuras.end();
10094 --aura;
10095 if ( (caster = (*aura)->GetCaster()) &&
10096 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
10098 target = caster;
10099 break;
10101 }while (aura != tauntAuras.begin());
10105 if ( !target && !m_ThreatManager.isThreatListEmpty() )
10106 // No taunt aura or taunt aura caster is dead standart target selection
10107 target = m_ThreatManager.getHostilTarget();
10109 if(target)
10111 if(!hasUnitState(UNIT_STAT_STUNNED))
10112 SetInFront(target);
10113 ((Creature*)this)->AI()->AttackStart(target);
10114 return true;
10117 // no target but something prevent go to evade mode
10118 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
10119 return false;
10121 // last case when creature don't must go to evade mode:
10122 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
10123 // for example at owner command to pet attack some far away creature
10124 // Note: creature not have targeted movement generator but have attacker in this case
10125 if (GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE || hasUnitState(UNIT_STAT_FOLLOW))
10127 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
10129 if ((*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this))
10130 return false;
10134 // enter in evade mode in other case
10135 ((Creature*)this)->AI()->EnterEvadeMode();
10137 return false;
10140 //======================================================================
10141 //======================================================================
10142 //======================================================================
10144 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
10146 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
10148 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
10150 int32 level = int32(getLevel());
10151 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
10152 level = (int32)spellProto->maxLevel;
10153 else if (level < (int32)spellProto->baseLevel)
10154 level = (int32)spellProto->baseLevel;
10155 level-= (int32)spellProto->spellLevel;
10157 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
10158 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
10159 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
10160 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
10161 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
10163 // range can have possitive and negative values, so order its for irand
10164 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
10165 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
10166 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
10168 int32 value = basePoints + randvalue;
10169 //random damage
10170 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
10171 value += (int32)(comboDamage * comboPoints);
10173 if(Player* modOwner = GetSpellModOwner())
10175 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
10176 switch(effect_index)
10178 case 0:
10179 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
10180 break;
10181 case 1:
10182 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
10183 break;
10184 case 2:
10185 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
10186 break;
10190 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
10191 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
10192 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK &&
10193 (spellProto->Effect[effect_index] != SPELL_EFFECT_APPLY_AURA || spellProto->EffectApplyAuraName[effect_index] != SPELL_AURA_MOD_DECREASE_SPEED))
10194 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
10196 return value;
10199 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
10201 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
10203 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
10205 int32 minduration = GetSpellDuration(spellProto);
10206 int32 maxduration = GetSpellMaxDuration(spellProto);
10208 int32 duration;
10210 if( minduration != -1 && minduration != maxduration )
10211 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
10212 else
10213 duration = minduration;
10215 if (duration > 0)
10217 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
10218 // Find total mod value (negative bonus)
10219 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
10220 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
10221 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
10222 // Find max mod (negative bonus)
10223 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
10225 int32 durationMod = 0;
10226 // Select strongest negative mod
10227 if (durationMod_always > durationMod_not_stack)
10228 durationMod = durationMod_not_stack;
10229 else
10230 durationMod = durationMod_always;
10232 if (durationMod != 0)
10233 duration = int32(int64(duration) * (100+durationMod) /100);
10235 if (duration < 0) duration = 0;
10238 return duration;
10241 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
10243 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10245 if(i->DRGroup != group)
10246 continue;
10248 if(!i->hitCount)
10249 return DIMINISHING_LEVEL_1;
10251 if(!i->hitTime)
10252 return DIMINISHING_LEVEL_1;
10254 // If last spell was casted more than 15 seconds ago - reset the count.
10255 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
10257 i->hitCount = DIMINISHING_LEVEL_1;
10258 return DIMINISHING_LEVEL_1;
10260 // or else increase the count.
10261 else
10263 return DiminishingLevels(i->hitCount);
10266 return DIMINISHING_LEVEL_1;
10269 void Unit::IncrDiminishing(DiminishingGroup group)
10271 // Checking for existing in the table
10272 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10274 if(i->DRGroup != group)
10275 continue;
10276 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
10277 i->hitCount += 1;
10278 return;
10280 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
10283 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level, int32 limitduration)
10285 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
10286 return;
10288 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
10289 if(limitduration > 0 && duration > limitduration)
10291 // test pet/charm masters instead pets/charmeds
10292 Unit const* targetOwner = GetCharmerOrOwner();
10293 Unit const* casterOwner = caster->GetCharmerOrOwner();
10295 Unit const* target = targetOwner ? targetOwner : this;
10296 Unit const* source = casterOwner ? casterOwner : caster;
10298 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
10299 duration = limitduration;
10302 float mod = 1.0f;
10304 // Some diminishings applies to mobs too (for example, Stun)
10305 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
10307 DiminishingLevels diminish = Level;
10308 switch(diminish)
10310 case DIMINISHING_LEVEL_1: break;
10311 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
10312 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
10313 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
10314 default: break;
10318 duration = int32(duration * mod);
10321 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
10323 // Checking for existing in the table
10324 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
10326 if(i->DRGroup != group)
10327 continue;
10329 if(apply)
10330 i->stack += 1;
10331 else if(i->stack)
10333 i->stack -= 1;
10334 // Remember time after last aura from group removed
10335 if (i->stack == 0)
10336 i->hitTime = getMSTime();
10338 break;
10342 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
10344 return ObjectAccessor::GetUnit(object,guid);
10347 bool Unit::isVisibleForInState( Player const* u, WorldObject const* viewPoint, bool inVisibleList ) const
10349 return isVisibleForOrDetect(u, viewPoint, false, inVisibleList, false);
10352 uint32 Unit::GetCreatureType() const
10354 if(GetTypeId() == TYPEID_PLAYER)
10356 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
10357 if(ssEntry && ssEntry->creatureType > 0)
10358 return ssEntry->creatureType;
10359 else
10360 return CREATURE_TYPE_HUMANOID;
10362 else
10363 return ((Creature*)this)->GetCreatureInfo()->type;
10366 /*#######################################
10367 ######## ########
10368 ######## STAT SYSTEM ########
10369 ######## ########
10370 #######################################*/
10372 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
10374 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
10376 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
10377 return false;
10380 float val = 1.0f;
10382 switch(modifierType)
10384 case BASE_VALUE:
10385 case TOTAL_VALUE:
10386 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
10387 break;
10388 case BASE_PCT:
10389 case TOTAL_PCT:
10390 if(amount <= -100.0f) //small hack-fix for -100% modifiers
10391 amount = -200.0f;
10393 val = (100.0f + amount) / 100.0f;
10394 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
10395 break;
10397 default:
10398 break;
10401 if(!CanModifyStats())
10402 return false;
10404 switch(unitMod)
10406 case UNIT_MOD_STAT_STRENGTH:
10407 case UNIT_MOD_STAT_AGILITY:
10408 case UNIT_MOD_STAT_STAMINA:
10409 case UNIT_MOD_STAT_INTELLECT:
10410 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
10412 case UNIT_MOD_ARMOR: UpdateArmor(); break;
10413 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
10415 case UNIT_MOD_MANA:
10416 case UNIT_MOD_RAGE:
10417 case UNIT_MOD_FOCUS:
10418 case UNIT_MOD_ENERGY:
10419 case UNIT_MOD_HAPPINESS:
10420 case UNIT_MOD_RUNE:
10421 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
10423 case UNIT_MOD_RESISTANCE_HOLY:
10424 case UNIT_MOD_RESISTANCE_FIRE:
10425 case UNIT_MOD_RESISTANCE_NATURE:
10426 case UNIT_MOD_RESISTANCE_FROST:
10427 case UNIT_MOD_RESISTANCE_SHADOW:
10428 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
10430 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
10431 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
10433 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
10434 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
10435 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
10437 default:
10438 break;
10441 return true;
10444 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
10446 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
10448 sLog.outError("trial to access non existed modifier value from UnitMods!");
10449 return 0.0f;
10452 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
10453 return 0.0f;
10455 return m_auraModifiersGroup[unitMod][modifierType];
10458 float Unit::GetTotalStatValue(Stats stat) const
10460 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
10462 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
10463 return 0.0f;
10465 // value = ((base_value * base_pct) + total_value) * total_pct
10466 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
10467 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
10468 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
10469 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
10471 return value;
10474 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
10476 if(unitMod >= UNIT_MOD_END)
10478 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
10479 return 0.0f;
10482 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
10483 return 0.0f;
10485 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
10486 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
10487 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
10488 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
10490 return value;
10493 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
10495 SpellSchools school = SPELL_SCHOOL_NORMAL;
10497 switch(unitMod)
10499 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
10500 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
10501 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
10502 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
10503 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
10504 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
10506 default:
10507 break;
10510 return school;
10513 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
10515 Stats stat = STAT_STRENGTH;
10517 switch(unitMod)
10519 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
10520 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
10521 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
10522 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
10523 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
10525 default:
10526 break;
10529 return stat;
10532 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
10534 switch(unitMod)
10536 case UNIT_MOD_MANA: return POWER_MANA;
10537 case UNIT_MOD_RAGE: return POWER_RAGE;
10538 case UNIT_MOD_FOCUS: return POWER_FOCUS;
10539 case UNIT_MOD_ENERGY: return POWER_ENERGY;
10540 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
10541 case UNIT_MOD_RUNE: return POWER_RUNE;
10542 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
10543 default: return POWER_MANA;
10546 return POWER_MANA;
10549 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
10551 if (attType == RANGED_ATTACK)
10553 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
10554 if (ap < 0)
10555 return 0.0f;
10556 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
10558 else
10560 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
10561 if (ap < 0)
10562 return 0.0f;
10563 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
10567 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
10569 if (attType == OFF_ATTACK && !haveOffhandWeapon())
10570 return 0.0f;
10572 return m_weaponDamage[attType][type];
10575 void Unit::SetLevel(uint32 lvl)
10577 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
10579 // group update
10580 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
10581 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
10584 void Unit::SetHealth(uint32 val)
10586 uint32 maxHealth = GetMaxHealth();
10587 if(maxHealth < val)
10588 val = maxHealth;
10590 SetUInt32Value(UNIT_FIELD_HEALTH, val);
10592 // group update
10593 if(GetTypeId() == TYPEID_PLAYER)
10595 if(((Player*)this)->GetGroup())
10596 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
10598 else if(((Creature*)this)->isPet())
10600 Pet *pet = ((Pet*)this);
10601 if(pet->isControlled())
10603 Unit *owner = GetOwner();
10604 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10605 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
10610 void Unit::SetMaxHealth(uint32 val)
10612 uint32 health = GetHealth();
10613 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
10615 // group update
10616 if(GetTypeId() == TYPEID_PLAYER)
10618 if(((Player*)this)->GetGroup())
10619 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
10621 else if(((Creature*)this)->isPet())
10623 Pet *pet = ((Pet*)this);
10624 if(pet->isControlled())
10626 Unit *owner = GetOwner();
10627 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10628 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
10632 if(val < health)
10633 SetHealth(val);
10636 void Unit::SetPower(Powers power, uint32 val)
10638 if(GetPower(power) == val)
10639 return;
10641 uint32 maxPower = GetMaxPower(power);
10642 if(maxPower < val)
10643 val = maxPower;
10645 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
10647 WorldPacket data(SMSG_POWER_UPDATE);
10648 data.append(GetPackGUID());
10649 data << uint8(power);
10650 data << uint32(val);
10651 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
10653 // group update
10654 if(GetTypeId() == TYPEID_PLAYER)
10656 if(((Player*)this)->GetGroup())
10657 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10659 else if(((Creature*)this)->isPet())
10661 Pet *pet = ((Pet*)this);
10662 if(pet->isControlled())
10664 Unit *owner = GetOwner();
10665 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10666 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10669 // Update the pet's character sheet with happiness damage bonus
10670 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
10672 pet->UpdateDamagePhysical(BASE_ATTACK);
10677 void Unit::SetMaxPower(Powers power, uint32 val)
10679 uint32 cur_power = GetPower(power);
10680 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
10682 // group update
10683 if(GetTypeId() == TYPEID_PLAYER)
10685 if(((Player*)this)->GetGroup())
10686 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10688 else if(((Creature*)this)->isPet())
10690 Pet *pet = ((Pet*)this);
10691 if(pet->isControlled())
10693 Unit *owner = GetOwner();
10694 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10695 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10699 if(val < cur_power)
10700 SetPower(power, val);
10703 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
10705 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
10707 // group update
10708 if(GetTypeId() == TYPEID_PLAYER)
10710 if(((Player*)this)->GetGroup())
10711 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10713 else if(((Creature*)this)->isPet())
10715 Pet *pet = ((Pet*)this);
10716 if(pet->isControlled())
10718 Unit *owner = GetOwner();
10719 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10720 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10725 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
10727 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
10729 // group update
10730 if(GetTypeId() == TYPEID_PLAYER)
10732 if(((Player*)this)->GetGroup())
10733 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10735 else if(((Creature*)this)->isPet())
10737 Pet *pet = ((Pet*)this);
10738 if(pet->isControlled())
10740 Unit *owner = GetOwner();
10741 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10742 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10747 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10749 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10750 if(apply)
10751 tAuraProcTriggerDamage.push_back(aura);
10752 else
10753 tAuraProcTriggerDamage.remove(aura);
10756 uint32 Unit::GetCreatePowers( Powers power ) const
10758 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10759 switch(power)
10761 case POWER_MANA: return GetCreateMana();
10762 case POWER_RAGE: return 1000;
10763 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10764 case POWER_ENERGY: return 100;
10765 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10766 case POWER_RUNIC_POWER: return 1000;
10767 case POWER_RUNE: return 0;
10768 case POWER_HEALTH: return 0;
10771 return 0;
10774 void Unit::AddToWorld()
10776 Object::AddToWorld();
10779 void Unit::RemoveFromWorld()
10781 // cleanup
10782 if(IsInWorld())
10784 RemoveNotOwnSingleTargetAuras();
10785 RemoveGuardians();
10788 Object::RemoveFromWorld();
10791 void Unit::CleanupsBeforeDelete()
10793 if(m_uint32Values) // only for fully created object
10795 InterruptNonMeleeSpells(true);
10796 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10797 CombatStop();
10798 ClearComboPointHolders();
10799 DeleteThreatList();
10800 getHostilRefManager().setOnlineOfflineState(false);
10801 RemoveAllAuras();
10802 RemoveAllGameObjects();
10803 RemoveAllDynObjects();
10804 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10806 RemoveFromWorld();
10809 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10811 if(!m_charmInfo)
10812 m_charmInfo = new CharmInfo(charm);
10813 return m_charmInfo;
10816 CharmInfo::CharmInfo(Unit* unit)
10817 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10819 for(int i = 0; i < CREATURE_MAX_SPELLS; ++i)
10820 m_charmspells[i].SetActionAndType(0,ACT_DISABLED);
10823 void CharmInfo::InitPetActionBar()
10825 // the first 3 SpellOrActions are attack, follow and stay
10826 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_START - ACTION_BAR_INDEX_START; ++i)
10827 SetActionBar(ACTION_BAR_INDEX_START + i,COMMAND_ATTACK - i,ACT_COMMAND);
10829 // middle 4 SpellOrActions are spells/special attacks/abilities
10830 for(uint32 i = 0; i < ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START; ++i)
10831 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_START + i,0,ACT_DISABLED);
10833 // last 3 SpellOrActions are reactions
10834 for(uint32 i = 0; i < ACTION_BAR_INDEX_END - ACTION_BAR_INDEX_PET_SPELL_END; ++i)
10835 SetActionBar(ACTION_BAR_INDEX_PET_SPELL_END + i,COMMAND_ATTACK - i,ACT_REACTION);
10838 void CharmInfo::InitEmptyActionBar()
10840 SetActionBar(ACTION_BAR_INDEX_START,COMMAND_ATTACK,ACT_COMMAND);
10841 for(uint32 x = ACTION_BAR_INDEX_START+1; x < ACTION_BAR_INDEX_END; ++x)
10842 SetActionBar(x,0,ACT_PASSIVE);
10845 void CharmInfo::InitPossessCreateSpells()
10847 InitEmptyActionBar(); //charm action bar
10849 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
10850 return;
10852 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10854 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10855 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10856 else
10857 AddSpellToActionBar(((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10861 void CharmInfo::InitCharmCreateSpells()
10863 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10865 InitEmptyActionBar();
10866 return;
10869 InitPetActionBar();
10871 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10873 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10875 if(!spellId)
10877 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
10878 continue;
10881 if (IsPassiveSpell(spellId))
10883 m_unit->CastSpell(m_unit, spellId, true);
10884 m_charmspells[x].SetActionAndType(spellId,ACT_PASSIVE);
10886 else
10888 m_charmspells[x].SetActionAndType(spellId,ACT_DISABLED);
10890 ActiveStates newstate;
10891 bool onlyselfcast = true;
10892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10894 if(!spellInfo) onlyselfcast = false;
10895 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10897 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10898 onlyselfcast = false;
10901 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10902 newstate = ACT_DISABLED;
10903 else
10904 newstate = ACT_PASSIVE;
10906 AddSpellToActionBar(spellId, newstate);
10911 bool CharmInfo::AddSpellToActionBar(uint32 spell_id, ActiveStates newstate)
10913 uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
10915 // new spell rank can be already listed
10916 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10918 if (uint32 action = PetActionBar[i].GetAction())
10920 if (PetActionBar[i].IsActionBarForSpell() && spellmgr.GetFirstSpellInChain(action) == first_id)
10922 PetActionBar[i].SetAction(spell_id);
10923 return true;
10928 // or use empty slot in other case
10929 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10931 if (!PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
10933 SetActionBar(i,spell_id,newstate == ACT_DECIDE ? ACT_DISABLED : newstate);
10934 return true;
10937 return false;
10940 bool CharmInfo::RemoveSpellFromActionBar(uint32 spell_id)
10942 uint32 first_id = spellmgr.GetFirstSpellInChain(spell_id);
10944 for(uint8 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
10946 if (uint32 action = PetActionBar[i].GetAction())
10948 if (PetActionBar[i].IsActionBarForSpell() && spellmgr.GetFirstSpellInChain(action) == first_id)
10950 SetActionBar(i,0,ACT_DISABLED);
10951 return true;
10956 return false;
10959 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10961 if(IsPassiveSpell(spellid))
10962 return;
10964 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10965 if(spellid == m_charmspells[x].GetAction())
10966 m_charmspells[x].SetType(apply ? ACT_ENABLED : ACT_DISABLED);
10969 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10971 m_petnumber = petnumber;
10972 if(statwindow)
10973 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10974 else
10975 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10978 void CharmInfo::LoadPetActionBar(const std::string& data )
10980 InitPetActionBar();
10982 Tokens tokens = StrSplit(data, " ");
10984 if (tokens.size() != (ACTION_BAR_INDEX_PET_SPELL_END-ACTION_BAR_INDEX_PET_SPELL_START)*2)
10985 return; // non critical, will reset to default
10987 int index;
10988 Tokens::iterator iter;
10989 for(iter = tokens.begin(), index = ACTION_BAR_INDEX_PET_SPELL_START; index < ACTION_BAR_INDEX_PET_SPELL_END; ++iter, ++index )
10991 // use unsigned cast to avoid sign negative format use at long-> ActiveStates (int) conversion
10992 uint8 type = atol((*iter).c_str());
10993 ++iter;
10994 uint32 action = atol((*iter).c_str());
10996 PetActionBar[index].SetActionAndType(action,ActiveStates(type));
10998 // check correctness
10999 if(PetActionBar[index].IsActionBarForSpell() && !sSpellStore.LookupEntry(PetActionBar[index].GetAction()))
11000 SetActionBar(index,0,ACT_DISABLED);
11004 void CharmInfo::BuildActionBar( WorldPacket* data )
11006 for(uint32 i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11007 *data << uint32(PetActionBar[i].packedData);
11010 void CharmInfo::SetSpellAutocast( uint32 spell_id, bool state )
11012 for(int i = 0; i < MAX_UNIT_ACTION_BAR_INDEX; ++i)
11014 if(spell_id == PetActionBar[i].GetAction() && PetActionBar[i].IsActionBarForSpell())
11016 PetActionBar[i].SetType(state ? ACT_ENABLED : ACT_DISABLED);
11017 break;
11022 bool Unit::isFrozen() const
11024 return HasAuraState(AURA_STATE_FROZEN);
11027 struct ProcTriggeredData
11029 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
11030 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
11031 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
11033 SpellProcEventEntry const *spellProcEvent;
11034 Aura* triggeredByAura;
11035 Unit::spellEffectPair triggeredByAura_SpellPair;
11038 typedef std::list< ProcTriggeredData > ProcTriggeredList;
11039 typedef std::list< uint32> RemoveSpellList;
11041 // List of auras that CAN be trigger but may not exist in spell_proc_event
11042 // in most case need for drop charges
11043 // in some types of aura need do additional check
11044 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
11045 bool InitTriggerAuraData()
11047 for (int i=0;i<TOTAL_AURAS;++i)
11049 isTriggerAura[i]=false;
11050 isNonTriggerAura[i] = false;
11052 isTriggerAura[SPELL_AURA_DUMMY] = true;
11053 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
11054 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
11055 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
11056 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
11057 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
11058 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
11059 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
11060 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
11061 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
11062 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
11063 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
11064 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
11065 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
11066 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
11067 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
11068 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
11069 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
11070 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
11071 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
11072 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
11073 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
11074 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
11075 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
11076 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
11077 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
11078 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
11079 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
11080 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
11081 isTriggerAura[SPELL_AURA_MOD_SPELL_CRIT_CHANCE] = true;
11083 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
11084 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
11086 return true;
11089 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
11091 uint32 procEx = PROC_EX_NONE;
11092 // Check victim state
11093 if (missCondition!=SPELL_MISS_NONE)
11094 switch (missCondition)
11096 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
11097 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
11098 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
11099 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
11100 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
11101 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
11102 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
11103 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
11104 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
11105 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
11106 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
11107 default:
11108 break;
11110 else
11112 // On block
11113 if (damageInfo->blocked)
11114 procEx|=PROC_EX_BLOCK;
11115 // On absorb
11116 if (damageInfo->absorb)
11117 procEx|=PROC_EX_ABSORB;
11118 // On crit
11119 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
11120 procEx|=PROC_EX_CRITICAL_HIT;
11121 else
11122 procEx|=PROC_EX_NORMAL_HIT;
11124 return procEx;
11127 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
11129 // For melee/ranged based attack need update skills and set some Aura states
11130 if (procFlag & MELEE_BASED_TRIGGER_MASK)
11132 // Update skills here for players
11133 if (GetTypeId() == TYPEID_PLAYER)
11135 // On melee based hit/miss/resist need update skill (for victim and attacker)
11136 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
11138 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
11139 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
11141 // Update defence if player is victim and parry/dodge/block
11142 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
11143 ((Player*)this)->UpdateDefense();
11145 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
11146 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
11148 // for victim
11149 if (isVictim)
11151 // if victim and dodge attack
11152 if (procExtra&PROC_EX_DODGE)
11154 //Update AURA_STATE on dodge
11155 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
11157 ModifyAuraState(AURA_STATE_DEFENSE, true);
11158 StartReactiveTimer( REACTIVE_DEFENSE );
11161 // if victim and parry attack
11162 if (procExtra & PROC_EX_PARRY)
11164 // For Hunters only Counterattack (skip Mongoose bite)
11165 if (getClass() == CLASS_HUNTER)
11167 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
11168 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
11170 else
11172 ModifyAuraState(AURA_STATE_DEFENSE, true);
11173 StartReactiveTimer( REACTIVE_DEFENSE );
11176 // if and victim block attack
11177 if (procExtra & PROC_EX_BLOCK)
11179 ModifyAuraState(AURA_STATE_DEFENSE,true);
11180 StartReactiveTimer( REACTIVE_DEFENSE );
11183 else //For attacker
11185 // Overpower on victim dodge
11186 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
11188 ((Player*)this)->AddComboPoints(pTarget, 1);
11189 StartReactiveTimer( REACTIVE_OVERPOWER );
11195 RemoveSpellList removedSpells;
11196 ProcTriggeredList procTriggered;
11197 // Fill procTriggered list
11198 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
11200 // skip deleted auras (possible at recursive triggered call
11201 if(itr->second->IsDeleted())
11202 continue;
11204 SpellProcEventEntry const* spellProcEvent = NULL;
11205 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
11206 continue;
11208 itr->second->SetInUse(true); // prevent aura deletion
11209 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
11212 // Nothing found
11213 if (procTriggered.empty())
11214 return;
11216 // Handle effects proceed this time
11217 for(ProcTriggeredList::const_iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
11219 // Some auras can be deleted in function called in this loop (except first, ofc)
11220 Aura *triggeredByAura = i->triggeredByAura;
11221 if(triggeredByAura->IsDeleted())
11222 continue;
11224 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
11225 Modifier *auraModifier = triggeredByAura->GetModifier();
11226 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
11227 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
11228 // For players set spell cooldown if need
11229 uint32 cooldown = 0;
11230 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
11231 cooldown = spellProcEvent->cooldown;
11233 switch(auraModifier->m_auraname)
11235 case SPELL_AURA_PROC_TRIGGER_SPELL:
11237 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11238 // Don`t drop charge or add cooldown for not started trigger
11239 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11241 triggeredByAura->SetInUse(false);
11242 continue;
11244 break;
11246 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
11248 sLog.outDebug("ProcDamageAndSpell: doing %u damage from spell id %u (triggered by %s aura of spell %u)", auraModifier->m_amount, spellInfo->Id, (isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11249 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
11250 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
11251 DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb);
11252 SendSpellNonMeleeDamageLog(&damageInfo);
11253 DealSpellDamage(&damageInfo, true);
11254 break;
11256 case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN:
11257 case SPELL_AURA_MANA_SHIELD:
11258 case SPELL_AURA_OBS_MOD_MANA:
11259 case SPELL_AURA_DUMMY:
11261 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s dummy aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11262 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11264 triggeredByAura->SetInUse(false);
11265 continue;
11267 break;
11269 case SPELL_AURA_MOD_HASTE:
11271 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11272 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11274 triggeredByAura->SetInUse(false);
11275 continue;
11277 break;
11279 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
11281 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11282 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
11284 triggeredByAura->SetInUse(false);
11285 continue;
11287 break;
11289 case SPELL_AURA_PRAYER_OF_MENDING:
11291 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
11292 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
11294 HandleMendingAuraProc(triggeredByAura);
11295 break;
11297 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
11299 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered with value by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11301 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11303 triggeredByAura->SetInUse(false);
11304 continue;
11306 break;
11308 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
11309 // Skip melee hits or instant cast spells
11310 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
11312 triggeredByAura->SetInUse(false);
11313 continue;
11315 break;
11316 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
11317 // Skip Melee hits and spells ws wrong school
11318 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
11320 triggeredByAura->SetInUse(false);
11321 continue;
11323 break;
11324 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
11325 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
11326 // Skip melee hits and spells ws wrong school or zero cost
11327 if (procSpell == NULL ||
11328 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
11329 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
11331 triggeredByAura->SetInUse(false);
11332 continue;
11334 break;
11335 case SPELL_AURA_MECHANIC_IMMUNITY:
11336 // Compare mechanic
11337 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
11339 triggeredByAura->SetInUse(false);
11340 continue;
11342 break;
11343 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
11344 // Compare mechanic
11345 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
11347 triggeredByAura->SetInUse(false);
11348 continue;
11350 break;
11351 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
11352 // Compare casters
11353 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
11355 triggeredByAura->SetInUse(false);
11356 continue;
11358 break;
11359 case SPELL_AURA_MOD_SPELL_CRIT_CHANCE:
11360 if (!procSpell)
11362 triggeredByAura->SetInUse(false);
11363 continue;
11365 sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s spell crit chance aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
11366 if (!HandleSpellCritChanceAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
11368 triggeredByAura->SetInUse(false);
11369 continue;
11371 break;
11372 default:
11373 // nothing do, just charges counter
11374 break;
11377 // Remove charge (aura can be removed by triggers)
11378 if(useCharges && !triggeredByAura->IsDeleted())
11380 // If last charge dropped add spell to remove list
11381 if(triggeredByAura->DropAuraCharge())
11382 removedSpells.push_back(triggeredByAura->GetId());
11385 triggeredByAura->SetInUse(false);
11387 if (!removedSpells.empty())
11389 // Sort spells and remove dublicates
11390 removedSpells.sort();
11391 removedSpells.unique();
11392 // Remove auras from removedAuras
11393 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();++i)
11394 RemoveAurasDueToSpell(*i);
11398 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
11400 return SPELL_SCHOOL_MASK_NORMAL;
11403 Player* Unit::GetSpellModOwner()
11405 if(GetTypeId()==TYPEID_PLAYER)
11406 return (Player*)this;
11407 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
11409 Unit* owner = GetOwner();
11410 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
11411 return (Player*)owner;
11413 return NULL;
11416 ///----------Pet responses methods-----------------
11417 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
11419 if(msg == SPELL_CAST_OK)
11420 return;
11422 Unit *owner = GetCharmerOrOwner();
11423 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11424 return;
11426 WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1);
11427 data << uint8(0); // cast count?
11428 data << uint32(spellid);
11429 data << uint8(msg);
11430 // uint32 for some reason
11431 // uint32 for some reason
11432 ((Player*)owner)->GetSession()->SendPacket(&data);
11435 void Unit::SendPetActionFeedback (uint8 msg)
11437 Unit* owner = GetOwner();
11438 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11439 return;
11441 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
11442 data << uint8(msg);
11443 ((Player*)owner)->GetSession()->SendPacket(&data);
11446 void Unit::SendPetTalk (uint32 pettalk)
11448 Unit* owner = GetOwner();
11449 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11450 return;
11452 WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4);
11453 data << uint64(GetGUID());
11454 data << uint32(pettalk);
11455 ((Player*)owner)->GetSession()->SendPacket(&data);
11458 void Unit::SendPetAIReaction(uint64 guid)
11460 Unit* owner = GetOwner();
11461 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
11462 return;
11464 WorldPacket data(SMSG_AI_REACTION, 8 + 4);
11465 data << uint64(guid);
11466 data << uint32(AI_REACTION_AGGRO);
11467 ((Player*)owner)->GetSession()->SendPacket(&data);
11470 ///----------End of Pet responses methods----------
11472 void Unit::StopMoving()
11474 clearUnitState(UNIT_STAT_MOVING);
11476 // send explicit stop packet
11477 // player expected for correct work MONSTER_MOVE_WALK
11478 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, GetTypeId()==TYPEID_PLAYER ? MONSTER_MOVE_WALK : MONSTER_MOVE_NONE, 0);
11480 // update position and orientation for near players
11481 WorldPacket data;
11482 BuildHeartBeatMsg(&data);
11483 SendMessageToSet(&data,false);
11486 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID, uint32 time)
11488 if( apply )
11490 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
11491 return;
11493 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
11495 GetMotionMaster()->MovementExpired(false);
11496 CastStop(GetGUID()==casterGUID ? spellID : 0);
11498 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
11500 GetMotionMaster()->MoveFleeing(caster, time); // caster==NULL processed in MoveFleeing
11502 else
11504 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
11506 GetMotionMaster()->MovementExpired(false);
11508 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
11510 // restore appropriate movement generator
11511 if(getVictim())
11512 GetMotionMaster()->MoveChase(getVictim());
11513 else
11514 GetMotionMaster()->Initialize();
11516 // attack caster if can
11517 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
11518 if(caster && ((Creature*)this)->AI())
11519 ((Creature*)this)->AI()->AttackedBy(caster);
11523 if (GetTypeId() == TYPEID_PLAYER)
11524 ((Player*)this)->SetClientControl(this, !apply);
11527 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
11529 if( apply )
11531 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
11533 CastStop(GetGUID()==casterGUID ? spellID : 0);
11535 GetMotionMaster()->MoveConfused();
11537 else
11539 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
11541 GetMotionMaster()->MovementExpired(false);
11543 if (GetTypeId() == TYPEID_UNIT)
11545 // if in combat restore movement generator
11546 if(getVictim())
11547 GetMotionMaster()->MoveChase(getVictim());
11551 if(GetTypeId() == TYPEID_PLAYER)
11552 ((Player*)this)->SetClientControl(this, !apply);
11555 bool Unit::IsSitState() const
11557 uint8 s = getStandState();
11558 return
11559 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
11560 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
11561 s == UNIT_STAND_STATE_SIT;
11564 bool Unit::IsStandState() const
11566 uint8 s = getStandState();
11567 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
11570 void Unit::SetStandState(uint8 state)
11572 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
11574 if (IsStandState())
11575 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
11577 if(GetTypeId()==TYPEID_PLAYER)
11579 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
11580 data << (uint8)state;
11581 ((Player*)this)->GetSession()->SendPacket(&data);
11585 bool Unit::IsPolymorphed() const
11587 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
11590 void Unit::SetDisplayId(uint32 modelId)
11592 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
11594 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11596 Pet *pet = ((Pet*)this);
11597 if(!pet->isControlled())
11598 return;
11599 Unit *owner = GetOwner();
11600 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11601 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
11605 void Unit::ClearComboPointHolders()
11607 while(!m_ComboPointHolders.empty())
11609 uint32 lowguid = *m_ComboPointHolders.begin();
11611 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
11612 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
11613 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
11614 else
11615 m_ComboPointHolders.erase(lowguid); // or remove manually
11619 void Unit::ClearAllReactives()
11621 for(int i=0; i < MAX_REACTIVE; ++i)
11622 m_reactiveTimer[i] = 0;
11624 if (HasAuraState( AURA_STATE_DEFENSE))
11625 ModifyAuraState(AURA_STATE_DEFENSE, false);
11626 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
11627 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
11628 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
11629 ((Player*)this)->ClearComboPoints();
11632 void Unit::UpdateReactives( uint32 p_time )
11634 for(int i = 0; i < MAX_REACTIVE; ++i)
11636 ReactiveType reactive = ReactiveType(i);
11638 if(!m_reactiveTimer[reactive])
11639 continue;
11641 if ( m_reactiveTimer[reactive] <= p_time)
11643 m_reactiveTimer[reactive] = 0;
11645 switch ( reactive )
11647 case REACTIVE_DEFENSE:
11648 if (HasAuraState(AURA_STATE_DEFENSE))
11649 ModifyAuraState(AURA_STATE_DEFENSE, false);
11650 break;
11651 case REACTIVE_HUNTER_PARRY:
11652 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
11653 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
11654 break;
11655 case REACTIVE_OVERPOWER:
11656 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
11657 ((Player*)this)->ClearComboPoints();
11658 break;
11659 default:
11660 break;
11663 else
11665 m_reactiveTimer[reactive] -= p_time;
11670 Unit* Unit::SelectNearbyTarget(Unit* except /*= NULL*/) const
11672 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
11673 Cell cell(p);
11674 cell.data.Part.reserved = ALL_DISTRICT;
11675 cell.SetNoCreate();
11677 std::list<Unit *> targets;
11680 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
11681 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
11683 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
11684 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
11686 CellLock<GridReadGuard> cell_lock(cell, p);
11687 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
11688 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
11691 // remove current target
11692 if(except)
11693 targets.remove(except);
11695 // remove not LoS targets
11696 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
11698 if(!IsWithinLOSInMap(*tIter))
11700 std::list<Unit *>::iterator tIter2 = tIter;
11701 ++tIter;
11702 targets.erase(tIter2);
11704 else
11705 ++tIter;
11708 // no appropriate targets
11709 if(targets.empty())
11710 return NULL;
11712 // select random
11713 uint32 rIdx = urand(0,targets.size()-1);
11714 std::list<Unit *>::const_iterator tcIter = targets.begin();
11715 for(uint32 i = 0; i < rIdx; ++i)
11716 ++tcIter;
11718 return *tcIter;
11721 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
11723 for (AuraMap::const_iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
11725 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
11726 return true;
11728 return false;
11731 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
11733 if(val > 0)
11735 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
11736 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
11738 else
11740 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
11741 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
11745 void Unit::ApplyCastTimePercentMod(float val, bool apply )
11747 if(val > 0)
11748 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
11749 else
11750 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
11753 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
11755 // Not apply this to creature casted spells with casttime==0
11756 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
11757 return 3500;
11759 if (CastingTime > 7000) CastingTime = 7000;
11760 if (CastingTime < 1500) CastingTime = 1500;
11762 if(damagetype == DOT && !IsChanneledSpell(spellProto))
11763 CastingTime = 3500;
11765 int32 overTime = 0;
11766 uint8 effects = 0;
11767 bool DirectDamage = false;
11768 bool AreaEffect = false;
11770 for ( uint32 i=0; i<3;++i)
11772 switch ( spellProto->Effect[i] )
11774 case SPELL_EFFECT_SCHOOL_DAMAGE:
11775 case SPELL_EFFECT_POWER_DRAIN:
11776 case SPELL_EFFECT_HEALTH_LEECH:
11777 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
11778 case SPELL_EFFECT_POWER_BURN:
11779 case SPELL_EFFECT_HEAL:
11780 DirectDamage = true;
11781 break;
11782 case SPELL_EFFECT_APPLY_AURA:
11783 switch ( spellProto->EffectApplyAuraName[i] )
11785 case SPELL_AURA_PERIODIC_DAMAGE:
11786 case SPELL_AURA_PERIODIC_HEAL:
11787 case SPELL_AURA_PERIODIC_LEECH:
11788 if ( GetSpellDuration(spellProto) )
11789 overTime = GetSpellDuration(spellProto);
11790 break;
11791 default:
11792 // -5% per additional effect
11793 ++effects;
11794 break;
11796 default:
11797 break;
11800 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11801 AreaEffect = true;
11804 // Combined Spells with Both Over Time and Direct Damage
11805 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11807 // mainly for DoTs which are 3500 here otherwise
11808 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11809 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11810 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11811 // Portion to Over Time
11812 float PtOT = (overTime / 15000.0f) / ((overTime / 15000.0f) + (OriginalCastTime / 3500.0f));
11814 if ( damagetype == DOT )
11815 CastingTime = uint32(CastingTime * PtOT);
11816 else if ( PtOT < 1.0f )
11817 CastingTime = uint32(CastingTime * (1 - PtOT));
11818 else
11819 CastingTime = 0;
11822 // Area Effect Spells receive only half of bonus
11823 if ( AreaEffect )
11824 CastingTime /= 2;
11826 // -5% of total per any additional effect
11827 for ( uint8 i=0; i<effects; ++i)
11829 if ( CastingTime > 175 )
11831 CastingTime -= 175;
11833 else
11835 CastingTime = 0;
11836 break;
11840 return CastingTime;
11843 void Unit::UpdateAuraForGroup(uint8 slot)
11845 if(GetTypeId() == TYPEID_PLAYER)
11847 Player* player = (Player*)this;
11848 if(player->GetGroup())
11850 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11851 player->SetAuraUpdateMask(slot);
11854 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11856 Pet *pet = ((Pet*)this);
11857 if(pet->isControlled())
11859 Unit *owner = GetOwner();
11860 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11862 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11863 pet->SetAuraUpdateMask(slot);
11869 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11871 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11872 return float(GetAttackTime(attType))/1000.0f;
11874 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11875 if (!Weapon)
11876 return 2.4; // fist attack
11878 switch (Weapon->GetProto()->InventoryType)
11880 case INVTYPE_2HWEAPON:
11881 return 3.3;
11882 case INVTYPE_RANGED:
11883 case INVTYPE_RANGEDRIGHT:
11884 case INVTYPE_THROWN:
11885 return 2.8;
11886 case INVTYPE_WEAPON:
11887 case INVTYPE_WEAPONMAINHAND:
11888 case INVTYPE_WEAPONOFFHAND:
11889 default:
11890 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11894 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11896 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11897 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11898 if ((*itr)->GetId() == spell_id)
11899 return *itr;
11901 return NULL;
11904 void Unit::SetContestedPvP(Player *attackedPlayer)
11906 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11908 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11909 return;
11911 player->SetContestedPvPTimer(30000);
11912 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11914 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11915 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11916 // call MoveInLineOfSight for nearby contested guards
11917 SetVisibility(GetVisibility());
11919 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11921 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11922 // call MoveInLineOfSight for nearby contested guards
11923 SetVisibility(GetVisibility());
11927 void Unit::AddPetAura(PetAura const* petSpell)
11929 m_petAuras.insert(petSpell);
11930 if(Pet* pet = GetPet())
11931 pet->CastPetAura(petSpell);
11934 void Unit::RemovePetAura(PetAura const* petSpell)
11936 m_petAuras.erase(petSpell);
11937 if(Pet* pet = GetPet())
11938 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11941 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11943 Pet* pet = new Pet(HUNTER_PET);
11945 if(!pet->CreateBaseAtCreature(creatureTarget))
11947 delete pet;
11948 return NULL;
11951 pet->SetOwnerGUID(GetGUID());
11952 pet->SetCreatorGUID(GetGUID());
11953 pet->setFaction(getFaction());
11954 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11956 if(GetTypeId()==TYPEID_PLAYER)
11957 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11959 if(IsPvP())
11960 pet->SetPvP(true);
11962 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11964 if(!pet->InitStatsForLevel(level))
11966 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11967 delete pet;
11968 return NULL;
11971 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11972 // this enables pet details window (Shift+P)
11973 pet->AIM_Initialize();
11974 pet->InitPetCreateSpells();
11975 pet->InitLevelupSpellsForLevel();
11976 pet->InitTalentForLevel();
11977 pet->SetHealth(pet->GetMaxHealth());
11979 return pet;
11982 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11984 SpellEntry const* spellProto = aura->GetSpellProto ();
11986 // Get proc Event Entry
11987 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11989 // Aura info stored here
11990 Modifier *mod = aura->GetModifier();
11991 // Skip this auras
11992 if (isNonTriggerAura[mod->m_auraname])
11993 return false;
11994 // If not trigger by default and spellProcEvent==NULL - skip
11995 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11996 return false;
11998 // Get EventProcFlag
11999 uint32 EventProcFlag;
12000 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
12001 EventProcFlag = spellProcEvent->procFlags;
12002 else
12003 EventProcFlag = spellProto->procFlags; // else get from spell proto
12004 // Continue if no trigger exist
12005 if (!EventProcFlag)
12006 return false;
12008 // Check spellProcEvent data requirements
12009 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
12010 return false;
12012 // In most cases req get honor or XP from kill
12013 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
12015 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
12016 // Shadow Word: Death - can trigger from every kill
12017 if (aura->GetId() == 32409)
12018 allow = true;
12019 if (!allow)
12020 return false;
12022 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
12023 // But except periodic triggers (can triggered from self)
12024 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
12025 return false;
12027 // Check if current equipment allows aura to proc
12028 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
12030 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
12032 Item *item = NULL;
12033 if(attType == BASE_ATTACK)
12034 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
12035 else if (attType == OFF_ATTACK)
12036 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
12037 else
12038 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
12040 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
12041 return false;
12043 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
12044 return false;
12046 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
12048 // Check if player is wearing shield
12049 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
12050 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
12051 return false;
12054 // Get chance from spell
12055 float chance = (float)spellProto->procChance;
12056 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
12057 if(spellProcEvent && spellProcEvent->customChance)
12058 chance = spellProcEvent->customChance;
12059 // If PPM exist calculate chance from PPM
12060 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
12062 uint32 WeaponSpeed = GetAttackTime(attType);
12063 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
12065 // Apply chance modifer aura
12066 if(Player* modOwner = GetSpellModOwner())
12068 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
12069 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
12072 return roll_chance_f(chance);
12075 bool Unit::HandleMendingAuraProc( Aura* triggeredByAura )
12077 // aura can be deleted at casts
12078 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
12079 uint32 effIdx = triggeredByAura->GetEffIndex();
12080 int32 heal = triggeredByAura->GetModifier()->m_amount;
12081 uint64 caster_guid = triggeredByAura->GetCasterGUID();
12083 // jumps
12084 int32 jumps = triggeredByAura->GetAuraCharges()-1;
12086 // current aura expire
12087 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
12089 // next target selection
12090 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
12092 float radius;
12093 if (spellProto->EffectRadiusIndex[effIdx])
12094 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
12095 else
12096 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
12098 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
12100 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
12102 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
12104 // aura will applied from caster, but spell casted from current aura holder
12105 SpellModifier *mod = new SpellModifier;
12106 mod->op = SPELLMOD_CHARGES;
12107 mod->value = jumps-5; // negative
12108 mod->type = SPELLMOD_FLAT;
12109 mod->spellId = spellProto->Id;
12110 mod->mask = spellProto->SpellFamilyFlags;
12111 mod->mask2 = spellProto->SpellFamilyFlags2;
12113 // remove before apply next (locked against deleted)
12114 triggeredByAura->SetInUse(true);
12115 RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID());
12117 caster->AddSpellMod(mod, true);
12118 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
12119 caster->AddSpellMod(mod, false);
12120 triggeredByAura->SetInUse(false);
12125 // heal
12126 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
12127 return true;
12130 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
12132 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
12134 if(!IS_UNIT_GUID(target_guid))
12135 return;
12137 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
12138 if(!target)
12139 return;
12141 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
12143 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
12144 target->RemoveAura(iter);
12145 else
12146 ++iter;
12150 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
12152 if(newPhaseMask==GetPhaseMask())
12153 return;
12155 if(IsInWorld())
12156 RemoveNotOwnSingleTargetAuras(newPhaseMask); // we can lost access to caster or target
12158 WorldObject::SetPhaseMask(newPhaseMask,update);
12160 if(IsInWorld())
12161 if(Pet* pet = GetPet())
12162 pet->SetPhaseMask(newPhaseMask,true);
12165 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
12167 if(GetTypeId() == TYPEID_PLAYER)
12168 ((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));
12169 else
12171 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
12173 WorldPacket data;
12174 BuildHeartBeatMsg(&data);
12175 SendMessageToSet(&data, false);
12179 void Unit::SetPvP( bool state )
12181 if(state)
12182 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
12183 else
12184 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP);
12186 if(Pet* pet = GetPet())
12187 pet->SetPvP(state);
12188 if(Unit* charmed = GetCharm())
12189 charmed->SetPvP(state);
12191 for (int8 i = 0; i < MAX_TOTEM; ++i)
12192 if(m_TotemSlot[i])
12193 if(Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]))
12194 totem->SetPvP(state);
12197 void Unit::KnockBackFrom(Unit* target, float horizintalSpeed, float verticalSpeed)
12199 float angle = this == target ? GetOrientation() + M_PI : target->GetAngle(this);
12200 float vsin = sin(angle);
12201 float vcos = cos(angle);
12203 // Effect propertly implemented only for players
12204 if(GetTypeId()==TYPEID_PLAYER)
12206 WorldPacket data(SMSG_MOVE_KNOCK_BACK, 8+4+4+4+4+4);
12207 data.append(GetPackGUID());
12208 data << uint32(0); // Sequence
12209 data << float(vcos); // x direction
12210 data << float(vsin); // y direction
12211 data << float(horizintalSpeed); // Horizontal speed
12212 data << float(-verticalSpeed); // Z Movement speed (vertical)
12213 ((Player*)this)->GetSession()->SendPacket(&data);
12215 else
12217 float dis = horizintalSpeed;
12219 float ox, oy, oz;
12220 GetPosition(ox, oy, oz);
12222 float fx = ox + dis * vcos;
12223 float fy = oy + dis * vsin;
12224 float fz = oz;
12226 float fx2, fy2, fz2; // getObjectHitPos overwrite last args in any result case
12227 if(VMAP::VMapFactory::createOrGetVMapManager()->getObjectHitPos(GetMapId(), ox,oy,oz+0.5, fx,fy,oz+0.5,fx2,fy2,fz2, -0.5))
12229 fx = fx2;
12230 fy = fy2;
12231 fz = fz2;
12232 UpdateGroundPositionZ(fx, fy, fz);
12235 //FIXME: this mostly hack, must exist some packet for proper creature move at client side
12236 // with CreatureRelocation at server side
12237 NearTeleportTo(fx, fy, fz, GetOrientation(), this == target);