[7702] Implement some damage/healing achievement statistics.
[AHbot.git] / src / game / Unit.cpp
blob11362fed0c7728451d2f8e3385e430aef73d6c17
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"
48 #include <math.h>
50 float baseMoveSpeed[MAX_MOVE_TYPE] =
52 2.5f, // MOVE_WALK
53 7.0f, // MOVE_RUN
54 1.25f, // MOVE_RUN_BACK
55 4.722222f, // MOVE_SWIM
56 4.5f, // MOVE_SWIM_BACK
57 3.141594f, // MOVE_TURN_RATE
58 7.0f, // MOVE_FLIGHT
59 4.5f, // MOVE_FLIGHT_BACK
60 3.14f // MOVE_PITCH_RATE
63 // Used for prepare can/can`t triggr aura
64 static bool InitTriggerAuraData();
65 // Define can trigger auras
66 static bool isTriggerAura[TOTAL_AURAS];
67 // Define can`t trigger auras (need for disable second trigger)
68 static bool isNonTriggerAura[TOTAL_AURAS];
69 // Prepare lists
70 static bool procPrepared = InitTriggerAuraData();
72 Unit::Unit()
73 : WorldObject(), i_motionMaster(this), m_ThreatManager(this), m_HostilRefManager(this)
75 m_objectType |= TYPEMASK_UNIT;
76 m_objectTypeId = TYPEID_UNIT;
77 // 2.3.2 - 0x70
78 m_updateFlag = (UPDATEFLAG_LOWGUID | UPDATEFLAG_HIGHGUID | UPDATEFLAG_LIVING | UPDATEFLAG_HAS_POSITION);
80 m_attackTimer[BASE_ATTACK] = 0;
81 m_attackTimer[OFF_ATTACK] = 0;
82 m_attackTimer[RANGED_ATTACK] = 0;
83 m_modAttackSpeedPct[BASE_ATTACK] = 1.0f;
84 m_modAttackSpeedPct[OFF_ATTACK] = 1.0f;
85 m_modAttackSpeedPct[RANGED_ATTACK] = 1.0f;
87 m_extraAttacks = 0;
89 m_state = 0;
90 m_form = FORM_NONE;
91 m_deathState = ALIVE;
93 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
94 m_currentSpells[i] = NULL;
96 m_addDmgOnce = 0;
98 for(int i = 0; i < MAX_TOTEM; ++i)
99 m_TotemSlot[i] = 0;
101 m_ObjectSlot[0] = m_ObjectSlot[1] = m_ObjectSlot[2] = m_ObjectSlot[3] = 0;
102 //m_Aura = NULL;
103 //m_AurasCheck = 2000;
104 //m_removeAuraTimer = 4;
105 //tmpAura = NULL;
107 m_Visibility = VISIBILITY_ON;
109 m_detectInvisibilityMask = 0;
110 m_invisibilityMask = 0;
111 m_transform = 0;
112 m_ShapeShiftFormSpellId = 0;
113 m_canModifyStats = false;
115 for (int i = 0; i < MAX_SPELL_IMMUNITY; ++i)
116 m_spellImmune[i].clear();
117 for (int i = 0; i < UNIT_MOD_END; ++i)
119 m_auraModifiersGroup[i][BASE_VALUE] = 0.0f;
120 m_auraModifiersGroup[i][BASE_PCT] = 1.0f;
121 m_auraModifiersGroup[i][TOTAL_VALUE] = 0.0f;
122 m_auraModifiersGroup[i][TOTAL_PCT] = 1.0f;
124 // implement 50% base damage from offhand
125 m_auraModifiersGroup[UNIT_MOD_DAMAGE_OFFHAND][TOTAL_PCT] = 0.5f;
127 for (int i = 0; i < MAX_ATTACK; ++i)
129 m_weaponDamage[i][MINDAMAGE] = BASE_MINDAMAGE;
130 m_weaponDamage[i][MAXDAMAGE] = BASE_MAXDAMAGE;
132 for (int i = 0; i < MAX_STATS; ++i)
133 m_createStats[i] = 0.0f;
135 m_attacking = NULL;
136 m_modMeleeHitChance = 0.0f;
137 m_modRangedHitChance = 0.0f;
138 m_modSpellHitChance = 0.0f;
139 m_baseSpellCritChance = 5;
141 m_CombatTimer = 0;
142 m_lastManaUse = 0;
144 //m_victimThreat = 0.0f;
145 for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
146 m_threatModifier[i] = 1.0f;
147 m_isSorted = true;
148 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
149 m_speed_rate[i] = 1.0f;
151 m_removedAuras = 0;
152 m_charmInfo = NULL;
153 m_unit_movement_flags = 0;
155 // remove aurastates allowing special moves
156 for(int i=0; i < MAX_REACTIVE; ++i)
157 m_reactiveTimer[i] = 0;
160 Unit::~Unit()
162 // set current spells as deletable
163 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
165 if (m_currentSpells[i])
167 m_currentSpells[i]->SetReferencedFromCurrent(false);
168 m_currentSpells[i] = NULL;
172 RemoveAllGameObjects();
173 RemoveAllDynObjects();
175 if(m_charmInfo) delete m_charmInfo;
178 void Unit::Update( uint32 p_time )
180 /*if(p_time > m_AurasCheck)
182 m_AurasCheck = 2000;
183 _UpdateAura();
184 }else
185 m_AurasCheck -= p_time;*/
187 // WARNING! Order of execution here is important, do not change.
188 // Spells must be processed with event system BEFORE they go to _UpdateSpells.
189 // Or else we may have some SPELL_STATE_FINISHED spells stalled in pointers, that is bad.
190 m_Events.Update( p_time );
191 _UpdateSpells( p_time );
193 // update combat timer only for players and pets
194 if (isInCombat() && (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet() || ((Creature*)this)->isCharmed()))
196 // Check UNIT_STAT_MELEE_ATTACKING or UNIT_STAT_CHASE (without UNIT_STAT_FOLLOW in this case) so pets can reach far away
197 // targets without stopping half way there and running off.
198 // These flags are reset after target dies or another command is given.
199 if( m_HostilRefManager.isEmpty() )
201 // m_CombatTimer set at aura start and it will be freeze until aura removing
202 if ( m_CombatTimer <= p_time )
203 ClearInCombat();
204 else
205 m_CombatTimer -= p_time;
209 if(uint32 base_att = getAttackTimer(BASE_ATTACK))
211 setAttackTimer(BASE_ATTACK, (p_time >= base_att ? 0 : base_att - p_time) );
214 // update abilities available only for fraction of time
215 UpdateReactives( p_time );
217 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, GetHealth() < GetMaxHealth()*0.20f);
218 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, GetHealth() < GetMaxHealth()*0.35f);
219 ModifyAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, GetHealth() > GetMaxHealth()*0.75f);
221 i_motionMaster.UpdateMotion(p_time);
224 bool Unit::haveOffhandWeapon() const
226 if(GetTypeId() == TYPEID_PLAYER)
227 return ((Player*)this)->GetWeaponForAttack(OFF_ATTACK,true);
228 else
229 return false;
232 void Unit::SendMonsterMoveWithSpeedToCurrentDestination(Player* player)
234 float x, y, z;
235 if(GetMotionMaster()->GetDestination(x, y, z))
236 SendMonsterMoveWithSpeed(x, y, z, 0, player);
239 void Unit::SendMonsterMoveWithSpeed(float x, float y, float z, uint32 transitTime, Player* player)
241 if (!transitTime)
243 if(GetTypeId()==TYPEID_PLAYER)
245 Traveller<Player> traveller(*(Player*)this);
246 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
248 else
250 Traveller<Creature> traveller(*(Creature*)this);
251 transitTime = traveller.GetTotalTrevelTimeTo(x,y,z);
254 //float orientation = (float)atan2((double)dy, (double)dx);
255 SendMonsterMove(x, y, z, 0, GetUnitMovementFlags(), transitTime, player);
258 void Unit::SendMonsterMove(float NewPosX, float NewPosY, float NewPosZ, uint8 type, uint32 MovementFlags, uint32 Time, Player* player)
260 WorldPacket data( SMSG_MONSTER_MOVE, (41 + GetPackGUID().size()) );
261 data.append(GetPackGUID());
263 data << GetPositionX() << GetPositionY() << GetPositionZ();
264 data << uint32(getMSTime());
266 data << uint8(type); // unknown
267 switch(type)
269 case 0: // normal packet
270 break;
271 case 1: // stop packet (raw pos?)
272 SendMessageToSet( &data, true );
273 return;
274 case 2: // facing spot, not used currently
275 data << float(0);
276 data << float(0);
277 data << float(0);
278 break;
279 case 3: // not used currently
280 data << uint64(0); // probably target guid (facing target?)
281 break;
282 case 4: // not used currently
283 data << float(0); // facing angle
284 break;
287 data << uint32(MovementFlags);
288 data << uint32(Time); // Time in between points
289 data << uint32(1); // 1 single waypoint
290 data << NewPosX << NewPosY << NewPosZ; // the single waypoint Point B
292 if(player)
293 player->GetSession()->SendPacket(&data);
294 else
295 SendMessageToSet( &data, true );
298 void Unit::SendMonsterMoveByPath(Path const& path, uint32 start, uint32 end, uint32 MovementFlags)
300 uint32 traveltime = uint32(path.GetTotalLength(start, end) * 32);
302 uint32 pathSize = end-start;
304 WorldPacket data( SMSG_MONSTER_MOVE, (GetPackGUID().size()+4+4+4+4+1+4+4+4+pathSize*4*3) );
305 data.append(GetPackGUID());
306 data << GetPositionX();
307 data << GetPositionY();
308 data << GetPositionZ();
309 data << getMSTime();
310 data << uint8( 0 );
311 data << uint32( MovementFlags );
312 data << uint32( traveltime );
313 data << uint32( pathSize );
314 data.append( (char*)path.GetNodes(start), pathSize * 4 * 3 );
315 SendMessageToSet(&data, true);
318 void Unit::resetAttackTimer(WeaponAttackType type)
320 m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]);
323 bool Unit::canReachWithAttack(Unit *pVictim) const
325 assert(pVictim);
326 float reach = GetFloatValue(UNIT_FIELD_COMBATREACH);
327 if( reach <= 0.0f )
328 reach = 1.0f;
329 return IsWithinDistInMap(pVictim, reach);
332 void Unit::RemoveSpellsCausingAura(AuraType auraType)
334 if (auraType >= TOTAL_AURAS) return;
335 AuraList::iterator iter, next;
336 for (iter = m_modAuras[auraType].begin(); iter != m_modAuras[auraType].end(); iter = next)
338 next = iter;
339 ++next;
341 if (*iter)
343 RemoveAurasDueToSpell((*iter)->GetId());
344 if (!m_modAuras[auraType].empty())
345 next = m_modAuras[auraType].begin();
346 else
347 return;
352 bool Unit::HasAuraType(AuraType auraType) const
354 return (!m_modAuras[auraType].empty());
357 /* Called by DealDamage for auras that have a chance to be dispelled on damage taken. */
358 void Unit::RemoveSpellbyDamageTaken(AuraType auraType, uint32 damage)
360 if(!HasAuraType(auraType))
361 return;
363 // The chance to dispel an aura depends on the damage taken with respect to the casters level.
364 uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50;
365 float chance = float(damage) / max_dmg * 100.0f;
366 if (roll_chance_f(chance))
367 RemoveSpellsCausingAura(auraType);
370 uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDamage, DamageEffectType damagetype, SpellSchoolMask damageSchoolMask, SpellEntry const *spellProto, bool durabilityLoss)
372 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
373 return 0;
375 //You don't lose health from damage taken from another player while in a sanctuary
376 //You still see it in the combat log though
377 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
379 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
380 if(area && area->flags & AREA_FLAG_SANCTUARY) //sanctuary
381 return 0;
384 // remove affects from victim (including from 0 damage and DoTs)
385 if(pVictim != this)
386 pVictim->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
388 // remove affects from attacker at any non-DoT damage (including 0 damage)
389 if( damagetype != DOT)
391 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
392 RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH);
394 if(pVictim != this)
395 RemoveSpellsCausingAura(SPELL_AURA_MOD_INVISIBILITY);
397 if(pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->IsStandState() && !pVictim->hasUnitState(UNIT_STAT_STUNNED))
398 pVictim->SetStandState(UNIT_STAND_STATE_STAND);
401 //Script Event damage Deal
402 if( GetTypeId()== TYPEID_UNIT && ((Creature *)this)->AI())
403 ((Creature *)this)->AI()->DamageDeal(pVictim, damage);
404 //Script Event damage taken
405 if( pVictim->GetTypeId()== TYPEID_UNIT && ((Creature *)pVictim)->AI() )
406 ((Creature *)pVictim)->AI()->DamageTaken(this, damage);
408 if(!damage)
410 // Rage from physical damage received .
411 if(cleanDamage && cleanDamage->damage && (damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL) && pVictim->GetTypeId() == TYPEID_PLAYER && (pVictim->getPowerType() == POWER_RAGE))
412 ((Player*)pVictim)->RewardRage(cleanDamage->damage, 0, false);
414 return 0;
416 if (!spellProto || !IsAuraAddedBySpell(SPELL_AURA_MOD_FEAR, spellProto->Id))
417 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_FEAR, damage);
418 // root type spells do not dispel the root effect
419 if (!spellProto || !(spellProto->Mechanic == MECHANIC_ROOT || IsAuraAddedBySpell(SPELL_AURA_MOD_ROOT, spellProto->Id)))
420 pVictim->RemoveSpellbyDamageTaken(SPELL_AURA_MOD_ROOT, damage);
422 // no xp,health if type 8 /critters/
423 if(pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER)
425 pVictim->setDeathState(JUST_DIED);
426 pVictim->SetHealth(0);
428 // allow loot only if has loot_id in creature_template
429 CreatureInfo const* cInfo = ((Creature*)pVictim)->GetCreatureInfo();
430 if(cInfo && cInfo->lootid)
431 pVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
433 // some critters required for quests
434 if(GetTypeId() == TYPEID_PLAYER)
435 ((Player*)this)->KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
437 return damage;
440 DEBUG_LOG("DealDamageStart");
442 uint32 health = pVictim->GetHealth();
443 sLog.outDetail("deal dmg:%d to health:%d ",damage,health);
445 // duel ends when player has 1 or less hp
446 bool duel_hasEnded = false;
447 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->duel && damage >= (health-1))
449 // prevent kill only if killed in duel and killed by opponent or opponent controlled creature
450 if(((Player*)pVictim)->duel->opponent==this || ((Player*)pVictim)->duel->opponent->GetGUID() == GetOwnerGUID())
451 damage = health-1;
453 duel_hasEnded = true;
455 //Get in CombatState
456 if(pVictim != this && damagetype != DOT)
458 SetInCombatWith(pVictim);
459 pVictim->SetInCombatWith(this);
461 if(Player* attackedPlayer = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself())
462 SetContestedPvP(attackedPlayer);
465 // Rage from Damage made (only from direct weapon damage)
466 if( cleanDamage && damagetype==DIRECT_DAMAGE && this != pVictim && GetTypeId() == TYPEID_PLAYER && (getPowerType() == POWER_RAGE))
468 uint32 weaponSpeedHitFactor;
470 switch(cleanDamage->attackType)
472 case BASE_ATTACK:
474 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
475 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 7);
476 else
477 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
479 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
481 break;
483 case OFF_ATTACK:
485 if(cleanDamage->hitOutCome == MELEE_HIT_CRIT)
486 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 3.5f);
487 else
488 weaponSpeedHitFactor = uint32(GetAttackTime(cleanDamage->attackType)/1000.0f * 1.75f);
490 ((Player*)this)->RewardRage(damage, weaponSpeedHitFactor, true);
492 break;
494 case RANGED_ATTACK:
495 break;
499 if (GetTypeId() == TYPEID_PLAYER && this != pVictim)
501 Player *killer = ((Player*)this);
503 // in bg, count dmg if victim is also a player
504 if (pVictim->GetTypeId()==TYPEID_PLAYER)
506 if (BattleGround *bg = killer->GetBattleGround())
508 // FIXME: kept by compatibility. don't know in BG if the restriction apply.
509 bg->UpdatePlayerScore(killer, SCORE_DAMAGE_DONE, damage);
513 killer->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT, damage);
516 if (pVictim->GetTypeId() == TYPEID_PLAYER)
517 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED, damage);
519 if (pVictim->GetTypeId() == TYPEID_UNIT && !((Creature*)pVictim)->isPet() && !((Creature*)pVictim)->hasLootRecipient())
520 ((Creature*)pVictim)->SetLootRecipient(this);
522 if (health <= damage)
524 DEBUG_LOG("DealDamage: victim just died");
526 if (pVictim->GetTypeId() == TYPEID_PLAYER)
527 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, health);
530 // find player: owner of controlled `this` or `this` itself maybe
531 Player *player = GetCharmerOrOwnerPlayerOrPlayerItself();
533 if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetLootRecipient())
534 player = ((Creature*)pVictim)->GetLootRecipient();
535 // Reward player, his pets, and group/raid members
536 // call kill spell proc event (before real die and combat stop to triggering auras removed at death/combat stop)
537 if(player && player!=pVictim)
539 player->RewardPlayerAndGroupAtKill(pVictim);
540 player->ProcDamageAndSpell(pVictim, PROC_FLAG_KILL, PROC_FLAG_KILLED, PROC_EX_NONE, 0);
543 DEBUG_LOG("DealDamageAttackStop");
545 // stop combat
546 pVictim->CombatStop();
547 pVictim->getHostilRefManager().deleteReferences();
549 bool damageFromSpiritOfRedemtionTalent = spellProto && spellProto->Id == 27795;
551 // if talent known but not triggered (check priest class for speedup check)
552 Aura* spiritOfRedemtionTalentReady = NULL;
553 if( !damageFromSpiritOfRedemtionTalent && // not called from SPELL_AURA_SPIRIT_OF_REDEMPTION
554 pVictim->GetTypeId()==TYPEID_PLAYER && pVictim->getClass()==CLASS_PRIEST )
556 AuraList const& vDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
557 for(AuraList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr)
559 if((*itr)->GetSpellProto()->SpellIconID==1654)
561 spiritOfRedemtionTalentReady = *itr;
562 break;
567 DEBUG_LOG("SET JUST_DIED");
568 if(!spiritOfRedemtionTalentReady)
569 pVictim->setDeathState(JUST_DIED);
571 DEBUG_LOG("DealDamageHealth1");
573 if(spiritOfRedemtionTalentReady)
575 // save value before aura remove
576 uint32 ressSpellId = pVictim->GetUInt32Value(PLAYER_SELF_RES_SPELL);
577 if(!ressSpellId)
578 ressSpellId = ((Player*)pVictim)->GetResurrectionSpellId();
580 //Remove all expected to remove at death auras (most important negative case like DoT or periodic triggers)
581 pVictim->RemoveAllAurasOnDeath();
583 // restore for use at real death
584 pVictim->SetUInt32Value(PLAYER_SELF_RES_SPELL,ressSpellId);
586 // FORM_SPIRITOFREDEMPTION and related auras
587 pVictim->CastSpell(pVictim,27827,true,NULL,spiritOfRedemtionTalentReady);
589 else
590 pVictim->SetHealth(0);
592 // remember victim PvP death for corpse type and corpse reclaim delay
593 // at original death (not at SpiritOfRedemtionTalent timeout)
594 if( pVictim->GetTypeId()==TYPEID_PLAYER && !damageFromSpiritOfRedemtionTalent )
595 ((Player*)pVictim)->SetPvPDeath(player!=NULL);
597 // Call KilledUnit for creatures
598 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI())
599 ((Creature*)this)->AI()->KilledUnit(pVictim);
601 // achievement stuff
602 if (pVictim->GetTypeId() == TYPEID_PLAYER)
604 if (GetTypeId() == TYPEID_UNIT)
605 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE, GetEntry());
606 else if(GetTypeId() == TYPEID_PLAYER && pVictim != this)
607 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER, 1, ((Player*)this)->GetTeam());
610 // 10% durability loss on death
611 // clean InHateListOf
612 if (pVictim->GetTypeId() == TYPEID_PLAYER)
614 // only if not player and not controlled by player pet. And not at BG
615 if (durabilityLoss && !player && !((Player*)pVictim)->InBattleGround())
617 DEBUG_LOG("We are dead, loosing 10 percents durability");
618 ((Player*)pVictim)->DurabilityLossAll(0.10f,false);
619 // durability lost message
620 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
621 ((Player*)pVictim)->GetSession()->SendPacket(&data);
624 else // creature died
626 DEBUG_LOG("DealDamageNotPlayer");
627 Creature *cVictim = (Creature*)pVictim;
629 if(!cVictim->isPet())
631 cVictim->DeleteThreatList();
632 cVictim->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
634 // Call creature just died function
635 if (cVictim->AI())
636 cVictim->AI()->JustDied(this);
638 // Dungeon specific stuff, only applies to players killing creatures
639 if(cVictim->GetInstanceId())
641 Map *m = cVictim->GetMap();
642 Player *creditedPlayer = GetCharmerOrOwnerPlayerOrPlayerItself();
643 // TODO: do instance binding anyway if the charmer/owner is offline
645 if(m->IsDungeon() && creditedPlayer)
647 if(m->IsRaid() || m->IsHeroic())
649 if(cVictim->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)
650 ((InstanceMap *)m)->PermBindAllPlayers(creditedPlayer);
652 else
654 // the reset time is set but not added to the scheduler
655 // until the players leave the instance
656 time_t resettime = cVictim->GetRespawnTimeEx() + 2 * HOUR;
657 if(InstanceSave *save = sInstanceSaveManager.GetInstanceSave(cVictim->GetInstanceId()))
658 if(save->GetResetTime() < resettime) save->SetResetTime(resettime);
664 // last damage from non duel opponent or opponent controlled creature
665 if(duel_hasEnded)
667 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
668 Player *he = (Player*)pVictim;
670 assert(he->duel);
672 he->duel->opponent->CombatStopWithPets(true);
673 he->CombatStopWithPets(true);
675 he->DuelComplete(DUEL_INTERUPTED);
678 // battleground things (do this at the end, so the death state flag will be properly set to handle in the bg->handlekill)
679 if(pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->InBattleGround())
681 Player *killed = ((Player*)pVictim);
682 if(BattleGround *bg = killed->GetBattleGround())
683 if(player)
684 bg->HandleKillPlayer(killed, player);
685 //later we can add support for creature->player kills here i'm
686 //not sure, but i guess those kills also get counted in av
687 //else if(GetTypeId() == TYPEID_UNIT)
688 // bg->HandleKillPlayer(killed,(Creature*)this);
691 else // if (health <= damage)
693 DEBUG_LOG("DealDamageAlive");
695 if (pVictim->GetTypeId() == TYPEID_PLAYER)
696 ((Player*)pVictim)->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED, damage);
698 pVictim->ModifyHealth(- (int32)damage);
700 if(damagetype != DOT)
702 if(!getVictim())
704 // if not have main target then attack state with target (including AI call)
705 //start melee attacks only after melee hit
706 Attack(pVictim,(damagetype == DIRECT_DAMAGE));
709 // if damage pVictim call AI reaction
710 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
711 ((Creature*)pVictim)->AI()->AttackedBy(this);
714 // polymorphed and other negative transformed cases
715 if(pVictim->getTransForm() && pVictim->hasUnitState(UNIT_STAT_CONFUSED))
716 pVictim->RemoveAurasDueToSpell(pVictim->getTransForm());
718 if(damagetype == DIRECT_DAMAGE || damagetype == SPELL_DIRECT_DAMAGE)
720 if (!spellProto || !(spellProto->AuraInterruptFlags&AURA_INTERRUPT_FLAG_DIRECT_DAMAGE))
721 pVictim->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_DIRECT_DAMAGE);
723 if (pVictim->GetTypeId() != TYPEID_PLAYER)
725 if(spellProto && IsDamageToThreatSpell(spellProto))
726 pVictim->AddThreat(this, damage*2, damageSchoolMask, spellProto);
727 else
728 pVictim->AddThreat(this, damage, damageSchoolMask, spellProto);
730 else // victim is a player
732 // Rage from damage received
733 if(this != pVictim && pVictim->getPowerType() == POWER_RAGE)
735 uint32 rage_damage = damage + (cleanDamage ? cleanDamage->damage : 0);
736 ((Player*)pVictim)->RewardRage(rage_damage, 0, false);
739 // random durability for items (HIT TAKEN)
740 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
742 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
743 ((Player*)pVictim)->DurabilityPointLossForEquipSlot(slot);
747 if(GetTypeId()==TYPEID_PLAYER)
749 // random durability for items (HIT DONE)
750 if (roll_chance_f(sWorld.getRate(RATE_DURABILITY_LOSS_DAMAGE)))
752 EquipmentSlots slot = EquipmentSlots(urand(0,EQUIPMENT_SLOT_END-1));
753 ((Player*)this)->DurabilityPointLossForEquipSlot(slot);
757 // TODO: Store auras by interrupt flag to speed this up.
758 AuraMap& vAuras = pVictim->GetAuras();
759 for (AuraMap::iterator i = vAuras.begin(), next; i != vAuras.end(); i = next)
761 const SpellEntry *se = i->second->GetSpellProto();
762 next = i; ++next;
763 if (spellProto && spellProto->Id == se->Id) // Not drop auras added by self
764 continue;
765 if( se->AuraInterruptFlags & AURA_INTERRUPT_FLAG_DAMAGE )
767 bool remove = true;
768 if (se->procFlags & (1<<3))
770 if (!roll_chance_i(se->procChance))
771 remove = false;
773 if (remove)
775 pVictim->RemoveAurasDueToSpell(i->second->GetId());
776 // FIXME: this may cause the auras with proc chance to be rerolled several times
777 next = vAuras.begin();
782 if (damagetype != NODAMAGE && damage && pVictim->GetTypeId() == TYPEID_PLAYER)
784 if( damagetype != DOT )
786 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
788 // skip channeled spell (processed differently below)
789 if (i == CURRENT_CHANNELED_SPELL)
790 continue;
792 if(Spell* spell = pVictim->m_currentSpells[i])
793 if(spell->getState() == SPELL_STATE_PREPARING)
795 if(spell->m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_ABORT_ON_DMG)
796 pVictim->InterruptSpell(i);
797 else
798 spell->Delayed();
803 if(Spell* spell = pVictim->m_currentSpells[CURRENT_CHANNELED_SPELL])
805 if (spell->getState() == SPELL_STATE_CASTING)
807 uint32 channelInterruptFlags = spell->m_spellInfo->ChannelInterruptFlags;
808 if( channelInterruptFlags & CHANNEL_FLAG_DELAY )
810 if(pVictim!=this) //don't shorten the duration of channeling if you damage yourself
811 spell->DelayedChannel();
813 else if( (channelInterruptFlags & (CHANNEL_FLAG_DAMAGE | CHANNEL_FLAG_DAMAGE2)) )
815 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
816 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
819 else if (spell->getState() == SPELL_STATE_DELAYED)
820 // break channeled spell in delayed state on damage
822 sLog.outDetail("Spell %u canceled at damage!",spell->m_spellInfo->Id);
823 pVictim->InterruptSpell(CURRENT_CHANNELED_SPELL);
828 // last damage from duel opponent
829 if(duel_hasEnded)
831 assert(pVictim->GetTypeId()==TYPEID_PLAYER);
832 Player *he = (Player*)pVictim;
834 assert(he->duel);
836 he->SetHealth(1);
838 he->duel->opponent->CombatStopWithPets(true);
839 he->CombatStopWithPets(true);
841 he->CastSpell(he, 7267, true); // beg
842 he->DuelComplete(DUEL_WON);
846 DEBUG_LOG("DealDamageEnd returned %d damage", damage);
848 return damage;
851 void Unit::CastStop(uint32 except_spellid)
853 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
854 if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id!=except_spellid)
855 InterruptSpell(i,false);
858 void Unit::CastSpell(Unit* Victim, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
860 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
862 if(!spellInfo)
864 sLog.outError("CastSpell: unknown spell id %i by caster: %s %u)", spellId,(GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
865 return;
868 CastSpell(Victim,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
871 void Unit::CastSpell(Unit* Victim,SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
873 if(!spellInfo)
875 sLog.outError("CastSpell: unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
876 return;
879 if (castItem)
880 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
882 if(!originalCaster && triggeredByAura)
883 originalCaster = triggeredByAura->GetCasterGUID();
885 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
887 SpellCastTargets targets;
888 targets.setUnitTarget( Victim );
889 spell->m_CastItem = castItem;
890 spell->prepare(&targets, triggeredByAura);
893 void Unit::CastCustomSpell(Unit* Victim,uint32 spellId, int32 const* bp0, int32 const* bp1, int32 const* bp2, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
895 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
897 if(!spellInfo)
899 sLog.outError("CastCustomSpell: unknown spell id %i", spellId);
900 return;
903 CastCustomSpell(Victim,spellInfo,bp0,bp1,bp2,triggered,castItem,triggeredByAura, originalCaster);
906 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)
908 if(!spellInfo)
910 sLog.outError("CastCustomSpell: unknown spell");
911 return;
914 if (castItem)
915 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
917 if(!originalCaster && triggeredByAura)
918 originalCaster = triggeredByAura->GetCasterGUID();
920 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster);
922 if(bp0)
923 spell->m_currentBasePoints[0] = *bp0-int32(spellInfo->EffectBaseDice[0]);
925 if(bp1)
926 spell->m_currentBasePoints[1] = *bp1-int32(spellInfo->EffectBaseDice[1]);
928 if(bp2)
929 spell->m_currentBasePoints[2] = *bp2-int32(spellInfo->EffectBaseDice[2]);
931 SpellCastTargets targets;
932 targets.setUnitTarget( Victim );
933 spell->m_CastItem = castItem;
934 spell->prepare(&targets, triggeredByAura);
937 // used for scripting
938 void Unit::CastSpell(float x, float y, float z, uint32 spellId, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
940 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId );
942 if(!spellInfo)
944 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()));
945 return;
948 CastSpell(x, y, z,spellInfo,triggered,castItem,triggeredByAura, originalCaster);
951 // used for scripting
952 void Unit::CastSpell(float x, float y, float z, SpellEntry const *spellInfo, bool triggered, Item *castItem, Aura* triggeredByAura, uint64 originalCaster)
954 if(!spellInfo)
956 sLog.outError("CastSpell(x,y,z): unknown spell by caster: %s %u)", (GetTypeId()==TYPEID_PLAYER ? "player (GUID:" : "creature (Entry:"),(GetTypeId()==TYPEID_PLAYER ? GetGUIDLow() : GetEntry()));
957 return;
960 if (castItem)
961 DEBUG_LOG("WORLD: cast Item spellId - %i", spellInfo->Id);
963 if(!originalCaster && triggeredByAura)
964 originalCaster = triggeredByAura->GetCasterGUID();
966 Spell *spell = new Spell(this, spellInfo, triggered, originalCaster );
968 SpellCastTargets targets;
969 targets.setDestination(x, y, z);
970 spell->m_CastItem = castItem;
971 spell->prepare(&targets, triggeredByAura);
974 // Obsolete func need remove, here only for comotability vs another patches
975 uint32 Unit::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool isTriggeredSpell, bool useSpellDamage)
977 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellID);
978 SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, spellInfo->SchoolMask);
979 CalculateSpellDamage(&damageInfo, damage, spellInfo);
980 SendSpellNonMeleeDamageLog(&damageInfo);
981 DealSpellDamage(&damageInfo, true);
982 return damageInfo.damage;
985 void Unit::CalculateSpellDamage(SpellNonMeleeDamage *damageInfo, int32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType)
987 SpellSchoolMask damageSchoolMask = SpellSchoolMask(damageInfo->schoolMask);
988 Unit *pVictim = damageInfo->target;
990 if (damage < 0)
991 return;
993 if(!this || !pVictim)
994 return;
995 if(!this->isAlive() || !pVictim->isAlive())
996 return;
998 uint32 crTypeMask = pVictim->GetCreatureTypeMask();
999 // Check spell crit chance
1000 bool crit = isSpellCrit(pVictim, spellInfo, damageSchoolMask, attackType);
1001 bool blocked = false;
1002 // Per-school calc
1003 switch (spellInfo->DmgClass)
1005 // Melee and Ranged Spells
1006 case SPELL_DAMAGE_CLASS_RANGED:
1007 case SPELL_DAMAGE_CLASS_MELEE:
1009 // Physical Damage
1010 if ( damageSchoolMask & SPELL_SCHOOL_MASK_NORMAL )
1012 //Calculate armor mitigation
1013 damage = CalcArmorReducedDamage(pVictim, damage);
1014 // Get blocked status
1015 blocked = isSpellBlocked(pVictim, spellInfo, attackType);
1017 // Magical Damage
1018 else
1020 // Calculate damage bonus
1021 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1023 if (crit)
1025 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1027 // Calculate crit bonus
1028 uint32 crit_bonus = damage;
1029 // Apply crit_damage bonus for melee spells
1030 if(Player* modOwner = GetSpellModOwner())
1031 modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
1032 damage += crit_bonus;
1034 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1035 int32 critPctDamageMod=0;
1036 if(attackType == RANGED_ATTACK)
1037 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1038 else
1040 critPctDamageMod += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1041 critPctDamageMod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1043 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1044 critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1046 if (critPctDamageMod!=0)
1047 damage = int32((damage) * float((100.0f + critPctDamageMod)/100.0f));
1049 // Resilience - reduce crit damage
1050 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1051 damage -= ((Player*)pVictim)->GetMeleeCritDamageReduction(damage);
1053 // Spell weapon based damage CAN BE crit & blocked at same time
1054 if (blocked)
1056 damageInfo->blocked = uint32(pVictim->GetShieldBlockValue());
1057 if (damage < damageInfo->blocked)
1058 damageInfo->blocked = damage;
1059 damage-=damageInfo->blocked;
1062 break;
1063 // Magical Attacks
1064 case SPELL_DAMAGE_CLASS_NONE:
1065 case SPELL_DAMAGE_CLASS_MAGIC:
1067 // Calculate damage bonus
1068 damage = SpellDamageBonus(pVictim, spellInfo, damage, SPELL_DIRECT_DAMAGE);
1069 // If crit add critical bonus
1070 if (crit)
1072 damageInfo->HitInfo|= SPELL_HIT_TYPE_CRIT;
1073 damage = SpellCriticalDamageBonus(spellInfo, damage, pVictim);
1074 // Resilience - reduce crit damage
1075 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1076 damage -= ((Player*)pVictim)->GetSpellCritDamageReduction(damage);
1079 break;
1082 // Calculate absorb resist
1083 if(damage > 0)
1085 // lookup absorb/resist ignore auras on caster for spell
1086 bool ignore = false;
1087 Unit::AuraList const& ignoreAbsorb = GetAurasByType(SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL);
1088 for(Unit::AuraList::const_iterator i = ignoreAbsorb.begin(); i != ignoreAbsorb.end(); ++i)
1089 if ((*i)->isAffectedOnSpell(spellInfo))
1091 ignore = true;
1092 break;
1095 if (!ignore)
1097 CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist);
1098 damage-= damageInfo->absorb + damageInfo->resist;
1101 else
1102 damage = 0;
1103 damageInfo->damage = damage;
1106 void Unit::DealSpellDamage(SpellNonMeleeDamage *damageInfo, bool durabilityLoss)
1108 if (damageInfo==0)
1109 return;
1111 Unit *pVictim = damageInfo->target;
1113 if(!this || !pVictim)
1114 return;
1116 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1117 return;
1119 SpellEntry const *spellProto = sSpellStore.LookupEntry(damageInfo->SpellID);
1120 if (spellProto == NULL)
1122 sLog.outDebug("Unit::DealSpellDamage have wrong damageInfo->SpellID: %u", damageInfo->SpellID);
1123 return;
1126 //You don't lose health from damage taken from another player while in a sanctuary
1127 //You still see it in the combat log though
1128 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1130 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1131 if(area && area->flags & 0x800) //sanctuary
1132 return;
1135 // Call default DealDamage
1136 CleanDamage cleanDamage(damageInfo->cleanDamage, BASE_ATTACK, MELEE_HIT_NORMAL);
1137 DealDamage(pVictim, damageInfo->damage, &cleanDamage, SPELL_DIRECT_DAMAGE, SpellSchoolMask(damageInfo->schoolMask), spellProto, durabilityLoss);
1140 //TODO for melee need create structure as in
1141 void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType)
1143 damageInfo->attacker = this;
1144 damageInfo->target = pVictim;
1145 damageInfo->damageSchoolMask = GetMeleeDamageSchoolMask();
1146 damageInfo->attackType = attackType;
1147 damageInfo->damage = 0;
1148 damageInfo->cleanDamage = 0;
1149 damageInfo->absorb = 0;
1150 damageInfo->resist = 0;
1151 damageInfo->blocked_amount = 0;
1153 damageInfo->TargetState = 0;
1154 damageInfo->HitInfo = 0;
1155 damageInfo->procAttacker = PROC_FLAG_NONE;
1156 damageInfo->procVictim = PROC_FLAG_NONE;
1157 damageInfo->procEx = PROC_EX_NONE;
1158 damageInfo->hitOutCome = MELEE_HIT_EVADE;
1160 if(!this || !pVictim)
1161 return;
1162 if(!this->isAlive() || !pVictim->isAlive())
1163 return;
1165 // Select HitInfo/procAttacker/procVictim flag based on attack type
1166 switch (attackType)
1168 case BASE_ATTACK:
1169 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT;
1170 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;
1171 damageInfo->HitInfo = HITINFO_NORMALSWING2;
1172 break;
1173 case OFF_ATTACK:
1174 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_MILEE_HIT | PROC_FLAG_SUCCESSFUL_OFFHAND_HIT;
1175 damageInfo->procVictim = PROC_FLAG_TAKEN_MELEE_HIT;//|PROC_FLAG_TAKEN_OFFHAND_HIT // not used
1176 damageInfo->HitInfo = HITINFO_LEFTSWING;
1177 break;
1178 case RANGED_ATTACK:
1179 damageInfo->procAttacker = PROC_FLAG_SUCCESSFUL_RANGED_HIT;
1180 damageInfo->procVictim = PROC_FLAG_TAKEN_RANGED_HIT;
1181 damageInfo->HitInfo = 0x08;// test
1182 break;
1183 default:
1184 break;
1187 // Physical Immune check
1188 if(damageInfo->target->IsImmunedToDamage(SpellSchoolMask(damageInfo->damageSchoolMask)))
1190 damageInfo->HitInfo |= HITINFO_NORMALSWING;
1191 damageInfo->TargetState = VICTIMSTATE_IS_IMMUNE;
1193 damageInfo->procEx |=PROC_EX_IMMUNE;
1194 damageInfo->damage = 0;
1195 damageInfo->cleanDamage = 0;
1196 return;
1198 damage += CalculateDamage (damageInfo->attackType, false);
1199 // Add melee damage bonus
1200 MeleeDamageBonus(damageInfo->target, &damage, damageInfo->attackType);
1201 // Calculate armor reduction
1202 damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage);
1203 damageInfo->cleanDamage += damage - damageInfo->damage;
1205 damageInfo->hitOutCome = RollMeleeOutcomeAgainst(damageInfo->target, damageInfo->attackType);
1207 // Disable parry or dodge for ranged attack
1208 if(damageInfo->attackType == RANGED_ATTACK)
1210 if (damageInfo->hitOutCome == MELEE_HIT_PARRY) damageInfo->hitOutCome = MELEE_HIT_NORMAL;
1211 if (damageInfo->hitOutCome == MELEE_HIT_DODGE) damageInfo->hitOutCome = MELEE_HIT_MISS;
1214 switch(damageInfo->hitOutCome)
1216 case MELEE_HIT_EVADE:
1218 damageInfo->HitInfo |= HITINFO_MISS|HITINFO_SWINGNOHITSOUND;
1219 damageInfo->TargetState = VICTIMSTATE_EVADES;
1221 damageInfo->procEx|=PROC_EX_EVADE;
1222 damageInfo->damage = 0;
1223 damageInfo->cleanDamage = 0;
1224 return;
1226 case MELEE_HIT_MISS:
1228 damageInfo->HitInfo |= HITINFO_MISS;
1229 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1231 damageInfo->procEx|=PROC_EX_MISS;
1232 damageInfo->damage = 0;
1233 damageInfo->cleanDamage = 0;
1234 break;
1236 case MELEE_HIT_NORMAL:
1237 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1238 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1239 break;
1240 case MELEE_HIT_CRIT:
1242 damageInfo->HitInfo |= HITINFO_CRITICALHIT;
1243 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1245 damageInfo->procEx|=PROC_EX_CRITICAL_HIT;
1246 // Crit bonus calc
1247 damageInfo->damage += damageInfo->damage;
1248 int32 mod=0;
1249 // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE
1250 if(damageInfo->attackType == RANGED_ATTACK)
1251 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE);
1252 else
1254 mod += damageInfo->target->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE);
1255 mod += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_DAMAGE_BONUS_MELEE);
1258 uint32 crTypeMask = damageInfo->target->GetCreatureTypeMask();
1260 // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS
1261 mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask);
1262 if (mod!=0)
1263 damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f));
1265 // Resilience - reduce crit damage
1266 if (pVictim->GetTypeId()==TYPEID_PLAYER)
1268 uint32 resilienceReduction = ((Player*)pVictim)->GetMeleeCritDamageReduction(damageInfo->damage);
1269 damageInfo->damage -= resilienceReduction;
1270 damageInfo->cleanDamage += resilienceReduction;
1272 break;
1274 case MELEE_HIT_PARRY:
1275 damageInfo->TargetState = VICTIMSTATE_PARRY;
1276 damageInfo->procEx|=PROC_EX_PARRY;
1277 damageInfo->cleanDamage += damageInfo->damage;
1278 damageInfo->damage = 0;
1279 break;
1281 case MELEE_HIT_DODGE:
1282 damageInfo->TargetState = VICTIMSTATE_DODGE;
1283 damageInfo->procEx|=PROC_EX_DODGE;
1284 damageInfo->cleanDamage += damageInfo->damage;
1285 damageInfo->damage = 0;
1286 break;
1287 case MELEE_HIT_BLOCK:
1289 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1290 damageInfo->HitInfo |= HITINFO_BLOCK;
1291 damageInfo->procEx|=PROC_EX_BLOCK;
1292 damageInfo->blocked_amount = damageInfo->target->GetShieldBlockValue();
1293 if (damageInfo->blocked_amount >= damageInfo->damage)
1295 damageInfo->TargetState = VICTIMSTATE_BLOCKS;
1296 damageInfo->blocked_amount = damageInfo->damage;
1298 damageInfo->damage -= damageInfo->blocked_amount;
1299 damageInfo->cleanDamage += damageInfo->blocked_amount;
1300 break;
1302 case MELEE_HIT_GLANCING:
1304 damageInfo->HitInfo |= HITINFO_GLANCING;
1305 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1306 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1307 float reducePercent = 1.0f; //damage factor
1308 // calculate base values and mods
1309 float baseLowEnd = 1.3f;
1310 float baseHighEnd = 1.2f;
1311 switch(getClass()) // lowering base values for casters
1313 case CLASS_SHAMAN:
1314 case CLASS_PRIEST:
1315 case CLASS_MAGE:
1316 case CLASS_WARLOCK:
1317 case CLASS_DRUID:
1318 baseLowEnd -= 0.7f;
1319 baseHighEnd -= 0.3f;
1320 break;
1323 float maxLowEnd = 0.6f;
1324 switch(getClass()) // upper for melee classes
1326 case CLASS_WARRIOR:
1327 case CLASS_ROGUE:
1328 maxLowEnd = 0.91f; //If the attacker is a melee class then instead the lower value of 0.91
1331 // calculate values
1332 int32 diff = damageInfo->target->GetDefenseSkillValue() - GetWeaponSkillValue(damageInfo->attackType);
1333 float lowEnd = baseLowEnd - ( 0.05f * diff );
1334 float highEnd = baseHighEnd - ( 0.03f * diff );
1336 // apply max/min bounds
1337 if ( lowEnd < 0.01f ) //the low end must not go bellow 0.01f
1338 lowEnd = 0.01f;
1339 else if ( lowEnd > maxLowEnd ) //the smaller value of this and 0.6 is kept as the low end
1340 lowEnd = maxLowEnd;
1342 if ( highEnd < 0.2f ) //high end limits
1343 highEnd = 0.2f;
1344 if ( highEnd > 0.99f )
1345 highEnd = 0.99f;
1347 if(lowEnd > highEnd) // prevent negative range size
1348 lowEnd = highEnd;
1350 reducePercent = lowEnd + rand_norm() * ( highEnd - lowEnd );
1352 damageInfo->cleanDamage += damageInfo->damage-uint32(reducePercent * damageInfo->damage);
1353 damageInfo->damage = uint32(reducePercent * damageInfo->damage);
1354 break;
1356 case MELEE_HIT_CRUSHING:
1358 damageInfo->HitInfo |= HITINFO_CRUSHING;
1359 damageInfo->TargetState = VICTIMSTATE_NORMAL;
1360 damageInfo->procEx|=PROC_EX_NORMAL_HIT;
1361 // 150% normal damage
1362 damageInfo->damage += (damageInfo->damage / 2);
1363 break;
1365 default:
1367 break;
1370 // Calculate absorb resist
1371 if(int32(damageInfo->damage) > 0)
1373 damageInfo->procVictim |= PROC_FLAG_TAKEN_ANY_DAMAGE;
1374 // Calculate absorb & resists
1375 CalcAbsorbResist(damageInfo->target, SpellSchoolMask(damageInfo->damageSchoolMask), DIRECT_DAMAGE, damageInfo->damage, &damageInfo->absorb, &damageInfo->resist);
1376 damageInfo->damage-=damageInfo->absorb + damageInfo->resist;
1377 if (damageInfo->absorb)
1379 damageInfo->HitInfo|=HITINFO_ABSORB;
1380 damageInfo->procEx|=PROC_EX_ABSORB;
1382 if (damageInfo->resist)
1383 damageInfo->HitInfo|=HITINFO_RESIST;
1386 else // Umpossible get negative result but....
1387 damageInfo->damage = 0;
1390 void Unit::DealMeleeDamage(CalcDamageInfo *damageInfo, bool durabilityLoss)
1392 if (damageInfo==0) return;
1393 Unit *pVictim = damageInfo->target;
1395 if(!this || !pVictim)
1396 return;
1398 if (!pVictim->isAlive() || pVictim->isInFlight() || pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
1399 return;
1401 //You don't lose health from damage taken from another player while in a sanctuary
1402 //You still see it in the combat log though
1403 if(pVictim != this && GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
1405 const AreaTableEntry *area = GetAreaEntryByAreaID(pVictim->GetAreaId());
1406 if(area && area->flags & 0x800) //sanctuary
1407 return;
1410 // Hmmmm dont like this emotes cloent must by self do all animations
1411 if (damageInfo->HitInfo&HITINFO_CRITICALHIT)
1412 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_WOUNDCRITICAL);
1413 if(damageInfo->blocked_amount && damageInfo->TargetState!=VICTIMSTATE_BLOCKS)
1414 pVictim->HandleEmoteCommand(EMOTE_ONESHOT_PARRYSHIELD);
1416 if(damageInfo->TargetState == VICTIMSTATE_PARRY)
1418 // Get attack timers
1419 float offtime = float(pVictim->getAttackTimer(OFF_ATTACK));
1420 float basetime = float(pVictim->getAttackTimer(BASE_ATTACK));
1421 // Reduce attack time
1422 if (pVictim->haveOffhandWeapon() && offtime < basetime)
1424 float percent20 = pVictim->GetAttackTime(OFF_ATTACK) * 0.20f;
1425 float percent60 = 3.0f * percent20;
1426 if(offtime > percent20 && offtime <= percent60)
1428 pVictim->setAttackTimer(OFF_ATTACK, uint32(percent20));
1430 else if(offtime > percent60)
1432 offtime -= 2.0f * percent20;
1433 pVictim->setAttackTimer(OFF_ATTACK, uint32(offtime));
1436 else
1438 float percent20 = pVictim->GetAttackTime(BASE_ATTACK) * 0.20;
1439 float percent60 = 3.0f * percent20;
1440 if(basetime > percent20 && basetime <= percent60)
1442 pVictim->setAttackTimer(BASE_ATTACK, uint32(percent20));
1444 else if(basetime > percent60)
1446 basetime -= 2.0f * percent20;
1447 pVictim->setAttackTimer(BASE_ATTACK, uint32(basetime));
1452 // Call default DealDamage
1453 CleanDamage cleanDamage(damageInfo->cleanDamage,damageInfo->attackType,damageInfo->hitOutCome);
1454 DealDamage(pVictim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss);
1456 // If this is a creature and it attacks from behind it has a probability to daze it's victim
1457 if( (damageInfo->hitOutCome==MELEE_HIT_CRIT || damageInfo->hitOutCome==MELEE_HIT_CRUSHING || damageInfo->hitOutCome==MELEE_HIT_NORMAL || damageInfo->hitOutCome==MELEE_HIT_GLANCING) &&
1458 GetTypeId() != TYPEID_PLAYER && !((Creature*)this)->GetCharmerOrOwnerGUID() && !pVictim->HasInArc(M_PI, this) )
1460 // -probability is between 0% and 40%
1461 // 20% base chance
1462 float Probability = 20.0f;
1464 //there is a newbie protection, at level 10 just 7% base chance; assuming linear function
1465 if( pVictim->getLevel() < 30 )
1466 Probability = 0.65f*pVictim->getLevel()+0.5f;
1468 uint32 VictimDefense=pVictim->GetDefenseSkillValue();
1469 uint32 AttackerMeleeSkill=GetUnitMeleeSkill();
1471 Probability *= AttackerMeleeSkill/(float)VictimDefense;
1473 if(Probability > 40.0f)
1474 Probability = 40.0f;
1476 if(roll_chance_f(Probability))
1477 CastSpell(pVictim, 1604, true);
1480 // If not miss
1481 if (!(damageInfo->HitInfo & HITINFO_MISS))
1483 if(GetTypeId() == TYPEID_PLAYER && pVictim->isAlive())
1485 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
1486 ((Player*)this)->CastItemCombatSpell(((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0,i), pVictim, damageInfo->attackType);
1489 // victim's damage shield
1490 std::set<Aura*> alreadyDone;
1491 uint32 removedAuras = pVictim->m_removedAuras;
1492 AuraList const& vDamageShields = pVictim->GetAurasByType(SPELL_AURA_DAMAGE_SHIELD);
1493 for(AuraList::const_iterator i = vDamageShields.begin(), next = vDamageShields.begin(); i != vDamageShields.end(); i = next)
1495 next++;
1496 if (alreadyDone.find(*i) == alreadyDone.end())
1498 alreadyDone.insert(*i);
1499 uint32 damage=(*i)->GetModifier()->m_amount;
1500 SpellEntry const *spellProto = sSpellStore.LookupEntry((*i)->GetId());
1501 if(!spellProto)
1502 continue;
1503 //Calculate absorb resist ??? no data in opcode for this possibly unable to absorb or resist?
1504 //uint32 absorb;
1505 //uint32 resist;
1506 //CalcAbsorbResist(pVictim, SpellSchools(spellProto->School), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist);
1507 //damage-=absorb + resist;
1509 WorldPacket data(SMSG_SPELLDAMAGESHIELD,(8+8+4+4+4+4));
1510 data << uint64(pVictim->GetGUID());
1511 data << uint64(GetGUID());
1512 data << uint32(spellProto->Id);
1513 data << uint32(damage); // Damage
1514 data << uint32(0); // Overkill
1515 data << uint32(spellProto->SchoolMask);
1516 pVictim->SendMessageToSet(&data, true );
1518 pVictim->DealDamage(this, damage, 0, SPELL_DIRECT_DAMAGE, GetSpellSchoolMask(spellProto), spellProto, true);
1520 if (pVictim->m_removedAuras > removedAuras)
1522 removedAuras = pVictim->m_removedAuras;
1523 next = vDamageShields.begin();
1531 void Unit::HandleEmoteCommand(uint32 anim_id)
1533 WorldPacket data( SMSG_EMOTE, 12 );
1534 data << uint32(anim_id);
1535 data << uint64(GetGUID());
1536 SendMessageToSet(&data, true);
1539 uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage)
1541 uint32 newdamage = 0;
1542 float armor = pVictim->GetArmor();
1543 // Ignore enemy armor by SPELL_AURA_MOD_TARGET_RESISTANCE aura
1544 armor += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, SPELL_SCHOOL_MASK_NORMAL);
1546 // Apply Player CR_ARMOR_PENETRATION rating
1547 if (GetTypeId()==TYPEID_PLAYER)
1548 armor *= 1.0f - ((Player*)this)->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f;
1550 if (armor < 0.0f) armor=0.0f;
1552 float levelModifier = getLevel();
1553 if ( levelModifier > 59 )
1554 levelModifier = levelModifier + (4.5f * (levelModifier-59));
1556 float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40);
1557 tmpvalue = tmpvalue/(1.0f + tmpvalue);
1559 if(tmpvalue < 0.0f)
1560 tmpvalue = 0.0f;
1561 if(tmpvalue > 0.75f)
1562 tmpvalue = 0.75f;
1563 newdamage = uint32(damage - (damage * tmpvalue));
1565 return (newdamage > 1) ? newdamage : 1;
1568 void Unit::CalcAbsorbResist(Unit *pVictim,SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist)
1570 if(!pVictim || !pVictim->isAlive() || !damage)
1571 return;
1573 // Magic damage, check for resists
1574 if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL)==0)
1576 // Get base victim resistance for school
1577 float tmpvalue2 = (float)pVictim->GetResistance(GetFirstSchoolInMask(schoolMask));
1578 // Ignore resistance by self SPELL_AURA_MOD_TARGET_RESISTANCE aura
1579 tmpvalue2 += (float)GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_TARGET_RESISTANCE, schoolMask);
1581 tmpvalue2 *= (float)(0.15f / getLevel());
1582 if (tmpvalue2 < 0.0f)
1583 tmpvalue2 = 0.0f;
1584 if (tmpvalue2 > 0.75f)
1585 tmpvalue2 = 0.75f;
1586 uint32 ran = urand(0, 100);
1587 uint32 faq[4] = {24,6,4,6};
1588 uint8 m = 0;
1589 float Binom = 0.0f;
1590 for (uint8 i = 0; i < 4; i++)
1592 Binom += 2400 *( powf(tmpvalue2, i) * powf( (1-tmpvalue2), (4-i)))/faq[i];
1593 if (ran > Binom )
1594 ++m;
1595 else
1596 break;
1598 if (damagetype == DOT && m == 4)
1599 *resist += uint32(damage - 1);
1600 else
1601 *resist += uint32(damage * m / 4);
1602 if(*resist > damage)
1603 *resist = damage;
1605 else
1606 *resist = 0;
1608 int32 RemainingDamage = damage - *resist;
1610 // Get unit state (need for some absorb check)
1611 uint32 unitflag = pVictim->GetUInt32Value(UNIT_FIELD_FLAGS);
1612 // Reflect damage spells (not cast any damage spell in aura lookup)
1613 uint32 reflectSpell = 0;
1614 int32 reflectDamage = 0;
1615 // Need remove expired auras after
1616 bool existExpired = false;
1617 // absorb without mana cost
1618 AuraList const& vSchoolAbsorb = pVictim->GetAurasByType(SPELL_AURA_SCHOOL_ABSORB);
1619 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i)
1621 Modifier* mod = (*i)->GetModifier();
1622 if (!(mod->m_miscvalue & schoolMask))
1623 continue;
1625 SpellEntry const* spellProto = (*i)->GetSpellProto();
1627 // Max Amount can be absorbed by this aura
1628 int32 currentAbsorb = mod->m_amount;
1630 // Found empty aura (umpossible but..)
1631 if (currentAbsorb <=0)
1633 existExpired = true;
1634 continue;
1636 // Handle custom absorb auras
1637 // TODO: try find better way
1638 switch(spellProto->SpellFamilyName)
1640 case SPELLFAMILY_GENERIC:
1642 // Astral Shift
1643 if (spellProto->SpellIconID == 3066)
1645 //reduces all damage taken while stun, fear or silence
1646 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1647 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1648 continue;
1650 // Nerves of Steel
1651 if (spellProto->SpellIconID == 2115)
1653 // while affected by Stun and Fear
1654 if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING))
1655 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1656 continue;
1658 // Spell Deflection
1659 if (spellProto->SpellIconID == 3006)
1661 // You have a chance equal to your Parry chance
1662 if (damagetype == DIRECT_DAMAGE && // Only for direct damage
1663 roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance
1664 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1665 continue;
1667 // Reflective Shield (Lady Malande boss)
1668 if (spellProto->Id == 41475)
1670 if(RemainingDamage < currentAbsorb)
1671 reflectDamage = RemainingDamage / 2;
1672 else
1673 reflectDamage = currentAbsorb / 2;
1674 reflectSpell = 33619;
1675 break;
1677 if (spellProto->Id == 39228 || // Argussian Compass
1678 spellProto->Id == 60218) // Essence of Gossamer
1680 // Max absorb stored in 1 dummy effect
1681 if (spellProto->EffectBasePoints[1] < currentAbsorb)
1682 currentAbsorb = spellProto->EffectBasePoints[1];
1683 break;
1685 break;
1687 case SPELLFAMILY_DRUID:
1689 // Primal Tenacity
1690 if (spellProto->SpellIconID == 2253)
1692 //reduces all damage taken while Stunned
1693 if (unitflag & UNIT_FLAG_STUNNED)
1694 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1695 continue;
1697 break;
1699 case SPELLFAMILY_ROGUE:
1701 // Cheat Death
1702 if(spellProto->SpellIconID == 2109)
1704 if (pVictim->GetTypeId()==TYPEID_PLAYER && // Only players
1705 pVictim->GetHealth() <= RemainingDamage && // Only if damage kill
1706 !((Player*)pVictim)->HasSpellCooldown(31231) && // Only if no cooldown
1707 roll_chance_i(currentAbsorb)) // Only if roll
1709 pVictim->CastSpell(pVictim,31231,true);
1710 ((Player*)pVictim)->AddSpellCooldown(31231,0,time(NULL)+60);
1711 // with health > 10% lost health until health==10%, in other case no losses
1712 uint32 health10 = pVictim->GetMaxHealth()/10;
1713 RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0;
1715 continue;
1717 break;
1719 case SPELLFAMILY_PRIEST:
1721 // Reflective Shield
1722 if (spellProto->SpellFamilyFlags == 0x1)
1724 if (pVictim == this)
1725 break;
1726 Unit* caster = (*i)->GetCaster();
1727 if (!caster)
1728 break;
1729 AuraList const& vOverRideCS = caster->GetAurasByType(SPELL_AURA_DUMMY);
1730 for(AuraList::const_iterator k = vOverRideCS.begin(); k != vOverRideCS.end(); ++k)
1732 switch((*k)->GetModifier()->m_miscvalue)
1734 case 5065: // Rank 1
1735 case 5064: // Rank 2
1736 case 5063: // Rank 3
1738 if(RemainingDamage >= currentAbsorb)
1739 reflectDamage = (*k)->GetModifier()->m_amount * currentAbsorb/100;
1740 else
1741 reflectDamage = (*k)->GetModifier()->m_amount * RemainingDamage/100;
1742 reflectSpell = 33619;
1743 } break;
1744 default: break;
1747 break;
1749 break;
1751 case SPELLFAMILY_SHAMAN:
1753 // Astral Shift
1754 if (spellProto->SpellIconID == 3066)
1756 //reduces all damage taken while stun, fear or silence
1757 if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED))
1758 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1759 continue;
1761 break;
1763 case SPELLFAMILY_DEATHKNIGHT:
1765 // Shadow of Death
1766 if (spellProto->SpellIconID == 1958)
1768 // TODO: absorb only while transform
1769 continue;
1771 // Anti-Magic Shell (on self)
1772 if (spellProto->Id == 48707)
1774 // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power.
1775 // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power.
1776 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1777 int32 regen = absorbed * 2 / 10;
1778 pVictim->CastCustomSpell(pVictim, 49088, &regen, 0, 0, true, 0, *i);
1779 RemainingDamage -= absorbed;
1780 continue;
1782 // Anti-Magic Shell (on single party/raid member)
1783 if (spellProto->Id == 50462)
1785 RemainingDamage -= RemainingDamage * currentAbsorb / 100;
1786 continue;
1788 // Anti-Magic Zone
1789 if (spellProto->Id == 50461)
1791 Unit* caster = (*i)->GetCaster();
1792 if (!caster)
1793 continue;
1794 int32 absorbed = RemainingDamage * currentAbsorb / 100;
1795 int32 canabsorb = caster->GetHealth();
1796 if (canabsorb < absorbed)
1797 absorbed = canabsorb;
1798 DealDamage(caster, absorbed, NULL, damagetype, schoolMask, 0, false);
1799 RemainingDamage -= absorbed;
1800 continue;
1802 break;
1804 default:
1805 break;
1808 // currentAbsorb - damage can be absorbed by shield
1809 // If need absorb less damage
1810 if (RemainingDamage < currentAbsorb)
1811 currentAbsorb = RemainingDamage;
1813 RemainingDamage -= currentAbsorb;
1815 // Reduce shield amount
1816 mod->m_amount-=currentAbsorb;
1817 // Need remove it later
1818 if (mod->m_amount<=0)
1819 existExpired = true;
1822 // Remove all expired absorb auras
1823 if (existExpired)
1825 for(AuraList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();)
1827 if ((*i)->GetModifier()->m_amount<=0)
1829 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1830 i = vSchoolAbsorb.begin();
1832 else
1833 ++i;
1836 // Cast back reflect damage spell
1837 if (reflectSpell)
1838 pVictim->CastCustomSpell(this, reflectSpell, &reflectDamage, NULL, NULL, true);
1840 // absorb by mana cost
1841 AuraList const& vManaShield = pVictim->GetAurasByType(SPELL_AURA_MANA_SHIELD);
1842 for(AuraList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next)
1844 next = i; ++next;
1846 // check damage school mask
1847 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1848 continue;
1850 int32 currentAbsorb;
1851 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1852 currentAbsorb = (*i)->GetModifier()->m_amount;
1853 else
1854 currentAbsorb = RemainingDamage;
1856 float manaMultiplier = (*i)->GetSpellProto()->EffectMultipleValue[(*i)->GetEffIndex()];
1857 if(Player *modOwner = pVictim->GetSpellModOwner())
1858 modOwner->ApplySpellMod((*i)->GetId(), SPELLMOD_MULTIPLE_VALUE, manaMultiplier);
1860 int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier);
1861 if (currentAbsorb > maxAbsorb)
1862 currentAbsorb = maxAbsorb;
1864 (*i)->GetModifier()->m_amount -= currentAbsorb;
1865 if((*i)->GetModifier()->m_amount <= 0)
1867 pVictim->RemoveAurasDueToSpell((*i)->GetId());
1868 next = vManaShield.begin();
1871 int32 manaReduction = int32(currentAbsorb * manaMultiplier);
1872 pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false);
1874 RemainingDamage -= currentAbsorb;
1877 // only split damage if not damaging yourself
1878 if(pVictim != this)
1880 AuraList const& vSplitDamageFlat = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_FLAT);
1881 for(AuraList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next)
1883 next = i; ++next;
1885 // check damage school mask
1886 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1887 continue;
1889 // Damage can be splitted only if aura has an alive caster
1890 Unit *caster = (*i)->GetCaster();
1891 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1892 continue;
1894 int32 currentAbsorb;
1895 if (RemainingDamage >= (*i)->GetModifier()->m_amount)
1896 currentAbsorb = (*i)->GetModifier()->m_amount;
1897 else
1898 currentAbsorb = RemainingDamage;
1900 RemainingDamage -= currentAbsorb;
1902 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, currentAbsorb, schoolMask, 0, 0, false, 0, false);
1904 CleanDamage cleanDamage = CleanDamage(currentAbsorb, BASE_ATTACK, MELEE_HIT_NORMAL);
1905 DealDamage(caster, currentAbsorb, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1908 AuraList const& vSplitDamagePct = pVictim->GetAurasByType(SPELL_AURA_SPLIT_DAMAGE_PCT);
1909 for(AuraList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next)
1911 next = i; ++next;
1913 // check damage school mask
1914 if(((*i)->GetModifier()->m_miscvalue & schoolMask)==0)
1915 continue;
1917 // Damage can be splitted only if aura has an alive caster
1918 Unit *caster = (*i)->GetCaster();
1919 if(!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive())
1920 continue;
1922 int32 splitted = int32(RemainingDamage * (*i)->GetModifier()->m_amount / 100.0f);
1924 RemainingDamage -= splitted;
1926 SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, 0, 0, false, 0, false);
1928 CleanDamage cleanDamage = CleanDamage(splitted, BASE_ATTACK, MELEE_HIT_NORMAL);
1929 DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false);
1933 *absorb = damage - RemainingDamage - *resist;
1936 void Unit::AttackerStateUpdate (Unit *pVictim, WeaponAttackType attType, bool extra )
1938 if(hasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED) )
1939 return;
1941 if (!pVictim->isAlive())
1942 return;
1944 if(IsNonMeleeSpellCasted(false))
1945 return;
1947 uint32 hitInfo;
1948 if (attType == BASE_ATTACK)
1949 hitInfo = HITINFO_NORMALSWING2;
1950 else if (attType == OFF_ATTACK)
1951 hitInfo = HITINFO_LEFTSWING;
1952 else
1953 return; // ignore ranged case
1955 uint32 extraAttacks = m_extraAttacks;
1957 // melee attack spell casted at main hand attack only
1958 if (attType == BASE_ATTACK && m_currentSpells[CURRENT_MELEE_SPELL])
1960 m_currentSpells[CURRENT_MELEE_SPELL]->cast();
1962 // not recent extra attack only at any non extra attack (melee spell case)
1963 if(!extra && extraAttacks)
1965 while(m_extraAttacks)
1967 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
1968 if(m_extraAttacks > 0)
1969 --m_extraAttacks;
1973 // if damage pVictim call AI reaction
1974 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
1975 ((Creature*)pVictim)->AI()->AttackedBy(this);
1977 return;
1980 // attack can be redirected to another target
1981 pVictim = SelectMagnetTarget(pVictim);
1983 CalcDamageInfo damageInfo;
1984 CalculateMeleeDamage(pVictim, 0, &damageInfo, attType);
1985 // Send log damage message to client
1986 SendAttackStateUpdate(&damageInfo);
1987 ProcDamageAndSpell(damageInfo.target, damageInfo.procAttacker, damageInfo.procVictim, damageInfo.procEx, damageInfo.damage, damageInfo.attackType);
1988 DealMeleeDamage(&damageInfo,true);
1990 if (GetTypeId() == TYPEID_PLAYER)
1991 DEBUG_LOG("AttackerStateUpdate: (Player) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1992 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1993 else
1994 DEBUG_LOG("AttackerStateUpdate: (NPC) %u attacked %u (TypeId: %u) for %u dmg, absorbed %u, blocked %u, resisted %u.",
1995 GetGUIDLow(), pVictim->GetGUIDLow(), pVictim->GetTypeId(), damageInfo.damage, damageInfo.absorb, damageInfo.blocked_amount, damageInfo.resist);
1997 // extra attack only at any non extra attack (normal case)
1998 if(!extra && extraAttacks)
2000 while(m_extraAttacks)
2002 AttackerStateUpdate(pVictim, BASE_ATTACK, true);
2003 if(m_extraAttacks > 0)
2004 --m_extraAttacks;
2008 // if damage pVictim call AI reaction
2009 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->AI())
2010 ((Creature*)pVictim)->AI()->AttackedBy(this);
2013 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst(const Unit *pVictim, WeaponAttackType attType) const
2015 // This is only wrapper
2017 // Miss chance based on melee
2018 float miss_chance = MeleeMissChanceCalc(pVictim, attType);
2020 // Critical hit chance
2021 float crit_chance = GetUnitCriticalChance(attType, pVictim);
2023 // stunned target cannot dodge and this is check in GetUnitDodgeChance() (returned 0 in this case)
2024 float dodge_chance = pVictim->GetUnitDodgeChance();
2025 float block_chance = pVictim->GetUnitBlockChance();
2026 float parry_chance = pVictim->GetUnitParryChance();
2028 // Useful if want to specify crit & miss chances for melee, else it could be removed
2029 DEBUG_LOG("MELEE OUTCOME: miss %f crit %f dodge %f parry %f block %f", miss_chance,crit_chance,dodge_chance,parry_chance,block_chance);
2031 return RollMeleeOutcomeAgainst(pVictim, attType, int32(crit_chance*100), int32(miss_chance*100), int32(dodge_chance*100),int32(parry_chance*100),int32(block_chance*100));
2034 MeleeHitOutcome Unit::RollMeleeOutcomeAgainst (const Unit *pVictim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const
2036 if(pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2037 return MELEE_HIT_EVADE;
2039 int32 attackerMaxSkillValueForLevel = GetMaxSkillValueForLevel(pVictim);
2040 int32 victimMaxSkillValueForLevel = pVictim->GetMaxSkillValueForLevel(this);
2042 int32 attackerWeaponSkill = GetWeaponSkillValue(attType,pVictim);
2043 int32 victimDefenseSkill = pVictim->GetDefenseSkillValue(this);
2045 // bonus from skills is 0.04%
2046 int32 skillBonus = 4 * ( attackerWeaponSkill - victimMaxSkillValueForLevel );
2047 int32 sum = 0, tmp = 0;
2048 int32 roll = urand (0, 10000);
2050 DEBUG_LOG ("RollMeleeOutcomeAgainst: skill bonus of %d for attacker", skillBonus);
2051 DEBUG_LOG ("RollMeleeOutcomeAgainst: rolled %d, miss %d, dodge %d, parry %d, block %d, crit %d",
2052 roll, miss_chance, dodge_chance, parry_chance, block_chance, crit_chance);
2054 tmp = miss_chance;
2056 if (tmp > 0 && roll < (sum += tmp ))
2058 DEBUG_LOG ("RollMeleeOutcomeAgainst: MISS");
2059 return MELEE_HIT_MISS;
2062 // always crit against a sitting target (except 0 crit chance)
2063 if( pVictim->GetTypeId() == TYPEID_PLAYER && crit_chance > 0 && !pVictim->IsStandState() )
2065 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT (sitting victim)");
2066 return MELEE_HIT_CRIT;
2069 // Dodge chance
2071 // only players can't dodge if attacker is behind
2072 if (pVictim->GetTypeId() == TYPEID_PLAYER && !pVictim->HasInArc(M_PI,this))
2074 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind and victim was a player.");
2076 else
2078 // Reduce dodge chance by attacker expertise rating
2079 if (GetTypeId() == TYPEID_PLAYER)
2080 dodge_chance -= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2082 // Modify dodge chance by attacker SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2083 dodge_chance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE);
2085 tmp = dodge_chance;
2086 if ( (tmp > 0) // check if unit _can_ dodge
2087 && ((tmp -= skillBonus) > 0)
2088 && roll < (sum += tmp))
2090 DEBUG_LOG ("RollMeleeOutcomeAgainst: DODGE <%d, %d)", sum-tmp, sum);
2091 return MELEE_HIT_DODGE;
2095 // parry & block chances
2097 // check if attack comes from behind, nobody can parry or block if attacker is behind
2098 if (!pVictim->HasInArc(M_PI,this))
2100 DEBUG_LOG ("RollMeleeOutcomeAgainst: attack came from behind.");
2102 else
2104 // Reduce parry chance by attacker expertise rating
2105 if (GetTypeId() == TYPEID_PLAYER)
2106 parry_chance-= int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType)*100);
2108 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_PARRY) )
2110 int32 tmp = int32(parry_chance);
2111 if ( (tmp > 0) // check if unit _can_ parry
2112 && ((tmp -= skillBonus) > 0)
2113 && (roll < (sum += tmp)))
2115 DEBUG_LOG ("RollMeleeOutcomeAgainst: PARRY <%d, %d)", sum-tmp, sum);
2116 return MELEE_HIT_PARRY;
2120 if(pVictim->GetTypeId()==TYPEID_PLAYER || !(((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK) )
2122 tmp = block_chance;
2123 if ( (tmp > 0) // check if unit _can_ block
2124 && ((tmp -= skillBonus) > 0)
2125 && (roll < (sum += tmp)))
2127 DEBUG_LOG ("RollMeleeOutcomeAgainst: BLOCK <%d, %d)", sum-tmp, sum);
2128 return MELEE_HIT_BLOCK;
2133 // Critical chance
2134 tmp = crit_chance;
2136 if (tmp > 0 && roll < (sum += tmp))
2138 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRIT <%d, %d)", sum-tmp, sum);
2139 return MELEE_HIT_CRIT;
2142 // 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)
2143 if( attType != RANGED_ATTACK &&
2144 (GetTypeId() == TYPEID_PLAYER || ((Creature*)this)->isPet()) &&
2145 pVictim->GetTypeId() != TYPEID_PLAYER && !((Creature*)pVictim)->isPet() &&
2146 getLevel() < pVictim->getLevelForTarget(this) )
2148 // cap possible value (with bonuses > max skill)
2149 int32 skill = attackerWeaponSkill;
2150 int32 maxskill = attackerMaxSkillValueForLevel;
2151 skill = (skill > maxskill) ? maxskill : skill;
2153 tmp = (10 + (victimDefenseSkill - skill)) * 100;
2154 tmp = tmp > 4000 ? 4000 : tmp;
2155 if (roll < (sum += tmp))
2157 DEBUG_LOG ("RollMeleeOutcomeAgainst: GLANCING <%d, %d)", sum-4000, sum);
2158 return MELEE_HIT_GLANCING;
2162 // mobs can score crushing blows if they're 4 or more levels above victim
2163 if (getLevelForTarget(pVictim) >= pVictim->getLevelForTarget(this) + 4 &&
2164 // can be from by creature (if can) or from controlled player that considered as creature
2165 (GetTypeId()!=TYPEID_PLAYER && !((Creature*)this)->isPet() &&
2166 !(((Creature*)this)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_CRUSH) ||
2167 GetTypeId()==TYPEID_PLAYER && GetCharmerOrOwnerGUID()))
2169 // when their weapon skill is 15 or more above victim's defense skill
2170 tmp = victimDefenseSkill;
2171 int32 tmpmax = victimMaxSkillValueForLevel;
2172 // having defense above your maximum (from items, talents etc.) has no effect
2173 tmp = tmp > tmpmax ? tmpmax : tmp;
2174 // tmp = mob's level * 5 - player's current defense skill
2175 tmp = attackerMaxSkillValueForLevel - tmp;
2176 if(tmp >= 15)
2178 // add 2% chance per lacking skill point, min. is 15%
2179 tmp = tmp * 200 - 1500;
2180 if (roll < (sum += tmp))
2182 DEBUG_LOG ("RollMeleeOutcomeAgainst: CRUSHING <%d, %d)", sum-tmp, sum);
2183 return MELEE_HIT_CRUSHING;
2188 DEBUG_LOG ("RollMeleeOutcomeAgainst: NORMAL");
2189 return MELEE_HIT_NORMAL;
2192 uint32 Unit::CalculateDamage (WeaponAttackType attType, bool normalized)
2194 float min_damage, max_damage;
2196 if (normalized && GetTypeId()==TYPEID_PLAYER)
2197 ((Player*)this)->CalculateMinMaxDamage(attType,normalized,min_damage, max_damage);
2198 else
2200 switch (attType)
2202 case RANGED_ATTACK:
2203 min_damage = GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE);
2204 max_damage = GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE);
2205 break;
2206 case BASE_ATTACK:
2207 min_damage = GetFloatValue(UNIT_FIELD_MINDAMAGE);
2208 max_damage = GetFloatValue(UNIT_FIELD_MAXDAMAGE);
2209 break;
2210 case OFF_ATTACK:
2211 min_damage = GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE);
2212 max_damage = GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE);
2213 break;
2214 // Just for good manner
2215 default:
2216 min_damage = 0.0f;
2217 max_damage = 0.0f;
2218 break;
2222 if (min_damage > max_damage)
2224 std::swap(min_damage,max_damage);
2227 if(max_damage == 0.0f)
2228 max_damage = 5.0f;
2230 return urand((uint32)min_damage, (uint32)max_damage);
2233 float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const
2235 if(spellProto->spellLevel <= 0)
2236 return 1.0f;
2238 float LvlPenalty = 0.0f;
2240 if(spellProto->spellLevel < 20)
2241 LvlPenalty = 20.0f - spellProto->spellLevel * 3.75f;
2242 float LvlFactor = (float(spellProto->spellLevel) + 6.0f) / float(getLevel());
2243 if(LvlFactor > 1.0f)
2244 LvlFactor = 1.0f;
2246 return (100.0f - LvlPenalty) * LvlFactor / 100.0f;
2249 void Unit::SendAttackStart(Unit* pVictim)
2251 WorldPacket data( SMSG_ATTACKSTART, 16 );
2252 data << uint64(GetGUID());
2253 data << uint64(pVictim->GetGUID());
2255 SendMessageToSet(&data, true);
2256 DEBUG_LOG( "WORLD: Sent SMSG_ATTACKSTART" );
2259 void Unit::SendAttackStop(Unit* victim)
2261 if(!victim)
2262 return;
2264 WorldPacket data( SMSG_ATTACKSTOP, (4+16) ); // we guess size
2265 data.append(GetPackGUID());
2266 data.append(victim->GetPackGUID()); // can be 0x00...
2267 data << uint32(0); // can be 0x1
2268 SendMessageToSet(&data, true);
2269 sLog.outDetail("%s %u stopped attacking %s %u", (GetTypeId()==TYPEID_PLAYER ? "player" : "creature"), GetGUIDLow(), (victim->GetTypeId()==TYPEID_PLAYER ? "player" : "creature"),victim->GetGUIDLow());
2271 /*if(victim->GetTypeId() == TYPEID_UNIT)
2272 ((Creature*)victim)->AI().EnterEvadeMode(this);*/
2275 bool Unit::isSpellBlocked(Unit *pVictim, SpellEntry const *spellProto, WeaponAttackType attackType)
2277 if (pVictim->HasInArc(M_PI,this))
2279 /* Currently not exist spells with ignore block
2280 // Ignore combat result aura (parry/dodge check on prepare)
2281 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2282 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2284 if (!(*i)->isAffectedOnSpell(spellProto))
2285 continue;
2286 if ((*i)->GetModifier()->m_miscvalue == )
2287 return false;
2291 // Check creatures flags_extra for disable block
2292 if(pVictim->GetTypeId()==TYPEID_UNIT &&
2293 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_BLOCK )
2294 return false;
2296 float blockChance = pVictim->GetUnitBlockChance();
2297 blockChance += (int32(GetWeaponSkillValue(attackType)) - int32(pVictim->GetMaxSkillValueForLevel()))*0.04f;
2298 if (roll_chance_f(blockChance))
2299 return true;
2301 return false;
2304 // Melee based spells can be miss, parry or dodge on this step
2305 // Crit or block - determined on damage calculation phase! (and can be both in some time)
2306 float Unit::MeleeSpellMissChance(Unit *pVictim, WeaponAttackType attType, int32 skillDiff, SpellEntry const *spell)
2308 // Calculate hit chance (more correct for chance mod)
2309 int32 HitChance;
2311 // PvP - PvE melee chances
2312 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2313 int32 leveldif = pVictim->getLevelForTarget(this) - getLevelForTarget(pVictim);
2314 if(leveldif < 3)
2315 HitChance = 95 - leveldif;
2316 else
2317 HitChance = 93 - (leveldif - 2) * lchance;
2319 // Hit chance depends from victim auras
2320 if(attType == RANGED_ATTACK)
2321 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2322 else
2323 HitChance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2325 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2326 if(Player *modOwner = GetSpellModOwner())
2327 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, HitChance);
2329 // Miss = 100 - hit
2330 float miss_chance= 100.0f - HitChance;
2332 // Bonuses from attacker aura and ratings
2333 if (attType == RANGED_ATTACK)
2334 miss_chance -= m_modRangedHitChance;
2335 else
2336 miss_chance -= m_modMeleeHitChance;
2338 // bonus from skills is 0.04%
2339 miss_chance -= skillDiff * 0.04f;
2341 // Limit miss chance from 0 to 60%
2342 if (miss_chance < 0.0f)
2343 return 0.0f;
2344 if (miss_chance > 60.0f)
2345 return 60.0f;
2346 return miss_chance;
2349 // Melee based spells hit result calculations
2350 SpellMissInfo Unit::MeleeSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2352 WeaponAttackType attType = BASE_ATTACK;
2354 if (spell->DmgClass == SPELL_DAMAGE_CLASS_RANGED)
2355 attType = RANGED_ATTACK;
2357 // bonus from skills is 0.04% per skill Diff
2358 int32 attackerWeaponSkill = int32(GetWeaponSkillValue(attType,pVictim));
2359 int32 skillDiff = attackerWeaponSkill - int32(pVictim->GetMaxSkillValueForLevel(this));
2360 int32 fullSkillDiff = attackerWeaponSkill - int32(pVictim->GetDefenseSkillValue(this));
2362 uint32 roll = urand (0, 10000);
2364 uint32 missChance = uint32(MeleeSpellMissChance(pVictim, attType, fullSkillDiff, spell)*100.0f);
2365 // Roll miss
2366 uint32 tmp = missChance;
2367 if (roll < tmp)
2368 return SPELL_MISS_MISS;
2370 // Chance resist mechanic (select max value from every mechanic spell effect)
2371 int32 resist_mech = 0;
2372 // Get effects mechanic and chance
2373 for(int eff = 0; eff < 3; ++eff)
2375 int32 effect_mech = GetEffectMechanic(spell, eff);
2376 if (effect_mech)
2378 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2379 if (resist_mech < temp*100)
2380 resist_mech = temp*100;
2383 // Roll chance
2384 tmp += resist_mech;
2385 if (roll < tmp)
2386 return SPELL_MISS_RESIST;
2388 bool canDodge = true;
2389 bool canParry = true;
2391 // Same spells cannot be parry/dodge
2392 if (spell->Attributes & SPELL_ATTR_IMPOSSIBLE_DODGE_PARRY_BLOCK)
2393 return SPELL_MISS_NONE;
2395 // Ranged attack cannot be parry/dodge only deflect
2396 if (attType == RANGED_ATTACK)
2398 // only if in front
2399 if (pVictim->HasInArc(M_PI,this))
2401 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2402 tmp+=deflect_chance;
2403 if (roll < tmp)
2404 return SPELL_MISS_DEFLECT;
2406 return SPELL_MISS_NONE;
2409 // Check for attack from behind
2410 if (!pVictim->HasInArc(M_PI,this))
2412 // Can`t dodge from behind in PvP (but its possible in PvE)
2413 if (GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_PLAYER)
2414 canDodge = false;
2415 // Can`t parry
2416 canParry = false;
2418 // Check creatures flags_extra for disable parry
2419 if(pVictim->GetTypeId()==TYPEID_UNIT)
2421 uint32 flagEx = ((Creature*)pVictim)->GetCreatureInfo()->flags_extra;
2422 if( flagEx & CREATURE_FLAG_EXTRA_NO_PARRY )
2423 canParry = false;
2425 // Ignore combat result aura
2426 AuraList const& ignore = GetAurasByType(SPELL_AURA_IGNORE_COMBAT_RESULT);
2427 for(AuraList::const_iterator i = ignore.begin(); i != ignore.end(); ++i)
2429 if (!(*i)->isAffectedOnSpell(spell))
2430 continue;
2431 switch((*i)->GetModifier()->m_miscvalue)
2433 case MELEE_HIT_DODGE: canDodge = false; break;
2434 case MELEE_HIT_BLOCK: break; // Block check in hit step
2435 case MELEE_HIT_PARRY: canParry = false; break;
2436 default:
2437 DEBUG_LOG("Spell %u SPELL_AURA_IGNORE_COMBAT_RESULT have unhandled state %d", (*i)->GetId(), (*i)->GetModifier()->m_miscvalue);
2438 break;
2442 if (canDodge)
2444 // Roll dodge
2445 int32 dodgeChance = int32(pVictim->GetUnitDodgeChance()*100.0f) - skillDiff * 4;
2446 // Reduce enemy dodge chance by SPELL_AURA_MOD_COMBAT_RESULT_CHANCE
2447 dodgeChance+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_COMBAT_RESULT_CHANCE, VICTIMSTATE_DODGE)*100;
2448 // Reduce dodge chance by attacker expertise rating
2449 if (GetTypeId() == TYPEID_PLAYER)
2450 dodgeChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2451 if (dodgeChance < 0)
2452 dodgeChance = 0;
2454 tmp += dodgeChance;
2455 if (roll < tmp)
2456 return SPELL_MISS_DODGE;
2459 if (canParry)
2461 // Roll parry
2462 int32 parryChance = int32(pVictim->GetUnitParryChance()*100.0f) - skillDiff * 4;
2463 // Reduce parry chance by attacker expertise rating
2464 if (GetTypeId() == TYPEID_PLAYER)
2465 parryChance-=int32(((Player*)this)->GetExpertiseDodgeOrParryReduction(attType) * 100.0f);
2466 if (parryChance < 0)
2467 parryChance = 0;
2469 tmp += parryChance;
2470 if (roll < tmp)
2471 return SPELL_MISS_PARRY;
2474 return SPELL_MISS_NONE;
2477 // TODO need use unit spell resistances in calculations
2478 SpellMissInfo Unit::MagicSpellHitResult(Unit *pVictim, SpellEntry const *spell)
2480 // Can`t miss on dead target (on skinning for example)
2481 if (!pVictim->isAlive())
2482 return SPELL_MISS_NONE;
2484 SpellSchoolMask schoolMask = GetSpellSchoolMask(spell);
2485 // PvP - PvE spell misschances per leveldif > 2
2486 int32 lchance = pVictim->GetTypeId() == TYPEID_PLAYER ? 7 : 11;
2487 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2489 // Base hit chance from attacker and victim levels
2490 int32 modHitChance;
2491 if(leveldif < 3)
2492 modHitChance = 96 - leveldif;
2493 else
2494 modHitChance = 94 - (leveldif - 2) * lchance;
2496 // Spellmod from SPELLMOD_RESIST_MISS_CHANCE
2497 if(Player *modOwner = GetSpellModOwner())
2498 modOwner->ApplySpellMod(spell->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance);
2499 // Increase from attacker SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT auras
2500 modHitChance+=GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT, schoolMask);
2501 // Chance hit from victim SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE auras
2502 modHitChance+= pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE, schoolMask);
2503 // Reduce spell hit chance for Area of effect spells from victim SPELL_AURA_MOD_AOE_AVOIDANCE aura
2504 if (IsAreaOfEffectSpell(spell))
2505 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_AOE_AVOIDANCE);
2506 // Reduce spell hit chance for dispel mechanic spells from victim SPELL_AURA_MOD_DISPEL_RESIST
2507 if (IsDispelSpell(spell))
2508 modHitChance-=pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_DISPEL_RESIST);
2509 // Chance resist mechanic (select max value from every mechanic spell effect)
2510 int32 resist_mech = 0;
2511 // Get effects mechanic and chance
2512 for(int eff = 0; eff < 3; ++eff)
2514 int32 effect_mech = GetEffectMechanic(spell, eff);
2515 if (effect_mech)
2517 int32 temp = pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MECHANIC_RESISTANCE, effect_mech);
2518 if (resist_mech < temp)
2519 resist_mech = temp;
2522 // Apply mod
2523 modHitChance-=resist_mech;
2525 // Chance resist debuff
2526 modHitChance-=pVictim->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DEBUFF_RESISTANCE, int32(spell->Dispel));
2528 int32 HitChance = modHitChance * 100;
2529 // Increase hit chance from attacker SPELL_AURA_MOD_SPELL_HIT_CHANCE and attacker ratings
2530 HitChance += int32(m_modSpellHitChance*100.0f);
2532 // Decrease hit chance from victim rating bonus
2533 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2534 HitChance -= int32(((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_SPELL)*100.0f);
2536 if (HitChance < 100) HitChance = 100;
2537 if (HitChance > 10000) HitChance = 10000;
2539 int32 tmp = 10000 - HitChance;
2541 uint32 rand = urand(0,10000);
2543 if (rand < tmp)
2544 return SPELL_MISS_RESIST;
2546 // cast by caster in front of victim
2547 if (pVictim->HasInArc(M_PI,this))
2549 int32 deflect_chance = pVictim->GetTotalAuraModifier(SPELL_AURA_DEFLECT_SPELLS)*100;
2550 tmp+=deflect_chance;
2551 if (rand < tmp)
2552 return SPELL_MISS_DEFLECT;
2555 return SPELL_MISS_NONE;
2558 // Calculate spell hit result can be:
2559 // Every spell can: Evade/Immune/Reflect/Sucesful hit
2560 // For melee based spells:
2561 // Miss
2562 // Dodge
2563 // Parry
2564 // For spells
2565 // Resist
2566 SpellMissInfo Unit::SpellHitResult(Unit *pVictim, SpellEntry const *spell, bool CanReflect)
2568 // Return evade for units in evade mode
2569 if (pVictim->GetTypeId()==TYPEID_UNIT && ((Creature*)pVictim)->IsInEvadeMode())
2570 return SPELL_MISS_EVADE;
2572 // Check for immune
2573 if (pVictim->IsImmunedToSpell(spell))
2574 return SPELL_MISS_IMMUNE;
2576 // All positive spells can`t miss
2577 // TODO: client not show miss log for this spells - so need find info for this in dbc and use it!
2578 if (IsPositiveSpell(spell->Id))
2579 return SPELL_MISS_NONE;
2581 // Check for immune
2582 if (pVictim->IsImmunedToDamage(GetSpellSchoolMask(spell)))
2583 return SPELL_MISS_IMMUNE;
2585 // Try victim reflect spell
2586 if (CanReflect)
2588 int32 reflectchance = pVictim->GetTotalAuraModifier(SPELL_AURA_REFLECT_SPELLS);
2589 Unit::AuraList const& mReflectSpellsSchool = pVictim->GetAurasByType(SPELL_AURA_REFLECT_SPELLS_SCHOOL);
2590 for(Unit::AuraList::const_iterator i = mReflectSpellsSchool.begin(); i != mReflectSpellsSchool.end(); ++i)
2591 if((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spell))
2592 reflectchance += (*i)->GetModifier()->m_amount;
2593 if (reflectchance > 0 && roll_chance_i(reflectchance))
2595 // Start triggers for remove charges if need (trigger only for victim, and mark as active spell)
2596 ProcDamageAndSpell(pVictim, PROC_FLAG_NONE, PROC_FLAG_TAKEN_NEGATIVE_SPELL_HIT, PROC_EX_REFLECT, 1, BASE_ATTACK, spell);
2597 return SPELL_MISS_REFLECT;
2601 switch (spell->DmgClass)
2603 case SPELL_DAMAGE_CLASS_RANGED:
2604 case SPELL_DAMAGE_CLASS_MELEE:
2605 return MeleeSpellHitResult(pVictim, spell);
2606 case SPELL_DAMAGE_CLASS_NONE:
2607 case SPELL_DAMAGE_CLASS_MAGIC:
2608 return MagicSpellHitResult(pVictim, spell);
2610 return SPELL_MISS_NONE;
2613 float Unit::MeleeMissChanceCalc(const Unit *pVictim, WeaponAttackType attType) const
2615 if(!pVictim)
2616 return 0.0f;
2618 // Base misschance 5%
2619 float misschance = 5.0f;
2621 // DualWield - Melee spells and physical dmg spells - 5% , white damage 24%
2622 if (haveOffhandWeapon() && attType != RANGED_ATTACK)
2624 bool isNormal = false;
2625 for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; i++)
2627 if( m_currentSpells[i] && (GetSpellSchoolMask(m_currentSpells[i]->m_spellInfo) & SPELL_SCHOOL_MASK_NORMAL) )
2629 isNormal = true;
2630 break;
2633 if (isNormal || m_currentSpells[CURRENT_MELEE_SPELL])
2635 misschance = 5.0f;
2637 else
2639 misschance = 24.0f;
2643 // PvP : PvE melee misschances per leveldif > 2
2644 int32 chance = pVictim->GetTypeId() == TYPEID_PLAYER ? 5 : 7;
2646 int32 leveldif = int32(pVictim->getLevelForTarget(this)) - int32(getLevelForTarget(pVictim));
2647 if(leveldif < 0)
2648 leveldif = 0;
2650 // Hit chance from attacker based on ratings and auras
2651 float m_modHitChance;
2652 if (attType == RANGED_ATTACK)
2653 m_modHitChance = m_modRangedHitChance;
2654 else
2655 m_modHitChance = m_modMeleeHitChance;
2657 if(leveldif < 3)
2658 misschance += (leveldif - m_modHitChance);
2659 else
2660 misschance += ((leveldif - 2) * chance - m_modHitChance);
2662 // Hit chance for victim based on ratings
2663 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2665 if (attType == RANGED_ATTACK)
2666 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_RANGED);
2667 else
2668 misschance += ((Player*)pVictim)->GetRatingBonusValue(CR_HIT_TAKEN_MELEE);
2671 // Modify miss chance by victim auras
2672 if(attType == RANGED_ATTACK)
2673 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE);
2674 else
2675 misschance -= pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE);
2677 // Modify miss chance from skill difference ( bonus from skills is 0.04% )
2678 int32 skillBonus = int32(GetWeaponSkillValue(attType,pVictim)) - int32(pVictim->GetDefenseSkillValue(this));
2679 misschance -= skillBonus * 0.04f;
2681 // Limit miss chance from 0 to 60%
2682 if ( misschance < 0.0f)
2683 return 0.0f;
2684 if ( misschance > 60.0f)
2685 return 60.0f;
2687 return misschance;
2690 uint32 Unit::GetDefenseSkillValue(Unit const* target) const
2692 if(GetTypeId() == TYPEID_PLAYER)
2694 // in PvP use full skill instead current skill value
2695 uint32 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2696 ? ((Player*)this)->GetMaxSkillValue(SKILL_DEFENSE)
2697 : ((Player*)this)->GetSkillValue(SKILL_DEFENSE);
2698 value += uint32(((Player*)this)->GetRatingBonusValue(CR_DEFENSE_SKILL));
2699 return value;
2701 else
2702 return GetUnitMeleeSkill(target);
2705 float Unit::GetUnitDodgeChance() const
2707 if(hasUnitState(UNIT_STAT_STUNNED))
2708 return 0.0f;
2709 if( GetTypeId() == TYPEID_PLAYER )
2710 return GetFloatValue(PLAYER_DODGE_PERCENTAGE);
2711 else
2713 if(((Creature const*)this)->isTotem())
2714 return 0.0f;
2715 else
2717 float dodge = 5.0f;
2718 dodge += GetTotalAuraModifier(SPELL_AURA_MOD_DODGE_PERCENT);
2719 return dodge > 0.0f ? dodge : 0.0f;
2724 float Unit::GetUnitParryChance() const
2726 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2727 return 0.0f;
2729 float chance = 0.0f;
2731 if(GetTypeId() == TYPEID_PLAYER)
2733 Player const* player = (Player const*)this;
2734 if(player->CanParry() )
2736 Item *tmpitem = player->GetWeaponForAttack(BASE_ATTACK,true);
2737 if(!tmpitem)
2738 tmpitem = player->GetWeaponForAttack(OFF_ATTACK,true);
2740 if(tmpitem)
2741 chance = GetFloatValue(PLAYER_PARRY_PERCENTAGE);
2744 else if(GetTypeId() == TYPEID_UNIT)
2746 if(GetCreatureType() == CREATURE_TYPE_HUMANOID)
2748 chance = 5.0f;
2749 chance += GetTotalAuraModifier(SPELL_AURA_MOD_PARRY_PERCENT);
2753 return chance > 0.0f ? chance : 0.0f;
2756 float Unit::GetUnitBlockChance() const
2758 if ( IsNonMeleeSpellCasted(false) || hasUnitState(UNIT_STAT_STUNNED))
2759 return 0.0f;
2761 if(GetTypeId() == TYPEID_PLAYER)
2763 Player const* player = (Player const*)this;
2764 if(player->CanBlock() )
2766 Item *tmpitem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
2767 if(tmpitem && !tmpitem->IsBroken() && tmpitem->GetProto()->Block)
2768 return GetFloatValue(PLAYER_BLOCK_PERCENTAGE);
2770 // is player but has no block ability or no not broken shield equipped
2771 return 0.0f;
2773 else
2775 if(((Creature const*)this)->isTotem())
2776 return 0.0f;
2777 else
2779 float block = 5.0f;
2780 block += GetTotalAuraModifier(SPELL_AURA_MOD_BLOCK_PERCENT);
2781 return block > 0.0f ? block : 0.0f;
2786 float Unit::GetUnitCriticalChance(WeaponAttackType attackType, const Unit *pVictim) const
2788 float crit;
2790 if(GetTypeId() == TYPEID_PLAYER)
2792 switch(attackType)
2794 case BASE_ATTACK:
2795 crit = GetFloatValue( PLAYER_CRIT_PERCENTAGE );
2796 break;
2797 case OFF_ATTACK:
2798 crit = GetFloatValue( PLAYER_OFFHAND_CRIT_PERCENTAGE );
2799 break;
2800 case RANGED_ATTACK:
2801 crit = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE );
2802 break;
2803 // Just for good manner
2804 default:
2805 crit = 0.0f;
2806 break;
2809 else
2811 crit = 5.0f;
2812 crit += GetTotalAuraModifier(SPELL_AURA_MOD_CRIT_PERCENT);
2815 // flat aura mods
2816 if(attackType == RANGED_ATTACK)
2817 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE);
2818 else
2819 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE);
2821 crit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
2823 // reduce crit chance from Rating for players
2824 if (pVictim->GetTypeId()==TYPEID_PLAYER)
2826 if (attackType==RANGED_ATTACK)
2827 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_RANGED);
2828 else
2829 crit -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE);
2832 // Apply crit chance from defence skill
2833 crit += (int32(GetMaxSkillValueForLevel(pVictim)) - int32(pVictim->GetDefenseSkillValue(this))) * 0.04f;
2835 if (crit < 0.0f)
2836 crit = 0.0f;
2837 return crit;
2840 uint32 Unit::GetWeaponSkillValue (WeaponAttackType attType, Unit const* target) const
2842 uint32 value = 0;
2843 if(GetTypeId() == TYPEID_PLAYER)
2845 Item* item = ((Player*)this)->GetWeaponForAttack(attType,true);
2847 // feral or unarmed skill only for base attack
2848 if(attType != BASE_ATTACK && !item )
2849 return 0;
2851 if(IsInFeralForm())
2852 return GetMaxSkillValueForLevel(); // always maximized SKILL_FERAL_COMBAT in fact
2854 // weapon skill or (unarmed for base attack)
2855 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
2857 // in PvP use full skill instead current skill value
2858 value = (target && target->GetTypeId() == TYPEID_PLAYER)
2859 ? ((Player*)this)->GetMaxSkillValue(skill)
2860 : ((Player*)this)->GetSkillValue(skill);
2861 // Modify value from ratings
2862 value += uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL));
2863 switch (attType)
2865 case BASE_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_MAINHAND));break;
2866 case OFF_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_OFFHAND));break;
2867 case RANGED_ATTACK: value+=uint32(((Player*)this)->GetRatingBonusValue(CR_WEAPON_SKILL_RANGED));break;
2870 else
2871 value = GetUnitMeleeSkill(target);
2872 return value;
2875 void Unit::_UpdateSpells( uint32 time )
2877 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL])
2878 _UpdateAutoRepeatSpell();
2880 // remove finished spells from current pointers
2881 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
2883 if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED)
2885 m_currentSpells[i]->SetReferencedFromCurrent(false);
2886 m_currentSpells[i] = NULL; // remove pointer
2890 // TODO: Find a better way to prevent crash when multiple auras are removed.
2891 m_removedAuras = 0;
2892 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
2893 if ((*i).second)
2894 (*i).second->SetUpdated(false);
2896 for (AuraMap::iterator i = m_Auras.begin(), next; i != m_Auras.end(); i = next)
2898 next = i;
2899 ++next;
2900 if ((*i).second)
2902 // prevent double update
2903 if ((*i).second->IsUpdated())
2904 continue;
2905 (*i).second->SetUpdated(true);
2906 (*i).second->Update( time );
2907 // several auras can be deleted due to update
2908 if (m_removedAuras)
2910 if (m_Auras.empty()) break;
2911 next = m_Auras.begin();
2912 m_removedAuras = 0;
2917 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end();)
2919 if ((*i).second)
2921 if ( !(*i).second->GetAuraDuration() && !((*i).second->IsPermanent() || ((*i).second->IsPassive())) )
2923 RemoveAura(i);
2925 else
2927 ++i;
2930 else
2932 ++i;
2936 if(!m_gameObj.empty())
2938 GameObjectList::iterator ite1, dnext1;
2939 for (ite1 = m_gameObj.begin(); ite1 != m_gameObj.end(); ite1 = dnext1)
2941 dnext1 = ite1;
2942 //(*i)->Update( difftime );
2943 if( !(*ite1)->isSpawned() )
2945 (*ite1)->SetOwnerGUID(0);
2946 (*ite1)->SetRespawnTime(0);
2947 (*ite1)->Delete();
2948 dnext1 = m_gameObj.erase(ite1);
2950 else
2951 ++dnext1;
2956 void Unit::_UpdateAutoRepeatSpell()
2958 //check "realtime" interrupts
2959 if ( (GetTypeId() == TYPEID_PLAYER && ((Player*)this)->isMoving()) || IsNonMeleeSpellCasted(false,false,true) )
2961 // cancel wand shoot
2962 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
2963 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2964 m_AutoRepeatFirstCast = true;
2965 return;
2968 //apply delay
2969 if ( m_AutoRepeatFirstCast && getAttackTimer(RANGED_ATTACK) < 500 )
2970 setAttackTimer(RANGED_ATTACK,500);
2971 m_AutoRepeatFirstCast = false;
2973 //castroutine
2974 if (isAttackReady(RANGED_ATTACK))
2976 // Check if able to cast
2977 if(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->CheckCast(true) != SPELL_CAST_OK)
2979 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
2980 return;
2983 // we want to shoot
2984 Spell* spell = new Spell(this, m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo, true, 0);
2985 spell->prepare(&(m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_targets));
2987 // all went good, reset attack
2988 resetAttackTimer(RANGED_ATTACK);
2992 void Unit::SetCurrentCastedSpell( Spell * pSpell )
2994 assert(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells
2996 uint32 CSpellType = pSpell->GetCurrentContainer();
2998 if (pSpell == m_currentSpells[CSpellType]) return; // avoid breaking self
3000 // break same type spell if it is not delayed
3001 InterruptSpell(CSpellType,false);
3003 // special breakage effects:
3004 switch (CSpellType)
3006 case CURRENT_GENERIC_SPELL:
3008 // generic spells always break channeled not delayed spells
3009 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3011 // autorepeat breaking
3012 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3014 // break autorepeat if not Auto Shot
3015 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3016 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3017 m_AutoRepeatFirstCast = true;
3019 } break;
3021 case CURRENT_CHANNELED_SPELL:
3023 // channel spells always break generic non-delayed and any channeled spells
3024 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3025 InterruptSpell(CURRENT_CHANNELED_SPELL);
3027 // it also does break autorepeat if not Auto Shot
3028 if ( m_currentSpells[CURRENT_AUTOREPEAT_SPELL] &&
3029 m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id != SPELL_ID_AUTOSHOT )
3030 InterruptSpell(CURRENT_AUTOREPEAT_SPELL);
3031 } break;
3033 case CURRENT_AUTOREPEAT_SPELL:
3035 // only Auto Shoot does not break anything
3036 if (pSpell->m_spellInfo->Id != SPELL_ID_AUTOSHOT)
3038 // generic autorepeats break generic non-delayed and channeled non-delayed spells
3039 InterruptSpell(CURRENT_GENERIC_SPELL,false);
3040 InterruptSpell(CURRENT_CHANNELED_SPELL,false);
3042 // special action: set first cast flag
3043 m_AutoRepeatFirstCast = true;
3044 } break;
3046 default:
3048 // other spell types don't break anything now
3049 } break;
3052 // current spell (if it is still here) may be safely deleted now
3053 if (m_currentSpells[CSpellType])
3054 m_currentSpells[CSpellType]->SetReferencedFromCurrent(false);
3056 // set new current spell
3057 m_currentSpells[CSpellType] = pSpell;
3058 pSpell->SetReferencedFromCurrent(true);
3061 void Unit::InterruptSpell(uint32 spellType, bool withDelayed)
3063 assert(spellType < CURRENT_MAX_SPELL);
3065 if (m_currentSpells[spellType] && (withDelayed || m_currentSpells[spellType]->getState() != SPELL_STATE_DELAYED) )
3067 // send autorepeat cancel message for autorepeat spells
3068 if (spellType == CURRENT_AUTOREPEAT_SPELL)
3070 if(GetTypeId()==TYPEID_PLAYER)
3071 ((Player*)this)->SendAutoRepeatCancel();
3074 if (m_currentSpells[spellType]->getState() != SPELL_STATE_FINISHED)
3075 m_currentSpells[spellType]->cancel();
3077 // cancel can interrupt spell already (caster cancel ->target aura remove -> caster iterrupt)
3078 if (m_currentSpells[spellType])
3080 m_currentSpells[spellType]->SetReferencedFromCurrent(false);
3081 m_currentSpells[spellType] = NULL;
3086 bool Unit::IsNonMeleeSpellCasted(bool withDelayed, bool skipChanneled, bool skipAutorepeat) const
3088 // We don't do loop here to explicitly show that melee spell is excluded.
3089 // Maybe later some special spells will be excluded too.
3091 // generic spells are casted when they are not finished and not delayed
3092 if ( m_currentSpells[CURRENT_GENERIC_SPELL] &&
3093 (m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_FINISHED) &&
3094 (withDelayed || m_currentSpells[CURRENT_GENERIC_SPELL]->getState() != SPELL_STATE_DELAYED) )
3095 return(true);
3097 // channeled spells may be delayed, but they are still considered casted
3098 else if ( !skipChanneled && m_currentSpells[CURRENT_CHANNELED_SPELL] &&
3099 (m_currentSpells[CURRENT_CHANNELED_SPELL]->getState() != SPELL_STATE_FINISHED) )
3100 return(true);
3102 // autorepeat spells may be finished or delayed, but they are still considered casted
3103 else if ( !skipAutorepeat && m_currentSpells[CURRENT_AUTOREPEAT_SPELL] )
3104 return(true);
3106 return(false);
3109 void Unit::InterruptNonMeleeSpells(bool withDelayed, uint32 spell_id)
3111 // generic spells are interrupted if they are not finished or delayed
3112 if (m_currentSpells[CURRENT_GENERIC_SPELL] && (!spell_id || m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Id==spell_id))
3113 InterruptSpell(CURRENT_GENERIC_SPELL,withDelayed);
3115 // autorepeat spells are interrupted if they are not finished or delayed
3116 if (m_currentSpells[CURRENT_AUTOREPEAT_SPELL] && (!spell_id || m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo->Id==spell_id))
3117 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,withDelayed);
3119 // channeled spells are interrupted if they are not finished, even if they are delayed
3120 if (m_currentSpells[CURRENT_CHANNELED_SPELL] && (!spell_id || m_currentSpells[CURRENT_CHANNELED_SPELL]->m_spellInfo->Id==spell_id))
3121 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
3124 Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const
3126 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
3127 if(m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id==spell_id)
3128 return m_currentSpells[i];
3129 return NULL;
3132 bool Unit::isInFront(Unit const* target, float distance, float arc) const
3134 return IsWithinDistInMap(target, distance) && HasInArc( arc, target );
3137 void Unit::SetInFront(Unit const* target)
3139 SetOrientation(GetAngle(target));
3142 bool Unit::isInBack(Unit const* target, float distance, float arc) const
3144 return IsWithinDistInMap(target, distance) && !HasInArc( 2 * M_PI - arc, target );
3147 bool Unit::isInAccessablePlaceFor(Creature const* c) const
3149 if(IsInWater())
3150 return c->canSwim();
3151 else
3152 return c->canWalk() || c->canFly();
3155 bool Unit::IsInWater() const
3157 return MapManager::Instance().GetBaseMap(GetMapId())->IsInWater(GetPositionX(),GetPositionY(), GetPositionZ());
3160 bool Unit::IsUnderWater() const
3162 return MapManager::Instance().GetBaseMap(GetMapId())->IsUnderWater(GetPositionX(),GetPositionY(),GetPositionZ());
3165 void Unit::DeMorph()
3167 SetDisplayId(GetNativeDisplayId());
3170 int32 Unit::GetTotalAuraModifier(AuraType auratype) const
3172 int32 modifier = 0;
3174 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3175 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3176 modifier += (*i)->GetModifier()->m_amount;
3178 return modifier;
3181 float Unit::GetTotalAuraMultiplier(AuraType auratype) const
3183 float multiplier = 1.0f;
3185 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3186 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3187 multiplier *= (100.0f + (*i)->GetModifier()->m_amount)/100.0f;
3189 return multiplier;
3192 int32 Unit::GetMaxPositiveAuraModifier(AuraType auratype) const
3194 int32 modifier = 0;
3196 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3197 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3198 if ((*i)->GetModifier()->m_amount > modifier)
3199 modifier = (*i)->GetModifier()->m_amount;
3201 return modifier;
3204 int32 Unit::GetMaxNegativeAuraModifier(AuraType auratype) const
3206 int32 modifier = 0;
3208 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3209 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3210 if ((*i)->GetModifier()->m_amount < modifier)
3211 modifier = (*i)->GetModifier()->m_amount;
3213 return modifier;
3216 int32 Unit::GetTotalAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3218 int32 modifier = 0;
3220 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3221 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3223 Modifier* mod = (*i)->GetModifier();
3224 if (mod->m_miscvalue & misc_mask)
3225 modifier += mod->m_amount;
3227 return modifier;
3230 float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask) const
3232 float multiplier = 1.0f;
3234 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3235 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3237 Modifier* mod = (*i)->GetModifier();
3238 if (mod->m_miscvalue & misc_mask)
3239 multiplier *= (100.0f + mod->m_amount)/100.0f;
3241 return multiplier;
3244 int32 Unit::GetMaxPositiveAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3246 int32 modifier = 0;
3248 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3249 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3251 Modifier* mod = (*i)->GetModifier();
3252 if (mod->m_miscvalue & misc_mask && mod->m_amount > modifier)
3253 modifier = mod->m_amount;
3256 return modifier;
3259 int32 Unit::GetMaxNegativeAuraModifierByMiscMask(AuraType auratype, uint32 misc_mask) const
3261 int32 modifier = 0;
3263 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3264 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3266 Modifier* mod = (*i)->GetModifier();
3267 if (mod->m_miscvalue & misc_mask && mod->m_amount < modifier)
3268 modifier = mod->m_amount;
3271 return modifier;
3274 int32 Unit::GetTotalAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3276 int32 modifier = 0;
3278 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3279 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3281 Modifier* mod = (*i)->GetModifier();
3282 if (mod->m_miscvalue == misc_value)
3283 modifier += mod->m_amount;
3285 return modifier;
3288 float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_value) const
3290 float multiplier = 1.0f;
3292 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3293 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3295 Modifier* mod = (*i)->GetModifier();
3296 if (mod->m_miscvalue == misc_value)
3297 multiplier *= (100.0f + mod->m_amount)/100.0f;
3299 return multiplier;
3302 int32 Unit::GetMaxPositiveAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3304 int32 modifier = 0;
3306 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3307 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3309 Modifier* mod = (*i)->GetModifier();
3310 if (mod->m_miscvalue == misc_value && mod->m_amount > modifier)
3311 modifier = mod->m_amount;
3314 return modifier;
3317 int32 Unit::GetMaxNegativeAuraModifierByMiscValue(AuraType auratype, int32 misc_value) const
3319 int32 modifier = 0;
3321 AuraList const& mTotalAuraList = GetAurasByType(auratype);
3322 for(AuraList::const_iterator i = mTotalAuraList.begin();i != mTotalAuraList.end(); ++i)
3324 Modifier* mod = (*i)->GetModifier();
3325 if (mod->m_miscvalue == misc_value && mod->m_amount < modifier)
3326 modifier = mod->m_amount;
3329 return modifier;
3332 bool Unit::AddAura(Aura *Aur)
3334 // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load)
3335 if( !isAlive() && Aur->GetId() != 20584 && Aur->GetId() != 8326 && Aur->GetId() != 2584 &&
3336 (GetTypeId()!=TYPEID_PLAYER || !((Player*)this)->GetSession()->PlayerLoading()) )
3338 delete Aur;
3339 return false;
3342 if(Aur->GetTarget() != this)
3344 sLog.outError("Aura (spell %u eff %u) add to aura list of %s (lowguid: %u) but Aura target is %s (lowguid: %u)",
3345 Aur->GetId(),Aur->GetEffIndex(),(GetTypeId()==TYPEID_PLAYER?"player":"creature"),GetGUIDLow(),
3346 (Aur->GetTarget()->GetTypeId()==TYPEID_PLAYER?"player":"creature"),Aur->GetTarget()->GetGUIDLow());
3347 delete Aur;
3348 return false;
3351 SpellEntry const* aurSpellInfo = Aur->GetSpellProto();
3353 spellEffectPair spair = spellEffectPair(Aur->GetId(), Aur->GetEffIndex());
3354 AuraMap::iterator i = m_Auras.find( spair );
3356 // take out same spell
3357 if (i != m_Auras.end())
3359 // passive and persistent auras can stack with themselves any number of times
3360 if (!Aur->IsPassive() && !Aur->IsPersistent())
3362 for(AuraMap::iterator i2 = m_Auras.lower_bound(spair); i2 != m_Auras.upper_bound(spair); ++i2)
3364 if(i2->second->GetCasterGUID()==Aur->GetCasterGUID())
3366 // Aura can stack on self -> Stack it;
3367 if(aurSpellInfo->StackAmount)
3369 i2->second->modStackAmount(1);
3370 delete Aur;
3371 return false;
3373 // can be only single (this check done at _each_ aura add
3374 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3375 break;
3378 bool stop = false;
3379 switch(aurSpellInfo->EffectApplyAuraName[Aur->GetEffIndex()])
3381 // DoT/HoT/etc
3382 case SPELL_AURA_PERIODIC_DAMAGE: // allow stack
3383 case SPELL_AURA_PERIODIC_DAMAGE_PERCENT:
3384 case SPELL_AURA_PERIODIC_LEECH:
3385 case SPELL_AURA_PERIODIC_HEAL:
3386 case SPELL_AURA_OBS_MOD_HEALTH:
3387 case SPELL_AURA_PERIODIC_MANA_LEECH:
3388 case SPELL_AURA_PERIODIC_ENERGIZE:
3389 case SPELL_AURA_OBS_MOD_MANA:
3390 case SPELL_AURA_POWER_BURN_MANA:
3391 break;
3392 default: // not allow
3393 // can be only single (this check done at _each_ aura add
3394 RemoveAura(i2,AURA_REMOVE_BY_STACK);
3395 stop = true;
3396 break;
3399 if(stop)
3400 break;
3405 // passive auras not stacable with other ranks
3406 if (!IsPassiveSpellStackableWithRanks(aurSpellInfo))
3408 if (!RemoveNoStackAurasDueToAura(Aur))
3410 delete Aur;
3411 return false; // couldn't remove conflicting aura with higher rank
3415 // update single target auras list (before aura add to aura list, to prevent unexpected remove recently added aura)
3416 if (Aur->IsSingleTarget() && Aur->GetTarget())
3418 // caster pointer can be deleted in time aura remove, find it by guid at each iteration
3419 for(;;)
3421 Unit* caster = Aur->GetCaster();
3422 if(!caster) // caster deleted and not required adding scAura
3423 break;
3425 bool restart = false;
3426 AuraList& scAuras = caster->GetSingleCastAuras();
3427 for(AuraList::iterator itr = scAuras.begin(); itr != scAuras.end(); ++itr)
3429 if( (*itr)->GetTarget() != Aur->GetTarget() &&
3430 IsSingleTargetSpells((*itr)->GetSpellProto(),aurSpellInfo) )
3432 if ((*itr)->IsInUse())
3434 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());
3435 continue;
3437 (*itr)->GetTarget()->RemoveAura((*itr)->GetId(), (*itr)->GetEffIndex());
3438 restart = true;
3439 break;
3443 if(!restart)
3445 // done
3446 scAuras.push_back(Aur);
3447 break;
3452 // add aura, register in lists and arrays
3453 Aur->_AddAura();
3454 m_Auras.insert(AuraMap::value_type(spellEffectPair(Aur->GetId(), Aur->GetEffIndex()), Aur));
3455 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3457 m_modAuras[Aur->GetModifier()->m_auraname].push_back(Aur);
3460 Aur->ApplyModifier(true,true);
3461 sLog.outDebug("Aura %u now is in use", Aur->GetModifier()->m_auraname);
3462 return true;
3465 void Unit::RemoveRankAurasDueToSpell(uint32 spellId)
3467 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
3468 if(!spellInfo)
3469 return;
3470 AuraMap::iterator i,next;
3471 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3473 next = i;
3474 ++next;
3475 uint32 i_spellId = (*i).second->GetId();
3476 if((*i).second && i_spellId && i_spellId != spellId)
3478 if(spellmgr.IsRankSpellDueToSpell(spellInfo,i_spellId))
3480 RemoveAurasDueToSpell(i_spellId);
3482 if( m_Auras.empty() )
3483 break;
3484 else
3485 next = m_Auras.begin();
3491 bool Unit::RemoveNoStackAurasDueToAura(Aura *Aur)
3493 if (!Aur)
3494 return false;
3496 SpellEntry const* spellProto = Aur->GetSpellProto();
3497 if (!spellProto)
3498 return false;
3500 uint32 spellId = Aur->GetId();
3501 uint32 effIndex = Aur->GetEffIndex();
3503 // passive spell special case (only non stackable with ranks)
3504 if(IsPassiveSpell(spellId))
3506 if(IsPassiveSpellStackableWithRanks(spellProto))
3507 return true;
3510 SpellSpecific spellId_spec = GetSpellSpecific(spellId);
3512 AuraMap::iterator i,next;
3513 for (i = m_Auras.begin(); i != m_Auras.end(); i = next)
3515 next = i;
3516 ++next;
3517 if (!(*i).second) continue;
3519 SpellEntry const* i_spellProto = (*i).second->GetSpellProto();
3521 if (!i_spellProto)
3522 continue;
3524 uint32 i_spellId = i_spellProto->Id;
3526 // early checks that spellId is passive non stackable spell
3527 if(IsPassiveSpell(i_spellId))
3529 // passive non-stackable spells not stackable only for same caster
3530 if(Aur->GetCasterGUID()!=i->second->GetCasterGUID())
3531 continue;
3533 // passive non-stackable spells not stackable only with another rank of same spell
3534 if (!spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3535 continue;
3538 uint32 i_effIndex = (*i).second->GetEffIndex();
3540 if(i_spellId == spellId) continue;
3542 bool is_triggered_by_spell = false;
3543 // prevent triggered aura of removing aura that triggered it
3544 for(int j = 0; j < 3; ++j)
3545 if (i_spellProto->EffectTriggerSpell[j] == spellProto->Id)
3546 is_triggered_by_spell = true;
3548 if (is_triggered_by_spell)
3549 continue;
3551 SpellSpecific i_spellId_spec = GetSpellSpecific(i_spellId);
3553 bool is_sspc = IsSingleFromSpellSpecificPerCaster(spellId_spec,i_spellId_spec);
3554 bool is_sspt = IsSingleFromSpellSpecificRanksPerTarget(spellId_spec,i_spellId_spec);
3556 if( is_sspc && Aur->GetCasterGUID() == (*i).second->GetCasterGUID() )
3558 // cannot remove higher rank
3559 if (spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId))
3560 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3561 return false;
3563 // Its a parent aura (create this aura in ApplyModifier)
3564 if ((*i).second->IsInUse())
3566 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());
3567 continue;
3569 RemoveAurasDueToSpell(i_spellId);
3571 if( m_Auras.empty() )
3572 break;
3573 else
3574 next = m_Auras.begin();
3576 else if( is_sspt && Aur->GetCasterGUID() != (*i).second->GetCasterGUID() && spellmgr.IsRankSpellDueToSpell(spellProto, i_spellId) )
3578 // cannot remove higher rank
3579 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3580 return false;
3582 // Its a parent aura (create this aura in ApplyModifier)
3583 if ((*i).second->IsInUse())
3585 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());
3586 continue;
3588 RemoveAurasDueToSpell(i_spellId);
3590 if( m_Auras.empty() )
3591 break;
3592 else
3593 next = m_Auras.begin();
3595 else if( !is_sspc && spellmgr.IsNoStackSpellDueToSpell(spellId, i_spellId) )
3597 // Its a parent aura (create this aura in ApplyModifier)
3598 if ((*i).second->IsInUse())
3600 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());
3601 continue;
3603 RemoveAurasDueToSpell(i_spellId);
3605 if( m_Auras.empty() )
3606 break;
3607 else
3608 next = m_Auras.begin();
3610 // Potions stack aura by aura (elixirs/flask already checked)
3611 else if( spellProto->SpellFamilyName == SPELLFAMILY_POTION && i_spellProto->SpellFamilyName == SPELLFAMILY_POTION )
3613 if (IsNoStackAuraDueToAura(spellId, effIndex, i_spellId, i_effIndex))
3615 if(CompareAuraRanks(spellId, effIndex, i_spellId, i_effIndex) < 0)
3616 return false; // cannot remove higher rank
3618 // Its a parent aura (create this aura in ApplyModifier)
3619 if ((*i).second->IsInUse())
3621 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());
3622 continue;
3624 RemoveAura(i);
3625 next = i;
3629 return true;
3632 void Unit::RemoveAura(uint32 spellId, uint32 effindex, Aura* except)
3634 spellEffectPair spair = spellEffectPair(spellId, effindex);
3635 for(AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3637 if(iter->second!=except)
3639 RemoveAura(iter);
3640 iter = m_Auras.lower_bound(spair);
3642 else
3643 ++iter;
3647 void Unit::RemoveAurasByCasterSpell(uint32 spellId, uint64 casterGUID)
3649 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3651 Aura *aur = iter->second;
3652 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3653 RemoveAura(iter);
3654 else
3655 ++iter;
3659 void Unit::RemoveAurasDueToSpellByDispel(uint32 spellId, uint64 casterGUID, Unit *dispeler)
3661 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3663 Aura *aur = iter->second;
3664 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3666 // Custom dispel case
3667 // Unstable Affliction
3668 if (aur->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (aur->GetSpellProto()->SpellFamilyFlags & 0x010000000000LL))
3670 int32 damage = aur->GetModifier()->m_amount*9;
3671 uint64 caster_guid = aur->GetCasterGUID();
3673 // Remove aura
3674 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3676 // backfire damage and silence
3677 dispeler->CastCustomSpell(dispeler, 31117, &damage, NULL, NULL, true, NULL, NULL,caster_guid);
3679 iter = m_Auras.begin(); // iterator can be invalidate at cast if self-dispel
3681 else
3682 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3684 else
3685 ++iter;
3689 void Unit::RemoveAurasDueToSpellBySteal(uint32 spellId, uint64 casterGUID, Unit *stealer)
3691 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3693 Aura *aur = iter->second;
3694 if (aur->GetId() == spellId && aur->GetCasterGUID() == casterGUID)
3696 int32 basePoints = aur->GetBasePoints();
3697 // construct the new aura for the attacker - will never return NULL, it's just a wrapper for
3698 // some different constructors
3699 Aura * new_aur = CreateAura(aur->GetSpellProto(), aur->GetEffIndex(), &basePoints, stealer, this);
3701 // set its duration and maximum duration
3702 // max duration 2 minutes (in msecs)
3703 int32 dur = aur->GetAuraDuration();
3704 const int32 max_dur = 2*MINUTE*IN_MILISECONDS;
3705 new_aur->SetAuraMaxDuration( max_dur > dur ? dur : max_dur );
3706 new_aur->SetAuraDuration( max_dur > dur ? dur : max_dur );
3708 // Unregister _before_ adding to stealer
3709 aur->UnregisterSingleCastAura();
3711 // strange but intended behaviour: Stolen single target auras won't be treated as single targeted
3712 new_aur->SetIsSingleTarget(false);
3714 // add the new aura to stealer
3715 stealer->AddAura(new_aur);
3717 // Remove aura as dispel
3718 RemoveAura(iter, AURA_REMOVE_BY_DISPEL);
3720 else
3721 ++iter;
3725 void Unit::RemoveAurasDueToSpellByCancel(uint32 spellId)
3727 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3729 if (iter->second->GetId() == spellId)
3730 RemoveAura(iter, AURA_REMOVE_BY_CANCEL);
3731 else
3732 ++iter;
3736 void Unit::RemoveAurasWithDispelType( DispelType type )
3738 // Create dispel mask by dispel type
3739 uint32 dispelMask = GetDispellMask(type);
3740 // Dispel all existing auras vs current dispel type
3741 AuraMap& auras = GetAuras();
3742 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
3744 SpellEntry const* spell = itr->second->GetSpellProto();
3745 if( (1<<spell->Dispel) & dispelMask )
3747 // Dispel aura
3748 RemoveAurasDueToSpell(spell->Id);
3749 itr = auras.begin();
3751 else
3752 ++itr;
3756 void Unit::RemoveSingleAuraFromStack(uint32 spellId, uint32 effindex)
3758 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3759 if(iter != m_Auras.end())
3761 if (iter->second->modStackAmount(-1))
3762 RemoveAura(iter);
3766 void Unit::RemoveSingleSpellAurasFromStack(uint32 spellId)
3768 for (int i=0; i<3; ++i)
3769 RemoveSingleAuraFromStack(spellId, i);
3772 void Unit::RemoveAurasDueToSpell(uint32 spellId, Aura* except)
3774 for (int i = 0; i < 3; ++i)
3775 RemoveAura(spellId,i,except);
3778 void Unit::RemoveAurasDueToItemSpell(Item* castItem,uint32 spellId)
3780 for (int k=0; k < 3; ++k)
3782 spellEffectPair spair = spellEffectPair(spellId, k);
3783 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair);)
3785 if (iter->second->GetCastItemGUID() == castItem->GetGUID())
3787 RemoveAura(iter);
3788 iter = m_Auras.upper_bound(spair); // overwrite by more appropriate
3790 else
3791 ++iter;
3796 void Unit::RemoveAurasWithInterruptFlags(uint32 flags)
3798 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3800 if (iter->second->GetSpellProto()->AuraInterruptFlags & flags)
3801 RemoveAura(iter);
3802 else
3803 ++iter;
3807 void Unit::RemoveNotOwnSingleTargetAuras()
3809 // single target auras from other casters
3810 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); )
3812 if (iter->second->GetCasterGUID()!=GetGUID() && IsSingleTargetSpell(iter->second->GetSpellProto()))
3813 RemoveAura(iter);
3814 else
3815 ++iter;
3818 // single target auras at other targets
3819 AuraList& scAuras = GetSingleCastAuras();
3820 for (AuraList::iterator iter = scAuras.begin(); iter != scAuras.end(); )
3822 Aura* aura = *iter;
3823 if (aura->GetTarget()!=this)
3825 scAuras.erase(iter); // explicitly remove, instead waiting remove in RemoveAura
3826 aura->GetTarget()->RemoveAura(aura->GetId(),aura->GetEffIndex());
3827 iter = scAuras.begin();
3829 else
3830 ++iter;
3835 void Unit::RemoveAura(AuraMap::iterator &i, AuraRemoveMode mode)
3837 Aura* Aur = i->second;
3838 SpellEntry const* AurSpellInfo = Aur->GetSpellProto();
3840 Aur->UnregisterSingleCastAura();
3842 // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order)
3843 if (Aur->GetModifier()->m_auraname < TOTAL_AURAS)
3845 m_modAuras[Aur->GetModifier()->m_auraname].remove(Aur);
3848 // Set remove mode
3849 Aur->SetRemoveMode(mode);
3850 // some ShapeshiftBoosts at remove trigger removing other auras including parent Shapeshift aura
3851 // remove aura from list before to prevent deleting it before
3852 m_Auras.erase(i);
3853 ++m_removedAuras; // internal count used by unit update
3855 // Statue unsummoned at aura remove
3856 Totem* statue = NULL;
3857 bool caster_channeled = false;
3858 if(IsChanneledSpell(AurSpellInfo))
3860 Unit* caster = Aur->GetCaster();
3862 if(caster)
3864 if(caster->GetTypeId()==TYPEID_UNIT && ((Creature*)caster)->isTotem() && ((Totem*)caster)->GetTotemType()==TOTEM_STATUE)
3865 statue = ((Totem*)caster);
3866 else
3867 caster_channeled = caster==this;
3871 sLog.outDebug("Aura %u now is remove mode %d",Aur->GetModifier()->m_auraname, mode);
3872 Aur->ApplyModifier(false,true);
3873 Aur->_RemoveAura();
3874 delete Aur;
3876 if(caster_channeled)
3877 RemoveAurasAtChanneledTarget (AurSpellInfo);
3879 if(statue)
3880 statue->UnSummon();
3882 // only way correctly remove all auras from list
3883 if( m_Auras.empty() )
3884 i = m_Auras.end();
3885 else
3886 i = m_Auras.begin();
3889 void Unit::RemoveAllAuras()
3891 while (!m_Auras.empty())
3893 AuraMap::iterator iter = m_Auras.begin();
3894 RemoveAura(iter);
3898 void Unit::RemoveArenaAuras(bool onleave)
3900 // in join, remove positive buffs, on end, remove negative
3901 // used to remove positive visible auras in arenas
3902 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3904 if ( !(iter->second->GetSpellProto()->AttributesEx4 & (1<<21)) // don't remove stances, shadowform, pally/hunter auras
3905 && !iter->second->IsPassive() // don't remove passive auras
3906 && (!(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)
3907 && (iter->second->IsPositive() ^ onleave)) // remove positive buffs on enter, negative buffs on leave
3908 RemoveAura(iter);
3909 else
3910 ++iter;
3914 void Unit::RemoveAllAurasOnDeath()
3916 // used just after dieing to remove all visible auras
3917 // and disable the mods for the passive ones
3918 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
3920 if (!iter->second->IsPassive() && !iter->second->IsDeathPersistent())
3921 RemoveAura(iter, AURA_REMOVE_BY_DEATH);
3922 else
3923 ++iter;
3927 void Unit::DelayAura(uint32 spellId, uint32 effindex, int32 delaytime)
3929 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3930 if (iter != m_Auras.end())
3932 if (iter->second->GetAuraDuration() < delaytime)
3933 iter->second->SetAuraDuration(0);
3934 else
3935 iter->second->SetAuraDuration(iter->second->GetAuraDuration() - delaytime);
3936 iter->second->SendAuraUpdate(false);
3937 sLog.outDebug("Aura %u partially interrupted on unit %u, new duration: %u ms",iter->second->GetModifier()->m_auraname, GetGUIDLow(), iter->second->GetAuraDuration());
3941 void Unit::_RemoveAllAuraMods()
3943 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3945 (*i).second->ApplyModifier(false);
3949 void Unit::_ApplyAllAuraMods()
3951 for (AuraMap::iterator i = m_Auras.begin(); i != m_Auras.end(); ++i)
3953 (*i).second->ApplyModifier(true);
3957 Aura* Unit::GetAura(uint32 spellId, uint32 effindex)
3959 AuraMap::iterator iter = m_Auras.find(spellEffectPair(spellId, effindex));
3960 if (iter != m_Auras.end())
3961 return iter->second;
3962 return NULL;
3965 Aura* Unit::GetAura(AuraType type, uint32 family, uint64 familyFlag, uint32 familyFlag2, uint64 casterGUID)
3967 AuraList const& auras = GetAurasByType(type);
3968 for(AuraList::const_iterator i = auras.begin();i != auras.end(); ++i)
3970 SpellEntry const *spell = (*i)->GetSpellProto();
3971 if (spell->SpellFamilyName == family && (spell->SpellFamilyFlags & familyFlag || spell->SpellFamilyFlags2 & familyFlag2))
3973 if (casterGUID && (*i)->GetCasterGUID()!=casterGUID)
3974 continue;
3975 return (*i);
3978 return NULL;
3981 bool Unit::HasAura(uint32 spellId) const
3983 for (int i = 0; i < 3 ; ++i)
3985 AuraMap::const_iterator iter = m_Auras.find(spellEffectPair(spellId, i));
3986 if (iter != m_Auras.end())
3987 return true;
3989 return false;
3992 void Unit::AddDynObject(DynamicObject* dynObj)
3994 m_dynObjGUIDs.push_back(dynObj->GetGUID());
3997 void Unit::RemoveDynObject(uint32 spellid)
3999 if(m_dynObjGUIDs.empty())
4000 return;
4001 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4003 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4004 if(!dynObj)
4006 i = m_dynObjGUIDs.erase(i);
4008 else if(spellid == 0 || dynObj->GetSpellId() == spellid)
4010 dynObj->Delete();
4011 i = m_dynObjGUIDs.erase(i);
4013 else
4014 ++i;
4018 void Unit::RemoveAllDynObjects()
4020 while(!m_dynObjGUIDs.empty())
4022 DynamicObject* dynObj = GetMap()->GetDynamicObject(*m_dynObjGUIDs.begin());
4023 if(dynObj)
4024 dynObj->Delete();
4025 m_dynObjGUIDs.erase(m_dynObjGUIDs.begin());
4029 DynamicObject * Unit::GetDynObject(uint32 spellId, uint32 effIndex)
4031 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4033 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4034 if(!dynObj)
4036 i = m_dynObjGUIDs.erase(i);
4037 continue;
4040 if (dynObj->GetSpellId() == spellId && dynObj->GetEffIndex() == effIndex)
4041 return dynObj;
4042 ++i;
4044 return NULL;
4047 DynamicObject * Unit::GetDynObject(uint32 spellId)
4049 for (DynObjectGUIDs::iterator i = m_dynObjGUIDs.begin(); i != m_dynObjGUIDs.end();)
4051 DynamicObject* dynObj = GetMap()->GetDynamicObject(*i);
4052 if(!dynObj)
4054 i = m_dynObjGUIDs.erase(i);
4055 continue;
4058 if (dynObj->GetSpellId() == spellId)
4059 return dynObj;
4060 ++i;
4062 return NULL;
4065 GameObject* Unit::GetGameObject(uint32 spellId) const
4067 for (GameObjectList::const_iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4068 if ((*i)->GetSpellId() == spellId)
4069 return *i;
4071 return NULL;
4074 void Unit::AddGameObject(GameObject* gameObj)
4076 assert(gameObj && gameObj->GetOwnerGUID()==0);
4077 m_gameObj.push_back(gameObj);
4078 gameObj->SetOwnerGUID(GetGUID());
4080 if ( GetTypeId()==TYPEID_PLAYER && gameObj->GetSpellId() )
4082 SpellEntry const* createBySpell = sSpellStore.LookupEntry(gameObj->GetSpellId());
4083 // Need disable spell use for owner
4084 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4085 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4086 ((Player*)this)->AddSpellAndCategoryCooldowns(createBySpell,0,NULL,true);
4090 void Unit::RemoveGameObject(GameObject* gameObj, bool del)
4092 assert(gameObj && gameObj->GetOwnerGUID()==GetGUID());
4094 gameObj->SetOwnerGUID(0);
4096 // GO created by some spell
4097 if (uint32 spellid = gameObj->GetSpellId())
4099 RemoveAurasDueToSpell(spellid);
4101 if (GetTypeId()==TYPEID_PLAYER)
4103 SpellEntry const* createBySpell = sSpellStore.LookupEntry(spellid );
4104 // Need activate spell use for owner
4105 if (createBySpell && createBySpell->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
4106 // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases)
4107 ((Player*)this)->SendCooldownEvent(createBySpell);
4111 m_gameObj.remove(gameObj);
4113 if(del)
4115 gameObj->SetRespawnTime(0);
4116 gameObj->Delete();
4120 void Unit::RemoveGameObject(uint32 spellid, bool del)
4122 if(m_gameObj.empty())
4123 return;
4124 GameObjectList::iterator i, next;
4125 for (i = m_gameObj.begin(); i != m_gameObj.end(); i = next)
4127 next = i;
4128 if(spellid == 0 || (*i)->GetSpellId() == spellid)
4130 (*i)->SetOwnerGUID(0);
4131 if(del)
4133 (*i)->SetRespawnTime(0);
4134 (*i)->Delete();
4137 next = m_gameObj.erase(i);
4139 else
4140 ++next;
4144 void Unit::RemoveAllGameObjects()
4146 // remove references to unit
4147 for(GameObjectList::iterator i = m_gameObj.begin(); i != m_gameObj.end();)
4149 (*i)->SetOwnerGUID(0);
4150 (*i)->SetRespawnTime(0);
4151 (*i)->Delete();
4152 i = m_gameObj.erase(i);
4156 void Unit::SendSpellNonMeleeDamageLog(SpellNonMeleeDamage *log)
4158 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4159 data.append(log->target->GetPackGUID());
4160 data.append(log->attacker->GetPackGUID());
4161 data << uint32(log->SpellID);
4162 data << uint32(log->damage); //damage amount
4163 data << uint32(0);
4164 data << uint8 (log->schoolMask); //damage school
4165 data << uint32(log->absorb); //AbsorbedDamage
4166 data << uint32(log->resist); //resist
4167 data << uint8 (log->phusicalLog); // damsge type? flag
4168 data << uint8 (log->unused); //unused
4169 data << uint32(log->blocked); //blocked
4170 data << uint32(log->HitInfo);
4171 data << uint8 (0); // flag to use extend data
4172 SendMessageToSet( &data, true );
4175 void Unit::SendSpellNonMeleeDamageLog(Unit *target,uint32 SpellID,uint32 Damage, SpellSchoolMask damageSchoolMask,uint32 AbsorbedDamage, uint32 Resist,bool PhysicalDamage, uint32 Blocked, bool CriticalHit)
4177 sLog.outDebug("Sending: SMSG_SPELLNONMELEEDAMAGELOG");
4178 WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG, (16+4+4+1+4+4+1+1+4+4+1)); // we guess size
4179 data.append(target->GetPackGUID());
4180 data.append(GetPackGUID());
4181 data << uint32(SpellID);
4182 data << uint32(Damage-AbsorbedDamage-Resist-Blocked);
4183 data << uint32(0); // wotlk
4184 data << uint8(damageSchoolMask); // spell school
4185 data << uint32(AbsorbedDamage); // AbsorbedDamage
4186 data << uint32(Resist); // resist
4187 data << uint8(PhysicalDamage); // 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
4188 data << uint8(0); // unk isFromAura
4189 data << uint32(Blocked); // blocked
4190 data << uint32(CriticalHit ? 0x27 : 0x25); // hitType, flags: 0x2 - SPELL_HIT_TYPE_CRIT, 0x10 - replace caster?
4191 data << uint8(0); // isDebug?
4192 SendMessageToSet( &data, true );
4195 void Unit::ProcDamageAndSpell(Unit *pVictim, uint32 procAttacker, uint32 procVictim, uint32 procExtra, uint32 amount, WeaponAttackType attType, SpellEntry const *procSpell)
4197 // Not much to do if no flags are set.
4198 if (procAttacker)
4199 ProcDamageAndSpellFor(false,pVictim,procAttacker, procExtra,attType, procSpell, amount);
4200 // Now go on with a victim's events'n'auras
4201 // Not much to do if no flags are set or there is no victim
4202 if(pVictim && pVictim->isAlive() && procVictim)
4203 pVictim->ProcDamageAndSpellFor(true,this,procVictim, procExtra, attType, procSpell, amount);
4206 void Unit::SendSpellMiss(Unit *target, uint32 spellID, SpellMissInfo missInfo)
4208 WorldPacket data(SMSG_SPELLLOGMISS, (4+8+1+4+8+1));
4209 data << uint32(spellID);
4210 data << uint64(GetGUID());
4211 data << uint8(0); // can be 0 or 1
4212 data << uint32(1); // target count
4213 // for(i = 0; i < target count; ++i)
4214 data << uint64(target->GetGUID()); // target GUID
4215 data << uint8(missInfo);
4216 // end loop
4217 SendMessageToSet(&data, true);
4220 void Unit::SendAttackStateUpdate(CalcDamageInfo *damageInfo)
4222 uint32 count = 1;
4223 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4224 data << (uint32)damageInfo->HitInfo;
4225 data.append(GetPackGUID());
4226 data.append(damageInfo->target->GetPackGUID());
4227 data << (uint32)(damageInfo->damage); // Full damage
4228 data << uint32(0); // overkill value
4230 data << (uint8)count; // Sub damage count
4232 for(int i = 0; i < count; ++i)
4234 data << (uint32)(damageInfo->damageSchoolMask); // School of sub damage
4235 data << (float)damageInfo->damage; // sub damage
4236 data << (uint32)damageInfo->damage; // Sub Damage
4239 if(damageInfo->HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4241 for(int i = 0; i < count; ++i)
4242 data << (uint32)damageInfo->absorb; // Absorb
4245 if(damageInfo->HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4247 for(int i = 0; i < count; ++i)
4248 data << (uint32)damageInfo->resist; // Resist
4251 data << (uint8)damageInfo->TargetState;
4252 data << (uint32)0;
4253 data << (uint32)0;
4255 if(damageInfo->HitInfo & HITINFO_BLOCK)
4256 data << (uint32)damageInfo->blocked_amount;
4258 if(damageInfo->HitInfo & HITINFO_UNK3)
4259 data << uint32(0);
4261 if(damageInfo->HitInfo & HITINFO_UNK1)
4263 data << uint32(0);
4264 data << float(0);
4265 data << float(0);
4266 data << float(0);
4267 data << float(0);
4268 data << float(0);
4269 data << float(0);
4270 data << float(0);
4271 data << float(0);
4272 for(uint8 i = 0; i < 5; ++i)
4274 data << float(0);
4275 data << float(0);
4277 data << uint32(0);
4280 SendMessageToSet( &data, true );
4283 void Unit::SendAttackStateUpdate(uint32 HitInfo, Unit *target, uint8 SwingType, SpellSchoolMask damageSchoolMask, uint32 Damage, uint32 AbsorbDamage, uint32 Resist, VictimState TargetState, uint32 BlockedAmount)
4285 sLog.outDebug("WORLD: Sending SMSG_ATTACKERSTATEUPDATE");
4287 WorldPacket data(SMSG_ATTACKERSTATEUPDATE, (16+45)); // we guess size
4288 data << uint32(HitInfo); // flags
4289 data.append(GetPackGUID());
4290 data.append(target->GetPackGUID());
4291 data << uint32(Damage-AbsorbDamage-Resist-BlockedAmount);// damage
4292 data << uint32(0); // overkill value
4294 data << (uint8)SwingType; // count?
4296 // for(i = 0; i < SwingType; ++i)
4297 data << (uint32)damageSchoolMask;
4298 data << (float)(Damage-AbsorbDamage-Resist-BlockedAmount);
4299 data << (uint32)(Damage-AbsorbDamage-Resist-BlockedAmount);
4300 // end loop
4302 if(HitInfo & (HITINFO_ABSORB | HITINFO_ABSORB2))
4304 // for(i = 0; i < SwingType; ++i)
4305 data << uint32(AbsorbDamage);
4306 // end loop
4309 if(HitInfo & (HITINFO_RESIST | HITINFO_RESIST2))
4311 // for(i = 0; i < SwingType; ++i)
4312 data << uint32(Resist);
4313 // end loop
4316 data << (uint8)TargetState;
4317 data << (uint32)0;
4318 data << (uint32)0;
4320 if(HitInfo & HITINFO_BLOCK)
4322 data << uint32(BlockedAmount);
4325 if(HitInfo & HITINFO_UNK3)
4327 data << uint32(0);
4330 if(HitInfo & HITINFO_UNK1)
4332 data << uint32(0);
4333 data << float(0);
4334 data << float(0);
4335 data << float(0);
4336 data << float(0);
4337 data << float(0);
4338 data << float(0);
4339 data << float(0);
4340 data << float(0);
4341 for(uint8 i = 0; i < 5; ++i)
4343 data << float(0);
4344 data << float(0);
4346 data << uint32(0);
4349 SendMessageToSet( &data, true );
4352 bool Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown)
4354 SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto();
4356 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4357 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4359 uint32 triggered_spell_id = 0;
4360 Unit* target = pVictim;
4361 int32 basepoints0 = 0;
4363 switch(hasteSpell->SpellFamilyName)
4365 case SPELLFAMILY_ROGUE:
4367 switch(hasteSpell->Id)
4369 // Blade Flurry
4370 case 13877:
4371 case 33735:
4373 target = SelectNearbyTarget();
4374 if(!target)
4375 return false;
4376 basepoints0 = damage;
4377 triggered_spell_id = 22482;
4378 break;
4381 break;
4385 // processed charge only counting case
4386 if(!triggered_spell_id)
4387 return true;
4389 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
4391 if(!triggerEntry)
4393 sLog.outError("Unit::HandleHasteAuraProc: Spell %u have not existed triggered spell %u",hasteSpell->Id,triggered_spell_id);
4394 return false;
4397 // default case
4398 if(!target || target!=this && !target->isAlive())
4399 return false;
4401 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
4402 return false;
4404 if(basepoints0)
4405 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
4406 else
4407 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
4409 if( cooldown && GetTypeId()==TYPEID_PLAYER )
4410 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
4412 return true;
4415 bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown)
4417 SpellEntry const *dummySpell = triggeredByAura->GetSpellProto ();
4418 uint32 effIndex = triggeredByAura->GetEffIndex();
4419 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
4421 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
4422 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
4424 uint32 triggered_spell_id = 0;
4425 Unit* target = pVictim;
4426 int32 basepoints0 = 0;
4428 switch(dummySpell->SpellFamilyName)
4430 case SPELLFAMILY_GENERIC:
4432 switch (dummySpell->Id)
4434 // Eye for an Eye
4435 case 9799:
4436 case 25988:
4438 // return damage % to attacker but < 50% own total health
4439 basepoints0 = triggerAmount*int32(damage)/100;
4440 if(basepoints0 > GetMaxHealth()/2)
4441 basepoints0 = GetMaxHealth()/2;
4443 triggered_spell_id = 25997;
4444 break;
4446 // Sweeping Strikes
4447 case 12328:
4448 case 18765:
4449 case 35429:
4451 // prevent chain of triggered spell from same triggered spell
4452 if(procSpell && procSpell->Id==26654)
4453 return false;
4455 target = SelectNearbyTarget();
4456 if(!target)
4457 return false;
4459 triggered_spell_id = 26654;
4460 break;
4462 // Unstable Power
4463 case 24658:
4465 if (!procSpell || procSpell->Id == 24659)
4466 return false;
4467 // Need remove one 24659 aura
4468 RemoveSingleSpellAurasFromStack(24659);
4469 return true;
4471 // Restless Strength
4472 case 24661:
4474 // Need remove one 24662 aura
4475 RemoveSingleSpellAurasFromStack(24662);
4476 return true;
4478 // Adaptive Warding (Frostfire Regalia set)
4479 case 28764:
4481 if(!procSpell)
4482 return false;
4484 // find Mage Armor
4485 bool found = false;
4486 AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT);
4487 for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter)
4489 if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto())
4491 if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & 0x10000000))
4493 found=true;
4494 break;
4498 if(!found)
4499 return false;
4501 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4503 case SPELL_SCHOOL_NORMAL:
4504 case SPELL_SCHOOL_HOLY:
4505 return false; // ignored
4506 case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break;
4507 case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break;
4508 case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break;
4509 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break;
4510 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break;
4511 default:
4512 return false;
4515 target = this;
4516 break;
4518 // Obsidian Armor (Justice Bearer`s Pauldrons shoulder)
4519 case 27539:
4521 if(!procSpell)
4522 return false;
4524 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
4526 case SPELL_SCHOOL_NORMAL:
4527 return false; // ignore
4528 case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break;
4529 case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break;
4530 case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break;
4531 case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break;
4532 case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break;
4533 case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break;
4534 default:
4535 return false;
4538 target = this;
4539 break;
4541 // Mana Leech (Passive) (Priest Pet Aura)
4542 case 28305:
4544 // Cast on owner
4545 target = GetOwner();
4546 if(!target)
4547 return false;
4549 triggered_spell_id = 34650;
4550 break;
4552 // Mark of Malice
4553 case 33493:
4555 // Cast finish spell at last charge
4556 if (triggeredByAura->GetAuraCharges() > 1)
4557 return false;
4559 target = this;
4560 triggered_spell_id = 33494;
4561 break;
4563 // Twisted Reflection (boss spell)
4564 case 21063:
4565 triggered_spell_id = 21064;
4566 break;
4567 // Vampiric Aura (boss spell)
4568 case 38196:
4570 basepoints0 = 3 * damage; // 300%
4571 if (basepoints0 < 0)
4572 return false;
4574 triggered_spell_id = 31285;
4575 target = this;
4576 break;
4578 // Aura of Madness (Darkmoon Card: Madness trinket)
4579 //=====================================================
4580 // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior)
4581 // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid)
4582 // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid)
4583 // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4584 // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes)
4585 // 41005 Manic: +35 haste (spell, melee and ranged) (All classes)
4586 // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter)
4587 // 41011 Martyr Complex: +35 stamina (All classes)
4588 // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4589 // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin)
4590 case 39446:
4592 if(GetTypeId() != TYPEID_PLAYER)
4593 return false;
4595 // Select class defined buff
4596 switch (getClass())
4598 case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4599 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409
4601 uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409};
4602 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4603 break;
4605 case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011
4606 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011
4608 uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011};
4609 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4610 break;
4612 case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409
4613 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409
4614 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409
4615 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409
4617 uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409};
4618 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4619 break;
4621 case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409
4623 uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409};
4624 triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ];
4625 break;
4627 default:
4628 return false;
4631 target = this;
4632 if (roll_chance_i(10))
4633 ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL);
4634 break;
4637 // TODO: need find item for aura and triggered spells
4638 // Sunwell Exalted Caster Neck (??? neck)
4639 // cast ??? Light's Wrath if Exalted by Aldor
4640 // cast ??? Arcane Bolt if Exalted by Scryers*/
4641 case 46569:
4642 return false; // disable for while
4645 if(GetTypeId() != TYPEID_PLAYER)
4646 return false;
4648 // Get Aldor reputation rank
4649 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4651 target = this;
4652 triggered_spell_id = ???
4653 break;
4655 // Get Scryers reputation rank
4656 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4658 triggered_spell_id = ???
4659 break;
4661 return false;
4662 }/**/
4663 // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck)
4664 // cast 45479 Light's Wrath if Exalted by Aldor
4665 // cast 45429 Arcane Bolt if Exalted by Scryers
4666 case 45481:
4668 if(GetTypeId() != TYPEID_PLAYER)
4669 return false;
4671 // Get Aldor reputation rank
4672 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4674 target = this;
4675 triggered_spell_id = 45479;
4676 break;
4678 // Get Scryers reputation rank
4679 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4681 triggered_spell_id = 45429;
4682 break;
4684 return false;
4686 // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck)
4687 // cast 45480 Light's Strength if Exalted by Aldor
4688 // cast 45428 Arcane Strike if Exalted by Scryers
4689 case 45482:
4691 if(GetTypeId() != TYPEID_PLAYER)
4692 return false;
4694 // Get Aldor reputation rank
4695 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4697 target = this;
4698 triggered_spell_id = 45480;
4699 break;
4701 // Get Scryers reputation rank
4702 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4704 triggered_spell_id = 45428;
4705 break;
4707 return false;
4709 // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck)
4710 // cast 45431 Arcane Insight if Exalted by Aldor
4711 // cast 45432 Light's Ward if Exalted by Scryers
4712 case 45483:
4714 if(GetTypeId() != TYPEID_PLAYER)
4715 return false;
4717 // Get Aldor reputation rank
4718 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4720 target = this;
4721 triggered_spell_id = 45432;
4722 break;
4724 // Get Scryers reputation rank
4725 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4727 target = this;
4728 triggered_spell_id = 45431;
4729 break;
4731 return false;
4733 // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck)
4734 // cast 45478 Light's Salvation if Exalted by Aldor
4735 // cast 45430 Arcane Surge if Exalted by Scryers
4736 case 45484:
4738 if(GetTypeId() != TYPEID_PLAYER)
4739 return false;
4741 // Get Aldor reputation rank
4742 if (((Player *)this)->GetReputationRank(932) == REP_EXALTED)
4744 target = this;
4745 triggered_spell_id = 45478;
4746 break;
4748 // Get Scryers reputation rank
4749 if (((Player *)this)->GetReputationRank(934) == REP_EXALTED)
4751 triggered_spell_id = 45430;
4752 break;
4754 return false;
4756 // Living Seed
4757 case 48504:
4759 triggered_spell_id = 48503;
4760 basepoints0 = triggerAmount;
4761 target = this;
4762 break;
4764 // Vampiric Touch (generic, used by some boss)
4765 case 52723:
4766 case 60501:
4768 triggered_spell_id = 52724;
4769 basepoints0 = damage / 2;
4770 target = this;
4771 break;
4773 // Divine purpose
4774 case 31871:
4775 case 31872:
4777 // Roll chane
4778 if (!roll_chance_i(triggerAmount))
4779 return false;
4781 // Remove any stun effect on target
4782 AuraMap& Auras = pVictim->GetAuras();
4783 for(AuraMap::iterator iter = Auras.begin(); iter != Auras.end();)
4785 SpellEntry const *spell = iter->second->GetSpellProto();
4786 if( spell->Mechanic == MECHANIC_STUN ||
4787 spell->EffectMechanic[iter->second->GetEffIndex()] == MECHANIC_STUN)
4789 pVictim->RemoveAurasDueToSpell(spell->Id);
4790 iter = Auras.begin();
4792 else
4793 ++iter;
4795 return true;
4798 break;
4800 case SPELLFAMILY_MAGE:
4802 // Magic Absorption
4803 if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura
4805 if (getPowerType() != POWER_MANA)
4806 return false;
4808 // mana reward
4809 basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100);
4810 target = this;
4811 triggered_spell_id = 29442;
4812 break;
4814 // Master of Elements
4815 if (dummySpell->SpellIconID == 1920)
4817 if(!procSpell)
4818 return false;
4820 // mana cost save
4821 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4822 basepoints0 = cost * triggerAmount/100;
4823 if( basepoints0 <=0 )
4824 return false;
4826 target = this;
4827 triggered_spell_id = 29077;
4828 break;
4830 // Hot Streak
4831 if (dummySpell->SpellIconID == 2999)
4833 if (effIndex!=0)
4834 return true;
4835 Aura *counter = GetAura(triggeredByAura->GetId(), 1);
4836 if (!counter)
4837 return true;
4839 // Count spell criticals in a row in second aura
4840 Modifier *mod = counter->GetModifier();
4841 if (procEx & PROC_EX_CRITICAL_HIT)
4843 mod->m_amount *=2;
4844 if (mod->m_amount < 100) // not enough
4845 return true;
4846 // Crititcal counted -> roll chance
4847 if (roll_chance_i(triggerAmount))
4848 CastSpell(this, 48108, true, castItem, triggeredByAura);
4850 mod->m_amount = 25;
4851 return true;
4853 // Burnout
4854 if (dummySpell->SpellIconID == 2998)
4856 if(!procSpell)
4857 return false;
4859 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
4860 basepoints0 = cost * triggerAmount/100;
4861 if( basepoints0 <=0 )
4862 return false;
4863 triggered_spell_id = 44450;
4864 target = this;
4865 break;
4867 // Incanter's Regalia set (add trigger chance to Mana Shield)
4868 if (dummySpell->SpellFamilyFlags & 0x0000000000008000LL)
4870 if(GetTypeId() != TYPEID_PLAYER)
4871 return false;
4873 target = this;
4874 triggered_spell_id = 37436;
4875 break;
4877 switch(dummySpell->Id)
4879 // Ignite
4880 case 11119:
4881 case 11120:
4882 case 12846:
4883 case 12847:
4884 case 12848:
4886 switch (dummySpell->Id)
4888 case 11119: basepoints0 = int32(0.04f*damage); break;
4889 case 11120: basepoints0 = int32(0.08f*damage); break;
4890 case 12846: basepoints0 = int32(0.12f*damage); break;
4891 case 12847: basepoints0 = int32(0.16f*damage); break;
4892 case 12848: basepoints0 = int32(0.20f*damage); break;
4893 default:
4894 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id);
4895 return false;
4898 triggered_spell_id = 12654;
4899 break;
4901 // Combustion
4902 case 11129:
4904 //last charge and crit
4905 if (triggeredByAura->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) )
4907 RemoveAurasDueToSpell(28682); //-> remove Combustion auras
4908 return true; // charge counting (will removed)
4911 CastSpell(this, 28682, true, castItem, triggeredByAura);
4912 return (procEx & PROC_EX_CRITICAL_HIT);// charge update only at crit hits, no hidden cooldowns
4915 break;
4917 case SPELLFAMILY_WARRIOR:
4919 // Retaliation
4920 if(dummySpell->SpellFamilyFlags==0x0000000800000000LL)
4922 // check attack comes not from behind
4923 if (!HasInArc(M_PI, pVictim))
4924 return false;
4926 triggered_spell_id = 22858;
4927 break;
4929 // Second Wind
4930 if (dummySpell->SpellIconID == 1697)
4932 // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example)
4933 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
4934 return false;
4935 // Need stun or root mechanic
4936 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_STUN))))
4937 return false;
4939 switch (dummySpell->Id)
4941 case 29838: triggered_spell_id=29842; break;
4942 case 29834: triggered_spell_id=29841; break;
4943 case 42770: triggered_spell_id=42771; break;
4944 default:
4945 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id);
4946 return false;
4949 target = this;
4950 break;
4952 // Damage Shield
4953 if (dummySpell->SpellIconID == 3214)
4955 triggered_spell_id = 59653;
4956 basepoints0 = GetShieldBlockValue() * triggerAmount / 100;
4957 break;
4959 break;
4961 case SPELLFAMILY_WARLOCK:
4963 // Seed of Corruption
4964 if (dummySpell->SpellFamilyFlags & 0x0000001000000000LL)
4966 Modifier* mod = triggeredByAura->GetModifier();
4967 // if damage is more than need or target die from damage deal finish spell
4968 if( mod->m_amount <= damage || GetHealth() <= damage )
4970 // remember guid before aura delete
4971 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4973 // Remove aura (before cast for prevent infinite loop handlers)
4974 RemoveAurasDueToSpell(triggeredByAura->GetId());
4976 // Cast finish spell (triggeredByAura already not exist!)
4977 CastSpell(this, 27285, true, castItem, NULL, casterGuid);
4978 return true; // no hidden cooldown
4981 // Damage counting
4982 mod->m_amount-=damage;
4983 return true;
4985 // Seed of Corruption (Mobs cast) - no die req
4986 if (dummySpell->SpellFamilyFlags == 0x00LL && dummySpell->SpellIconID == 1932)
4988 Modifier* mod = triggeredByAura->GetModifier();
4989 // if damage is more than need deal finish spell
4990 if( mod->m_amount <= damage )
4992 // remember guid before aura delete
4993 uint64 casterGuid = triggeredByAura->GetCasterGUID();
4995 // Remove aura (before cast for prevent infinite loop handlers)
4996 RemoveAurasDueToSpell(triggeredByAura->GetId());
4998 // Cast finish spell (triggeredByAura already not exist!)
4999 CastSpell(this, 32865, true, castItem, NULL, casterGuid);
5000 return true; // no hidden cooldown
5002 // Damage counting
5003 mod->m_amount-=damage;
5004 return true;
5006 // Fel Synergy
5007 if (dummySpell->SpellIconID == 3222)
5009 target = GetPet();
5010 if (!target)
5011 return false;
5012 triggered_spell_id = 54181;
5013 basepoints0 = damage * triggerAmount / 100;
5014 break;
5016 switch(dummySpell->Id)
5018 // Nightfall
5019 case 18094:
5020 case 18095:
5022 target = this;
5023 triggered_spell_id = 17941;
5024 break;
5026 //Soul Leech
5027 case 30293:
5028 case 30295:
5029 case 30296:
5031 // health
5032 basepoints0 = int32(damage*triggerAmount/100);
5033 target = this;
5034 triggered_spell_id = 30294;
5035 break;
5037 // Shadowflame (Voidheart Raiment set bonus)
5038 case 37377:
5040 triggered_spell_id = 37379;
5041 break;
5043 // Pet Healing (Corruptor Raiment or Rift Stalker Armor)
5044 case 37381:
5046 target = GetPet();
5047 if(!target)
5048 return false;
5050 // heal amount
5051 basepoints0 = damage * triggerAmount/100;
5052 triggered_spell_id = 37382;
5053 break;
5055 // Shadowflame Hellfire (Voidheart Raiment set bonus)
5056 case 39437:
5058 triggered_spell_id = 37378;
5059 break;
5062 break;
5064 case SPELLFAMILY_PRIEST:
5066 // Vampiric Touch
5067 if( dummySpell->SpellFamilyFlags & 0x0000040000000000LL )
5069 if(!pVictim || !pVictim->isAlive())
5070 return false;
5072 // pVictim is caster of aura
5073 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5074 return false;
5076 // energize amount
5077 basepoints0 = triggerAmount*damage/100;
5078 pVictim->CastCustomSpell(pVictim,34919,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5079 return true; // no hidden cooldown
5081 // Divine Aegis
5082 if (dummySpell->SpellIconID == 2820)
5084 basepoints0 = damage * triggerAmount/100;
5085 triggered_spell_id = 47753;
5086 break;
5088 switch(dummySpell->Id)
5090 // Vampiric Embrace
5091 case 15286:
5093 if(!pVictim || !pVictim->isAlive())
5094 return false;
5096 // pVictim is caster of aura
5097 if(triggeredByAura->GetCasterGUID() != pVictim->GetGUID())
5098 return false;
5100 // heal amount
5101 int32 team = triggerAmount*damage/500;
5102 int32 self = triggerAmount*damage/100 - team;
5103 pVictim->CastCustomSpell(pVictim,15290,&team,&self,NULL,true,castItem,triggeredByAura);
5104 return true; // no hidden cooldown
5106 // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen)
5107 case 40438:
5109 // Shadow Word: Pain
5110 if( procSpell->SpellFamilyFlags & 0x0000000000008000LL )
5111 triggered_spell_id = 40441;
5112 // Renew
5113 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5114 triggered_spell_id = 40440;
5115 else
5116 return false;
5118 target = this;
5119 break;
5121 // Oracle Healing Bonus ("Garments of the Oracle" set)
5122 case 26169:
5124 // heal amount
5125 basepoints0 = int32(damage * 10/100);
5126 target = this;
5127 triggered_spell_id = 26170;
5128 break;
5130 // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set
5131 case 39372:
5133 if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 )
5134 return false;
5136 // heal amount
5137 basepoints0 = damage * triggerAmount/100;
5138 target = this;
5139 triggered_spell_id = 39373;
5140 break;
5142 // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus)
5143 case 28809:
5145 triggered_spell_id = 28810;
5146 break;
5148 // Glyph of Dispel Magic
5149 case 55677:
5151 if(!target->IsFriendlyTo(this))
5152 return false;
5154 basepoints0 = int32(target->GetMaxHealth() * triggerAmount / 100);
5155 triggered_spell_id = 56131;
5156 break;
5159 break;
5161 case SPELLFAMILY_DRUID:
5163 switch(dummySpell->Id)
5165 // Healing Touch (Dreamwalker Raiment set)
5166 case 28719:
5168 // mana back
5169 basepoints0 = int32(procSpell->manaCost * 30 / 100);
5170 target = this;
5171 triggered_spell_id = 28742;
5172 break;
5174 // Healing Touch Refund (Idol of Longevity trinket)
5175 case 28847:
5177 target = this;
5178 triggered_spell_id = 28848;
5179 break;
5181 // Mana Restore (Malorne Raiment set / Malorne Regalia set)
5182 case 37288:
5183 case 37295:
5185 target = this;
5186 triggered_spell_id = 37238;
5187 break;
5189 // Druid Tier 6 Trinket
5190 case 40442:
5192 float chance;
5194 // Starfire
5195 if( procSpell->SpellFamilyFlags & 0x0000000000000004LL )
5197 triggered_spell_id = 40445;
5198 chance = 25.f;
5200 // Rejuvenation
5201 else if( procSpell->SpellFamilyFlags & 0x0000000000000010LL )
5203 triggered_spell_id = 40446;
5204 chance = 25.f;
5206 // Mangle (cat/bear)
5207 else if( procSpell->SpellFamilyFlags & 0x0000044000000000LL )
5209 triggered_spell_id = 40452;
5210 chance = 40.f;
5212 else
5213 return false;
5215 if (!roll_chance_f(chance))
5216 return false;
5218 target = this;
5219 break;
5221 // Maim Interrupt
5222 case 44835:
5224 // Deadly Interrupt Effect
5225 triggered_spell_id = 32747;
5226 break;
5229 // Eclipse
5230 if (dummySpell->SpellIconID == 2856)
5232 if (!procSpell)
5233 return false;
5234 // Only 0 aura can proc
5235 if (effIndex!=0)
5236 return true;
5237 // Wrath crit
5238 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5240 if (!roll_chance_i(60))
5241 return false;
5242 triggered_spell_id = 48518;
5243 target = this;
5244 break;
5246 // Starfire crit
5247 if (procSpell->SpellFamilyFlags & 0x0000000000000004LL)
5249 triggered_spell_id = 48517;
5250 target = this;
5251 break;
5253 return false;
5255 // Living Seed
5256 else if (dummySpell->SpellIconID == 2860)
5258 triggered_spell_id = 48504;
5259 basepoints0 = triggerAmount * damage / 100;
5260 break;
5262 break;
5264 case SPELLFAMILY_ROGUE:
5266 switch(dummySpell->Id)
5268 // Deadly Throw Interrupt
5269 case 32748:
5271 // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw
5272 if(this == pVictim)
5273 return false;
5275 triggered_spell_id = 32747;
5276 break;
5279 // Cut to the Chase
5280 if( dummySpell->SpellIconID == 2909 )
5282 // "refresh your Slice and Dice duration to its 5 combo point maximum"
5283 // lookup Slice and Dice
5284 AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_HASTE);
5285 for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr)
5287 SpellEntry const *spellProto = (*itr)->GetSpellProto();
5288 if( spellProto->SpellFamilyName == SPELLFAMILY_ROGUE &&
5289 spellProto->SpellFamilyFlags & 0x0000000000040000LL)
5291 (*itr)->SetAuraMaxDuration(GetSpellMaxDuration(spellProto));
5292 (*itr)->RefreshAura();
5293 return true;
5296 return false;
5298 // Deadly Brew
5299 if( dummySpell->SpellIconID == 2963 )
5301 triggered_spell_id = 25809;
5302 break;
5304 // Quick Recovery
5305 if( dummySpell->SpellIconID == 2116 )
5307 if(!procSpell)
5308 return false;
5310 // energy cost save
5311 basepoints0 = procSpell->manaCost * triggerAmount/100;
5312 if(basepoints0 <= 0)
5313 return false;
5315 target = this;
5316 triggered_spell_id = 31663;
5317 break;
5319 break;
5321 case SPELLFAMILY_HUNTER:
5323 // Thrill of the Hunt
5324 if ( dummySpell->SpellIconID == 2236 )
5326 if(!procSpell)
5327 return false;
5329 // mana cost save
5330 int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
5331 basepoints0 = mana * 40/100;
5332 if(basepoints0 <= 0)
5333 return false;
5335 target = this;
5336 triggered_spell_id = 34720;
5337 break;
5339 // Hunting Party
5340 if ( dummySpell->SpellIconID == 3406 )
5342 triggered_spell_id = 57669;
5343 target = this;
5344 break;
5346 // Lock and Load
5347 if ( dummySpell->SpellIconID == 3579 )
5349 // Proc only from periodic (from trap activation proc another aura of this spell)
5350 if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount))
5351 return false;
5352 triggered_spell_id = 56453;
5353 target = this;
5354 break;
5356 // Rapid Recuperation
5357 if ( dummySpell->SpellIconID == 3560 )
5359 // This effect only from Rapid Killing (mana regen)
5360 if (!(procSpell->SpellFamilyFlags & 0x0100000000000000LL))
5361 return false;
5362 triggered_spell_id = 56654;
5363 target = this;
5364 break;
5366 break;
5368 case SPELLFAMILY_PALADIN:
5370 // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage)
5371 if (dummySpell->SpellFamilyFlags&0x000000008000000LL && effIndex==0)
5373 triggered_spell_id = 25742;
5374 float ap = GetTotalAttackPowerValue(BASE_ATTACK);
5375 int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5376 SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim);
5377 basepoints0 = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000;
5378 break;
5380 // Sacred Shield
5381 if (dummySpell->SpellFamilyFlags&0x0008000000000000LL)
5383 triggered_spell_id = 58597;
5384 target = this;
5385 break;
5387 // Righteous Vengeance
5388 if (dummySpell->SpellIconID == 3025)
5390 // 4 damage tick
5391 basepoints0 = triggerAmount*damage/400;
5392 triggered_spell_id = 61840;
5393 break;
5395 // Sheath of Light
5396 if (dummySpell->SpellIconID == 3030)
5398 // 4 healing tick
5399 basepoints0 = triggerAmount*damage/400;
5400 triggered_spell_id = 54203;
5401 break;
5403 switch(dummySpell->Id)
5405 // Judgement of Light
5406 case 20185:
5408 // Get judgement caster
5409 Unit *caster = triggeredByAura->GetCaster();
5410 if (!caster)
5411 return false;
5412 float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK);
5413 int32 holy = caster->SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) +
5414 caster->SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, this);
5415 basepoints0 = int32(ap*0.10f + 0.10f*holy);
5416 pVictim->CastCustomSpell(pVictim, 20267, &basepoints0, 0, 0, true, 0, triggeredByAura);
5417 return true;
5419 // Judgement of Wisdom
5420 case 20186:
5422 if (pVictim->getPowerType() == POWER_MANA)
5423 pVictim->CastSpell(pVictim, 20268, true, 0, triggeredByAura);
5424 return true;
5426 // Holy Power (Redemption Armor set)
5427 case 28789:
5429 if(!pVictim)
5430 return false;
5432 // Set class defined buff
5433 switch (pVictim->getClass())
5435 case CLASS_PALADIN:
5436 case CLASS_PRIEST:
5437 case CLASS_SHAMAN:
5438 case CLASS_DRUID:
5439 triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5440 break;
5441 case CLASS_MAGE:
5442 case CLASS_WARLOCK:
5443 triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5444 break;
5445 case CLASS_HUNTER:
5446 case CLASS_ROGUE:
5447 triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d.
5448 break;
5449 case CLASS_WARRIOR:
5450 triggered_spell_id = 28790; // Increases the friendly target's armor
5451 break;
5452 default:
5453 return false;
5455 break;
5457 // Seal of Vengeance (damage calc on apply aura)
5458 case 31801:
5460 if(effIndex != 0) // effect 1,2 used by seal unleashing code
5461 return false;
5463 triggered_spell_id = 31803;
5464 break;
5466 // Spiritual Attunement
5467 case 31785:
5468 case 33776:
5470 // if healed by another unit (pVictim)
5471 if(this == pVictim)
5472 return false;
5474 // heal amount
5475 basepoints0 = triggerAmount*damage/100;
5476 target = this;
5477 triggered_spell_id = 31786;
5478 break;
5480 // Seal of Blood do damage trigger
5481 case 31892:
5483 if (effIndex == 0) // 0 effect - is proc on enemy
5484 triggered_spell_id = 31893;
5485 else if (effIndex == 1) // 1 effect - is proc on self
5487 // add spell damage from prev effect (27%)
5488 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5489 basepoints0 = triggerAmount * damage / 100;
5490 target = this;
5491 triggered_spell_id = 32221;
5493 else
5494 return true;
5495 break;
5497 // Seal of the Martyr do damage trigger
5498 case 53720:
5500 if (effIndex == 0) // 0 effect - is proc on enemy
5501 triggered_spell_id = 53719;
5502 else if (effIndex == 1) // 1 effect - is proc on self
5504 // add spell damage from prev effect (27%)
5505 damage += CalculateDamage(BASE_ATTACK, false) * 27 / 100;
5506 basepoints0 = triggerAmount * damage / 100;
5507 target = this;
5508 triggered_spell_id = 53718;
5510 else
5511 return true;
5512 break;
5514 // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal)
5515 case 40470:
5517 if( !procSpell )
5518 return false;
5520 float chance;
5522 // Flash of light/Holy light
5523 if( procSpell->SpellFamilyFlags & 0x00000000C0000000LL)
5525 triggered_spell_id = 40471;
5526 chance = 15.f;
5528 // Judgement
5529 else if( procSpell->SpellFamilyFlags & 0x0000000000800000LL )
5531 triggered_spell_id = 40472;
5532 chance = 50.f;
5534 else
5535 return false;
5537 if (!roll_chance_f(chance))
5538 return false;
5540 break;
5542 // Glyph of Divinity
5543 case 54939:
5545 // Lookup base amount mana restore
5546 for (int i=0; i<3;i++)
5547 if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE)
5549 int32 mana = procSpell->EffectBasePoints[i];
5550 CastCustomSpell(this, 54986, 0, &mana, 0, true, castItem, triggeredByAura);
5551 break;
5553 return true;
5555 // Glyph of Flash of Light
5556 case 54936:
5558 triggered_spell_id = 54957;
5559 basepoints0 = triggerAmount*damage/100;
5560 break;
5562 // Glyph of Holy Light
5563 case 54937:
5565 triggered_spell_id = 54968;
5566 basepoints0 = triggerAmount*damage/100;
5567 break;
5570 break;
5572 case SPELLFAMILY_SHAMAN:
5574 switch(dummySpell->Id)
5576 // Totemic Power (The Earthshatterer set)
5577 case 28823:
5579 if( !pVictim )
5580 return false;
5582 // Set class defined buff
5583 switch (pVictim->getClass())
5585 case CLASS_PALADIN:
5586 case CLASS_PRIEST:
5587 case CLASS_SHAMAN:
5588 case CLASS_DRUID:
5589 triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d.
5590 break;
5591 case CLASS_MAGE:
5592 case CLASS_WARLOCK:
5593 triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d.
5594 break;
5595 case CLASS_HUNTER:
5596 case CLASS_ROGUE:
5597 triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d.
5598 break;
5599 case CLASS_WARRIOR:
5600 triggered_spell_id = 28827; // Increases the friendly target's armor
5601 break;
5602 default:
5603 return false;
5605 break;
5607 // Lesser Healing Wave (Totem of Flowing Water Relic)
5608 case 28849:
5610 target = this;
5611 triggered_spell_id = 28850;
5612 break;
5614 // Windfury Weapon (Passive) 1-5 Ranks
5615 case 33757:
5617 if(GetTypeId()!=TYPEID_PLAYER)
5618 return false;
5620 if(!castItem || !castItem->IsEquipped())
5621 return false;
5623 // custom cooldown processing case
5624 if( cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5625 return false;
5627 // Now amount of extra power stored in 1 effect of Enchant spell
5628 // Get it by item enchant id
5629 uint32 spellId;
5630 switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)))
5632 case 283: spellId = 8232; break; // 1 Rank
5633 case 284: spellId = 8235; break; // 2 Rank
5634 case 525: spellId = 10486; break; // 3 Rank
5635 case 1669:spellId = 16362; break; // 4 Rank
5636 case 2636:spellId = 25505; break; // 5 Rank
5637 case 3785:spellId = 58801; break; // 6 Rank
5638 case 3786:spellId = 58803; break; // 7 Rank
5639 case 3787:spellId = 58804; break; // 8 Rank
5640 default:
5642 sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)",
5643 castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id);
5644 return false;
5648 SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId);
5649 if(!windfurySpellEntry)
5651 sLog.outError("Unit::HandleDummyAuraProc: non existed spell id: %u (Windfury)",spellId);
5652 return false;
5655 int32 extra_attack_power = CalculateSpellDamage(windfurySpellEntry, 1, windfurySpellEntry->EffectBasePoints[1], pVictim);
5657 // Off-Hand case
5658 if ( castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
5660 // Value gained from additional AP
5661 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2);
5662 triggered_spell_id = 33750;
5664 // Main-Hand case
5665 else
5667 // Value gained from additional AP
5668 basepoints0 = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000);
5669 triggered_spell_id = 25504;
5672 // apply cooldown before cast to prevent processing itself
5673 if( cooldown )
5674 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5676 // Attack Twice
5677 for ( uint32 i = 0; i<2; ++i )
5678 CastCustomSpell(pVictim,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5680 return true;
5682 // Shaman Tier 6 Trinket
5683 case 40463:
5685 if( !procSpell )
5686 return false;
5688 float chance;
5689 if (procSpell->SpellFamilyFlags & 0x0000000000000001LL)
5691 triggered_spell_id = 40465; // Lightning Bolt
5692 chance = 15.f;
5694 else if (procSpell->SpellFamilyFlags & 0x0000000000000080LL)
5696 triggered_spell_id = 40465; // Lesser Healing Wave
5697 chance = 10.f;
5699 else if (procSpell->SpellFamilyFlags & 0x0000001000000000LL)
5701 triggered_spell_id = 40466; // Stormstrike
5702 chance = 50.f;
5704 else
5705 return false;
5707 if (!roll_chance_f(chance))
5708 return false;
5710 target = this;
5711 break;
5713 // Glyph of Healing Wave
5714 case 55440:
5716 // Not proc from self heals
5717 if (this==pVictim)
5718 return false;
5719 basepoints0 = triggerAmount * damage / 100;
5720 target = this;
5721 triggered_spell_id = 55533;
5722 break;
5724 // Spirit Hunt
5725 case 58877:
5727 // Cast on owner
5728 target = GetOwner();
5729 if(!target)
5730 return false;
5731 basepoints0 = triggerAmount * damage / 100;
5732 triggered_spell_id = 58879;
5733 break;
5736 // Ancestral Awakening
5737 if (dummySpell->SpellIconID == 3065)
5739 // TODO: frite dummy fot triggered spell
5740 triggered_spell_id = 52759;
5741 basepoints0 = triggerAmount * damage / 100;
5742 target = this;
5743 break;
5745 // Earth Shield
5746 if(dummySpell->SpellFamilyFlags & 0x0000040000000000LL)
5748 basepoints0 = triggerAmount;
5749 target = this;
5750 triggered_spell_id = 379;
5751 break;
5753 // Improved Water Shield
5754 if (dummySpell->SpellIconID == 2287)
5756 // Lesser Healing Wave need aditional 60% roll
5757 if (procSpell->SpellFamilyFlags & 0x0000000000000080LL && !roll_chance_i(60))
5758 return false;
5759 // lookup water shield
5760 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5761 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5763 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5764 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000002000000000LL)
5766 uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()];
5767 CastSpell(this, spell, true, castItem, triggeredByAura);
5768 if ((*itr)->DropAuraCharge())
5769 RemoveAurasDueToSpell((*itr)->GetId());
5770 return true;
5773 return false;
5774 break;
5776 // Lightning Overload
5777 if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura
5779 if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim )
5780 return false;
5782 // custom cooldown processing case
5783 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id))
5784 return false;
5786 uint32 spellId = 0;
5787 // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost
5788 switch (procSpell->Id)
5790 // Lightning Bolt
5791 case 403: spellId = 45284; break; // Rank 1
5792 case 529: spellId = 45286; break; // Rank 2
5793 case 548: spellId = 45287; break; // Rank 3
5794 case 915: spellId = 45288; break; // Rank 4
5795 case 943: spellId = 45289; break; // Rank 5
5796 case 6041: spellId = 45290; break; // Rank 6
5797 case 10391: spellId = 45291; break; // Rank 7
5798 case 10392: spellId = 45292; break; // Rank 8
5799 case 15207: spellId = 45293; break; // Rank 9
5800 case 15208: spellId = 45294; break; // Rank 10
5801 case 25448: spellId = 45295; break; // Rank 11
5802 case 25449: spellId = 45296; break; // Rank 12
5803 case 49237: spellId = 49239; break; // Rank 13
5804 case 49238: spellId = 49240; break; // Rank 14
5805 // Chain Lightning
5806 case 421: spellId = 45297; break; // Rank 1
5807 case 930: spellId = 45298; break; // Rank 2
5808 case 2860: spellId = 45299; break; // Rank 3
5809 case 10605: spellId = 45300; break; // Rank 4
5810 case 25439: spellId = 45301; break; // Rank 5
5811 case 25442: spellId = 45302; break; // Rank 6
5812 case 49268: spellId = 49270; break; // Rank 7
5813 case 49269: spellId = 49271; break; // Rank 8
5814 default:
5815 sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id);
5816 return false;
5818 // No thread generated mod
5819 // TODO: exist special flag in spell attributes for this, need found and use!
5820 SpellModifier *mod = new SpellModifier;
5821 mod->op = SPELLMOD_THREAT;
5822 mod->value = -100;
5823 mod->type = SPELLMOD_PCT;
5824 mod->spellId = dummySpell->Id;
5825 mod->mask = 0x0000000000000003LL;
5826 mod->mask2= 0LL;
5827 ((Player*)this)->AddSpellMod(mod, true);
5829 // Remove cooldown (Chain Lightning - have Category Recovery time)
5830 if (procSpell->SpellFamilyFlags & 0x0000000000000002LL)
5831 ((Player*)this)->RemoveSpellCooldown(spellId);
5833 CastSpell(pVictim, spellId, true, castItem, triggeredByAura);
5835 ((Player*)this)->AddSpellMod(mod, false);
5837 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5838 ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown);
5840 return true;
5842 // Static Shock
5843 if(dummySpell->SpellIconID == 3059)
5845 // lookup Lightning Shield
5846 AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL);
5847 for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr)
5849 if( (*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN &&
5850 (*itr)->GetSpellProto()->SpellFamilyFlags & 0x0000000000000400LL)
5852 uint32 spell = 0;
5853 switch ((*itr)->GetId())
5855 case 324: spell = 26364; break;
5856 case 325: spell = 26365; break;
5857 case 905: spell = 26366; break;
5858 case 945: spell = 26367; break;
5859 case 8134: spell = 26369; break;
5860 case 10431: spell = 26370; break;
5861 case 10432: spell = 26363; break;
5862 case 25469: spell = 26371; break;
5863 case 25472: spell = 26372; break;
5864 case 49280: spell = 49278; break;
5865 case 49281: spell = 49279; break;
5866 default:
5867 return false;
5869 CastSpell(this, spell, true, castItem, triggeredByAura);
5870 if ((*itr)->DropAuraCharge())
5871 RemoveAurasDueToSpell((*itr)->GetId());
5872 return true;
5875 return false;
5876 break;
5878 break;
5880 case SPELLFAMILY_DEATHKNIGHT:
5882 // Blood Aura
5883 if (dummySpell->SpellIconID == 2636)
5885 if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim))
5886 return false;
5887 basepoints0 = triggerAmount * damage / 100;
5888 triggered_spell_id = 53168;
5889 break;
5891 // Butchery
5892 if (dummySpell->SpellIconID == 2664)
5894 basepoints0 = triggerAmount;
5895 triggered_spell_id = 50163;
5896 target = this;
5897 break;
5899 // Dancing Rune Weapon
5900 if (dummySpell->Id == 49028)
5902 // 1 dummy aura for dismiss rune blade
5903 if (effIndex!=2)
5904 return false;
5905 // TODO: wite script for this "fights on its own, doing the same attacks"
5906 // NOTE: Trigger here on every attack and spell cast
5907 return false;
5909 // Mark of Blood
5910 if (dummySpell->Id == 49005)
5912 // TODO: need more info (cooldowns/PPM)
5913 triggered_spell_id = 50424;
5914 break;
5916 // Vendetta
5917 if (dummySpell->SpellFamilyFlags & 0x0000000000010000LL)
5919 basepoints0 = triggerAmount * GetMaxHealth() / 100;
5920 triggered_spell_id = 50181;
5921 target = this;
5922 break;
5924 // Necrosis
5925 if (dummySpell->SpellIconID == 2709)
5927 basepoints0 = triggerAmount * damage / 100;
5928 triggered_spell_id = 51460;
5929 break;
5931 // Runic Power Back on Snare/Root
5932 if (dummySpell->Id == 61257)
5934 // only for spells and hit/crit (trigger start always) and not start from self casted spells
5935 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
5936 return false;
5937 // Need snare or root mechanic
5938 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_ROOT)|(1<<MECHANIC_SNARE))))
5939 return false;
5940 triggered_spell_id = 61258;
5941 target = this;
5942 break;
5944 // Wandering Plague
5945 if (dummySpell->SpellIconID == 1614)
5947 if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim)))
5948 return false;
5949 basepoints0 = triggerAmount * damage / 100;
5950 triggered_spell_id = 50526;
5951 break;
5953 break;
5955 default:
5956 break;
5959 // processed charge only counting case
5960 if(!triggered_spell_id)
5961 return true;
5963 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
5965 if(!triggerEntry)
5967 sLog.outError("Unit::HandleDummyAuraProc: Spell %u have not existed triggered spell %u",dummySpell->Id,triggered_spell_id);
5968 return false;
5971 // default case
5972 if(!target || target!=this && !target->isAlive())
5973 return false;
5975 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
5976 return false;
5978 if(basepoints0)
5979 CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
5980 else
5981 CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura);
5983 if( cooldown && GetTypeId()==TYPEID_PLAYER )
5984 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
5986 return true;
5989 bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown)
5991 // Get triggered aura spell info
5992 SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto();
5994 // Basepoints of trigger aura
5995 int32 triggerAmount = triggeredByAura->GetModifier()->m_amount;
5997 // Set trigger spell id, target, custom basepoints
5998 uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()];
5999 Unit* target = NULL;
6000 int32 basepoints0 = 0;
6002 if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE)
6003 basepoints0 = triggerAmount;
6005 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6006 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6008 // Try handle uncnown trigger spells
6009 if (sSpellStore.LookupEntry(trigger_spell_id)==NULL)
6011 switch (auraSpellInfo->SpellFamilyName)
6013 case SPELLFAMILY_GENERIC:
6014 //if (auraSpellInfo->Id==59532) // Abandon Passengers on Poly
6015 //if (auraSpellInfo->Id==54775) // Abandon Vehicle on Poly
6016 //if (auraSpellInfo->Id==34082) // Advantaged State (DND)
6017 if (auraSpellInfo->Id == 23780) // Aegis of Preservation (Aegis of Preservation trinket)
6018 trigger_spell_id = 23781;
6019 //else if (auraSpellInfo->Id==43504) // Alterac Valley OnKill Proc Aura
6020 //else if (auraSpellInfo->Id == 48876) // Beast's Mark
6022 // trigger_spell_id = 48877;
6024 //else if (auraSpellInfo->Id == 59237) // Beast's Mark
6026 // trigger_spell_id = 59233;
6028 //else if (auraSpellInfo->Id==46939) // Black Bow of the Betrayer
6030 // trigger_spell_id = 29471; // gain mana
6031 // 27526; // drain mana if possible
6033 //else if (auraSpellInfo->Id==50844) // Blood Mirror
6034 //else if (auraSpellInfo->Id==54476) // Blood Presence
6035 //else if (auraSpellInfo->Id==50689) // Blood Presence (Rank 1)
6036 //else if (auraSpellInfo->Id==37030) // Chaotic Temperament
6037 //else if (auraSpellInfo->Id==52856) // Charge
6038 else if (auraSpellInfo->Id==43820) // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket)
6040 // Pct value stored in dummy
6041 basepoints0 = pVictim->GetCreateHealth() * auraSpellInfo->EffectBasePoints[1] / 100;
6042 target = pVictim;
6043 break;
6045 //else if (auraSpellInfo->Id==41248) // Consuming Strikes
6046 // trigger_spell_id = 41249;
6047 //else if (auraSpellInfo->Id==45205) // Copy Offhand Weapon
6048 //else if (auraSpellInfo->Id==57594) // Copy Ranged Weapon
6049 //else if (auraSpellInfo->Id==41054) // Copy Weapon
6050 // trigger_spell_id = 41055;
6051 //else if (auraSpellInfo->Id==45343) // Dark Flame Aura
6052 //else if (auraSpellInfo->Id==47300) // Dark Flame Aura
6053 else if (auraSpellInfo->Id==57345) // Darkmoon Card: Greatness
6055 float stat = 0.0f;
6056 // strength
6057 if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); }
6058 // agility
6059 if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); }
6060 // intellect
6061 if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);}
6062 // spirit
6063 if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235;stat = GetStat(STAT_SPIRIT); }
6065 //else if (auraSpellInfo->Id==31255) // Deadly Swiftness (Rank 1)
6066 //else if (auraSpellInfo->Id==5301) // Defensive State (DND)
6067 //else if (auraSpellInfo->Id==13358) // Defensive State (DND)
6068 //else if (auraSpellInfo->Id==16092) // Defensive State (DND)
6069 //else if (auraSpellInfo->Id==24949) // Defensive State 2 (DND)
6070 //else if (auraSpellInfo->Id==40329) // Demo Shout Sensor
6071 else if (auraSpellInfo->Id == 33896) // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher)
6072 trigger_spell_id = 33898;
6073 //else if (auraSpellInfo->Id==18943) // Double Attack
6074 //else if (auraSpellInfo->Id==19194) // Double Attack
6075 //else if (auraSpellInfo->Id==19817) // Double Attack
6076 //else if (auraSpellInfo->Id==19818) // Double Attack
6077 //else if (auraSpellInfo->Id==22835) // Drunken Rage
6078 // trigger_spell_id = 14822;
6080 else if (auraSpellInfo->SpellIconID==191) // Elemental Response
6082 switch (auraSpellInfo->Id && auraSpellInfo->AttributesEx==0)
6084 case 34191:
6085 case 34329:
6086 case 34524:
6087 case 34582:
6088 case 36733:
6089 break;
6090 default:
6091 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Elemental Response",auraSpellInfo->Id);
6092 return false;
6094 //This generic aura self-triggers a different spell for each school of magic that lands on the wearer:
6095 switch (procSpell->School)
6097 case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break;
6098 case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break;
6099 case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break;
6100 case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break;
6101 case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break;
6102 case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break;
6103 case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break;
6104 default:
6105 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u Elemental Response wrong school",auraSpellInfo->Id);
6106 return false;
6110 //else if (auraSpellInfo->Id==40364) // Entangling Roots Sensor
6111 //else if (auraSpellInfo->Id==33207) // Gossip NPC Periodic - Fidget
6112 //else if (auraSpellInfo->Id==50051) // Ethereal Pet Aura
6113 //else if (auraSpellInfo->Id==35321) // Gushing Wound
6114 //else if (auraSpellInfo->Id==38363) // Gushing Wound
6115 //else if (auraSpellInfo->Id==39215) // Gushing Wound
6116 //else if (auraSpellInfo->Id==44527) // Hate Monster (Spar Buddy) (30 sec)
6117 //else if (auraSpellInfo->Id==44819) // Hate Monster (Spar Buddy) (>30% Health)
6118 //else if (auraSpellInfo->Id==44526) // Hate Monster (Spar) (30 sec)
6119 //else if (auraSpellInfo->Id==44820) // Hate Monster (Spar) (<30%)
6120 //else if (auraSpellInfo->Id==49059) // Horde, Hate Monster (Spar Buddy) (>30% Health)
6121 //else if (auraSpellInfo->Id==40250) // Improved Duration
6122 //else if (auraSpellInfo->Id==59288) // Infra-Green Shield
6123 //else if (auraSpellInfo->Id==54072) // Knockback Ball Passive
6124 else if (auraSpellInfo->Id==27522 || auraSpellInfo->Id==40336)
6125 // Mana Drain Trigger
6127 // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target.
6128 if (this && this->isAlive())
6129 CastSpell(this, 29471, true, castItem, triggeredByAura);
6130 if (pVictim && pVictim->isAlive())
6131 CastSpell(pVictim, 27526, true, castItem, triggeredByAura);
6132 return true;
6134 //else if (auraSpellInfo->Id==55580) // Mana Link
6135 //else if (auraSpellInfo->Id==45903) // Offensive State
6136 //else if (auraSpellInfo->Id==44326) // Pure Energy Passive
6137 //else if (auraSpellInfo->Id==43453) // Rune Ward
6138 //else if (auraSpellInfo->Id== 7137) // Shadow Charge (Rank 1)
6139 //else if (auraSpellInfo->Id==36576) // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger
6140 //else if (auraSpellInfo->Id==34783) // Spell Reflection
6141 //else if (auraSpellInfo->Id==36096) // Spell Reflection
6142 //else if (auraSpellInfo->Id==57587) // Steal Ranged ()
6143 //else if (auraSpellInfo->Id==36207) // Steal Weapon
6144 //else if (auraSpellInfo->Id== 7377) // Take Immune Periodic Damage <Not Working>
6145 //else if (auraSpellInfo->Id==35205) // Vanish
6146 //else if (auraSpellInfo->Id==42730) // Woe Strike
6147 //else if (auraSpellInfo->Id==59735) // Woe Strike
6148 //else if (auraSpellInfo->Id==46146) // [PH] Ahune Spanky Hands
6149 break;
6150 case SPELLFAMILY_MAGE:
6151 if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed
6153 switch (auraSpellInfo->Id)
6155 case 31641: // Rank 1
6156 case 31642: // Rank 2
6157 trigger_spell_id = 31643;
6158 break;
6159 default:
6160 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blazing Speed",auraSpellInfo->Id);
6161 return false;
6164 break;
6165 case SPELLFAMILY_WARRIOR:
6166 if (auraSpellInfo->Id == 50421) // Scent of Blood
6167 trigger_spell_id = 50422;
6168 break;
6169 case SPELLFAMILY_WARLOCK:
6171 // Pyroclasm
6172 if (auraSpellInfo->SpellIconID == 1137)
6174 if(!pVictim || !pVictim->isAlive() || pVictim == this || procSpell == NULL)
6175 return false;
6176 // Calculate spell tick count for spells
6177 uint32 tick = 1; // Default tick = 1
6179 // Hellfire have 15 tick
6180 if (procSpell->SpellFamilyFlags&0x0000000000000040LL)
6181 tick = 15;
6182 // Rain of Fire have 4 tick
6183 else if (procSpell->SpellFamilyFlags&0x0000000000000020LL)
6184 tick = 4;
6185 else
6186 return false;
6188 // Calculate chance = baseChance / tick
6189 float chance = 0;
6190 switch (auraSpellInfo->Id)
6192 case 18096: chance = 13.0f / tick; break;
6193 case 18073: chance = 26.0f / tick; break;
6195 // Roll chance
6196 if (!roll_chance_f(chance))
6197 return false;
6199 trigger_spell_id = 18093;
6201 // Drain Soul
6202 else if (auraSpellInfo->SpellFamilyFlags & 0x0000000000004000LL)
6204 Unit::AuraList const& mAddFlatModifier = GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER);
6205 for(Unit::AuraList::const_iterator i = mAddFlatModifier.begin(); i != mAddFlatModifier.end(); ++i)
6207 if ((*i)->GetModifier()->m_miscvalue == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113)
6209 int32 value2 = CalculateSpellDamage((*i)->GetSpellProto(),2,(*i)->GetSpellProto()->EffectBasePoints[2],this);
6210 // Drain Soul
6211 CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura);
6212 break;
6215 // Not remove charge (aura removed on death in any cases)
6216 // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura
6217 return false;
6219 // Nether Protection
6220 else if (auraSpellInfo->SpellIconID == 1985)
6222 if (!procSpell)
6223 return false;
6224 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6226 case SPELL_SCHOOL_NORMAL:
6227 case SPELL_SCHOOL_HOLY:
6228 return false; // ignore
6229 case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break;
6230 case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break;
6231 case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break;
6232 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break;
6233 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6234 default:
6235 return false;
6238 break;
6240 case SPELLFAMILY_PRIEST:
6242 // Greater Heal Refund
6243 if (auraSpellInfo->Id==37594)
6244 trigger_spell_id = 37595;
6245 // Blessed Recovery
6246 else if (auraSpellInfo->SpellIconID == 1875)
6248 switch (auraSpellInfo->Id)
6250 case 27811: trigger_spell_id = 27813; break;
6251 case 27815: trigger_spell_id = 27817; break;
6252 case 27816: trigger_spell_id = 27818; break;
6253 default:
6254 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id);
6255 return false;
6257 basepoints0 = damage * triggerAmount / 100 / 3;
6258 target = this;
6260 break;
6262 case SPELLFAMILY_DRUID:
6264 // Druid Forms Trinket
6265 if (auraSpellInfo->Id==37336)
6267 switch(m_form)
6269 case FORM_NONE: trigger_spell_id = 37344;break;
6270 case FORM_CAT: trigger_spell_id = 37341;break;
6271 case FORM_BEAR:
6272 case FORM_DIREBEAR: trigger_spell_id = 37340;break;
6273 case FORM_TREE: trigger_spell_id = 37342;break;
6274 case FORM_MOONKIN: trigger_spell_id = 37343;break;
6275 default:
6276 return false;
6279 //else if (auraSpellInfo->Id==40363)// Entangling Roots ()
6280 // trigger_spell_id = ????;
6281 // Leader of the Pack
6282 else if (auraSpellInfo->Id == 24932)
6284 if (triggerAmount == 0)
6285 return false;
6286 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6287 trigger_spell_id = 34299;
6289 break;
6291 case SPELLFAMILY_HUNTER:
6292 break;
6293 case SPELLFAMILY_PALADIN:
6296 // Blessed Life
6297 if (auraSpellInfo->SpellIconID == 2137)
6299 switch (auraSpellInfo->Id)
6301 case 31828: // Rank 1
6302 case 31829: // Rank 2
6303 case 31830: // Rank 3
6304 break;
6305 default:
6306 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u miss posibly Blessed Life", auraSpellInfo->Id);
6307 return false;
6311 // Healing Discount
6312 if (auraSpellInfo->Id==37705)
6314 trigger_spell_id = 37706;
6315 target = this;
6317 // Soul Preserver
6318 if (auraSpellInfo->Id==60510)
6320 trigger_spell_id = 60515;
6321 target = this;
6323 // Illumination
6324 else if (auraSpellInfo->SpellIconID==241)
6326 if(!procSpell)
6327 return false;
6328 // procspell is triggered spell but we need mana cost of original casted spell
6329 uint32 originalSpellId = procSpell->Id;
6330 // Holy Shock heal
6331 if(procSpell->SpellFamilyFlags & 0x0001000000000000LL)
6333 switch(procSpell->Id)
6335 case 25914: originalSpellId = 20473; break;
6336 case 25913: originalSpellId = 20929; break;
6337 case 25903: originalSpellId = 20930; break;
6338 case 27175: originalSpellId = 27174; break;
6339 case 33074: originalSpellId = 33072; break;
6340 case 48820: originalSpellId = 48824; break;
6341 case 48821: originalSpellId = 48825; break;
6342 default:
6343 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in HShock",procSpell->Id);
6344 return false;
6347 SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId);
6348 if(!originalSpell)
6350 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u unknown but selected as original in Illu",originalSpellId);
6351 return false;
6353 // percent stored in effect 1 (class scripts) base points
6354 int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100;
6355 basepoints0 = cost*auraSpellInfo->CalculateSimpleValue(1)/100;
6356 trigger_spell_id = 20272;
6357 target = this;
6359 // Lightning Capacitor
6360 else if (auraSpellInfo->Id==37657)
6362 if(!pVictim || !pVictim->isAlive())
6363 return false;
6364 // stacking
6365 CastSpell(this, 37658, true, NULL, triggeredByAura);
6367 Aura * dummy = GetDummyAura(37658);
6368 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6369 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6370 return false;
6372 RemoveAurasDueToSpell(37658);
6373 trigger_spell_id = 37661;
6374 target = pVictim;
6376 // Thunder Capacitor
6377 else if (auraSpellInfo->Id == 54841)
6379 if(!pVictim || !pVictim->isAlive())
6380 return false;
6381 // stacking
6382 CastSpell(this, 54842, true, NULL, triggeredByAura);
6384 // counting
6385 Aura * dummy = GetDummyAura(54842);
6386 // release at 3 aura in stack (cont contain in basepoint of trigger aura)
6387 if(!dummy || dummy->GetStackAmount() < triggerAmount)
6388 return false;
6390 RemoveAurasDueToSpell(54842);
6391 trigger_spell_id = 54843;
6392 target = pVictim;
6394 break;
6396 case SPELLFAMILY_SHAMAN:
6398 // Lightning Shield (overwrite non existing triggered spell call in spell.dbc
6399 if(auraSpellInfo->SpellFamilyFlags & 0x0000000000000400)
6401 switch(auraSpellInfo->Id)
6403 case 324: // Rank 1
6404 trigger_spell_id = 26364; break;
6405 case 325: // Rank 2
6406 trigger_spell_id = 26365; break;
6407 case 905: // Rank 3
6408 trigger_spell_id = 26366; break;
6409 case 945: // Rank 4
6410 trigger_spell_id = 26367; break;
6411 case 8134: // Rank 5
6412 trigger_spell_id = 26369; break;
6413 case 10431: // Rank 6
6414 trigger_spell_id = 26370; break;
6415 case 10432: // Rank 7
6416 trigger_spell_id = 26363; break;
6417 case 25469: // Rank 8
6418 trigger_spell_id = 26371; break;
6419 case 25472: // Rank 9
6420 trigger_spell_id = 26372; break;
6421 case 49280: // Rank 10
6422 trigger_spell_id = 49278; break;
6423 case 49281: // Rank 11
6424 trigger_spell_id = 49279; break;
6425 default:
6426 sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in LShield", auraSpellInfo->Id);
6427 return false;
6430 // Lightning Shield (The Ten Storms set)
6431 else if (auraSpellInfo->Id == 23551)
6433 trigger_spell_id = 23552;
6434 target = pVictim;
6436 // Damage from Lightning Shield (The Ten Storms set)
6437 else if (auraSpellInfo->Id == 23552)
6438 trigger_spell_id = 27635;
6439 // Mana Surge (The Earthfury set)
6440 else if (auraSpellInfo->Id == 23572)
6442 if(!procSpell)
6443 return false;
6444 basepoints0 = procSpell->manaCost * 35 / 100;
6445 trigger_spell_id = 23571;
6446 target = this;
6448 // Nature's Guardian
6449 else if (auraSpellInfo->SpellIconID == 2013)
6451 // Check health condition - should drop to less 30% (damage deal after this!)
6452 if (!(10*(int32(GetHealth() - damage)) < 3 * GetMaxHealth()))
6453 return false;
6455 if(pVictim && pVictim->isAlive())
6456 pVictim->getThreatManager().modifyThreatPercent(this,-10);
6458 basepoints0 = triggerAmount * GetMaxHealth() / 100;
6459 trigger_spell_id = 31616;
6460 target = this;
6462 break;
6464 case SPELLFAMILY_DEATHKNIGHT:
6466 // Acclimation
6467 if (auraSpellInfo->SpellIconID == 1930)
6469 if (!procSpell)
6470 return false;
6471 switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell)))
6473 case SPELL_SCHOOL_NORMAL:
6474 return false; // ignore
6475 case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break;
6476 case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break;
6477 case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break;
6478 case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break;
6479 case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break;
6480 case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break;
6481 default:
6482 return false;
6485 // Blood Presence
6486 else if (auraSpellInfo->Id == 48266)
6488 if (GetTypeId() != TYPEID_PLAYER)
6489 return false;
6490 if (!((Player*)this)->isHonorOrXPTarget(pVictim))
6491 return false;
6492 trigger_spell_id = 50475;
6493 basepoints0 = damage * triggerAmount / 100;
6495 break;
6497 default:
6498 break;
6502 // All ok. Check current trigger spell
6503 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id);
6504 if ( triggerEntry == NULL )
6506 // Not cast unknown spell
6507 // sLog.outError("Unit::HandleProcTriggerSpell: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex());
6508 return false;
6511 // not allow proc extra attack spell at extra attack
6512 if( m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6513 return false;
6515 // Costum requirements (not listed in procEx) Warning! damage dealing after this
6516 // Custom triggered spells
6517 switch (auraSpellInfo->Id)
6519 // Persistent Shield (Scarab Brooch trinket)
6520 // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect)
6521 case 26467:
6523 basepoints0 = damage * 15 / 100;
6524 target = pVictim;
6525 trigger_spell_id = 26470;
6526 break;
6528 // Cheat Death
6529 case 28845:
6531 // When your health drops below 20% ....
6532 if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5)
6533 return false;
6534 break;
6536 // Deadly Swiftness (Rank 1)
6537 case 31255:
6539 // whenever you deal damage to a target who is below 20% health.
6540 if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5)
6541 return false;
6543 target = this;
6544 trigger_spell_id = 22588;
6546 // Greater Heal Refund (Avatar Raiment set)
6547 case 37594:
6549 // Not give if target alredy have full health
6550 if (pVictim->GetHealth() == pVictim->GetMaxHealth())
6551 return false;
6552 // If your Greater Heal brings the target to full health, you gain $37595s1 mana.
6553 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6554 return false;
6555 break;
6557 // Bonus Healing (Crystal Spire of Karabor mace)
6558 case 40971:
6560 // If your target is below $s1% health
6561 if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100)
6562 return false;
6563 break;
6565 // Evasive Maneuvers (Commendation of Kael`thas trinket)
6566 case 45057:
6568 // reduce you below $s1% health
6569 if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100)
6570 return false;
6571 break;
6573 // Rapid Recuperation
6574 case 53228:
6575 case 53232:
6577 // This effect only from Rapid Fire (ability cast)
6578 if (!(procSpell->SpellFamilyFlags & 0x0000000000000020LL))
6579 return false;
6580 break;
6584 // Costum basepoints/target for exist spell
6585 // dummy basepoints or other customs
6586 switch(trigger_spell_id)
6588 // Cast positive spell on enemy target
6589 case 7099: // Curse of Mending
6590 case 39647: // Curse of Mending
6591 case 29494: // Temptation
6592 case 20233: // Improved Lay on Hands (cast on target)
6594 target = pVictim;
6595 break;
6597 // Combo points add triggers (need add combopoint only for main tatget, and after possible combopoints reset)
6598 case 15250: // Rogue Setup
6600 if(!pVictim || pVictim != getVictim()) // applied only for main target
6601 return false;
6602 break; // continue normal case
6604 // Finish movies that add combo
6605 case 14189: // Seal Fate (Netherblade set)
6606 case 14157: // Ruthlessness
6608 // Need add combopoint AFTER finish movie (or they dropped in finish phase)
6609 break;
6611 // Bloodthirst (($m/100)% of max health)
6612 case 23880:
6614 basepoints0 = int32(GetMaxHealth() * triggerAmount / 100);
6615 break;
6617 // Shamanistic Rage triggered spell
6618 case 30824:
6620 basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100);
6621 break;
6623 // Enlightenment (trigger only from mana cost spells)
6624 case 35095:
6626 if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0)
6627 return false;
6628 break;
6630 // Brain Freeze
6631 case 57761:
6633 if(!procSpell)
6634 return false;
6635 // For trigger from Blizzard need exist Improved Blizzard
6636 if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && procSpell->SpellFamilyFlags & 0x0000000000000080LL)
6638 bool found = false;
6639 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
6640 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
6642 int32 script = (*i)->GetModifier()->m_miscvalue;
6643 if(script==836 || script==988 || script==989)
6645 found=true;
6646 break;
6649 if(!found)
6650 return false;
6652 break;
6654 // Astral Shift
6655 case 52179:
6657 if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim)
6658 return false;
6660 // Need stun, fear or silence mechanic
6661 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_SILENCE)|(1<<MECHANIC_STUN)|(1<<MECHANIC_FEAR))))
6662 return false;
6663 break;
6665 // Burning Determination
6666 case 54748:
6668 if(!procSpell)
6669 return false;
6670 // Need Interrupt or Silenced mechanic
6671 if (!(GetAllSpellMechanicMask(procSpell) & ((1<<MECHANIC_INTERRUPT)|(1<<MECHANIC_SILENCE))))
6672 return false;
6673 break;
6675 // Lock and Load
6676 case 56453:
6678 // Proc only from trap activation (from periodic proc another aura of this spell)
6679 if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !roll_chance_i(triggerAmount))
6680 return false;
6681 break;
6685 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id))
6686 return false;
6688 // try detect target manually if not set
6689 if ( target == NULL )
6690 target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim;
6692 // default case
6693 if(!target || target!=this && !target->isAlive())
6694 return false;
6696 if(basepoints0)
6697 CastCustomSpell(target,trigger_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura);
6698 else
6699 CastSpell(target,trigger_spell_id,true,castItem,triggeredByAura);
6701 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6702 ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown);
6704 return true;
6707 bool Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 damage, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 cooldown)
6709 int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue;
6711 if(!pVictim || !pVictim->isAlive())
6712 return false;
6714 Item* castItem = triggeredByAura->GetCastItemGUID() && GetTypeId()==TYPEID_PLAYER
6715 ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGUID()) : NULL;
6717 uint32 triggered_spell_id = 0;
6719 switch(scriptId)
6721 case 836: // Improved Blizzard (Rank 1)
6723 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6724 return false;
6725 triggered_spell_id = 12484;
6726 break;
6728 case 988: // Improved Blizzard (Rank 2)
6730 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6731 return false;
6732 triggered_spell_id = 12485;
6733 break;
6735 case 989: // Improved Blizzard (Rank 3)
6737 if (!procSpell || procSpell->SpellVisual[0]!=9487)
6738 return false;
6739 triggered_spell_id = 12486;
6740 break;
6742 case 4086: // Improved Mend Pet (Rank 1)
6743 case 4087: // Improved Mend Pet (Rank 2)
6745 int32 chance = triggeredByAura->GetSpellProto()->EffectBasePoints[triggeredByAura->GetEffIndex()];
6746 if(!roll_chance_i(chance))
6747 return false;
6749 triggered_spell_id = 24406;
6750 break;
6752 case 4533: // Dreamwalker Raiment 2 pieces bonus
6754 // Chance 50%
6755 if (!roll_chance_i(50))
6756 return false;
6758 switch (pVictim->getPowerType())
6760 case POWER_MANA: triggered_spell_id = 28722; break;
6761 case POWER_RAGE: triggered_spell_id = 28723; break;
6762 case POWER_ENERGY: triggered_spell_id = 28724; break;
6763 default:
6764 return false;
6766 break;
6768 case 4537: // Dreamwalker Raiment 6 pieces bonus
6769 triggered_spell_id = 28750; // Blessing of the Claw
6770 break;
6771 case 5497: // Improved Mana Gems (Serpent-Coil Braid)
6772 triggered_spell_id = 37445; // Mana Surge
6773 break;
6774 case 8152: // Serendipity
6776 // if heal your target over maximum health
6777 if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth())
6778 return false;
6779 int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100;
6780 int32 basepoints0 = cost * triggeredByAura->GetModifier()->m_amount/100;
6781 CastCustomSpell(this, 47762, &basepoints0, 0, 0, true, 0, triggeredByAura);
6782 return true;
6786 // not processed
6787 if(!triggered_spell_id)
6788 return false;
6790 // standard non-dummy case
6791 SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id);
6793 if(!triggerEntry)
6795 sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId);
6796 return false;
6799 if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id))
6800 return false;
6802 CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura);
6804 if( cooldown && GetTypeId()==TYPEID_PLAYER )
6805 ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown);
6807 return true;
6810 void Unit::setPowerType(Powers new_powertype)
6812 SetByteValue(UNIT_FIELD_BYTES_0, 3, new_powertype);
6814 if(GetTypeId() == TYPEID_PLAYER)
6816 if(((Player*)this)->GetGroup())
6817 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POWER_TYPE);
6819 else if(((Creature*)this)->isPet())
6821 Pet *pet = ((Pet*)this);
6822 if(pet->isControlled())
6824 Unit *owner = GetOwner();
6825 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
6826 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_POWER_TYPE);
6830 switch(new_powertype)
6832 default:
6833 case POWER_MANA:
6834 break;
6835 case POWER_RAGE:
6836 SetMaxPower(POWER_RAGE,GetCreatePowers(POWER_RAGE));
6837 SetPower( POWER_RAGE,0);
6838 break;
6839 case POWER_FOCUS:
6840 SetMaxPower(POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6841 SetPower( POWER_FOCUS,GetCreatePowers(POWER_FOCUS));
6842 break;
6843 case POWER_ENERGY:
6844 SetMaxPower(POWER_ENERGY,GetCreatePowers(POWER_ENERGY));
6845 SetPower( POWER_ENERGY,0);
6846 break;
6847 case POWER_HAPPINESS:
6848 SetMaxPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6849 SetPower(POWER_HAPPINESS,GetCreatePowers(POWER_HAPPINESS));
6850 break;
6854 FactionTemplateEntry const* Unit::getFactionTemplateEntry() const
6856 FactionTemplateEntry const* entry = sFactionTemplateStore.LookupEntry(getFaction());
6857 if(!entry)
6859 static uint64 guid = 0; // prevent repeating spam same faction problem
6861 if(GetGUID() != guid)
6863 if(GetTypeId() == TYPEID_PLAYER)
6864 sLog.outError("Player %s have invalid faction (faction template id) #%u", ((Player*)this)->GetName(), getFaction());
6865 else
6866 sLog.outError("Creature (template id: %u) have invalid faction (faction template id) #%u", ((Creature*)this)->GetCreatureInfo()->Entry, getFaction());
6867 guid = GetGUID();
6870 return entry;
6873 bool Unit::IsHostileTo(Unit const* unit) const
6875 // always non-hostile to self
6876 if(unit==this)
6877 return false;
6879 // always non-hostile to GM in GM mode
6880 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6881 return false;
6883 // always hostile to enemy
6884 if(getVictim()==unit || unit->getVictim()==this)
6885 return true;
6887 // test pet/charm masters instead pers/charmeds
6888 Unit const* testerOwner = GetCharmerOrOwner();
6889 Unit const* targetOwner = unit->GetCharmerOrOwner();
6891 // always hostile to owner's enemy
6892 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
6893 return true;
6895 // always hostile to enemy owner
6896 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
6897 return true;
6899 // always hostile to owner of owner's enemy
6900 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
6901 return true;
6903 Unit const* tester = testerOwner ? testerOwner : this;
6904 Unit const* target = targetOwner ? targetOwner : unit;
6906 // always non-hostile to target with common owner, or to owner/pet
6907 if(tester==target)
6908 return false;
6910 // special cases (Duel, etc)
6911 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
6913 Player const* pTester = (Player const*)tester;
6914 Player const* pTarget = (Player const*)target;
6916 // Duel
6917 if(pTester->duel && pTester->duel->opponent == pTarget && pTester->duel->startTime != 0)
6918 return true;
6920 // Group
6921 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
6922 return false;
6924 // Sanctuary
6925 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
6926 return false;
6928 // PvP FFA state
6929 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))
6930 return true;
6932 //= PvP states
6933 // Green/Blue (can't attack)
6934 if(pTester->GetTeam()==pTarget->GetTeam())
6935 return false;
6937 // Red (can attack) if true, Blue/Yellow (can't attack) in another case
6938 return pTester->IsPvP() && pTarget->IsPvP();
6941 // faction base cases
6942 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
6943 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
6944 if(!tester_faction || !target_faction)
6945 return false;
6947 if(target->isAttackingPlayer() && tester->IsContestedGuard())
6948 return true;
6950 // PvC forced reaction and reputation case
6951 if(tester->GetTypeId()==TYPEID_PLAYER)
6953 // forced reaction
6954 if(target_faction->faction)
6956 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
6957 return *force <= REP_HOSTILE;
6959 // if faction have reputation then hostile state for tester at 100% dependent from at_war state
6960 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
6961 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
6962 return (factionState->Flags & FACTION_FLAG_AT_WAR);
6965 // CvP forced reaction and reputation case
6966 else if(target->GetTypeId()==TYPEID_PLAYER)
6968 // forced reaction
6969 if(tester_faction->faction)
6971 if(ReputationRank const* force = ((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
6972 return *force <= REP_HOSTILE;
6974 // apply reputation state
6975 FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction);
6976 if(raw_tester_faction && raw_tester_faction->reputationListID >=0 )
6977 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) <= REP_HOSTILE;
6981 // common faction based case (CvC,PvC,CvP)
6982 return tester_faction->IsHostileTo(*target_faction);
6985 bool Unit::IsFriendlyTo(Unit const* unit) const
6987 // always friendly to self
6988 if(unit==this)
6989 return true;
6991 // always friendly to GM in GM mode
6992 if(unit->GetTypeId()==TYPEID_PLAYER && ((Player const*)unit)->isGameMaster())
6993 return true;
6995 // always non-friendly to enemy
6996 if(getVictim()==unit || unit->getVictim()==this)
6997 return false;
6999 // test pet/charm masters instead pers/charmeds
7000 Unit const* testerOwner = GetCharmerOrOwner();
7001 Unit const* targetOwner = unit->GetCharmerOrOwner();
7003 // always non-friendly to owner's enemy
7004 if(testerOwner && (testerOwner->getVictim()==unit || unit->getVictim()==testerOwner))
7005 return false;
7007 // always non-friendly to enemy owner
7008 if(targetOwner && (getVictim()==targetOwner || targetOwner->getVictim()==this))
7009 return false;
7011 // always non-friendly to owner of owner's enemy
7012 if(testerOwner && targetOwner && (testerOwner->getVictim()==targetOwner || targetOwner->getVictim()==testerOwner))
7013 return false;
7015 Unit const* tester = testerOwner ? testerOwner : this;
7016 Unit const* target = targetOwner ? targetOwner : unit;
7018 // always friendly to target with common owner, or to owner/pet
7019 if(tester==target)
7020 return true;
7022 // special cases (Duel)
7023 if(tester->GetTypeId()==TYPEID_PLAYER && target->GetTypeId()==TYPEID_PLAYER)
7025 Player const* pTester = (Player const*)tester;
7026 Player const* pTarget = (Player const*)target;
7028 // Duel
7029 if(pTester->duel && pTester->duel->opponent == target && pTester->duel->startTime != 0)
7030 return false;
7032 // Group
7033 if(pTester->GetGroup() && pTester->GetGroup()==pTarget->GetGroup())
7034 return true;
7036 // Sanctuary
7037 if(pTarget->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY) && pTester->HasByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY))
7038 return true;
7040 // PvP FFA state
7041 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))
7042 return false;
7044 //= PvP states
7045 // Green/Blue (non-attackable)
7046 if(pTester->GetTeam()==pTarget->GetTeam())
7047 return true;
7049 // Blue (friendly/non-attackable) if not PVP, or Yellow/Red in another case (attackable)
7050 return !pTarget->IsPvP();
7053 // faction base cases
7054 FactionTemplateEntry const*tester_faction = tester->getFactionTemplateEntry();
7055 FactionTemplateEntry const*target_faction = target->getFactionTemplateEntry();
7056 if(!tester_faction || !target_faction)
7057 return false;
7059 if(target->isAttackingPlayer() && tester->IsContestedGuard())
7060 return false;
7062 // PvC forced reaction and reputation case
7063 if(tester->GetTypeId()==TYPEID_PLAYER)
7065 // forced reaction
7066 if(target_faction->faction)
7068 if(ReputationRank const* force =((Player*)tester)->GetReputationMgr().GetForcedRankIfAny(target_faction))
7069 return *force >= REP_FRIENDLY;
7071 // if faction have reputation then friendly state for tester at 100% dependent from at_war state
7072 if(FactionEntry const* raw_target_faction = sFactionStore.LookupEntry(target_faction->faction))
7073 if(FactionState const* factionState = ((Player*)tester)->GetReputationMgr().GetState(raw_target_faction))
7074 return !(factionState->Flags & FACTION_FLAG_AT_WAR);
7077 // CvP forced reaction and reputation case
7078 else if(target->GetTypeId()==TYPEID_PLAYER)
7080 // forced reaction
7081 if(tester_faction->faction)
7083 if(ReputationRank const* force =((Player*)target)->GetReputationMgr().GetForcedRankIfAny(tester_faction))
7084 return *force >= REP_FRIENDLY;
7086 // apply reputation state
7087 if(FactionEntry const* raw_tester_faction = sFactionStore.LookupEntry(tester_faction->faction))
7088 if(raw_tester_faction->reputationListID >=0 )
7089 return ((Player const*)target)->GetReputationMgr().GetRank(raw_tester_faction) >= REP_FRIENDLY;
7093 // common faction based case (CvC,PvC,CvP)
7094 return tester_faction->IsFriendlyTo(*target_faction);
7097 bool Unit::IsHostileToPlayers() const
7099 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7100 if(!my_faction || !my_faction->faction)
7101 return false;
7103 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7104 if(raw_faction && raw_faction->reputationListID >=0 )
7105 return false;
7107 return my_faction->IsHostileToPlayers();
7110 bool Unit::IsNeutralToAll() const
7112 FactionTemplateEntry const* my_faction = getFactionTemplateEntry();
7113 if(!my_faction || !my_faction->faction)
7114 return true;
7116 FactionEntry const* raw_faction = sFactionStore.LookupEntry(my_faction->faction);
7117 if(raw_faction && raw_faction->reputationListID >=0 )
7118 return false;
7120 return my_faction->IsNeutralToAll();
7123 bool Unit::Attack(Unit *victim, bool meleeAttack)
7125 if(!victim || victim == this)
7126 return false;
7128 // dead units can neither attack nor be attacked
7129 if(!isAlive() || !victim->isAlive())
7130 return false;
7132 // player cannot attack in mount state
7133 if(GetTypeId()==TYPEID_PLAYER && IsMounted())
7134 return false;
7136 // nobody can attack GM in GM-mode
7137 if(victim->GetTypeId()==TYPEID_PLAYER)
7139 if(((Player*)victim)->isGameMaster())
7140 return false;
7142 else
7144 if(((Creature*)victim)->IsInEvadeMode())
7145 return false;
7148 // remove SPELL_AURA_MOD_UNATTACKABLE at attack (in case non-interruptible spells stun aura applied also that not let attack)
7149 if(HasAuraType(SPELL_AURA_MOD_UNATTACKABLE))
7150 RemoveSpellsCausingAura(SPELL_AURA_MOD_UNATTACKABLE);
7152 // in fighting already
7153 if (m_attacking)
7155 if (m_attacking == victim)
7157 // switch to melee attack from ranged/magic
7158 if( meleeAttack && !hasUnitState(UNIT_STAT_MELEE_ATTACKING) )
7160 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7161 SendAttackStart(victim);
7162 return true;
7164 return false;
7167 // remove old target data
7168 AttackStop(true);
7170 // new battle
7171 else
7173 // set position before any AI calls/assistance
7174 if(GetTypeId()==TYPEID_UNIT)
7175 ((Creature*)this)->SetCombatStartPosition(GetPositionX(), GetPositionY(), GetPositionZ());
7178 //Set our target
7179 SetUInt64Value(UNIT_FIELD_TARGET, victim->GetGUID());
7181 if(meleeAttack)
7182 addUnitState(UNIT_STAT_MELEE_ATTACKING);
7184 m_attacking = victim;
7185 m_attacking->_addAttacker(this);
7187 if(GetTypeId()==TYPEID_UNIT)
7189 WorldPacket data(SMSG_AI_REACTION, 12);
7190 data << uint64(GetGUID());
7191 data << uint32(AI_REACTION_AGGRO); // Aggro sound
7192 ((WorldObject*)this)->SendMessageToSet(&data, true);
7194 ((Creature*)this)->CallAssistance();
7197 // delay offhand weapon attack to next attack time
7198 if(haveOffhandWeapon())
7199 resetAttackTimer(OFF_ATTACK);
7201 if(meleeAttack)
7202 SendAttackStart(victim);
7204 return true;
7207 bool Unit::AttackStop(bool targetSwitch /*=false*/)
7209 if (!m_attacking)
7210 return false;
7212 Unit* victim = m_attacking;
7214 m_attacking->_removeAttacker(this);
7215 m_attacking = NULL;
7217 //Clear our target
7218 SetUInt64Value(UNIT_FIELD_TARGET, 0);
7220 clearUnitState(UNIT_STAT_MELEE_ATTACKING);
7222 InterruptSpell(CURRENT_MELEE_SPELL);
7224 // reset only at real combat stop
7225 if(!targetSwitch && GetTypeId()==TYPEID_UNIT )
7226 ((Creature*)this)->SetNoCallAssistance(false);
7228 SendAttackStop(victim);
7230 return true;
7233 void Unit::CombatStop(bool includingCast)
7235 if (includingCast && IsNonMeleeSpellCasted(false))
7236 InterruptNonMeleeSpells(false);
7238 AttackStop();
7239 RemoveAllAttackers();
7240 if( GetTypeId()==TYPEID_PLAYER )
7241 ((Player*)this)->SendAttackSwingCancelAttack(); // melee and ranged forced attack cancel
7242 ClearInCombat();
7245 void Unit::CombatStopWithPets(bool includingCast)
7247 CombatStop(includingCast);
7248 if(Pet* pet = GetPet())
7249 pet->CombatStop(includingCast);
7250 if(Unit* charm = GetCharm())
7251 charm->CombatStop(includingCast);
7252 if(GetTypeId()==TYPEID_PLAYER)
7254 GuardianPetList const& guardians = ((Player*)this)->GetGuardians();
7255 for(GuardianPetList::const_iterator itr = guardians.begin(); itr != guardians.end(); ++itr)
7256 if(Unit* guardian = Unit::GetUnit(*this,*itr))
7257 guardian->CombatStop(includingCast);
7261 bool Unit::isAttackingPlayer() const
7263 if(hasUnitState(UNIT_STAT_ATTACK_PLAYER))
7264 return true;
7266 Pet* pet = GetPet();
7267 if(pet && pet->isAttackingPlayer())
7268 return true;
7270 Unit* charmed = GetCharm();
7271 if(charmed && charmed->isAttackingPlayer())
7272 return true;
7274 for (int8 i = 0; i < MAX_TOTEM; i++)
7276 if(m_TotemSlot[i])
7278 Creature *totem = GetMap()->GetCreature(m_TotemSlot[i]);
7279 if(totem && totem->isAttackingPlayer())
7280 return true;
7284 return false;
7287 void Unit::RemoveAllAttackers()
7289 while (!m_attackers.empty())
7291 AttackerSet::iterator iter = m_attackers.begin();
7292 if(!(*iter)->AttackStop())
7294 sLog.outError("WORLD: Unit has an attacker that isn't attacking it!");
7295 m_attackers.erase(iter);
7300 void Unit::ModifyAuraState(AuraState flag, bool apply)
7302 if (apply)
7304 if (!HasFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1)))
7306 SetFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7307 if(GetTypeId() == TYPEID_PLAYER)
7309 const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap();
7310 for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr)
7312 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
7313 SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first);
7314 if (!spellInfo || !IsPassiveSpell(itr->first)) continue;
7315 if (spellInfo->CasterAuraState == flag)
7316 CastSpell(this, itr->first, true, NULL);
7321 else
7323 if (HasFlag(UNIT_FIELD_AURASTATE,1<<(flag-1)))
7325 RemoveFlag(UNIT_FIELD_AURASTATE, 1<<(flag-1));
7326 Unit::AuraMap& tAuras = GetAuras();
7327 for (Unit::AuraMap::iterator itr = tAuras.begin(); itr != tAuras.end();)
7329 SpellEntry const* spellProto = (*itr).second->GetSpellProto();
7330 if (spellProto->CasterAuraState == flag)
7332 // exceptions (applied at state but not removed at state change)
7333 // Rampage
7334 if(spellProto->SpellIconID==2006 && spellProto->SpellFamilyName==SPELLFAMILY_WARRIOR && spellProto->SpellFamilyFlags==0x100000)
7336 ++itr;
7337 continue;
7340 RemoveAura(itr);
7342 else
7343 ++itr;
7349 Unit *Unit::GetOwner() const
7351 uint64 ownerid = GetOwnerGUID();
7352 if(!ownerid)
7353 return NULL;
7354 return ObjectAccessor::GetUnit(*this, ownerid);
7357 Unit *Unit::GetCharmer() const
7359 if(uint64 charmerid = GetCharmerGUID())
7360 return ObjectAccessor::GetUnit(*this, charmerid);
7361 return NULL;
7364 Player* Unit::GetCharmerOrOwnerPlayerOrPlayerItself()
7366 uint64 guid = GetCharmerOrOwnerGUID();
7367 if(IS_PLAYER_GUID(guid))
7368 return ObjectAccessor::GetPlayer(*this, guid);
7370 return GetTypeId()==TYPEID_PLAYER ? (Player*)this : NULL;
7373 Pet* Unit::GetPet() const
7375 if(uint64 pet_guid = GetPetGUID())
7377 if(Pet* pet = ObjectAccessor::GetPet(pet_guid))
7378 return pet;
7380 sLog.outError("Unit::GetPet: Pet %u not exist.",GUID_LOPART(pet_guid));
7381 const_cast<Unit*>(this)->SetPet(0);
7384 return NULL;
7387 Unit* Unit::GetCharm() const
7389 if(uint64 charm_guid = GetCharmGUID())
7391 if(Unit* pet = ObjectAccessor::GetUnit(*this, charm_guid))
7392 return pet;
7394 sLog.outError("Unit::GetCharm: Charmed creature %u not exist.",GUID_LOPART(charm_guid));
7395 const_cast<Unit*>(this)->SetCharm(NULL);
7398 return NULL;
7401 float Unit::GetCombatDistance( const Unit* target ) const
7403 float radius = target->GetFloatValue(UNIT_FIELD_COMBATREACH) + GetFloatValue(UNIT_FIELD_COMBATREACH);
7404 float dx = GetPositionX() - target->GetPositionX();
7405 float dy = GetPositionY() - target->GetPositionY();
7406 float dz = GetPositionZ() - target->GetPositionZ();
7407 float dist = sqrt((dx*dx) + (dy*dy) + (dz*dz)) - radius;
7408 return ( dist > 0 ? dist : 0);
7411 void Unit::SetPet(Pet* pet)
7413 SetUInt64Value(UNIT_FIELD_SUMMON, pet ? pet->GetGUID() : 0);
7415 // FIXME: hack, speed must be set only at follow
7416 if(pet)
7417 for(int i = 0; i < MAX_MOVE_TYPE; ++i)
7418 pet->SetSpeed(UnitMoveType(i), m_speed_rate[i], true);
7421 void Unit::SetCharm(Unit* pet)
7423 SetUInt64Value(UNIT_FIELD_CHARM, pet ? pet->GetGUID() : 0);
7425 if(GetTypeId() == TYPEID_PLAYER)
7426 ((Player*)this)->m_mover = pet ? pet : this;
7429 void Unit::UnsummonAllTotems()
7431 for (int8 i = 0; i < MAX_TOTEM; ++i)
7433 if(!m_TotemSlot[i])
7434 continue;
7436 Creature *OldTotem = GetMap()->GetCreature(m_TotemSlot[i]);
7437 if (OldTotem && OldTotem->isTotem())
7438 ((Totem*)OldTotem)->UnSummon();
7442 int32 Unit::DealHeal(Unit *pVictim, uint32 addhealth, SpellEntry const *spellProto, bool critical)
7444 int32 gain = pVictim->ModifyHealth(int32(addhealth));
7446 if (GetTypeId()==TYPEID_PLAYER)
7448 SendHealSpellLog(pVictim, spellProto->Id, addhealth, critical);
7450 if (BattleGround *bg = ((Player*)this)->GetBattleGround())
7451 bg->UpdatePlayerScore((Player*)this, SCORE_HEALING_DONE, gain);
7453 // healing done is count ONLY if the target is a player.
7454 if (pVictim->GetTypeId()==TYPEID_PLAYER)
7456 // use the actual gain, as the overheal shall not be counted.
7457 ((Player*)this)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE, gain);
7460 ((Player*)this)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED, addhealth);
7463 if (pVictim->GetTypeId()==TYPEID_PLAYER)
7465 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED, gain);
7466 ((Player*)pVictim)->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED, addhealth);
7469 return gain;
7472 Unit* Unit::SelectMagnetTarget(Unit *victim, SpellEntry const *spellInfo)
7474 if(!victim)
7475 return NULL;
7477 // Magic case
7478 if(spellInfo && (spellInfo->DmgClass == SPELL_DAMAGE_CLASS_NONE || spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC))
7480 Unit::AuraList const& magnetAuras = victim->GetAurasByType(SPELL_AURA_SPELL_MAGNET);
7481 for(Unit::AuraList::const_iterator itr = magnetAuras.begin(); itr != magnetAuras.end(); ++itr)
7482 if(Unit* magnet = (*itr)->GetCaster())
7483 if(magnet->IsWithinLOSInMap(this) && magnet->isAlive())
7484 return magnet;
7486 // Melee && ranged case
7487 else
7489 AuraList const& hitTriggerAuras = victim->GetAurasByType(SPELL_AURA_ADD_CASTER_HIT_TRIGGER);
7490 for(AuraList::const_iterator i = hitTriggerAuras.begin(); i != hitTriggerAuras.end(); ++i)
7491 if(Unit* magnet = (*i)->GetCaster())
7492 if(magnet->isAlive() && magnet->IsWithinLOSInMap(this))
7493 if(roll_chance_i((*i)->GetModifier()->m_amount))
7494 return magnet;
7497 return victim;
7500 void Unit::SendHealSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, bool critical)
7502 // we guess size
7503 WorldPacket data(SMSG_SPELLHEALLOG, (8+8+4+4+1));
7504 data.append(pVictim->GetPackGUID());
7505 data.append(GetPackGUID());
7506 data << uint32(SpellID);
7507 data << uint32(Damage);
7508 data << uint32(0); // over healing?
7509 data << uint8(critical ? 1 : 0);
7510 data << uint8(0); // unused in client?
7511 SendMessageToSet(&data, true);
7514 void Unit::SendEnergizeSpellLog(Unit *pVictim, uint32 SpellID, uint32 Damage, Powers powertype)
7516 WorldPacket data(SMSG_SPELLENERGIZELOG, (8+8+4+4+4+1));
7517 data.append(pVictim->GetPackGUID());
7518 data.append(GetPackGUID());
7519 data << uint32(SpellID);
7520 data << uint32(powertype);
7521 data << uint32(Damage);
7522 SendMessageToSet(&data, true);
7525 uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 pdamage, DamageEffectType damagetype, uint32 stack)
7527 if(!spellProto || !pVictim || damagetype==DIRECT_DAMAGE )
7528 return pdamage;
7530 // For totems get damage bonus from owner (statue isn't totem in fact)
7531 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
7533 if(Unit* owner = GetOwner())
7534 return owner->SpellDamageBonus(pVictim, spellProto, pdamage, damagetype);
7537 // Taken/Done total percent damage auras
7538 float DoneTotalMod = 1.0f;
7539 float TakenTotalMod = 1.0f;
7540 int32 DoneTotal = 0;
7541 int32 TakenTotal = 0;
7543 // ..done
7544 // Pet damage
7545 if( GetTypeId() == TYPEID_UNIT && !((Creature*)this)->isPet() )
7546 DoneTotalMod *= ((Creature*)this)->GetSpellDamageMod(((Creature*)this)->GetCreatureInfo()->rank);
7548 AuraList const& mModDamagePercentDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
7549 for(AuraList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i)
7551 if( ((*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto)) &&
7552 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7553 // -1 == any item class (not wand then)
7554 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7555 // 0 == any inventory type (not wand then)
7557 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7561 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7562 // Add flat bonus from spell damage versus
7563 DoneTotal += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS, creatureTypeMask);
7564 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
7565 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
7566 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7567 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7569 // done scripted mod (take it from owner)
7570 Unit *owner = GetOwner();
7571 if (!owner) owner = this;
7572 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7573 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7575 if (!(*i)->isAffectedOnSpell(spellProto))
7576 continue;
7577 switch((*i)->GetModifier()->m_miscvalue)
7579 case 4920: // Molten Fury
7580 case 4919:
7581 case 6917: // Death's Embrace
7582 case 6926:
7583 case 6928:
7585 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7586 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7587 break;
7589 // Soul Siphon
7590 case 4992:
7591 case 4993:
7593 // effect 1 m_amount
7594 int32 maxPercent = (*i)->GetModifier()->m_amount;
7595 // effect 0 m_amount
7596 int32 stepPercent = CalculateSpellDamage((*i)->GetSpellProto(), 0, (*i)->GetSpellProto()->EffectBasePoints[0], this);
7597 // count affliction effects and calc additional damage in percentage
7598 int32 modPercent = 0;
7599 AuraMap const& victimAuras = pVictim->GetAuras();
7600 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
7602 SpellEntry const* m_spell = itr->second->GetSpellProto();
7603 if (m_spell->SpellFamilyName != SPELLFAMILY_WARLOCK || !(m_spell->SpellFamilyFlags & 0x0004071B8044C402LL))
7604 continue;
7605 modPercent += stepPercent * itr->second->GetStackAmount();
7606 if (modPercent >= maxPercent)
7608 modPercent = maxPercent;
7609 break;
7612 DoneTotalMod *= (modPercent+100.0f)/100.0f;
7613 break;
7615 case 6916: // Death's Embrace
7616 case 6925:
7617 case 6927:
7618 if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT))
7619 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7620 break;
7621 case 5481: // Starfire Bonus
7623 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x0000000000200002LL))
7624 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7625 break;
7627 case 4418: // Increased Shock Damage
7628 case 4554: // Increased Lightning Damage
7629 case 4555: // Improved Moonfire
7630 case 5142: // Increased Lightning Damage
7631 case 5147: // Improved Consecration / Libram of Resurgence
7632 case 5148: // Idol of the Shooting Star
7633 case 6008: // Increased Lightning Damage / Totem of Hex
7635 DoneTotal+=(*i)->GetModifier()->m_amount;
7636 break;
7638 // Tundra Stalker
7639 // Merciless Combat
7640 case 7277:
7642 // Merciless Combat
7643 if ((*i)->GetSpellProto()->SpellIconID == 2656)
7645 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7646 DoneTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
7648 else // Tundra Stalker
7650 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_DEATHKNIGHT, 0x0400000000000000LL))
7651 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7652 break;
7654 break;
7656 case 7293: // Rage of Rivendare
7658 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0x0200000000000000LL))
7659 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7660 break;
7662 // Twisted Faith
7663 case 7377:
7665 if (pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x0000000000008000LL, 0, GetGUID()))
7666 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7667 break;
7669 // Marked for Death
7670 case 7598:
7671 case 7599:
7672 case 7600:
7673 case 7601:
7674 case 7602:
7676 if (pVictim->GetAura(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x0000000000000400LL))
7677 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7678 break;
7683 // Custom scripted damage
7684 // Ice Lance
7685 if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellIconID == 186)
7687 if (pVictim->isFrozen())
7688 DoneTotalMod *= 3.0f;
7691 // ..taken
7692 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
7693 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
7694 if( (*i)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellProto) )
7695 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7697 // .. taken pct: dummy auras
7698 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7700 //Cheat Death
7701 if (Aura *dummy = pVictim->GetDummyAura(45182))
7703 float mod = -((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2*4;
7704 if (mod < dummy->GetModifier()->m_amount)
7705 mod = dummy->GetModifier()->m_amount;
7706 TakenTotalMod *= (mod+100.0f)/100.0f;
7710 // From caster spells
7711 AuraList const& mOwnerTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER);
7712 for(AuraList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i)
7713 if( (*i)->GetCasterGUID() == GetGUID() && (*i)->isAffectedOnSpell(spellProto))
7714 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7716 // Mod damage from spell mechanic
7717 uint32 mechanicMask = GetAllSpellMechanicMask(spellProto);
7718 if (mechanicMask)
7720 AuraList const& mDamageDoneMechanic = pVictim->GetAurasByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT);
7721 for(AuraList::const_iterator i = mDamageDoneMechanic.begin();i != mDamageDoneMechanic.end(); ++i)
7722 if(mechanicMask & uint32(1<<((*i)->GetModifier()->m_miscvalue)))
7723 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
7726 // Taken/Done fixed damage bonus auras
7727 int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto));
7728 int32 TakenAdvertisedBenefit = SpellBaseDamageBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
7730 // Pets just add their bonus damage to their spell damage
7731 // note that their spell damage is just gain of their own auras
7732 if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
7733 DoneAdvertisedBenefit += ((Pet*)this)->GetBonusDamage();
7735 float LvlPenalty = CalculateLevelPenalty(spellProto);
7736 // Spellmod SpellDamage
7737 float SpellModSpellDamage = 100.0f;
7738 if(Player* modOwner = GetSpellModOwner())
7739 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_SPELL_BONUS_DAMAGE,SpellModSpellDamage);
7740 SpellModSpellDamage /= 100.0f;
7742 // Check for table values
7743 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
7744 if (bonus)
7746 float coeff;
7747 if (damagetype == DOT)
7748 coeff = bonus->dot_damage * LvlPenalty * stack;
7749 else
7750 coeff = bonus->direct_damage * LvlPenalty * stack;
7752 if (bonus->ap_bonus)
7753 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
7755 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
7756 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
7758 // Default calculation
7759 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
7761 // Damage Done from spell damage bonus
7762 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
7763 // Damage over Time spells bonus calculation
7764 float DotFactor = 1.0f;
7765 if(damagetype == DOT)
7767 int32 DotDuration = GetSpellDuration(spellProto);
7768 // 200% limit
7769 if(DotDuration > 0)
7771 if(DotDuration > 30000) DotDuration = 30000;
7772 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
7773 int x = 0;
7774 for(int j = 0; j < 3; j++)
7776 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
7777 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
7778 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
7780 x = j;
7781 break;
7784 int32 DotTicks = 6;
7785 if(spellProto->EffectAmplitude[x] != 0)
7786 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
7787 if(DotTicks)
7789 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
7790 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
7794 // Distribute Damage over multiple effects, reduce by AoE
7795 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
7796 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
7797 for(int j = 0; j < 3; ++j)
7799 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
7800 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
7802 CastingTime /= 2;
7803 break;
7806 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage);
7807 TakenTotal+= int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty);
7810 float tmpDamage = (pdamage + DoneTotal) * DoneTotalMod;
7811 // apply spellmod to Done damage (flat and pct)
7812 if(Player* modOwner = GetSpellModOwner())
7813 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, tmpDamage);
7815 tmpDamage = (tmpDamage + TakenTotal) * TakenTotalMod;
7817 return tmpDamage > 0 ? uint32(tmpDamage) : 0;
7820 int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask)
7822 int32 DoneAdvertisedBenefit = 0;
7824 // ..done
7825 AuraList const& mDamageDone = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
7826 for(AuraList::const_iterator i = mDamageDone.begin();i != mDamageDone.end(); ++i)
7827 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0 &&
7828 (*i)->GetSpellProto()->EquippedItemClass == -1 &&
7829 // -1 == any item class (not wand then)
7830 (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0 )
7831 // 0 == any inventory type (not wand then)
7832 DoneAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7834 if (GetTypeId() == TYPEID_PLAYER)
7836 // Base value
7837 DoneAdvertisedBenefit +=((Player*)this)->GetBaseSpellDamageBonus();
7839 // Damage bonus from stats
7840 AuraList const& mDamageDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT);
7841 for(AuraList::const_iterator i = mDamageDoneOfStatPercent.begin();i != mDamageDoneOfStatPercent.end(); ++i)
7843 if((*i)->GetModifier()->m_miscvalue & schoolMask)
7845 // stat used stored in miscValueB for this aura
7846 Stats usedStat = Stats((*i)->GetMiscBValue());
7847 DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
7850 // ... and attack power
7851 AuraList const& mDamageDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER);
7852 for(AuraList::const_iterator i =mDamageDonebyAP.begin();i != mDamageDonebyAP.end(); ++i)
7853 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
7854 DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
7857 return DoneAdvertisedBenefit;
7860 int32 Unit::SpellBaseDamageBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
7862 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
7864 int32 TakenAdvertisedBenefit = 0;
7865 // ..done (for creature type by mask) in taken
7866 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
7867 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
7868 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
7869 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7871 // ..taken
7872 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
7873 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
7874 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
7875 TakenAdvertisedBenefit += (*i)->GetModifier()->m_amount;
7877 return TakenAdvertisedBenefit;
7880 bool Unit::isSpellCrit(Unit *pVictim, SpellEntry const *spellProto, SpellSchoolMask schoolMask, WeaponAttackType attackType)
7882 // not critting spell
7883 if((spellProto->AttributesEx2 & SPELL_ATTR_EX2_CANT_CRIT))
7884 return false;
7886 float crit_chance = 0.0f;
7887 switch(spellProto->DmgClass)
7889 case SPELL_DAMAGE_CLASS_NONE:
7890 return false;
7891 case SPELL_DAMAGE_CLASS_MAGIC:
7893 if (schoolMask & SPELL_SCHOOL_MASK_NORMAL)
7894 crit_chance = 0.0f;
7895 // For other schools
7896 else if (GetTypeId() == TYPEID_PLAYER)
7897 crit_chance = GetFloatValue( PLAYER_SPELL_CRIT_PERCENTAGE1 + GetFirstSchoolInMask(schoolMask));
7898 else
7900 crit_chance = m_baseSpellCritChance;
7901 crit_chance += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7903 // taken
7904 if (pVictim)
7906 if (!IsPositiveSpell(spellProto->Id))
7908 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE
7909 crit_chance += pVictim->GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE, schoolMask);
7910 // Modify critical chance by victim SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE
7911 crit_chance += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCE);
7912 // Modify by player victim resilience
7913 if (pVictim->GetTypeId() == TYPEID_PLAYER)
7914 crit_chance -= ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
7917 // scripted (increase crit chance ... against ... target by x%
7918 AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
7919 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
7921 if (!((*i)->isAffectedOnSpell(spellProto)))
7922 continue;
7923 switch((*i)->GetModifier()->m_miscvalue)
7925 case 849: if (pVictim->isFrozen()) crit_chance+= 17.0f; break; //Shatter Rank 1
7926 case 910: if (pVictim->isFrozen()) crit_chance+= 34.0f; break; //Shatter Rank 2
7927 case 911: if (pVictim->isFrozen()) crit_chance+= 50.0f; break; //Shatter Rank 3
7928 case 7917: // Glyph of Shadowburn
7929 if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
7930 crit_chance+=(*i)->GetModifier()->m_amount;
7931 break;
7932 case 7997: // Renewed Hope
7933 case 7998:
7934 if (pVictim->HasAura(6788))
7935 crit_chance+=(*i)->GetModifier()->m_amount;
7936 break;
7937 case 21: // Test of Faith
7938 case 6935:
7939 case 6918:
7940 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
7941 crit_chance+=(*i)->GetModifier()->m_amount;
7942 break;
7943 default:
7944 break;
7947 // Custom crit by class
7948 switch(spellProto->SpellFamilyName)
7950 case SPELLFAMILY_PALADIN:
7951 // Sacred Shield
7952 if (spellProto->SpellFamilyFlags & 0x0000000040000000LL)
7954 Aura *aura = pVictim->GetDummyAura(58597);
7955 if (aura && aura->GetCasterGUID() == GetGUID())
7956 crit_chance+=aura->GetModifier()->m_amount;
7957 break;
7959 break;
7960 case SPELLFAMILY_SHAMAN:
7961 // Lava Burst
7962 if (spellProto->SpellFamilyFlags & 0x0000100000000000LL)
7964 if (Aura *flameShock = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, 0x0000000010000000LL, 0, GetGUID()))
7966 // Consume shock aura if not have Glyph of Flame Shock
7967 if (!GetAura(55447, 0))
7968 pVictim->RemoveAurasByCasterSpell(flameShock->GetId(), GetGUID());
7969 return true;
7971 break;
7973 break;
7977 break;
7979 case SPELL_DAMAGE_CLASS_MELEE:
7980 case SPELL_DAMAGE_CLASS_RANGED:
7982 if (pVictim)
7984 crit_chance = GetUnitCriticalChance(attackType, pVictim);
7985 crit_chance+= GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL, schoolMask);
7987 break;
7989 default:
7990 return false;
7992 // percent done
7993 // only players use intelligence for critical chance computations
7994 if(Player* modOwner = GetSpellModOwner())
7995 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRITICAL_CHANCE, crit_chance);
7997 crit_chance = crit_chance > 0.0f ? crit_chance : 0.0f;
7998 if (roll_chance_f(crit_chance))
7999 return true;
8000 return false;
8003 uint32 Unit::SpellCriticalDamageBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8005 // Calculate critical bonus
8006 int32 crit_bonus;
8007 switch(spellProto->DmgClass)
8009 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8010 case SPELL_DAMAGE_CLASS_RANGED:
8011 // TODO: write here full calculation for melee/ranged spells
8012 crit_bonus = damage;
8013 break;
8014 default:
8015 crit_bonus = damage / 2; // for spells is 50%
8016 break;
8019 // adds additional damage to crit_bonus (from talents)
8020 if(Player* modOwner = GetSpellModOwner())
8021 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus);
8023 if(pVictim)
8025 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8026 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8029 if(crit_bonus > 0)
8030 damage += crit_bonus;
8032 return damage;
8035 uint32 Unit::SpellCriticalHealingBonus(SpellEntry const *spellProto, uint32 damage, Unit *pVictim)
8037 // Calculate critical bonus
8038 int32 crit_bonus;
8039 switch(spellProto->DmgClass)
8041 case SPELL_DAMAGE_CLASS_MELEE: // for melee based spells is 100%
8042 case SPELL_DAMAGE_CLASS_RANGED:
8043 // TODO: write here full calculation for melee/ranged spells
8044 crit_bonus = damage;
8045 break;
8046 default:
8047 crit_bonus = damage / 2; // for spells is 50%
8048 break;
8051 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplier(SPELL_AURA_MOD_CRITICAL_HEALING_BONUS));
8053 if(pVictim)
8055 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8056 crit_bonus = int32(crit_bonus * GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, creatureTypeMask));
8059 if(crit_bonus > 0)
8060 damage += crit_bonus;
8062 return damage;
8065 uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack)
8067 // No heal amount for this class spells
8068 if (spellProto->DmgClass == SPELL_DAMAGE_CLASS_NONE)
8069 return healamount;
8071 // For totems get healing bonus from owner (statue isn't totem in fact)
8072 if( GetTypeId()==TYPEID_UNIT && ((Creature*)this)->isTotem() && ((Totem*)this)->GetTotemType()!=TOTEM_STATUE)
8073 if(Unit* owner = GetOwner())
8074 return owner->SpellHealingBonus(pVictim, spellProto, healamount, damagetype, stack);
8076 // Healing Done
8077 // Taken/Done total percent damage auras
8078 float DoneTotalMod = 1.0f;
8079 float TakenTotalMod = 1.0f;
8080 int32 DoneTotal = 0;
8081 int32 TakenTotal = 0;
8083 // Healing done percent
8084 AuraList const& mHealingDonePct = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT);
8085 for(AuraList::const_iterator i = mHealingDonePct.begin();i != mHealingDonePct.end(); ++i)
8086 DoneTotalMod *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
8088 // done scripted mod (take it from owner)
8089 Unit *owner = GetOwner();
8090 if (!owner) owner = this;
8091 AuraList const& mOverrideClassScript= owner->GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8092 for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i)
8094 if (!(*i)->isAffectedOnSpell(spellProto))
8095 continue;
8096 switch((*i)->GetModifier()->m_miscvalue)
8098 case 4415: // Increased Rejuvenation Healing
8099 case 4953:
8100 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
8101 DoneTotal+=(*i)->GetModifier()->m_amount;
8102 break;
8103 case 7997: // Renewed Hope
8104 case 7998:
8105 if (pVictim->HasAura(6788))
8106 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8107 break;
8108 case 21: // Test of Faith
8109 case 6935:
8110 case 6918:
8111 if (pVictim->GetHealth() < pVictim->GetMaxHealth()/2)
8112 DoneTotalMod *=((*i)->GetModifier()->m_amount + 100.0f)/100.0f;
8113 break;
8114 case 7798: // Glyph of Regrowth
8116 if (pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x0000000000000040LL))
8117 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8118 break;
8120 case 8477: // Nourish Heal Boost
8122 int32 stepPercent = (*i)->GetModifier()->m_amount;
8123 int32 modPercent = 0;
8124 AuraMap const& victimAuras = pVictim->GetAuras();
8125 for (AuraMap::const_iterator itr = victimAuras.begin(); itr != victimAuras.end(); ++itr)
8127 if (itr->second->GetCasterGUID()!=GetGUID())
8128 continue;
8129 SpellEntry const* m_spell = itr->second->GetSpellProto();
8130 if ( m_spell->SpellFamilyName != SPELLFAMILY_DRUID ||
8131 !(m_spell->SpellFamilyFlags & 0x0000001000000050LL))
8132 continue;
8133 modPercent += stepPercent * itr->second->GetStackAmount();
8135 DoneTotalMod *= (modPercent+100.0f)/100.0f;
8136 break;
8138 case 7871: // Glyph of Lesser Healing Wave
8140 if (pVictim->GetAura(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x0000040000000000LL, 0, GetGUID()))
8141 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8142 break;
8144 default:
8145 break;
8149 // Taken/Done fixed damage bonus auras
8150 int32 DoneAdvertisedBenefit = SpellBaseHealingBonus(GetSpellSchoolMask(spellProto));
8151 int32 TakenAdvertisedBenefit = SpellBaseHealingBonusForVictim(GetSpellSchoolMask(spellProto), pVictim);
8153 float LvlPenalty = CalculateLevelPenalty(spellProto);
8154 // Spellmod SpellDamage
8155 float SpellModSpellDamage = 100.0f;
8156 if(Player* modOwner = GetSpellModOwner())
8157 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_SPELL_BONUS_DAMAGE, SpellModSpellDamage);
8158 SpellModSpellDamage /= 100.0f;
8160 // Check for table values
8161 SpellBonusEntry const* bonus = spellmgr.GetSpellBonusData(spellProto->Id);
8162 if (bonus)
8164 float coeff;
8165 if (damagetype == DOT)
8166 coeff = bonus->dot_damage * LvlPenalty * stack;
8167 else
8168 coeff = bonus->direct_damage * LvlPenalty * stack;
8170 if (bonus->ap_bonus)
8171 DoneTotal += int32(bonus->ap_bonus * GetTotalAttackPowerValue(BASE_ATTACK) * stack);
8173 DoneTotal += int32(DoneAdvertisedBenefit * coeff * SpellModSpellDamage);
8174 TakenTotal += int32(TakenAdvertisedBenefit * coeff);
8176 // Default calculation
8177 else if (DoneAdvertisedBenefit || TakenAdvertisedBenefit)
8179 // Damage Done from spell damage bonus
8180 uint32 CastingTime = !IsChanneledSpell(spellProto) ? GetSpellCastTime(spellProto) : GetSpellDuration(spellProto);
8181 // Damage over Time spells bonus calculation
8182 float DotFactor = 1.0f;
8183 if(damagetype == DOT)
8185 int32 DotDuration = GetSpellDuration(spellProto);
8186 // 200% limit
8187 if(DotDuration > 0)
8189 if(DotDuration > 30000) DotDuration = 30000;
8190 if(!IsChanneledSpell(spellProto)) DotFactor = DotDuration / 15000.0f;
8191 int x = 0;
8192 for(int j = 0; j < 3; j++)
8194 if( spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && (
8195 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_DAMAGE ||
8196 spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH) )
8198 x = j;
8199 break;
8202 int32 DotTicks = 6;
8203 if(spellProto->EffectAmplitude[x] != 0)
8204 DotTicks = DotDuration / spellProto->EffectAmplitude[x];
8205 if(DotTicks)
8207 DoneAdvertisedBenefit = DoneAdvertisedBenefit * int32(stack) / DotTicks;
8208 TakenAdvertisedBenefit = TakenAdvertisedBenefit * int32(stack) / DotTicks;
8212 // Distribute Damage over multiple effects, reduce by AoE
8213 CastingTime = GetCastingTimeForBonus( spellProto, damagetype, CastingTime );
8214 // 50% for damage and healing spells for leech spells from damage bonus and 0% from healing
8215 for(int j = 0; j < 3; ++j)
8217 if( spellProto->Effect[j] == SPELL_EFFECT_HEALTH_LEECH ||
8218 spellProto->Effect[j] == SPELL_EFFECT_APPLY_AURA && spellProto->EffectApplyAuraName[j] == SPELL_AURA_PERIODIC_LEECH )
8220 CastingTime /= 2;
8221 break;
8224 DoneTotal += int32(DoneAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * SpellModSpellDamage * 1.88f);
8225 TakenTotal += int32(TakenAdvertisedBenefit * (CastingTime / 3500.0f) * DotFactor * LvlPenalty * 1.88f);
8228 // use float as more appropriate for negative values and percent applying
8229 float heal = (healamount + DoneTotal)*DoneTotalMod;
8230 // apply spellmod to Done amount
8231 if(Player* modOwner = GetSpellModOwner())
8232 modOwner->ApplySpellMod(spellProto->Id, damagetype == DOT ? SPELLMOD_DOT : SPELLMOD_DAMAGE, heal);
8234 // Taken mods
8235 // Healing Wave cast
8236 if (spellProto->SpellFamilyName == SPELLFAMILY_SHAMAN && spellProto->SpellFamilyFlags & 0x0000000000000040LL)
8238 // Search for Healing Way on Victim
8239 Unit::AuraList const& auraDummy = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8240 for(Unit::AuraList::const_iterator itr = auraDummy.begin(); itr!=auraDummy.end(); ++itr)
8241 if((*itr)->GetId() == 29203)
8242 TakenTotalMod *= ((*itr)->GetModifier()->m_amount+100.0f) / 100.0f;
8245 // Healing taken percent
8246 float minval = pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8247 if(minval)
8248 TakenTotalMod *= (100.0f + minval) / 100.0f;
8250 float maxval = pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT);
8251 if(maxval)
8252 TakenTotalMod *= (100.0f + maxval) / 100.0f;
8254 AuraList const& mHealingGet= pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING_RECEIVED);
8255 for(AuraList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i)
8256 if ((*i)->isAffectedOnSpell(spellProto))
8257 TakenTotalMod *= ((*i)->GetModifier()->m_amount + 100.0f) / 100.0f;
8259 heal = (heal + TakenTotal) * TakenTotalMod;
8261 return heal < 0 ? 0 : uint32(heal);
8264 int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask)
8266 int32 AdvertisedBenefit = 0;
8268 AuraList const& mHealingDone = GetAurasByType(SPELL_AURA_MOD_HEALING_DONE);
8269 for(AuraList::const_iterator i = mHealingDone.begin();i != mHealingDone.end(); ++i)
8270 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8271 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8273 // Healing bonus of spirit, intellect and strength
8274 if (GetTypeId() == TYPEID_PLAYER)
8276 // Base value
8277 AdvertisedBenefit +=((Player*)this)->GetBaseSpellHealingBonus();
8279 // Healing bonus from stats
8280 AuraList const& mHealingDoneOfStatPercent = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT);
8281 for(AuraList::const_iterator i = mHealingDoneOfStatPercent.begin();i != mHealingDoneOfStatPercent.end(); ++i)
8283 // stat used dependent from misc value (stat index)
8284 Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]);
8285 AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetModifier()->m_amount / 100.0f);
8288 // ... and attack power
8289 AuraList const& mHealingDonebyAP = GetAurasByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER);
8290 for(AuraList::const_iterator i = mHealingDonebyAP.begin();i != mHealingDonebyAP.end(); ++i)
8291 if ((*i)->GetModifier()->m_miscvalue & schoolMask)
8292 AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetModifier()->m_amount / 100.0f);
8294 return AdvertisedBenefit;
8297 int32 Unit::SpellBaseHealingBonusForVictim(SpellSchoolMask schoolMask, Unit *pVictim)
8299 int32 AdvertisedBenefit = 0;
8300 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_HEALING);
8301 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8302 if(((*i)->GetModifier()->m_miscvalue & schoolMask) != 0)
8303 AdvertisedBenefit += (*i)->GetModifier()->m_amount;
8304 return AdvertisedBenefit;
8307 bool Unit::IsImmunedToDamage(SpellSchoolMask shoolMask)
8309 //If m_immuneToSchool type contain this school type, IMMUNE damage.
8310 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8311 for (SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8312 if(itr->type & shoolMask)
8313 return true;
8315 //If m_immuneToDamage type contain magic, IMMUNE damage.
8316 SpellImmuneList const& damageList = m_spellImmune[IMMUNITY_DAMAGE];
8317 for (SpellImmuneList::const_iterator itr = damageList.begin(); itr != damageList.end(); ++itr)
8318 if(itr->type & shoolMask)
8319 return true;
8321 return false;
8324 bool Unit::IsImmunedToSpell(SpellEntry const* spellInfo)
8326 if (!spellInfo)
8327 return false;
8329 //FIX ME this hack: don't get feared if stunned
8330 if (spellInfo->Mechanic == MECHANIC_FEAR )
8332 if ( hasUnitState(UNIT_STAT_STUNNED) )
8333 return true;
8336 //TODO add spellEffect immunity checks!, player with flag in bg is imune to imunity buffs from other friendly players!
8337 //SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_EFFECT];
8339 SpellImmuneList const& dispelList = m_spellImmune[IMMUNITY_DISPEL];
8340 for(SpellImmuneList::const_iterator itr = dispelList.begin(); itr != dispelList.end(); ++itr)
8341 if(itr->type == spellInfo->Dispel)
8342 return true;
8344 if( !(spellInfo->AttributesEx & SPELL_ATTR_EX_UNAFFECTED_BY_SCHOOL_IMMUNE) && // unaffected by school immunity
8345 !(spellInfo->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)) // can remove immune (by dispell or immune it)
8347 SpellImmuneList const& schoolList = m_spellImmune[IMMUNITY_SCHOOL];
8348 for(SpellImmuneList::const_iterator itr = schoolList.begin(); itr != schoolList.end(); ++itr)
8349 if( !(IsPositiveSpell(itr->spellId) && IsPositiveSpell(spellInfo->Id)) &&
8350 (itr->type & GetSpellSchoolMask(spellInfo)) )
8351 return true;
8354 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8355 for(SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8357 if(itr->type == spellInfo->Mechanic)
8359 return true;
8363 return false;
8366 bool Unit::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
8368 //If m_immuneToEffect type contain this effect type, IMMUNE effect.
8369 uint32 effect = spellInfo->Effect[index];
8370 SpellImmuneList const& effectList = m_spellImmune[IMMUNITY_EFFECT];
8371 for (SpellImmuneList::const_iterator itr = effectList.begin(); itr != effectList.end(); ++itr)
8372 if(itr->type == effect)
8373 return true;
8375 if(uint32 mechanic = spellInfo->EffectMechanic[index])
8377 SpellImmuneList const& mechanicList = m_spellImmune[IMMUNITY_MECHANIC];
8378 for (SpellImmuneList::const_iterator itr = mechanicList.begin(); itr != mechanicList.end(); ++itr)
8379 if(itr->type == mechanic)
8380 return true;
8383 if(uint32 aura = spellInfo->EffectApplyAuraName[index])
8385 SpellImmuneList const& list = m_spellImmune[IMMUNITY_STATE];
8386 for(SpellImmuneList::const_iterator itr = list.begin(); itr != list.end(); ++itr)
8387 if(itr->type == aura)
8388 return true;
8389 // Check for immune to application of harmful magical effects
8390 AuraList const& immuneAuraApply = GetAurasByType(SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL);
8391 for(AuraList::const_iterator iter = immuneAuraApply.begin(); iter != immuneAuraApply.end(); ++iter)
8392 if (spellInfo->Dispel == DISPEL_MAGIC && // Magic debuff
8393 ((*iter)->GetModifier()->m_miscvalue & GetSpellSchoolMask(spellInfo)) && // Check school
8394 !IsPositiveEffect(spellInfo->Id, index)) // Harmful
8395 return true;
8398 return false;
8401 bool Unit::IsDamageToThreatSpell(SpellEntry const * spellInfo) const
8403 if(!spellInfo)
8404 return false;
8406 uint32 family = spellInfo->SpellFamilyName;
8407 uint64 flags = spellInfo->SpellFamilyFlags;
8409 if((family == 5 && flags == 256) || //Searing Pain
8410 (family == 6 && flags == 8192) || //Mind Blast
8411 (family == 11 && flags == 1048576)) //Earth Shock
8412 return true;
8414 return false;
8417 void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage,WeaponAttackType attType, SpellEntry const *spellProto)
8419 if(!pVictim)
8420 return;
8422 if(*pdamage == 0)
8423 return;
8425 uint32 creatureTypeMask = pVictim->GetCreatureTypeMask();
8427 // Taken/Done fixed damage bonus auras
8428 int32 DoneFlatBenefit = 0;
8429 int32 TakenFlatBenefit = 0;
8431 // ..done (for creature type by mask) in taken
8432 AuraList const& mDamageDoneCreature = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_CREATURE);
8433 for(AuraList::const_iterator i = mDamageDoneCreature.begin();i != mDamageDoneCreature.end(); ++i)
8434 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8435 DoneFlatBenefit += (*i)->GetModifier()->m_amount;
8437 // ..done
8438 // SPELL_AURA_MOD_DAMAGE_DONE included in weapon damage
8440 // ..done (base at attack power for marked target and base at attack power for creature type)
8441 int32 APbonus = 0;
8442 if(attType == RANGED_ATTACK)
8444 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS);
8446 // ..done (base at attack power and creature type)
8447 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS);
8448 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8449 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8450 APbonus += (*i)->GetModifier()->m_amount;
8452 else
8454 APbonus += pVictim->GetTotalAuraModifier(SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS);
8456 // ..done (base at attack power and creature type)
8457 AuraList const& mCreatureAttackPower = GetAurasByType(SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS);
8458 for(AuraList::const_iterator i = mCreatureAttackPower.begin();i != mCreatureAttackPower.end(); ++i)
8459 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8460 APbonus += (*i)->GetModifier()->m_amount;
8463 if (APbonus!=0) // Can be negative
8465 bool normalized = false;
8466 if(spellProto)
8468 for (uint8 i = 0; i<3;i++)
8470 if (spellProto->Effect[i] == SPELL_EFFECT_NORMALIZED_WEAPON_DMG)
8472 normalized = true;
8473 break;
8478 DoneFlatBenefit += int32(APbonus/14.0f * GetAPMultiplier(attType,normalized));
8481 // ..taken
8482 AuraList const& mDamageTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_TAKEN);
8483 for(AuraList::const_iterator i = mDamageTaken.begin();i != mDamageTaken.end(); ++i)
8484 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8485 TakenFlatBenefit += (*i)->GetModifier()->m_amount;
8487 if(attType!=RANGED_ATTACK)
8488 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN);
8489 else
8490 TakenFlatBenefit += pVictim->GetTotalAuraModifier(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN);
8492 // Done/Taken total percent damage auras
8493 float DoneTotalMod = 1.0f;
8494 float TakenTotalMod = 1.0f;
8496 // ..done
8497 // SPELL_AURA_MOD_DAMAGE_PERCENT_DONE included in weapon damage
8498 // SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT included in weapon damage
8500 AuraList const& mDamageDoneVersus = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS);
8501 for(AuraList::const_iterator i = mDamageDoneVersus.begin();i != mDamageDoneVersus.end(); ++i)
8502 if(creatureTypeMask & uint32((*i)->GetModifier()->m_miscvalue))
8503 DoneTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8505 // ..taken
8506 AuraList const& mModDamagePercentTaken = pVictim->GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN);
8507 for(AuraList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i)
8508 if((*i)->GetModifier()->m_miscvalue & GetMeleeDamageSchoolMask())
8509 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8511 // .. taken pct: dummy auras
8512 AuraList const& mDummyAuras = pVictim->GetAurasByType(SPELL_AURA_DUMMY);
8513 for(AuraList::const_iterator i = mDummyAuras.begin(); i != mDummyAuras.end(); ++i)
8515 switch((*i)->GetSpellProto()->SpellIconID)
8517 //Cheat Death
8518 case 2109:
8519 if((*i)->GetModifier()->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)
8521 if(pVictim->GetTypeId() != TYPEID_PLAYER)
8522 continue;
8523 float mod = ((Player*)pVictim)->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f);
8524 if (mod < (*i)->GetModifier()->m_amount)
8525 mod = (*i)->GetModifier()->m_amount;
8526 TakenTotalMod *= (mod+100.0f)/100.0f;
8528 break;
8529 //Mangle
8530 case 2312:
8531 if(spellProto==NULL)
8532 break;
8533 // Should increase Shred (initial Damage of Lacerate and Rake handled in Spell::EffectSchoolDMG)
8534 if(spellProto->SpellFamilyName==SPELLFAMILY_DRUID && (spellProto->SpellFamilyFlags==0x00008000LL))
8535 TakenTotalMod *= (100.0f+(*i)->GetModifier()->m_amount)/100.0f;
8536 break;
8540 // .. taken pct: class scripts
8541 AuraList const& mclassScritAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS);
8542 for(AuraList::const_iterator i = mclassScritAuras.begin(); i != mclassScritAuras.end(); ++i)
8544 switch((*i)->GetMiscValue())
8546 case 6427: case 6428: // Dirty Deeds
8547 if(pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT))
8549 Aura* eff0 = GetAura((*i)->GetId(),0);
8550 if(!eff0 || (*i)->GetEffIndex()!=1)
8552 sLog.outError("Spell structure of DD (%u) changed.",(*i)->GetId());
8553 continue;
8556 // effect 0 have expected value but in negative state
8557 TakenTotalMod *= (-eff0->GetModifier()->m_amount+100.0f)/100.0f;
8559 break;
8563 if(attType != RANGED_ATTACK)
8565 AuraList const& mModMeleeDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT);
8566 for(AuraList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i)
8567 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8569 else
8571 AuraList const& mModRangedDamageTakenPercent = pVictim->GetAurasByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT);
8572 for(AuraList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i)
8573 TakenTotalMod *= ((*i)->GetModifier()->m_amount+100.0f)/100.0f;
8576 float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod;
8578 // apply spellmod to Done damage
8579 if(spellProto)
8581 if(Player* modOwner = GetSpellModOwner())
8582 modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage);
8585 tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod;
8587 // bonus result can be negative
8588 *pdamage = tmpDamage > 0 ? uint32(tmpDamage) : 0;
8591 void Unit::ApplySpellImmune(uint32 spellId, uint32 op, uint32 type, bool apply)
8593 if (apply)
8595 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(), next; itr != m_spellImmune[op].end(); itr = next)
8597 next = itr; ++next;
8598 if(itr->type == type)
8600 m_spellImmune[op].erase(itr);
8601 next = m_spellImmune[op].begin();
8604 SpellImmune Immune;
8605 Immune.spellId = spellId;
8606 Immune.type = type;
8607 m_spellImmune[op].push_back(Immune);
8609 else
8611 for (SpellImmuneList::iterator itr = m_spellImmune[op].begin(); itr != m_spellImmune[op].end(); ++itr)
8613 if(itr->spellId == spellId)
8615 m_spellImmune[op].erase(itr);
8616 break;
8623 void Unit::ApplySpellDispelImmunity(const SpellEntry * spellProto, DispelType type, bool apply)
8625 ApplySpellImmune(spellProto->Id,IMMUNITY_DISPEL, type, apply);
8627 if (apply && spellProto->AttributesEx & SPELL_ATTR_EX_DISPEL_AURAS_ON_IMMUNITY)
8628 RemoveAurasWithDispelType(type);
8631 float Unit::GetWeaponProcChance() const
8633 // normalized proc chance for weapon attack speed
8634 // (odd formula...)
8635 if(isAttackReady(BASE_ATTACK))
8636 return (GetAttackTime(BASE_ATTACK) * 1.8f / 1000.0f);
8637 else if (haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
8638 return (GetAttackTime(OFF_ATTACK) * 1.6f / 1000.0f);
8639 return 0;
8642 float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM) const
8644 // proc per minute chance calculation
8645 if (PPM <= 0) return 0.0f;
8646 uint32 result = uint32((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60))
8647 return result;
8650 void Unit::Mount(uint32 mount)
8652 if(!mount)
8653 return;
8655 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOUNTING);
8657 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, mount);
8659 SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8661 // unsummon pet
8662 if(GetTypeId() == TYPEID_PLAYER)
8663 ((Player*)this)->UnsummonPetTemporaryIfAny();
8666 void Unit::Unmount()
8668 if(!IsMounted())
8669 return;
8671 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_MOUNTED);
8673 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
8674 RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNT );
8676 // only resummon old pet if the player is already added to a map
8677 // this prevents adding a pet to a not created map which would otherwise cause a crash
8678 // (it could probably happen when logging in after a previous crash)
8679 if(GetTypeId() == TYPEID_PLAYER)
8680 ((Player*)this)->ResummonPetTemporaryUnSummonedIfAny();
8683 void Unit::SetInCombatWith(Unit* enemy)
8685 Unit* eOwner = enemy->GetCharmerOrOwnerOrSelf();
8686 if(eOwner->IsPvP())
8688 SetInCombatState(true);
8689 return;
8692 //check for duel
8693 if(eOwner->GetTypeId() == TYPEID_PLAYER && ((Player*)eOwner)->duel)
8695 Unit const* myOwner = GetCharmerOrOwnerOrSelf();
8696 if(((Player const*)eOwner)->duel->opponent == myOwner)
8698 SetInCombatState(true);
8699 return;
8702 SetInCombatState(false);
8705 void Unit::SetInCombatState(bool PvP)
8707 // only alive units can be in combat
8708 if(!isAlive())
8709 return;
8711 if(PvP)
8712 m_CombatTimer = 5000;
8713 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8715 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8716 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8719 void Unit::ClearInCombat()
8721 m_CombatTimer = 0;
8722 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IN_COMBAT);
8724 if(isCharmed() || (GetTypeId()!=TYPEID_PLAYER && ((Creature*)this)->isPet()))
8725 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT);
8727 // Player's state will be cleared in Player::UpdateContestedPvP
8728 if(GetTypeId()!=TYPEID_PLAYER)
8729 clearUnitState(UNIT_STAT_ATTACK_PLAYER);
8730 else
8731 ((Player*)this)->UpdatePotionCooldown();
8734 bool Unit::isTargetableForAttack() const
8736 if (GetTypeId()==TYPEID_PLAYER && ((Player *)this)->isGameMaster())
8737 return false;
8739 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE))
8740 return false;
8742 return isAlive() && !hasUnitState(UNIT_STAT_DIED)&& !isInFlight() /*&& !isStealth()*/;
8745 int32 Unit::ModifyHealth(int32 dVal)
8747 int32 gain = 0;
8749 if(dVal==0)
8750 return 0;
8752 int32 curHealth = (int32)GetHealth();
8754 int32 val = dVal + curHealth;
8755 if(val <= 0)
8757 SetHealth(0);
8758 return -curHealth;
8761 int32 maxHealth = (int32)GetMaxHealth();
8763 if(val < maxHealth)
8765 SetHealth(val);
8766 gain = val - curHealth;
8768 else if(curHealth != maxHealth)
8770 SetHealth(maxHealth);
8771 gain = maxHealth - curHealth;
8774 return gain;
8777 int32 Unit::ModifyPower(Powers power, int32 dVal)
8779 int32 gain = 0;
8781 if(dVal==0)
8782 return 0;
8784 int32 curPower = (int32)GetPower(power);
8786 int32 val = dVal + curPower;
8787 if(val <= 0)
8789 SetPower(power,0);
8790 return -curPower;
8793 int32 maxPower = (int32)GetMaxPower(power);
8795 if(val < maxPower)
8797 SetPower(power,val);
8798 gain = val - curPower;
8800 else if(curPower != maxPower)
8802 SetPower(power,maxPower);
8803 gain = maxPower - curPower;
8806 return gain;
8809 bool Unit::isVisibleForOrDetect(Unit const* u, bool detect, bool inVisibleList, bool is3dDistance) const
8811 if(!u)
8812 return false;
8814 // Always can see self
8815 if (u==this)
8816 return true;
8818 // player visible for other player if not logout and at same transport
8819 // including case when player is out of world
8820 bool at_same_transport =
8821 GetTypeId() == TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER &&
8822 !((Player*)this)->GetSession()->PlayerLogout() && !((Player*)u)->GetSession()->PlayerLogout() &&
8823 !((Player*)this)->GetSession()->PlayerLoading() && !((Player*)u)->GetSession()->PlayerLoading() &&
8824 ((Player*)this)->GetTransport() && ((Player*)this)->GetTransport() == ((Player*)u)->GetTransport();
8826 // not in world
8827 if(!at_same_transport && (!IsInWorld() || !u->IsInWorld()))
8828 return false;
8830 // forbidden to seen (at GM respawn command)
8831 if(m_Visibility==VISIBILITY_RESPAWN)
8832 return false;
8834 // always seen by owner
8835 if(GetCharmerOrOwnerGUID()==u->GetGUID())
8836 return true;
8838 // Grid dead/alive checks
8839 if( u->GetTypeId()==TYPEID_PLAYER)
8841 // non visible at grid for any stealth state
8842 if(!IsVisibleInGridForPlayer((Player *)u))
8843 return false;
8845 // if player is dead then he can't detect anyone in any cases
8846 if(!u->isAlive())
8847 detect = false;
8849 else
8851 // all dead creatures/players not visible for any creatures
8852 if(!u->isAlive() || !isAlive())
8853 return false;
8856 // different visible distance checks
8857 if(u->isInFlight()) // what see player in flight
8859 // use object grey distance for all (only see objects any way)
8860 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceInFlight()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8861 return false;
8863 else if(!isAlive()) // distance for show body
8865 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForObject()+(inVisibleList ? World::GetVisibleObjectGreyDistance() : 0.0f), is3dDistance))
8866 return false;
8868 else if(GetTypeId()==TYPEID_PLAYER) // distance for show player
8870 if(u->GetTypeId()==TYPEID_PLAYER)
8872 // Players far than max visible distance for player or not in our map are not visible too
8873 if (!at_same_transport && !IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8874 return false;
8876 else
8878 // Units far than max visible distance for creature or not in our map are not visible too
8879 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8880 return false;
8883 else if(GetCharmerOrOwnerGUID()) // distance for show pet/charmed
8885 // Pet/charmed far than max visible distance for player or not in our map are not visible too
8886 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForPlayer()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8887 return false;
8889 else // distance for show creature
8891 // Units far than max visible distance for creature or not in our map are not visible too
8892 if (!IsWithinDistInMap(u,World::GetMaxVisibleDistanceForCreature()+(inVisibleList ? World::GetVisibleUnitGreyDistance() : 0.0f), is3dDistance))
8893 return false;
8896 // Visible units, always are visible for all units, except for units under invisibility and phases
8897 if (m_Visibility == VISIBILITY_ON && u->m_invisibilityMask==0 && InSamePhase(u))
8898 return true;
8900 // GMs see any players, not higher GMs and all units in any phase
8901 if (u->GetTypeId() == TYPEID_PLAYER && ((Player *)u)->isGameMaster())
8903 if(GetTypeId() == TYPEID_PLAYER)
8904 return ((Player *)this)->GetSession()->GetSecurity() <= ((Player *)u)->GetSession()->GetSecurity();
8905 else
8906 return true;
8909 // non faction visibility non-breakable for non-GMs
8910 if (m_Visibility == VISIBILITY_OFF)
8911 return false;
8913 // phased visibility (both must phased in same way)
8914 if(!InSamePhase(u))
8915 return false;
8917 // raw invisibility
8918 bool invisible = (m_invisibilityMask != 0 || u->m_invisibilityMask !=0);
8920 // detectable invisibility case
8921 if( invisible && (
8922 // Invisible units, always are visible for units under same invisibility type
8923 (m_invisibilityMask & u->m_invisibilityMask)!=0 ||
8924 // Invisible units, always are visible for unit that can detect this invisibility (have appropriate level for detect)
8925 u->canDetectInvisibilityOf(this) ||
8926 // Units that can detect invisibility always are visible for units that can be detected
8927 canDetectInvisibilityOf(u) ))
8929 invisible = false;
8932 // special cases for always overwrite invisibility/stealth
8933 if(invisible || m_Visibility == VISIBILITY_GROUP_STEALTH)
8935 // non-hostile case
8936 if (!u->IsHostileTo(this))
8938 // 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)
8939 if(GetTypeId()==TYPEID_PLAYER && u->GetTypeId()==TYPEID_PLAYER)
8941 if(((Player*)this)->IsGroupVisibleFor(((Player*)u)))
8942 return true;
8944 // else apply same rules as for hostile case (detecting check for stealth)
8947 // hostile case
8948 else
8950 // Hunter mark functionality
8951 AuraList const& auras = GetAurasByType(SPELL_AURA_MOD_STALKED);
8952 for(AuraList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
8953 if((*iter)->GetCasterGUID()==u->GetGUID())
8954 return true;
8956 // else apply detecting check for stealth
8959 // none other cases for detect invisibility, so invisible
8960 if(invisible)
8961 return false;
8963 // else apply stealth detecting check
8966 // unit got in stealth in this moment and must ignore old detected state
8967 if (m_Visibility == VISIBILITY_GROUP_NO_DETECT)
8968 return false;
8970 // GM invisibility checks early, invisibility if any detectable, so if not stealth then visible
8971 if (m_Visibility != VISIBILITY_GROUP_STEALTH)
8972 return true;
8974 // NOW ONLY STEALTH CASE
8976 // stealth and detected and visible for some seconds
8977 if (u->GetTypeId() == TYPEID_PLAYER && ((Player*)u)->m_DetectInvTimer > 300 && ((Player*)u)->HaveAtClient(this))
8978 return true;
8980 //if in non-detect mode then invisible for unit
8981 if (!detect)
8982 return false;
8984 // Special cases
8986 // If is attacked then stealth is lost, some creature can use stealth too
8987 if( !getAttackers().empty() )
8988 return true;
8990 // If there is collision rogue is seen regardless of level difference
8991 // TODO: check sizes in DB
8992 float distance = GetDistance(u);
8993 if (distance < 0.24f)
8994 return true;
8996 //If a mob or player is stunned he will not be able to detect stealth
8997 if (u->hasUnitState(UNIT_STAT_STUNNED) && (u != this))
8998 return false;
9000 // Creature can detect target only in aggro radius
9001 if(u->GetTypeId() != TYPEID_PLAYER)
9003 //Always invisible from back and out of aggro range
9004 bool isInFront = u->isInFront(this,((Creature const*)u)->GetAttackDistance(this));
9005 if(!isInFront)
9006 return false;
9008 else
9010 //Always invisible from back
9011 bool isInFront = u->isInFront(this,(GetTypeId()==TYPEID_PLAYER || GetCharmerOrOwnerGUID()) ? World::GetMaxVisibleDistanceForPlayer() : World::GetMaxVisibleDistanceForCreature());
9012 if(!isInFront)
9013 return false;
9016 // if doesn't have stealth detection (Shadow Sight), then check how stealthy the unit is, otherwise just check los
9017 if(!u->HasAuraType(SPELL_AURA_DETECT_STEALTH))
9019 //Calculation if target is in front
9021 //Visible distance based on stealth value (stealth rank 4 300MOD, 10.5 - 3 = 7.5)
9022 float visibleDistance = 10.5f - (GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH)/100.0f);
9024 //Visible distance is modified by
9025 //-Level Diff (every level diff = 1.0f in visible distance)
9026 visibleDistance += int32(u->getLevelForTarget(this)) - int32(getLevelForTarget(u));
9028 //This allows to check talent tree and will add addition stealth dependent on used points)
9029 int32 stealthMod = GetTotalAuraModifier(SPELL_AURA_MOD_STEALTH_LEVEL);
9030 if(stealthMod < 0)
9031 stealthMod = 0;
9033 //-Stealth Mod(positive like Master of Deception) and Stealth Detection(negative like paranoia)
9034 //based on wowwiki every 5 mod we have 1 more level diff in calculation
9035 visibleDistance += (int32(u->GetTotalAuraModifier(SPELL_AURA_MOD_DETECT)) - stealthMod)/5.0f;
9037 if(distance > visibleDistance)
9038 return false;
9041 // Now check is target visible with LoS
9042 float ox,oy,oz;
9043 u->GetPosition(ox,oy,oz);
9044 return IsWithinLOS(ox,oy,oz);
9047 void Unit::SetVisibility(UnitVisibility x)
9049 m_Visibility = x;
9051 if(IsInWorld())
9053 Map *m = GetMap();
9055 if(GetTypeId()==TYPEID_PLAYER)
9056 m->PlayerRelocation((Player*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9057 else
9058 m->CreatureRelocation((Creature*)this,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
9062 bool Unit::canDetectInvisibilityOf(Unit const* u) const
9064 if(uint32 mask = (m_detectInvisibilityMask & u->m_invisibilityMask))
9066 for(uint32 i = 0; i < 10; ++i)
9068 if(((1 << i) & mask)==0)
9069 continue;
9071 // find invisibility level
9072 uint32 invLevel = 0;
9073 Unit::AuraList const& iAuras = u->GetAurasByType(SPELL_AURA_MOD_INVISIBILITY);
9074 for(Unit::AuraList::const_iterator itr = iAuras.begin(); itr != iAuras.end(); ++itr)
9075 if(((*itr)->GetModifier()->m_miscvalue)==i && invLevel < (*itr)->GetModifier()->m_amount)
9076 invLevel = (*itr)->GetModifier()->m_amount;
9078 // find invisibility detect level
9079 uint32 detectLevel = 0;
9080 Unit::AuraList const& dAuras = GetAurasByType(SPELL_AURA_MOD_INVISIBILITY_DETECTION);
9081 for(Unit::AuraList::const_iterator itr = dAuras.begin(); itr != dAuras.end(); ++itr)
9082 if(((*itr)->GetModifier()->m_miscvalue)==i && detectLevel < (*itr)->GetModifier()->m_amount)
9083 detectLevel = (*itr)->GetModifier()->m_amount;
9085 if(i==6 && GetTypeId()==TYPEID_PLAYER) // special drunk detection case
9087 detectLevel = ((Player*)this)->GetDrunkValue();
9090 if(invLevel <= detectLevel)
9091 return true;
9095 return false;
9098 void Unit::UpdateSpeed(UnitMoveType mtype, bool forced)
9100 int32 main_speed_mod = 0;
9101 float stack_bonus = 1.0f;
9102 float non_stack_bonus = 1.0f;
9104 switch(mtype)
9106 case MOVE_WALK:
9107 return;
9108 case MOVE_RUN:
9110 if (IsMounted()) // Use on mount auras
9112 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED);
9113 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS);
9114 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f;
9116 else
9118 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED);
9119 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS);
9120 non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f;
9122 break;
9124 case MOVE_RUN_BACK:
9125 return;
9126 case MOVE_SWIM:
9128 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SWIM_SPEED);
9129 break;
9131 case MOVE_SWIM_BACK:
9132 return;
9133 case MOVE_FLIGHT:
9135 if (IsMounted()) // Use on mount auras
9136 main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
9137 else // Use not mount (shapeshift for example) auras (should stack)
9138 main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_SPEED_FLIGHT);
9139 stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_FLIGHT_SPEED_ALWAYS);
9140 non_stack_bonus = (100.0 + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f;
9141 break;
9143 case MOVE_FLIGHT_BACK:
9144 return;
9145 default:
9146 sLog.outError("Unit::UpdateSpeed: Unsupported move type (%d)", mtype);
9147 return;
9150 float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus;
9151 // now we ready for speed calculation
9152 float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus;
9154 switch(mtype)
9156 case MOVE_RUN:
9157 case MOVE_SWIM:
9158 case MOVE_FLIGHT:
9160 // Normalize speed by 191 aura SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED if need
9161 // TODO: possible affect only on MOVE_RUN
9162 if(int32 normalization = GetMaxPositiveAuraModifier(SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED))
9164 // Use speed from aura
9165 float max_speed = normalization / baseMoveSpeed[mtype];
9166 if (speed > max_speed)
9167 speed = max_speed;
9169 break;
9171 default:
9172 break;
9175 // Apply strongest slow aura mod to speed
9176 int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED);
9177 if (slow)
9178 speed *=(100.0f + slow)/100.0f;
9179 SetSpeed(mtype, speed, forced);
9182 float Unit::GetSpeed( UnitMoveType mtype ) const
9184 return m_speed_rate[mtype]*baseMoveSpeed[mtype];
9187 void Unit::SetSpeed(UnitMoveType mtype, float rate, bool forced)
9189 if (rate < 0)
9190 rate = 0.0f;
9192 // Update speed only on change
9193 if (m_speed_rate[mtype] == rate)
9194 return;
9196 m_speed_rate[mtype] = rate;
9198 propagateSpeedChange();
9200 WorldPacket data;
9201 if(!forced)
9203 switch(mtype)
9205 case MOVE_WALK:
9206 data.Initialize(MSG_MOVE_SET_WALK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9207 break;
9208 case MOVE_RUN:
9209 data.Initialize(MSG_MOVE_SET_RUN_SPEED, 8+4+2+4+4+4+4+4+4+4);
9210 break;
9211 case MOVE_RUN_BACK:
9212 data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9213 break;
9214 case MOVE_SWIM:
9215 data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 8+4+2+4+4+4+4+4+4+4);
9216 break;
9217 case MOVE_SWIM_BACK:
9218 data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9219 break;
9220 case MOVE_TURN_RATE:
9221 data.Initialize(MSG_MOVE_SET_TURN_RATE, 8+4+2+4+4+4+4+4+4+4);
9222 break;
9223 case MOVE_FLIGHT:
9224 data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 8+4+2+4+4+4+4+4+4+4);
9225 break;
9226 case MOVE_FLIGHT_BACK:
9227 data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 8+4+2+4+4+4+4+4+4+4);
9228 break;
9229 case MOVE_PITCH_RATE:
9230 data.Initialize(MSG_MOVE_SET_PITCH_RATE, 8+4+2+4+4+4+4+4+4+4);
9231 break;
9232 default:
9233 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9234 return;
9237 data.append(GetPackGUID());
9238 data << uint32(0); // movement flags
9239 data << uint16(0); // unk flags
9240 data << uint32(getMSTime());
9241 data << float(GetPositionX());
9242 data << float(GetPositionY());
9243 data << float(GetPositionZ());
9244 data << float(GetOrientation());
9245 data << uint32(0); // fall time
9246 data << float(GetSpeed(mtype));
9247 SendMessageToSet( &data, true );
9249 else
9251 if(GetTypeId() == TYPEID_PLAYER)
9253 // register forced speed changes for WorldSession::HandleForceSpeedChangeAck
9254 // and do it only for real sent packets and use run for run/mounted as client expected
9255 ++((Player*)this)->m_forced_speed_changes[mtype];
9258 switch(mtype)
9260 case MOVE_WALK:
9261 data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE, 16);
9262 break;
9263 case MOVE_RUN:
9264 data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE, 17);
9265 break;
9266 case MOVE_RUN_BACK:
9267 data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE, 16);
9268 break;
9269 case MOVE_SWIM:
9270 data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE, 16);
9271 break;
9272 case MOVE_SWIM_BACK:
9273 data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, 16);
9274 break;
9275 case MOVE_TURN_RATE:
9276 data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE, 16);
9277 break;
9278 case MOVE_FLIGHT:
9279 data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE, 16);
9280 break;
9281 case MOVE_FLIGHT_BACK:
9282 data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, 16);
9283 break;
9284 case MOVE_PITCH_RATE:
9285 data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE, 16);
9286 break;
9287 default:
9288 sLog.outError("Unit::SetSpeed: Unsupported move type (%d), data not sent to client.",mtype);
9289 return;
9291 data.append(GetPackGUID());
9292 data << (uint32)0; // moveEvent, NUM_PMOVE_EVTS = 0x39
9293 if (mtype == MOVE_RUN)
9294 data << uint8(0); // new 2.1.0
9295 data << float(GetSpeed(mtype));
9296 SendMessageToSet( &data, true );
9298 if(Pet* pet = GetPet())
9299 pet->SetSpeed(MOVE_RUN, m_speed_rate[mtype],forced);
9302 void Unit::SetHover(bool on)
9304 if(on)
9305 CastSpell(this,11010,true);
9306 else
9307 RemoveAurasDueToSpell(11010);
9310 void Unit::setDeathState(DeathState s)
9312 if (s != ALIVE && s!= JUST_ALIVED)
9314 CombatStop();
9315 DeleteThreatList();
9316 ClearComboPointHolders(); // any combo points pointed to unit lost at it death
9318 if(IsNonMeleeSpellCasted(false))
9319 InterruptNonMeleeSpells(false);
9322 if (s == JUST_DIED)
9324 RemoveAllAurasOnDeath();
9325 UnsummonAllTotems();
9327 ModifyAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, false);
9328 ModifyAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, false);
9329 // remove aurastates allowing special moves
9330 ClearAllReactives();
9331 ClearDiminishings();
9333 else if(s == JUST_ALIVED)
9335 RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); // clear skinnable for creature and player (at battleground)
9338 if (m_deathState != ALIVE && s == ALIVE)
9340 //_ApplyAllAuraMods();
9342 m_deathState = s;
9345 /*########################################
9346 ######## ########
9347 ######## AGGRO SYSTEM ########
9348 ######## ########
9349 ########################################*/
9350 bool Unit::CanHaveThreatList() const
9352 // only creatures can have threat list
9353 if( GetTypeId() != TYPEID_UNIT )
9354 return false;
9356 // only alive units can have threat list
9357 if( !isAlive() )
9358 return false;
9360 // totems can not have threat list
9361 if( ((Creature*)this)->isTotem() )
9362 return false;
9364 // vehicles can not have threat list
9365 if( ((Creature*)this)->isVehicle() )
9366 return false;
9368 // pets can not have a threat list, unless they are controlled by a creature
9369 if( ((Creature*)this)->isPet() && IS_PLAYER_GUID(((Pet*)this)->GetOwnerGUID()) )
9370 return false;
9372 return true;
9375 //======================================================================
9377 float Unit::ApplyTotalThreatModifier(float threat, SpellSchoolMask schoolMask)
9379 if(!HasAuraType(SPELL_AURA_MOD_THREAT))
9380 return threat;
9382 SpellSchools school = GetFirstSchoolInMask(schoolMask);
9384 return threat * m_threatModifier[school];
9387 //======================================================================
9389 void Unit::AddThreat(Unit* pVictim, float threat, SpellSchoolMask schoolMask, SpellEntry const *threatSpell)
9391 // Only mobs can manage threat lists
9392 if(CanHaveThreatList())
9393 m_ThreatManager.addThreat(pVictim, threat, schoolMask, threatSpell);
9396 //======================================================================
9398 void Unit::DeleteThreatList()
9400 m_ThreatManager.clearReferences();
9403 //======================================================================
9405 void Unit::TauntApply(Unit* taunter)
9407 assert(GetTypeId()== TYPEID_UNIT);
9409 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9410 return;
9412 if(!CanHaveThreatList())
9413 return;
9415 Unit *target = getVictim();
9416 if(target && target == taunter)
9417 return;
9419 SetInFront(taunter);
9420 if (((Creature*)this)->AI())
9421 ((Creature*)this)->AI()->AttackStart(taunter);
9423 m_ThreatManager.tauntApply(taunter);
9426 //======================================================================
9428 void Unit::TauntFadeOut(Unit *taunter)
9430 assert(GetTypeId()== TYPEID_UNIT);
9432 if(!taunter || (taunter->GetTypeId() == TYPEID_PLAYER && ((Player*)taunter)->isGameMaster()))
9433 return;
9435 if(!CanHaveThreatList())
9436 return;
9438 Unit *target = getVictim();
9439 if(!target || target != taunter)
9440 return;
9442 if(m_ThreatManager.isThreatListEmpty())
9444 if(((Creature*)this)->AI())
9445 ((Creature*)this)->AI()->EnterEvadeMode();
9446 return;
9449 m_ThreatManager.tauntFadeOut(taunter);
9450 target = m_ThreatManager.getHostilTarget();
9452 if (target && target != taunter)
9454 SetInFront(target);
9455 if (((Creature*)this)->AI())
9456 ((Creature*)this)->AI()->AttackStart(target);
9460 //======================================================================
9462 bool Unit::SelectHostilTarget()
9464 //function provides main threat functionality
9465 //next-victim-selection algorithm and evade mode are called
9466 //threat list sorting etc.
9468 assert(GetTypeId()== TYPEID_UNIT);
9470 if (!this->isAlive())
9471 return false;
9472 //This function only useful once AI has been initialized
9473 if (!((Creature*)this)->AI())
9474 return false;
9476 Unit* target = NULL;
9478 // First checking if we have some taunt on us
9479 const AuraList& tauntAuras = GetAurasByType(SPELL_AURA_MOD_TAUNT);
9480 if ( !tauntAuras.empty() )
9482 Unit* caster;
9484 // The last taunt aura caster is alive an we are happy to attack him
9485 if ( (caster = tauntAuras.back()->GetCaster()) && caster->isAlive() )
9486 return true;
9487 else if (tauntAuras.size() > 1)
9489 // We do not have last taunt aura caster but we have more taunt auras,
9490 // so find first available target
9492 // Auras are pushed_back, last caster will be on the end
9493 AuraList::const_iterator aura = --tauntAuras.end();
9496 --aura;
9497 if ( (caster = (*aura)->GetCaster()) &&
9498 caster->IsInMap(this) && caster->isTargetableForAttack() && caster->isInAccessablePlaceFor((Creature*)this) )
9500 target = caster;
9501 break;
9503 }while (aura != tauntAuras.begin());
9507 if ( !target && !m_ThreatManager.isThreatListEmpty() )
9508 // No taunt aura or taunt aura caster is dead standart target selection
9509 target = m_ThreatManager.getHostilTarget();
9511 if(target)
9513 if(!hasUnitState(UNIT_STAT_STUNNED))
9514 SetInFront(target);
9515 ((Creature*)this)->AI()->AttackStart(target);
9516 return true;
9519 // no target but something prevent go to evade mode
9520 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_TAUNT) )
9521 return false;
9523 // last case when creature don't must go to evade mode:
9524 // it in combat but attacker not make any damage and not enter to aggro radius to have record in threat list
9525 // for example at owner command to pet attack some far away creature
9526 // Note: creature not have targeted movement generator but have attacker in this case
9527 if( GetMotionMaster()->GetCurrentMovementGeneratorType() != TARGETED_MOTION_TYPE )
9529 for(AttackerSet::const_iterator itr = m_attackers.begin(); itr != m_attackers.end(); ++itr)
9531 if( (*itr)->IsInMap(this) && (*itr)->isTargetableForAttack() && (*itr)->isInAccessablePlaceFor((Creature*)this) )
9532 return false;
9536 // enter in evade mode in other case
9537 ((Creature*)this)->AI()->EnterEvadeMode();
9539 return false;
9542 //======================================================================
9543 //======================================================================
9544 //======================================================================
9546 int32 Unit::CalculateSpellDamage(SpellEntry const* spellProto, uint8 effect_index, int32 effBasePoints, Unit const* target)
9548 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9550 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9552 int32 level = int32(getLevel());
9553 if (level > (int32)spellProto->maxLevel && spellProto->maxLevel > 0)
9554 level = (int32)spellProto->maxLevel;
9555 else if (level < (int32)spellProto->baseLevel)
9556 level = (int32)spellProto->baseLevel;
9557 level-= (int32)spellProto->spellLevel;
9559 float basePointsPerLevel = spellProto->EffectRealPointsPerLevel[effect_index];
9560 float randomPointsPerLevel = spellProto->EffectDicePerLevel[effect_index];
9561 int32 basePoints = int32(effBasePoints + level * basePointsPerLevel);
9562 int32 randomPoints = int32(spellProto->EffectDieSides[effect_index] + level * randomPointsPerLevel);
9563 float comboDamage = spellProto->EffectPointsPerComboPoint[effect_index];
9565 // range can have possitive and negative values, so order its for irand
9566 int32 randvalue = int32(spellProto->EffectBaseDice[effect_index]) >= randomPoints
9567 ? irand(randomPoints, int32(spellProto->EffectBaseDice[effect_index]))
9568 : irand(int32(spellProto->EffectBaseDice[effect_index]), randomPoints);
9570 int32 value = basePoints + randvalue;
9571 //random damage
9572 if(comboDamage != 0 && unitPlayer && target && (target->GetGUID() == unitPlayer->GetComboTarget()))
9573 value += (int32)(comboDamage * comboPoints);
9575 if(Player* modOwner = GetSpellModOwner())
9577 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value);
9578 switch(effect_index)
9580 case 0:
9581 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value);
9582 break;
9583 case 1:
9584 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value);
9585 break;
9586 case 2:
9587 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value);
9588 break;
9592 if(spellProto->Attributes & SPELL_ATTR_LEVEL_DAMAGE_CALCULATION && spellProto->spellLevel &&
9593 spellProto->Effect[effect_index] != SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &&
9594 spellProto->Effect[effect_index] != SPELL_EFFECT_KNOCK_BACK)
9595 value = int32(value*0.25f*exp(getLevel()*(70-spellProto->spellLevel)/1000.0f));
9597 return value;
9600 int32 Unit::CalculateSpellDuration(SpellEntry const* spellProto, uint8 effect_index, Unit const* target)
9602 Player* unitPlayer = (GetTypeId() == TYPEID_PLAYER) ? (Player*)this : NULL;
9604 uint8 comboPoints = unitPlayer ? unitPlayer->GetComboPoints() : 0;
9606 int32 minduration = GetSpellDuration(spellProto);
9607 int32 maxduration = GetSpellMaxDuration(spellProto);
9609 int32 duration;
9611 if( minduration != -1 && minduration != maxduration )
9612 duration = minduration + int32((maxduration - minduration) * comboPoints / 5);
9613 else
9614 duration = minduration;
9616 if (duration > 0)
9618 int32 mechanic = GetEffectMechanic(spellProto, effect_index);
9619 // Find total mod value (negative bonus)
9620 int32 durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD, mechanic);
9621 // Modify from SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL aura (stack always ?)
9622 durationMod_always+=target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL, spellProto->Dispel);
9623 // Find max mod (negative bonus)
9624 int32 durationMod_not_stack = target->GetMaxNegativeAuraModifierByMiscValue(SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK, mechanic);
9626 int32 durationMod = 0;
9627 // Select strongest negative mod
9628 if (durationMod_always > durationMod_not_stack)
9629 durationMod = durationMod_not_stack;
9630 else
9631 durationMod = durationMod_always;
9633 if (durationMod != 0)
9634 duration = int32(int64(duration) * (100+durationMod) /100);
9636 if (duration < 0) duration = 0;
9639 return duration;
9642 DiminishingLevels Unit::GetDiminishing(DiminishingGroup group)
9644 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9646 if(i->DRGroup != group)
9647 continue;
9649 if(!i->hitCount)
9650 return DIMINISHING_LEVEL_1;
9652 if(!i->hitTime)
9653 return DIMINISHING_LEVEL_1;
9655 // If last spell was casted more than 15 seconds ago - reset the count.
9656 if(i->stack==0 && getMSTimeDiff(i->hitTime,getMSTime()) > 15000)
9658 i->hitCount = DIMINISHING_LEVEL_1;
9659 return DIMINISHING_LEVEL_1;
9661 // or else increase the count.
9662 else
9664 return DiminishingLevels(i->hitCount);
9667 return DIMINISHING_LEVEL_1;
9670 void Unit::IncrDiminishing(DiminishingGroup group)
9672 // Checking for existing in the table
9673 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9675 if(i->DRGroup != group)
9676 continue;
9677 if(i->hitCount < DIMINISHING_LEVEL_IMMUNE)
9678 i->hitCount += 1;
9679 return;
9681 m_Diminishing.push_back(DiminishingReturn(group,getMSTime(),DIMINISHING_LEVEL_2));
9684 void Unit::ApplyDiminishingToDuration(DiminishingGroup group, int32 &duration,Unit* caster,DiminishingLevels Level)
9686 if(duration == -1 || group == DIMINISHING_NONE || caster->IsFriendlyTo(this) )
9687 return;
9689 // Duration of crowd control abilities on pvp target is limited by 10 sec. (2.2.0)
9690 if(duration > 10000 && IsDiminishingReturnsGroupDurationLimited(group))
9692 // test pet/charm masters instead pets/charmeds
9693 Unit const* targetOwner = GetCharmerOrOwner();
9694 Unit const* casterOwner = caster->GetCharmerOrOwner();
9696 Unit const* target = targetOwner ? targetOwner : this;
9697 Unit const* source = casterOwner ? casterOwner : caster;
9699 if(target->GetTypeId() == TYPEID_PLAYER && source->GetTypeId() == TYPEID_PLAYER)
9700 duration = 10000;
9703 float mod = 1.0f;
9705 // Some diminishings applies to mobs too (for example, Stun)
9706 if((GetDiminishingReturnsGroupType(group) == DRTYPE_PLAYER && GetTypeId() == TYPEID_PLAYER) || GetDiminishingReturnsGroupType(group) == DRTYPE_ALL)
9708 DiminishingLevels diminish = Level;
9709 switch(diminish)
9711 case DIMINISHING_LEVEL_1: break;
9712 case DIMINISHING_LEVEL_2: mod = 0.5f; break;
9713 case DIMINISHING_LEVEL_3: mod = 0.25f; break;
9714 case DIMINISHING_LEVEL_IMMUNE: mod = 0.0f;break;
9715 default: break;
9719 duration = int32(duration * mod);
9722 void Unit::ApplyDiminishingAura( DiminishingGroup group, bool apply )
9724 // Checking for existing in the table
9725 for(Diminishing::iterator i = m_Diminishing.begin(); i != m_Diminishing.end(); ++i)
9727 if(i->DRGroup != group)
9728 continue;
9730 if(apply)
9731 i->stack += 1;
9732 else if(i->stack)
9734 i->stack -= 1;
9735 // Remember time after last aura from group removed
9736 if (i->stack == 0)
9737 i->hitTime = getMSTime();
9739 break;
9743 Unit* Unit::GetUnit(WorldObject& object, uint64 guid)
9745 return ObjectAccessor::GetUnit(object,guid);
9748 bool Unit::isVisibleForInState( Player const* u, bool inVisibleList ) const
9750 return isVisibleForOrDetect(u, false, inVisibleList, false);
9753 uint32 Unit::GetCreatureType() const
9755 if(GetTypeId() == TYPEID_PLAYER)
9757 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
9758 if(ssEntry && ssEntry->creatureType > 0)
9759 return ssEntry->creatureType;
9760 else
9761 return CREATURE_TYPE_HUMANOID;
9763 else
9764 return ((Creature*)this)->GetCreatureInfo()->type;
9767 /*#######################################
9768 ######## ########
9769 ######## STAT SYSTEM ########
9770 ######## ########
9771 #######################################*/
9773 bool Unit::HandleStatModifier(UnitMods unitMod, UnitModifierType modifierType, float amount, bool apply)
9775 if(unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9777 sLog.outError("ERROR in HandleStatModifier(): non existed UnitMods or wrong UnitModifierType!");
9778 return false;
9781 float val = 1.0f;
9783 switch(modifierType)
9785 case BASE_VALUE:
9786 case TOTAL_VALUE:
9787 m_auraModifiersGroup[unitMod][modifierType] += apply ? amount : -amount;
9788 break;
9789 case BASE_PCT:
9790 case TOTAL_PCT:
9791 if(amount <= -100.0f) //small hack-fix for -100% modifiers
9792 amount = -200.0f;
9794 val = (100.0f + amount) / 100.0f;
9795 m_auraModifiersGroup[unitMod][modifierType] *= apply ? val : (1.0f/val);
9796 break;
9798 default:
9799 break;
9802 if(!CanModifyStats())
9803 return false;
9805 switch(unitMod)
9807 case UNIT_MOD_STAT_STRENGTH:
9808 case UNIT_MOD_STAT_AGILITY:
9809 case UNIT_MOD_STAT_STAMINA:
9810 case UNIT_MOD_STAT_INTELLECT:
9811 case UNIT_MOD_STAT_SPIRIT: UpdateStats(GetStatByAuraGroup(unitMod)); break;
9813 case UNIT_MOD_ARMOR: UpdateArmor(); break;
9814 case UNIT_MOD_HEALTH: UpdateMaxHealth(); break;
9816 case UNIT_MOD_MANA:
9817 case UNIT_MOD_RAGE:
9818 case UNIT_MOD_FOCUS:
9819 case UNIT_MOD_ENERGY:
9820 case UNIT_MOD_HAPPINESS:
9821 case UNIT_MOD_RUNE:
9822 case UNIT_MOD_RUNIC_POWER: UpdateMaxPower(GetPowerTypeByAuraGroup(unitMod)); break;
9824 case UNIT_MOD_RESISTANCE_HOLY:
9825 case UNIT_MOD_RESISTANCE_FIRE:
9826 case UNIT_MOD_RESISTANCE_NATURE:
9827 case UNIT_MOD_RESISTANCE_FROST:
9828 case UNIT_MOD_RESISTANCE_SHADOW:
9829 case UNIT_MOD_RESISTANCE_ARCANE: UpdateResistances(GetSpellSchoolByAuraGroup(unitMod)); break;
9831 case UNIT_MOD_ATTACK_POWER: UpdateAttackPowerAndDamage(); break;
9832 case UNIT_MOD_ATTACK_POWER_RANGED: UpdateAttackPowerAndDamage(true); break;
9834 case UNIT_MOD_DAMAGE_MAINHAND: UpdateDamagePhysical(BASE_ATTACK); break;
9835 case UNIT_MOD_DAMAGE_OFFHAND: UpdateDamagePhysical(OFF_ATTACK); break;
9836 case UNIT_MOD_DAMAGE_RANGED: UpdateDamagePhysical(RANGED_ATTACK); break;
9838 default:
9839 break;
9842 return true;
9845 float Unit::GetModifierValue(UnitMods unitMod, UnitModifierType modifierType) const
9847 if( unitMod >= UNIT_MOD_END || modifierType >= MODIFIER_TYPE_END)
9849 sLog.outError("trial to access non existed modifier value from UnitMods!");
9850 return 0.0f;
9853 if(modifierType == TOTAL_PCT && m_auraModifiersGroup[unitMod][modifierType] <= 0.0f)
9854 return 0.0f;
9856 return m_auraModifiersGroup[unitMod][modifierType];
9859 float Unit::GetTotalStatValue(Stats stat) const
9861 UnitMods unitMod = UnitMods(UNIT_MOD_STAT_START + stat);
9863 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9864 return 0.0f;
9866 // value = ((base_value * base_pct) + total_value) * total_pct
9867 float value = m_auraModifiersGroup[unitMod][BASE_VALUE] + GetCreateStat(stat);
9868 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9869 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9870 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9872 return value;
9875 float Unit::GetTotalAuraModValue(UnitMods unitMod) const
9877 if(unitMod >= UNIT_MOD_END)
9879 sLog.outError("trial to access non existed UnitMods in GetTotalAuraModValue()!");
9880 return 0.0f;
9883 if(m_auraModifiersGroup[unitMod][TOTAL_PCT] <= 0.0f)
9884 return 0.0f;
9886 float value = m_auraModifiersGroup[unitMod][BASE_VALUE];
9887 value *= m_auraModifiersGroup[unitMod][BASE_PCT];
9888 value += m_auraModifiersGroup[unitMod][TOTAL_VALUE];
9889 value *= m_auraModifiersGroup[unitMod][TOTAL_PCT];
9891 return value;
9894 SpellSchools Unit::GetSpellSchoolByAuraGroup(UnitMods unitMod) const
9896 SpellSchools school = SPELL_SCHOOL_NORMAL;
9898 switch(unitMod)
9900 case UNIT_MOD_RESISTANCE_HOLY: school = SPELL_SCHOOL_HOLY; break;
9901 case UNIT_MOD_RESISTANCE_FIRE: school = SPELL_SCHOOL_FIRE; break;
9902 case UNIT_MOD_RESISTANCE_NATURE: school = SPELL_SCHOOL_NATURE; break;
9903 case UNIT_MOD_RESISTANCE_FROST: school = SPELL_SCHOOL_FROST; break;
9904 case UNIT_MOD_RESISTANCE_SHADOW: school = SPELL_SCHOOL_SHADOW; break;
9905 case UNIT_MOD_RESISTANCE_ARCANE: school = SPELL_SCHOOL_ARCANE; break;
9907 default:
9908 break;
9911 return school;
9914 Stats Unit::GetStatByAuraGroup(UnitMods unitMod) const
9916 Stats stat = STAT_STRENGTH;
9918 switch(unitMod)
9920 case UNIT_MOD_STAT_STRENGTH: stat = STAT_STRENGTH; break;
9921 case UNIT_MOD_STAT_AGILITY: stat = STAT_AGILITY; break;
9922 case UNIT_MOD_STAT_STAMINA: stat = STAT_STAMINA; break;
9923 case UNIT_MOD_STAT_INTELLECT: stat = STAT_INTELLECT; break;
9924 case UNIT_MOD_STAT_SPIRIT: stat = STAT_SPIRIT; break;
9926 default:
9927 break;
9930 return stat;
9933 Powers Unit::GetPowerTypeByAuraGroup(UnitMods unitMod) const
9935 switch(unitMod)
9937 case UNIT_MOD_MANA: return POWER_MANA;
9938 case UNIT_MOD_RAGE: return POWER_RAGE;
9939 case UNIT_MOD_FOCUS: return POWER_FOCUS;
9940 case UNIT_MOD_ENERGY: return POWER_ENERGY;
9941 case UNIT_MOD_HAPPINESS: return POWER_HAPPINESS;
9942 case UNIT_MOD_RUNE: return POWER_RUNE;
9943 case UNIT_MOD_RUNIC_POWER:return POWER_RUNIC_POWER;
9946 return POWER_MANA;
9949 float Unit::GetTotalAttackPowerValue(WeaponAttackType attType) const
9951 if (attType == RANGED_ATTACK)
9953 int32 ap = GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS);
9954 if (ap < 0)
9955 return 0.0f;
9956 return ap * (1.0f + GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER));
9958 else
9960 int32 ap = GetInt32Value(UNIT_FIELD_ATTACK_POWER) + GetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS);
9961 if (ap < 0)
9962 return 0.0f;
9963 return ap * (1.0f + GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER));
9967 float Unit::GetWeaponDamageRange(WeaponAttackType attType ,WeaponDamageRange type) const
9969 if (attType == OFF_ATTACK && !haveOffhandWeapon())
9970 return 0.0f;
9972 return m_weaponDamage[attType][type];
9975 void Unit::SetLevel(uint32 lvl)
9977 SetUInt32Value(UNIT_FIELD_LEVEL, lvl);
9979 // group update
9980 if ((GetTypeId() == TYPEID_PLAYER) && ((Player*)this)->GetGroup())
9981 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_LEVEL);
9984 void Unit::SetHealth(uint32 val)
9986 uint32 maxHealth = GetMaxHealth();
9987 if(maxHealth < val)
9988 val = maxHealth;
9990 SetUInt32Value(UNIT_FIELD_HEALTH, val);
9992 // group update
9993 if(GetTypeId() == TYPEID_PLAYER)
9995 if(((Player*)this)->GetGroup())
9996 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_HP);
9998 else if(((Creature*)this)->isPet())
10000 Pet *pet = ((Pet*)this);
10001 if(pet->isControlled())
10003 Unit *owner = GetOwner();
10004 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10005 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_HP);
10010 void Unit::SetMaxHealth(uint32 val)
10012 uint32 health = GetHealth();
10013 SetUInt32Value(UNIT_FIELD_MAXHEALTH, val);
10015 // group update
10016 if(GetTypeId() == TYPEID_PLAYER)
10018 if(((Player*)this)->GetGroup())
10019 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_HP);
10021 else if(((Creature*)this)->isPet())
10023 Pet *pet = ((Pet*)this);
10024 if(pet->isControlled())
10026 Unit *owner = GetOwner();
10027 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10028 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_HP);
10032 if(val < health)
10033 SetHealth(val);
10036 void Unit::SetPower(Powers power, uint32 val)
10038 if(GetPower(power) == val)
10039 return;
10041 uint32 maxPower = GetMaxPower(power);
10042 if(maxPower < val)
10043 val = maxPower;
10045 SetStatInt32Value(UNIT_FIELD_POWER1 + power, val);
10047 WorldPacket data(SMSG_POWER_UPDATE);
10048 data.append(GetPackGUID());
10049 data << uint8(power);
10050 data << uint32(val);
10051 SendMessageToSet(&data, GetTypeId() == TYPEID_PLAYER ? true : false);
10053 // group update
10054 if(GetTypeId() == TYPEID_PLAYER)
10056 if(((Player*)this)->GetGroup())
10057 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10059 else if(((Creature*)this)->isPet())
10061 Pet *pet = ((Pet*)this);
10062 if(pet->isControlled())
10064 Unit *owner = GetOwner();
10065 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10066 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10069 // Update the pet's character sheet with happiness damage bonus
10070 if(pet->getPetType() == HUNTER_PET && power == POWER_HAPPINESS)
10072 pet->UpdateDamagePhysical(BASE_ATTACK);
10077 void Unit::SetMaxPower(Powers power, uint32 val)
10079 uint32 cur_power = GetPower(power);
10080 SetStatInt32Value(UNIT_FIELD_MAXPOWER1 + power, val);
10082 // group update
10083 if(GetTypeId() == TYPEID_PLAYER)
10085 if(((Player*)this)->GetGroup())
10086 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10088 else if(((Creature*)this)->isPet())
10090 Pet *pet = ((Pet*)this);
10091 if(pet->isControlled())
10093 Unit *owner = GetOwner();
10094 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10095 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10099 if(val < cur_power)
10100 SetPower(power, val);
10103 void Unit::ApplyPowerMod(Powers power, uint32 val, bool apply)
10105 ApplyModUInt32Value(UNIT_FIELD_POWER1+power, val, apply);
10107 // group update
10108 if(GetTypeId() == TYPEID_PLAYER)
10110 if(((Player*)this)->GetGroup())
10111 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_CUR_POWER);
10113 else if(((Creature*)this)->isPet())
10115 Pet *pet = ((Pet*)this);
10116 if(pet->isControlled())
10118 Unit *owner = GetOwner();
10119 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10120 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_CUR_POWER);
10125 void Unit::ApplyMaxPowerMod(Powers power, uint32 val, bool apply)
10127 ApplyModUInt32Value(UNIT_FIELD_MAXPOWER1+power, val, apply);
10129 // group update
10130 if(GetTypeId() == TYPEID_PLAYER)
10132 if(((Player*)this)->GetGroup())
10133 ((Player*)this)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_MAX_POWER);
10135 else if(((Creature*)this)->isPet())
10137 Pet *pet = ((Pet*)this);
10138 if(pet->isControlled())
10140 Unit *owner = GetOwner();
10141 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10142 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MAX_POWER);
10147 void Unit::ApplyAuraProcTriggerDamage( Aura* aura, bool apply )
10149 AuraList& tAuraProcTriggerDamage = m_modAuras[SPELL_AURA_PROC_TRIGGER_DAMAGE];
10150 if(apply)
10151 tAuraProcTriggerDamage.push_back(aura);
10152 else
10153 tAuraProcTriggerDamage.remove(aura);
10156 uint32 Unit::GetCreatePowers( Powers power ) const
10158 // POWER_FOCUS and POWER_HAPPINESS only have hunter pet
10159 switch(power)
10161 case POWER_MANA: return GetCreateMana();
10162 case POWER_RAGE: return 1000;
10163 case POWER_FOCUS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 100);
10164 case POWER_ENERGY: return 100;
10165 case POWER_HAPPINESS: return (GetTypeId()==TYPEID_PLAYER || !((Creature const*)this)->isPet() || ((Pet const*)this)->getPetType()!=HUNTER_PET ? 0 : 1050000);
10166 case POWER_RUNIC_POWER: return 1000;
10169 return 0;
10172 void Unit::AddToWorld()
10174 Object::AddToWorld();
10177 void Unit::RemoveFromWorld()
10179 // cleanup
10180 if(IsInWorld())
10182 RemoveNotOwnSingleTargetAuras();
10185 Object::RemoveFromWorld();
10188 void Unit::CleanupsBeforeDelete()
10190 if(m_uint32Values) // only for fully created object
10192 InterruptNonMeleeSpells(true);
10193 m_Events.KillAllEvents(false); // non-delatable (currently casted spells) will not deleted now but it will deleted at call in Map::RemoveAllObjectsInRemoveList
10194 CombatStop();
10195 ClearComboPointHolders();
10196 DeleteThreatList();
10197 getHostilRefManager().setOnlineOfflineState(false);
10198 RemoveAllAuras();
10199 RemoveAllGameObjects();
10200 RemoveAllDynObjects();
10201 GetMotionMaster()->Clear(false); // remove different non-standard movement generators.
10203 RemoveFromWorld();
10206 CharmInfo* Unit::InitCharmInfo(Unit *charm)
10208 if(!m_charmInfo)
10209 m_charmInfo = new CharmInfo(charm);
10210 return m_charmInfo;
10213 CharmInfo::CharmInfo(Unit* unit)
10214 : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_reactState(REACT_PASSIVE), m_petnumber(0)
10216 for(int i =0; i<4; ++i)
10218 m_charmspells[i].spellId = 0;
10219 m_charmspells[i].active = ACT_DISABLED;
10223 void CharmInfo::InitPetActionBar()
10225 // the first 3 SpellOrActions are attack, follow and stay
10226 for(uint32 i = 0; i < 3; i++)
10228 PetActionBar[i].Type = ACT_COMMAND;
10229 PetActionBar[i].SpellOrAction = COMMAND_ATTACK - i;
10231 PetActionBar[i + 7].Type = ACT_REACTION;
10232 PetActionBar[i + 7].SpellOrAction = COMMAND_ATTACK - i;
10234 for(uint32 i=0; i < 4; i++)
10236 PetActionBar[i + 3].Type = ACT_DISABLED;
10237 PetActionBar[i + 3].SpellOrAction = 0;
10241 void CharmInfo::InitEmptyActionBar()
10243 for(uint32 x = 1; x < 10; ++x)
10245 PetActionBar[x].Type = ACT_PASSIVE;
10246 PetActionBar[x].SpellOrAction = 0;
10248 PetActionBar[0].Type = ACT_COMMAND;
10249 PetActionBar[0].SpellOrAction = COMMAND_ATTACK;
10252 void CharmInfo::InitPossessCreateSpells()
10254 InitEmptyActionBar(); //charm action bar
10256 if(m_unit->GetTypeId() == TYPEID_PLAYER) //possessed players don't have spells, keep the action bar empty
10257 return;
10259 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10261 if (IsPassiveSpell(((Creature*)m_unit)->m_spells[x]))
10262 m_unit->CastSpell(m_unit, ((Creature*)m_unit)->m_spells[x], true);
10263 else
10264 AddSpellToAB(0, ((Creature*)m_unit)->m_spells[x], ACT_PASSIVE);
10268 void CharmInfo::InitCharmCreateSpells()
10270 if(m_unit->GetTypeId() == TYPEID_PLAYER) //charmed players don't have spells
10272 InitEmptyActionBar();
10273 return;
10276 InitPetActionBar();
10278 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10280 uint32 spellId = ((Creature*)m_unit)->m_spells[x];
10281 m_charmspells[x].spellId = spellId;
10283 if(!spellId)
10284 continue;
10286 if (IsPassiveSpell(spellId))
10288 m_unit->CastSpell(m_unit, spellId, true);
10289 m_charmspells[x].active = ACT_PASSIVE;
10291 else
10293 ActiveStates newstate;
10294 bool onlyselfcast = true;
10295 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
10297 if(!spellInfo) onlyselfcast = false;
10298 for(uint32 i = 0;i<3 && onlyselfcast;++i) //non existent spell will not make any problems as onlyselfcast would be false -> break right away
10300 if(spellInfo->EffectImplicitTargetA[i] != TARGET_SELF && spellInfo->EffectImplicitTargetA[i] != 0)
10301 onlyselfcast = false;
10304 if(onlyselfcast || !IsPositiveSpell(spellId)) //only self cast and spells versus enemies are autocastable
10305 newstate = ACT_DISABLED;
10306 else
10307 newstate = ACT_PASSIVE;
10309 AddSpellToAB(0, spellId, newstate);
10314 bool CharmInfo::AddSpellToAB(uint32 oldid, uint32 newid, ActiveStates newstate)
10316 for(uint8 i = 0; i < 10; i++)
10318 if((PetActionBar[i].Type == ACT_DISABLED || PetActionBar[i].Type == ACT_ENABLED || PetActionBar[i].Type == ACT_PASSIVE) && PetActionBar[i].SpellOrAction == oldid)
10320 PetActionBar[i].SpellOrAction = newid;
10321 if(!oldid)
10323 if(newstate == ACT_DECIDE)
10324 PetActionBar[i].Type = ACT_DISABLED;
10325 else
10326 PetActionBar[i].Type = newstate;
10329 return true;
10332 return false;
10335 void CharmInfo::ToggleCreatureAutocast(uint32 spellid, bool apply)
10337 if(IsPassiveSpell(spellid))
10338 return;
10340 for(uint32 x = 0; x < CREATURE_MAX_SPELLS; ++x)
10342 if(spellid == m_charmspells[x].spellId)
10344 m_charmspells[x].active = apply ? ACT_ENABLED : ACT_DISABLED;
10349 void CharmInfo::SetPetNumber(uint32 petnumber, bool statwindow)
10351 m_petnumber = petnumber;
10352 if(statwindow)
10353 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, m_petnumber);
10354 else
10355 m_unit->SetUInt32Value(UNIT_FIELD_PETNUMBER, 0);
10358 bool Unit::isFrozen() const
10360 return HasAuraState(AURA_STATE_FROZEN);
10363 struct ProcTriggeredData
10365 ProcTriggeredData(SpellProcEventEntry const * _spellProcEvent, Aura* _triggeredByAura)
10366 : spellProcEvent(_spellProcEvent), triggeredByAura(_triggeredByAura),
10367 triggeredByAura_SpellPair(Unit::spellEffectPair(triggeredByAura->GetId(),triggeredByAura->GetEffIndex()))
10369 SpellProcEventEntry const *spellProcEvent;
10370 Aura* triggeredByAura;
10371 Unit::spellEffectPair triggeredByAura_SpellPair;
10374 typedef std::list< ProcTriggeredData > ProcTriggeredList;
10375 typedef std::list< uint32> RemoveSpellList;
10377 // List of auras that CAN be trigger but may not exist in spell_proc_event
10378 // in most case need for drop charges
10379 // in some types of aura need do additional check
10380 // for example SPELL_AURA_MECHANIC_IMMUNITY - need check for mechanic
10381 bool InitTriggerAuraData()
10383 for (int i=0;i<TOTAL_AURAS;i++)
10385 isTriggerAura[i]=false;
10386 isNonTriggerAura[i] = false;
10388 isTriggerAura[SPELL_AURA_DUMMY] = true;
10389 isTriggerAura[SPELL_AURA_MOD_CONFUSE] = true;
10390 isTriggerAura[SPELL_AURA_MOD_THREAT] = true;
10391 isTriggerAura[SPELL_AURA_MOD_STUN] = true; // Aura not have charges but need remove him on trigger
10392 isTriggerAura[SPELL_AURA_MOD_DAMAGE_DONE] = true;
10393 isTriggerAura[SPELL_AURA_MOD_DAMAGE_TAKEN] = true;
10394 isTriggerAura[SPELL_AURA_MOD_RESISTANCE] = true;
10395 isTriggerAura[SPELL_AURA_MOD_ROOT] = true;
10396 isTriggerAura[SPELL_AURA_REFLECT_SPELLS] = true;
10397 isTriggerAura[SPELL_AURA_DAMAGE_IMMUNITY] = true;
10398 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL] = true;
10399 isTriggerAura[SPELL_AURA_PROC_TRIGGER_DAMAGE] = true;
10400 isTriggerAura[SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK] = true;
10401 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT] = true;
10402 isTriggerAura[SPELL_AURA_MOD_POWER_COST_SCHOOL] = true;
10403 isTriggerAura[SPELL_AURA_REFLECT_SPELLS_SCHOOL] = true;
10404 isTriggerAura[SPELL_AURA_MECHANIC_IMMUNITY] = true;
10405 isTriggerAura[SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN] = true;
10406 isTriggerAura[SPELL_AURA_SPELL_MAGNET] = true;
10407 isTriggerAura[SPELL_AURA_MOD_ATTACK_POWER] = true;
10408 isTriggerAura[SPELL_AURA_ADD_CASTER_HIT_TRIGGER] = true;
10409 isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true;
10410 isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true;
10411 isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true;
10412 isTriggerAura[SPELL_AURA_MOD_HASTE] = true;
10413 isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true;
10414 isTriggerAura[SPELL_AURA_PRAYER_OF_MENDING] = true;
10415 isTriggerAura[SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE] = true;
10416 isTriggerAura[SPELL_AURA_MOD_DAMAGE_FROM_CASTER] = true;
10418 isNonTriggerAura[SPELL_AURA_MOD_POWER_REGEN]=true;
10419 isNonTriggerAura[SPELL_AURA_REDUCE_PUSHBACK]=true;
10421 return true;
10424 uint32 createProcExtendMask(SpellNonMeleeDamage *damageInfo, SpellMissInfo missCondition)
10426 uint32 procEx = PROC_EX_NONE;
10427 // Check victim state
10428 if (missCondition!=SPELL_MISS_NONE)
10429 switch (missCondition)
10431 case SPELL_MISS_MISS: procEx|=PROC_EX_MISS; break;
10432 case SPELL_MISS_RESIST: procEx|=PROC_EX_RESIST; break;
10433 case SPELL_MISS_DODGE: procEx|=PROC_EX_DODGE; break;
10434 case SPELL_MISS_PARRY: procEx|=PROC_EX_PARRY; break;
10435 case SPELL_MISS_BLOCK: procEx|=PROC_EX_BLOCK; break;
10436 case SPELL_MISS_EVADE: procEx|=PROC_EX_EVADE; break;
10437 case SPELL_MISS_IMMUNE: procEx|=PROC_EX_IMMUNE; break;
10438 case SPELL_MISS_IMMUNE2: procEx|=PROC_EX_IMMUNE; break;
10439 case SPELL_MISS_DEFLECT: procEx|=PROC_EX_DEFLECT;break;
10440 case SPELL_MISS_ABSORB: procEx|=PROC_EX_ABSORB; break;
10441 case SPELL_MISS_REFLECT: procEx|=PROC_EX_REFLECT;break;
10442 default:
10443 break;
10445 else
10447 // On block
10448 if (damageInfo->blocked)
10449 procEx|=PROC_EX_BLOCK;
10450 // On absorb
10451 if (damageInfo->absorb)
10452 procEx|=PROC_EX_ABSORB;
10453 // On crit
10454 if (damageInfo->HitInfo & SPELL_HIT_TYPE_CRIT)
10455 procEx|=PROC_EX_CRITICAL_HIT;
10456 else
10457 procEx|=PROC_EX_NORMAL_HIT;
10459 return procEx;
10462 void Unit::ProcDamageAndSpellFor( bool isVictim, Unit * pTarget, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, SpellEntry const * procSpell, uint32 damage )
10464 // For melee/ranged based attack need update skills and set some Aura states
10465 if (procFlag & MELEE_BASED_TRIGGER_MASK)
10467 // Update skills here for players
10468 if (GetTypeId() == TYPEID_PLAYER)
10470 // On melee based hit/miss/resist need update skill (for victim and attacker)
10471 if (procExtra&(PROC_EX_NORMAL_HIT|PROC_EX_MISS|PROC_EX_RESIST))
10473 if (pTarget->GetTypeId() != TYPEID_PLAYER && pTarget->GetCreatureType() != CREATURE_TYPE_CRITTER)
10474 ((Player*)this)->UpdateCombatSkills(pTarget, attType, isVictim);
10476 // Update defence if player is victim and parry/dodge/block
10477 if (isVictim && procExtra&(PROC_EX_DODGE|PROC_EX_PARRY|PROC_EX_BLOCK))
10478 ((Player*)this)->UpdateDefense();
10480 // If exist crit/parry/dodge/block need update aura state (for victim and attacker)
10481 if (procExtra & (PROC_EX_CRITICAL_HIT|PROC_EX_PARRY|PROC_EX_DODGE|PROC_EX_BLOCK))
10483 // for victim
10484 if (isVictim)
10486 // if victim and dodge attack
10487 if (procExtra&PROC_EX_DODGE)
10489 //Update AURA_STATE on dodge
10490 if (getClass() != CLASS_ROGUE) // skip Rogue Riposte
10492 ModifyAuraState(AURA_STATE_DEFENSE, true);
10493 StartReactiveTimer( REACTIVE_DEFENSE );
10496 // if victim and parry attack
10497 if (procExtra & PROC_EX_PARRY)
10499 // For Hunters only Counterattack (skip Mongoose bite)
10500 if (getClass() == CLASS_HUNTER)
10502 ModifyAuraState(AURA_STATE_HUNTER_PARRY, true);
10503 StartReactiveTimer( REACTIVE_HUNTER_PARRY );
10505 else
10507 ModifyAuraState(AURA_STATE_DEFENSE, true);
10508 StartReactiveTimer( REACTIVE_DEFENSE );
10511 // if and victim block attack
10512 if (procExtra & PROC_EX_BLOCK)
10514 ModifyAuraState(AURA_STATE_DEFENSE,true);
10515 StartReactiveTimer( REACTIVE_DEFENSE );
10518 else //For attacker
10520 // Overpower on victim dodge
10521 if (procExtra&PROC_EX_DODGE && GetTypeId() == TYPEID_PLAYER && getClass() == CLASS_WARRIOR)
10523 ((Player*)this)->AddComboPoints(pTarget, 1);
10524 StartReactiveTimer( REACTIVE_OVERPOWER );
10530 RemoveSpellList removedSpells;
10531 ProcTriggeredList procTriggered;
10532 // Fill procTriggered list
10533 for(AuraMap::const_iterator itr = GetAuras().begin(); itr!= GetAuras().end(); ++itr)
10535 SpellProcEventEntry const* spellProcEvent = NULL;
10536 if(!IsTriggeredAtSpellProcEvent(pTarget, itr->second, procSpell, procFlag, procExtra, attType, isVictim, (damage > 0), spellProcEvent))
10537 continue;
10539 procTriggered.push_back( ProcTriggeredData(spellProcEvent, itr->second) );
10542 // Nothing found
10543 if (procTriggered.empty())
10544 return;
10546 // Handle effects proceed this time
10547 for(ProcTriggeredList::iterator i = procTriggered.begin(); i != procTriggered.end(); ++i)
10549 // Some auras can be deleted in function called in this loop (except first, ofc)
10550 // Until storing auars in std::multimap to hard check deleting by another way
10551 if(i != procTriggered.begin())
10553 bool found = false;
10554 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10555 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10556 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10558 if(itr->second==i->triggeredByAura)
10560 found = true;
10561 break;
10564 if(!found)
10566 // sLog.outDebug("Spell aura %u (id:%u effect:%u) has been deleted before call spell proc event handler", i->triggeredByAura->GetModifier()->m_auraname, i->triggeredByAura_SpellPair.first, i->triggeredByAura_SpellPair.second);
10567 // sLog.outDebug("It can be deleted one from early proccesed auras:");
10568 // for(ProcTriggeredList::iterator i2 = procTriggered.begin(); i != i2; ++i2)
10569 // sLog.outDebug(" Spell aura %u (id:%u effect:%u)", i->triggeredByAura->GetModifier()->m_auraname,i2->triggeredByAura_SpellPair.first,i2->triggeredByAura_SpellPair.second);
10570 // sLog.outDebug(" <end of list>");
10571 continue;
10575 SpellProcEventEntry const *spellProcEvent = i->spellProcEvent;
10576 Aura *triggeredByAura = i->triggeredByAura;
10577 Modifier *auraModifier = triggeredByAura->GetModifier();
10578 SpellEntry const *spellInfo = triggeredByAura->GetSpellProto();
10579 uint32 effIndex = triggeredByAura->GetEffIndex();
10580 bool useCharges = triggeredByAura->GetAuraCharges() > 0;
10581 // For players set spell cooldown if need
10582 uint32 cooldown = 0;
10583 if (GetTypeId() == TYPEID_PLAYER && spellProcEvent && spellProcEvent->cooldown)
10584 cooldown = spellProcEvent->cooldown;
10586 switch(auraModifier->m_auraname)
10588 case SPELL_AURA_PROC_TRIGGER_SPELL:
10590 sLog.outDebug("ProcDamageAndSpell: casting spell %u (triggered by %s aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId());
10591 // Don`t drop charge or add cooldown for not started trigger
10592 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10593 continue;
10594 break;
10596 case SPELL_AURA_PROC_TRIGGER_DAMAGE:
10598 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());
10599 SpellNonMeleeDamage damageInfo(this, pTarget, spellInfo->Id, spellInfo->SchoolMask);
10600 CalculateSpellDamage(&damageInfo, auraModifier->m_amount, spellInfo);
10601 SendSpellNonMeleeDamageLog(&damageInfo);
10602 DealSpellDamage(&damageInfo, true);
10603 break;
10605 case SPELL_AURA_MANA_SHIELD:
10606 case SPELL_AURA_DUMMY:
10608 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());
10609 if (!HandleDummyAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10610 continue;
10611 break;
10613 case SPELL_AURA_MOD_HASTE:
10615 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());
10616 if (!HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10617 continue;
10618 break;
10620 case SPELL_AURA_OVERRIDE_CLASS_SCRIPTS:
10622 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());
10623 if (!HandleOverrideClassScriptAuraProc(pTarget, damage, triggeredByAura, procSpell, cooldown))
10624 continue;
10625 break;
10627 case SPELL_AURA_PRAYER_OF_MENDING:
10629 sLog.outDebug("ProcDamageAndSpell: casting mending (triggered by %s dummy aura of spell %u)",
10630 (isVictim?"a victim's":"an attacker's"),triggeredByAura->GetId());
10632 HandleMeandingAuraProc(triggeredByAura);
10633 break;
10635 case SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE:
10637 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());
10639 if (!HandleProcTriggerSpell(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown))
10640 continue;
10641 break;
10643 case SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK:
10644 // Skip melee hits or instant cast spells
10645 if (procSpell == NULL || GetSpellCastTime(procSpell) == 0)
10646 continue;
10647 break;
10648 case SPELL_AURA_REFLECT_SPELLS_SCHOOL:
10649 // Skip Melee hits and spells ws wrong school
10650 if (procSpell == NULL || (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0)
10651 continue;
10652 break;
10653 case SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT:
10654 case SPELL_AURA_MOD_POWER_COST_SCHOOL:
10655 // Skip melee hits and spells ws wrong school or zero cost
10656 if (procSpell == NULL ||
10657 (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check
10658 (auraModifier->m_miscvalue & procSpell->SchoolMask) == 0) // School check
10659 continue;
10660 break;
10661 case SPELL_AURA_MECHANIC_IMMUNITY:
10662 // Compare mechanic
10663 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10664 continue;
10665 break;
10666 case SPELL_AURA_MOD_MECHANIC_RESISTANCE:
10667 // Compare mechanic
10668 if (procSpell==NULL || procSpell->Mechanic != auraModifier->m_miscvalue)
10669 continue;
10670 break;
10671 case SPELL_AURA_MOD_DAMAGE_FROM_CASTER:
10672 // Compare casters
10673 if (triggeredByAura->GetCasterGUID() != pTarget->GetGUID())
10674 continue;
10675 break;
10676 default:
10677 // nothing do, just charges counter
10678 break;
10680 // Remove charge (aura can be removed by triggers)
10681 if(useCharges)
10683 // need found aura on drop (can be dropped by triggers)
10684 AuraMap::const_iterator lower = GetAuras().lower_bound(i->triggeredByAura_SpellPair);
10685 AuraMap::const_iterator upper = GetAuras().upper_bound(i->triggeredByAura_SpellPair);
10686 for(AuraMap::const_iterator itr = lower; itr!= upper; ++itr)
10688 // If last charge dropped add spell to remove list
10689 if(itr->second == i->triggeredByAura && triggeredByAura->DropAuraCharge())
10691 removedSpells.push_back(triggeredByAura->GetId());
10692 break;
10697 if (!removedSpells.empty())
10699 // Sort spells and remove dublicates
10700 removedSpells.sort();
10701 removedSpells.unique();
10702 // Remove auras from removedAuras
10703 for(RemoveSpellList::const_iterator i = removedSpells.begin(); i != removedSpells.end();i++)
10704 RemoveAurasDueToSpell(*i);
10708 SpellSchoolMask Unit::GetMeleeDamageSchoolMask() const
10710 return SPELL_SCHOOL_MASK_NORMAL;
10713 Player* Unit::GetSpellModOwner()
10715 if(GetTypeId()==TYPEID_PLAYER)
10716 return (Player*)this;
10717 if(((Creature*)this)->isPet() || ((Creature*)this)->isTotem())
10719 Unit* owner = GetOwner();
10720 if(owner && owner->GetTypeId()==TYPEID_PLAYER)
10721 return (Player*)owner;
10723 return NULL;
10726 ///----------Pet responses methods-----------------
10727 void Unit::SendPetCastFail(uint32 spellid, SpellCastResult msg)
10729 if(msg == SPELL_CAST_OK)
10730 return;
10732 Unit *owner = GetCharmerOrOwner();
10733 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10734 return;
10736 WorldPacket data(SMSG_PET_CAST_FAILED, (4+1));
10737 data << uint8(0); // cast count?
10738 data << uint32(spellid);
10739 data << uint8(msg);
10740 // uint32 for some reason
10741 // uint32 for some reason
10742 ((Player*)owner)->GetSession()->SendPacket(&data);
10745 void Unit::SendPetActionFeedback (uint8 msg)
10747 Unit* owner = GetOwner();
10748 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10749 return;
10751 WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1);
10752 data << uint8(msg);
10753 ((Player*)owner)->GetSession()->SendPacket(&data);
10756 void Unit::SendPetTalk (uint32 pettalk)
10758 Unit* owner = GetOwner();
10759 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10760 return;
10762 WorldPacket data(SMSG_PET_ACTION_SOUND, 8+4);
10763 data << uint64(GetGUID());
10764 data << uint32(pettalk);
10765 ((Player*)owner)->GetSession()->SendPacket(&data);
10768 void Unit::SendPetSpellCooldown (uint32 spellid, time_t cooltime)
10770 Unit* owner = GetOwner();
10771 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10772 return;
10774 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4);
10775 data << uint64(GetGUID());
10776 data << uint8(0x0); // flags (0x1, 0x2)
10777 data << uint32(spellid);
10778 data << uint32(cooltime);
10780 ((Player*)owner)->GetSession()->SendPacket(&data);
10783 void Unit::SendPetClearCooldown (uint32 spellid)
10785 Unit* owner = GetOwner();
10786 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10787 return;
10789 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
10790 data << uint32(spellid);
10791 data << uint64(GetGUID());
10792 ((Player*)owner)->GetSession()->SendPacket(&data);
10795 void Unit::SendPetAIReaction(uint64 guid)
10797 Unit* owner = GetOwner();
10798 if(!owner || owner->GetTypeId() != TYPEID_PLAYER)
10799 return;
10801 WorldPacket data(SMSG_AI_REACTION, 12);
10802 data << uint64(guid) << uint32(00000002);
10803 ((Player*)owner)->GetSession()->SendPacket(&data);
10806 ///----------End of Pet responses methods----------
10808 void Unit::StopMoving()
10810 clearUnitState(UNIT_STAT_MOVING);
10812 // send explicit stop packet
10813 // rely on vmaps here because for example stormwind is in air
10814 //float z = MapManager::Instance().GetBaseMap(GetMapId())->GetHeight(GetPositionX(), GetPositionY(), GetPositionZ(), true);
10815 //if (fabs(GetPositionZ() - z) < 2.0f)
10816 // Relocate(GetPositionX(), GetPositionY(), z);
10817 Relocate(GetPositionX(), GetPositionY(),GetPositionZ());
10819 SendMonsterMove(GetPositionX(), GetPositionY(), GetPositionZ(), 0, true, 0);
10821 // update position and orientation;
10822 WorldPacket data;
10823 BuildHeartBeatMsg(&data);
10824 SendMessageToSet(&data,false);
10827 void Unit::SetFeared(bool apply, uint64 casterGUID, uint32 spellID)
10829 if( apply )
10831 if(HasAuraType(SPELL_AURA_PREVENTS_FLEEING))
10832 return;
10834 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10836 GetMotionMaster()->MovementExpired(false);
10837 CastStop(GetGUID()==casterGUID ? spellID : 0);
10839 Unit* caster = ObjectAccessor::GetUnit(*this,casterGUID);
10841 GetMotionMaster()->MoveFleeing(caster); // caster==NULL processed in MoveFleeing
10843 else
10845 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING);
10847 GetMotionMaster()->MovementExpired(false);
10849 if( GetTypeId() != TYPEID_PLAYER && isAlive() )
10851 // restore appropriate movement generator
10852 if(getVictim())
10853 GetMotionMaster()->MoveChase(getVictim());
10854 else
10855 GetMotionMaster()->Initialize();
10857 // attack caster if can
10858 Unit* caster = ObjectAccessor::GetObjectInWorld(casterGUID, (Unit*)NULL);
10859 if(caster && ((Creature*)this)->AI())
10860 ((Creature*)this)->AI()->AttackedBy(caster);
10864 if (GetTypeId() == TYPEID_PLAYER)
10865 ((Player*)this)->SetClientControl(this, !apply);
10868 void Unit::SetConfused(bool apply, uint64 casterGUID, uint32 spellID)
10870 if( apply )
10872 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10874 CastStop(GetGUID()==casterGUID ? spellID : 0);
10876 GetMotionMaster()->MoveConfused();
10878 else
10880 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_CONFUSED);
10882 GetMotionMaster()->MovementExpired(false);
10884 if (GetTypeId() == TYPEID_UNIT)
10886 // if in combat restore movement generator
10887 if(getVictim())
10888 GetMotionMaster()->MoveChase(getVictim());
10892 if(GetTypeId() == TYPEID_PLAYER)
10893 ((Player*)this)->SetClientControl(this, !apply);
10896 bool Unit::IsSitState() const
10898 uint8 s = getStandState();
10899 return
10900 s == UNIT_STAND_STATE_SIT_CHAIR || s == UNIT_STAND_STATE_SIT_LOW_CHAIR ||
10901 s == UNIT_STAND_STATE_SIT_MEDIUM_CHAIR || s == UNIT_STAND_STATE_SIT_HIGH_CHAIR ||
10902 s == UNIT_STAND_STATE_SIT;
10905 bool Unit::IsStandState() const
10907 uint8 s = getStandState();
10908 return !IsSitState() && s != UNIT_STAND_STATE_SLEEP && s != UNIT_STAND_STATE_KNEEL;
10911 void Unit::SetStandState(uint8 state)
10913 SetByteValue(UNIT_FIELD_BYTES_1, 0, state);
10915 if (IsStandState())
10916 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_NOT_SEATED);
10918 if(GetTypeId()==TYPEID_PLAYER)
10920 WorldPacket data(SMSG_STANDSTATE_UPDATE, 1);
10921 data << (uint8)state;
10922 ((Player*)this)->GetSession()->SendPacket(&data);
10926 bool Unit::IsPolymorphed() const
10928 return GetSpellSpecific(getTransForm())==SPELL_MAGE_POLYMORPH;
10931 void Unit::SetDisplayId(uint32 modelId)
10933 SetUInt32Value(UNIT_FIELD_DISPLAYID, modelId);
10935 if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
10937 Pet *pet = ((Pet*)this);
10938 if(!pet->isControlled())
10939 return;
10940 Unit *owner = GetOwner();
10941 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
10942 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_MODEL_ID);
10946 void Unit::ClearComboPointHolders()
10948 while(!m_ComboPointHolders.empty())
10950 uint32 lowguid = *m_ComboPointHolders.begin();
10952 Player* plr = objmgr.GetPlayer(MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER));
10953 if(plr && plr->GetComboTarget()==GetGUID()) // recheck for safe
10954 plr->ClearComboPoints(); // remove also guid from m_ComboPointHolders;
10955 else
10956 m_ComboPointHolders.erase(lowguid); // or remove manually
10960 void Unit::ClearAllReactives()
10962 for(int i=0; i < MAX_REACTIVE; ++i)
10963 m_reactiveTimer[i] = 0;
10965 if (HasAuraState( AURA_STATE_DEFENSE))
10966 ModifyAuraState(AURA_STATE_DEFENSE, false);
10967 if (getClass() == CLASS_HUNTER && HasAuraState( AURA_STATE_HUNTER_PARRY))
10968 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10969 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10970 ((Player*)this)->ClearComboPoints();
10973 void Unit::UpdateReactives( uint32 p_time )
10975 for(int i = 0; i < MAX_REACTIVE; ++i)
10977 ReactiveType reactive = ReactiveType(i);
10979 if(!m_reactiveTimer[reactive])
10980 continue;
10982 if ( m_reactiveTimer[reactive] <= p_time)
10984 m_reactiveTimer[reactive] = 0;
10986 switch ( reactive )
10988 case REACTIVE_DEFENSE:
10989 if (HasAuraState(AURA_STATE_DEFENSE))
10990 ModifyAuraState(AURA_STATE_DEFENSE, false);
10991 break;
10992 case REACTIVE_HUNTER_PARRY:
10993 if ( getClass() == CLASS_HUNTER && HasAuraState(AURA_STATE_HUNTER_PARRY))
10994 ModifyAuraState(AURA_STATE_HUNTER_PARRY, false);
10995 break;
10996 case REACTIVE_OVERPOWER:
10997 if(getClass() == CLASS_WARRIOR && GetTypeId() == TYPEID_PLAYER)
10998 ((Player*)this)->ClearComboPoints();
10999 break;
11000 default:
11001 break;
11004 else
11006 m_reactiveTimer[reactive] -= p_time;
11011 Unit* Unit::SelectNearbyTarget() const
11013 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
11014 Cell cell(p);
11015 cell.data.Part.reserved = ALL_DISTRICT;
11016 cell.SetNoCreate();
11018 std::list<Unit *> targets;
11021 MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, this, ATTACK_DISTANCE);
11022 MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> searcher(this, targets, u_check);
11024 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_unit_searcher(searcher);
11025 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_unit_searcher(searcher);
11027 CellLock<GridReadGuard> cell_lock(cell, p);
11028 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
11029 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
11032 // remove current target
11033 if(getVictim())
11034 targets.remove(getVictim());
11036 // remove not LoS targets
11037 for(std::list<Unit *>::iterator tIter = targets.begin(); tIter != targets.end();)
11039 if(!IsWithinLOSInMap(*tIter))
11041 std::list<Unit *>::iterator tIter2 = tIter;
11042 ++tIter;
11043 targets.erase(tIter2);
11045 else
11046 ++tIter;
11049 // no appropriate targets
11050 if(targets.empty())
11051 return NULL;
11053 // select random
11054 uint32 rIdx = urand(0,targets.size()-1);
11055 std::list<Unit *>::const_iterator tcIter = targets.begin();
11056 for(uint32 i = 0; i < rIdx; ++i)
11057 ++tcIter;
11059 return *tcIter;
11062 bool Unit::hasNegativeAuraWithInterruptFlag(uint32 flag)
11064 for (AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end(); ++iter)
11066 if (!iter->second->IsPositive() && iter->second->GetSpellProto()->AuraInterruptFlags & flag)
11067 return true;
11069 return false;
11072 void Unit::ApplyAttackTimePercentMod( WeaponAttackType att,float val, bool apply )
11074 if(val > 0)
11076 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], val, !apply);
11077 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,val,!apply);
11079 else
11081 ApplyPercentModFloatVar(m_modAttackSpeedPct[att], -val, apply);
11082 ApplyPercentModFloatValue(UNIT_FIELD_BASEATTACKTIME+att,-val,apply);
11086 void Unit::ApplyCastTimePercentMod(float val, bool apply )
11088 if(val > 0)
11089 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,val,!apply);
11090 else
11091 ApplyPercentModFloatValue(UNIT_MOD_CAST_SPEED,-val,apply);
11094 uint32 Unit::GetCastingTimeForBonus( SpellEntry const *spellProto, DamageEffectType damagetype, uint32 CastingTime )
11096 // Not apply this to creature casted spells with casttime==0
11097 if(CastingTime==0 && GetTypeId()==TYPEID_UNIT && !((Creature*)this)->isPet())
11098 return 3500;
11100 if (CastingTime > 7000) CastingTime = 7000;
11101 if (CastingTime < 1500) CastingTime = 1500;
11103 if(damagetype == DOT && !IsChanneledSpell(spellProto))
11104 CastingTime = 3500;
11106 int32 overTime = 0;
11107 uint8 effects = 0;
11108 bool DirectDamage = false;
11109 bool AreaEffect = false;
11111 for ( uint32 i=0; i<3;i++)
11113 switch ( spellProto->Effect[i] )
11115 case SPELL_EFFECT_SCHOOL_DAMAGE:
11116 case SPELL_EFFECT_POWER_DRAIN:
11117 case SPELL_EFFECT_HEALTH_LEECH:
11118 case SPELL_EFFECT_ENVIRONMENTAL_DAMAGE:
11119 case SPELL_EFFECT_POWER_BURN:
11120 case SPELL_EFFECT_HEAL:
11121 DirectDamage = true;
11122 break;
11123 case SPELL_EFFECT_APPLY_AURA:
11124 switch ( spellProto->EffectApplyAuraName[i] )
11126 case SPELL_AURA_PERIODIC_DAMAGE:
11127 case SPELL_AURA_PERIODIC_HEAL:
11128 case SPELL_AURA_PERIODIC_LEECH:
11129 if ( GetSpellDuration(spellProto) )
11130 overTime = GetSpellDuration(spellProto);
11131 break;
11132 default:
11133 // -5% per additional effect
11134 ++effects;
11135 break;
11137 default:
11138 break;
11141 if(IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetA[i])) || IsAreaEffectTarget(Targets(spellProto->EffectImplicitTargetB[i])))
11142 AreaEffect = true;
11145 // Combined Spells with Both Over Time and Direct Damage
11146 if ( overTime > 0 && CastingTime > 0 && DirectDamage )
11148 // mainly for DoTs which are 3500 here otherwise
11149 uint32 OriginalCastTime = GetSpellCastTime(spellProto);
11150 if (OriginalCastTime > 7000) OriginalCastTime = 7000;
11151 if (OriginalCastTime < 1500) OriginalCastTime = 1500;
11152 // Portion to Over Time
11153 float PtOT = (overTime / 15000.f) / ((overTime / 15000.f) + (OriginalCastTime / 3500.f));
11155 if ( damagetype == DOT )
11156 CastingTime = uint32(CastingTime * PtOT);
11157 else if ( PtOT < 1.0f )
11158 CastingTime = uint32(CastingTime * (1 - PtOT));
11159 else
11160 CastingTime = 0;
11163 // Area Effect Spells receive only half of bonus
11164 if ( AreaEffect )
11165 CastingTime /= 2;
11167 // -5% of total per any additional effect
11168 for ( uint8 i=0; i<effects; ++i)
11170 if ( CastingTime > 175 )
11172 CastingTime -= 175;
11174 else
11176 CastingTime = 0;
11177 break;
11181 return CastingTime;
11184 void Unit::UpdateAuraForGroup(uint8 slot)
11186 if(GetTypeId() == TYPEID_PLAYER)
11188 Player* player = (Player*)this;
11189 if(player->GetGroup())
11191 player->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_AURAS);
11192 player->SetAuraUpdateMask(slot);
11195 else if(GetTypeId() == TYPEID_UNIT && ((Creature*)this)->isPet())
11197 Pet *pet = ((Pet*)this);
11198 if(pet->isControlled())
11200 Unit *owner = GetOwner();
11201 if(owner && (owner->GetTypeId() == TYPEID_PLAYER) && ((Player*)owner)->GetGroup())
11203 ((Player*)owner)->SetGroupUpdateFlag(GROUP_UPDATE_FLAG_PET_AURAS);
11204 pet->SetAuraUpdateMask(slot);
11210 float Unit::GetAPMultiplier(WeaponAttackType attType, bool normalized)
11212 if (!normalized || GetTypeId() != TYPEID_PLAYER)
11213 return float(GetAttackTime(attType))/1000.0f;
11215 Item *Weapon = ((Player*)this)->GetWeaponForAttack(attType);
11216 if (!Weapon)
11217 return 2.4; // fist attack
11219 switch (Weapon->GetProto()->InventoryType)
11221 case INVTYPE_2HWEAPON:
11222 return 3.3;
11223 case INVTYPE_RANGED:
11224 case INVTYPE_RANGEDRIGHT:
11225 case INVTYPE_THROWN:
11226 return 2.8;
11227 case INVTYPE_WEAPON:
11228 case INVTYPE_WEAPONMAINHAND:
11229 case INVTYPE_WEAPONOFFHAND:
11230 default:
11231 return Weapon->GetProto()->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER ? 1.7 : 2.4;
11235 Aura* Unit::GetDummyAura( uint32 spell_id ) const
11237 Unit::AuraList const& mDummy = GetAurasByType(SPELL_AURA_DUMMY);
11238 for(Unit::AuraList::const_iterator itr = mDummy.begin(); itr != mDummy.end(); ++itr)
11239 if ((*itr)->GetId() == spell_id)
11240 return *itr;
11242 return NULL;
11245 bool Unit::IsUnderLastManaUseEffect() const
11247 return getMSTimeDiff(m_lastManaUse,getMSTime()) < 5000;
11250 void Unit::SetContestedPvP(Player *attackedPlayer)
11252 Player* player = GetCharmerOrOwnerPlayerOrPlayerItself();
11254 if(!player || attackedPlayer && (attackedPlayer == player || player->duel && player->duel->opponent == attackedPlayer))
11255 return;
11257 player->SetContestedPvPTimer(30000);
11258 if(!player->hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11260 player->addUnitState(UNIT_STAT_ATTACK_PLAYER);
11261 player->SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP);
11262 // call MoveInLineOfSight for nearby contested guards
11263 SetVisibility(GetVisibility());
11265 if(!hasUnitState(UNIT_STAT_ATTACK_PLAYER))
11267 addUnitState(UNIT_STAT_ATTACK_PLAYER);
11268 // call MoveInLineOfSight for nearby contested guards
11269 SetVisibility(GetVisibility());
11273 void Unit::AddPetAura(PetAura const* petSpell)
11275 m_petAuras.insert(petSpell);
11276 if(Pet* pet = GetPet())
11277 pet->CastPetAura(petSpell);
11280 void Unit::RemovePetAura(PetAura const* petSpell)
11282 m_petAuras.erase(petSpell);
11283 if(Pet* pet = GetPet())
11284 pet->RemoveAurasDueToSpell(petSpell->GetAura(pet->GetEntry()));
11287 Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget,uint32 spell_id)
11289 Pet* pet = new Pet(HUNTER_PET);
11291 if(!pet->CreateBaseAtCreature(creatureTarget))
11293 delete pet;
11294 return NULL;
11297 pet->SetOwnerGUID(GetGUID());
11298 pet->SetCreatorGUID(GetGUID());
11299 pet->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, getFaction());
11300 pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, spell_id);
11302 if(GetTypeId()==TYPEID_PLAYER)
11303 pet->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
11305 uint32 level = (creatureTarget->getLevel() < (getLevel() - 5)) ? (getLevel() - 5) : creatureTarget->getLevel();
11307 if(!pet->InitStatsForLevel(level))
11309 sLog.outError("Pet::InitStatsForLevel() failed for creature (Entry: %u)!",creatureTarget->GetEntry());
11310 delete pet;
11311 return NULL;
11314 pet->GetCharmInfo()->SetPetNumber(objmgr.GeneratePetNumber(), true);
11315 // this enables pet details window (Shift+P)
11316 pet->AIM_Initialize();
11317 pet->InitPetCreateSpells();
11318 pet->InitTalentForLevel();
11319 pet->SetHealth(pet->GetMaxHealth());
11321 return pet;
11324 bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, Aura* aura, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, bool active, SpellProcEventEntry const*& spellProcEvent )
11326 SpellEntry const* spellProto = aura->GetSpellProto ();
11328 // Get proc Event Entry
11329 spellProcEvent = spellmgr.GetSpellProcEvent(spellProto->Id);
11331 // Aura info stored here
11332 Modifier *mod = aura->GetModifier();
11333 // Skip this auras
11334 if (isNonTriggerAura[mod->m_auraname])
11335 return false;
11336 // If not trigger by default and spellProcEvent==NULL - skip
11337 if (!isTriggerAura[mod->m_auraname] && spellProcEvent==NULL)
11338 return false;
11340 // Get EventProcFlag
11341 uint32 EventProcFlag;
11342 if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags
11343 EventProcFlag = spellProcEvent->procFlags;
11344 else
11345 EventProcFlag = spellProto->procFlags; // else get from spell proto
11346 // Continue if no trigger exist
11347 if (!EventProcFlag)
11348 return false;
11350 // Check spellProcEvent data requirements
11351 if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra, active))
11352 return false;
11354 // In most cases req get honor or XP from kill
11355 if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER)
11357 bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim);
11358 // Shadow Word: Death - can trigger from every kill
11359 if (aura->GetId() == 32409)
11360 allow = true;
11361 if (!allow)
11362 return false;
11364 // Aura added by spell can`t trogger from self (prevent drop charges/do triggers)
11365 // But except periodic triggers (can triggered from self)
11366 if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags&PROC_FLAG_ON_TAKE_PERIODIC))
11367 return false;
11369 // Check if current equipment allows aura to proc
11370 if(!isVictim && GetTypeId() == TYPEID_PLAYER)
11372 if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON)
11374 Item *item = NULL;
11375 if(attType == BASE_ATTACK)
11376 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
11377 else if (attType == OFF_ATTACK)
11378 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11379 else
11380 item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED);
11382 if (!((Player*)this)->IsUseEquipedWeapon(attType==BASE_ATTACK))
11383 return false;
11385 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11386 return false;
11388 else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR)
11390 // Check if player is wearing shield
11391 Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
11392 if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask))
11393 return false;
11396 // Get chance from spell
11397 float chance = (float)spellProto->procChance;
11398 // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance;
11399 if(spellProcEvent && spellProcEvent->customChance)
11400 chance = spellProcEvent->customChance;
11401 // If PPM exist calculate chance from PPM
11402 if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0)
11404 uint32 WeaponSpeed = GetAttackTime(attType);
11405 chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate);
11407 // Apply chance modifer aura
11408 if(Player* modOwner = GetSpellModOwner())
11409 modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
11411 return roll_chance_f(chance);
11414 bool Unit::HandleMeandingAuraProc( Aura* triggeredByAura )
11416 // aura can be deleted at casts
11417 SpellEntry const* spellProto = triggeredByAura->GetSpellProto();
11418 uint32 effIdx = triggeredByAura->GetEffIndex();
11419 int32 heal = triggeredByAura->GetModifier()->m_amount;
11420 uint64 caster_guid = triggeredByAura->GetCasterGUID();
11422 // jumps
11423 int32 jumps = triggeredByAura->GetAuraCharges()-1;
11425 // current aura expire
11426 triggeredByAura->SetAuraCharges(1); // will removed at next charges decrease
11428 // next target selection
11429 if(jumps > 0 && GetTypeId()==TYPEID_PLAYER && IS_PLAYER_GUID(caster_guid))
11431 float radius;
11432 if (spellProto->EffectRadiusIndex[effIdx])
11433 radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx]));
11434 else
11435 radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex));
11437 if(Player* caster = ((Player*)triggeredByAura->GetCaster()))
11439 caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL);
11441 if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius))
11443 // aura will applied from caster, but spell casted from current aura holder
11444 SpellModifier *mod = new SpellModifier;
11445 mod->op = SPELLMOD_CHARGES;
11446 mod->value = jumps-5; // negative
11447 mod->type = SPELLMOD_FLAT;
11448 mod->spellId = spellProto->Id;
11449 mod->mask = spellProto->SpellFamilyFlags;
11450 mod->mask2 = spellProto->SpellFamilyFlags2;
11452 caster->AddSpellMod(mod, true);
11453 CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID());
11454 caster->AddSpellMod(mod, false);
11459 // heal
11460 CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid);
11461 return true;
11464 void Unit::RemoveAurasAtChanneledTarget(SpellEntry const* spellInfo)
11466 uint64 target_guid = GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT);
11468 if(!IS_UNIT_GUID(target_guid))
11469 return;
11471 Unit* target = ObjectAccessor::GetUnit(*this, target_guid);
11472 if(!target)
11473 return;
11475 for (AuraMap::iterator iter = target->GetAuras().begin(); iter != target->GetAuras().end(); )
11477 if (iter->second->GetId() == spellInfo->Id && iter->second->GetCasterGUID()==GetGUID())
11478 target->RemoveAura(iter);
11479 else
11480 ++iter;
11484 void Unit::SetPhaseMask(uint32 newPhaseMask, bool update)
11486 WorldObject::SetPhaseMask(newPhaseMask,update);
11488 if(IsInWorld())
11489 if(Pet* pet = GetPet())
11490 pet->SetPhaseMask(newPhaseMask,true);
11493 void Unit::NearTeleportTo( float x, float y, float z, float orientation, bool casting /*= false*/ )
11495 if(GetTypeId() == TYPEID_PLAYER)
11496 ((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));
11497 else
11499 GetMap()->CreatureRelocation((Creature*)this, x, y, z, orientation);
11501 WorldPacket data;
11502 // Work strange for many spells: triggered active mover set for targeted player to creature
11503 //BuildTeleportAckMsg(&data, x, y, z, orientation);
11504 BuildHeartBeatMsg(&data);
11505 SendMessageToSet(&data, false);